const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/LeadSiteHome-X2ToJUBR.js","assets/useLeadSiteSearchSuggestions-BHcjgBmt.js","assets/CityPagesModule-BkoKa_Rk.js","assets/ListingCarouselModule-CbfrqzpH.js","assets/imageOptimization-Csrlnz8M.js","assets/LeadSiteLuxuryHome-DNqdQpme.js","assets/LeadSiteExchangeListings-But2LKOW.js","assets/LeadSiteLandRanchHome-Cu3w5XwD.js","assets/LeadSiteSearch-RHBL4StH.js","assets/LeadSiteListingCardImage-DQMXd6ip.js","assets/LeadSiteMap-ChetK8i0.js","assets/LeadSiteLuxurySearch-Zi_5OPyE.js","assets/LeadSiteListingDetail-BlqyDqZJ.js","assets/ListingVideoTour-UPpxE1uS.js","assets/useListingVideos-D_k7Xe3S.js","assets/LeadSiteLuxuryListingDetail-CqsfTze_.js","assets/LeadSiteCityPage-S78hcP0U.js","assets/LeadSiteSubdivisionPage-BqZdjsAT.js","assets/LeadSiteFocusPage-DZePjoda.js","assets/PublicLiveEvent-DqRZL-oW.js","assets/useLiveEngagement-CFtpvaRz.js","assets/LiveEventConsole-Bo4v675Z.js","assets/StagingStudio-CJ8s1uUi.js","assets/presets-D-jLJY5F.js","assets/download-BqCckdNk.js","assets/BeforeAfterSlider-vesdZSCC.js","assets/BuyCreditsDialog-i2fQ5ae2.js","assets/StagingLibrary-CHx7-CDl.js","assets/StagingCredits-ClOSzSVB.js","assets/StagingSharePage-BdsbfUVp.js","assets/StagingStudioAdmin-DbI2st0_.js","assets/PostcardManager-Dt3HBWuY.js","assets/usePostcardZones-C0sRZvPI.js","assets/DirectMail-CeFK67JL.js","assets/LeadSiteEditor-BU0lIVdF.js","assets/ImageUrlField-CXB3cwXe.js","assets/HomepageModuleManager-KWsagoYW.js","assets/LeadSiteEditor-BzY4kI8E.css","assets/AdminLeadSiteThemes-D20rw6Jz.js","assets/AdminFreeWebsiteOfferStudio-xL2FnG3l.js","assets/MLSListingDetail-DLZFZe-G.js","assets/EmailCampaignComposer-BIGpm3FG.js","assets/EditorModeSelector-4fg1uu2P.js","assets/SharedCampaignTemplates-DPVbaLWe.js","assets/TemplateEditorDialog-b1pEw6im.js","assets/AgentTemplates-Dv3_rcxO.js","assets/TheLocalMoveHome-BG1kwU8o.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-izA95kLE.js"])))=>i.map(i=>d[i]); var Tcs=Object.defineProperty;var Uct=s=>{throw TypeError(s)};var Mcs=(s,t,n)=>t in s?Tcs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n;var Lr=(s,t,n)=>Mcs(s,typeof t!="symbol"?t+"":t,n),QRe=(s,t,n)=>t.has(s)||Uct("Cannot "+n);var fe=(s,t,n)=>(QRe(s,t,"read from private field"),n?n.call(s):t.get(s)),is=(s,t,n)=>t.has(s)?Uct("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,n),$t=(s,t,n,r)=>(QRe(s,t,"write to private field"),r?r.call(s,n):t.set(s,n),n),Xt=(s,t,n)=>(QRe(s,t,"access private method"),n);var O0=(s,t,n,r)=>({set _(a){$t(s,t,a,n)},get _(){return fe(s,t,r)}});function Pcs(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 op=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function od(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function Lcs(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 rCt={exports:{}},s6e={},aCt={exports:{}},kd={};/** * @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 vne=Symbol.for("react.element"),Ics=Symbol.for("react.portal"),Rcs=Symbol.for("react.fragment"),Dcs=Symbol.for("react.strict_mode"),Ocs=Symbol.for("react.profiler"),Fcs=Symbol.for("react.provider"),zcs=Symbol.for("react.context"),Bcs=Symbol.for("react.forward_ref"),Ucs=Symbol.for("react.suspense"),qcs=Symbol.for("react.memo"),$cs=Symbol.for("react.lazy"),qct=Symbol.iterator;function Vcs(s){return s===null||typeof s!="object"?null:(s=qct&&s[qct]||s["@@iterator"],typeof s=="function"?s:null)}var iCt={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},oCt=Object.assign,lCt={};function QH(s,t,n){this.props=s,this.context=t,this.refs=lCt,this.updater=n||iCt}QH.prototype.isReactComponent={};QH.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")};QH.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")};function cCt(){}cCt.prototype=QH.prototype;function hYe(s,t,n){this.props=s,this.context=t,this.refs=lCt,this.updater=n||iCt}var mYe=hYe.prototype=new cCt;mYe.constructor=hYe;oCt(mYe,QH.prototype);mYe.isPureReactComponent=!0;var $ct=Array.isArray,dCt=Object.prototype.hasOwnProperty,pYe={current:null},uCt={key:!0,ref:!0,__self:!0,__source:!0};function hCt(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)dCt.call(t,r)&&!uCt.hasOwnProperty(r)&&(a[r]=t[r]);var o=arguments.length-2;if(o===1)a.children=n;else if(1>>1,ie=le[ne];if(0>>1;nea(be,se))hea(ge,be)?(le[ne]=ge,le[he]=se,ne=he):(le[ne]=be,le[je]=se,ne=je);else if(hea(ge,se))le[ne]=ge,le[he]=se,ne=he;else break e}}return ue}function a(le,ue){var se=le.sortIndex-ue.sortIndex;return se!==0?se:le.id-ue.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,p=!1,f=!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 N(le){for(var ue=n(d);ue!==null;){if(ue.callback===null)r(d);else if(ue.startTime<=le)r(d),ue.sortIndex=ue.expirationTime,t(c,ue);else break;ue=n(d)}}function S(le){if(x=!1,N(le),!f)if(n(c)!==null)f=!0,Z(A);else{var ue=n(d);ue!==null&&Q(S,ue.startTime-le)}}function A(le,ue){f=!1,x&&(x=!1,v(M),M=-1),p=!0;var se=m;try{for(N(ue),h=n(c);h!==null&&(!(h.expirationTime>ue)||le&&!z());){var ne=h.callback;if(typeof ne=="function"){h.callback=null,m=h.priorityLevel;var ie=ne(h.expirationTime<=ue);ue=s.unstable_now(),typeof ie=="function"?h.callback=ie:h===n(c)&&r(c),N(ue)}else r(c);h=n(c)}if(h!==null)var ce=!0;else{var je=n(d);je!==null&&Q(S,je.startTime-ue),ce=!1}return ce}finally{h=null,m=se,p=!1}}var T=!1,L=null,M=-1,I=5,R=-1;function z(){return!(s.unstable_now()-Rle||125ne?(le.sortIndex=se,t(d,le),n(c)===null&&le===n(d)&&(x?(v(M),M=-1):x=!0,Q(S,se-ne))):(le.sortIndex=ie,t(c,le),f||p||(f=!0,Z(A))),le},s.unstable_shouldYield=z,s.unstable_wrapCallback=function(le){var ue=m;return function(){var se=m;m=ue;try{return le.apply(this,arguments)}finally{m=se}}}})(xCt);gCt.exports=xCt;var mX=gCt.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 tds=j,mj=mX;function Ka(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"),wBe=Object.prototype.hasOwnProperty,sds=/^[: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]*$/,Hct={},Gct={};function nds(s){return wBe.call(Gct,s)?!0:wBe.call(Hct,s)?!1:sds.test(s)?Gct[s]=!0:(Hct[s]=!0,!1)}function rds(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 ads(s,t,n,r){if(t===null||typeof t>"u"||rds(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 kb(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 yv={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(s){yv[s]=new kb(s,0,!1,s,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(s){var t=s[0];yv[t]=new kb(t,1,!1,s[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(s){yv[s]=new kb(s,2,!1,s.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(s){yv[s]=new kb(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){yv[s]=new kb(s,3,!1,s.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(s){yv[s]=new kb(s,3,!0,s,null,!1,!1)});["capture","download"].forEach(function(s){yv[s]=new kb(s,4,!1,s,null,!1,!1)});["cols","rows","size","span"].forEach(function(s){yv[s]=new kb(s,6,!1,s,null,!1,!1)});["rowSpan","start"].forEach(function(s){yv[s]=new kb(s,5,!1,s.toLowerCase(),null,!1,!1)});var xYe=/[\-:]([a-z])/g;function yYe(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(xYe,yYe);yv[t]=new kb(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(xYe,yYe);yv[t]=new kb(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(xYe,yYe);yv[t]=new kb(t,1,!1,s,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(s){yv[s]=new kb(s,1,!1,s.toLowerCase(),null,!1,!1)});yv.xlinkHref=new kb("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(s){yv[s]=new kb(s,1,!1,s.toLowerCase(),null,!0,!0)});function vYe(s,t,n,r){var a=yv.hasOwnProperty(t)?yv[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{tDe=!1,Error.prepareStackTrace=n}return(s=s?s.displayName||s.name:"")?dZ(s):""}function ids(s){switch(s.tag){case 5:return dZ(s.type);case 16:return dZ("Lazy");case 13:return dZ("Suspense");case 19:return dZ("SuspenseList");case 0:case 2:case 15:return s=sDe(s.type,!1),s;case 11:return s=sDe(s.type.render,!1),s;case 1:return s=sDe(s.type,!0),s;default:return""}}function SBe(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 nU:return"Fragment";case sU:return"Portal";case jBe:return"Profiler";case bYe:return"StrictMode";case NBe:return"Suspense";case kBe:return"SuspenseList"}if(typeof s=="object")switch(s.$$typeof){case bCt:return(s.displayName||"Context")+".Consumer";case vCt:return(s._context.displayName||"Context")+".Provider";case _Ye:var t=s.render;return s=s.displayName,s||(s=t.displayName||t.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case wYe:return t=s.displayName||null,t!==null?t:SBe(s.type)||"Memo";case DT:t=s._payload,s=s._init;try{return SBe(s(t))}catch{}}return null}function ods(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 SBe(t);case 8:return t===bYe?"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 sP(s){switch(typeof s){case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function wCt(s){var t=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function lds(s){var t=wCt(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 Fie(s){s._valueTracker||(s._valueTracker=lds(s))}function jCt(s){if(!s)return!1;var t=s._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return s&&(r=wCt(s)?s.checked?"true":"false":s.value),s=r,s!==n?(t.setValue(s),!0):!1}function m3e(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 CBe(s,t){var n=t.checked;return Mf({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??s._wrapperState.initialChecked})}function Kct(s,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=sP(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 NCt(s,t){t=t.checked,t!=null&&vYe(s,"checked",t,!1)}function ABe(s,t){NCt(s,t);var n=sP(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")?EBe(s,t.type,n):t.hasOwnProperty("defaultValue")&&EBe(s,t.type,sP(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(s.defaultChecked=!!t.defaultChecked)}function Yct(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 EBe(s,t,n){(t!=="number"||m3e(s.ownerDocument)!==s)&&(n==null?s.defaultValue=""+s._wrapperState.initialValue:s.defaultValue!==""+n&&(s.defaultValue=""+n))}var uZ=Array.isArray;function BU(s,t,n,r){if(s=s.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=zie.firstChild;s.firstChild;)s.removeChild(s.firstChild);for(;t.firstChild;)s.appendChild(t.firstChild)}});function PJ(s,t){if(t){var n=s.firstChild;if(n&&n===s.lastChild&&n.nodeType===3){n.nodeValue=t;return}}s.textContent=t}var pX={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},cds=["Webkit","ms","Moz","O"];Object.keys(pX).forEach(function(s){cds.forEach(function(t){t=t+s.charAt(0).toUpperCase()+s.substring(1),pX[t]=pX[s]})});function ACt(s,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||pX.hasOwnProperty(s)&&pX[s]?(""+t).trim():t+"px"}function ECt(s,t){s=s.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,a=ACt(n,t[n],r);n==="float"&&(n="cssFloat"),r?s.setProperty(n,a):s[n]=a}}var dds=Mf({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 PBe(s,t){if(t){if(dds[s]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(Ka(137,s));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(Ka(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(Ka(61))}if(t.style!=null&&typeof t.style!="object")throw Error(Ka(62))}}function LBe(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 IBe=null;function jYe(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var RBe=null,UU=null,qU=null;function Qct(s){if(s=wne(s)){if(typeof RBe!="function")throw Error(Ka(280));var t=s.stateNode;t&&(t=o6e(t),RBe(s.stateNode,s.type,t))}}function TCt(s){UU?qU?qU.push(s):qU=[s]:UU=s}function MCt(){if(UU){var s=UU,t=qU;if(qU=UU=null,Qct(s),t)for(s=0;s>>=0,s===0?32:31-(_ds(s)/wds|0)|0}var Bie=64,Uie=4194304;function hZ(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 x3e(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=hZ(o):(i&=l,i!==0&&(r=hZ(i)))}else l=n&~a,l!==0?r=hZ(l):i!==0&&(r=hZ(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 bne(s,t,n){s.pendingLanes|=t,t!==536870912&&(s.suspendedLanes=0,s.pingedLanes=0),s=s.eventTimes,t=31-Kk(t),s[t]=n}function Sds(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=gX),odt=" ",ldt=!1;function XCt(s,t){switch(s){case"keyup":return eus.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function QCt(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var rU=!1;function sus(s,t){switch(s){case"compositionend":return QCt(t);case"keypress":return t.which!==32?null:(ldt=!0,odt);case"textInput":return s=t.data,s===odt&&ldt?null:s;default:return null}}function nus(s,t){if(rU)return s==="compositionend"||!MYe&&XCt(s,t)?(s=YCt(),wde=AYe=Y6=null,rU=!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=hdt(n)}}function sAt(s,t){return s&&t?s===t?!0:s&&s.nodeType===3?!1:t&&t.nodeType===3?sAt(s,t.parentNode):"contains"in s?s.contains(t):s.compareDocumentPosition?!!(s.compareDocumentPosition(t)&16):!1:!1}function nAt(){for(var s=window,t=m3e();t instanceof s.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)s=t.contentWindow;else break;t=m3e(s.document)}return t}function PYe(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 hus(s){var t=nAt(),n=s.focusedElem,r=s.selectionRange;if(t!==n&&n&&n.ownerDocument&&sAt(n.ownerDocument.documentElement,n)){if(r!==null&&PYe(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=mdt(n,i);var l=mdt(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,aU=null,UBe=null,yX=null,qBe=!1;function pdt(s,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;qBe||aU==null||aU!==m3e(r)||(r=aU,"selectionStart"in r&&PYe(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}),yX&&FJ(yX,r)||(yX=r,r=b3e(UBe,"onSelect"),0lU||(s.current=KBe[lU],KBe[lU]=null,lU--)}function Tm(s,t){lU++,KBe[lU]=s.current,s.current=t}var nP={},o1=PP(nP),N_=PP(!1),h7=nP;function NV(s,t){var n=s.type.contextTypes;if(!n)return nP;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 k_(s){return s=s.childContextTypes,s!=null}function w3e(){lp(N_),lp(o1)}function _dt(s,t,n){if(o1.current!==nP)throw Error(Ka(168));Tm(o1,t),Tm(N_,n)}function hAt(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(Ka(108,ods(s)||"Unknown",a));return Mf({},n,r)}function j3e(s){return s=(s=s.stateNode)&&s.__reactInternalMemoizedMergedChildContext||nP,h7=o1.current,Tm(o1,s),Tm(N_,N_.current),!0}function wdt(s,t,n){var r=s.stateNode;if(!r)throw Error(Ka(169));n?(s=hAt(s,t,h7),r.__reactInternalMemoizedMergedChildContext=s,lp(N_),lp(o1),Tm(o1,s)):lp(N_),Tm(N_,n)}var EC=null,l6e=!1,gDe=!1;function mAt(s){EC===null?EC=[s]:EC.push(s)}function Nus(s){l6e=!0,mAt(s)}function LP(){if(!gDe&&EC!==null){gDe=!0;var s=0,t=Mh;try{var n=EC;for(Mh=1;s>=l,a-=l,hA=1<<32-Kk(t)+a|n<M?(I=L,L=null):I=L.sibling;var R=m(v,L,N[M],S);if(R===null){L===null&&(L=I);break}s&&L&&R.alternate===null&&t(v,L),b=i(R,b,M),T===null?A=R:T.sibling=R,T=R,L=I}if(M===N.length)return n(v,L),Dp&&dI(v,M),A;if(L===null){for(;MM?(I=L,L=null):I=L.sibling;var z=m(v,L,R.value,S);if(z===null){L===null&&(L=I);break}s&&L&&z.alternate===null&&t(v,L),b=i(z,b,M),T===null?A=z:T.sibling=z,T=z,L=I}if(R.done)return n(v,L),Dp&&dI(v,M),A;if(L===null){for(;!R.done;M++,R=N.next())R=h(v,R.value,S),R!==null&&(b=i(R,b,M),T===null?A=R:T.sibling=R,T=R);return Dp&&dI(v,M),A}for(L=r(v,L);!R.done;M++,R=N.next())R=p(L,v,M,R.value,S),R!==null&&(s&&R.alternate!==null&&L.delete(R.key===null?M:R.key),b=i(R,b,M),T===null?A=R:T.sibling=R,T=R);return s&&L.forEach(function($){return t(v,$)}),Dp&&dI(v,M),A}function y(v,b,N,S){if(typeof N=="object"&&N!==null&&N.type===nU&&N.key===null&&(N=N.props.children),typeof N=="object"&&N!==null){switch(N.$$typeof){case Oie:e:{for(var A=N.key,T=b;T!==null;){if(T.key===A){if(A=N.type,A===nU){if(T.tag===7){n(v,T.sibling),b=a(T,N.props.children),b.return=v,v=b;break e}}else if(T.elementType===A||typeof A=="object"&&A!==null&&A.$$typeof===DT&&kdt(A)===T.type){n(v,T.sibling),b=a(T,N.props),b.ref=RK(v,T,N),b.return=v,v=b;break e}n(v,T);break}else t(v,T);T=T.sibling}N.type===nU?(b=vF(N.props.children,v.mode,S,N.key),b.return=v,v=b):(S=Tde(N.type,N.key,N.props,null,v.mode,S),S.ref=RK(v,b,N),S.return=v,v=S)}return l(v);case sU:e:{for(T=N.key;b!==null;){if(b.key===T)if(b.tag===4&&b.stateNode.containerInfo===N.containerInfo&&b.stateNode.implementation===N.implementation){n(v,b.sibling),b=a(b,N.children||[]),b.return=v,v=b;break e}else{n(v,b);break}else t(v,b);b=b.sibling}b=NDe(N,v.mode,S),b.return=v,v=b}return l(v);case DT:return T=N._init,y(v,b,T(N._payload),S)}if(uZ(N))return f(v,b,N,S);if(TK(N))return x(v,b,N,S);Kie(v,N)}return typeof N=="string"&&N!==""||typeof N=="number"?(N=""+N,b!==null&&b.tag===6?(n(v,b.sibling),b=a(b,N),b.return=v,v=b):(n(v,b),b=jDe(N,v.mode,S),b.return=v,v=b),l(v)):n(v,b)}return y}var SV=xAt(!0),yAt=xAt(!1),S3e=PP(null),C3e=null,uU=null,DYe=null;function OYe(){DYe=uU=C3e=null}function FYe(s){var t=S3e.current;lp(S3e),s._currentValue=t}function XBe(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 VU(s,t){C3e=s,DYe=uU=null,s=s.dependencies,s!==null&&s.firstContext!==null&&(s.lanes&t&&(x_=!0),s.firstContext=null)}function dN(s){var t=s._currentValue;if(DYe!==s)if(s={context:s,memoizedValue:t,next:null},uU===null){if(C3e===null)throw Error(Ka(308));uU=s,C3e.dependencies={lanes:0,firstContext:s}}else uU=uU.next=s;return t}var zD=null;function zYe(s){zD===null?zD=[s]:zD.push(s)}function vAt(s,t,n,r){var a=t.interleaved;return a===null?(n.next=n,zYe(t)):(n.next=a.next,a.next=n),t.interleaved=n,QA(s,r)}function QA(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 OT=!1;function BYe(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function bAt(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 _A(s,t){return{eventTime:s,lane:t,tag:0,payload:null,callback:null,next:null}}function gM(s,t,n){var r=s.updateQueue;if(r===null)return null;if(r=r.shared,xu&2){var a=r.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),r.pending=t,QA(s,n)}return a=r.interleaved,a===null?(t.next=t,zYe(r)):(t.next=a.next,a.next=t),r.interleaved=t,QA(s,n)}function Nde(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,kYe(s,n)}}function Sdt(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 A3e(s,t,n,r){var a=s.updateQueue;OT=!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,p=o.eventTime;if((r&m)===m){u!==null&&(u=u.next={eventTime:p,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var f=s,x=o;switch(m=t,p=n,x.tag){case 1:if(f=x.payload,typeof f=="function"){h=f.call(p,h,m);break e}h=f;break e;case 3:f.flags=f.flags&-65537|128;case 0:if(f=x.payload,m=typeof f=="function"?f.call(p,h,m):f,m==null)break e;h=Mf({},h,m);break e;case 2:OT=!0}}o.callback!==null&&o.lane!==0&&(s.flags|=64,m=a.effects,m===null?a.effects=[o]:m.push(o))}else p={eventTime:p,lane:m,tag:o.tag,payload:o.payload,callback:o.callback,next:null},u===null?(d=u=p,c=h):u=u.next=p,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);f7|=l,s.lanes=l,s.memoizedState=h}}function Cdt(s,t,n){if(s=t.effects,t.effects=null,s!==null)for(t=0;tn?n:4,s(!0);var r=yDe.transition;yDe.transition={};try{s(!1),t()}finally{Mh=n,yDe.transition=r}}function OAt(){return uN().memoizedState}function Aus(s,t,n){var r=yM(s);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},FAt(s))zAt(t,n);else if(n=vAt(s,t,n,r),n!==null){var a=lb();Yk(n,s,r,a),BAt(n,t,r)}}function Eus(s,t,n){var r=yM(s),a={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(FAt(s))zAt(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,uS(o,l)){var c=t.interleaved;c===null?(a.next=a,zYe(t)):(a.next=c.next,c.next=a),t.interleaved=a;return}}catch{}finally{}n=vAt(s,t,a,r),n!==null&&(a=lb(),Yk(n,s,r,a),BAt(n,t,r))}}function FAt(s){var t=s.alternate;return s===jf||t!==null&&t===jf}function zAt(s,t){vX=T3e=!0;var n=s.pending;n===null?t.next=t:(t.next=n.next,n.next=t),s.pending=t}function BAt(s,t,n){if(n&4194240){var r=t.lanes;r&=s.pendingLanes,n|=r,t.lanes=n,kYe(s,n)}}var M3e={readContext:dN,useCallback:Rv,useContext:Rv,useEffect:Rv,useImperativeHandle:Rv,useInsertionEffect:Rv,useLayoutEffect:Rv,useMemo:Rv,useReducer:Rv,useRef:Rv,useState:Rv,useDebugValue:Rv,useDeferredValue:Rv,useTransition:Rv,useMutableSource:Rv,useSyncExternalStore:Rv,useId:Rv,unstable_isNewReconciler:!1},Tus={readContext:dN,useCallback:function(s,t){return N5().memoizedState=[s,t===void 0?null:t],s},useContext:dN,useEffect:Edt,useImperativeHandle:function(s,t,n){return n=n!=null?n.concat([s]):null,Sde(4194308,4,PAt.bind(null,t,s),n)},useLayoutEffect:function(s,t){return Sde(4194308,4,s,t)},useInsertionEffect:function(s,t){return Sde(4,2,s,t)},useMemo:function(s,t){var n=N5();return t=t===void 0?null:t,s=s(),n.memoizedState=[s,t],s},useReducer:function(s,t,n){var r=N5();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=Aus.bind(null,jf,s),[r.memoizedState,s]},useRef:function(s){var t=N5();return s={current:s},t.memoizedState=s},useState:Adt,useDebugValue:KYe,useDeferredValue:function(s){return N5().memoizedState=s},useTransition:function(){var s=Adt(!1),t=s[0];return s=Cus.bind(null,s[1]),N5().memoizedState=s,[t,s]},useMutableSource:function(){},useSyncExternalStore:function(s,t,n){var r=jf,a=N5();if(Dp){if(n===void 0)throw Error(Ka(407));n=n()}else{if(n=t(),ay===null)throw Error(Ka(349));p7&30||NAt(r,t,n)}a.memoizedState=n;var i={value:n,getSnapshot:t};return a.queue=i,Edt(SAt.bind(null,r,i,s),[s]),r.flags|=2048,GJ(9,kAt.bind(null,r,i,n,t),void 0,null),n},useId:function(){var s=N5(),t=ay.identifierPrefix;if(Dp){var n=mA,r=hA;n=(r&~(1<<32-Kk(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=VJ++,0<\/script>",s=s.removeChild(s.firstChild)):typeof r.is=="string"?s=l.createElement(n,{is:r.is}):(s=l.createElement(n),n==="select"&&(l=s,r.multiple?l.multiple=!0:r.size&&(l.size=r.size))):s=l.createElementNS(s,n),s[a4]=t,s[UJ]=r,ZAt(s,t,!1,!1),t.stateNode=s;e:{switch(l=LBe(n,r),n){case"dialog":Jm("cancel",s),Jm("close",s),a=r;break;case"iframe":case"object":case"embed":Jm("load",s),a=r;break;case"video":case"audio":for(a=0;aEV&&(t.flags|=128,r=!0,DK(i,!1),t.lanes=4194304)}else{if(!r)if(s=E3e(l),s!==null){if(t.flags|=128,r=!0,n=s.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),DK(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!Dp)return Dv(t),null}else 2*Mg()-i.renderingStartTime>EV&&n!==1073741824&&(t.flags|=128,r=!0,DK(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=Mg(),t.sibling=null,n=ff.current,Tm(ff,r?n&1|2:n&1),t):(Dv(t),null);case 22:case 23:return eZe(),r=t.memoizedState!==null,s!==null&&s.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Mw&1073741824&&(Dv(t),t.subtreeFlags&6&&(t.flags|=8192)):Dv(t),null;case 24:return null;case 25:return null}throw Error(Ka(156,t.tag))}function Fus(s,t){switch(IYe(t),t.tag){case 1:return k_(t.type)&&w3e(),s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 3:return CV(),lp(N_),lp(o1),$Ye(),s=t.flags,s&65536&&!(s&128)?(t.flags=s&-65537|128,t):null;case 5:return qYe(t),null;case 13:if(lp(ff),s=t.memoizedState,s!==null&&s.dehydrated!==null){if(t.alternate===null)throw Error(Ka(340));kV()}return s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 19:return lp(ff),null;case 4:return CV(),null;case 10:return FYe(t.type._context),null;case 22:case 23:return eZe(),null;case 24:return null;default:return null}}var Zie=!1,Qv=!1,zus=typeof WeakSet=="function"?WeakSet:Set,co=null;function hU(s,t){var n=s.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Xf(s,t,r)}else n.current=null}function iUe(s,t,n){try{n()}catch(r){Xf(s,t,r)}}var Bdt=!1;function Bus(s,t){if($Be=y3e,s=nAt(),PYe(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 p;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),(p=h.firstChild)!==null;)m=h,h=p;for(;;){if(h===s)break t;if(m===n&&++d===a&&(o=l),m===i&&++u===r&&(c=l),(p=h.nextSibling)!==null)break;h=m,m=h.parentNode}h=p}n=o===-1||c===-1?null:{start:o,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(VBe={focusedElem:s,selectionRange:n},y3e=!1,co=t;co!==null;)if(t=co,s=t.child,(t.subtreeFlags&1028)!==0&&s!==null)s.return=t,co=s;else for(;co!==null;){t=co;try{var f=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(f!==null){var x=f.memoizedProps,y=f.memoizedState,v=t.stateNode,b=v.getSnapshotBeforeUpdate(t.elementType===t.type?x:mk(t.type,x),y);v.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var N=t.stateNode.containerInfo;N.nodeType===1?N.textContent="":N.nodeType===9&&N.documentElement&&N.removeChild(N.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Ka(163))}}catch(S){Xf(t,t.return,S)}if(s=t.sibling,s!==null){s.return=t.return,co=s;break}co=t.return}return f=Bdt,Bdt=!1,f}function bX(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&&iUe(t,n,i)}a=a.next}while(a!==r)}}function u6e(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 oUe(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 JAt(s){var t=s.alternate;t!==null&&(s.alternate=null,JAt(t)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(t=s.stateNode,t!==null&&(delete t[a4],delete t[UJ],delete t[WBe],delete t[wus],delete t[jus])),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 eEt(s){return s.tag===5||s.tag===3||s.tag===4}function Udt(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||eEt(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 lUe(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=_3e));else if(r!==4&&(s=s.child,s!==null))for(lUe(s,t,n),s=s.sibling;s!==null;)lUe(s,t,n),s=s.sibling}function cUe(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(cUe(s,t,n),s=s.sibling;s!==null;)cUe(s,t,n),s=s.sibling}var Hy=null,Tk=!1;function QE(s,t,n){for(n=n.child;n!==null;)tEt(s,t,n),n=n.sibling}function tEt(s,t,n){if(N4&&typeof N4.onCommitFiberUnmount=="function")try{N4.onCommitFiberUnmount(n6e,n)}catch{}switch(n.tag){case 5:Qv||hU(n,t);case 6:var r=Hy,a=Tk;Hy=null,QE(s,t,n),Hy=r,Tk=a,Hy!==null&&(Tk?(s=Hy,n=n.stateNode,s.nodeType===8?s.parentNode.removeChild(n):s.removeChild(n)):Hy.removeChild(n.stateNode));break;case 18:Hy!==null&&(Tk?(s=Hy,n=n.stateNode,s.nodeType===8?fDe(s.parentNode,n):s.nodeType===1&&fDe(s,n),DJ(s)):fDe(Hy,n.stateNode));break;case 4:r=Hy,a=Tk,Hy=n.stateNode.containerInfo,Tk=!0,QE(s,t,n),Hy=r,Tk=a;break;case 0:case 11:case 14:case 15:if(!Qv&&(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)&&iUe(n,t,l),a=a.next}while(a!==r)}QE(s,t,n);break;case 1:if(!Qv&&(hU(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){Xf(n,t,o)}QE(s,t,n);break;case 21:QE(s,t,n);break;case 22:n.mode&1?(Qv=(r=Qv)||n.memoizedState!==null,QE(s,t,n),Qv=r):QE(s,t,n);break;default:QE(s,t,n)}}function qdt(s){var t=s.updateQueue;if(t!==null){s.updateQueue=null;var n=s.stateNode;n===null&&(n=s.stateNode=new zus),t.forEach(function(r){var a=Yus.bind(null,s,r);n.has(r)||(n.add(r),r.then(a,a))})}}function JN(s,t){var n=t.deletions;if(n!==null)for(var r=0;ra&&(a=l),r&=~i}if(r=a,r=Mg()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*qus(r/1960))-r,10s?16:s,Z6===null)var r=!1;else{if(s=Z6,Z6=null,I3e=0,xu&6)throw Error(Ka(331));var a=xu;for(xu|=4,co=s.current;co!==null;){var i=co,l=i.child;if(co.flags&16){var o=i.deletions;if(o!==null){for(var c=0;cMg()-QYe?yF(s,0):XYe|=n),S_(s,t)}function cEt(s,t){t===0&&(s.mode&1?(t=Uie,Uie<<=1,!(Uie&130023424)&&(Uie=4194304)):t=1);var n=lb();s=QA(s,t),s!==null&&(bne(s,t,n),S_(s,n))}function Kus(s){var t=s.memoizedState,n=0;t!==null&&(n=t.retryLane),cEt(s,n)}function Yus(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(Ka(314))}r!==null&&r.delete(t),cEt(s,n)}var dEt;dEt=function(s,t,n){if(s!==null)if(s.memoizedProps!==t.pendingProps||N_.current)x_=!0;else{if(!(s.lanes&n)&&!(t.flags&128))return x_=!1,Dus(s,t,n);x_=!!(s.flags&131072)}else x_=!1,Dp&&t.flags&1048576&&pAt(t,k3e,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Cde(s,t),s=t.pendingProps;var a=NV(t,o1.current);VU(t,n),a=HYe(null,t,r,s,a,n);var i=GYe();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,k_(r)?(i=!0,j3e(t)):i=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,BYe(t),a.updater=d6e,t.stateNode=a,a._reactInternals=t,JBe(t,r,s,n),t=sUe(null,t,r,!0,i,n)):(t.tag=0,Dp&&i&&LYe(t),W1(null,t,a,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Cde(s,t),s=t.pendingProps,a=r._init,r=a(r._payload),t.type=r,a=t.tag=Xus(r),s=mk(r,s),a){case 0:t=tUe(null,t,r,s,n);break e;case 1:t=Odt(null,t,r,s,n);break e;case 11:t=Rdt(null,t,r,s,n);break e;case 14:t=Ddt(null,t,r,mk(r.type,s),n);break e}throw Error(Ka(306,r,""))}return t;case 0:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:mk(r,a),tUe(s,t,r,a,n);case 1:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:mk(r,a),Odt(s,t,r,a,n);case 3:e:{if(WAt(t),s===null)throw Error(Ka(387));r=t.pendingProps,i=t.memoizedState,a=i.element,bAt(s,t),A3e(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=AV(Error(Ka(423)),t),t=Fdt(s,t,r,n,a);break e}else if(r!==a){a=AV(Error(Ka(424)),t),t=Fdt(s,t,r,n,a);break e}else for(qw=fM(t.stateNode.containerInfo.firstChild),Zw=t,Dp=!0,Dk=null,n=yAt(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(kV(),r===a){t=JA(s,t,n);break e}W1(s,t,r,n)}t=t.child}return t;case 5:return _At(t),s===null&&ZBe(t),r=t.type,a=t.pendingProps,i=s!==null?s.memoizedProps:null,l=a.children,HBe(r,a)?l=null:i!==null&&HBe(r,i)&&(t.flags|=32),GAt(s,t),W1(s,t,l,n),t.child;case 6:return s===null&&ZBe(t),null;case 13:return KAt(s,t,n);case 4:return UYe(t,t.stateNode.containerInfo),r=t.pendingProps,s===null?t.child=SV(t,null,r,n):W1(s,t,r,n),t.child;case 11:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:mk(r,a),Rdt(s,t,r,a,n);case 7:return W1(s,t,t.pendingProps,n),t.child;case 8:return W1(s,t,t.pendingProps.children,n),t.child;case 12:return W1(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,Tm(S3e,r._currentValue),r._currentValue=l,i!==null)if(uS(i.value,l)){if(i.children===a.children&&!N_.current){t=JA(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=_A(-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),XBe(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(Ka(341));l.lanes|=n,o=l.alternate,o!==null&&(o.lanes|=n),XBe(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}W1(s,t,a.children,n),t=t.child}return t;case 9:return a=t.type,r=t.pendingProps.children,VU(t,n),a=dN(a),r=r(a),t.flags|=1,W1(s,t,r,n),t.child;case 14:return r=t.type,a=mk(r,t.pendingProps),a=mk(r.type,a),Ddt(s,t,r,a,n);case 15:return VAt(s,t,t.type,t.pendingProps,n);case 17:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:mk(r,a),Cde(s,t),t.tag=1,k_(r)?(s=!0,j3e(t)):s=!1,VU(t,n),UAt(t,r,a),JBe(t,r,a,n),sUe(null,t,r,!0,s,n);case 19:return YAt(s,t,n);case 22:return HAt(s,t,n)}throw Error(Ka(156,t.tag))};function uEt(s,t){return FCt(s,t)}function Zus(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 z2(s,t,n,r){return new Zus(s,t,n,r)}function sZe(s){return s=s.prototype,!(!s||!s.isReactComponent)}function Xus(s){if(typeof s=="function")return sZe(s)?1:0;if(s!=null){if(s=s.$$typeof,s===_Ye)return 11;if(s===wYe)return 14}return 2}function vM(s,t){var n=s.alternate;return n===null?(n=z2(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 Tde(s,t,n,r,a,i){var l=2;if(r=s,typeof s=="function")sZe(s)&&(l=1);else if(typeof s=="string")l=5;else e:switch(s){case nU:return vF(n.children,a,i,t);case bYe:l=8,a|=8;break;case jBe:return s=z2(12,n,t,a|2),s.elementType=jBe,s.lanes=i,s;case NBe:return s=z2(13,n,t,a),s.elementType=NBe,s.lanes=i,s;case kBe:return s=z2(19,n,t,a),s.elementType=kBe,s.lanes=i,s;case _Ct:return m6e(n,a,i,t);default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case vCt:l=10;break e;case bCt:l=9;break e;case _Ye:l=11;break e;case wYe:l=14;break e;case DT:l=16,r=null;break e}throw Error(Ka(130,s==null?s:typeof s,""))}return t=z2(l,n,t,a),t.elementType=s,t.type=r,t.lanes=i,t}function vF(s,t,n,r){return s=z2(7,s,r,t),s.lanes=n,s}function m6e(s,t,n,r){return s=z2(22,s,r,t),s.elementType=_Ct,s.lanes=n,s.stateNode={isHidden:!1},s}function jDe(s,t,n){return s=z2(6,s,null,t),s.lanes=n,s}function NDe(s,t,n){return t=z2(4,s.children!==null?s.children:[],s.key,t),t.lanes=n,t.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},t}function Qus(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=rDe(0),this.expirationTimes=rDe(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=rDe(0),this.identifierPrefix=r,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function nZe(s,t,n,r,a,i,l,o,c){return s=new Qus(s,t,n,o,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=z2(3,null,null,t),s.current=i,i.stateNode=s,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},BYe(i),s}function Jus(s,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(fEt)}catch(s){console.error(s)}}fEt(),fCt.exports=Nj;var tv=fCt.exports;const oZe=od(tv);var gEt,Zdt=tv;gEt=Zdt.createRoot,Zdt.hydrateRoot;const rhs="modulepreload",ahs=function(s){return"/"+s},Xdt={},ui=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=ahs(c),c in Xdt)return;Xdt[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":rhs,d||(h.as="script"),h.crossOrigin="",h.href=c,o&&h.setAttribute("nonce",o),document.head.appendChild(h),d)return new Promise((m,p)=>{h.addEventListener("load",m),h.addEventListener("error",()=>p(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)})},ihs=new Set(["localhost","relevelup.com","thelocalmove.com","www.thelocalmove.com"]),ohs=s=>s.toLowerCase().replace(/:\d+$/,"").replace(/^www\./,"");function lhs(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")||ihs.has(s))}function xEt(s){return yEt(s)!==null}function yEt(s){const t=ohs(s);return lhs(t)?null:t}const chs=1,dhs=1e6;let kDe=0;function uhs(){return kDe=(kDe+1)%Number.MAX_SAFE_INTEGER,kDe.toString()}const SDe=new Map,Qdt=s=>{if(SDe.has(s))return;const t=setTimeout(()=>{SDe.delete(s),jX({type:"REMOVE_TOAST",toastId:s})},dhs);SDe.set(s,t)},hhs=(s,t)=>{switch(t.type){case"ADD_TOAST":return{...s,toasts:[t.toast,...s.toasts].slice(0,chs)};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?Qdt(n):s.toasts.forEach(r=>{Qdt(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)}}},Mde=[];let Pde={toasts:[]};function jX(s){Pde=hhs(Pde,s),Mde.forEach(t=>{t(Pde)})}function ka({...s}){const t=uhs(),n=a=>jX({type:"UPDATE_TOAST",toast:{...a,id:t}}),r=()=>jX({type:"DISMISS_TOAST",toastId:t});return jX({type:"ADD_TOAST",toast:{...s,id:t,open:!0,onOpenChange:a=>{a||r()}}}),{id:t,dismiss:r,update:n}}function Ai(){const[s,t]=j.useState(Pde);return j.useEffect(()=>(Mde.push(t),()=>{const n=Mde.indexOf(t);n>-1&&Mde.splice(n,1)}),[s]),{...s,toast:ka,dismiss:n=>jX({type:"DISMISS_TOAST",toastId:n})}}function va(s,t,{checkForDefaultPrevented:n=!0}={}){return function(a){if(s==null||s(a),n===!1||!a.defaultPrevented)return t==null?void 0:t(a)}}function Jdt(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function eE(...s){return t=>{let n=!1;const r=s.map(a=>{const i=Jdt(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a{const{children:l,...o}=i,c=j.useMemo(()=>o,Object.values(o));return e.jsx(n.Provider,{value:c,children:l})};r.displayName=s+"Provider";function a(i){const l=j.useContext(n);if(l)return l;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${s}\``)}return[r,a]}function Up(s,t=[]){let n=[];function r(i,l){const o=j.createContext(l),c=n.length;n=[...n,l];const d=h=>{var v;const{scope:m,children:p,...f}=h,x=((v=m==null?void 0:m[s])==null?void 0:v[c])||o,y=j.useMemo(()=>f,Object.values(f));return e.jsx(x.Provider,{value:y,children:p})};d.displayName=i+"Provider";function u(h,m){var x;const p=((x=m==null?void 0:m[s])==null?void 0:x[c])||o,f=j.useContext(p);if(f)return f;if(l!==void 0)return l;throw new Error(`\`${h}\` must be used within \`${i}\``)}return[d,u]}const a=()=>{const i=n.map(l=>j.createContext(l));return function(o){const c=(o==null?void 0:o[s])||i;return j.useMemo(()=>({[`__scope${s}`]:{...o,[s]:c}}),[o,c])}};return a.scopeName=s,[r,phs(a,...t)]}function phs(...s){const t=s[0];if(s.length===1)return t;const n=()=>{const r=s.map(a=>({useScope:a(),scopeName:a.scopeName}));return 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])}};return n.scopeName=t.scopeName,n}function rP(s){const t=fhs(s),n=j.forwardRef((r,a)=>{const{children:i,...l}=r,o=j.Children.toArray(i),c=o.find(ghs);if(c){const d=c.props.children,u=o.map(h=>h===c?j.Children.count(d)>1?j.Children.only(null):j.isValidElement(d)?d.props.children:null:h);return e.jsx(t,{...l,ref:a,children:j.isValidElement(d)?j.cloneElement(d,void 0,u):null})}return e.jsx(t,{...l,ref:a,children:i})});return n.displayName=`${s}.Slot`,n}var lZe=rP("Slot");function fhs(s){const t=j.forwardRef((n,r)=>{const{children:a,...i}=n;if(j.isValidElement(a)){const l=yhs(a),o=xhs(i,a.props);return a.type!==j.Fragment&&(o.ref=r?eE(r,l):l),j.cloneElement(a,o)}return j.Children.count(a)>1?j.Children.only(null):null});return t.displayName=`${s}.SlotClone`,t}var vEt=Symbol("radix.slottable");function bEt(s){const t=({children:n})=>e.jsx(e.Fragment,{children:n});return t.displayName=`${s}.Slottable`,t.__radixId=vEt,t}function ghs(s){return j.isValidElement(s)&&typeof s.type=="function"&&"__radixId"in s.type&&s.type.__radixId===vEt}function xhs(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}}function yhs(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)}function tG(s){const t=s+"CollectionProvider",[n,r]=Up(t),[a,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),l=x=>{const{scope:y,children:v}=x,b=Dt.useRef(null),N=Dt.useRef(new Map).current;return e.jsx(a,{scope:y,itemMap:N,collectionRef:b,children:v})};l.displayName=t;const o=s+"CollectionSlot",c=rP(o),d=Dt.forwardRef((x,y)=>{const{scope:v,children:b}=x,N=i(o,v),S=Uo(y,N.collectionRef);return e.jsx(c,{ref:S,children:b})});d.displayName=o;const u=s+"CollectionItemSlot",h="data-radix-collection-item",m=rP(u),p=Dt.forwardRef((x,y)=>{const{scope:v,children:b,...N}=x,S=Dt.useRef(null),A=Uo(y,S),T=i(u,v);return Dt.useEffect(()=>(T.itemMap.set(S,{ref:S,...N}),()=>void T.itemMap.delete(S))),e.jsx(m,{[h]:"",ref:A,children:b})});p.displayName=u;function f(x){const y=i(s+"CollectionConsumer",x);return Dt.useCallback(()=>{const b=y.collectionRef.current;if(!b)return[];const N=Array.from(b.querySelectorAll(`[${h}]`));return Array.from(y.itemMap.values()).sort((T,L)=>N.indexOf(T.ref.current)-N.indexOf(L.ref.current))},[y.collectionRef,y.itemMap])}return[{Provider:l,Slot:d,ItemSlot:p},f,r]}var vhs=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],si=vhs.reduce((s,t)=>{const n=rP(`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 cZe(s,t){s&&tv.flushSync(()=>s.dispatchEvent(t))}function sg(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)},[])}function bhs(s,t=globalThis==null?void 0:globalThis.document){const n=sg(s);j.useEffect(()=>{const r=a=>{a.key==="Escape"&&n(a)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var _hs="DismissableLayer",pUe="dismissableLayer.update",whs="dismissableLayer.pointerDownOutside",jhs="dismissableLayer.focusOutside",eut,_Et=j.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),IP=j.forwardRef((s,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,onDismiss:o,...c}=s,d=j.useContext(_Et),[u,h]=j.useState(null),m=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=j.useState({}),f=Uo(t,L=>h(L)),x=Array.from(d.layers),[y]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),v=x.indexOf(y),b=u?x.indexOf(u):-1,N=d.layersWithOutsidePointerEventsDisabled.size>0,S=b>=v,A=khs(L=>{const M=L.target,I=[...d.branches].some(R=>R.contains(M));!S||I||(a==null||a(L),l==null||l(L),L.defaultPrevented||o==null||o())},m),T=Shs(L=>{const M=L.target;[...d.branches].some(R=>R.contains(M))||(i==null||i(L),l==null||l(L),L.defaultPrevented||o==null||o())},m);return bhs(L=>{b===d.layers.size-1&&(r==null||r(L),!L.defaultPrevented&&o&&(L.preventDefault(),o()))},m),j.useEffect(()=>{if(u)return n&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(eut=m.body.style.pointerEvents,m.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(u)),d.layers.add(u),tut(),()=>{n&&d.layersWithOutsidePointerEventsDisabled.size===1&&(m.body.style.pointerEvents=eut)}},[u,m,n,d]),j.useEffect(()=>()=>{u&&(d.layers.delete(u),d.layersWithOutsidePointerEventsDisabled.delete(u),tut())},[u,d]),j.useEffect(()=>{const L=()=>p({});return document.addEventListener(pUe,L),()=>document.removeEventListener(pUe,L)},[]),e.jsx(si.div,{...c,ref:f,style:{pointerEvents:N?S?"auto":"none":void 0,...s.style},onFocusCapture:va(s.onFocusCapture,T.onFocusCapture),onBlurCapture:va(s.onBlurCapture,T.onBlurCapture),onPointerDownCapture:va(s.onPointerDownCapture,A.onPointerDownCapture)})});IP.displayName=_hs;var Nhs="DismissableLayerBranch",wEt=j.forwardRef((s,t)=>{const n=j.useContext(_Et),r=j.useRef(null),a=Uo(t,r);return j.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),e.jsx(si.div,{...s,ref:a})});wEt.displayName=Nhs;function khs(s,t=globalThis==null?void 0:globalThis.document){const n=sg(s),r=j.useRef(!1),a=j.useRef(()=>{});return j.useEffect(()=>{const i=o=>{if(o.target&&!r.current){let c=function(){jEt(whs,n,d,{discrete:!0})};const d={originalEvent:o};o.pointerType==="touch"?(t.removeEventListener("click",a.current),a.current=c,t.addEventListener("click",a.current,{once:!0})):c()}else t.removeEventListener("click",a.current);r.current=!1},l=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(l),t.removeEventListener("pointerdown",i),t.removeEventListener("click",a.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function Shs(s,t=globalThis==null?void 0:globalThis.document){const n=sg(s),r=j.useRef(!1);return j.useEffect(()=>{const a=i=>{i.target&&!r.current&&jEt(jhs,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",a),()=>t.removeEventListener("focusin",a)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function tut(){const s=new CustomEvent(pUe);document.dispatchEvent(s)}function jEt(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?cZe(a,i):a.dispatchEvent(i)}var Chs=IP,Ahs=wEt,dg=globalThis!=null&&globalThis.document?j.useLayoutEffect:()=>{},Ehs="Portal",sG=j.forwardRef((s,t)=>{var o;const{container:n,...r}=s,[a,i]=j.useState(!1);dg(()=>i(!0),[]);const l=n||a&&((o=globalThis==null?void 0:globalThis.document)==null?void 0:o.body);return l?oZe.createPortal(e.jsx(si.div,{...r,ref:t}),l):null});sG.displayName=Ehs;function Ths(s,t){return j.useReducer((n,r)=>t[n][r]??n,s)}var Xg=s=>{const{present:t,children:n}=s,r=Mhs(t),a=typeof n=="function"?n({present:r.isPresent}):j.Children.only(n),i=Uo(r.ref,Phs(a));return typeof n=="function"||r.isPresent?j.cloneElement(a,{ref:i}):null};Xg.displayName="Presence";function Mhs(s){const[t,n]=j.useState(),r=j.useRef(null),a=j.useRef(s),i=j.useRef("none"),l=s?"mounted":"unmounted",[o,c]=Ths(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return j.useEffect(()=>{const d=Jie(r.current);i.current=o==="mounted"?d:"none"},[o]),dg(()=>{const d=r.current,u=a.current;if(u!==s){const m=i.current,p=Jie(d);s?c("MOUNT"):p==="none"||(d==null?void 0:d.display)==="none"?c("UNMOUNT"):c(u&&m!==p?"ANIMATION_OUT":"UNMOUNT"),a.current=s}},[s,c]),dg(()=>{if(t){let d;const u=t.ownerDocument.defaultView??window,h=p=>{const x=Jie(r.current).includes(p.animationName);if(p.target===t&&x&&(c("ANIMATION_END"),!a.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",d=u.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},m=p=>{p.target===t&&(i.current=Jie(r.current))};return t.addEventListener("animationstart",m),t.addEventListener("animationcancel",h),t.addEventListener("animationend",h),()=>{u.clearTimeout(d),t.removeEventListener("animationstart",m),t.removeEventListener("animationcancel",h),t.removeEventListener("animationend",h)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(o),ref:j.useCallback(d=>{r.current=d?getComputedStyle(d):null,n(d)},[])}}function Jie(s){return(s==null?void 0:s.animationName)||"none"}function Phs(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)}var Lhs=gYe[" useInsertionEffect ".trim().toString()]||dg;function Sx({prop:s,defaultProp:t,onChange:n=()=>{},caller:r}){const[a,i,l]=Ihs({defaultProp:t,onChange:n}),o=s!==void 0,c=o?s:a;{const u=j.useRef(s!==void 0);j.useEffect(()=>{const h=u.current;h!==o&&console.warn(`${r} is changing from ${h?"controlled":"uncontrolled"} to ${o?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=o},[o,r])}const d=j.useCallback(u=>{var h;if(o){const m=Rhs(u)?u(s):u;m!==s&&((h=l.current)==null||h.call(l,m))}else i(u)},[o,s,i,l]);return[c,d]}function Ihs({defaultProp:s,onChange:t}){const[n,r]=j.useState(s),a=j.useRef(n),i=j.useRef(t);return Lhs(()=>{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]}function Rhs(s){return typeof s=="function"}var NEt=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"}),Dhs="VisuallyHidden",y6e=j.forwardRef((s,t)=>e.jsx(si.span,{...s,ref:t,style:{...NEt,...s.style}}));y6e.displayName=Dhs;var Ohs=y6e,dZe="ToastProvider",[uZe,Fhs,zhs]=tG("Toast"),[kEt,Hfr]=Up("Toast",[zhs]),[Bhs,v6e]=kEt(dZe),SEt=s=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:a="right",swipeThreshold:i=50,children:l}=s,[o,c]=j.useState(null),[d,u]=j.useState(0),h=j.useRef(!1),m=j.useRef(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${dZe}\`. Expected non-empty \`string\`.`),e.jsx(uZe.Provider,{scope:t,children:e.jsx(Bhs,{scope:t,label:n,duration:r,swipeDirection:a,swipeThreshold:i,toastCount:d,viewport:o,onViewportChange:c,onToastAdd:j.useCallback(()=>u(p=>p+1),[]),onToastRemove:j.useCallback(()=>u(p=>p-1),[]),isFocusedToastEscapeKeyDownRef:h,isClosePausedRef:m,children:l})})};SEt.displayName=dZe;var CEt="ToastViewport",Uhs=["F8"],fUe="toast.viewportPause",gUe="toast.viewportResume",AEt=j.forwardRef((s,t)=>{const{__scopeToast:n,hotkey:r=Uhs,label:a="Notifications ({hotkey})",...i}=s,l=v6e(CEt,n),o=Fhs(n),c=j.useRef(null),d=j.useRef(null),u=j.useRef(null),h=j.useRef(null),m=Uo(t,h,l.onViewportChange),p=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),f=l.toastCount>0;j.useEffect(()=>{const y=v=>{var N;r.length!==0&&r.every(S=>v[S]||v.code===S)&&((N=h.current)==null||N.focus())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[r]),j.useEffect(()=>{const y=c.current,v=h.current;if(f&&y&&v){const b=()=>{if(!l.isClosePausedRef.current){const T=new CustomEvent(fUe);v.dispatchEvent(T),l.isClosePausedRef.current=!0}},N=()=>{if(l.isClosePausedRef.current){const T=new CustomEvent(gUe);v.dispatchEvent(T),l.isClosePausedRef.current=!1}},S=T=>{!y.contains(T.relatedTarget)&&N()},A=()=>{y.contains(document.activeElement)||N()};return y.addEventListener("focusin",b),y.addEventListener("focusout",S),y.addEventListener("pointermove",b),y.addEventListener("pointerleave",A),window.addEventListener("blur",b),window.addEventListener("focus",N),()=>{y.removeEventListener("focusin",b),y.removeEventListener("focusout",S),y.removeEventListener("pointermove",b),y.removeEventListener("pointerleave",A),window.removeEventListener("blur",b),window.removeEventListener("focus",N)}}},[f,l.isClosePausedRef]);const x=j.useCallback(({tabbingDirection:y})=>{const b=o().map(N=>{const S=N.ref.current,A=[S,...ems(S)];return y==="forwards"?A:A.reverse()});return(y==="forwards"?b.reverse():b).flat()},[o]);return j.useEffect(()=>{const y=h.current;if(y){const v=b=>{var A,T,L;const N=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!N){const M=document.activeElement,I=b.shiftKey;if(b.target===y&&I){(A=d.current)==null||A.focus();return}const $=x({tabbingDirection:I?"backwards":"forwards"}),H=$.findIndex(V=>V===M);CDe($.slice(H+1))?b.preventDefault():I?(T=d.current)==null||T.focus():(L=u.current)==null||L.focus()}};return y.addEventListener("keydown",v),()=>y.removeEventListener("keydown",v)}},[o,x]),e.jsxs(Ahs,{ref:c,role:"region","aria-label":a.replace("{hotkey}",p),tabIndex:-1,style:{pointerEvents:f?void 0:"none"},children:[f&&e.jsx(xUe,{ref:d,onFocusFromOutsideViewport:()=>{const y=x({tabbingDirection:"forwards"});CDe(y)}}),e.jsx(uZe.Slot,{scope:n,children:e.jsx(si.ol,{tabIndex:-1,...i,ref:m})}),f&&e.jsx(xUe,{ref:u,onFocusFromOutsideViewport:()=>{const y=x({tabbingDirection:"backwards"});CDe(y)}})]})});AEt.displayName=CEt;var EEt="ToastFocusProxy",xUe=j.forwardRef((s,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...a}=s,i=v6e(EEt,n);return e.jsx(y6e,{"aria-hidden":!0,tabIndex:0,...a,ref:t,style:{position:"fixed"},onFocus:l=>{var d;const o=l.relatedTarget;!((d=i.viewport)!=null&&d.contains(o))&&r()}})});xUe.displayName=EEt;var Nne="Toast",qhs="toast.swipeStart",$hs="toast.swipeMove",Vhs="toast.swipeCancel",Hhs="toast.swipeEnd",TEt=j.forwardRef((s,t)=>{const{forceMount:n,open:r,defaultOpen:a,onOpenChange:i,...l}=s,[o,c]=Sx({prop:r,defaultProp:a??!0,onChange:i,caller:Nne});return e.jsx(Xg,{present:n||o,children:e.jsx(Khs,{open:o,...l,ref:t,onClose:()=>c(!1),onPause:sg(s.onPause),onResume:sg(s.onResume),onSwipeStart:va(s.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:va(s.onSwipeMove,d=>{const{x:u,y:h}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${u}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${h}px`)}),onSwipeCancel:va(s.onSwipeCancel,d=>{d.currentTarget.setAttribute("data-swipe","cancel"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:va(s.onSwipeEnd,d=>{const{x:u,y:h}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${u}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${h}px`),c(!1)})})})});TEt.displayName=Nne;var[Ghs,Whs]=kEt(Nne,{onClose(){}}),Khs=j.forwardRef((s,t)=>{const{__scopeToast:n,type:r="foreground",duration:a,open:i,onClose:l,onEscapeKeyDown:o,onPause:c,onResume:d,onSwipeStart:u,onSwipeMove:h,onSwipeCancel:m,onSwipeEnd:p,...f}=s,x=v6e(Nne,n),[y,v]=j.useState(null),b=Uo(t,V=>v(V)),N=j.useRef(null),S=j.useRef(null),A=a||x.duration,T=j.useRef(0),L=j.useRef(A),M=j.useRef(0),{onToastAdd:I,onToastRemove:R}=x,z=sg(()=>{var K;(y==null?void 0:y.contains(document.activeElement))&&((K=x.viewport)==null||K.focus()),l()}),$=j.useCallback(V=>{!V||V===1/0||(window.clearTimeout(M.current),T.current=new Date().getTime(),M.current=window.setTimeout(z,V))},[z]);j.useEffect(()=>{const V=x.viewport;if(V){const K=()=>{$(L.current),d==null||d()},Z=()=>{const Q=new Date().getTime()-T.current;L.current=L.current-Q,window.clearTimeout(M.current),c==null||c()};return V.addEventListener(fUe,Z),V.addEventListener(gUe,K),()=>{V.removeEventListener(fUe,Z),V.removeEventListener(gUe,K)}}},[x.viewport,A,c,d,$]),j.useEffect(()=>{i&&!x.isClosePausedRef.current&&$(A)},[i,A,x.isClosePausedRef,$]),j.useEffect(()=>(I(),()=>R()),[I,R]);const H=j.useMemo(()=>y?OEt(y):null,[y]);return x.viewport?e.jsxs(e.Fragment,{children:[H&&e.jsx(Yhs,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0,children:H}),e.jsx(Ghs,{scope:n,onClose:z,children:tv.createPortal(e.jsx(uZe.ItemSlot,{scope:n,children:e.jsx(Chs,{asChild:!0,onEscapeKeyDown:va(o,()=>{x.isFocusedToastEscapeKeyDownRef.current||z(),x.isFocusedToastEscapeKeyDownRef.current=!1}),children:e.jsx(si.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":x.swipeDirection,...f,ref:b,style:{userSelect:"none",touchAction:"none",...s.style},onKeyDown:va(s.onKeyDown,V=>{V.key==="Escape"&&(o==null||o(V.nativeEvent),V.nativeEvent.defaultPrevented||(x.isFocusedToastEscapeKeyDownRef.current=!0,z()))}),onPointerDown:va(s.onPointerDown,V=>{V.button===0&&(N.current={x:V.clientX,y:V.clientY})}),onPointerMove:va(s.onPointerMove,V=>{if(!N.current)return;const K=V.clientX-N.current.x,Z=V.clientY-N.current.y,Q=!!S.current,le=["left","right"].includes(x.swipeDirection),ue=["left","up"].includes(x.swipeDirection)?Math.min:Math.max,se=le?ue(0,K):0,ne=le?0:ue(0,Z),ie=V.pointerType==="touch"?10:2,ce={x:se,y:ne},je={originalEvent:V,delta:ce};Q?(S.current=ce,eoe($hs,h,je,{discrete:!1})):sut(ce,x.swipeDirection,ie)?(S.current=ce,eoe(qhs,u,je,{discrete:!1}),V.target.setPointerCapture(V.pointerId)):(Math.abs(K)>ie||Math.abs(Z)>ie)&&(N.current=null)}),onPointerUp:va(s.onPointerUp,V=>{const K=S.current,Z=V.target;if(Z.hasPointerCapture(V.pointerId)&&Z.releasePointerCapture(V.pointerId),S.current=null,N.current=null,K){const Q=V.currentTarget,le={originalEvent:V,delta:K};sut(K,x.swipeDirection,x.swipeThreshold)?eoe(Hhs,p,le,{discrete:!0}):eoe(Vhs,m,le,{discrete:!0}),Q.addEventListener("click",ue=>ue.preventDefault(),{once:!0})}})})})}),x.viewport)})]}):null}),Yhs=s=>{const{__scopeToast:t,children:n,...r}=s,a=v6e(Nne,t),[i,l]=j.useState(!1),[o,c]=j.useState(!1);return Qhs(()=>l(!0)),j.useEffect(()=>{const d=window.setTimeout(()=>c(!0),1e3);return()=>window.clearTimeout(d)},[]),o?null:e.jsx(sG,{asChild:!0,children:e.jsx(y6e,{...r,children:i&&e.jsxs(e.Fragment,{children:[a.label," ",n]})})})},Zhs="ToastTitle",MEt=j.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s;return e.jsx(si.div,{...r,ref:t})});MEt.displayName=Zhs;var Xhs="ToastDescription",PEt=j.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s;return e.jsx(si.div,{...r,ref:t})});PEt.displayName=Xhs;var LEt="ToastAction",IEt=j.forwardRef((s,t)=>{const{altText:n,...r}=s;return n.trim()?e.jsx(DEt,{altText:n,asChild:!0,children:e.jsx(hZe,{...r,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${LEt}\`. Expected non-empty \`string\`.`),null)});IEt.displayName=LEt;var REt="ToastClose",hZe=j.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s,a=Whs(REt,n);return e.jsx(DEt,{asChild:!0,children:e.jsx(si.button,{type:"button",...r,ref:t,onClick:va(s.onClick,a.onClose)})})});hZe.displayName=REt;var DEt=j.forwardRef((s,t)=>{const{__scopeToast:n,altText:r,...a}=s;return e.jsx(si.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...a,ref:t})});function OEt(s){const t=[];return Array.from(s.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),Jhs(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(...OEt(r))}}),t}function eoe(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?cZe(a,i):a.dispatchEvent(i)}var sut=(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};function Qhs(s=()=>{}){const t=sg(s);dg(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function Jhs(s){return s.nodeType===s.ELEMENT_NODE}function ems(s){const t=[],n=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode: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}});for(;n.nextNode();)t.push(n.currentNode);return t}function CDe(s){const t=document.activeElement;return s.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}var tms=SEt,FEt=AEt,zEt=TEt,BEt=MEt,UEt=PEt,qEt=IEt,$Et=hZe;function VEt(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,rut=mc,u9=(s,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return rut(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=nut(u)||nut(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,...p}=u;return Object.entries(p).every(f=>{let[x,y]=f;return Array.isArray(y)?y.includes({...i,...o}[x]):{...i,...o}[x]===y})?[...d,h,m]:d},[]);return rut(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 sms=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),HEt=(...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 nms={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 GEt=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,...nms,width:t,height:t,stroke:s,strokeWidth:r?Number(n)*24/Number(t):n,className:HEt("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 me=(s,t)=>{const n=j.forwardRef(({className:r,...a},i)=>j.createElement(GEt,{ref:i,iconNode:t,className:HEt(`lucide-${sms(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 Lde=me("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 Ide=me("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 Rde=me("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 Dde=me("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 Lm=me("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 Ode=me("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 Fde=me("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 hI=me("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 mI=me("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 zde=me("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 pI=me("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 Bde=me("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 Ude=me("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 qde=me("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 $de=me("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 Vde=me("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 bM=me("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 Hde=me("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 Gde=me("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 Wde=me("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 Kde=me("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 Yde=me("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 Zde=me("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 Xde=me("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 Qde=me("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 Jde=me("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 eue=me("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 tue=me("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 _M=me("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 wM=me("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 sue=me("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 nue=me("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 rue=me("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 aue=me("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 iue=me("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 oue=me("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 lue=me("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 cue=me("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 due=me("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 uue=me("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 hue=me("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 mue=me("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 pue=me("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 fue=me("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 gue=me("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 xue=me("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 yue=me("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 vue=me("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 bue=me("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 _ue=me("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 wue=me("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 jue=me("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 Nue=me("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 jM=me("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 kue=me("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 n1=me("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 Sue=me("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 Cue=me("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 Aue=me("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 Eue=me("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 Tue=me("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 Mue=me("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 Pue=me("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 Lue=me("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 Iue=me("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 Rue=me("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 Due=me("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 fI=me("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 Oue=me("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 Fue=me("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 zue=me("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 NX=me("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 Bue=me("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 Uue=me("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 que=me("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 gI=me("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 xI=me("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 ag=me("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 $ue=me("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 kX=me("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 Vue=me("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 Aa=me("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 Hue=me("ArrowRightFromLine",[["path",{d:"M3 5v14",key:"1nt18q"}],["path",{d:"M21 12H7",key:"13ipq5"}],["path",{d:"m15 18 6-6-6-6",key:"6tx3qv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const S4=me("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 Gue=me("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 Oa=me("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 Wue=me("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 Kue=me("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 yI=me("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 xx=me("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 Yue=me("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 Zue=me("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 Xue=me("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 vI=me("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 bF=me("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 Que=me("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 Jue=me("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 bI=me("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 cp=me("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 ehe=me("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 the=me("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 she=me("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 nhe=me("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 rhe=me("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 ahe=me("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 Eh=me("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 ihe=me("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 _I=me("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 ohe=me("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 lhe=me("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 che=me("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 dhe=me("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 TC=me("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 uhe=me("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 hhe=me("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 mhe=me("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 phe=me("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 fhe=me("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 ghe=me("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 xhe=me("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 yhe=me("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 vhe=me("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 bhe=me("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 _he=me("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 whe=me("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 jhe=me("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 Nhe=me("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 khe=me("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 _F=me("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 She=me("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 Che=me("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 Ahe=me("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 Ehe=me("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 The=me("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 d0=me("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 Mhe=me("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 Phe=me("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 Lhe=me("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 Ihe=me("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 Rhe=me("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 Dhe=me("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 SX=me("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 Ohe=me("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 Fhe=me("Bean",[["path",{d:"M10.165 6.598C9.954 7.478 9.64 8.36 9 9c-.64.64-1.521.954-2.402 1.165A6 6 0 0 0 8 22c7.732 0 14-6.268 14-14a6 6 0 0 0-11.835-1.402Z",key:"1tvzk7"}],["path",{d:"M5.341 10.62a4 4 0 1 0 5.279-5.28",key:"2cyri2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const C4=me("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 zhe=me("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 Xw=me("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 Bhe=me("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 Uhe=me("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 qhe=me("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 $he=me("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 Vhe=me("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 Hhe=me("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 Zk=me("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 Ghe=me("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 A4=me("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 bx=me("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 wI=me("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 jI=me("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 Whe=me("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 Khe=me("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 Yhe=me("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 Zhe=me("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 Xhe=me("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 Qhe=me("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 Jhe=me("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 eme=me("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 tme=me("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 sme=me("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 nme=me("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 rme=me("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 ame=me("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 ime=me("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 ome=me("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 lme=me("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 wA=me("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 cme=me("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 dme=me("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 ume=me("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 hme=me("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 mme=me("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 pme=me("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 fme=me("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 NI=me("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 gme=me("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 xme=me("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 yme=me("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 vme=me("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 bme=me("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 _me=me("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 wme=me("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 jme=me("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 Nme=me("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 kme=me("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 ig=me("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 Sme=me("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 Cme=me("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 Ame=me("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 Eme=me("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 Tme=me("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 Mme=me("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 Pme=me("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 Lme=me("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 Ime=me("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 Rme=me("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 NM=me("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 Dme=me("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 u0=me("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 Ome=me("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 Fme=me("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 zme=me("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=me("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 CX=me("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 Bme=me("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 FT=me("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 Ume=me("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 qme=me("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 $me=me("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 AX=me("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 Vme=me("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 Hme=me("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 Gme=me("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 Wme=me("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 og=me("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 Kme=me("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 Yme=me("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 Zme=me("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 Xme=me("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 Qme=me("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 _i=me("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 wF=me("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 Jme=me("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 epe=me("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 tpe=me("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 spe=me("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 npe=me("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 lg=me("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 Qw=me("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 rpe=me("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 ape=me("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 ipe=me("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 ope=me("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 cv=me("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 ch=me("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 lpe=me("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 nc=me("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 cpe=me("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 Xk=me("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 dpe=me("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 upe=me("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 GU=me("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 hpe=me("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 sv=me("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 mpe=me("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 ppe=me("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 fpe=me("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 gpe=me("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 EX=me("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 pa=me("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 xpe=me("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 _x=me("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 ype=me("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 vpe=me("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 bpe=me("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 _pe=me("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 wpe=me("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 kI=me("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 jpe=me("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 Npe=me("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 kpe=me("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 Spe=me("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 Cpe=me("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 Ape=me("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 Epe=me("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 Tpe=me("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 Mpe=me("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 Ppe=me("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 Lpe=me("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 Ipe=me("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 Rpe=me("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 SI=me("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 CI=me("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 Dpe=me("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 Ope=me("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 Fpe=me("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 AI=me("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 EI=me("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 TI=me("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 zpe=me("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 MI=me("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 Bpe=me("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 Cl=me("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 Upe=me("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 PI=me("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 qpe=me("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 $pe=me("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 LI=me("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 II=me("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 Vpe=me("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 RI=me("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 DI=me("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 OI=me("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 Hpe=me("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 jF=me("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 Xr=me("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 Gpe=me("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 Wpe=me("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 rl=me("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 Kpe=me("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 Ype=me("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 rd=me("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 gi=me("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 dv=me("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 Zpe=me("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 Xpe=me("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 Qpe=me("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 Jpe=me("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 efe=me("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 tfe=me("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 sfe=me("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 Jw=me("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 nfe=me("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 NF=me("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 rfe=me("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 afe=me("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 ife=me("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 Vo=me("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 FI=me("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 zI=me("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 BI=me("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 UI=me("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 qI=me("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 $I=me("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 VI=me("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 HI=me("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 Yo=me("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 zr=me("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 GI=me("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 WI=me("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 KI=me("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 YI=me("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 ofe=me("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 ZI=me("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 lfe=me("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 cfe=me("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 dfe=me("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 ufe=me("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 hfe=me("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 mfe=me("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 pfe=me("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 XI=me("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 MC=me("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 QI=me("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 ffe=me("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 JI=me("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 e8=me("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 t8=me("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 s8=me("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 $h=me("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 n8=me("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 r8=me("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 a8=me("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 gfe=me("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 i8=me("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 o8=me("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 l8=me("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 ou=me("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 Nf=me("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 xfe=me("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 yfe=me("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 WU=me("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 T4=me("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 vfe=me("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 iy=me("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 bfe=me("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 _fe=me("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 c8=me("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 d8=me("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 wfe=me("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 jfe=me("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 Nfe=me("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 kfe=me("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 Sfe=me("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 Cfe=me("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 Afe=me("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 Efe=me("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 Tfe=me("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 Mfe=me("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 Pfe=me("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 Lfe=me("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 Ife=me("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 Rfe=me("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 Dfe=me("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 Ofe=me("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 Ffe=me("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 zfe=me("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 Bfe=me("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 Yr=me("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 Ufe=me("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 qfe=me("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 u8=me("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 $fe=me("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 Vfe=me("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 Hfe=me("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 Gfe=me("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 Wfe=me("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 Kfe=me("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 Yfe=me("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 Zfe=me("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 Xfe=me("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 Qfe=me("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 Jfe=me("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 ege=me("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 h8=me("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 tge=me("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 sge=me("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 pA=me("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 nge=me("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 PC=me("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 jA=me("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 rge=me("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 age=me("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 M4=me("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 ige=me("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 TX=me("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 m8=me("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 zT=me("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 oge=me("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 lge=me("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 cge=me("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 kF=me("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 dge=me("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 uge=me("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 hge=me("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 mge=me("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 pge=me("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 p8=me("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 SF=me("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 fge=me("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 gge=me("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 xge=me("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 yge=me("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 vge=me("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 bge=me("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 _ge=me("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 wge=me("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 jge=me("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 Pa=me("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 Nge=me("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 kge=me("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 Sge=me("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 MX=me("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 Cge=me("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 Age=me("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 Ege=me("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 Tge=me("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 Mge=me("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 Pge=me("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 Lge=me("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 Ige=me("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 oy=me("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 Rge=me("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 Dge=me("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 Oge=me("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 Fge=me("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 h0=me("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 zge=me("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 Bge=me("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 Uge=me("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 qge=me("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 $ge=me("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 Vge=me("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 Hge=me("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 PX=me("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 Gge=me("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 Wge=me("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 Kge=me("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 Yge=me("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 f8=me("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 Zge=me("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 Xge=me("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 Qge=me("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 Jge=me("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 exe=me("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 txe=me("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 sxe=me("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 nxe=me("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 rxe=me("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 axe=me("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 ixe=me("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 oxe=me("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 lxe=me("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 cxe=me("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 dxe=me("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 uxe=me("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 hxe=me("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 mxe=me("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 pxe=me("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 yu=me("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 fxe=me("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 gxe=me("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 G2=me("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 xxe=me("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 pi=me("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 yxe=me("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 vxe=me("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 bxe=me("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 _xe=me("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 wxe=me("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 cb=me("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 jxe=me("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 Nxe=me("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 kxe=me("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 Sxe=me("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 Cxe=me("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 Axe=me("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 Ok=me("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 Exe=me("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 Txe=me("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 Mxe=me("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 KU=me("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 ey=me("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 Z1=me("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 Pxe=me("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 Lxe=me("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 Ixe=me("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 LX=me("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 Rxe=me("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 Dxe=me("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 Oxe=me("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 Sr=me("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 Fxe=me("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 Vg=me("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 xa=me("Eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zp=me("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 zxe=me("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 Bxe=me("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 Uxe=me("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 qxe=me("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 $xe=me("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 Vxe=me("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 Hxe=me("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 Gxe=me("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 Wxe=me("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 Kxe=me("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 g8=me("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 Yxe=me("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 Zxe=me("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 Xxe=me("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 x8=me("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 y8=me("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 v8=me("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 b8=me("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 IX=me("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 RX=me("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 Qxe=me("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 Jxe=me("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 e0e=me("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 _8=me("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 t0e=me("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 s0e=me("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 W2=me("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 n0e=me("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 kM=me("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 r0e=me("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 a0e=me("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 i0e=me("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 o0e=me("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 l0e=me("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 c0e=me("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 d0e=me("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 u0e=me("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 h0e=me("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 m0e=me("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 p0e=me("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 Iw=me("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 w8=me("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 YU=me("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 f0e=me("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 g0e=me("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 x0e=me("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 y0e=me("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 DX=me("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 v0e=me("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 Qk=me("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 OX=me("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 b0e=me("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 _0e=me("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 Ur=me("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 w0e=me("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 j0e=me("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 N0e=me("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 k0e=me("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 S0e=me("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 FX=me("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 C0e=me("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 A0e=me("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 E0e=me("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 T0e=me("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 M0e=me("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 ZU=me("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 P0e=me("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 Gh=me("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 L0e=me("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 K2=me("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 I0e=me("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 R0e=me("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 D0e=me("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 O0e=me("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 F0e=me("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 z0e=me("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 B0e=me("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 U0e=me("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 NA=me("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 q0e=me("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 Xd=me("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 $0e=me("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 V0e=me("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 H0e=me("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 SM=me("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 G0e=me("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 W0e=me("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 zX=me("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 K0e=me("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 Y0e=me("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 Hk=me("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 Z0e=me("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 X0e=me("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 Q0e=me("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 J0e=me("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 eye=me("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 tye=me("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 sye=me("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 nye=me("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 rye=me("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 j8=me("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 aye=me("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 iye=me("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 oye=me("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 lye=me("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 cye=me("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 dye=me("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 uye=me("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 hye=me("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 mye=me("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 pye=me("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 fye=me("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 r1=me("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 gye=me("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 N8=me("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 xye=me("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 yye=me("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 vye=me("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 bye=me("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 _ye=me("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 wye=me("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 jye=me("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 Nye=me("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 kye=me("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 Sye=me("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 Cye=me("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 Aye=me("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 Eye=me("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 Tye=me("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 Mye=me("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 Pye=me("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 Lye=me("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 Iye=me("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 Rye=me("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 Dye=me("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 Oye=me("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 Fye=me("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 zye=me("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 Bye=me("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 Uye=me("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 qye=me("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 $ye=me("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 Vye=me("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 Hye=me("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 CF=me("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 Ro=me("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 Gye=me("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 Wye=me("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 k8=me("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 Kye=me("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 Yye=me("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 Zye=me("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 Xye=me("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 Qye=me("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 Jye=me("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 eve=me("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 tve=me("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 sve=me("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 nve=me("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 rve=me("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 ave=me("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 ive=me("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 ove=me("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 lve=me("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 cve=me("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 dve=me("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 fl=me("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 uve=me("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 hve=me("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 Kh=me("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 mve=me("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 pve=me("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 S8=me("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 fve=me("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 C8=me("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 Aw=me("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 gve=me("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 kf=me("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 xve=me("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 yve=me("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 vve=me("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 bve=me("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 BX=me("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 _ve=me("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 UX=me("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 e4=me("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 wve=me("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 jve=me("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 XU=me("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 a1=me("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 Nve=me("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 kve=me("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 qX=me("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 Sve=me("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 CM=me("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 Cve=me("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 Ave=me("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 QU=me("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 AF=me("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 JU=me("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 Eve=me("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 Tve=me("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 Mve=me("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 Pve=me("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 Lve=me("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 Ive=me("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 Rve=me("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 Dve=me("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 $X=me("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 Ove=me("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 Fve=me("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 ko=me("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 zve=me("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 Bve=me("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 Uve=me("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 Y2=me("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 qve=me("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 $ve=me("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 Vve=me("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 Hve=me("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 VX=me("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 Gve=me("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 Wve=me("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 ra=me("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 A8=me("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 E8=me("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 Kve=me("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 Yve=me("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 Zve=me("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 Xve=me("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 Qve=me("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 ly=me("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 Jve=me("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 e1e=me("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 pc=me("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 t1e=me("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 s1e=me("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 AM=me("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 T8=me("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 M8=me("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 n1e=me("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 eq=me("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 Jk=me("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 r1e=me("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 gm=me("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 kA=me("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 a1e=me("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 i1e=me("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 o1e=me("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 l1e=me("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 P4=me("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 SA=me("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 c1e=me("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 C_=me("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 d1e=me("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 u1e=me("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 h1e=me("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 m1e=me("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 p1e=me("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 f1e=me("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 g1e=me("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 x1e=me("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 y1e=me("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 v1e=me("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 tq=me("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 b1e=me("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 _1e=me("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 P8=me("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 w1e=me("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 j1e=me("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 N1e=me("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 k1e=me("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 S1e=me("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 C1e=me("Layers3",[["path",{d:"m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z",key:"8b97xw"}],["path",{d:"m6.08 9.5-3.5 1.6a1 1 0 0 0 0 1.81l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9a1 1 0 0 0 0-1.83l-3.5-1.59",key:"1e5n1m"}],["path",{d:"m6.08 14.5-3.5 1.6a1 1 0 0 0 0 1.81l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9a1 1 0 0 0 0-1.83l-3.5-1.59",key:"1iwflc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const L4=me("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 EF=me("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 Hg=me("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 A1e=me("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 E1e=me("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 T1e=me("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 ej=me("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 M1e=me("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 P1e=me("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 L1e=me("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 I1e=me("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 R1e=me("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 tj=me("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 sq=me("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 D1e=me("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 O1e=me("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 eS=me("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 F1e=me("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 ad=me("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 Rc=me("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 Gg=me("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 z1e=me("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 cy=me("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 B1e=me("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 U1e=me("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 HX=me("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 q1e=me("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 $1e=me("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 sj=me("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 V1e=me("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 H1e=me("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 G1e=me("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 W1e=me("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 K1e=me("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 Y1e=me("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 Z1e=me("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 m0=me("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 Et=me("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 X1e=me("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 Q1e=me("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 J1e=me("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 ebe=me("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 nq=me("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 L8=me("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 tbe=me("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 I8=me("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 Ql=me("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 EM=me("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 TF=me("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 sbe=me("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 nbe=me("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 rbe=me("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 abe=me("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 rq=me("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 ibe=me("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 GX=me("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 WX=me("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 obe=me("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 lbe=me("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 cbe=me("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 TM=me("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 ln=me("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 dbe=me("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 ube=me("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 hbe=me("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 mbe=me("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 pbe=me("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 fbe=me("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 gbe=me("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 xbe=me("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 ybe=me("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 vbe=me("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 bbe=me("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 _be=me("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 ni=me("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 wbe=me("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 MF=me("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 jbe=me("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 KX=me("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 PF=me("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 CA=me("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 Nbe=me("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 Th=me("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 kbe=me("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 Sbe=me("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 AA=me("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 Cbe=me("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 Abe=me("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 Ebe=me("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 aq=me("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 Tbe=me("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 Mbe=me("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 Pbe=me("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 YX=me("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 Lbe=me("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 Ibe=me("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 Rbe=me("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 vu=me("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 Dbe=me("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 Obe=me("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 Fbe=me("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 zbe=me("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 Bbe=me("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 Ube=me("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 ZX=me("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 qbe=me("MessageSquareOff",[["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M3.6 3.6c-.4.3-.6.8-.6 1.4v16l4-4h10",key:"pwpm4a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const p4=me("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 EA=me("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 XX=me("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 $be=me("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 Vbe=me("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 Hbe=me("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 Gbe=me("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 Ki=me("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 QX=me("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 Wbe=me("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 R8=me("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 LF=me("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 Kbe=me("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 Ybe=me("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 Zbe=me("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 Xbe=me("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 Qbe=me("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 Jbe=me("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 e_e=me("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 t_e=me("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 Z2=me("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 s_e=me("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 n_e=me("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 r_e=me("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 a_e=me("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 i_e=me("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 o_e=me("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 iq=me("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 l_e=me("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 c_e=me("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 d_e=me("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 IF=me("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 u_e=me("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 X2=me("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 h_e=me("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 m_e=me("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 p_e=me("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 f_e=me("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 g_e=me("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 JX=me("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 x_e=me("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 Ch=me("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 n0=me("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 y_e=me("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 D8=me("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 v_e=me("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 b_e=me("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 __e=me("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 w_e=me("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 j_e=me("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 N_e=me("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 k_e=me("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 S_e=me("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 C_e=me("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 A_e=me("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 E_e=me("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 T_e=me("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 eQ=me("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 M_e=me("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 P_e=me("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 L_e=me("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 oq=me("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 I_e=me("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 R_e=me("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 D_e=me("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 tQ=me("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 O_e=me("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 Q2=me("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 F_e=me("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 z_e=me("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 B_e=me("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 U_e=me("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 q_e=me("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 $_e=me("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 V_e=me("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 H_e=me("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 G_e=me("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 Fk=me("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 W_e=me("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 O8=me("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 F8=me("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 K_e=me("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 Y_e=me("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 Z_e=me("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 X_e=me("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 Q_e=me("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 J_e=me("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 ewe=me("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 twe=me("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 swe=me("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 nwe=me("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 rwe=me("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 awe=me("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 dh=me("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 iwe=me("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 owe=me("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 z8=me("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 lwe=me("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 $c=me("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 cwe=me("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 B8=me("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 dwe=me("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 uwe=me("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 U8=me("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 q8=me("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 $8=me("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 V8=me("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 hwe=me("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 H8=me("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 mwe=me("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 pwe=me("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 fwe=me("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 G8=me("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 gwe=me("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 xwe=me("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 ywe=me("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 vwe=me("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 LC=me("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 MM=me("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 bwe=me("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 _we=me("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 Wg=me("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 uv=me("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 wwe=me("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 jwe=me("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 Pg=me("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 Nwe=me("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 TA=me("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 C2=me("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 lq=me("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 kwe=me("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 Swe=me("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 ri=me("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 Cwe=me("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 PM=me("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 Awe=me("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 Ewe=me("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 sQ=me("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 Twe=me("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 Mwe=me("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 Pwe=me("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 Lwe=me("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 Iwe=me("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 ba=me("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 Rwe=me("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 Dwe=me("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 Owe=me("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 Fwe=me("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 zwe=me("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 Bwe=me("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 Uwe=me("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 qwe=me("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 $we=me("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 Vwe=me("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 Hwe=me("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 nQ=me("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 MA=me("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 Gwe=me("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 Wwe=me("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 Kwe=me("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 Ywe=me("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 rQ=me("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 lu=me("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 Zwe=me("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 W8=me("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 J2=me("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 an=me("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 Xwe=me("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 Qwe=me("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 Jwe=me("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 eje=me("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 tje=me("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 sje=me("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 nje=me("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 rje=me("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 aje=me("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 aQ=me("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 hv=me("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 ije=me("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 PA=me("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 oje=me("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 lje=me("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 cje=me("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 dje=me("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 Sf=me("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 tS=me("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 uje=me("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 cq=me("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 hje=me("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 mje=me("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 pje=me("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 fje=me("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 mv=me("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 gje=me("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 xje=me("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 yje=me("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 vje=me("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 bje=me("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 _je=me("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 wje=me("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 jje=me("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 Nje=me("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 kje=me("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 Sje=me("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 Cje=me("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 Aje=me("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 Eje=me("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 K8=me("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 Tje=me("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 Mje=me("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 Pje=me("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 Lje=me("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 Ije=me("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 LA=me("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 Rje=me("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 dq=me("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 Dje=me("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 no=me("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 Oje=me("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 Fje=me("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 zje=me("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 Bje=me("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 iQ=me("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 IA=me("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 Uje=me("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 qje=me("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 $je=me("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 uq=me("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 Vje=me("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 Hje=me("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 pv=me("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 Gje=me("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 Wje=me("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 Y8=me("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 Kje=me("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 Kg=me("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 Yje=me("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 RF=me("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 Zje=me("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 hq=me("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 Xje=me("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 Z8=me("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 X8=me("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 Qje=me("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 Jje=me("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 I4=me("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 e2e=me("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 t2e=me("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 s2e=me("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 n2e=me("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 r2e=me("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 a2e=me("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 i2e=me("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 o2e=me("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 Ho=me("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 Q8=me("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 l2e=me("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 c2e=me("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 d2e=me("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 u2e=me("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 h2e=me("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 m2e=me("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 p2e=me("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 f2e=me("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 g2e=me("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 x2e=me("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 y2e=me("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 v2e=me("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 b2e=me("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 _2e=me("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 w2e=me("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 mq=me("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 j2e=me("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 N2e=me("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 k2e=me("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 S2e=me("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 pq=me("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 Fr=me("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 C2e=me("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 J8=me("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 A2e=me("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 $r=me("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 E2e=me("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 T2e=me("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 M2e=me("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 P2e=me("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 L2e=me("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 I2e=me("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 R4=me("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 qc=me("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 R2e=me("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 jd=me("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 oQ=me("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 D2e=me("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 O2e=me("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 fq=me("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 F2e=me("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 cg=me("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 z2e=me("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 B2e=me("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 U2e=me("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 DF=me("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 q2e=me("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 OF=me("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 eR=me("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 Im=me("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 $2e=me("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 V2e=me("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 H2e=me("Shirt",[["path",{d:"M20.38 3.46 16 2a4 4 0 0 1-8 0L3.62 3.46a2 2 0 0 0-1.34 2.23l.58 3.47a1 1 0 0 0 .99.84H6v10c0 1.1.9 2 2 2h8a2 2 0 0 0 2-2V10h2.15a1 1 0 0 0 .99-.84l.58-3.47a2 2 0 0 0-1.34-2.23z",key:"1wgbhj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const D4=me("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 G2e=me("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 sS=me("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 W2e=me("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 K2e=me("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 Y2e=me("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 Z2e=me("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 FF=me("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 X2e=me("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 Q2e=me("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 J2e=me("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 eNe=me("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 tNe=me("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 sNe=me("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 nNe=me("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 rNe=me("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 aNe=me("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 iNe=me("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 oNe=me("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 lQ=me("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 lNe=me("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 cNe=me("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 dNe=me("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 uNe=me("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 LM=me("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 tR=me("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 hNe=me("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 mNe=me("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 i1=me("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 pNe=me("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 fNe=me("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 gNe=me("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 $w=me("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 gq=me("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 xNe=me("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 yNe=me("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 vNe=me("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 IM=me("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 cn=me("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 bNe=me("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 _Ne=me("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 wNe=me("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 jNe=me("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 NNe=me("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 kNe=me("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 SNe=me("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 RM=me("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 sR=me("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 nR=me("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 rR=me("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 aR=me("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 iR=me("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 oR=me("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 lR=me("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 cR=me("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 dR=me("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 uR=me("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 hR=me("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 mR=me("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 pR=me("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 fR=me("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 gR=me("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 v5=me("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 t4=me("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 xR=me("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 yR=me("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 vR=me("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 bR=me("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 _R=me("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 wR=me("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 CNe=me("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 ANe=me("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 jR=me("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 NR=me("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 kR=me("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 SR=me("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 CR=me("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 AR=me("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 ER=me("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 TR=me("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 MR=me("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 PR=me("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 LR=me("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 IR=me("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 RR=me("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 DR=me("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 OR=me("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 sp=me("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 FR=me("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 zR=me("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 BR=me("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 UR=me("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 qR=me("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 $R=me("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 ENe=me("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 VR=me("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 HR=me("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 GR=me("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 WR=me("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 KR=me("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 TNe=me("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 MNe=me("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 YR=me("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 ZR=me("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 XR=me("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 QR=me("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 db=me("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 PNe=me("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 LNe=me("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 INe=me("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 RNe=me("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 DNe=me("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 Ua=me("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 ONe=me("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 FNe=me("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 zNe=me("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 BNe=me("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 zF=me("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 xq=me("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 UNe=me("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 qNe=me("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 cQ=me("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 $Ne=me("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 VNe=me("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 HNe=me("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 GNe=me("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 WNe=me("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 eN=me("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 KNe=me("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 YNe=me("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 ZNe=me("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 XNe=me("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 QNe=me("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 JNe=me("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 eke=me("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 tke=me("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 ske=me("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 yq=me("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 nke=me("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 rke=me("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 ake=me("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 ike=me("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 oke=me("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 lke=me("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 vq=me("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 cke=me("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 bq=me("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 dke=me("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 Cf=me("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 dQ=me("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 uke=me("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 hke=me("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 mke=me("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 pke=me("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 fke=me("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 gke=me("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 Gu=me("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 xke=me("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 yke=me("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 vke=me("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 bke=me("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 JR=me("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 _ke=me("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 wke=me("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 _q=me("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 jke=me("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 Nke=me("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 kke=me("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 eD=me("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 Ske=me("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 Cke=me("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 Ake=me("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 Eke=me("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 Tke=me("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 uQ=me("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 wx=me("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 Mke=me("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 Pke=me("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 Lke=me("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 Ike=me("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 Rke=me("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 Dke=me("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 BF=me("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 Oke=me("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 Fke=me("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 zke=me("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 Bke=me("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 Uke=me("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 qke=me("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 $ke=me("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 Vke=me("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 Hke=me("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 Gke=me("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 Wke=me("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 Kke=me("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 Yke=me("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 Zke=me("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 Xke=me("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 Qke=me("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 Jke=me("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 eSe=me("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 tSe=me("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 tD=me("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 In=me("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 sSe=me("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 nSe=me("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 sD=me("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 DM=me("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 rSe=me("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 aSe=me("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 nS=me("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 iSe=me("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 rc=me("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 tc=me("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 oSe=me("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 lSe=me("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 Al=me("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 hQ=me("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 cSe=me("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 dSe=me("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 nD=me("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 uSe=me("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 hSe=me("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 mQ=me("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 mSe=me("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 wq=me("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 pSe=me("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 fSe=me("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 UF=me("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 pQ=me("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 gSe=me("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 RA=me("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 xSe=me("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 ySe=me("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 vSe=me("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 rD=me("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 bSe=me("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 qF=me("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 jq=me("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 qa=me("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 _Se=me("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 tN=me("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 fQ=me("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 Nq=me("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 wSe=me("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 zl=me("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 aD=me("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 iD=me("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 oD=me("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 jSe=me("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 lD=me("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 NSe=me("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 cD=me("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 dD=me("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 kSe=me("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 SSe=me("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 So=me("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 zk=me("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 Bn=me("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 uD=me("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 hD=me("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 CSe=me("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 kq=me("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 ASe=me("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 ESe=me("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 TSe=me("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 MSe=me("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 PSe=me("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 LSe=me("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 Wr=me("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 ISe=me("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 RSe=me("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 DSe=me("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 OSe=me("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 FSe=me("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 gQ=me("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 zSe=me("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 xQ=me("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 BSe=me("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 USe=me("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 qSe=me("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 mD=me("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 yQ=me("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 $Se=me("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 Lg=me("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 VSe=me("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 HSe=me("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 GSe=me("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 WSe=me("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 KSe=me("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 YSe=me("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 ZSe=me("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 XSe=me("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 QSe=me("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 JSe=me("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 e5e=me("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 t5e=me("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 s5e=me("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 n5e=me("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 r5e=me("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 a5e=me("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 i5e=me("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 o5e=me("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 l5e=me("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 c5e=me("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 d5e=me("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 u5e=me("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 $F=me("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 h5e=me("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 m5e=me("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 O4=me("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 er=me("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 Sq=me("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 p5e=me("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 Af=me("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 OM=me("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 Cq=me("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 rms=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:Lde,AArrowUp:Ide,ALargeSmall:Rde,Accessibility:Dde,Activity:Lm,AirVent:Ode,Airplay:Fde,AlarmClock:Bde,AlarmClockCheck:hI,AlarmClockMinus:mI,AlarmClockOff:zde,AlarmClockPlus:pI,AlarmSmoke:Ude,Album:qde,AlignCenter:bM,AlignCenterHorizontal:$de,AlignCenterVertical:Vde,AlignEndHorizontal:Hde,AlignEndVertical:Gde,AlignHorizontalDistributeCenter:Wde,AlignHorizontalDistributeEnd:Kde,AlignHorizontalDistributeStart:Yde,AlignHorizontalJustifyCenter:Zde,AlignHorizontalJustifyEnd:Xde,AlignHorizontalJustifyStart:Qde,AlignHorizontalSpaceAround:Jde,AlignHorizontalSpaceBetween:eue,AlignJustify:tue,AlignLeft:_M,AlignRight:wM,AlignStartHorizontal:sue,AlignStartVertical:nue,AlignVerticalDistributeCenter:rue,AlignVerticalDistributeEnd:aue,AlignVerticalDistributeStart:iue,AlignVerticalJustifyCenter:oue,AlignVerticalJustifyEnd:lue,AlignVerticalJustifyStart:cue,AlignVerticalSpaceAround:due,AlignVerticalSpaceBetween:uue,Ambulance:hue,Ampersand:mue,Ampersands:pue,Amphora:fue,Anchor:gue,Angry:xue,Annoyed:yue,Antenna:vue,Anvil:bue,Aperture:_ue,AppWindow:jue,AppWindowMac:wue,Apple:Nue,Archive:n1,ArchiveRestore:jM,ArchiveX:kue,Armchair:Sue,ArrowBigDown:Aue,ArrowBigDownDash:Cue,ArrowBigLeft:Tue,ArrowBigLeftDash:Eue,ArrowBigRight:Pue,ArrowBigRightDash:Mue,ArrowBigUp:Iue,ArrowBigUpDash:Lue,ArrowDown:ag,ArrowDown01:Rue,ArrowDown10:Due,ArrowDownAZ:fI,ArrowDownFromLine:Oue,ArrowDownLeft:Fue,ArrowDownNarrowWide:zue,ArrowDownRight:NX,ArrowDownToDot:Bue,ArrowDownToLine:Uue,ArrowDownUp:que,ArrowDownWideNarrow:gI,ArrowDownZA:xI,ArrowLeft:Aa,ArrowLeftFromLine:$ue,ArrowLeftRight:kX,ArrowLeftToLine:Vue,ArrowRight:Oa,ArrowRightFromLine:Hue,ArrowRightLeft:S4,ArrowRightToLine:Gue,ArrowUp:cp,ArrowUp01:Wue,ArrowUp10:Kue,ArrowUpAZ:yI,ArrowUpDown:xx,ArrowUpFromDot:Yue,ArrowUpFromLine:Zue,ArrowUpLeft:Xue,ArrowUpNarrowWide:vI,ArrowUpRight:bF,ArrowUpToLine:Que,ArrowUpWideNarrow:Jue,ArrowUpZA:bI,ArrowsUpFromLine:ehe,Asterisk:the,AtSign:she,Atom:nhe,AudioLines:rhe,AudioWaveform:ahe,Award:Eh,Axe:ihe,Axis3d:_I,Baby:ohe,Backpack:lhe,Badge:Nhe,BadgeAlert:che,BadgeCent:dhe,BadgeCheck:TC,BadgeDollarSign:uhe,BadgeEuro:hhe,BadgeHelp:mhe,BadgeIndianRupee:phe,BadgeInfo:fhe,BadgeJapaneseYen:ghe,BadgeMinus:xhe,BadgePercent:yhe,BadgePlus:vhe,BadgePoundSterling:bhe,BadgeRussianRuble:_he,BadgeSwissFranc:whe,BadgeX:jhe,BaggageClaim:khe,Ban:_F,Banana:She,Bandage:Che,Banknote:Ahe,Barcode:Ehe,Baseline:The,Bath:d0,Battery:Dhe,BatteryCharging:Mhe,BatteryFull:Phe,BatteryLow:Lhe,BatteryMedium:Ihe,BatteryWarning:Rhe,Beaker:SX,Bean:Fhe,BeanOff:Ohe,Bed:Xw,BedDouble:C4,BedSingle:zhe,Beef:Bhe,Beer:qhe,BeerOff:Uhe,Bell:bx,BellDot:$he,BellElectric:Vhe,BellMinus:Hhe,BellOff:Zk,BellPlus:Ghe,BellRing:A4,BetweenHorizontalEnd:wI,BetweenHorizontalStart:jI,BetweenVerticalEnd:Whe,BetweenVerticalStart:Khe,BicepsFlexed:Yhe,Bike:Zhe,Binary:Xhe,Binoculars:Qhe,Biohazard:Jhe,Bird:eme,Bitcoin:tme,Blend:sme,Blinds:nme,Blocks:rme,Bluetooth:lme,BluetoothConnected:ame,BluetoothOff:ime,BluetoothSearching:ome,Bold:wA,Bolt:cme,Bomb:dme,Bone:ume,Book:Lme,BookA:hme,BookAudio:mme,BookCheck:pme,BookCopy:fme,BookDashed:NI,BookDown:gme,BookHeadphones:xme,BookHeart:yme,BookImage:vme,BookKey:bme,BookLock:_me,BookMarked:wme,BookMinus:jme,BookOpen:ig,BookOpenCheck:Nme,BookOpenText:kme,BookPlus:Sme,BookText:Cme,BookType:Ame,BookUp:Tme,BookUp2:Eme,BookUser:Mme,BookX:Pme,Bookmark:u0,BookmarkCheck:Ime,BookmarkMinus:Rme,BookmarkPlus:NM,BookmarkX:Dme,BoomBox:Ome,Bot:E4,BotMessageSquare:Fme,BotOff:zme,Box:CX,Boxes:Bme,Braces:FT,Brackets:Ume,Brain:AX,BrainCircuit:qme,BrainCog:$me,BrickWall:Vme,Briefcase:og,BriefcaseBusiness:Hme,BriefcaseConveyorBelt:Gme,BriefcaseMedical:Wme,BringToFront:Kme,Brush:Yme,Bug:Qme,BugOff:Zme,BugPlay:Xme,Building:wF,Building2:_i,Bus:epe,BusFront:Jme,Cable:spe,CableCar:tpe,Cake:lg,CakeSlice:npe,Calculator:Qw,Calendar:pa,Calendar1:rpe,CalendarArrowDown:ape,CalendarArrowUp:ipe,CalendarCheck:cv,CalendarCheck2:ope,CalendarClock:ch,CalendarCog:lpe,CalendarDays:nc,CalendarFold:cpe,CalendarHeart:Xk,CalendarMinus:upe,CalendarMinus2:dpe,CalendarOff:GU,CalendarPlus:sv,CalendarPlus2:hpe,CalendarRange:mpe,CalendarSearch:ppe,CalendarSync:fpe,CalendarX:EX,CalendarX2:gpe,Camera:_x,CameraOff:xpe,Candy:bpe,CandyCane:ype,CandyOff:vpe,Cannabis:_pe,Captions:kI,CaptionsOff:wpe,Car:kpe,CarFront:jpe,CarTaxiFront:Npe,Caravan:Spe,Carrot:Cpe,CaseLower:Ape,CaseSensitive:Epe,CaseUpper:Tpe,CassetteTape:Mpe,Cast:Ppe,Castle:Lpe,Cat:Ipe,Cctv:Rpe,ChartArea:SI,ChartBar:AI,ChartBarBig:CI,ChartBarDecreasing:Dpe,ChartBarIncreasing:Ope,ChartBarStacked:Fpe,ChartCandlestick:EI,ChartColumn:Cl,ChartColumnBig:TI,ChartColumnDecreasing:zpe,ChartColumnIncreasing:MI,ChartColumnStacked:Bpe,ChartGantt:Upe,ChartLine:PI,ChartNetwork:qpe,ChartNoAxesColumn:II,ChartNoAxesColumnDecreasing:$pe,ChartNoAxesColumnIncreasing:LI,ChartNoAxesCombined:Vpe,ChartNoAxesGantt:RI,ChartPie:DI,ChartScatter:OI,ChartSpline:Hpe,Check:Xr,CheckCheck:jF,ChefHat:Gpe,Cherry:Wpe,ChevronDown:rl,ChevronFirst:Kpe,ChevronLast:Ype,ChevronLeft:rd,ChevronRight:gi,ChevronUp:dv,ChevronsDown:Xpe,ChevronsDownUp:Zpe,ChevronsLeft:efe,ChevronsLeftRight:Jpe,ChevronsLeftRightEllipsis:Qpe,ChevronsRight:sfe,ChevronsRightLeft:tfe,ChevronsUp:nfe,ChevronsUpDown:Jw,Chrome:NF,Church:rfe,Cigarette:ife,CigaretteOff:afe,Circle:Nf,CircleAlert:Vo,CircleArrowDown:FI,CircleArrowLeft:zI,CircleArrowOutDownLeft:BI,CircleArrowOutDownRight:UI,CircleArrowOutUpLeft:qI,CircleArrowOutUpRight:$I,CircleArrowRight:VI,CircleArrowUp:HI,CircleCheck:zr,CircleCheckBig:Yo,CircleChevronDown:GI,CircleChevronLeft:WI,CircleChevronRight:KI,CircleChevronUp:YI,CircleDashed:ofe,CircleDivide:ZI,CircleDollarSign:lfe,CircleDot:dfe,CircleDotDashed:cfe,CircleEllipsis:ufe,CircleEqual:hfe,CircleFadingArrowUp:mfe,CircleFadingPlus:pfe,CircleGauge:XI,CircleHelp:MC,CircleMinus:QI,CircleOff:ffe,CircleParking:e8,CircleParkingOff:JI,CirclePause:t8,CirclePercent:s8,CirclePlay:$h,CirclePlus:n8,CirclePower:r8,CircleSlash:gfe,CircleSlash2:a8,CircleStop:i8,CircleUser:l8,CircleUserRound:o8,CircleX:ou,CircuitBoard:xfe,Citrus:yfe,Clapperboard:WU,Clipboard:kfe,ClipboardCheck:T4,ClipboardCopy:vfe,ClipboardList:iy,ClipboardMinus:bfe,ClipboardPaste:_fe,ClipboardPen:d8,ClipboardPenLine:c8,ClipboardPlus:wfe,ClipboardType:jfe,ClipboardX:Nfe,Clock:Yr,Clock1:Sfe,Clock10:Cfe,Clock11:Afe,Clock12:Efe,Clock2:Tfe,Clock3:Mfe,Clock4:Pfe,Clock5:Lfe,Clock6:Ife,Clock7:Rfe,Clock8:Dfe,Clock9:Ofe,ClockAlert:Ffe,ClockArrowDown:zfe,ClockArrowUp:Bfe,Cloud:tge,CloudAlert:Ufe,CloudCog:qfe,CloudDownload:u8,CloudDrizzle:$fe,CloudFog:Vfe,CloudHail:Hfe,CloudLightning:Gfe,CloudMoon:Kfe,CloudMoonRain:Wfe,CloudOff:Yfe,CloudRain:Xfe,CloudRainWind:Zfe,CloudSnow:Qfe,CloudSun:ege,CloudSunRain:Jfe,CloudUpload:h8,Cloudy:sge,Clover:pA,Club:nge,Code:jA,CodeXml:PC,Codepen:rge,Codesandbox:age,Coffee:M4,Cog:ige,Coins:TX,Columns2:m8,Columns3:zT,Columns4:oge,Combine:lge,Command:cge,Compass:kF,Component:dge,Computer:uge,ConciergeBell:hge,Cone:mge,Construction:pge,Contact:SF,ContactRound:p8,Container:fge,Contrast:gge,Cookie:xge,CookingPot:yge,Copy:Pa,CopyCheck:vge,CopyMinus:bge,CopyPlus:_ge,CopySlash:wge,CopyX:jge,Copyleft:Nge,Copyright:kge,CornerDownLeft:Sge,CornerDownRight:MX,CornerLeftDown:Cge,CornerLeftUp:Age,CornerRightDown:Ege,CornerRightUp:Tge,CornerUpLeft:Mge,CornerUpRight:Pge,Cpu:Lge,CreativeCommons:Ige,CreditCard:oy,Croissant:Rge,Crop:Dge,Cross:Oge,Crosshair:Fge,Crown:h0,Cuboid:zge,CupSoda:Bge,Currency:Uge,Cylinder:qge,Dam:$ge,Database:PX,DatabaseBackup:Vge,DatabaseZap:Hge,Delete:Gge,Dessert:Wge,Diameter:Kge,Diamond:Xge,DiamondMinus:Yge,DiamondPercent:f8,DiamondPlus:Zge,Dice1:Qge,Dice2:Jge,Dice3:exe,Dice4:txe,Dice5:sxe,Dice6:nxe,Dices:rxe,Diff:axe,Disc:cxe,Disc2:ixe,Disc3:oxe,DiscAlbum:lxe,Divide:dxe,Dna:hxe,DnaOff:uxe,Dock:mxe,Dog:pxe,DollarSign:yu,Donut:fxe,DoorClosed:gxe,DoorOpen:G2,Dot:xxe,Download:pi,DraftingCompass:yxe,Drama:vxe,Dribbble:bxe,Drill:_xe,Droplet:wxe,Droplets:cb,Drum:jxe,Drumstick:Nxe,Dumbbell:kxe,Ear:Cxe,EarOff:Sxe,Earth:Ok,EarthLock:Axe,Eclipse:Exe,Egg:KU,EggFried:Txe,EggOff:Mxe,Ellipsis:Z1,EllipsisVertical:ey,Equal:Ixe,EqualApproximately:Pxe,EqualNot:Lxe,Eraser:LX,EthernetPort:Rxe,Euro:Dxe,Expand:Oxe,ExternalLink:Sr,Eye:xa,EyeClosed:Fxe,EyeOff:Vg,Facebook:zp,Factory:zxe,Fan:Bxe,FastForward:Uxe,Feather:qxe,Fence:$xe,FerrisWheel:Vxe,Figma:Hxe,File:ZU,FileArchive:Gxe,FileAudio:Kxe,FileAudio2:Wxe,FileAxis3d:g8,FileBadge:Zxe,FileBadge2:Yxe,FileBox:Xxe,FileChartColumn:y8,FileChartColumnIncreasing:x8,FileChartLine:v8,FileChartPie:b8,FileCheck:RX,FileCheck2:IX,FileClock:Qxe,FileCode:e0e,FileCode2:Jxe,FileCog:_8,FileDiff:t0e,FileDigit:s0e,FileDown:W2,FileHeart:n0e,FileImage:kM,FileInput:r0e,FileJson:i0e,FileJson2:a0e,FileKey:l0e,FileKey2:o0e,FileLock:d0e,FileLock2:c0e,FileMinus:h0e,FileMinus2:u0e,FileMusic:m0e,FileOutput:p0e,FilePen:w8,FilePenLine:Iw,FilePlus:f0e,FilePlus2:YU,FileQuestion:g0e,FileScan:x0e,FileSearch:DX,FileSearch2:y0e,FileSliders:v0e,FileSpreadsheet:Qk,FileStack:OX,FileSymlink:b0e,FileTerminal:_0e,FileText:Ur,FileType:j0e,FileType2:w0e,FileUp:N0e,FileUser:k0e,FileVideo:FX,FileVideo2:S0e,FileVolume:A0e,FileVolume2:C0e,FileWarning:E0e,FileX:M0e,FileX2:T0e,Files:P0e,Film:Gh,Filter:K2,FilterX:L0e,Fingerprint:I0e,FireExtinguisher:R0e,Fish:F0e,FishOff:D0e,FishSymbol:O0e,Flag:NA,FlagOff:z0e,FlagTriangleLeft:B0e,FlagTriangleRight:U0e,Flame:Xd,FlameKindling:q0e,Flashlight:V0e,FlashlightOff:$0e,FlaskConical:SM,FlaskConicalOff:H0e,FlaskRound:G0e,FlipHorizontal:zX,FlipHorizontal2:W0e,FlipVertical:Y0e,FlipVertical2:K0e,Flower:Z0e,Flower2:Hk,Focus:X0e,FoldHorizontal:Q0e,FoldVertical:J0e,Folder:Sye,FolderArchive:eye,FolderCheck:tye,FolderClock:sye,FolderClosed:nye,FolderCode:rye,FolderCog:j8,FolderDot:aye,FolderDown:iye,FolderGit:lye,FolderGit2:oye,FolderHeart:cye,FolderInput:dye,FolderKanban:uye,FolderKey:hye,FolderLock:mye,FolderMinus:pye,FolderOpen:r1,FolderOpenDot:fye,FolderOutput:gye,FolderPen:N8,FolderPlus:xye,FolderRoot:yye,FolderSearch:bye,FolderSearch2:vye,FolderSymlink:_ye,FolderSync:wye,FolderTree:jye,FolderUp:Nye,FolderX:kye,Folders:Cye,Footprints:Aye,Forklift:Eye,Forward:Tye,Frame:Mye,Framer:Pye,Frown:Lye,Fuel:Iye,Fullscreen:Rye,GalleryHorizontal:Oye,GalleryHorizontalEnd:Dye,GalleryThumbnails:Fye,GalleryVertical:Bye,GalleryVerticalEnd:zye,Gamepad:qye,Gamepad2:Uye,Gauge:$ye,Gavel:Vye,Gem:Hye,Ghost:CF,Gift:Ro,GitBranch:Wye,GitBranchPlus:Gye,GitCommitHorizontal:k8,GitCommitVertical:Kye,GitCompare:Zye,GitCompareArrows:Yye,GitFork:Xye,GitGraph:Qye,GitMerge:Jye,GitPullRequest:ave,GitPullRequestArrow:eve,GitPullRequestClosed:tve,GitPullRequestCreate:nve,GitPullRequestCreateArrow:sve,GitPullRequestDraft:rve,Github:ive,Gitlab:ove,GlassWater:lve,Glasses:cve,Globe:fl,GlobeLock:dve,Goal:uve,Grab:hve,GraduationCap:Kh,Grape:mve,Grid2x2:C8,Grid2x2Check:pve,Grid2x2Plus:S8,Grid2x2X:fve,Grid3x3:Aw,Grip:xve,GripHorizontal:gve,GripVertical:kf,Group:yve,Guitar:vve,Ham:bve,Hammer:BX,Hand:XU,HandCoins:_ve,HandHeart:UX,HandHelping:e4,HandMetal:wve,HandPlatter:jve,Handshake:a1,HardDrive:qX,HardDriveDownload:Nve,HardDriveUpload:kve,HardHat:Sve,Hash:CM,Haze:Cve,HdmiPort:Ave,Heading:Pve,Heading1:QU,Heading2:AF,Heading3:JU,Heading4:Eve,Heading5:Tve,Heading6:Mve,HeadphoneOff:Lve,Headphones:Ive,Headset:Rve,Heart:ko,HeartCrack:Dve,HeartHandshake:$X,HeartOff:Ove,HeartPulse:Fve,Heater:zve,Hexagon:Bve,Highlighter:Uve,History:Y2,Hop:$ve,HopOff:qve,Hospital:Vve,Hotel:Hve,Hourglass:VX,House:ra,HousePlug:Gve,HousePlus:Wve,IceCreamBowl:A8,IceCreamCone:E8,IdCard:Kve,Image:pc,ImageDown:Yve,ImageMinus:Zve,ImageOff:Xve,ImagePlay:Qve,ImagePlus:ly,ImageUp:Jve,ImageUpscale:e1e,Images:t1e,Import:s1e,Inbox:AM,IndentDecrease:T8,IndentIncrease:M8,IndianRupee:n1e,Infinity:eq,Info:Jk,InspectionPanel:r1e,Instagram:gm,Italic:kA,IterationCcw:a1e,IterationCw:i1e,JapaneseYen:o1e,Joystick:l1e,Kanban:P4,Key:C_,KeyRound:SA,KeySquare:c1e,Keyboard:h1e,KeyboardMusic:d1e,KeyboardOff:u1e,Lamp:y1e,LampCeiling:m1e,LampDesk:p1e,LampFloor:f1e,LampWallDown:g1e,LampWallUp:x1e,LandPlot:v1e,Landmark:tq,Languages:b1e,Laptop:w1e,LaptopMinimal:P8,LaptopMinimalCheck:_1e,Lasso:N1e,LassoSelect:j1e,Laugh:k1e,Layers:L4,Layers2:S1e,Layers3:C1e,LayoutDashboard:EF,LayoutGrid:Hg,LayoutList:A1e,LayoutPanelLeft:E1e,LayoutPanelTop:T1e,LayoutTemplate:ej,Leaf:M1e,LeafyGreen:P1e,Lectern:L1e,LetterText:I1e,Library:tj,LibraryBig:R1e,LifeBuoy:sq,Ligature:D1e,Lightbulb:eS,LightbulbOff:O1e,Link:Rc,Link2:ad,Link2Off:F1e,Linkedin:Gg,List:m0,ListCheck:z1e,ListChecks:cy,ListCollapse:B1e,ListEnd:U1e,ListFilter:HX,ListMinus:q1e,ListMusic:$1e,ListOrdered:sj,ListPlus:V1e,ListRestart:H1e,ListStart:G1e,ListTodo:W1e,ListTree:K1e,ListVideo:Y1e,ListX:Z1e,Loader:Q1e,LoaderCircle:Et,LoaderPinwheel:X1e,Locate:nq,LocateFixed:J1e,LocateOff:ebe,Lock:Ql,LockKeyhole:tbe,LockKeyholeOpen:L8,LockOpen:I8,LogIn:EM,LogOut:TF,Logs:sbe,Lollipop:nbe,Luggage:rbe,Magnet:abe,Mail:ln,MailCheck:rq,MailMinus:ibe,MailOpen:GX,MailPlus:WX,MailQuestion:obe,MailSearch:lbe,MailWarning:cbe,MailX:TM,Mailbox:dbe,Mails:ube,Map:MF,MapPin:ni,MapPinCheck:mbe,MapPinCheckInside:hbe,MapPinHouse:pbe,MapPinMinus:gbe,MapPinMinusInside:fbe,MapPinOff:xbe,MapPinPlus:vbe,MapPinPlusInside:ybe,MapPinX:_be,MapPinXInside:bbe,MapPinned:wbe,Martini:jbe,Maximize:PF,Maximize2:KX,Medal:CA,Megaphone:Th,MegaphoneOff:Nbe,Meh:kbe,MemoryStick:Sbe,Menu:AA,Merge:Cbe,MessageCircle:vu,MessageCircleCode:Abe,MessageCircleDashed:Ebe,MessageCircleHeart:aq,MessageCircleMore:Tbe,MessageCircleOff:Mbe,MessageCirclePlus:Pbe,MessageCircleQuestion:YX,MessageCircleReply:Lbe,MessageCircleWarning:Ibe,MessageCircleX:Rbe,MessageSquare:Ki,MessageSquareCode:Dbe,MessageSquareDashed:Obe,MessageSquareDiff:Fbe,MessageSquareDot:zbe,MessageSquareHeart:Bbe,MessageSquareLock:Ube,MessageSquareMore:ZX,MessageSquareOff:qbe,MessageSquarePlus:p4,MessageSquareQuote:EA,MessageSquareReply:XX,MessageSquareShare:$be,MessageSquareText:Vbe,MessageSquareWarning:Hbe,MessageSquareX:Gbe,MessagesSquare:QX,Mic:LF,MicOff:Wbe,MicVocal:R8,Microchip:Kbe,Microscope:Ybe,Microwave:Zbe,Milestone:Xbe,Milk:Jbe,MilkOff:Qbe,Minimize:t_e,Minimize2:e_e,Minus:Z2,Monitor:X2,MonitorCheck:s_e,MonitorCog:n_e,MonitorDot:r_e,MonitorDown:a_e,MonitorOff:i_e,MonitorPause:o_e,MonitorPlay:iq,MonitorSmartphone:l_e,MonitorSpeaker:c_e,MonitorStop:d_e,MonitorUp:IF,MonitorX:u_e,Moon:m_e,MoonStar:h_e,Mountain:f_e,MountainSnow:p_e,Mouse:y_e,MouseOff:g_e,MousePointer:n0,MousePointer2:JX,MousePointerBan:x_e,MousePointerClick:Ch,Move:eQ,Move3d:D8,MoveDiagonal:b_e,MoveDiagonal2:v_e,MoveDown:j_e,MoveDownLeft:__e,MoveDownRight:w_e,MoveHorizontal:N_e,MoveLeft:k_e,MoveRight:S_e,MoveUp:E_e,MoveUpLeft:C_e,MoveUpRight:A_e,MoveVertical:T_e,Music:oq,Music2:M_e,Music3:P_e,Music4:L_e,Navigation:tQ,Navigation2:R_e,Navigation2Off:I_e,NavigationOff:D_e,Network:O_e,Newspaper:Q2,Nfc:F_e,Notebook:q_e,NotebookPen:z_e,NotebookTabs:B_e,NotebookText:U_e,NotepadText:V_e,NotepadTextDashed:$_e,Nut:G_e,NutOff:H_e,Octagon:K_e,OctagonAlert:Fk,OctagonMinus:W_e,OctagonPause:O8,OctagonX:F8,Omega:Y_e,Option:Z_e,Orbit:X_e,Origami:Q_e,Package:dh,Package2:J_e,PackageCheck:ewe,PackageMinus:twe,PackageOpen:swe,PackagePlus:nwe,PackageSearch:rwe,PackageX:awe,PaintBucket:iwe,PaintRoller:owe,Paintbrush:lwe,PaintbrushVertical:z8,Palette:$c,PanelBottom:uwe,PanelBottomClose:cwe,PanelBottomDashed:B8,PanelBottomOpen:dwe,PanelLeft:V8,PanelLeftClose:U8,PanelLeftDashed:q8,PanelLeftOpen:$8,PanelRight:pwe,PanelRightClose:hwe,PanelRightDashed:H8,PanelRightOpen:mwe,PanelTop:xwe,PanelTopClose:fwe,PanelTopDashed:G8,PanelTopOpen:gwe,PanelsLeftBottom:ywe,PanelsRightBottom:vwe,PanelsTopLeft:LC,Paperclip:MM,Parentheses:bwe,ParkingMeter:_we,PartyPopper:Wg,Pause:uv,PawPrint:wwe,PcCase:jwe,Pen:C2,PenLine:Pg,PenOff:Nwe,PenTool:TA,Pencil:ri,PencilLine:lq,PencilOff:kwe,PencilRuler:Swe,Pentagon:Cwe,Percent:PM,PersonStanding:Awe,PhilippinePeso:Ewe,Phone:ba,PhoneCall:sQ,PhoneForwarded:Twe,PhoneIncoming:Mwe,PhoneMissed:Pwe,PhoneOff:Lwe,PhoneOutgoing:Iwe,Pi:Rwe,Piano:Dwe,Pickaxe:Owe,PictureInPicture:zwe,PictureInPicture2:Fwe,PiggyBank:Bwe,Pilcrow:$we,PilcrowLeft:Uwe,PilcrowRight:qwe,Pill:Hwe,PillBottle:Vwe,Pin:MA,PinOff:nQ,Pipette:Gwe,Pizza:Wwe,Plane:rQ,PlaneLanding:Kwe,PlaneTakeoff:Ywe,Play:lu,Plug:J2,Plug2:Zwe,PlugZap:W8,Plus:an,Pocket:Qwe,PocketKnife:Xwe,Podcast:Jwe,Pointer:tje,PointerOff:eje,Popcorn:sje,Popsicle:nje,PoundSterling:rje,Power:aQ,PowerOff:aje,Presentation:hv,Printer:PA,PrinterCheck:ije,Projector:oje,Proportions:lje,Puzzle:cje,Pyramid:dje,QrCode:Sf,Quote:tS,Rabbit:uje,Radar:cq,Radiation:hje,Radical:mje,Radio:mv,RadioReceiver:pje,RadioTower:fje,Radius:gje,RailSymbol:xje,Rainbow:yje,Rat:vje,Ratio:bje,Receipt:Eje,ReceiptCent:_je,ReceiptEuro:wje,ReceiptIndianRupee:jje,ReceiptJapaneseYen:Nje,ReceiptPoundSterling:kje,ReceiptRussianRuble:Sje,ReceiptSwissFranc:Cje,ReceiptText:Aje,RectangleEllipsis:K8,RectangleHorizontal:Tje,RectangleVertical:Mje,Recycle:Pje,Redo:LA,Redo2:Lje,RedoDot:Ije,RefreshCcw:dq,RefreshCcwDot:Rje,RefreshCw:no,RefreshCwOff:Dje,Refrigerator:Oje,Regex:Fje,RemoveFormatting:zje,Repeat:IA,Repeat1:Bje,Repeat2:iQ,Replace:qje,ReplaceAll:Uje,Reply:uq,ReplyAll:$je,Rewind:Vje,Ribbon:Hje,Rocket:pv,RockingChair:Gje,RollerCoaster:Wje,Rotate3d:Y8,RotateCcw:Kg,RotateCcwSquare:Kje,RotateCw:RF,RotateCwSquare:Yje,Route:hq,RouteOff:Zje,Router:Xje,Rows2:Z8,Rows3:X8,Rows4:Qje,Rss:Jje,Ruler:I4,RussianRuble:e2e,Sailboat:t2e,Salad:s2e,Sandwich:n2e,Satellite:a2e,SatelliteDish:r2e,Save:Ho,SaveAll:i2e,SaveOff:o2e,Scale:l2e,Scale3d:Q8,Scaling:c2e,Scan:x2e,ScanBarcode:d2e,ScanEye:u2e,ScanFace:h2e,ScanLine:m2e,ScanQrCode:p2e,ScanSearch:f2e,ScanText:g2e,School:y2e,Scissors:b2e,ScissorsLineDashed:v2e,ScreenShare:w2e,ScreenShareOff:_2e,Scroll:j2e,ScrollText:mq,Search:Fr,SearchCheck:N2e,SearchCode:k2e,SearchSlash:S2e,SearchX:pq,Section:C2e,Send:$r,SendHorizontal:J8,SendToBack:A2e,SeparatorHorizontal:E2e,SeparatorVertical:T2e,Server:I2e,ServerCog:M2e,ServerCrash:P2e,ServerOff:L2e,Settings:qc,Settings2:R4,Shapes:R2e,Share:oQ,Share2:jd,Sheet:D2e,Shell:O2e,Shield:Im,ShieldAlert:fq,ShieldBan:F2e,ShieldCheck:cg,ShieldEllipsis:z2e,ShieldHalf:B2e,ShieldMinus:U2e,ShieldOff:DF,ShieldPlus:q2e,ShieldQuestion:OF,ShieldX:eR,Ship:V2e,ShipWheel:$2e,Shirt:H2e,ShoppingBag:D4,ShoppingBasket:G2e,ShoppingCart:sS,Shovel:W2e,ShowerHead:K2e,Shrink:Y2e,Shrub:Z2e,Shuffle:FF,Sigma:X2e,Signal:sNe,SignalHigh:Q2e,SignalLow:J2e,SignalMedium:eNe,SignalZero:tNe,Signature:nNe,Signpost:aNe,SignpostBig:rNe,Siren:iNe,SkipBack:oNe,SkipForward:lQ,Skull:lNe,Slack:cNe,Slash:dNe,Slice:uNe,SlidersHorizontal:LM,SlidersVertical:tR,Smartphone:i1,SmartphoneCharging:hNe,SmartphoneNfc:mNe,Smile:fNe,SmilePlus:pNe,Snail:gNe,Snowflake:$w,Sofa:gq,Soup:xNe,Space:yNe,Spade:vNe,Sparkle:IM,Sparkles:cn,Speaker:bNe,Speech:_Ne,SpellCheck:jNe,SpellCheck2:wNe,Spline:NNe,Split:kNe,SprayCan:SNe,Sprout:RM,Square:db,SquareActivity:sR,SquareArrowDown:aR,SquareArrowDownLeft:nR,SquareArrowDownRight:rR,SquareArrowLeft:iR,SquareArrowOutDownLeft:oR,SquareArrowOutDownRight:lR,SquareArrowOutUpLeft:cR,SquareArrowOutUpRight:dR,SquareArrowRight:uR,SquareArrowUp:pR,SquareArrowUpLeft:hR,SquareArrowUpRight:mR,SquareAsterisk:fR,SquareBottomDashedScissors:gR,SquareChartGantt:v5,SquareCheck:xR,SquareCheckBig:t4,SquareChevronDown:yR,SquareChevronLeft:vR,SquareChevronRight:bR,SquareChevronUp:_R,SquareCode:wR,SquareDashed:kR,SquareDashedBottom:ANe,SquareDashedBottomCode:CNe,SquareDashedKanban:jR,SquareDashedMousePointer:NR,SquareDivide:SR,SquareDot:CR,SquareEqual:AR,SquareFunction:ER,SquareKanban:TR,SquareLibrary:MR,SquareM:PR,SquareMenu:LR,SquareMinus:IR,SquareMousePointer:RR,SquareParking:OR,SquareParkingOff:DR,SquarePen:sp,SquarePercent:FR,SquarePi:zR,SquarePilcrow:BR,SquarePlay:UR,SquarePlus:qR,SquarePower:$R,SquareRadical:ENe,SquareScissors:VR,SquareSigma:HR,SquareSlash:GR,SquareSplitHorizontal:WR,SquareSplitVertical:KR,SquareSquare:TNe,SquareStack:MNe,SquareTerminal:YR,SquareUser:XR,SquareUserRound:ZR,SquareX:QR,Squircle:PNe,Squirrel:LNe,Stamp:INe,Star:Ua,StarHalf:RNe,StarOff:DNe,StepBack:ONe,StepForward:FNe,Stethoscope:zNe,Sticker:BNe,StickyNote:zF,Store:xq,StretchHorizontal:UNe,StretchVertical:qNe,Strikethrough:cQ,Subscript:$Ne,Sun:eN,SunDim:VNe,SunMedium:HNe,SunMoon:GNe,SunSnow:WNe,Sunrise:KNe,Sunset:YNe,Superscript:ZNe,SwatchBook:XNe,SwissFranc:QNe,SwitchCamera:JNe,Sword:eke,Swords:tke,Syringe:ske,Table:vq,Table2:yq,TableCellsMerge:nke,TableCellsSplit:rke,TableColumnsSplit:ake,TableOfContents:ike,TableProperties:oke,TableRowsSplit:lke,Tablet:bq,TabletSmartphone:cke,Tablets:dke,Tag:Cf,Tags:dQ,Tally1:uke,Tally2:hke,Tally3:mke,Tally4:pke,Tally5:fke,Tangent:gke,Target:Gu,Telescope:xke,Tent:vke,TentTree:yke,Terminal:bke,TestTube:_ke,TestTubeDiagonal:JR,TestTubes:wke,Text:Ske,TextCursor:jke,TextCursorInput:_q,TextQuote:Nke,TextSearch:kke,TextSelect:eD,Theater:Cke,Thermometer:Tke,ThermometerSnowflake:Ake,ThermometerSun:Eke,ThumbsDown:uQ,ThumbsUp:wx,Ticket:BF,TicketCheck:Mke,TicketMinus:Pke,TicketPercent:Lke,TicketPlus:Ike,TicketSlash:Rke,TicketX:Dke,Tickets:Fke,TicketsPlane:Oke,Timer:Uke,TimerOff:zke,TimerReset:Bke,ToggleLeft:qke,ToggleRight:$ke,Toilet:Vke,Tornado:Hke,Torus:Gke,Touchpad:Kke,TouchpadOff:Wke,TowerControl:Yke,ToyBrick:Zke,Tractor:Xke,TrafficCone:Qke,TrainFront:eSe,TrainFrontTunnel:Jke,TrainTrack:tSe,TramFront:tD,Trash:sSe,Trash2:In,TreeDeciduous:nSe,TreePalm:sD,TreePine:DM,Trees:rSe,Trello:aSe,TrendingDown:nS,TrendingUp:rc,TrendingUpDown:iSe,Triangle:lSe,TriangleAlert:tc,TriangleRight:oSe,Trophy:Al,Truck:hQ,Turtle:cSe,Tv:uSe,TvMinimal:nD,TvMinimalPlay:dSe,Twitch:hSe,Twitter:mQ,Type:wq,TypeOutline:mSe,Umbrella:fSe,UmbrellaOff:pSe,Underline:UF,Undo:RA,Undo2:pQ,UndoDot:gSe,UnfoldHorizontal:xSe,UnfoldVertical:ySe,Ungroup:vSe,University:rD,Unlink:qF,Unlink2:bSe,Unplug:jq,Upload:qa,Usb:_Se,User:So,UserCheck:tN,UserCog:fQ,UserMinus:Nq,UserPen:wSe,UserPlus:zl,UserRound:dD,UserRoundCheck:aD,UserRoundCog:iD,UserRoundMinus:oD,UserRoundPen:jSe,UserRoundPlus:lD,UserRoundSearch:NSe,UserRoundX:cD,UserSearch:kSe,UserX:SSe,Users:Bn,UsersRound:zk,Utensils:hD,UtensilsCrossed:uD,UtilityPole:CSe,Variable:kq,Vault:ASe,Vegan:ESe,VenetianMask:TSe,Vibrate:PSe,VibrateOff:MSe,Video:Wr,VideoOff:LSe,Videotape:ISe,View:RSe,Voicemail:DSe,Volleyball:OSe,Volume:BSe,Volume1:FSe,Volume2:gQ,VolumeOff:zSe,VolumeX:xQ,Vote:USe,Wallet:yQ,WalletCards:qSe,WalletMinimal:mD,Wallpaper:$Se,Wand:VSe,WandSparkles:Lg,Warehouse:HSe,WashingMachine:GSe,Watch:WSe,Waves:KSe,Waypoints:YSe,Webcam:ZSe,Webhook:QSe,WebhookOff:XSe,Weight:JSe,Wheat:t5e,WheatOff:e5e,WholeWord:s5e,Wifi:o5e,WifiHigh:n5e,WifiLow:r5e,WifiOff:a5e,WifiZero:i5e,Wind:c5e,WindArrowDown:l5e,Wine:u5e,WineOff:d5e,Workflow:$F,Worm:h5e,WrapText:m5e,Wrench:O4,X:er,Youtube:Sq,Zap:Af,ZapOff:p5e,ZoomIn:OM,ZoomOut:Cq},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 b6e=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:Lde,AArrowDownIcon:Lde,AArrowUp:Ide,AArrowUpIcon:Ide,ALargeSmall:Rde,ALargeSmallIcon:Rde,Accessibility:Dde,AccessibilityIcon:Dde,Activity:Lm,ActivityIcon:Lm,ActivitySquare:sR,ActivitySquareIcon:sR,AirVent:Ode,AirVentIcon:Ode,Airplay:Fde,AirplayIcon:Fde,AlarmCheck:hI,AlarmCheckIcon:hI,AlarmClock:Bde,AlarmClockCheck:hI,AlarmClockCheckIcon:hI,AlarmClockIcon:Bde,AlarmClockMinus:mI,AlarmClockMinusIcon:mI,AlarmClockOff:zde,AlarmClockOffIcon:zde,AlarmClockPlus:pI,AlarmClockPlusIcon:pI,AlarmMinus:mI,AlarmMinusIcon:mI,AlarmPlus:pI,AlarmPlusIcon:pI,AlarmSmoke:Ude,AlarmSmokeIcon:Ude,Album:qde,AlbumIcon:qde,AlertCircle:Vo,AlertCircleIcon:Vo,AlertOctagon:Fk,AlertOctagonIcon:Fk,AlertTriangle:tc,AlertTriangleIcon:tc,AlignCenter:bM,AlignCenterHorizontal:$de,AlignCenterHorizontalIcon:$de,AlignCenterIcon:bM,AlignCenterVertical:Vde,AlignCenterVerticalIcon:Vde,AlignEndHorizontal:Hde,AlignEndHorizontalIcon:Hde,AlignEndVertical:Gde,AlignEndVerticalIcon:Gde,AlignHorizontalDistributeCenter:Wde,AlignHorizontalDistributeCenterIcon:Wde,AlignHorizontalDistributeEnd:Kde,AlignHorizontalDistributeEndIcon:Kde,AlignHorizontalDistributeStart:Yde,AlignHorizontalDistributeStartIcon:Yde,AlignHorizontalJustifyCenter:Zde,AlignHorizontalJustifyCenterIcon:Zde,AlignHorizontalJustifyEnd:Xde,AlignHorizontalJustifyEndIcon:Xde,AlignHorizontalJustifyStart:Qde,AlignHorizontalJustifyStartIcon:Qde,AlignHorizontalSpaceAround:Jde,AlignHorizontalSpaceAroundIcon:Jde,AlignHorizontalSpaceBetween:eue,AlignHorizontalSpaceBetweenIcon:eue,AlignJustify:tue,AlignJustifyIcon:tue,AlignLeft:_M,AlignLeftIcon:_M,AlignRight:wM,AlignRightIcon:wM,AlignStartHorizontal:sue,AlignStartHorizontalIcon:sue,AlignStartVertical:nue,AlignStartVerticalIcon:nue,AlignVerticalDistributeCenter:rue,AlignVerticalDistributeCenterIcon:rue,AlignVerticalDistributeEnd:aue,AlignVerticalDistributeEndIcon:aue,AlignVerticalDistributeStart:iue,AlignVerticalDistributeStartIcon:iue,AlignVerticalJustifyCenter:oue,AlignVerticalJustifyCenterIcon:oue,AlignVerticalJustifyEnd:lue,AlignVerticalJustifyEndIcon:lue,AlignVerticalJustifyStart:cue,AlignVerticalJustifyStartIcon:cue,AlignVerticalSpaceAround:due,AlignVerticalSpaceAroundIcon:due,AlignVerticalSpaceBetween:uue,AlignVerticalSpaceBetweenIcon:uue,Ambulance:hue,AmbulanceIcon:hue,Ampersand:mue,AmpersandIcon:mue,Ampersands:pue,AmpersandsIcon:pue,Amphora:fue,AmphoraIcon:fue,Anchor:gue,AnchorIcon:gue,Angry:xue,AngryIcon:xue,Annoyed:yue,AnnoyedIcon:yue,Antenna:vue,AntennaIcon:vue,Anvil:bue,AnvilIcon:bue,Aperture:_ue,ApertureIcon:_ue,AppWindow:jue,AppWindowIcon:jue,AppWindowMac:wue,AppWindowMacIcon:wue,Apple:Nue,AppleIcon:Nue,Archive:n1,ArchiveIcon:n1,ArchiveRestore:jM,ArchiveRestoreIcon:jM,ArchiveX:kue,ArchiveXIcon:kue,AreaChart:SI,AreaChartIcon:SI,Armchair:Sue,ArmchairIcon:Sue,ArrowBigDown:Aue,ArrowBigDownDash:Cue,ArrowBigDownDashIcon:Cue,ArrowBigDownIcon:Aue,ArrowBigLeft:Tue,ArrowBigLeftDash:Eue,ArrowBigLeftDashIcon:Eue,ArrowBigLeftIcon:Tue,ArrowBigRight:Pue,ArrowBigRightDash:Mue,ArrowBigRightDashIcon:Mue,ArrowBigRightIcon:Pue,ArrowBigUp:Iue,ArrowBigUpDash:Lue,ArrowBigUpDashIcon:Lue,ArrowBigUpIcon:Iue,ArrowDown:ag,ArrowDown01:Rue,ArrowDown01Icon:Rue,ArrowDown10:Due,ArrowDown10Icon:Due,ArrowDownAZ:fI,ArrowDownAZIcon:fI,ArrowDownAz:fI,ArrowDownAzIcon:fI,ArrowDownCircle:FI,ArrowDownCircleIcon:FI,ArrowDownFromLine:Oue,ArrowDownFromLineIcon:Oue,ArrowDownIcon:ag,ArrowDownLeft:Fue,ArrowDownLeftFromCircle:BI,ArrowDownLeftFromCircleIcon:BI,ArrowDownLeftFromSquare:oR,ArrowDownLeftFromSquareIcon:oR,ArrowDownLeftIcon:Fue,ArrowDownLeftSquare:nR,ArrowDownLeftSquareIcon:nR,ArrowDownNarrowWide:zue,ArrowDownNarrowWideIcon:zue,ArrowDownRight:NX,ArrowDownRightFromCircle:UI,ArrowDownRightFromCircleIcon:UI,ArrowDownRightFromSquare:lR,ArrowDownRightFromSquareIcon:lR,ArrowDownRightIcon:NX,ArrowDownRightSquare:rR,ArrowDownRightSquareIcon:rR,ArrowDownSquare:aR,ArrowDownSquareIcon:aR,ArrowDownToDot:Bue,ArrowDownToDotIcon:Bue,ArrowDownToLine:Uue,ArrowDownToLineIcon:Uue,ArrowDownUp:que,ArrowDownUpIcon:que,ArrowDownWideNarrow:gI,ArrowDownWideNarrowIcon:gI,ArrowDownZA:xI,ArrowDownZAIcon:xI,ArrowDownZa:xI,ArrowDownZaIcon:xI,ArrowLeft:Aa,ArrowLeftCircle:zI,ArrowLeftCircleIcon:zI,ArrowLeftFromLine:$ue,ArrowLeftFromLineIcon:$ue,ArrowLeftIcon:Aa,ArrowLeftRight:kX,ArrowLeftRightIcon:kX,ArrowLeftSquare:iR,ArrowLeftSquareIcon:iR,ArrowLeftToLine:Vue,ArrowLeftToLineIcon:Vue,ArrowRight:Oa,ArrowRightCircle:VI,ArrowRightCircleIcon:VI,ArrowRightFromLine:Hue,ArrowRightFromLineIcon:Hue,ArrowRightIcon:Oa,ArrowRightLeft:S4,ArrowRightLeftIcon:S4,ArrowRightSquare:uR,ArrowRightSquareIcon:uR,ArrowRightToLine:Gue,ArrowRightToLineIcon:Gue,ArrowUp:cp,ArrowUp01:Wue,ArrowUp01Icon:Wue,ArrowUp10:Kue,ArrowUp10Icon:Kue,ArrowUpAZ:yI,ArrowUpAZIcon:yI,ArrowUpAz:yI,ArrowUpAzIcon:yI,ArrowUpCircle:HI,ArrowUpCircleIcon:HI,ArrowUpDown:xx,ArrowUpDownIcon:xx,ArrowUpFromDot:Yue,ArrowUpFromDotIcon:Yue,ArrowUpFromLine:Zue,ArrowUpFromLineIcon:Zue,ArrowUpIcon:cp,ArrowUpLeft:Xue,ArrowUpLeftFromCircle:qI,ArrowUpLeftFromCircleIcon:qI,ArrowUpLeftFromSquare:cR,ArrowUpLeftFromSquareIcon:cR,ArrowUpLeftIcon:Xue,ArrowUpLeftSquare:hR,ArrowUpLeftSquareIcon:hR,ArrowUpNarrowWide:vI,ArrowUpNarrowWideIcon:vI,ArrowUpRight:bF,ArrowUpRightFromCircle:$I,ArrowUpRightFromCircleIcon:$I,ArrowUpRightFromSquare:dR,ArrowUpRightFromSquareIcon:dR,ArrowUpRightIcon:bF,ArrowUpRightSquare:mR,ArrowUpRightSquareIcon:mR,ArrowUpSquare:pR,ArrowUpSquareIcon:pR,ArrowUpToLine:Que,ArrowUpToLineIcon:Que,ArrowUpWideNarrow:Jue,ArrowUpWideNarrowIcon:Jue,ArrowUpZA:bI,ArrowUpZAIcon:bI,ArrowUpZa:bI,ArrowUpZaIcon:bI,ArrowsUpFromLine:ehe,ArrowsUpFromLineIcon:ehe,Asterisk:the,AsteriskIcon:the,AsteriskSquare:fR,AsteriskSquareIcon:fR,AtSign:she,AtSignIcon:she,Atom:nhe,AtomIcon:nhe,AudioLines:rhe,AudioLinesIcon:rhe,AudioWaveform:ahe,AudioWaveformIcon:ahe,Award:Eh,AwardIcon:Eh,Axe:ihe,AxeIcon:ihe,Axis3D:_I,Axis3DIcon:_I,Axis3d:_I,Axis3dIcon:_I,Baby:ohe,BabyIcon:ohe,Backpack:lhe,BackpackIcon:lhe,Badge:Nhe,BadgeAlert:che,BadgeAlertIcon:che,BadgeCent:dhe,BadgeCentIcon:dhe,BadgeCheck:TC,BadgeCheckIcon:TC,BadgeDollarSign:uhe,BadgeDollarSignIcon:uhe,BadgeEuro:hhe,BadgeEuroIcon:hhe,BadgeHelp:mhe,BadgeHelpIcon:mhe,BadgeIcon:Nhe,BadgeIndianRupee:phe,BadgeIndianRupeeIcon:phe,BadgeInfo:fhe,BadgeInfoIcon:fhe,BadgeJapaneseYen:ghe,BadgeJapaneseYenIcon:ghe,BadgeMinus:xhe,BadgeMinusIcon:xhe,BadgePercent:yhe,BadgePercentIcon:yhe,BadgePlus:vhe,BadgePlusIcon:vhe,BadgePoundSterling:bhe,BadgePoundSterlingIcon:bhe,BadgeRussianRuble:_he,BadgeRussianRubleIcon:_he,BadgeSwissFranc:whe,BadgeSwissFrancIcon:whe,BadgeX:jhe,BadgeXIcon:jhe,BaggageClaim:khe,BaggageClaimIcon:khe,Ban:_F,BanIcon:_F,Banana:She,BananaIcon:She,Bandage:Che,BandageIcon:Che,Banknote:Ahe,BanknoteIcon:Ahe,BarChart:LI,BarChart2:II,BarChart2Icon:II,BarChart3:Cl,BarChart3Icon:Cl,BarChart4:MI,BarChart4Icon:MI,BarChartBig:TI,BarChartBigIcon:TI,BarChartHorizontal:AI,BarChartHorizontalBig:CI,BarChartHorizontalBigIcon:CI,BarChartHorizontalIcon:AI,BarChartIcon:LI,Barcode:Ehe,BarcodeIcon:Ehe,Baseline:The,BaselineIcon:The,Bath:d0,BathIcon:d0,Battery:Dhe,BatteryCharging:Mhe,BatteryChargingIcon:Mhe,BatteryFull:Phe,BatteryFullIcon:Phe,BatteryIcon:Dhe,BatteryLow:Lhe,BatteryLowIcon:Lhe,BatteryMedium:Ihe,BatteryMediumIcon:Ihe,BatteryWarning:Rhe,BatteryWarningIcon:Rhe,Beaker:SX,BeakerIcon:SX,Bean:Fhe,BeanIcon:Fhe,BeanOff:Ohe,BeanOffIcon:Ohe,Bed:Xw,BedDouble:C4,BedDoubleIcon:C4,BedIcon:Xw,BedSingle:zhe,BedSingleIcon:zhe,Beef:Bhe,BeefIcon:Bhe,Beer:qhe,BeerIcon:qhe,BeerOff:Uhe,BeerOffIcon:Uhe,Bell:bx,BellDot:$he,BellDotIcon:$he,BellElectric:Vhe,BellElectricIcon:Vhe,BellIcon:bx,BellMinus:Hhe,BellMinusIcon:Hhe,BellOff:Zk,BellOffIcon:Zk,BellPlus:Ghe,BellPlusIcon:Ghe,BellRing:A4,BellRingIcon:A4,BetweenHorizonalEnd:wI,BetweenHorizonalEndIcon:wI,BetweenHorizonalStart:jI,BetweenHorizonalStartIcon:jI,BetweenHorizontalEnd:wI,BetweenHorizontalEndIcon:wI,BetweenHorizontalStart:jI,BetweenHorizontalStartIcon:jI,BetweenVerticalEnd:Whe,BetweenVerticalEndIcon:Whe,BetweenVerticalStart:Khe,BetweenVerticalStartIcon:Khe,BicepsFlexed:Yhe,BicepsFlexedIcon:Yhe,Bike:Zhe,BikeIcon:Zhe,Binary:Xhe,BinaryIcon:Xhe,Binoculars:Qhe,BinocularsIcon:Qhe,Biohazard:Jhe,BiohazardIcon:Jhe,Bird:eme,BirdIcon:eme,Bitcoin:tme,BitcoinIcon:tme,Blend:sme,BlendIcon:sme,Blinds:nme,BlindsIcon:nme,Blocks:rme,BlocksIcon:rme,Bluetooth:lme,BluetoothConnected:ame,BluetoothConnectedIcon:ame,BluetoothIcon:lme,BluetoothOff:ime,BluetoothOffIcon:ime,BluetoothSearching:ome,BluetoothSearchingIcon:ome,Bold:wA,BoldIcon:wA,Bolt:cme,BoltIcon:cme,Bomb:dme,BombIcon:dme,Bone:ume,BoneIcon:ume,Book:Lme,BookA:hme,BookAIcon:hme,BookAudio:mme,BookAudioIcon:mme,BookCheck:pme,BookCheckIcon:pme,BookCopy:fme,BookCopyIcon:fme,BookDashed:NI,BookDashedIcon:NI,BookDown:gme,BookDownIcon:gme,BookHeadphones:xme,BookHeadphonesIcon:xme,BookHeart:yme,BookHeartIcon:yme,BookIcon:Lme,BookImage:vme,BookImageIcon:vme,BookKey:bme,BookKeyIcon:bme,BookLock:_me,BookLockIcon:_me,BookMarked:wme,BookMarkedIcon:wme,BookMinus:jme,BookMinusIcon:jme,BookOpen:ig,BookOpenCheck:Nme,BookOpenCheckIcon:Nme,BookOpenIcon:ig,BookOpenText:kme,BookOpenTextIcon:kme,BookPlus:Sme,BookPlusIcon:Sme,BookTemplate:NI,BookTemplateIcon:NI,BookText:Cme,BookTextIcon:Cme,BookType:Ame,BookTypeIcon:Ame,BookUp:Tme,BookUp2:Eme,BookUp2Icon:Eme,BookUpIcon:Tme,BookUser:Mme,BookUserIcon:Mme,BookX:Pme,BookXIcon:Pme,Bookmark:u0,BookmarkCheck:Ime,BookmarkCheckIcon:Ime,BookmarkIcon:u0,BookmarkMinus:Rme,BookmarkMinusIcon:Rme,BookmarkPlus:NM,BookmarkPlusIcon:NM,BookmarkX:Dme,BookmarkXIcon:Dme,BoomBox:Ome,BoomBoxIcon:Ome,Bot:E4,BotIcon:E4,BotMessageSquare:Fme,BotMessageSquareIcon:Fme,BotOff:zme,BotOffIcon:zme,Box:CX,BoxIcon:CX,BoxSelect:kR,BoxSelectIcon:kR,Boxes:Bme,BoxesIcon:Bme,Braces:FT,BracesIcon:FT,Brackets:Ume,BracketsIcon:Ume,Brain:AX,BrainCircuit:qme,BrainCircuitIcon:qme,BrainCog:$me,BrainCogIcon:$me,BrainIcon:AX,BrickWall:Vme,BrickWallIcon:Vme,Briefcase:og,BriefcaseBusiness:Hme,BriefcaseBusinessIcon:Hme,BriefcaseConveyorBelt:Gme,BriefcaseConveyorBeltIcon:Gme,BriefcaseIcon:og,BriefcaseMedical:Wme,BriefcaseMedicalIcon:Wme,BringToFront:Kme,BringToFrontIcon:Kme,Brush:Yme,BrushIcon:Yme,Bug:Qme,BugIcon:Qme,BugOff:Zme,BugOffIcon:Zme,BugPlay:Xme,BugPlayIcon:Xme,Building:wF,Building2:_i,Building2Icon:_i,BuildingIcon:wF,Bus:epe,BusFront:Jme,BusFrontIcon:Jme,BusIcon:epe,Cable:spe,CableCar:tpe,CableCarIcon:tpe,CableIcon:spe,Cake:lg,CakeIcon:lg,CakeSlice:npe,CakeSliceIcon:npe,Calculator:Qw,CalculatorIcon:Qw,Calendar:pa,Calendar1:rpe,Calendar1Icon:rpe,CalendarArrowDown:ape,CalendarArrowDownIcon:ape,CalendarArrowUp:ipe,CalendarArrowUpIcon:ipe,CalendarCheck:cv,CalendarCheck2:ope,CalendarCheck2Icon:ope,CalendarCheckIcon:cv,CalendarClock:ch,CalendarClockIcon:ch,CalendarCog:lpe,CalendarCogIcon:lpe,CalendarDays:nc,CalendarDaysIcon:nc,CalendarFold:cpe,CalendarFoldIcon:cpe,CalendarHeart:Xk,CalendarHeartIcon:Xk,CalendarIcon:pa,CalendarMinus:upe,CalendarMinus2:dpe,CalendarMinus2Icon:dpe,CalendarMinusIcon:upe,CalendarOff:GU,CalendarOffIcon:GU,CalendarPlus:sv,CalendarPlus2:hpe,CalendarPlus2Icon:hpe,CalendarPlusIcon:sv,CalendarRange:mpe,CalendarRangeIcon:mpe,CalendarSearch:ppe,CalendarSearchIcon:ppe,CalendarSync:fpe,CalendarSyncIcon:fpe,CalendarX:EX,CalendarX2:gpe,CalendarX2Icon:gpe,CalendarXIcon:EX,Camera:_x,CameraIcon:_x,CameraOff:xpe,CameraOffIcon:xpe,CandlestickChart:EI,CandlestickChartIcon:EI,Candy:bpe,CandyCane:ype,CandyCaneIcon:ype,CandyIcon:bpe,CandyOff:vpe,CandyOffIcon:vpe,Cannabis:_pe,CannabisIcon:_pe,Captions:kI,CaptionsIcon:kI,CaptionsOff:wpe,CaptionsOffIcon:wpe,Car:kpe,CarFront:jpe,CarFrontIcon:jpe,CarIcon:kpe,CarTaxiFront:Npe,CarTaxiFrontIcon:Npe,Caravan:Spe,CaravanIcon:Spe,Carrot:Cpe,CarrotIcon:Cpe,CaseLower:Ape,CaseLowerIcon:Ape,CaseSensitive:Epe,CaseSensitiveIcon:Epe,CaseUpper:Tpe,CaseUpperIcon:Tpe,CassetteTape:Mpe,CassetteTapeIcon:Mpe,Cast:Ppe,CastIcon:Ppe,Castle:Lpe,CastleIcon:Lpe,Cat:Ipe,CatIcon:Ipe,Cctv:Rpe,CctvIcon:Rpe,ChartArea:SI,ChartAreaIcon:SI,ChartBar:AI,ChartBarBig:CI,ChartBarBigIcon:CI,ChartBarDecreasing:Dpe,ChartBarDecreasingIcon:Dpe,ChartBarIcon:AI,ChartBarIncreasing:Ope,ChartBarIncreasingIcon:Ope,ChartBarStacked:Fpe,ChartBarStackedIcon:Fpe,ChartCandlestick:EI,ChartCandlestickIcon:EI,ChartColumn:Cl,ChartColumnBig:TI,ChartColumnBigIcon:TI,ChartColumnDecreasing:zpe,ChartColumnDecreasingIcon:zpe,ChartColumnIcon:Cl,ChartColumnIncreasing:MI,ChartColumnIncreasingIcon:MI,ChartColumnStacked:Bpe,ChartColumnStackedIcon:Bpe,ChartGantt:Upe,ChartGanttIcon:Upe,ChartLine:PI,ChartLineIcon:PI,ChartNetwork:qpe,ChartNetworkIcon:qpe,ChartNoAxesColumn:II,ChartNoAxesColumnDecreasing:$pe,ChartNoAxesColumnDecreasingIcon:$pe,ChartNoAxesColumnIcon:II,ChartNoAxesColumnIncreasing:LI,ChartNoAxesColumnIncreasingIcon:LI,ChartNoAxesCombined:Vpe,ChartNoAxesCombinedIcon:Vpe,ChartNoAxesGantt:RI,ChartNoAxesGanttIcon:RI,ChartPie:DI,ChartPieIcon:DI,ChartScatter:OI,ChartScatterIcon:OI,ChartSpline:Hpe,ChartSplineIcon:Hpe,Check:Xr,CheckCheck:jF,CheckCheckIcon:jF,CheckCircle:Yo,CheckCircle2:zr,CheckCircle2Icon:zr,CheckCircleIcon:Yo,CheckIcon:Xr,CheckSquare:t4,CheckSquare2:xR,CheckSquare2Icon:xR,CheckSquareIcon:t4,ChefHat:Gpe,ChefHatIcon:Gpe,Cherry:Wpe,CherryIcon:Wpe,ChevronDown:rl,ChevronDownCircle:GI,ChevronDownCircleIcon:GI,ChevronDownIcon:rl,ChevronDownSquare:yR,ChevronDownSquareIcon:yR,ChevronFirst:Kpe,ChevronFirstIcon:Kpe,ChevronLast:Ype,ChevronLastIcon:Ype,ChevronLeft:rd,ChevronLeftCircle:WI,ChevronLeftCircleIcon:WI,ChevronLeftIcon:rd,ChevronLeftSquare:vR,ChevronLeftSquareIcon:vR,ChevronRight:gi,ChevronRightCircle:KI,ChevronRightCircleIcon:KI,ChevronRightIcon:gi,ChevronRightSquare:bR,ChevronRightSquareIcon:bR,ChevronUp:dv,ChevronUpCircle:YI,ChevronUpCircleIcon:YI,ChevronUpIcon:dv,ChevronUpSquare:_R,ChevronUpSquareIcon:_R,ChevronsDown:Xpe,ChevronsDownIcon:Xpe,ChevronsDownUp:Zpe,ChevronsDownUpIcon:Zpe,ChevronsLeft:efe,ChevronsLeftIcon:efe,ChevronsLeftRight:Jpe,ChevronsLeftRightEllipsis:Qpe,ChevronsLeftRightEllipsisIcon:Qpe,ChevronsLeftRightIcon:Jpe,ChevronsRight:sfe,ChevronsRightIcon:sfe,ChevronsRightLeft:tfe,ChevronsRightLeftIcon:tfe,ChevronsUp:nfe,ChevronsUpDown:Jw,ChevronsUpDownIcon:Jw,ChevronsUpIcon:nfe,Chrome:NF,ChromeIcon:NF,Church:rfe,ChurchIcon:rfe,Cigarette:ife,CigaretteIcon:ife,CigaretteOff:afe,CigaretteOffIcon:afe,Circle:Nf,CircleAlert:Vo,CircleAlertIcon:Vo,CircleArrowDown:FI,CircleArrowDownIcon:FI,CircleArrowLeft:zI,CircleArrowLeftIcon:zI,CircleArrowOutDownLeft:BI,CircleArrowOutDownLeftIcon:BI,CircleArrowOutDownRight:UI,CircleArrowOutDownRightIcon:UI,CircleArrowOutUpLeft:qI,CircleArrowOutUpLeftIcon:qI,CircleArrowOutUpRight:$I,CircleArrowOutUpRightIcon:$I,CircleArrowRight:VI,CircleArrowRightIcon:VI,CircleArrowUp:HI,CircleArrowUpIcon:HI,CircleCheck:zr,CircleCheckBig:Yo,CircleCheckBigIcon:Yo,CircleCheckIcon:zr,CircleChevronDown:GI,CircleChevronDownIcon:GI,CircleChevronLeft:WI,CircleChevronLeftIcon:WI,CircleChevronRight:KI,CircleChevronRightIcon:KI,CircleChevronUp:YI,CircleChevronUpIcon:YI,CircleDashed:ofe,CircleDashedIcon:ofe,CircleDivide:ZI,CircleDivideIcon:ZI,CircleDollarSign:lfe,CircleDollarSignIcon:lfe,CircleDot:dfe,CircleDotDashed:cfe,CircleDotDashedIcon:cfe,CircleDotIcon:dfe,CircleEllipsis:ufe,CircleEllipsisIcon:ufe,CircleEqual:hfe,CircleEqualIcon:hfe,CircleFadingArrowUp:mfe,CircleFadingArrowUpIcon:mfe,CircleFadingPlus:pfe,CircleFadingPlusIcon:pfe,CircleGauge:XI,CircleGaugeIcon:XI,CircleHelp:MC,CircleHelpIcon:MC,CircleIcon:Nf,CircleMinus:QI,CircleMinusIcon:QI,CircleOff:ffe,CircleOffIcon:ffe,CircleParking:e8,CircleParkingIcon:e8,CircleParkingOff:JI,CircleParkingOffIcon:JI,CirclePause:t8,CirclePauseIcon:t8,CirclePercent:s8,CirclePercentIcon:s8,CirclePlay:$h,CirclePlayIcon:$h,CirclePlus:n8,CirclePlusIcon:n8,CirclePower:r8,CirclePowerIcon:r8,CircleSlash:gfe,CircleSlash2:a8,CircleSlash2Icon:a8,CircleSlashIcon:gfe,CircleSlashed:a8,CircleSlashedIcon:a8,CircleStop:i8,CircleStopIcon:i8,CircleUser:l8,CircleUserIcon:l8,CircleUserRound:o8,CircleUserRoundIcon:o8,CircleX:ou,CircleXIcon:ou,CircuitBoard:xfe,CircuitBoardIcon:xfe,Citrus:yfe,CitrusIcon:yfe,Clapperboard:WU,ClapperboardIcon:WU,Clipboard:kfe,ClipboardCheck:T4,ClipboardCheckIcon:T4,ClipboardCopy:vfe,ClipboardCopyIcon:vfe,ClipboardEdit:d8,ClipboardEditIcon:d8,ClipboardIcon:kfe,ClipboardList:iy,ClipboardListIcon:iy,ClipboardMinus:bfe,ClipboardMinusIcon:bfe,ClipboardPaste:_fe,ClipboardPasteIcon:_fe,ClipboardPen:d8,ClipboardPenIcon:d8,ClipboardPenLine:c8,ClipboardPenLineIcon:c8,ClipboardPlus:wfe,ClipboardPlusIcon:wfe,ClipboardSignature:c8,ClipboardSignatureIcon:c8,ClipboardType:jfe,ClipboardTypeIcon:jfe,ClipboardX:Nfe,ClipboardXIcon:Nfe,Clock:Yr,Clock1:Sfe,Clock10:Cfe,Clock10Icon:Cfe,Clock11:Afe,Clock11Icon:Afe,Clock12:Efe,Clock12Icon:Efe,Clock1Icon:Sfe,Clock2:Tfe,Clock2Icon:Tfe,Clock3:Mfe,Clock3Icon:Mfe,Clock4:Pfe,Clock4Icon:Pfe,Clock5:Lfe,Clock5Icon:Lfe,Clock6:Ife,Clock6Icon:Ife,Clock7:Rfe,Clock7Icon:Rfe,Clock8:Dfe,Clock8Icon:Dfe,Clock9:Ofe,Clock9Icon:Ofe,ClockAlert:Ffe,ClockAlertIcon:Ffe,ClockArrowDown:zfe,ClockArrowDownIcon:zfe,ClockArrowUp:Bfe,ClockArrowUpIcon:Bfe,ClockIcon:Yr,Cloud:tge,CloudAlert:Ufe,CloudAlertIcon:Ufe,CloudCog:qfe,CloudCogIcon:qfe,CloudDownload:u8,CloudDownloadIcon:u8,CloudDrizzle:$fe,CloudDrizzleIcon:$fe,CloudFog:Vfe,CloudFogIcon:Vfe,CloudHail:Hfe,CloudHailIcon:Hfe,CloudIcon:tge,CloudLightning:Gfe,CloudLightningIcon:Gfe,CloudMoon:Kfe,CloudMoonIcon:Kfe,CloudMoonRain:Wfe,CloudMoonRainIcon:Wfe,CloudOff:Yfe,CloudOffIcon:Yfe,CloudRain:Xfe,CloudRainIcon:Xfe,CloudRainWind:Zfe,CloudRainWindIcon:Zfe,CloudSnow:Qfe,CloudSnowIcon:Qfe,CloudSun:ege,CloudSunIcon:ege,CloudSunRain:Jfe,CloudSunRainIcon:Jfe,CloudUpload:h8,CloudUploadIcon:h8,Cloudy:sge,CloudyIcon:sge,Clover:pA,CloverIcon:pA,Club:nge,ClubIcon:nge,Code:jA,Code2:PC,Code2Icon:PC,CodeIcon:jA,CodeSquare:wR,CodeSquareIcon:wR,CodeXml:PC,CodeXmlIcon:PC,Codepen:rge,CodepenIcon:rge,Codesandbox:age,CodesandboxIcon:age,Coffee:M4,CoffeeIcon:M4,Cog:ige,CogIcon:ige,Coins:TX,CoinsIcon:TX,Columns:m8,Columns2:m8,Columns2Icon:m8,Columns3:zT,Columns3Icon:zT,Columns4:oge,Columns4Icon:oge,ColumnsIcon:m8,Combine:lge,CombineIcon:lge,Command:cge,CommandIcon:cge,Compass:kF,CompassIcon:kF,Component:dge,ComponentIcon:dge,Computer:uge,ComputerIcon:uge,ConciergeBell:hge,ConciergeBellIcon:hge,Cone:mge,ConeIcon:mge,Construction:pge,ConstructionIcon:pge,Contact:SF,Contact2:p8,Contact2Icon:p8,ContactIcon:SF,ContactRound:p8,ContactRoundIcon:p8,Container:fge,ContainerIcon:fge,Contrast:gge,ContrastIcon:gge,Cookie:xge,CookieIcon:xge,CookingPot:yge,CookingPotIcon:yge,Copy:Pa,CopyCheck:vge,CopyCheckIcon:vge,CopyIcon:Pa,CopyMinus:bge,CopyMinusIcon:bge,CopyPlus:_ge,CopyPlusIcon:_ge,CopySlash:wge,CopySlashIcon:wge,CopyX:jge,CopyXIcon:jge,Copyleft:Nge,CopyleftIcon:Nge,Copyright:kge,CopyrightIcon:kge,CornerDownLeft:Sge,CornerDownLeftIcon:Sge,CornerDownRight:MX,CornerDownRightIcon:MX,CornerLeftDown:Cge,CornerLeftDownIcon:Cge,CornerLeftUp:Age,CornerLeftUpIcon:Age,CornerRightDown:Ege,CornerRightDownIcon:Ege,CornerRightUp:Tge,CornerRightUpIcon:Tge,CornerUpLeft:Mge,CornerUpLeftIcon:Mge,CornerUpRight:Pge,CornerUpRightIcon:Pge,Cpu:Lge,CpuIcon:Lge,CreativeCommons:Ige,CreativeCommonsIcon:Ige,CreditCard:oy,CreditCardIcon:oy,Croissant:Rge,CroissantIcon:Rge,Crop:Dge,CropIcon:Dge,Cross:Oge,CrossIcon:Oge,Crosshair:Fge,CrosshairIcon:Fge,Crown:h0,CrownIcon:h0,Cuboid:zge,CuboidIcon:zge,CupSoda:Bge,CupSodaIcon:Bge,CurlyBraces:FT,CurlyBracesIcon:FT,Currency:Uge,CurrencyIcon:Uge,Cylinder:qge,CylinderIcon:qge,Dam:$ge,DamIcon:$ge,Database:PX,DatabaseBackup:Vge,DatabaseBackupIcon:Vge,DatabaseIcon:PX,DatabaseZap:Hge,DatabaseZapIcon:Hge,Delete:Gge,DeleteIcon:Gge,Dessert:Wge,DessertIcon:Wge,Diameter:Kge,DiameterIcon:Kge,Diamond:Xge,DiamondIcon:Xge,DiamondMinus:Yge,DiamondMinusIcon:Yge,DiamondPercent:f8,DiamondPercentIcon:f8,DiamondPlus:Zge,DiamondPlusIcon:Zge,Dice1:Qge,Dice1Icon:Qge,Dice2:Jge,Dice2Icon:Jge,Dice3:exe,Dice3Icon:exe,Dice4:txe,Dice4Icon:txe,Dice5:sxe,Dice5Icon:sxe,Dice6:nxe,Dice6Icon:nxe,Dices:rxe,DicesIcon:rxe,Diff:axe,DiffIcon:axe,Disc:cxe,Disc2:ixe,Disc2Icon:ixe,Disc3:oxe,Disc3Icon:oxe,DiscAlbum:lxe,DiscAlbumIcon:lxe,DiscIcon:cxe,Divide:dxe,DivideCircle:ZI,DivideCircleIcon:ZI,DivideIcon:dxe,DivideSquare:SR,DivideSquareIcon:SR,Dna:hxe,DnaIcon:hxe,DnaOff:uxe,DnaOffIcon:uxe,Dock:mxe,DockIcon:mxe,Dog:pxe,DogIcon:pxe,DollarSign:yu,DollarSignIcon:yu,Donut:fxe,DonutIcon:fxe,DoorClosed:gxe,DoorClosedIcon:gxe,DoorOpen:G2,DoorOpenIcon:G2,Dot:xxe,DotIcon:xxe,DotSquare:CR,DotSquareIcon:CR,Download:pi,DownloadCloud:u8,DownloadCloudIcon:u8,DownloadIcon:pi,DraftingCompass:yxe,DraftingCompassIcon:yxe,Drama:vxe,DramaIcon:vxe,Dribbble:bxe,DribbbleIcon:bxe,Drill:_xe,DrillIcon:_xe,Droplet:wxe,DropletIcon:wxe,Droplets:cb,DropletsIcon:cb,Drum:jxe,DrumIcon:jxe,Drumstick:Nxe,DrumstickIcon:Nxe,Dumbbell:kxe,DumbbellIcon:kxe,Ear:Cxe,EarIcon:Cxe,EarOff:Sxe,EarOffIcon:Sxe,Earth:Ok,EarthIcon:Ok,EarthLock:Axe,EarthLockIcon:Axe,Eclipse:Exe,EclipseIcon:Exe,Edit:sp,Edit2:C2,Edit2Icon:C2,Edit3:Pg,Edit3Icon:Pg,EditIcon:sp,Egg:KU,EggFried:Txe,EggFriedIcon:Txe,EggIcon:KU,EggOff:Mxe,EggOffIcon:Mxe,Ellipsis:Z1,EllipsisIcon:Z1,EllipsisVertical:ey,EllipsisVerticalIcon:ey,Equal:Ixe,EqualApproximately:Pxe,EqualApproximatelyIcon:Pxe,EqualIcon:Ixe,EqualNot:Lxe,EqualNotIcon:Lxe,EqualSquare:AR,EqualSquareIcon:AR,Eraser:LX,EraserIcon:LX,EthernetPort:Rxe,EthernetPortIcon:Rxe,Euro:Dxe,EuroIcon:Dxe,Expand:Oxe,ExpandIcon:Oxe,ExternalLink:Sr,ExternalLinkIcon:Sr,Eye:xa,EyeClosed:Fxe,EyeClosedIcon:Fxe,EyeIcon:xa,EyeOff:Vg,EyeOffIcon:Vg,Facebook:zp,FacebookIcon:zp,Factory:zxe,FactoryIcon:zxe,Fan:Bxe,FanIcon:Bxe,FastForward:Uxe,FastForwardIcon:Uxe,Feather:qxe,FeatherIcon:qxe,Fence:$xe,FenceIcon:$xe,FerrisWheel:Vxe,FerrisWheelIcon:Vxe,Figma:Hxe,FigmaIcon:Hxe,File:ZU,FileArchive:Gxe,FileArchiveIcon:Gxe,FileAudio:Kxe,FileAudio2:Wxe,FileAudio2Icon:Wxe,FileAudioIcon:Kxe,FileAxis3D:g8,FileAxis3DIcon:g8,FileAxis3d:g8,FileAxis3dIcon:g8,FileBadge:Zxe,FileBadge2:Yxe,FileBadge2Icon:Yxe,FileBadgeIcon:Zxe,FileBarChart:x8,FileBarChart2:y8,FileBarChart2Icon:y8,FileBarChartIcon:x8,FileBox:Xxe,FileBoxIcon:Xxe,FileChartColumn:y8,FileChartColumnIcon:y8,FileChartColumnIncreasing:x8,FileChartColumnIncreasingIcon:x8,FileChartLine:v8,FileChartLineIcon:v8,FileChartPie:b8,FileChartPieIcon:b8,FileCheck:RX,FileCheck2:IX,FileCheck2Icon:IX,FileCheckIcon:RX,FileClock:Qxe,FileClockIcon:Qxe,FileCode:e0e,FileCode2:Jxe,FileCode2Icon:Jxe,FileCodeIcon:e0e,FileCog:_8,FileCog2:_8,FileCog2Icon:_8,FileCogIcon:_8,FileDiff:t0e,FileDiffIcon:t0e,FileDigit:s0e,FileDigitIcon:s0e,FileDown:W2,FileDownIcon:W2,FileEdit:w8,FileEditIcon:w8,FileHeart:n0e,FileHeartIcon:n0e,FileIcon:ZU,FileImage:kM,FileImageIcon:kM,FileInput:r0e,FileInputIcon:r0e,FileJson:i0e,FileJson2:a0e,FileJson2Icon:a0e,FileJsonIcon:i0e,FileKey:l0e,FileKey2:o0e,FileKey2Icon:o0e,FileKeyIcon:l0e,FileLineChart:v8,FileLineChartIcon:v8,FileLock:d0e,FileLock2:c0e,FileLock2Icon:c0e,FileLockIcon:d0e,FileMinus:h0e,FileMinus2:u0e,FileMinus2Icon:u0e,FileMinusIcon:h0e,FileMusic:m0e,FileMusicIcon:m0e,FileOutput:p0e,FileOutputIcon:p0e,FilePen:w8,FilePenIcon:w8,FilePenLine:Iw,FilePenLineIcon:Iw,FilePieChart:b8,FilePieChartIcon:b8,FilePlus:f0e,FilePlus2:YU,FilePlus2Icon:YU,FilePlusIcon:f0e,FileQuestion:g0e,FileQuestionIcon:g0e,FileScan:x0e,FileScanIcon:x0e,FileSearch:DX,FileSearch2:y0e,FileSearch2Icon:y0e,FileSearchIcon:DX,FileSignature:Iw,FileSignatureIcon:Iw,FileSliders:v0e,FileSlidersIcon:v0e,FileSpreadsheet:Qk,FileSpreadsheetIcon:Qk,FileStack:OX,FileStackIcon:OX,FileSymlink:b0e,FileSymlinkIcon:b0e,FileTerminal:_0e,FileTerminalIcon:_0e,FileText:Ur,FileTextIcon:Ur,FileType:j0e,FileType2:w0e,FileType2Icon:w0e,FileTypeIcon:j0e,FileUp:N0e,FileUpIcon:N0e,FileUser:k0e,FileUserIcon:k0e,FileVideo:FX,FileVideo2:S0e,FileVideo2Icon:S0e,FileVideoIcon:FX,FileVolume:A0e,FileVolume2:C0e,FileVolume2Icon:C0e,FileVolumeIcon:A0e,FileWarning:E0e,FileWarningIcon:E0e,FileX:M0e,FileX2:T0e,FileX2Icon:T0e,FileXIcon:M0e,Files:P0e,FilesIcon:P0e,Film:Gh,FilmIcon:Gh,Filter:K2,FilterIcon:K2,FilterX:L0e,FilterXIcon:L0e,Fingerprint:I0e,FingerprintIcon:I0e,FireExtinguisher:R0e,FireExtinguisherIcon:R0e,Fish:F0e,FishIcon:F0e,FishOff:D0e,FishOffIcon:D0e,FishSymbol:O0e,FishSymbolIcon:O0e,Flag:NA,FlagIcon:NA,FlagOff:z0e,FlagOffIcon:z0e,FlagTriangleLeft:B0e,FlagTriangleLeftIcon:B0e,FlagTriangleRight:U0e,FlagTriangleRightIcon:U0e,Flame:Xd,FlameIcon:Xd,FlameKindling:q0e,FlameKindlingIcon:q0e,Flashlight:V0e,FlashlightIcon:V0e,FlashlightOff:$0e,FlashlightOffIcon:$0e,FlaskConical:SM,FlaskConicalIcon:SM,FlaskConicalOff:H0e,FlaskConicalOffIcon:H0e,FlaskRound:G0e,FlaskRoundIcon:G0e,FlipHorizontal:zX,FlipHorizontal2:W0e,FlipHorizontal2Icon:W0e,FlipHorizontalIcon:zX,FlipVertical:Y0e,FlipVertical2:K0e,FlipVertical2Icon:K0e,FlipVerticalIcon:Y0e,Flower:Z0e,Flower2:Hk,Flower2Icon:Hk,FlowerIcon:Z0e,Focus:X0e,FocusIcon:X0e,FoldHorizontal:Q0e,FoldHorizontalIcon:Q0e,FoldVertical:J0e,FoldVerticalIcon:J0e,Folder:Sye,FolderArchive:eye,FolderArchiveIcon:eye,FolderCheck:tye,FolderCheckIcon:tye,FolderClock:sye,FolderClockIcon:sye,FolderClosed:nye,FolderClosedIcon:nye,FolderCode:rye,FolderCodeIcon:rye,FolderCog:j8,FolderCog2:j8,FolderCog2Icon:j8,FolderCogIcon:j8,FolderDot:aye,FolderDotIcon:aye,FolderDown:iye,FolderDownIcon:iye,FolderEdit:N8,FolderEditIcon:N8,FolderGit:lye,FolderGit2:oye,FolderGit2Icon:oye,FolderGitIcon:lye,FolderHeart:cye,FolderHeartIcon:cye,FolderIcon:Sye,FolderInput:dye,FolderInputIcon:dye,FolderKanban:uye,FolderKanbanIcon:uye,FolderKey:hye,FolderKeyIcon:hye,FolderLock:mye,FolderLockIcon:mye,FolderMinus:pye,FolderMinusIcon:pye,FolderOpen:r1,FolderOpenDot:fye,FolderOpenDotIcon:fye,FolderOpenIcon:r1,FolderOutput:gye,FolderOutputIcon:gye,FolderPen:N8,FolderPenIcon:N8,FolderPlus:xye,FolderPlusIcon:xye,FolderRoot:yye,FolderRootIcon:yye,FolderSearch:bye,FolderSearch2:vye,FolderSearch2Icon:vye,FolderSearchIcon:bye,FolderSymlink:_ye,FolderSymlinkIcon:_ye,FolderSync:wye,FolderSyncIcon:wye,FolderTree:jye,FolderTreeIcon:jye,FolderUp:Nye,FolderUpIcon:Nye,FolderX:kye,FolderXIcon:kye,Folders:Cye,FoldersIcon:Cye,Footprints:Aye,FootprintsIcon:Aye,ForkKnife:hD,ForkKnifeCrossed:uD,ForkKnifeCrossedIcon:uD,ForkKnifeIcon:hD,Forklift:Eye,ForkliftIcon:Eye,FormInput:K8,FormInputIcon:K8,Forward:Tye,ForwardIcon:Tye,Frame:Mye,FrameIcon:Mye,Framer:Pye,FramerIcon:Pye,Frown:Lye,FrownIcon:Lye,Fuel:Iye,FuelIcon:Iye,Fullscreen:Rye,FullscreenIcon:Rye,FunctionSquare:ER,FunctionSquareIcon:ER,GalleryHorizontal:Oye,GalleryHorizontalEnd:Dye,GalleryHorizontalEndIcon:Dye,GalleryHorizontalIcon:Oye,GalleryThumbnails:Fye,GalleryThumbnailsIcon:Fye,GalleryVertical:Bye,GalleryVerticalEnd:zye,GalleryVerticalEndIcon:zye,GalleryVerticalIcon:Bye,Gamepad:qye,Gamepad2:Uye,Gamepad2Icon:Uye,GamepadIcon:qye,GanttChart:RI,GanttChartIcon:RI,GanttChartSquare:v5,GanttChartSquareIcon:v5,Gauge:$ye,GaugeCircle:XI,GaugeCircleIcon:XI,GaugeIcon:$ye,Gavel:Vye,GavelIcon:Vye,Gem:Hye,GemIcon:Hye,Ghost:CF,GhostIcon:CF,Gift:Ro,GiftIcon:Ro,GitBranch:Wye,GitBranchIcon:Wye,GitBranchPlus:Gye,GitBranchPlusIcon:Gye,GitCommit:k8,GitCommitHorizontal:k8,GitCommitHorizontalIcon:k8,GitCommitIcon:k8,GitCommitVertical:Kye,GitCommitVerticalIcon:Kye,GitCompare:Zye,GitCompareArrows:Yye,GitCompareArrowsIcon:Yye,GitCompareIcon:Zye,GitFork:Xye,GitForkIcon:Xye,GitGraph:Qye,GitGraphIcon:Qye,GitMerge:Jye,GitMergeIcon:Jye,GitPullRequest:ave,GitPullRequestArrow:eve,GitPullRequestArrowIcon:eve,GitPullRequestClosed:tve,GitPullRequestClosedIcon:tve,GitPullRequestCreate:nve,GitPullRequestCreateArrow:sve,GitPullRequestCreateArrowIcon:sve,GitPullRequestCreateIcon:nve,GitPullRequestDraft:rve,GitPullRequestDraftIcon:rve,GitPullRequestIcon:ave,Github:ive,GithubIcon:ive,Gitlab:ove,GitlabIcon:ove,GlassWater:lve,GlassWaterIcon:lve,Glasses:cve,GlassesIcon:cve,Globe:fl,Globe2:Ok,Globe2Icon:Ok,GlobeIcon:fl,GlobeLock:dve,GlobeLockIcon:dve,Goal:uve,GoalIcon:uve,Grab:hve,GrabIcon:hve,GraduationCap:Kh,GraduationCapIcon:Kh,Grape:mve,GrapeIcon:mve,Grid:Aw,Grid2X2:C8,Grid2X2Icon:C8,Grid2X2Plus:S8,Grid2X2PlusIcon:S8,Grid2x2:C8,Grid2x2Check:pve,Grid2x2CheckIcon:pve,Grid2x2Icon:C8,Grid2x2Plus:S8,Grid2x2PlusIcon:S8,Grid2x2X:fve,Grid2x2XIcon:fve,Grid3X3:Aw,Grid3X3Icon:Aw,Grid3x3:Aw,Grid3x3Icon:Aw,GridIcon:Aw,Grip:xve,GripHorizontal:gve,GripHorizontalIcon:gve,GripIcon:xve,GripVertical:kf,GripVerticalIcon:kf,Group:yve,GroupIcon:yve,Guitar:vve,GuitarIcon:vve,Ham:bve,HamIcon:bve,Hammer:BX,HammerIcon:BX,Hand:XU,HandCoins:_ve,HandCoinsIcon:_ve,HandHeart:UX,HandHeartIcon:UX,HandHelping:e4,HandHelpingIcon:e4,HandIcon:XU,HandMetal:wve,HandMetalIcon:wve,HandPlatter:jve,HandPlatterIcon:jve,Handshake:a1,HandshakeIcon:a1,HardDrive:qX,HardDriveDownload:Nve,HardDriveDownloadIcon:Nve,HardDriveIcon:qX,HardDriveUpload:kve,HardDriveUploadIcon:kve,HardHat:Sve,HardHatIcon:Sve,Hash:CM,HashIcon:CM,Haze:Cve,HazeIcon:Cve,HdmiPort:Ave,HdmiPortIcon:Ave,Heading:Pve,Heading1:QU,Heading1Icon:QU,Heading2:AF,Heading2Icon:AF,Heading3:JU,Heading3Icon:JU,Heading4:Eve,Heading4Icon:Eve,Heading5:Tve,Heading5Icon:Tve,Heading6:Mve,Heading6Icon:Mve,HeadingIcon:Pve,HeadphoneOff:Lve,HeadphoneOffIcon:Lve,Headphones:Ive,HeadphonesIcon:Ive,Headset:Rve,HeadsetIcon:Rve,Heart:ko,HeartCrack:Dve,HeartCrackIcon:Dve,HeartHandshake:$X,HeartHandshakeIcon:$X,HeartIcon:ko,HeartOff:Ove,HeartOffIcon:Ove,HeartPulse:Fve,HeartPulseIcon:Fve,Heater:zve,HeaterIcon:zve,HelpCircle:MC,HelpCircleIcon:MC,HelpingHand:e4,HelpingHandIcon:e4,Hexagon:Bve,HexagonIcon:Bve,Highlighter:Uve,HighlighterIcon:Uve,History:Y2,HistoryIcon:Y2,Home:ra,HomeIcon:ra,Hop:$ve,HopIcon:$ve,HopOff:qve,HopOffIcon:qve,Hospital:Vve,HospitalIcon:Vve,Hotel:Hve,HotelIcon:Hve,Hourglass:VX,HourglassIcon:VX,House:ra,HouseIcon:ra,HousePlug:Gve,HousePlugIcon:Gve,HousePlus:Wve,HousePlusIcon:Wve,IceCream:E8,IceCream2:A8,IceCream2Icon:A8,IceCreamBowl:A8,IceCreamBowlIcon:A8,IceCreamCone:E8,IceCreamConeIcon:E8,IceCreamIcon:E8,Icon:GEt,IdCard:Kve,IdCardIcon:Kve,Image:pc,ImageDown:Yve,ImageDownIcon:Yve,ImageIcon:pc,ImageMinus:Zve,ImageMinusIcon:Zve,ImageOff:Xve,ImageOffIcon:Xve,ImagePlay:Qve,ImagePlayIcon:Qve,ImagePlus:ly,ImagePlusIcon:ly,ImageUp:Jve,ImageUpIcon:Jve,ImageUpscale:e1e,ImageUpscaleIcon:e1e,Images:t1e,ImagesIcon:t1e,Import:s1e,ImportIcon:s1e,Inbox:AM,InboxIcon:AM,Indent:M8,IndentDecrease:T8,IndentDecreaseIcon:T8,IndentIcon:M8,IndentIncrease:M8,IndentIncreaseIcon:M8,IndianRupee:n1e,IndianRupeeIcon:n1e,Infinity:eq,InfinityIcon:eq,Info:Jk,InfoIcon:Jk,Inspect:RR,InspectIcon:RR,InspectionPanel:r1e,InspectionPanelIcon:r1e,Instagram:gm,InstagramIcon:gm,Italic:kA,ItalicIcon:kA,IterationCcw:a1e,IterationCcwIcon:a1e,IterationCw:i1e,IterationCwIcon:i1e,JapaneseYen:o1e,JapaneseYenIcon:o1e,Joystick:l1e,JoystickIcon:l1e,Kanban:P4,KanbanIcon:P4,KanbanSquare:TR,KanbanSquareDashed:jR,KanbanSquareDashedIcon:jR,KanbanSquareIcon:TR,Key:C_,KeyIcon:C_,KeyRound:SA,KeyRoundIcon:SA,KeySquare:c1e,KeySquareIcon:c1e,Keyboard:h1e,KeyboardIcon:h1e,KeyboardMusic:d1e,KeyboardMusicIcon:d1e,KeyboardOff:u1e,KeyboardOffIcon:u1e,Lamp:y1e,LampCeiling:m1e,LampCeilingIcon:m1e,LampDesk:p1e,LampDeskIcon:p1e,LampFloor:f1e,LampFloorIcon:f1e,LampIcon:y1e,LampWallDown:g1e,LampWallDownIcon:g1e,LampWallUp:x1e,LampWallUpIcon:x1e,LandPlot:v1e,LandPlotIcon:v1e,Landmark:tq,LandmarkIcon:tq,Languages:b1e,LanguagesIcon:b1e,Laptop:w1e,Laptop2:P8,Laptop2Icon:P8,LaptopIcon:w1e,LaptopMinimal:P8,LaptopMinimalCheck:_1e,LaptopMinimalCheckIcon:_1e,LaptopMinimalIcon:P8,Lasso:N1e,LassoIcon:N1e,LassoSelect:j1e,LassoSelectIcon:j1e,Laugh:k1e,LaughIcon:k1e,Layers:L4,Layers2:S1e,Layers2Icon:S1e,Layers3:C1e,Layers3Icon:C1e,LayersIcon:L4,Layout:LC,LayoutDashboard:EF,LayoutDashboardIcon:EF,LayoutGrid:Hg,LayoutGridIcon:Hg,LayoutIcon:LC,LayoutList:A1e,LayoutListIcon:A1e,LayoutPanelLeft:E1e,LayoutPanelLeftIcon:E1e,LayoutPanelTop:T1e,LayoutPanelTopIcon:T1e,LayoutTemplate:ej,LayoutTemplateIcon:ej,Leaf:M1e,LeafIcon:M1e,LeafyGreen:P1e,LeafyGreenIcon:P1e,Lectern:L1e,LecternIcon:L1e,LetterText:I1e,LetterTextIcon:I1e,Library:tj,LibraryBig:R1e,LibraryBigIcon:R1e,LibraryIcon:tj,LibrarySquare:MR,LibrarySquareIcon:MR,LifeBuoy:sq,LifeBuoyIcon:sq,Ligature:D1e,LigatureIcon:D1e,Lightbulb:eS,LightbulbIcon:eS,LightbulbOff:O1e,LightbulbOffIcon:O1e,LineChart:PI,LineChartIcon:PI,Link:Rc,Link2:ad,Link2Icon:ad,Link2Off:F1e,Link2OffIcon:F1e,LinkIcon:Rc,Linkedin:Gg,LinkedinIcon:Gg,List:m0,ListCheck:z1e,ListCheckIcon:z1e,ListChecks:cy,ListChecksIcon:cy,ListCollapse:B1e,ListCollapseIcon:B1e,ListEnd:U1e,ListEndIcon:U1e,ListFilter:HX,ListFilterIcon:HX,ListIcon:m0,ListMinus:q1e,ListMinusIcon:q1e,ListMusic:$1e,ListMusicIcon:$1e,ListOrdered:sj,ListOrderedIcon:sj,ListPlus:V1e,ListPlusIcon:V1e,ListRestart:H1e,ListRestartIcon:H1e,ListStart:G1e,ListStartIcon:G1e,ListTodo:W1e,ListTodoIcon:W1e,ListTree:K1e,ListTreeIcon:K1e,ListVideo:Y1e,ListVideoIcon:Y1e,ListX:Z1e,ListXIcon:Z1e,Loader:Q1e,Loader2:Et,Loader2Icon:Et,LoaderCircle:Et,LoaderCircleIcon:Et,LoaderIcon:Q1e,LoaderPinwheel:X1e,LoaderPinwheelIcon:X1e,Locate:nq,LocateFixed:J1e,LocateFixedIcon:J1e,LocateIcon:nq,LocateOff:ebe,LocateOffIcon:ebe,Lock:Ql,LockIcon:Ql,LockKeyhole:tbe,LockKeyholeIcon:tbe,LockKeyholeOpen:L8,LockKeyholeOpenIcon:L8,LockOpen:I8,LockOpenIcon:I8,LogIn:EM,LogInIcon:EM,LogOut:TF,LogOutIcon:TF,Logs:sbe,LogsIcon:sbe,Lollipop:nbe,LollipopIcon:nbe,LucideAArrowDown:Lde,LucideAArrowUp:Ide,LucideALargeSmall:Rde,LucideAccessibility:Dde,LucideActivity:Lm,LucideActivitySquare:sR,LucideAirVent:Ode,LucideAirplay:Fde,LucideAlarmCheck:hI,LucideAlarmClock:Bde,LucideAlarmClockCheck:hI,LucideAlarmClockMinus:mI,LucideAlarmClockOff:zde,LucideAlarmClockPlus:pI,LucideAlarmMinus:mI,LucideAlarmPlus:pI,LucideAlarmSmoke:Ude,LucideAlbum:qde,LucideAlertCircle:Vo,LucideAlertOctagon:Fk,LucideAlertTriangle:tc,LucideAlignCenter:bM,LucideAlignCenterHorizontal:$de,LucideAlignCenterVertical:Vde,LucideAlignEndHorizontal:Hde,LucideAlignEndVertical:Gde,LucideAlignHorizontalDistributeCenter:Wde,LucideAlignHorizontalDistributeEnd:Kde,LucideAlignHorizontalDistributeStart:Yde,LucideAlignHorizontalJustifyCenter:Zde,LucideAlignHorizontalJustifyEnd:Xde,LucideAlignHorizontalJustifyStart:Qde,LucideAlignHorizontalSpaceAround:Jde,LucideAlignHorizontalSpaceBetween:eue,LucideAlignJustify:tue,LucideAlignLeft:_M,LucideAlignRight:wM,LucideAlignStartHorizontal:sue,LucideAlignStartVertical:nue,LucideAlignVerticalDistributeCenter:rue,LucideAlignVerticalDistributeEnd:aue,LucideAlignVerticalDistributeStart:iue,LucideAlignVerticalJustifyCenter:oue,LucideAlignVerticalJustifyEnd:lue,LucideAlignVerticalJustifyStart:cue,LucideAlignVerticalSpaceAround:due,LucideAlignVerticalSpaceBetween:uue,LucideAmbulance:hue,LucideAmpersand:mue,LucideAmpersands:pue,LucideAmphora:fue,LucideAnchor:gue,LucideAngry:xue,LucideAnnoyed:yue,LucideAntenna:vue,LucideAnvil:bue,LucideAperture:_ue,LucideAppWindow:jue,LucideAppWindowMac:wue,LucideApple:Nue,LucideArchive:n1,LucideArchiveRestore:jM,LucideArchiveX:kue,LucideAreaChart:SI,LucideArmchair:Sue,LucideArrowBigDown:Aue,LucideArrowBigDownDash:Cue,LucideArrowBigLeft:Tue,LucideArrowBigLeftDash:Eue,LucideArrowBigRight:Pue,LucideArrowBigRightDash:Mue,LucideArrowBigUp:Iue,LucideArrowBigUpDash:Lue,LucideArrowDown:ag,LucideArrowDown01:Rue,LucideArrowDown10:Due,LucideArrowDownAZ:fI,LucideArrowDownAz:fI,LucideArrowDownCircle:FI,LucideArrowDownFromLine:Oue,LucideArrowDownLeft:Fue,LucideArrowDownLeftFromCircle:BI,LucideArrowDownLeftFromSquare:oR,LucideArrowDownLeftSquare:nR,LucideArrowDownNarrowWide:zue,LucideArrowDownRight:NX,LucideArrowDownRightFromCircle:UI,LucideArrowDownRightFromSquare:lR,LucideArrowDownRightSquare:rR,LucideArrowDownSquare:aR,LucideArrowDownToDot:Bue,LucideArrowDownToLine:Uue,LucideArrowDownUp:que,LucideArrowDownWideNarrow:gI,LucideArrowDownZA:xI,LucideArrowDownZa:xI,LucideArrowLeft:Aa,LucideArrowLeftCircle:zI,LucideArrowLeftFromLine:$ue,LucideArrowLeftRight:kX,LucideArrowLeftSquare:iR,LucideArrowLeftToLine:Vue,LucideArrowRight:Oa,LucideArrowRightCircle:VI,LucideArrowRightFromLine:Hue,LucideArrowRightLeft:S4,LucideArrowRightSquare:uR,LucideArrowRightToLine:Gue,LucideArrowUp:cp,LucideArrowUp01:Wue,LucideArrowUp10:Kue,LucideArrowUpAZ:yI,LucideArrowUpAz:yI,LucideArrowUpCircle:HI,LucideArrowUpDown:xx,LucideArrowUpFromDot:Yue,LucideArrowUpFromLine:Zue,LucideArrowUpLeft:Xue,LucideArrowUpLeftFromCircle:qI,LucideArrowUpLeftFromSquare:cR,LucideArrowUpLeftSquare:hR,LucideArrowUpNarrowWide:vI,LucideArrowUpRight:bF,LucideArrowUpRightFromCircle:$I,LucideArrowUpRightFromSquare:dR,LucideArrowUpRightSquare:mR,LucideArrowUpSquare:pR,LucideArrowUpToLine:Que,LucideArrowUpWideNarrow:Jue,LucideArrowUpZA:bI,LucideArrowUpZa:bI,LucideArrowsUpFromLine:ehe,LucideAsterisk:the,LucideAsteriskSquare:fR,LucideAtSign:she,LucideAtom:nhe,LucideAudioLines:rhe,LucideAudioWaveform:ahe,LucideAward:Eh,LucideAxe:ihe,LucideAxis3D:_I,LucideAxis3d:_I,LucideBaby:ohe,LucideBackpack:lhe,LucideBadge:Nhe,LucideBadgeAlert:che,LucideBadgeCent:dhe,LucideBadgeCheck:TC,LucideBadgeDollarSign:uhe,LucideBadgeEuro:hhe,LucideBadgeHelp:mhe,LucideBadgeIndianRupee:phe,LucideBadgeInfo:fhe,LucideBadgeJapaneseYen:ghe,LucideBadgeMinus:xhe,LucideBadgePercent:yhe,LucideBadgePlus:vhe,LucideBadgePoundSterling:bhe,LucideBadgeRussianRuble:_he,LucideBadgeSwissFranc:whe,LucideBadgeX:jhe,LucideBaggageClaim:khe,LucideBan:_F,LucideBanana:She,LucideBandage:Che,LucideBanknote:Ahe,LucideBarChart:LI,LucideBarChart2:II,LucideBarChart3:Cl,LucideBarChart4:MI,LucideBarChartBig:TI,LucideBarChartHorizontal:AI,LucideBarChartHorizontalBig:CI,LucideBarcode:Ehe,LucideBaseline:The,LucideBath:d0,LucideBattery:Dhe,LucideBatteryCharging:Mhe,LucideBatteryFull:Phe,LucideBatteryLow:Lhe,LucideBatteryMedium:Ihe,LucideBatteryWarning:Rhe,LucideBeaker:SX,LucideBean:Fhe,LucideBeanOff:Ohe,LucideBed:Xw,LucideBedDouble:C4,LucideBedSingle:zhe,LucideBeef:Bhe,LucideBeer:qhe,LucideBeerOff:Uhe,LucideBell:bx,LucideBellDot:$he,LucideBellElectric:Vhe,LucideBellMinus:Hhe,LucideBellOff:Zk,LucideBellPlus:Ghe,LucideBellRing:A4,LucideBetweenHorizonalEnd:wI,LucideBetweenHorizonalStart:jI,LucideBetweenHorizontalEnd:wI,LucideBetweenHorizontalStart:jI,LucideBetweenVerticalEnd:Whe,LucideBetweenVerticalStart:Khe,LucideBicepsFlexed:Yhe,LucideBike:Zhe,LucideBinary:Xhe,LucideBinoculars:Qhe,LucideBiohazard:Jhe,LucideBird:eme,LucideBitcoin:tme,LucideBlend:sme,LucideBlinds:nme,LucideBlocks:rme,LucideBluetooth:lme,LucideBluetoothConnected:ame,LucideBluetoothOff:ime,LucideBluetoothSearching:ome,LucideBold:wA,LucideBolt:cme,LucideBomb:dme,LucideBone:ume,LucideBook:Lme,LucideBookA:hme,LucideBookAudio:mme,LucideBookCheck:pme,LucideBookCopy:fme,LucideBookDashed:NI,LucideBookDown:gme,LucideBookHeadphones:xme,LucideBookHeart:yme,LucideBookImage:vme,LucideBookKey:bme,LucideBookLock:_me,LucideBookMarked:wme,LucideBookMinus:jme,LucideBookOpen:ig,LucideBookOpenCheck:Nme,LucideBookOpenText:kme,LucideBookPlus:Sme,LucideBookTemplate:NI,LucideBookText:Cme,LucideBookType:Ame,LucideBookUp:Tme,LucideBookUp2:Eme,LucideBookUser:Mme,LucideBookX:Pme,LucideBookmark:u0,LucideBookmarkCheck:Ime,LucideBookmarkMinus:Rme,LucideBookmarkPlus:NM,LucideBookmarkX:Dme,LucideBoomBox:Ome,LucideBot:E4,LucideBotMessageSquare:Fme,LucideBotOff:zme,LucideBox:CX,LucideBoxSelect:kR,LucideBoxes:Bme,LucideBraces:FT,LucideBrackets:Ume,LucideBrain:AX,LucideBrainCircuit:qme,LucideBrainCog:$me,LucideBrickWall:Vme,LucideBriefcase:og,LucideBriefcaseBusiness:Hme,LucideBriefcaseConveyorBelt:Gme,LucideBriefcaseMedical:Wme,LucideBringToFront:Kme,LucideBrush:Yme,LucideBug:Qme,LucideBugOff:Zme,LucideBugPlay:Xme,LucideBuilding:wF,LucideBuilding2:_i,LucideBus:epe,LucideBusFront:Jme,LucideCable:spe,LucideCableCar:tpe,LucideCake:lg,LucideCakeSlice:npe,LucideCalculator:Qw,LucideCalendar:pa,LucideCalendar1:rpe,LucideCalendarArrowDown:ape,LucideCalendarArrowUp:ipe,LucideCalendarCheck:cv,LucideCalendarCheck2:ope,LucideCalendarClock:ch,LucideCalendarCog:lpe,LucideCalendarDays:nc,LucideCalendarFold:cpe,LucideCalendarHeart:Xk,LucideCalendarMinus:upe,LucideCalendarMinus2:dpe,LucideCalendarOff:GU,LucideCalendarPlus:sv,LucideCalendarPlus2:hpe,LucideCalendarRange:mpe,LucideCalendarSearch:ppe,LucideCalendarSync:fpe,LucideCalendarX:EX,LucideCalendarX2:gpe,LucideCamera:_x,LucideCameraOff:xpe,LucideCandlestickChart:EI,LucideCandy:bpe,LucideCandyCane:ype,LucideCandyOff:vpe,LucideCannabis:_pe,LucideCaptions:kI,LucideCaptionsOff:wpe,LucideCar:kpe,LucideCarFront:jpe,LucideCarTaxiFront:Npe,LucideCaravan:Spe,LucideCarrot:Cpe,LucideCaseLower:Ape,LucideCaseSensitive:Epe,LucideCaseUpper:Tpe,LucideCassetteTape:Mpe,LucideCast:Ppe,LucideCastle:Lpe,LucideCat:Ipe,LucideCctv:Rpe,LucideChartArea:SI,LucideChartBar:AI,LucideChartBarBig:CI,LucideChartBarDecreasing:Dpe,LucideChartBarIncreasing:Ope,LucideChartBarStacked:Fpe,LucideChartCandlestick:EI,LucideChartColumn:Cl,LucideChartColumnBig:TI,LucideChartColumnDecreasing:zpe,LucideChartColumnIncreasing:MI,LucideChartColumnStacked:Bpe,LucideChartGantt:Upe,LucideChartLine:PI,LucideChartNetwork:qpe,LucideChartNoAxesColumn:II,LucideChartNoAxesColumnDecreasing:$pe,LucideChartNoAxesColumnIncreasing:LI,LucideChartNoAxesCombined:Vpe,LucideChartNoAxesGantt:RI,LucideChartPie:DI,LucideChartScatter:OI,LucideChartSpline:Hpe,LucideCheck:Xr,LucideCheckCheck:jF,LucideCheckCircle:Yo,LucideCheckCircle2:zr,LucideCheckSquare:t4,LucideCheckSquare2:xR,LucideChefHat:Gpe,LucideCherry:Wpe,LucideChevronDown:rl,LucideChevronDownCircle:GI,LucideChevronDownSquare:yR,LucideChevronFirst:Kpe,LucideChevronLast:Ype,LucideChevronLeft:rd,LucideChevronLeftCircle:WI,LucideChevronLeftSquare:vR,LucideChevronRight:gi,LucideChevronRightCircle:KI,LucideChevronRightSquare:bR,LucideChevronUp:dv,LucideChevronUpCircle:YI,LucideChevronUpSquare:_R,LucideChevronsDown:Xpe,LucideChevronsDownUp:Zpe,LucideChevronsLeft:efe,LucideChevronsLeftRight:Jpe,LucideChevronsLeftRightEllipsis:Qpe,LucideChevronsRight:sfe,LucideChevronsRightLeft:tfe,LucideChevronsUp:nfe,LucideChevronsUpDown:Jw,LucideChrome:NF,LucideChurch:rfe,LucideCigarette:ife,LucideCigaretteOff:afe,LucideCircle:Nf,LucideCircleAlert:Vo,LucideCircleArrowDown:FI,LucideCircleArrowLeft:zI,LucideCircleArrowOutDownLeft:BI,LucideCircleArrowOutDownRight:UI,LucideCircleArrowOutUpLeft:qI,LucideCircleArrowOutUpRight:$I,LucideCircleArrowRight:VI,LucideCircleArrowUp:HI,LucideCircleCheck:zr,LucideCircleCheckBig:Yo,LucideCircleChevronDown:GI,LucideCircleChevronLeft:WI,LucideCircleChevronRight:KI,LucideCircleChevronUp:YI,LucideCircleDashed:ofe,LucideCircleDivide:ZI,LucideCircleDollarSign:lfe,LucideCircleDot:dfe,LucideCircleDotDashed:cfe,LucideCircleEllipsis:ufe,LucideCircleEqual:hfe,LucideCircleFadingArrowUp:mfe,LucideCircleFadingPlus:pfe,LucideCircleGauge:XI,LucideCircleHelp:MC,LucideCircleMinus:QI,LucideCircleOff:ffe,LucideCircleParking:e8,LucideCircleParkingOff:JI,LucideCirclePause:t8,LucideCirclePercent:s8,LucideCirclePlay:$h,LucideCirclePlus:n8,LucideCirclePower:r8,LucideCircleSlash:gfe,LucideCircleSlash2:a8,LucideCircleSlashed:a8,LucideCircleStop:i8,LucideCircleUser:l8,LucideCircleUserRound:o8,LucideCircleX:ou,LucideCircuitBoard:xfe,LucideCitrus:yfe,LucideClapperboard:WU,LucideClipboard:kfe,LucideClipboardCheck:T4,LucideClipboardCopy:vfe,LucideClipboardEdit:d8,LucideClipboardList:iy,LucideClipboardMinus:bfe,LucideClipboardPaste:_fe,LucideClipboardPen:d8,LucideClipboardPenLine:c8,LucideClipboardPlus:wfe,LucideClipboardSignature:c8,LucideClipboardType:jfe,LucideClipboardX:Nfe,LucideClock:Yr,LucideClock1:Sfe,LucideClock10:Cfe,LucideClock11:Afe,LucideClock12:Efe,LucideClock2:Tfe,LucideClock3:Mfe,LucideClock4:Pfe,LucideClock5:Lfe,LucideClock6:Ife,LucideClock7:Rfe,LucideClock8:Dfe,LucideClock9:Ofe,LucideClockAlert:Ffe,LucideClockArrowDown:zfe,LucideClockArrowUp:Bfe,LucideCloud:tge,LucideCloudAlert:Ufe,LucideCloudCog:qfe,LucideCloudDownload:u8,LucideCloudDrizzle:$fe,LucideCloudFog:Vfe,LucideCloudHail:Hfe,LucideCloudLightning:Gfe,LucideCloudMoon:Kfe,LucideCloudMoonRain:Wfe,LucideCloudOff:Yfe,LucideCloudRain:Xfe,LucideCloudRainWind:Zfe,LucideCloudSnow:Qfe,LucideCloudSun:ege,LucideCloudSunRain:Jfe,LucideCloudUpload:h8,LucideCloudy:sge,LucideClover:pA,LucideClub:nge,LucideCode:jA,LucideCode2:PC,LucideCodeSquare:wR,LucideCodeXml:PC,LucideCodepen:rge,LucideCodesandbox:age,LucideCoffee:M4,LucideCog:ige,LucideCoins:TX,LucideColumns:m8,LucideColumns2:m8,LucideColumns3:zT,LucideColumns4:oge,LucideCombine:lge,LucideCommand:cge,LucideCompass:kF,LucideComponent:dge,LucideComputer:uge,LucideConciergeBell:hge,LucideCone:mge,LucideConstruction:pge,LucideContact:SF,LucideContact2:p8,LucideContactRound:p8,LucideContainer:fge,LucideContrast:gge,LucideCookie:xge,LucideCookingPot:yge,LucideCopy:Pa,LucideCopyCheck:vge,LucideCopyMinus:bge,LucideCopyPlus:_ge,LucideCopySlash:wge,LucideCopyX:jge,LucideCopyleft:Nge,LucideCopyright:kge,LucideCornerDownLeft:Sge,LucideCornerDownRight:MX,LucideCornerLeftDown:Cge,LucideCornerLeftUp:Age,LucideCornerRightDown:Ege,LucideCornerRightUp:Tge,LucideCornerUpLeft:Mge,LucideCornerUpRight:Pge,LucideCpu:Lge,LucideCreativeCommons:Ige,LucideCreditCard:oy,LucideCroissant:Rge,LucideCrop:Dge,LucideCross:Oge,LucideCrosshair:Fge,LucideCrown:h0,LucideCuboid:zge,LucideCupSoda:Bge,LucideCurlyBraces:FT,LucideCurrency:Uge,LucideCylinder:qge,LucideDam:$ge,LucideDatabase:PX,LucideDatabaseBackup:Vge,LucideDatabaseZap:Hge,LucideDelete:Gge,LucideDessert:Wge,LucideDiameter:Kge,LucideDiamond:Xge,LucideDiamondMinus:Yge,LucideDiamondPercent:f8,LucideDiamondPlus:Zge,LucideDice1:Qge,LucideDice2:Jge,LucideDice3:exe,LucideDice4:txe,LucideDice5:sxe,LucideDice6:nxe,LucideDices:rxe,LucideDiff:axe,LucideDisc:cxe,LucideDisc2:ixe,LucideDisc3:oxe,LucideDiscAlbum:lxe,LucideDivide:dxe,LucideDivideCircle:ZI,LucideDivideSquare:SR,LucideDna:hxe,LucideDnaOff:uxe,LucideDock:mxe,LucideDog:pxe,LucideDollarSign:yu,LucideDonut:fxe,LucideDoorClosed:gxe,LucideDoorOpen:G2,LucideDot:xxe,LucideDotSquare:CR,LucideDownload:pi,LucideDownloadCloud:u8,LucideDraftingCompass:yxe,LucideDrama:vxe,LucideDribbble:bxe,LucideDrill:_xe,LucideDroplet:wxe,LucideDroplets:cb,LucideDrum:jxe,LucideDrumstick:Nxe,LucideDumbbell:kxe,LucideEar:Cxe,LucideEarOff:Sxe,LucideEarth:Ok,LucideEarthLock:Axe,LucideEclipse:Exe,LucideEdit:sp,LucideEdit2:C2,LucideEdit3:Pg,LucideEgg:KU,LucideEggFried:Txe,LucideEggOff:Mxe,LucideEllipsis:Z1,LucideEllipsisVertical:ey,LucideEqual:Ixe,LucideEqualApproximately:Pxe,LucideEqualNot:Lxe,LucideEqualSquare:AR,LucideEraser:LX,LucideEthernetPort:Rxe,LucideEuro:Dxe,LucideExpand:Oxe,LucideExternalLink:Sr,LucideEye:xa,LucideEyeClosed:Fxe,LucideEyeOff:Vg,LucideFacebook:zp,LucideFactory:zxe,LucideFan:Bxe,LucideFastForward:Uxe,LucideFeather:qxe,LucideFence:$xe,LucideFerrisWheel:Vxe,LucideFigma:Hxe,LucideFile:ZU,LucideFileArchive:Gxe,LucideFileAudio:Kxe,LucideFileAudio2:Wxe,LucideFileAxis3D:g8,LucideFileAxis3d:g8,LucideFileBadge:Zxe,LucideFileBadge2:Yxe,LucideFileBarChart:x8,LucideFileBarChart2:y8,LucideFileBox:Xxe,LucideFileChartColumn:y8,LucideFileChartColumnIncreasing:x8,LucideFileChartLine:v8,LucideFileChartPie:b8,LucideFileCheck:RX,LucideFileCheck2:IX,LucideFileClock:Qxe,LucideFileCode:e0e,LucideFileCode2:Jxe,LucideFileCog:_8,LucideFileCog2:_8,LucideFileDiff:t0e,LucideFileDigit:s0e,LucideFileDown:W2,LucideFileEdit:w8,LucideFileHeart:n0e,LucideFileImage:kM,LucideFileInput:r0e,LucideFileJson:i0e,LucideFileJson2:a0e,LucideFileKey:l0e,LucideFileKey2:o0e,LucideFileLineChart:v8,LucideFileLock:d0e,LucideFileLock2:c0e,LucideFileMinus:h0e,LucideFileMinus2:u0e,LucideFileMusic:m0e,LucideFileOutput:p0e,LucideFilePen:w8,LucideFilePenLine:Iw,LucideFilePieChart:b8,LucideFilePlus:f0e,LucideFilePlus2:YU,LucideFileQuestion:g0e,LucideFileScan:x0e,LucideFileSearch:DX,LucideFileSearch2:y0e,LucideFileSignature:Iw,LucideFileSliders:v0e,LucideFileSpreadsheet:Qk,LucideFileStack:OX,LucideFileSymlink:b0e,LucideFileTerminal:_0e,LucideFileText:Ur,LucideFileType:j0e,LucideFileType2:w0e,LucideFileUp:N0e,LucideFileUser:k0e,LucideFileVideo:FX,LucideFileVideo2:S0e,LucideFileVolume:A0e,LucideFileVolume2:C0e,LucideFileWarning:E0e,LucideFileX:M0e,LucideFileX2:T0e,LucideFiles:P0e,LucideFilm:Gh,LucideFilter:K2,LucideFilterX:L0e,LucideFingerprint:I0e,LucideFireExtinguisher:R0e,LucideFish:F0e,LucideFishOff:D0e,LucideFishSymbol:O0e,LucideFlag:NA,LucideFlagOff:z0e,LucideFlagTriangleLeft:B0e,LucideFlagTriangleRight:U0e,LucideFlame:Xd,LucideFlameKindling:q0e,LucideFlashlight:V0e,LucideFlashlightOff:$0e,LucideFlaskConical:SM,LucideFlaskConicalOff:H0e,LucideFlaskRound:G0e,LucideFlipHorizontal:zX,LucideFlipHorizontal2:W0e,LucideFlipVertical:Y0e,LucideFlipVertical2:K0e,LucideFlower:Z0e,LucideFlower2:Hk,LucideFocus:X0e,LucideFoldHorizontal:Q0e,LucideFoldVertical:J0e,LucideFolder:Sye,LucideFolderArchive:eye,LucideFolderCheck:tye,LucideFolderClock:sye,LucideFolderClosed:nye,LucideFolderCode:rye,LucideFolderCog:j8,LucideFolderCog2:j8,LucideFolderDot:aye,LucideFolderDown:iye,LucideFolderEdit:N8,LucideFolderGit:lye,LucideFolderGit2:oye,LucideFolderHeart:cye,LucideFolderInput:dye,LucideFolderKanban:uye,LucideFolderKey:hye,LucideFolderLock:mye,LucideFolderMinus:pye,LucideFolderOpen:r1,LucideFolderOpenDot:fye,LucideFolderOutput:gye,LucideFolderPen:N8,LucideFolderPlus:xye,LucideFolderRoot:yye,LucideFolderSearch:bye,LucideFolderSearch2:vye,LucideFolderSymlink:_ye,LucideFolderSync:wye,LucideFolderTree:jye,LucideFolderUp:Nye,LucideFolderX:kye,LucideFolders:Cye,LucideFootprints:Aye,LucideForkKnife:hD,LucideForkKnifeCrossed:uD,LucideForklift:Eye,LucideFormInput:K8,LucideForward:Tye,LucideFrame:Mye,LucideFramer:Pye,LucideFrown:Lye,LucideFuel:Iye,LucideFullscreen:Rye,LucideFunctionSquare:ER,LucideGalleryHorizontal:Oye,LucideGalleryHorizontalEnd:Dye,LucideGalleryThumbnails:Fye,LucideGalleryVertical:Bye,LucideGalleryVerticalEnd:zye,LucideGamepad:qye,LucideGamepad2:Uye,LucideGanttChart:RI,LucideGanttChartSquare:v5,LucideGauge:$ye,LucideGaugeCircle:XI,LucideGavel:Vye,LucideGem:Hye,LucideGhost:CF,LucideGift:Ro,LucideGitBranch:Wye,LucideGitBranchPlus:Gye,LucideGitCommit:k8,LucideGitCommitHorizontal:k8,LucideGitCommitVertical:Kye,LucideGitCompare:Zye,LucideGitCompareArrows:Yye,LucideGitFork:Xye,LucideGitGraph:Qye,LucideGitMerge:Jye,LucideGitPullRequest:ave,LucideGitPullRequestArrow:eve,LucideGitPullRequestClosed:tve,LucideGitPullRequestCreate:nve,LucideGitPullRequestCreateArrow:sve,LucideGitPullRequestDraft:rve,LucideGithub:ive,LucideGitlab:ove,LucideGlassWater:lve,LucideGlasses:cve,LucideGlobe:fl,LucideGlobe2:Ok,LucideGlobeLock:dve,LucideGoal:uve,LucideGrab:hve,LucideGraduationCap:Kh,LucideGrape:mve,LucideGrid:Aw,LucideGrid2X2:C8,LucideGrid2X2Plus:S8,LucideGrid2x2:C8,LucideGrid2x2Check:pve,LucideGrid2x2Plus:S8,LucideGrid2x2X:fve,LucideGrid3X3:Aw,LucideGrid3x3:Aw,LucideGrip:xve,LucideGripHorizontal:gve,LucideGripVertical:kf,LucideGroup:yve,LucideGuitar:vve,LucideHam:bve,LucideHammer:BX,LucideHand:XU,LucideHandCoins:_ve,LucideHandHeart:UX,LucideHandHelping:e4,LucideHandMetal:wve,LucideHandPlatter:jve,LucideHandshake:a1,LucideHardDrive:qX,LucideHardDriveDownload:Nve,LucideHardDriveUpload:kve,LucideHardHat:Sve,LucideHash:CM,LucideHaze:Cve,LucideHdmiPort:Ave,LucideHeading:Pve,LucideHeading1:QU,LucideHeading2:AF,LucideHeading3:JU,LucideHeading4:Eve,LucideHeading5:Tve,LucideHeading6:Mve,LucideHeadphoneOff:Lve,LucideHeadphones:Ive,LucideHeadset:Rve,LucideHeart:ko,LucideHeartCrack:Dve,LucideHeartHandshake:$X,LucideHeartOff:Ove,LucideHeartPulse:Fve,LucideHeater:zve,LucideHelpCircle:MC,LucideHelpingHand:e4,LucideHexagon:Bve,LucideHighlighter:Uve,LucideHistory:Y2,LucideHome:ra,LucideHop:$ve,LucideHopOff:qve,LucideHospital:Vve,LucideHotel:Hve,LucideHourglass:VX,LucideHouse:ra,LucideHousePlug:Gve,LucideHousePlus:Wve,LucideIceCream:E8,LucideIceCream2:A8,LucideIceCreamBowl:A8,LucideIceCreamCone:E8,LucideIdCard:Kve,LucideImage:pc,LucideImageDown:Yve,LucideImageMinus:Zve,LucideImageOff:Xve,LucideImagePlay:Qve,LucideImagePlus:ly,LucideImageUp:Jve,LucideImageUpscale:e1e,LucideImages:t1e,LucideImport:s1e,LucideInbox:AM,LucideIndent:M8,LucideIndentDecrease:T8,LucideIndentIncrease:M8,LucideIndianRupee:n1e,LucideInfinity:eq,LucideInfo:Jk,LucideInspect:RR,LucideInspectionPanel:r1e,LucideInstagram:gm,LucideItalic:kA,LucideIterationCcw:a1e,LucideIterationCw:i1e,LucideJapaneseYen:o1e,LucideJoystick:l1e,LucideKanban:P4,LucideKanbanSquare:TR,LucideKanbanSquareDashed:jR,LucideKey:C_,LucideKeyRound:SA,LucideKeySquare:c1e,LucideKeyboard:h1e,LucideKeyboardMusic:d1e,LucideKeyboardOff:u1e,LucideLamp:y1e,LucideLampCeiling:m1e,LucideLampDesk:p1e,LucideLampFloor:f1e,LucideLampWallDown:g1e,LucideLampWallUp:x1e,LucideLandPlot:v1e,LucideLandmark:tq,LucideLanguages:b1e,LucideLaptop:w1e,LucideLaptop2:P8,LucideLaptopMinimal:P8,LucideLaptopMinimalCheck:_1e,LucideLasso:N1e,LucideLassoSelect:j1e,LucideLaugh:k1e,LucideLayers:L4,LucideLayers2:S1e,LucideLayers3:C1e,LucideLayout:LC,LucideLayoutDashboard:EF,LucideLayoutGrid:Hg,LucideLayoutList:A1e,LucideLayoutPanelLeft:E1e,LucideLayoutPanelTop:T1e,LucideLayoutTemplate:ej,LucideLeaf:M1e,LucideLeafyGreen:P1e,LucideLectern:L1e,LucideLetterText:I1e,LucideLibrary:tj,LucideLibraryBig:R1e,LucideLibrarySquare:MR,LucideLifeBuoy:sq,LucideLigature:D1e,LucideLightbulb:eS,LucideLightbulbOff:O1e,LucideLineChart:PI,LucideLink:Rc,LucideLink2:ad,LucideLink2Off:F1e,LucideLinkedin:Gg,LucideList:m0,LucideListCheck:z1e,LucideListChecks:cy,LucideListCollapse:B1e,LucideListEnd:U1e,LucideListFilter:HX,LucideListMinus:q1e,LucideListMusic:$1e,LucideListOrdered:sj,LucideListPlus:V1e,LucideListRestart:H1e,LucideListStart:G1e,LucideListTodo:W1e,LucideListTree:K1e,LucideListVideo:Y1e,LucideListX:Z1e,LucideLoader:Q1e,LucideLoader2:Et,LucideLoaderCircle:Et,LucideLoaderPinwheel:X1e,LucideLocate:nq,LucideLocateFixed:J1e,LucideLocateOff:ebe,LucideLock:Ql,LucideLockKeyhole:tbe,LucideLockKeyholeOpen:L8,LucideLockOpen:I8,LucideLogIn:EM,LucideLogOut:TF,LucideLogs:sbe,LucideLollipop:nbe,LucideLuggage:rbe,LucideMSquare:PR,LucideMagnet:abe,LucideMail:ln,LucideMailCheck:rq,LucideMailMinus:ibe,LucideMailOpen:GX,LucideMailPlus:WX,LucideMailQuestion:obe,LucideMailSearch:lbe,LucideMailWarning:cbe,LucideMailX:TM,LucideMailbox:dbe,LucideMails:ube,LucideMap:MF,LucideMapPin:ni,LucideMapPinCheck:mbe,LucideMapPinCheckInside:hbe,LucideMapPinHouse:pbe,LucideMapPinMinus:gbe,LucideMapPinMinusInside:fbe,LucideMapPinOff:xbe,LucideMapPinPlus:vbe,LucideMapPinPlusInside:ybe,LucideMapPinX:_be,LucideMapPinXInside:bbe,LucideMapPinned:wbe,LucideMartini:jbe,LucideMaximize:PF,LucideMaximize2:KX,LucideMedal:CA,LucideMegaphone:Th,LucideMegaphoneOff:Nbe,LucideMeh:kbe,LucideMemoryStick:Sbe,LucideMenu:AA,LucideMenuSquare:LR,LucideMerge:Cbe,LucideMessageCircle:vu,LucideMessageCircleCode:Abe,LucideMessageCircleDashed:Ebe,LucideMessageCircleHeart:aq,LucideMessageCircleMore:Tbe,LucideMessageCircleOff:Mbe,LucideMessageCirclePlus:Pbe,LucideMessageCircleQuestion:YX,LucideMessageCircleReply:Lbe,LucideMessageCircleWarning:Ibe,LucideMessageCircleX:Rbe,LucideMessageSquare:Ki,LucideMessageSquareCode:Dbe,LucideMessageSquareDashed:Obe,LucideMessageSquareDiff:Fbe,LucideMessageSquareDot:zbe,LucideMessageSquareHeart:Bbe,LucideMessageSquareLock:Ube,LucideMessageSquareMore:ZX,LucideMessageSquareOff:qbe,LucideMessageSquarePlus:p4,LucideMessageSquareQuote:EA,LucideMessageSquareReply:XX,LucideMessageSquareShare:$be,LucideMessageSquareText:Vbe,LucideMessageSquareWarning:Hbe,LucideMessageSquareX:Gbe,LucideMessagesSquare:QX,LucideMic:LF,LucideMic2:R8,LucideMicOff:Wbe,LucideMicVocal:R8,LucideMicrochip:Kbe,LucideMicroscope:Ybe,LucideMicrowave:Zbe,LucideMilestone:Xbe,LucideMilk:Jbe,LucideMilkOff:Qbe,LucideMinimize:t_e,LucideMinimize2:e_e,LucideMinus:Z2,LucideMinusCircle:QI,LucideMinusSquare:IR,LucideMonitor:X2,LucideMonitorCheck:s_e,LucideMonitorCog:n_e,LucideMonitorDot:r_e,LucideMonitorDown:a_e,LucideMonitorOff:i_e,LucideMonitorPause:o_e,LucideMonitorPlay:iq,LucideMonitorSmartphone:l_e,LucideMonitorSpeaker:c_e,LucideMonitorStop:d_e,LucideMonitorUp:IF,LucideMonitorX:u_e,LucideMoon:m_e,LucideMoonStar:h_e,LucideMoreHorizontal:Z1,LucideMoreVertical:ey,LucideMountain:f_e,LucideMountainSnow:p_e,LucideMouse:y_e,LucideMouseOff:g_e,LucideMousePointer:n0,LucideMousePointer2:JX,LucideMousePointerBan:x_e,LucideMousePointerClick:Ch,LucideMousePointerSquareDashed:NR,LucideMove:eQ,LucideMove3D:D8,LucideMove3d:D8,LucideMoveDiagonal:b_e,LucideMoveDiagonal2:v_e,LucideMoveDown:j_e,LucideMoveDownLeft:__e,LucideMoveDownRight:w_e,LucideMoveHorizontal:N_e,LucideMoveLeft:k_e,LucideMoveRight:S_e,LucideMoveUp:E_e,LucideMoveUpLeft:C_e,LucideMoveUpRight:A_e,LucideMoveVertical:T_e,LucideMusic:oq,LucideMusic2:M_e,LucideMusic3:P_e,LucideMusic4:L_e,LucideNavigation:tQ,LucideNavigation2:R_e,LucideNavigation2Off:I_e,LucideNavigationOff:D_e,LucideNetwork:O_e,LucideNewspaper:Q2,LucideNfc:F_e,LucideNotebook:q_e,LucideNotebookPen:z_e,LucideNotebookTabs:B_e,LucideNotebookText:U_e,LucideNotepadText:V_e,LucideNotepadTextDashed:$_e,LucideNut:G_e,LucideNutOff:H_e,LucideOctagon:K_e,LucideOctagonAlert:Fk,LucideOctagonMinus:W_e,LucideOctagonPause:O8,LucideOctagonX:F8,LucideOmega:Y_e,LucideOption:Z_e,LucideOrbit:X_e,LucideOrigami:Q_e,LucideOutdent:T8,LucidePackage:dh,LucidePackage2:J_e,LucidePackageCheck:ewe,LucidePackageMinus:twe,LucidePackageOpen:swe,LucidePackagePlus:nwe,LucidePackageSearch:rwe,LucidePackageX:awe,LucidePaintBucket:iwe,LucidePaintRoller:owe,LucidePaintbrush:lwe,LucidePaintbrush2:z8,LucidePaintbrushVertical:z8,LucidePalette:$c,LucidePalmtree:sD,LucidePanelBottom:uwe,LucidePanelBottomClose:cwe,LucidePanelBottomDashed:B8,LucidePanelBottomInactive:B8,LucidePanelBottomOpen:dwe,LucidePanelLeft:V8,LucidePanelLeftClose:U8,LucidePanelLeftDashed:q8,LucidePanelLeftInactive:q8,LucidePanelLeftOpen:$8,LucidePanelRight:pwe,LucidePanelRightClose:hwe,LucidePanelRightDashed:H8,LucidePanelRightInactive:H8,LucidePanelRightOpen:mwe,LucidePanelTop:xwe,LucidePanelTopClose:fwe,LucidePanelTopDashed:G8,LucidePanelTopInactive:G8,LucidePanelTopOpen:gwe,LucidePanelsLeftBottom:ywe,LucidePanelsLeftRight:zT,LucidePanelsRightBottom:vwe,LucidePanelsTopBottom:X8,LucidePanelsTopLeft:LC,LucidePaperclip:MM,LucideParentheses:bwe,LucideParkingCircle:e8,LucideParkingCircleOff:JI,LucideParkingMeter:_we,LucideParkingSquare:OR,LucideParkingSquareOff:DR,LucidePartyPopper:Wg,LucidePause:uv,LucidePauseCircle:t8,LucidePauseOctagon:O8,LucidePawPrint:wwe,LucidePcCase:jwe,LucidePen:C2,LucidePenBox:sp,LucidePenLine:Pg,LucidePenOff:Nwe,LucidePenSquare:sp,LucidePenTool:TA,LucidePencil:ri,LucidePencilLine:lq,LucidePencilOff:kwe,LucidePencilRuler:Swe,LucidePentagon:Cwe,LucidePercent:PM,LucidePercentCircle:s8,LucidePercentDiamond:f8,LucidePercentSquare:FR,LucidePersonStanding:Awe,LucidePhilippinePeso:Ewe,LucidePhone:ba,LucidePhoneCall:sQ,LucidePhoneForwarded:Twe,LucidePhoneIncoming:Mwe,LucidePhoneMissed:Pwe,LucidePhoneOff:Lwe,LucidePhoneOutgoing:Iwe,LucidePi:Rwe,LucidePiSquare:zR,LucidePiano:Dwe,LucidePickaxe:Owe,LucidePictureInPicture:zwe,LucidePictureInPicture2:Fwe,LucidePieChart:DI,LucidePiggyBank:Bwe,LucidePilcrow:$we,LucidePilcrowLeft:Uwe,LucidePilcrowRight:qwe,LucidePilcrowSquare:BR,LucidePill:Hwe,LucidePillBottle:Vwe,LucidePin:MA,LucidePinOff:nQ,LucidePipette:Gwe,LucidePizza:Wwe,LucidePlane:rQ,LucidePlaneLanding:Kwe,LucidePlaneTakeoff:Ywe,LucidePlay:lu,LucidePlayCircle:$h,LucidePlaySquare:UR,LucidePlug:J2,LucidePlug2:Zwe,LucidePlugZap:W8,LucidePlugZap2:W8,LucidePlus:an,LucidePlusCircle:n8,LucidePlusSquare:qR,LucidePocket:Qwe,LucidePocketKnife:Xwe,LucidePodcast:Jwe,LucidePointer:tje,LucidePointerOff:eje,LucidePopcorn:sje,LucidePopsicle:nje,LucidePoundSterling:rje,LucidePower:aQ,LucidePowerCircle:r8,LucidePowerOff:aje,LucidePowerSquare:$R,LucidePresentation:hv,LucidePrinter:PA,LucidePrinterCheck:ije,LucideProjector:oje,LucideProportions:lje,LucidePuzzle:cje,LucidePyramid:dje,LucideQrCode:Sf,LucideQuote:tS,LucideRabbit:uje,LucideRadar:cq,LucideRadiation:hje,LucideRadical:mje,LucideRadio:mv,LucideRadioReceiver:pje,LucideRadioTower:fje,LucideRadius:gje,LucideRailSymbol:xje,LucideRainbow:yje,LucideRat:vje,LucideRatio:bje,LucideReceipt:Eje,LucideReceiptCent:_je,LucideReceiptEuro:wje,LucideReceiptIndianRupee:jje,LucideReceiptJapaneseYen:Nje,LucideReceiptPoundSterling:kje,LucideReceiptRussianRuble:Sje,LucideReceiptSwissFranc:Cje,LucideReceiptText:Aje,LucideRectangleEllipsis:K8,LucideRectangleHorizontal:Tje,LucideRectangleVertical:Mje,LucideRecycle:Pje,LucideRedo:LA,LucideRedo2:Lje,LucideRedoDot:Ije,LucideRefreshCcw:dq,LucideRefreshCcwDot:Rje,LucideRefreshCw:no,LucideRefreshCwOff:Dje,LucideRefrigerator:Oje,LucideRegex:Fje,LucideRemoveFormatting:zje,LucideRepeat:IA,LucideRepeat1:Bje,LucideRepeat2:iQ,LucideReplace:qje,LucideReplaceAll:Uje,LucideReply:uq,LucideReplyAll:$je,LucideRewind:Vje,LucideRibbon:Hje,LucideRocket:pv,LucideRockingChair:Gje,LucideRollerCoaster:Wje,LucideRotate3D:Y8,LucideRotate3d:Y8,LucideRotateCcw:Kg,LucideRotateCcwSquare:Kje,LucideRotateCw:RF,LucideRotateCwSquare:Yje,LucideRoute:hq,LucideRouteOff:Zje,LucideRouter:Xje,LucideRows:Z8,LucideRows2:Z8,LucideRows3:X8,LucideRows4:Qje,LucideRss:Jje,LucideRuler:I4,LucideRussianRuble:e2e,LucideSailboat:t2e,LucideSalad:s2e,LucideSandwich:n2e,LucideSatellite:a2e,LucideSatelliteDish:r2e,LucideSave:Ho,LucideSaveAll:i2e,LucideSaveOff:o2e,LucideScale:l2e,LucideScale3D:Q8,LucideScale3d:Q8,LucideScaling:c2e,LucideScan:x2e,LucideScanBarcode:d2e,LucideScanEye:u2e,LucideScanFace:h2e,LucideScanLine:m2e,LucideScanQrCode:p2e,LucideScanSearch:f2e,LucideScanText:g2e,LucideScatterChart:OI,LucideSchool:y2e,LucideSchool2:rD,LucideScissors:b2e,LucideScissorsLineDashed:v2e,LucideScissorsSquare:VR,LucideScissorsSquareDashedBottom:gR,LucideScreenShare:w2e,LucideScreenShareOff:_2e,LucideScroll:j2e,LucideScrollText:mq,LucideSearch:Fr,LucideSearchCheck:N2e,LucideSearchCode:k2e,LucideSearchSlash:S2e,LucideSearchX:pq,LucideSection:C2e,LucideSend:$r,LucideSendHorizonal:J8,LucideSendHorizontal:J8,LucideSendToBack:A2e,LucideSeparatorHorizontal:E2e,LucideSeparatorVertical:T2e,LucideServer:I2e,LucideServerCog:M2e,LucideServerCrash:P2e,LucideServerOff:L2e,LucideSettings:qc,LucideSettings2:R4,LucideShapes:R2e,LucideShare:oQ,LucideShare2:jd,LucideSheet:D2e,LucideShell:O2e,LucideShield:Im,LucideShieldAlert:fq,LucideShieldBan:F2e,LucideShieldCheck:cg,LucideShieldClose:eR,LucideShieldEllipsis:z2e,LucideShieldHalf:B2e,LucideShieldMinus:U2e,LucideShieldOff:DF,LucideShieldPlus:q2e,LucideShieldQuestion:OF,LucideShieldX:eR,LucideShip:V2e,LucideShipWheel:$2e,LucideShirt:H2e,LucideShoppingBag:D4,LucideShoppingBasket:G2e,LucideShoppingCart:sS,LucideShovel:W2e,LucideShowerHead:K2e,LucideShrink:Y2e,LucideShrub:Z2e,LucideShuffle:FF,LucideSidebar:V8,LucideSidebarClose:U8,LucideSidebarOpen:$8,LucideSigma:X2e,LucideSigmaSquare:HR,LucideSignal:sNe,LucideSignalHigh:Q2e,LucideSignalLow:J2e,LucideSignalMedium:eNe,LucideSignalZero:tNe,LucideSignature:nNe,LucideSignpost:aNe,LucideSignpostBig:rNe,LucideSiren:iNe,LucideSkipBack:oNe,LucideSkipForward:lQ,LucideSkull:lNe,LucideSlack:cNe,LucideSlash:dNe,LucideSlashSquare:GR,LucideSlice:uNe,LucideSliders:tR,LucideSlidersHorizontal:LM,LucideSlidersVertical:tR,LucideSmartphone:i1,LucideSmartphoneCharging:hNe,LucideSmartphoneNfc:mNe,LucideSmile:fNe,LucideSmilePlus:pNe,LucideSnail:gNe,LucideSnowflake:$w,LucideSofa:gq,LucideSortAsc:vI,LucideSortDesc:gI,LucideSoup:xNe,LucideSpace:yNe,LucideSpade:vNe,LucideSparkle:IM,LucideSparkles:cn,LucideSpeaker:bNe,LucideSpeech:_Ne,LucideSpellCheck:jNe,LucideSpellCheck2:wNe,LucideSpline:NNe,LucideSplit:kNe,LucideSplitSquareHorizontal:WR,LucideSplitSquareVertical:KR,LucideSprayCan:SNe,LucideSprout:RM,LucideSquare:db,LucideSquareActivity:sR,LucideSquareArrowDown:aR,LucideSquareArrowDownLeft:nR,LucideSquareArrowDownRight:rR,LucideSquareArrowLeft:iR,LucideSquareArrowOutDownLeft:oR,LucideSquareArrowOutDownRight:lR,LucideSquareArrowOutUpLeft:cR,LucideSquareArrowOutUpRight:dR,LucideSquareArrowRight:uR,LucideSquareArrowUp:pR,LucideSquareArrowUpLeft:hR,LucideSquareArrowUpRight:mR,LucideSquareAsterisk:fR,LucideSquareBottomDashedScissors:gR,LucideSquareChartGantt:v5,LucideSquareCheck:xR,LucideSquareCheckBig:t4,LucideSquareChevronDown:yR,LucideSquareChevronLeft:vR,LucideSquareChevronRight:bR,LucideSquareChevronUp:_R,LucideSquareCode:wR,LucideSquareDashed:kR,LucideSquareDashedBottom:ANe,LucideSquareDashedBottomCode:CNe,LucideSquareDashedKanban:jR,LucideSquareDashedMousePointer:NR,LucideSquareDivide:SR,LucideSquareDot:CR,LucideSquareEqual:AR,LucideSquareFunction:ER,LucideSquareGanttChart:v5,LucideSquareKanban:TR,LucideSquareLibrary:MR,LucideSquareM:PR,LucideSquareMenu:LR,LucideSquareMinus:IR,LucideSquareMousePointer:RR,LucideSquareParking:OR,LucideSquareParkingOff:DR,LucideSquarePen:sp,LucideSquarePercent:FR,LucideSquarePi:zR,LucideSquarePilcrow:BR,LucideSquarePlay:UR,LucideSquarePlus:qR,LucideSquarePower:$R,LucideSquareRadical:ENe,LucideSquareScissors:VR,LucideSquareSigma:HR,LucideSquareSlash:GR,LucideSquareSplitHorizontal:WR,LucideSquareSplitVertical:KR,LucideSquareSquare:TNe,LucideSquareStack:MNe,LucideSquareTerminal:YR,LucideSquareUser:XR,LucideSquareUserRound:ZR,LucideSquareX:QR,LucideSquircle:PNe,LucideSquirrel:LNe,LucideStamp:INe,LucideStar:Ua,LucideStarHalf:RNe,LucideStarOff:DNe,LucideStars:cn,LucideStepBack:ONe,LucideStepForward:FNe,LucideStethoscope:zNe,LucideSticker:BNe,LucideStickyNote:zF,LucideStopCircle:i8,LucideStore:xq,LucideStretchHorizontal:UNe,LucideStretchVertical:qNe,LucideStrikethrough:cQ,LucideSubscript:$Ne,LucideSubtitles:kI,LucideSun:eN,LucideSunDim:VNe,LucideSunMedium:HNe,LucideSunMoon:GNe,LucideSunSnow:WNe,LucideSunrise:KNe,LucideSunset:YNe,LucideSuperscript:ZNe,LucideSwatchBook:XNe,LucideSwissFranc:QNe,LucideSwitchCamera:JNe,LucideSword:eke,LucideSwords:tke,LucideSyringe:ske,LucideTable:vq,LucideTable2:yq,LucideTableCellsMerge:nke,LucideTableCellsSplit:rke,LucideTableColumnsSplit:ake,LucideTableOfContents:ike,LucideTableProperties:oke,LucideTableRowsSplit:lke,LucideTablet:bq,LucideTabletSmartphone:cke,LucideTablets:dke,LucideTag:Cf,LucideTags:dQ,LucideTally1:uke,LucideTally2:hke,LucideTally3:mke,LucideTally4:pke,LucideTally5:fke,LucideTangent:gke,LucideTarget:Gu,LucideTelescope:xke,LucideTent:vke,LucideTentTree:yke,LucideTerminal:bke,LucideTerminalSquare:YR,LucideTestTube:_ke,LucideTestTube2:JR,LucideTestTubeDiagonal:JR,LucideTestTubes:wke,LucideText:Ske,LucideTextCursor:jke,LucideTextCursorInput:_q,LucideTextQuote:Nke,LucideTextSearch:kke,LucideTextSelect:eD,LucideTextSelection:eD,LucideTheater:Cke,LucideThermometer:Tke,LucideThermometerSnowflake:Ake,LucideThermometerSun:Eke,LucideThumbsDown:uQ,LucideThumbsUp:wx,LucideTicket:BF,LucideTicketCheck:Mke,LucideTicketMinus:Pke,LucideTicketPercent:Lke,LucideTicketPlus:Ike,LucideTicketSlash:Rke,LucideTicketX:Dke,LucideTickets:Fke,LucideTicketsPlane:Oke,LucideTimer:Uke,LucideTimerOff:zke,LucideTimerReset:Bke,LucideToggleLeft:qke,LucideToggleRight:$ke,LucideToilet:Vke,LucideTornado:Hke,LucideTorus:Gke,LucideTouchpad:Kke,LucideTouchpadOff:Wke,LucideTowerControl:Yke,LucideToyBrick:Zke,LucideTractor:Xke,LucideTrafficCone:Qke,LucideTrain:tD,LucideTrainFront:eSe,LucideTrainFrontTunnel:Jke,LucideTrainTrack:tSe,LucideTramFront:tD,LucideTrash:sSe,LucideTrash2:In,LucideTreeDeciduous:nSe,LucideTreePalm:sD,LucideTreePine:DM,LucideTrees:rSe,LucideTrello:aSe,LucideTrendingDown:nS,LucideTrendingUp:rc,LucideTrendingUpDown:iSe,LucideTriangle:lSe,LucideTriangleAlert:tc,LucideTriangleRight:oSe,LucideTrophy:Al,LucideTruck:hQ,LucideTurtle:cSe,LucideTv:uSe,LucideTv2:nD,LucideTvMinimal:nD,LucideTvMinimalPlay:dSe,LucideTwitch:hSe,LucideTwitter:mQ,LucideType:wq,LucideTypeOutline:mSe,LucideUmbrella:fSe,LucideUmbrellaOff:pSe,LucideUnderline:UF,LucideUndo:RA,LucideUndo2:pQ,LucideUndoDot:gSe,LucideUnfoldHorizontal:xSe,LucideUnfoldVertical:ySe,LucideUngroup:vSe,LucideUniversity:rD,LucideUnlink:qF,LucideUnlink2:bSe,LucideUnlock:I8,LucideUnlockKeyhole:L8,LucideUnplug:jq,LucideUpload:qa,LucideUploadCloud:h8,LucideUsb:_Se,LucideUser:So,LucideUser2:dD,LucideUserCheck:tN,LucideUserCheck2:aD,LucideUserCircle:l8,LucideUserCircle2:o8,LucideUserCog:fQ,LucideUserCog2:iD,LucideUserMinus:Nq,LucideUserMinus2:oD,LucideUserPen:wSe,LucideUserPlus:zl,LucideUserPlus2:lD,LucideUserRound:dD,LucideUserRoundCheck:aD,LucideUserRoundCog:iD,LucideUserRoundMinus:oD,LucideUserRoundPen:jSe,LucideUserRoundPlus:lD,LucideUserRoundSearch:NSe,LucideUserRoundX:cD,LucideUserSearch:kSe,LucideUserSquare:XR,LucideUserSquare2:ZR,LucideUserX:SSe,LucideUserX2:cD,LucideUsers:Bn,LucideUsers2:zk,LucideUsersRound:zk,LucideUtensils:hD,LucideUtensilsCrossed:uD,LucideUtilityPole:CSe,LucideVariable:kq,LucideVault:ASe,LucideVegan:ESe,LucideVenetianMask:TSe,LucideVerified:TC,LucideVibrate:PSe,LucideVibrateOff:MSe,LucideVideo:Wr,LucideVideoOff:LSe,LucideVideotape:ISe,LucideView:RSe,LucideVoicemail:DSe,LucideVolleyball:OSe,LucideVolume:BSe,LucideVolume1:FSe,LucideVolume2:gQ,LucideVolumeOff:zSe,LucideVolumeX:xQ,LucideVote:USe,LucideWallet:yQ,LucideWallet2:mD,LucideWalletCards:qSe,LucideWalletMinimal:mD,LucideWallpaper:$Se,LucideWand:VSe,LucideWand2:Lg,LucideWandSparkles:Lg,LucideWarehouse:HSe,LucideWashingMachine:GSe,LucideWatch:WSe,LucideWaves:KSe,LucideWaypoints:YSe,LucideWebcam:ZSe,LucideWebhook:QSe,LucideWebhookOff:XSe,LucideWeight:JSe,LucideWheat:t5e,LucideWheatOff:e5e,LucideWholeWord:s5e,LucideWifi:o5e,LucideWifiHigh:n5e,LucideWifiLow:r5e,LucideWifiOff:a5e,LucideWifiZero:i5e,LucideWind:c5e,LucideWindArrowDown:l5e,LucideWine:u5e,LucideWineOff:d5e,LucideWorkflow:$F,LucideWorm:h5e,LucideWrapText:m5e,LucideWrench:O4,LucideX:er,LucideXCircle:ou,LucideXOctagon:F8,LucideXSquare:QR,LucideYoutube:Sq,LucideZap:Af,LucideZapOff:p5e,LucideZoomIn:OM,LucideZoomOut:Cq,Luggage:rbe,LuggageIcon:rbe,MSquare:PR,MSquareIcon:PR,Magnet:abe,MagnetIcon:abe,Mail:ln,MailCheck:rq,MailCheckIcon:rq,MailIcon:ln,MailMinus:ibe,MailMinusIcon:ibe,MailOpen:GX,MailOpenIcon:GX,MailPlus:WX,MailPlusIcon:WX,MailQuestion:obe,MailQuestionIcon:obe,MailSearch:lbe,MailSearchIcon:lbe,MailWarning:cbe,MailWarningIcon:cbe,MailX:TM,MailXIcon:TM,Mailbox:dbe,MailboxIcon:dbe,Mails:ube,MailsIcon:ube,Map:MF,MapIcon:MF,MapPin:ni,MapPinCheck:mbe,MapPinCheckIcon:mbe,MapPinCheckInside:hbe,MapPinCheckInsideIcon:hbe,MapPinHouse:pbe,MapPinHouseIcon:pbe,MapPinIcon:ni,MapPinMinus:gbe,MapPinMinusIcon:gbe,MapPinMinusInside:fbe,MapPinMinusInsideIcon:fbe,MapPinOff:xbe,MapPinOffIcon:xbe,MapPinPlus:vbe,MapPinPlusIcon:vbe,MapPinPlusInside:ybe,MapPinPlusInsideIcon:ybe,MapPinX:_be,MapPinXIcon:_be,MapPinXInside:bbe,MapPinXInsideIcon:bbe,MapPinned:wbe,MapPinnedIcon:wbe,Martini:jbe,MartiniIcon:jbe,Maximize:PF,Maximize2:KX,Maximize2Icon:KX,MaximizeIcon:PF,Medal:CA,MedalIcon:CA,Megaphone:Th,MegaphoneIcon:Th,MegaphoneOff:Nbe,MegaphoneOffIcon:Nbe,Meh:kbe,MehIcon:kbe,MemoryStick:Sbe,MemoryStickIcon:Sbe,Menu:AA,MenuIcon:AA,MenuSquare:LR,MenuSquareIcon:LR,Merge:Cbe,MergeIcon:Cbe,MessageCircle:vu,MessageCircleCode:Abe,MessageCircleCodeIcon:Abe,MessageCircleDashed:Ebe,MessageCircleDashedIcon:Ebe,MessageCircleHeart:aq,MessageCircleHeartIcon:aq,MessageCircleIcon:vu,MessageCircleMore:Tbe,MessageCircleMoreIcon:Tbe,MessageCircleOff:Mbe,MessageCircleOffIcon:Mbe,MessageCirclePlus:Pbe,MessageCirclePlusIcon:Pbe,MessageCircleQuestion:YX,MessageCircleQuestionIcon:YX,MessageCircleReply:Lbe,MessageCircleReplyIcon:Lbe,MessageCircleWarning:Ibe,MessageCircleWarningIcon:Ibe,MessageCircleX:Rbe,MessageCircleXIcon:Rbe,MessageSquare:Ki,MessageSquareCode:Dbe,MessageSquareCodeIcon:Dbe,MessageSquareDashed:Obe,MessageSquareDashedIcon:Obe,MessageSquareDiff:Fbe,MessageSquareDiffIcon:Fbe,MessageSquareDot:zbe,MessageSquareDotIcon:zbe,MessageSquareHeart:Bbe,MessageSquareHeartIcon:Bbe,MessageSquareIcon:Ki,MessageSquareLock:Ube,MessageSquareLockIcon:Ube,MessageSquareMore:ZX,MessageSquareMoreIcon:ZX,MessageSquareOff:qbe,MessageSquareOffIcon:qbe,MessageSquarePlus:p4,MessageSquarePlusIcon:p4,MessageSquareQuote:EA,MessageSquareQuoteIcon:EA,MessageSquareReply:XX,MessageSquareReplyIcon:XX,MessageSquareShare:$be,MessageSquareShareIcon:$be,MessageSquareText:Vbe,MessageSquareTextIcon:Vbe,MessageSquareWarning:Hbe,MessageSquareWarningIcon:Hbe,MessageSquareX:Gbe,MessageSquareXIcon:Gbe,MessagesSquare:QX,MessagesSquareIcon:QX,Mic:LF,Mic2:R8,Mic2Icon:R8,MicIcon:LF,MicOff:Wbe,MicOffIcon:Wbe,MicVocal:R8,MicVocalIcon:R8,Microchip:Kbe,MicrochipIcon:Kbe,Microscope:Ybe,MicroscopeIcon:Ybe,Microwave:Zbe,MicrowaveIcon:Zbe,Milestone:Xbe,MilestoneIcon:Xbe,Milk:Jbe,MilkIcon:Jbe,MilkOff:Qbe,MilkOffIcon:Qbe,Minimize:t_e,Minimize2:e_e,Minimize2Icon:e_e,MinimizeIcon:t_e,Minus:Z2,MinusCircle:QI,MinusCircleIcon:QI,MinusIcon:Z2,MinusSquare:IR,MinusSquareIcon:IR,Monitor:X2,MonitorCheck:s_e,MonitorCheckIcon:s_e,MonitorCog:n_e,MonitorCogIcon:n_e,MonitorDot:r_e,MonitorDotIcon:r_e,MonitorDown:a_e,MonitorDownIcon:a_e,MonitorIcon:X2,MonitorOff:i_e,MonitorOffIcon:i_e,MonitorPause:o_e,MonitorPauseIcon:o_e,MonitorPlay:iq,MonitorPlayIcon:iq,MonitorSmartphone:l_e,MonitorSmartphoneIcon:l_e,MonitorSpeaker:c_e,MonitorSpeakerIcon:c_e,MonitorStop:d_e,MonitorStopIcon:d_e,MonitorUp:IF,MonitorUpIcon:IF,MonitorX:u_e,MonitorXIcon:u_e,Moon:m_e,MoonIcon:m_e,MoonStar:h_e,MoonStarIcon:h_e,MoreHorizontal:Z1,MoreHorizontalIcon:Z1,MoreVertical:ey,MoreVerticalIcon:ey,Mountain:f_e,MountainIcon:f_e,MountainSnow:p_e,MountainSnowIcon:p_e,Mouse:y_e,MouseIcon:y_e,MouseOff:g_e,MouseOffIcon:g_e,MousePointer:n0,MousePointer2:JX,MousePointer2Icon:JX,MousePointerBan:x_e,MousePointerBanIcon:x_e,MousePointerClick:Ch,MousePointerClickIcon:Ch,MousePointerIcon:n0,MousePointerSquareDashed:NR,MousePointerSquareDashedIcon:NR,Move:eQ,Move3D:D8,Move3DIcon:D8,Move3d:D8,Move3dIcon:D8,MoveDiagonal:b_e,MoveDiagonal2:v_e,MoveDiagonal2Icon:v_e,MoveDiagonalIcon:b_e,MoveDown:j_e,MoveDownIcon:j_e,MoveDownLeft:__e,MoveDownLeftIcon:__e,MoveDownRight:w_e,MoveDownRightIcon:w_e,MoveHorizontal:N_e,MoveHorizontalIcon:N_e,MoveIcon:eQ,MoveLeft:k_e,MoveLeftIcon:k_e,MoveRight:S_e,MoveRightIcon:S_e,MoveUp:E_e,MoveUpIcon:E_e,MoveUpLeft:C_e,MoveUpLeftIcon:C_e,MoveUpRight:A_e,MoveUpRightIcon:A_e,MoveVertical:T_e,MoveVerticalIcon:T_e,Music:oq,Music2:M_e,Music2Icon:M_e,Music3:P_e,Music3Icon:P_e,Music4:L_e,Music4Icon:L_e,MusicIcon:oq,Navigation:tQ,Navigation2:R_e,Navigation2Icon:R_e,Navigation2Off:I_e,Navigation2OffIcon:I_e,NavigationIcon:tQ,NavigationOff:D_e,NavigationOffIcon:D_e,Network:O_e,NetworkIcon:O_e,Newspaper:Q2,NewspaperIcon:Q2,Nfc:F_e,NfcIcon:F_e,Notebook:q_e,NotebookIcon:q_e,NotebookPen:z_e,NotebookPenIcon:z_e,NotebookTabs:B_e,NotebookTabsIcon:B_e,NotebookText:U_e,NotebookTextIcon:U_e,NotepadText:V_e,NotepadTextDashed:$_e,NotepadTextDashedIcon:$_e,NotepadTextIcon:V_e,Nut:G_e,NutIcon:G_e,NutOff:H_e,NutOffIcon:H_e,Octagon:K_e,OctagonAlert:Fk,OctagonAlertIcon:Fk,OctagonIcon:K_e,OctagonMinus:W_e,OctagonMinusIcon:W_e,OctagonPause:O8,OctagonPauseIcon:O8,OctagonX:F8,OctagonXIcon:F8,Omega:Y_e,OmegaIcon:Y_e,Option:Z_e,OptionIcon:Z_e,Orbit:X_e,OrbitIcon:X_e,Origami:Q_e,OrigamiIcon:Q_e,Outdent:T8,OutdentIcon:T8,Package:dh,Package2:J_e,Package2Icon:J_e,PackageCheck:ewe,PackageCheckIcon:ewe,PackageIcon:dh,PackageMinus:twe,PackageMinusIcon:twe,PackageOpen:swe,PackageOpenIcon:swe,PackagePlus:nwe,PackagePlusIcon:nwe,PackageSearch:rwe,PackageSearchIcon:rwe,PackageX:awe,PackageXIcon:awe,PaintBucket:iwe,PaintBucketIcon:iwe,PaintRoller:owe,PaintRollerIcon:owe,Paintbrush:lwe,Paintbrush2:z8,Paintbrush2Icon:z8,PaintbrushIcon:lwe,PaintbrushVertical:z8,PaintbrushVerticalIcon:z8,Palette:$c,PaletteIcon:$c,Palmtree:sD,PalmtreeIcon:sD,PanelBottom:uwe,PanelBottomClose:cwe,PanelBottomCloseIcon:cwe,PanelBottomDashed:B8,PanelBottomDashedIcon:B8,PanelBottomIcon:uwe,PanelBottomInactive:B8,PanelBottomInactiveIcon:B8,PanelBottomOpen:dwe,PanelBottomOpenIcon:dwe,PanelLeft:V8,PanelLeftClose:U8,PanelLeftCloseIcon:U8,PanelLeftDashed:q8,PanelLeftDashedIcon:q8,PanelLeftIcon:V8,PanelLeftInactive:q8,PanelLeftInactiveIcon:q8,PanelLeftOpen:$8,PanelLeftOpenIcon:$8,PanelRight:pwe,PanelRightClose:hwe,PanelRightCloseIcon:hwe,PanelRightDashed:H8,PanelRightDashedIcon:H8,PanelRightIcon:pwe,PanelRightInactive:H8,PanelRightInactiveIcon:H8,PanelRightOpen:mwe,PanelRightOpenIcon:mwe,PanelTop:xwe,PanelTopClose:fwe,PanelTopCloseIcon:fwe,PanelTopDashed:G8,PanelTopDashedIcon:G8,PanelTopIcon:xwe,PanelTopInactive:G8,PanelTopInactiveIcon:G8,PanelTopOpen:gwe,PanelTopOpenIcon:gwe,PanelsLeftBottom:ywe,PanelsLeftBottomIcon:ywe,PanelsLeftRight:zT,PanelsLeftRightIcon:zT,PanelsRightBottom:vwe,PanelsRightBottomIcon:vwe,PanelsTopBottom:X8,PanelsTopBottomIcon:X8,PanelsTopLeft:LC,PanelsTopLeftIcon:LC,Paperclip:MM,PaperclipIcon:MM,Parentheses:bwe,ParenthesesIcon:bwe,ParkingCircle:e8,ParkingCircleIcon:e8,ParkingCircleOff:JI,ParkingCircleOffIcon:JI,ParkingMeter:_we,ParkingMeterIcon:_we,ParkingSquare:OR,ParkingSquareIcon:OR,ParkingSquareOff:DR,ParkingSquareOffIcon:DR,PartyPopper:Wg,PartyPopperIcon:Wg,Pause:uv,PauseCircle:t8,PauseCircleIcon:t8,PauseIcon:uv,PauseOctagon:O8,PauseOctagonIcon:O8,PawPrint:wwe,PawPrintIcon:wwe,PcCase:jwe,PcCaseIcon:jwe,Pen:C2,PenBox:sp,PenBoxIcon:sp,PenIcon:C2,PenLine:Pg,PenLineIcon:Pg,PenOff:Nwe,PenOffIcon:Nwe,PenSquare:sp,PenSquareIcon:sp,PenTool:TA,PenToolIcon:TA,Pencil:ri,PencilIcon:ri,PencilLine:lq,PencilLineIcon:lq,PencilOff:kwe,PencilOffIcon:kwe,PencilRuler:Swe,PencilRulerIcon:Swe,Pentagon:Cwe,PentagonIcon:Cwe,Percent:PM,PercentCircle:s8,PercentCircleIcon:s8,PercentDiamond:f8,PercentDiamondIcon:f8,PercentIcon:PM,PercentSquare:FR,PercentSquareIcon:FR,PersonStanding:Awe,PersonStandingIcon:Awe,PhilippinePeso:Ewe,PhilippinePesoIcon:Ewe,Phone:ba,PhoneCall:sQ,PhoneCallIcon:sQ,PhoneForwarded:Twe,PhoneForwardedIcon:Twe,PhoneIcon:ba,PhoneIncoming:Mwe,PhoneIncomingIcon:Mwe,PhoneMissed:Pwe,PhoneMissedIcon:Pwe,PhoneOff:Lwe,PhoneOffIcon:Lwe,PhoneOutgoing:Iwe,PhoneOutgoingIcon:Iwe,Pi:Rwe,PiIcon:Rwe,PiSquare:zR,PiSquareIcon:zR,Piano:Dwe,PianoIcon:Dwe,Pickaxe:Owe,PickaxeIcon:Owe,PictureInPicture:zwe,PictureInPicture2:Fwe,PictureInPicture2Icon:Fwe,PictureInPictureIcon:zwe,PieChart:DI,PieChartIcon:DI,PiggyBank:Bwe,PiggyBankIcon:Bwe,Pilcrow:$we,PilcrowIcon:$we,PilcrowLeft:Uwe,PilcrowLeftIcon:Uwe,PilcrowRight:qwe,PilcrowRightIcon:qwe,PilcrowSquare:BR,PilcrowSquareIcon:BR,Pill:Hwe,PillBottle:Vwe,PillBottleIcon:Vwe,PillIcon:Hwe,Pin:MA,PinIcon:MA,PinOff:nQ,PinOffIcon:nQ,Pipette:Gwe,PipetteIcon:Gwe,Pizza:Wwe,PizzaIcon:Wwe,Plane:rQ,PlaneIcon:rQ,PlaneLanding:Kwe,PlaneLandingIcon:Kwe,PlaneTakeoff:Ywe,PlaneTakeoffIcon:Ywe,Play:lu,PlayCircle:$h,PlayCircleIcon:$h,PlayIcon:lu,PlaySquare:UR,PlaySquareIcon:UR,Plug:J2,Plug2:Zwe,Plug2Icon:Zwe,PlugIcon:J2,PlugZap:W8,PlugZap2:W8,PlugZap2Icon:W8,PlugZapIcon:W8,Plus:an,PlusCircle:n8,PlusCircleIcon:n8,PlusIcon:an,PlusSquare:qR,PlusSquareIcon:qR,Pocket:Qwe,PocketIcon:Qwe,PocketKnife:Xwe,PocketKnifeIcon:Xwe,Podcast:Jwe,PodcastIcon:Jwe,Pointer:tje,PointerIcon:tje,PointerOff:eje,PointerOffIcon:eje,Popcorn:sje,PopcornIcon:sje,Popsicle:nje,PopsicleIcon:nje,PoundSterling:rje,PoundSterlingIcon:rje,Power:aQ,PowerCircle:r8,PowerCircleIcon:r8,PowerIcon:aQ,PowerOff:aje,PowerOffIcon:aje,PowerSquare:$R,PowerSquareIcon:$R,Presentation:hv,PresentationIcon:hv,Printer:PA,PrinterCheck:ije,PrinterCheckIcon:ije,PrinterIcon:PA,Projector:oje,ProjectorIcon:oje,Proportions:lje,ProportionsIcon:lje,Puzzle:cje,PuzzleIcon:cje,Pyramid:dje,PyramidIcon:dje,QrCode:Sf,QrCodeIcon:Sf,Quote:tS,QuoteIcon:tS,Rabbit:uje,RabbitIcon:uje,Radar:cq,RadarIcon:cq,Radiation:hje,RadiationIcon:hje,Radical:mje,RadicalIcon:mje,Radio:mv,RadioIcon:mv,RadioReceiver:pje,RadioReceiverIcon:pje,RadioTower:fje,RadioTowerIcon:fje,Radius:gje,RadiusIcon:gje,RailSymbol:xje,RailSymbolIcon:xje,Rainbow:yje,RainbowIcon:yje,Rat:vje,RatIcon:vje,Ratio:bje,RatioIcon:bje,Receipt:Eje,ReceiptCent:_je,ReceiptCentIcon:_je,ReceiptEuro:wje,ReceiptEuroIcon:wje,ReceiptIcon:Eje,ReceiptIndianRupee:jje,ReceiptIndianRupeeIcon:jje,ReceiptJapaneseYen:Nje,ReceiptJapaneseYenIcon:Nje,ReceiptPoundSterling:kje,ReceiptPoundSterlingIcon:kje,ReceiptRussianRuble:Sje,ReceiptRussianRubleIcon:Sje,ReceiptSwissFranc:Cje,ReceiptSwissFrancIcon:Cje,ReceiptText:Aje,ReceiptTextIcon:Aje,RectangleEllipsis:K8,RectangleEllipsisIcon:K8,RectangleHorizontal:Tje,RectangleHorizontalIcon:Tje,RectangleVertical:Mje,RectangleVerticalIcon:Mje,Recycle:Pje,RecycleIcon:Pje,Redo:LA,Redo2:Lje,Redo2Icon:Lje,RedoDot:Ije,RedoDotIcon:Ije,RedoIcon:LA,RefreshCcw:dq,RefreshCcwDot:Rje,RefreshCcwDotIcon:Rje,RefreshCcwIcon:dq,RefreshCw:no,RefreshCwIcon:no,RefreshCwOff:Dje,RefreshCwOffIcon:Dje,Refrigerator:Oje,RefrigeratorIcon:Oje,Regex:Fje,RegexIcon:Fje,RemoveFormatting:zje,RemoveFormattingIcon:zje,Repeat:IA,Repeat1:Bje,Repeat1Icon:Bje,Repeat2:iQ,Repeat2Icon:iQ,RepeatIcon:IA,Replace:qje,ReplaceAll:Uje,ReplaceAllIcon:Uje,ReplaceIcon:qje,Reply:uq,ReplyAll:$je,ReplyAllIcon:$je,ReplyIcon:uq,Rewind:Vje,RewindIcon:Vje,Ribbon:Hje,RibbonIcon:Hje,Rocket:pv,RocketIcon:pv,RockingChair:Gje,RockingChairIcon:Gje,RollerCoaster:Wje,RollerCoasterIcon:Wje,Rotate3D:Y8,Rotate3DIcon:Y8,Rotate3d:Y8,Rotate3dIcon:Y8,RotateCcw:Kg,RotateCcwIcon:Kg,RotateCcwSquare:Kje,RotateCcwSquareIcon:Kje,RotateCw:RF,RotateCwIcon:RF,RotateCwSquare:Yje,RotateCwSquareIcon:Yje,Route:hq,RouteIcon:hq,RouteOff:Zje,RouteOffIcon:Zje,Router:Xje,RouterIcon:Xje,Rows:Z8,Rows2:Z8,Rows2Icon:Z8,Rows3:X8,Rows3Icon:X8,Rows4:Qje,Rows4Icon:Qje,RowsIcon:Z8,Rss:Jje,RssIcon:Jje,Ruler:I4,RulerIcon:I4,RussianRuble:e2e,RussianRubleIcon:e2e,Sailboat:t2e,SailboatIcon:t2e,Salad:s2e,SaladIcon:s2e,Sandwich:n2e,SandwichIcon:n2e,Satellite:a2e,SatelliteDish:r2e,SatelliteDishIcon:r2e,SatelliteIcon:a2e,Save:Ho,SaveAll:i2e,SaveAllIcon:i2e,SaveIcon:Ho,SaveOff:o2e,SaveOffIcon:o2e,Scale:l2e,Scale3D:Q8,Scale3DIcon:Q8,Scale3d:Q8,Scale3dIcon:Q8,ScaleIcon:l2e,Scaling:c2e,ScalingIcon:c2e,Scan:x2e,ScanBarcode:d2e,ScanBarcodeIcon:d2e,ScanEye:u2e,ScanEyeIcon:u2e,ScanFace:h2e,ScanFaceIcon:h2e,ScanIcon:x2e,ScanLine:m2e,ScanLineIcon:m2e,ScanQrCode:p2e,ScanQrCodeIcon:p2e,ScanSearch:f2e,ScanSearchIcon:f2e,ScanText:g2e,ScanTextIcon:g2e,ScatterChart:OI,ScatterChartIcon:OI,School:y2e,School2:rD,School2Icon:rD,SchoolIcon:y2e,Scissors:b2e,ScissorsIcon:b2e,ScissorsLineDashed:v2e,ScissorsLineDashedIcon:v2e,ScissorsSquare:VR,ScissorsSquareDashedBottom:gR,ScissorsSquareDashedBottomIcon:gR,ScissorsSquareIcon:VR,ScreenShare:w2e,ScreenShareIcon:w2e,ScreenShareOff:_2e,ScreenShareOffIcon:_2e,Scroll:j2e,ScrollIcon:j2e,ScrollText:mq,ScrollTextIcon:mq,Search:Fr,SearchCheck:N2e,SearchCheckIcon:N2e,SearchCode:k2e,SearchCodeIcon:k2e,SearchIcon:Fr,SearchSlash:S2e,SearchSlashIcon:S2e,SearchX:pq,SearchXIcon:pq,Section:C2e,SectionIcon:C2e,Send:$r,SendHorizonal:J8,SendHorizonalIcon:J8,SendHorizontal:J8,SendHorizontalIcon:J8,SendIcon:$r,SendToBack:A2e,SendToBackIcon:A2e,SeparatorHorizontal:E2e,SeparatorHorizontalIcon:E2e,SeparatorVertical:T2e,SeparatorVerticalIcon:T2e,Server:I2e,ServerCog:M2e,ServerCogIcon:M2e,ServerCrash:P2e,ServerCrashIcon:P2e,ServerIcon:I2e,ServerOff:L2e,ServerOffIcon:L2e,Settings:qc,Settings2:R4,Settings2Icon:R4,SettingsIcon:qc,Shapes:R2e,ShapesIcon:R2e,Share:oQ,Share2:jd,Share2Icon:jd,ShareIcon:oQ,Sheet:D2e,SheetIcon:D2e,Shell:O2e,ShellIcon:O2e,Shield:Im,ShieldAlert:fq,ShieldAlertIcon:fq,ShieldBan:F2e,ShieldBanIcon:F2e,ShieldCheck:cg,ShieldCheckIcon:cg,ShieldClose:eR,ShieldCloseIcon:eR,ShieldEllipsis:z2e,ShieldEllipsisIcon:z2e,ShieldHalf:B2e,ShieldHalfIcon:B2e,ShieldIcon:Im,ShieldMinus:U2e,ShieldMinusIcon:U2e,ShieldOff:DF,ShieldOffIcon:DF,ShieldPlus:q2e,ShieldPlusIcon:q2e,ShieldQuestion:OF,ShieldQuestionIcon:OF,ShieldX:eR,ShieldXIcon:eR,Ship:V2e,ShipIcon:V2e,ShipWheel:$2e,ShipWheelIcon:$2e,Shirt:H2e,ShirtIcon:H2e,ShoppingBag:D4,ShoppingBagIcon:D4,ShoppingBasket:G2e,ShoppingBasketIcon:G2e,ShoppingCart:sS,ShoppingCartIcon:sS,Shovel:W2e,ShovelIcon:W2e,ShowerHead:K2e,ShowerHeadIcon:K2e,Shrink:Y2e,ShrinkIcon:Y2e,Shrub:Z2e,ShrubIcon:Z2e,Shuffle:FF,ShuffleIcon:FF,Sidebar:V8,SidebarClose:U8,SidebarCloseIcon:U8,SidebarIcon:V8,SidebarOpen:$8,SidebarOpenIcon:$8,Sigma:X2e,SigmaIcon:X2e,SigmaSquare:HR,SigmaSquareIcon:HR,Signal:sNe,SignalHigh:Q2e,SignalHighIcon:Q2e,SignalIcon:sNe,SignalLow:J2e,SignalLowIcon:J2e,SignalMedium:eNe,SignalMediumIcon:eNe,SignalZero:tNe,SignalZeroIcon:tNe,Signature:nNe,SignatureIcon:nNe,Signpost:aNe,SignpostBig:rNe,SignpostBigIcon:rNe,SignpostIcon:aNe,Siren:iNe,SirenIcon:iNe,SkipBack:oNe,SkipBackIcon:oNe,SkipForward:lQ,SkipForwardIcon:lQ,Skull:lNe,SkullIcon:lNe,Slack:cNe,SlackIcon:cNe,Slash:dNe,SlashIcon:dNe,SlashSquare:GR,SlashSquareIcon:GR,Slice:uNe,SliceIcon:uNe,Sliders:tR,SlidersHorizontal:LM,SlidersHorizontalIcon:LM,SlidersIcon:tR,SlidersVertical:tR,SlidersVerticalIcon:tR,Smartphone:i1,SmartphoneCharging:hNe,SmartphoneChargingIcon:hNe,SmartphoneIcon:i1,SmartphoneNfc:mNe,SmartphoneNfcIcon:mNe,Smile:fNe,SmileIcon:fNe,SmilePlus:pNe,SmilePlusIcon:pNe,Snail:gNe,SnailIcon:gNe,Snowflake:$w,SnowflakeIcon:$w,Sofa:gq,SofaIcon:gq,SortAsc:vI,SortAscIcon:vI,SortDesc:gI,SortDescIcon:gI,Soup:xNe,SoupIcon:xNe,Space:yNe,SpaceIcon:yNe,Spade:vNe,SpadeIcon:vNe,Sparkle:IM,SparkleIcon:IM,Sparkles:cn,SparklesIcon:cn,Speaker:bNe,SpeakerIcon:bNe,Speech:_Ne,SpeechIcon:_Ne,SpellCheck:jNe,SpellCheck2:wNe,SpellCheck2Icon:wNe,SpellCheckIcon:jNe,Spline:NNe,SplineIcon:NNe,Split:kNe,SplitIcon:kNe,SplitSquareHorizontal:WR,SplitSquareHorizontalIcon:WR,SplitSquareVertical:KR,SplitSquareVerticalIcon:KR,SprayCan:SNe,SprayCanIcon:SNe,Sprout:RM,SproutIcon:RM,Square:db,SquareActivity:sR,SquareActivityIcon:sR,SquareArrowDown:aR,SquareArrowDownIcon:aR,SquareArrowDownLeft:nR,SquareArrowDownLeftIcon:nR,SquareArrowDownRight:rR,SquareArrowDownRightIcon:rR,SquareArrowLeft:iR,SquareArrowLeftIcon:iR,SquareArrowOutDownLeft:oR,SquareArrowOutDownLeftIcon:oR,SquareArrowOutDownRight:lR,SquareArrowOutDownRightIcon:lR,SquareArrowOutUpLeft:cR,SquareArrowOutUpLeftIcon:cR,SquareArrowOutUpRight:dR,SquareArrowOutUpRightIcon:dR,SquareArrowRight:uR,SquareArrowRightIcon:uR,SquareArrowUp:pR,SquareArrowUpIcon:pR,SquareArrowUpLeft:hR,SquareArrowUpLeftIcon:hR,SquareArrowUpRight:mR,SquareArrowUpRightIcon:mR,SquareAsterisk:fR,SquareAsteriskIcon:fR,SquareBottomDashedScissors:gR,SquareBottomDashedScissorsIcon:gR,SquareChartGantt:v5,SquareChartGanttIcon:v5,SquareCheck:xR,SquareCheckBig:t4,SquareCheckBigIcon:t4,SquareCheckIcon:xR,SquareChevronDown:yR,SquareChevronDownIcon:yR,SquareChevronLeft:vR,SquareChevronLeftIcon:vR,SquareChevronRight:bR,SquareChevronRightIcon:bR,SquareChevronUp:_R,SquareChevronUpIcon:_R,SquareCode:wR,SquareCodeIcon:wR,SquareDashed:kR,SquareDashedBottom:ANe,SquareDashedBottomCode:CNe,SquareDashedBottomCodeIcon:CNe,SquareDashedBottomIcon:ANe,SquareDashedIcon:kR,SquareDashedKanban:jR,SquareDashedKanbanIcon:jR,SquareDashedMousePointer:NR,SquareDashedMousePointerIcon:NR,SquareDivide:SR,SquareDivideIcon:SR,SquareDot:CR,SquareDotIcon:CR,SquareEqual:AR,SquareEqualIcon:AR,SquareFunction:ER,SquareFunctionIcon:ER,SquareGanttChart:v5,SquareGanttChartIcon:v5,SquareIcon:db,SquareKanban:TR,SquareKanbanIcon:TR,SquareLibrary:MR,SquareLibraryIcon:MR,SquareM:PR,SquareMIcon:PR,SquareMenu:LR,SquareMenuIcon:LR,SquareMinus:IR,SquareMinusIcon:IR,SquareMousePointer:RR,SquareMousePointerIcon:RR,SquareParking:OR,SquareParkingIcon:OR,SquareParkingOff:DR,SquareParkingOffIcon:DR,SquarePen:sp,SquarePenIcon:sp,SquarePercent:FR,SquarePercentIcon:FR,SquarePi:zR,SquarePiIcon:zR,SquarePilcrow:BR,SquarePilcrowIcon:BR,SquarePlay:UR,SquarePlayIcon:UR,SquarePlus:qR,SquarePlusIcon:qR,SquarePower:$R,SquarePowerIcon:$R,SquareRadical:ENe,SquareRadicalIcon:ENe,SquareScissors:VR,SquareScissorsIcon:VR,SquareSigma:HR,SquareSigmaIcon:HR,SquareSlash:GR,SquareSlashIcon:GR,SquareSplitHorizontal:WR,SquareSplitHorizontalIcon:WR,SquareSplitVertical:KR,SquareSplitVerticalIcon:KR,SquareSquare:TNe,SquareSquareIcon:TNe,SquareStack:MNe,SquareStackIcon:MNe,SquareTerminal:YR,SquareTerminalIcon:YR,SquareUser:XR,SquareUserIcon:XR,SquareUserRound:ZR,SquareUserRoundIcon:ZR,SquareX:QR,SquareXIcon:QR,Squircle:PNe,SquircleIcon:PNe,Squirrel:LNe,SquirrelIcon:LNe,Stamp:INe,StampIcon:INe,Star:Ua,StarHalf:RNe,StarHalfIcon:RNe,StarIcon:Ua,StarOff:DNe,StarOffIcon:DNe,Stars:cn,StarsIcon:cn,StepBack:ONe,StepBackIcon:ONe,StepForward:FNe,StepForwardIcon:FNe,Stethoscope:zNe,StethoscopeIcon:zNe,Sticker:BNe,StickerIcon:BNe,StickyNote:zF,StickyNoteIcon:zF,StopCircle:i8,StopCircleIcon:i8,Store:xq,StoreIcon:xq,StretchHorizontal:UNe,StretchHorizontalIcon:UNe,StretchVertical:qNe,StretchVerticalIcon:qNe,Strikethrough:cQ,StrikethroughIcon:cQ,Subscript:$Ne,SubscriptIcon:$Ne,Subtitles:kI,SubtitlesIcon:kI,Sun:eN,SunDim:VNe,SunDimIcon:VNe,SunIcon:eN,SunMedium:HNe,SunMediumIcon:HNe,SunMoon:GNe,SunMoonIcon:GNe,SunSnow:WNe,SunSnowIcon:WNe,Sunrise:KNe,SunriseIcon:KNe,Sunset:YNe,SunsetIcon:YNe,Superscript:ZNe,SuperscriptIcon:ZNe,SwatchBook:XNe,SwatchBookIcon:XNe,SwissFranc:QNe,SwissFrancIcon:QNe,SwitchCamera:JNe,SwitchCameraIcon:JNe,Sword:eke,SwordIcon:eke,Swords:tke,SwordsIcon:tke,Syringe:ske,SyringeIcon:ske,Table:vq,Table2:yq,Table2Icon:yq,TableCellsMerge:nke,TableCellsMergeIcon:nke,TableCellsSplit:rke,TableCellsSplitIcon:rke,TableColumnsSplit:ake,TableColumnsSplitIcon:ake,TableIcon:vq,TableOfContents:ike,TableOfContentsIcon:ike,TableProperties:oke,TablePropertiesIcon:oke,TableRowsSplit:lke,TableRowsSplitIcon:lke,Tablet:bq,TabletIcon:bq,TabletSmartphone:cke,TabletSmartphoneIcon:cke,Tablets:dke,TabletsIcon:dke,Tag:Cf,TagIcon:Cf,Tags:dQ,TagsIcon:dQ,Tally1:uke,Tally1Icon:uke,Tally2:hke,Tally2Icon:hke,Tally3:mke,Tally3Icon:mke,Tally4:pke,Tally4Icon:pke,Tally5:fke,Tally5Icon:fke,Tangent:gke,TangentIcon:gke,Target:Gu,TargetIcon:Gu,Telescope:xke,TelescopeIcon:xke,Tent:vke,TentIcon:vke,TentTree:yke,TentTreeIcon:yke,Terminal:bke,TerminalIcon:bke,TerminalSquare:YR,TerminalSquareIcon:YR,TestTube:_ke,TestTube2:JR,TestTube2Icon:JR,TestTubeDiagonal:JR,TestTubeDiagonalIcon:JR,TestTubeIcon:_ke,TestTubes:wke,TestTubesIcon:wke,Text:Ske,TextCursor:jke,TextCursorIcon:jke,TextCursorInput:_q,TextCursorInputIcon:_q,TextIcon:Ske,TextQuote:Nke,TextQuoteIcon:Nke,TextSearch:kke,TextSearchIcon:kke,TextSelect:eD,TextSelectIcon:eD,TextSelection:eD,TextSelectionIcon:eD,Theater:Cke,TheaterIcon:Cke,Thermometer:Tke,ThermometerIcon:Tke,ThermometerSnowflake:Ake,ThermometerSnowflakeIcon:Ake,ThermometerSun:Eke,ThermometerSunIcon:Eke,ThumbsDown:uQ,ThumbsDownIcon:uQ,ThumbsUp:wx,ThumbsUpIcon:wx,Ticket:BF,TicketCheck:Mke,TicketCheckIcon:Mke,TicketIcon:BF,TicketMinus:Pke,TicketMinusIcon:Pke,TicketPercent:Lke,TicketPercentIcon:Lke,TicketPlus:Ike,TicketPlusIcon:Ike,TicketSlash:Rke,TicketSlashIcon:Rke,TicketX:Dke,TicketXIcon:Dke,Tickets:Fke,TicketsIcon:Fke,TicketsPlane:Oke,TicketsPlaneIcon:Oke,Timer:Uke,TimerIcon:Uke,TimerOff:zke,TimerOffIcon:zke,TimerReset:Bke,TimerResetIcon:Bke,ToggleLeft:qke,ToggleLeftIcon:qke,ToggleRight:$ke,ToggleRightIcon:$ke,Toilet:Vke,ToiletIcon:Vke,Tornado:Hke,TornadoIcon:Hke,Torus:Gke,TorusIcon:Gke,Touchpad:Kke,TouchpadIcon:Kke,TouchpadOff:Wke,TouchpadOffIcon:Wke,TowerControl:Yke,TowerControlIcon:Yke,ToyBrick:Zke,ToyBrickIcon:Zke,Tractor:Xke,TractorIcon:Xke,TrafficCone:Qke,TrafficConeIcon:Qke,Train:tD,TrainFront:eSe,TrainFrontIcon:eSe,TrainFrontTunnel:Jke,TrainFrontTunnelIcon:Jke,TrainIcon:tD,TrainTrack:tSe,TrainTrackIcon:tSe,TramFront:tD,TramFrontIcon:tD,Trash:sSe,Trash2:In,Trash2Icon:In,TrashIcon:sSe,TreeDeciduous:nSe,TreeDeciduousIcon:nSe,TreePalm:sD,TreePalmIcon:sD,TreePine:DM,TreePineIcon:DM,Trees:rSe,TreesIcon:rSe,Trello:aSe,TrelloIcon:aSe,TrendingDown:nS,TrendingDownIcon:nS,TrendingUp:rc,TrendingUpDown:iSe,TrendingUpDownIcon:iSe,TrendingUpIcon:rc,Triangle:lSe,TriangleAlert:tc,TriangleAlertIcon:tc,TriangleIcon:lSe,TriangleRight:oSe,TriangleRightIcon:oSe,Trophy:Al,TrophyIcon:Al,Truck:hQ,TruckIcon:hQ,Turtle:cSe,TurtleIcon:cSe,Tv:uSe,Tv2:nD,Tv2Icon:nD,TvIcon:uSe,TvMinimal:nD,TvMinimalIcon:nD,TvMinimalPlay:dSe,TvMinimalPlayIcon:dSe,Twitch:hSe,TwitchIcon:hSe,Twitter:mQ,TwitterIcon:mQ,Type:wq,TypeIcon:wq,TypeOutline:mSe,TypeOutlineIcon:mSe,Umbrella:fSe,UmbrellaIcon:fSe,UmbrellaOff:pSe,UmbrellaOffIcon:pSe,Underline:UF,UnderlineIcon:UF,Undo:RA,Undo2:pQ,Undo2Icon:pQ,UndoDot:gSe,UndoDotIcon:gSe,UndoIcon:RA,UnfoldHorizontal:xSe,UnfoldHorizontalIcon:xSe,UnfoldVertical:ySe,UnfoldVerticalIcon:ySe,Ungroup:vSe,UngroupIcon:vSe,University:rD,UniversityIcon:rD,Unlink:qF,Unlink2:bSe,Unlink2Icon:bSe,UnlinkIcon:qF,Unlock:I8,UnlockIcon:I8,UnlockKeyhole:L8,UnlockKeyholeIcon:L8,Unplug:jq,UnplugIcon:jq,Upload:qa,UploadCloud:h8,UploadCloudIcon:h8,UploadIcon:qa,Usb:_Se,UsbIcon:_Se,User:So,User2:dD,User2Icon:dD,UserCheck:tN,UserCheck2:aD,UserCheck2Icon:aD,UserCheckIcon:tN,UserCircle:l8,UserCircle2:o8,UserCircle2Icon:o8,UserCircleIcon:l8,UserCog:fQ,UserCog2:iD,UserCog2Icon:iD,UserCogIcon:fQ,UserIcon:So,UserMinus:Nq,UserMinus2:oD,UserMinus2Icon:oD,UserMinusIcon:Nq,UserPen:wSe,UserPenIcon:wSe,UserPlus:zl,UserPlus2:lD,UserPlus2Icon:lD,UserPlusIcon:zl,UserRound:dD,UserRoundCheck:aD,UserRoundCheckIcon:aD,UserRoundCog:iD,UserRoundCogIcon:iD,UserRoundIcon:dD,UserRoundMinus:oD,UserRoundMinusIcon:oD,UserRoundPen:jSe,UserRoundPenIcon:jSe,UserRoundPlus:lD,UserRoundPlusIcon:lD,UserRoundSearch:NSe,UserRoundSearchIcon:NSe,UserRoundX:cD,UserRoundXIcon:cD,UserSearch:kSe,UserSearchIcon:kSe,UserSquare:XR,UserSquare2:ZR,UserSquare2Icon:ZR,UserSquareIcon:XR,UserX:SSe,UserX2:cD,UserX2Icon:cD,UserXIcon:SSe,Users:Bn,Users2:zk,Users2Icon:zk,UsersIcon:Bn,UsersRound:zk,UsersRoundIcon:zk,Utensils:hD,UtensilsCrossed:uD,UtensilsCrossedIcon:uD,UtensilsIcon:hD,UtilityPole:CSe,UtilityPoleIcon:CSe,Variable:kq,VariableIcon:kq,Vault:ASe,VaultIcon:ASe,Vegan:ESe,VeganIcon:ESe,VenetianMask:TSe,VenetianMaskIcon:TSe,Verified:TC,VerifiedIcon:TC,Vibrate:PSe,VibrateIcon:PSe,VibrateOff:MSe,VibrateOffIcon:MSe,Video:Wr,VideoIcon:Wr,VideoOff:LSe,VideoOffIcon:LSe,Videotape:ISe,VideotapeIcon:ISe,View:RSe,ViewIcon:RSe,Voicemail:DSe,VoicemailIcon:DSe,Volleyball:OSe,VolleyballIcon:OSe,Volume:BSe,Volume1:FSe,Volume1Icon:FSe,Volume2:gQ,Volume2Icon:gQ,VolumeIcon:BSe,VolumeOff:zSe,VolumeOffIcon:zSe,VolumeX:xQ,VolumeXIcon:xQ,Vote:USe,VoteIcon:USe,Wallet:yQ,Wallet2:mD,Wallet2Icon:mD,WalletCards:qSe,WalletCardsIcon:qSe,WalletIcon:yQ,WalletMinimal:mD,WalletMinimalIcon:mD,Wallpaper:$Se,WallpaperIcon:$Se,Wand:VSe,Wand2:Lg,Wand2Icon:Lg,WandIcon:VSe,WandSparkles:Lg,WandSparklesIcon:Lg,Warehouse:HSe,WarehouseIcon:HSe,WashingMachine:GSe,WashingMachineIcon:GSe,Watch:WSe,WatchIcon:WSe,Waves:KSe,WavesIcon:KSe,Waypoints:YSe,WaypointsIcon:YSe,Webcam:ZSe,WebcamIcon:ZSe,Webhook:QSe,WebhookIcon:QSe,WebhookOff:XSe,WebhookOffIcon:XSe,Weight:JSe,WeightIcon:JSe,Wheat:t5e,WheatIcon:t5e,WheatOff:e5e,WheatOffIcon:e5e,WholeWord:s5e,WholeWordIcon:s5e,Wifi:o5e,WifiHigh:n5e,WifiHighIcon:n5e,WifiIcon:o5e,WifiLow:r5e,WifiLowIcon:r5e,WifiOff:a5e,WifiOffIcon:a5e,WifiZero:i5e,WifiZeroIcon:i5e,Wind:c5e,WindArrowDown:l5e,WindArrowDownIcon:l5e,WindIcon:c5e,Wine:u5e,WineIcon:u5e,WineOff:d5e,WineOffIcon:d5e,Workflow:$F,WorkflowIcon:$F,Worm:h5e,WormIcon:h5e,WrapText:m5e,WrapTextIcon:m5e,Wrench:O4,WrenchIcon:O4,X:er,XCircle:ou,XCircleIcon:ou,XIcon:er,XOctagon:F8,XOctagonIcon:F8,XSquare:QR,XSquareIcon:QR,Youtube:Sq,YoutubeIcon:Sq,Zap:Af,ZapIcon:Af,ZapOff:p5e,ZapOffIcon:p5e,ZoomIn:OM,ZoomInIcon:OM,ZoomOut:Cq,ZoomOutIcon:Cq,createLucideIcon:me,icons:rms},Symbol.toStringTag,{value:"Module"})),mZe="-",ams=s=>{const t=oms(s),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=s;return{getClassGroupId:l=>{const o=l.split(mZe);return o[0]===""&&o.length!==1&&o.shift(),WEt(o,t)||ims(l)},getConflictingClassGroupIds:(l,o)=>{const c=n[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},WEt=(s,t)=>{var l;if(s.length===0)return t.classGroupId;const n=s[0],r=t.nextPart.get(n),a=r?WEt(s.slice(1),r):void 0;if(a)return a;if(t.validators.length===0)return;const i=s.join(mZe);return(l=t.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},aut=/^\[(.+)\]$/,ims=s=>{if(aut.test(s)){const t=aut.exec(s)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},oms=s=>{const{theme:t,prefix:n}=s,r={nextPart:new Map,validators:[]};return cms(Object.entries(s.classGroups),n).forEach(([i,l])=>{yUe(l,r,i,t)}),r},yUe=(s,t,n,r)=>{s.forEach(a=>{if(typeof a=="string"){const i=a===""?t:iut(t,a);i.classGroupId=n;return}if(typeof a=="function"){if(lms(a)){yUe(a(r),t,n,r);return}t.validators.push({validator:a,classGroupId:n});return}Object.entries(a).forEach(([i,l])=>{yUe(l,iut(t,i),n,r)})})},iut=(s,t)=>{let n=s;return t.split(mZe).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},lms=s=>s.isThemeGetter,cms=(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,dms=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)}}},KEt="!",ums=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:p,baseClassName:f,maybePostfixModifierPosition:x}};return n?o=>n({className:o,parseClassName:l}):l},hms=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},mms=s=>({cache:dms(s.cacheSize),parseClassName:ums(s),...ams(s)}),pms=/\s+/,fms=(s,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:a}=t,i=[],l=s.trim().split(pms);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:u,hasImportantModifier:h,baseClassName:m,maybePostfixModifierPosition:p}=n(d);let f=!!p,x=r(f?m.substring(0,p):m);if(!x){if(!f){o=d+(o.length>0?" "+o:o);continue}if(x=r(m),!x){o=d+(o.length>0?" "+o:o);continue}f=!1}const y=hms(u).join(":"),v=h?y+KEt:y,b=v+x;if(i.includes(b))continue;i.push(b);const N=a(x,f);for(let S=0;S0?" "+o:o)}return o};function gms(){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=mms(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=fms(c,n);return a(c,u),u}return function(){return i(gms.apply(null,arguments))}}const Zm=s=>{const t=n=>n[s]||[];return t.isThemeGetter=!0,t},ZEt=/^\[(?:([a-z-]+):)?(.+)\]$/i,yms=/^\d+\/\d+$/,vms=new Set(["px","full","screen"]),bms=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,_ms=/\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$/,wms=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,jms=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Nms=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Z3=s=>Aq(s)||vms.has(s)||yms.test(s),JE=s=>nG(s,"length",Pms),Aq=s=>!!s&&!Number.isNaN(Number(s)),ADe=s=>nG(s,"number",Aq),FK=s=>!!s&&Number.isInteger(Number(s)),kms=s=>s.endsWith("%")&&Aq(s.slice(0,-1)),zc=s=>ZEt.test(s),eT=s=>bms.test(s),Sms=new Set(["length","size","percentage"]),Cms=s=>nG(s,Sms,XEt),Ams=s=>nG(s,"position",XEt),Ems=new Set(["image","url"]),Tms=s=>nG(s,Ems,Ims),Mms=s=>nG(s,"",Lms),zK=()=>!0,nG=(s,t,n)=>{const r=ZEt.exec(s);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1},Pms=s=>_ms.test(s)&&!wms.test(s),XEt=()=>!1,Lms=s=>jms.test(s),Ims=s=>Nms.test(s),Rms=()=>{const s=Zm("colors"),t=Zm("spacing"),n=Zm("blur"),r=Zm("brightness"),a=Zm("borderColor"),i=Zm("borderRadius"),l=Zm("borderSpacing"),o=Zm("borderWidth"),c=Zm("contrast"),d=Zm("grayscale"),u=Zm("hueRotate"),h=Zm("invert"),m=Zm("gap"),p=Zm("gradientColorStops"),f=Zm("gradientColorStopPositions"),x=Zm("inset"),y=Zm("margin"),v=Zm("opacity"),b=Zm("padding"),N=Zm("saturate"),S=Zm("scale"),A=Zm("sepia"),T=Zm("skew"),L=Zm("space"),M=Zm("translate"),I=()=>["auto","contain","none"],R=()=>["auto","hidden","clip","visible","scroll"],z=()=>["auto",zc,t],$=()=>[zc,t],H=()=>["",Z3,JE],V=()=>["auto",Aq,zc],K=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],Z=()=>["solid","dashed","dotted","double","none"],Q=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],le=()=>["start","end","center","between","around","evenly","stretch"],ue=()=>["","0",zc],se=()=>["auto","avoid","all","avoid-page","page","left","right","column"],ne=()=>[Aq,zc];return{cacheSize:500,separator:":",theme:{colors:[zK],spacing:[Z3,JE],blur:["none","",eT,zc],brightness:ne(),borderColor:[s],borderRadius:["none","","full",eT,zc],borderSpacing:$(),borderWidth:H(),contrast:ne(),grayscale:ue(),hueRotate:ne(),invert:ue(),gap:$(),gradientColorStops:[s],gradientColorStopPositions:[kms,JE],inset:z(),margin:z(),opacity:ne(),padding:$(),saturate:ne(),scale:ne(),sepia:ue(),skew:ne(),space:$(),translate:$()},classGroups:{aspect:[{aspect:["auto","square","video",zc]}],container:["container"],columns:[{columns:[eT]}],"break-after":[{"break-after":se()}],"break-before":[{"break-before":se()}],"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:[...K(),zc]}],overflow:[{overflow:R()}],"overflow-x":[{"overflow-x":R()}],"overflow-y":[{"overflow-y":R()}],overscroll:[{overscroll:I()}],"overscroll-x":[{"overscroll-x":I()}],"overscroll-y":[{"overscroll-y":I()}],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",FK,zc]}],basis:[{basis:z()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",zc]}],grow:[{grow:ue()}],shrink:[{shrink:ue()}],order:[{order:["first","last","none",FK,zc]}],"grid-cols":[{"grid-cols":[zK]}],"col-start-end":[{col:["auto",{span:["full",FK,zc]},zc]}],"col-start":[{"col-start":V()}],"col-end":[{"col-end":V()}],"grid-rows":[{"grid-rows":[zK]}],"row-start-end":[{row:["auto",{span:[FK,zc]},zc]}],"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",zc]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",zc]}],gap:[{gap:[m]}],"gap-x":[{"gap-x":[m]}],"gap-y":[{"gap-y":[m]}],"justify-content":[{justify:["normal",...le()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...le(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...le(),"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":[L]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[L]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",zc,t]}],"min-w":[{"min-w":[zc,t,"min","max","fit"]}],"max-w":[{"max-w":[zc,t,"none","full","min","max","fit","prose",{screen:[eT]},eT]}],h:[{h:[zc,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[zc,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[zc,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[zc,t,"auto","min","max","fit"]}],"font-size":[{text:["base",eT,JE]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",ADe]}],"font-family":[{font:[zK]}],"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",zc]}],"line-clamp":[{"line-clamp":["none",Aq,ADe]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Z3,zc]}],"list-image":[{"list-image":["none",zc]}],"list-style-type":[{list:["none","disc","decimal",zc]}],"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:[...Z(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Z3,JE]}],"underline-offset":[{"underline-offset":["auto",Z3,zc]}],"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:$()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",zc]}],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",zc]}],"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:[...K(),Ams]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",Cms]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},Tms]}],"bg-color":[{bg:[s]}],"gradient-from-pos":[{from:[f]}],"gradient-via-pos":[{via:[f]}],"gradient-to-pos":[{to:[f]}],"gradient-from":[{from:[p]}],"gradient-via":[{via:[p]}],"gradient-to":[{to:[p]}],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:[...Z(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[v]}],"divide-style":[{divide:Z()}],"border-color":[{border:[a]}],"border-color-x":[{"border-x":[a]}],"border-color-y":[{"border-y":[a]}],"border-color-s":[{"border-s":[a]}],"border-color-e":[{"border-e":[a]}],"border-color-t":[{"border-t":[a]}],"border-color-r":[{"border-r":[a]}],"border-color-b":[{"border-b":[a]}],"border-color-l":[{"border-l":[a]}],"divide-color":[{divide:[a]}],"outline-style":[{outline:["",...Z()]}],"outline-offset":[{"outline-offset":[Z3,zc]}],"outline-w":[{outline:[Z3,JE]}],"outline-color":[{outline:[s]}],"ring-w":[{ring:H()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[s]}],"ring-opacity":[{"ring-opacity":[v]}],"ring-offset-w":[{"ring-offset":[Z3,JE]}],"ring-offset-color":[{"ring-offset":[s]}],shadow:[{shadow:["","inner","none",eT,Mms]}],"shadow-color":[{shadow:[zK]}],opacity:[{opacity:[v]}],"mix-blend":[{"mix-blend":[...Q(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":Q()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",eT,zc]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[h]}],saturate:[{saturate:[N]}],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":[N]}],"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",zc]}],duration:[{duration:ne()}],ease:[{ease:["linear","in","out","in-out",zc]}],delay:[{delay:ne()}],animate:[{animate:["none","spin","ping","pulse","bounce",zc]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[S]}],"scale-x":[{"scale-x":[S]}],"scale-y":[{"scale-y":[S]}],rotate:[{rotate:[FK,zc]}],"translate-x":[{"translate-x":[M]}],"translate-y":[{"translate-y":[M]}],"skew-x":[{"skew-x":[T]}],"skew-y":[{"skew-y":[T]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",zc]}],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",zc]}],"caret-color":[{caret:[s]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":$()}],"scroll-mx":[{"scroll-mx":$()}],"scroll-my":[{"scroll-my":$()}],"scroll-ms":[{"scroll-ms":$()}],"scroll-me":[{"scroll-me":$()}],"scroll-mt":[{"scroll-mt":$()}],"scroll-mr":[{"scroll-mr":$()}],"scroll-mb":[{"scroll-mb":$()}],"scroll-ml":[{"scroll-ml":$()}],"scroll-p":[{"scroll-p":$()}],"scroll-px":[{"scroll-px":$()}],"scroll-py":[{"scroll-py":$()}],"scroll-ps":[{"scroll-ps":$()}],"scroll-pe":[{"scroll-pe":$()}],"scroll-pt":[{"scroll-pt":$()}],"scroll-pr":[{"scroll-pr":$()}],"scroll-pb":[{"scroll-pb":$()}],"scroll-pl":[{"scroll-pl":$()}],"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",zc]}],fill:[{fill:[s,"none"]}],"stroke-w":[{stroke:[Z3,JE,ADe]}],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"]}}},Dms=xms(Rms);function Mt(...s){return Dms(mc(s))}function Uh(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 out(s){const t=new Date(s);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(t)}function KJ(s){return s?s.replace(/<[^>]*>/g,""):""}const Oms=tms,QEt=j.forwardRef(({className:s,...t},n)=>e.jsx(FEt,{ref:n,className:Mt("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}));QEt.displayName=FEt.displayName;const Fms=u9("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"}}),JEt=j.forwardRef(({className:s,variant:t,...n},r)=>e.jsx(zEt,{ref:r,className:Mt(Fms({variant:t}),s),...n}));JEt.displayName=zEt.displayName;const zms=j.forwardRef(({className:s,...t},n)=>e.jsx(qEt,{ref:n,className:Mt("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}));zms.displayName=qEt.displayName;const eTt=j.forwardRef(({className:s,...t},n)=>e.jsx($Et,{ref:n,className:Mt("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(er,{className:"h-4 w-4"})}));eTt.displayName=$Et.displayName;const tTt=j.forwardRef(({className:s,...t},n)=>e.jsx(BEt,{ref:n,className:Mt("text-sm font-semibold",s),...t}));tTt.displayName=BEt.displayName;const sTt=j.forwardRef(({className:s,...t},n)=>e.jsx(UEt,{ref:n,className:Mt("text-sm opacity-90",s),...t}));sTt.displayName=UEt.displayName;function Bms(){const{toasts:s}=Ai();return e.jsxs(Oms,{children:[s.map(function({id:t,title:n,description:r,action:a,...i}){return e.jsxs(JEt,{...i,children:[e.jsxs("div",{className:"grid gap-1",children:[n&&e.jsx(tTt,{children:n}),r&&e.jsx(sTt,{children:r})]}),a,e.jsx(eTt,{})]},t)}),e.jsx(QEt,{})]})}var lut=["light","dark"],Ums="(prefers-color-scheme: dark)",qms=j.createContext(void 0),$ms={setTheme:s=>{},themes:[]},Vms=()=>{var s;return(s=j.useContext(qms))!=null?s:$ms};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(f=>`'${f}'`).join(",")})`};`:`var d=document.documentElement,n='${n}',s='setAttribute';`,h=a?lut.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",m=(f,x=!1,y=!0)=>{let v=l?l[f]:f,b=x?f+"|| ''":`'${v}'`,N="";return a&&y&&!x&&lut.includes(f)&&(N+=`d.style.colorScheme = '${f}';`),n==="class"?x||v?N+=`c.add(${b})`:N+="null":v&&(N+=`d[s](n,${b})`),N},p=s?`!function(){${u}${m(s)}}()`:r?`!function(){try{${u}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${Ums}',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:p}})});var Hms=s=>{switch(s){case"success":return Kms;case"info":return Zms;case"warning":return Yms;case"error":return Xms;default:return null}},Gms=Array(12).fill(0),Wms=({visible:s,className:t})=>Dt.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":s},Dt.createElement("div",{className:"sonner-spinner"},Gms.map((n,r)=>Dt.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),Kms=Dt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Dt.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"})),Yms=Dt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},Dt.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"})),Zms=Dt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Dt.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"})),Xms=Dt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Dt.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"})),Qms=Dt.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"},Dt.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Dt.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),Jms=()=>{let[s,t]=Dt.useState(document.hidden);return Dt.useEffect(()=>{let n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),s},vUe=1,eps=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:vUe++,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],Dt.isValidElement(d))i=!1,this.create({id:r,type:"default",message:d});else if(sps(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)||vUe++;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}},l_=new eps,tps=(s,t)=>{let n=(t==null?void 0:t.id)||vUe++;return l_.addToast({title:s,...t,id:n}),n},sps=s=>s&&typeof s=="object"&&"ok"in s&&typeof s.ok=="boolean"&&"status"in s&&typeof s.status=="number",nps=tps,rps=()=>l_.toasts,aps=()=>l_.getActiveToasts(),re=Object.assign(nps,{success:l_.success,info:l_.info,warning:l_.warning,error:l_.error,custom:l_.custom,message:l_.message,promise:l_.promise,dismiss:l_.dismiss,loading:l_.loading},{getHistory:rps,getToasts:aps});function ips(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))}ips(`: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 toe(s){return s.label!==void 0}var ops=3,lps="32px",cps="16px",cut=4e3,dps=356,ups=14,hps=20,mps=200;function ek(...s){return s.filter(Boolean).join(" ")}function pps(s){let[t,n]=s.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}var fps=s=>{var t,n,r,a,i,l,o,c,d,u,h;let{invert:m,toast:p,unstyled:f,interacting:x,setHeights:y,visibleToasts:v,heights:b,index:N,toasts:S,expanded:A,removeToast:T,defaultRichColors:L,closeButton:M,style:I,cancelButtonStyle:R,actionButtonStyle:z,className:$="",descriptionClassName:H="",duration:V,position:K,gap:Z,loadingIcon:Q,expandByDefault:le,classNames:ue,icons:se,closeButtonAriaLabel:ne="Close toast",pauseWhenPageIsHidden:ie}=s,[ce,je]=Dt.useState(null),[be,he]=Dt.useState(null),[ge,ke]=Dt.useState(!1),[Te,Me]=Dt.useState(!1),[Oe,Se]=Dt.useState(!1),[Qe,Ae]=Dt.useState(!1),[Fe,Ne]=Dt.useState(!1),[$e,Ve]=Dt.useState(0),[qe,Ze]=Dt.useState(0),Ue=Dt.useRef(p.duration||V||cut),Ye=Dt.useRef(null),Ge=Dt.useRef(null),He=N===0,tt=N+1<=v,pt=p.type,ft=p.dismissible!==!1,qt=p.className||"",Ut=p.descriptionClassName||"",Wt=Dt.useMemo(()=>b.findIndex(cr=>cr.toastId===p.id)||0,[b,p.id]),us=Dt.useMemo(()=>{var cr;return(cr=p.closeButton)!=null?cr:M},[p.closeButton,M]),zt=Dt.useMemo(()=>p.duration||V||cut,[p.duration,V]),bt=Dt.useRef(0),As=Dt.useRef(0),vt=Dt.useRef(0),Ws=Dt.useRef(null),[on,Ms]=K.split("-"),dn=Dt.useMemo(()=>b.reduce((cr,Hs,_r)=>_r>=Wt?cr:cr+Hs.height,0),[b,Wt]),rn=Jms(),br=p.invert||m,Gn=pt==="loading";As.current=Dt.useMemo(()=>Wt*Z+dn,[Wt,dn]),Dt.useEffect(()=>{Ue.current=zt},[zt]),Dt.useEffect(()=>{ke(!0)},[]),Dt.useEffect(()=>{let cr=Ge.current;if(cr){let Hs=cr.getBoundingClientRect().height;return Ze(Hs),y(_r=>[{toastId:p.id,height:Hs,position:p.position},..._r]),()=>y(_r=>_r.filter(nn=>nn.toastId!==p.id))}},[y,p.id]),Dt.useLayoutEffect(()=>{if(!ge)return;let cr=Ge.current,Hs=cr.style.height;cr.style.height="auto";let _r=cr.getBoundingClientRect().height;cr.style.height=Hs,Ze(_r),y(nn=>nn.find(Zn=>Zn.toastId===p.id)?nn.map(Zn=>Zn.toastId===p.id?{...Zn,height:_r}:Zn):[{toastId:p.id,height:_r,position:p.position},...nn])},[ge,p.title,p.description,y,p.id]);let On=Dt.useCallback(()=>{Me(!0),Ve(As.current),y(cr=>cr.filter(Hs=>Hs.toastId!==p.id)),setTimeout(()=>{T(p)},mps)},[p,T,y,As]);Dt.useEffect(()=>{if(p.promise&&pt==="loading"||p.duration===1/0||p.type==="loading")return;let cr;return A||x||ie&&rn?(()=>{if(vt.current{var Hs;(Hs=p.onAutoClose)==null||Hs.call(p,p),On()},Ue.current)),()=>clearTimeout(cr)},[A,x,p,pt,ie,rn,On]),Dt.useEffect(()=>{p.delete&&On()},[On,p.delete]);function Rr(){var cr,Hs,_r;return se!=null&&se.loading?Dt.createElement("div",{className:ek(ue==null?void 0:ue.loader,(cr=p==null?void 0:p.classNames)==null?void 0:cr.loader,"sonner-loader"),"data-visible":pt==="loading"},se.loading):Q?Dt.createElement("div",{className:ek(ue==null?void 0:ue.loader,(Hs=p==null?void 0:p.classNames)==null?void 0:Hs.loader,"sonner-loader"),"data-visible":pt==="loading"},Q):Dt.createElement(Wms,{className:ek(ue==null?void 0:ue.loader,(_r=p==null?void 0:p.classNames)==null?void 0:_r.loader),visible:pt==="loading"})}return Dt.createElement("li",{tabIndex:0,ref:Ge,className:ek($,qt,ue==null?void 0:ue.toast,(t=p==null?void 0:p.classNames)==null?void 0:t.toast,ue==null?void 0:ue.default,ue==null?void 0:ue[pt],(n=p==null?void 0:p.classNames)==null?void 0:n[pt]),"data-sonner-toast":"","data-rich-colors":(r=p.richColors)!=null?r:L,"data-styled":!(p.jsx||p.unstyled||f),"data-mounted":ge,"data-promise":!!p.promise,"data-swiped":Fe,"data-removed":Te,"data-visible":tt,"data-y-position":on,"data-x-position":Ms,"data-index":N,"data-front":He,"data-swiping":Oe,"data-dismissible":ft,"data-type":pt,"data-invert":br,"data-swipe-out":Qe,"data-swipe-direction":be,"data-expanded":!!(A||le&&ge),style:{"--index":N,"--toasts-before":N,"--z-index":S.length-N,"--offset":`${Te?$e:As.current}px`,"--initial-height":le?"auto":`${qe}px`,...I,...p.style},onDragEnd:()=>{Se(!1),je(null),Ws.current=null},onPointerDown:cr=>{Gn||!ft||(Ye.current=new Date,Ve(As.current),cr.target.setPointerCapture(cr.pointerId),cr.target.tagName!=="BUTTON"&&(Se(!0),Ws.current={x:cr.clientX,y:cr.clientY}))},onPointerUp:()=>{var cr,Hs,_r,nn;if(Qe||!ft)return;Ws.current=null;let Zn=Number(((cr=Ge.current)==null?void 0:cr.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),es=Number(((Hs=Ge.current)==null?void 0:Hs.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),ar=new Date().getTime()-((_r=Ye.current)==null?void 0:_r.getTime()),Hn=ce==="x"?Zn:es,kn=Math.abs(Hn)/ar;if(Math.abs(Hn)>=hps||kn>.11){Ve(As.current),(nn=p.onDismiss)==null||nn.call(p,p),he(ce==="x"?Zn>0?"right":"left":es>0?"down":"up"),On(),Ae(!0),Ne(!1);return}Se(!1),je(null)},onPointerMove:cr=>{var Hs,_r,nn,Zn;if(!Ws.current||!ft||((Hs=window.getSelection())==null?void 0:Hs.toString().length)>0)return;let es=cr.clientY-Ws.current.y,ar=cr.clientX-Ws.current.x,Hn=(_r=s.swipeDirections)!=null?_r:pps(K);!ce&&(Math.abs(ar)>1||Math.abs(es)>1)&&je(Math.abs(ar)>Math.abs(es)?"x":"y");let kn={x:0,y:0};ce==="y"?(Hn.includes("top")||Hn.includes("bottom"))&&(Hn.includes("top")&&es<0||Hn.includes("bottom")&&es>0)&&(kn.y=es):ce==="x"&&(Hn.includes("left")||Hn.includes("right"))&&(Hn.includes("left")&&ar<0||Hn.includes("right")&&ar>0)&&(kn.x=ar),(Math.abs(kn.x)>0||Math.abs(kn.y)>0)&&Ne(!0),(nn=Ge.current)==null||nn.style.setProperty("--swipe-amount-x",`${kn.x}px`),(Zn=Ge.current)==null||Zn.style.setProperty("--swipe-amount-y",`${kn.y}px`)}},us&&!p.jsx?Dt.createElement("button",{"aria-label":ne,"data-disabled":Gn,"data-close-button":!0,onClick:Gn||!ft?()=>{}:()=>{var cr;On(),(cr=p.onDismiss)==null||cr.call(p,p)},className:ek(ue==null?void 0:ue.closeButton,(a=p==null?void 0:p.classNames)==null?void 0:a.closeButton)},(i=se==null?void 0:se.close)!=null?i:Qms):null,p.jsx||j.isValidElement(p.title)?p.jsx?p.jsx:typeof p.title=="function"?p.title():p.title:Dt.createElement(Dt.Fragment,null,pt||p.icon||p.promise?Dt.createElement("div",{"data-icon":"",className:ek(ue==null?void 0:ue.icon,(l=p==null?void 0:p.classNames)==null?void 0:l.icon)},p.promise||p.type==="loading"&&!p.icon?p.icon||Rr():null,p.type!=="loading"?p.icon||(se==null?void 0:se[pt])||Hms(pt):null):null,Dt.createElement("div",{"data-content":"",className:ek(ue==null?void 0:ue.content,(o=p==null?void 0:p.classNames)==null?void 0:o.content)},Dt.createElement("div",{"data-title":"",className:ek(ue==null?void 0:ue.title,(c=p==null?void 0:p.classNames)==null?void 0:c.title)},typeof p.title=="function"?p.title():p.title),p.description?Dt.createElement("div",{"data-description":"",className:ek(H,Ut,ue==null?void 0:ue.description,(d=p==null?void 0:p.classNames)==null?void 0:d.description)},typeof p.description=="function"?p.description():p.description):null),j.isValidElement(p.cancel)?p.cancel:p.cancel&&toe(p.cancel)?Dt.createElement("button",{"data-button":!0,"data-cancel":!0,style:p.cancelButtonStyle||R,onClick:cr=>{var Hs,_r;toe(p.cancel)&&ft&&((_r=(Hs=p.cancel).onClick)==null||_r.call(Hs,cr),On())},className:ek(ue==null?void 0:ue.cancelButton,(u=p==null?void 0:p.classNames)==null?void 0:u.cancelButton)},p.cancel.label):null,j.isValidElement(p.action)?p.action:p.action&&toe(p.action)?Dt.createElement("button",{"data-button":!0,"data-action":!0,style:p.actionButtonStyle||z,onClick:cr=>{var Hs,_r;toe(p.action)&&((_r=(Hs=p.action).onClick)==null||_r.call(Hs,cr),!cr.defaultPrevented&&On())},className:ek(ue==null?void 0:ue.actionButton,(h=p==null?void 0:p.classNames)==null?void 0:h.actionButton)},p.action.label):null))};function dut(){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 gps(s,t){let n={};return[s,t].forEach((r,a)=>{let i=a===1,l=i?"--mobile-offset":"--offset",o=i?cps:lps;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 xps=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:p,visibleToasts:f=ops,toastOptions:x,dir:y=dut(),gap:v=ups,loadingIcon:b,icons:N,containerAriaLabel:S="Notifications",pauseWhenPageIsHidden:A}=s,[T,L]=Dt.useState([]),M=Dt.useMemo(()=>Array.from(new Set([r].concat(T.filter(ie=>ie.position).map(ie=>ie.position)))),[T,r]),[I,R]=Dt.useState([]),[z,$]=Dt.useState(!1),[H,V]=Dt.useState(!1),[K,Z]=Dt.useState(u!=="system"?u:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),Q=Dt.useRef(null),le=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),ue=Dt.useRef(null),se=Dt.useRef(!1),ne=Dt.useCallback(ie=>{L(ce=>{var je;return(je=ce.find(be=>be.id===ie.id))!=null&&je.delete||l_.dismiss(ie.id),ce.filter(({id:be})=>be!==ie.id)})},[]);return Dt.useEffect(()=>l_.subscribe(ie=>{if(ie.dismiss){L(ce=>ce.map(je=>je.id===ie.id?{...je,delete:!0}:je));return}setTimeout(()=>{oZe.flushSync(()=>{L(ce=>{let je=ce.findIndex(be=>be.id===ie.id);return je!==-1?[...ce.slice(0,je),{...ce[je],...ie},...ce.slice(je+1)]:[ie,...ce]})})})}),[]),Dt.useEffect(()=>{if(u!=="system"){Z(u);return}if(u==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?Z("dark"):Z("light")),typeof window>"u")return;let ie=window.matchMedia("(prefers-color-scheme: dark)");try{ie.addEventListener("change",({matches:ce})=>{Z(ce?"dark":"light")})}catch{ie.addListener(({matches:je})=>{try{Z(je?"dark":"light")}catch(be){console.error(be)}})}},[u]),Dt.useEffect(()=>{T.length<=1&&$(!1)},[T]),Dt.useEffect(()=>{let ie=ce=>{var je,be;a.every(he=>ce[he]||ce.code===he)&&($(!0),(je=Q.current)==null||je.focus()),ce.code==="Escape"&&(document.activeElement===Q.current||(be=Q.current)!=null&&be.contains(document.activeElement))&&$(!1)};return document.addEventListener("keydown",ie),()=>document.removeEventListener("keydown",ie)},[a]),Dt.useEffect(()=>{if(Q.current)return()=>{ue.current&&(ue.current.focus({preventScroll:!0}),ue.current=null,se.current=!1)}},[Q.current]),Dt.createElement("section",{ref:t,"aria-label":`${S} ${le}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},M.map((ie,ce)=>{var je;let[be,he]=ie.split("-");return T.length?Dt.createElement("ol",{key:ie,dir:y==="auto"?dut():y,tabIndex:-1,ref:Q,className:o,"data-sonner-toaster":!0,"data-theme":K,"data-y-position":be,"data-lifted":z&&T.length>1&&!i,"data-x-position":he,style:{"--front-toast-height":`${((je=I[0])==null?void 0:je.height)||0}px`,"--width":`${dps}px`,"--gap":`${v}px`,...p,...gps(c,d)},onBlur:ge=>{se.current&&!ge.currentTarget.contains(ge.relatedTarget)&&(se.current=!1,ue.current&&(ue.current.focus({preventScroll:!0}),ue.current=null))},onFocus:ge=>{ge.target instanceof HTMLElement&&ge.target.dataset.dismissible==="false"||se.current||(se.current=!0,ue.current=ge.relatedTarget)},onMouseEnter:()=>$(!0),onMouseMove:()=>$(!0),onMouseLeave:()=>{H||$(!1)},onDragEnd:()=>$(!1),onPointerDown:ge=>{ge.target instanceof HTMLElement&&ge.target.dataset.dismissible==="false"||V(!0)},onPointerUp:()=>V(!1)},T.filter(ge=>!ge.position&&ce===0||ge.position===ie).map((ge,ke)=>{var Te,Me;return Dt.createElement(fps,{key:ge.id,icons:N,index:ke,toast:ge,defaultRichColors:h,duration:(Te=x==null?void 0:x.duration)!=null?Te:m,className:x==null?void 0:x.className,descriptionClassName:x==null?void 0:x.descriptionClassName,invert:n,visibleToasts:f,closeButton:(Me=x==null?void 0:x.closeButton)!=null?Me:l,interacting:H,position:ie,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:ne,toasts:T.filter(Oe=>Oe.position==ge.position),heights:I.filter(Oe=>Oe.position==ge.position),setHeights:R,expandByDefault:i,gap:v,loadingIcon:b,expanded:z,pauseWhenPageIsHidden:A,swipeDirections:s.swipeDirections})})):null}))});const yps=({...s})=>{const{theme:t="system"}=Vms();return e.jsx(xps,{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 vps=gYe[" useId ".trim().toString()]||(()=>{}),bps=0;function jx(s){const[t,n]=j.useState(vps());return dg(()=>{n(r=>r??String(bps++))},[s]),t?`radix-${t}`:""}var EDe="focusScope.autoFocusOnMount",TDe="focusScope.autoFocusOnUnmount",uut={bubbles:!1,cancelable:!0},_ps="FocusScope",kne=j.forwardRef((s,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:a,onUnmountAutoFocus:i,...l}=s,[o,c]=j.useState(null),d=sg(a),u=sg(i),h=j.useRef(null),m=Uo(t,x=>c(x)),p=j.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;j.useEffect(()=>{if(r){let x=function(N){if(p.paused||!o)return;const S=N.target;o.contains(S)?h.current=S:_T(h.current,{select:!0})},y=function(N){if(p.paused||!o)return;const S=N.relatedTarget;S!==null&&(o.contains(S)||_T(h.current,{select:!0}))},v=function(N){if(document.activeElement===document.body)for(const A of N)A.removedNodes.length>0&&_T(o)};document.addEventListener("focusin",x),document.addEventListener("focusout",y);const b=new MutationObserver(v);return o&&b.observe(o,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",x),document.removeEventListener("focusout",y),b.disconnect()}}},[r,o,p.paused]),j.useEffect(()=>{if(o){mut.add(p);const x=document.activeElement;if(!o.contains(x)){const v=new CustomEvent(EDe,uut);o.addEventListener(EDe,d),o.dispatchEvent(v),v.defaultPrevented||(wps(Cps(nTt(o)),{select:!0}),document.activeElement===x&&_T(o))}return()=>{o.removeEventListener(EDe,d),setTimeout(()=>{const v=new CustomEvent(TDe,uut);o.addEventListener(TDe,u),o.dispatchEvent(v),v.defaultPrevented||_T(x??document.body,{select:!0}),o.removeEventListener(TDe,u),mut.remove(p)},0)}}},[o,d,u,p]);const f=j.useCallback(x=>{if(!n&&!r||p.paused)return;const y=x.key==="Tab"&&!x.altKey&&!x.ctrlKey&&!x.metaKey,v=document.activeElement;if(y&&v){const b=x.currentTarget,[N,S]=jps(b);N&&S?!x.shiftKey&&v===S?(x.preventDefault(),n&&_T(N,{select:!0})):x.shiftKey&&v===N&&(x.preventDefault(),n&&_T(S,{select:!0})):v===b&&x.preventDefault()}},[n,r,p.paused]);return e.jsx(si.div,{tabIndex:-1,...l,ref:m,onKeyDown:f})});kne.displayName=_ps;function wps(s,{select:t=!1}={}){const n=document.activeElement;for(const r of s)if(_T(r,{select:t}),document.activeElement!==n)return}function jps(s){const t=nTt(s),n=hut(t,s),r=hut(t.reverse(),s);return[n,r]}function nTt(s){const t=[],n=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode: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}});for(;n.nextNode();)t.push(n.currentNode);return t}function hut(s,t){for(const n of s)if(!Nps(n,{upTo:t}))return n}function Nps(s,{upTo:t}){if(getComputedStyle(s).visibility==="hidden")return!0;for(;s;){if(t!==void 0&&s===t)return!1;if(getComputedStyle(s).display==="none")return!0;s=s.parentElement}return!1}function kps(s){return s instanceof HTMLInputElement&&"select"in s}function _T(s,{select:t=!1}={}){if(s&&s.focus){const n=document.activeElement;s.focus({preventScroll:!0}),s!==n&&kps(s)&&t&&s.select()}}var mut=Sps();function Sps(){let s=[];return{add(t){const n=s[0];t!==n&&(n==null||n.pause()),s=put(s,t),s.unshift(t)},remove(t){var n;s=put(s,t),(n=s[0])==null||n.resume()}}}function put(s,t){const n=[...s],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function Cps(s){return s.filter(t=>t.tagName!=="A")}var MDe=0;function _6e(){j.useEffect(()=>{const s=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",s[0]??fut()),document.body.insertAdjacentElement("beforeend",s[1]??fut()),MDe++,()=>{MDe===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),MDe--}},[])}function fut(){const s=document.createElement("span");return s.setAttribute("data-radix-focus-guard",""),s.tabIndex=0,s.style.outline="none",s.style.opacity="0",s.style.position="fixed",s.style.pointerEvents="none",s}var i4=function(){return i4=Object.assign||function(t){for(var n,r=1,a=arguments.length;r"u")return Vps;var t=Hps(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])}},Wps=oTt(),Eq="data-scroll-locked",Kps=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(Eps,` { overflow: hidden `).concat(r,`; padding-right: `).concat(o,"px ").concat(r,`; } body[`).concat(Eq,`] { 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(f5e,` { right: `).concat(o,"px ").concat(r,`; } .`).concat(g5e,` { margin-right: `).concat(o,"px ").concat(r,`; } .`).concat(f5e," .").concat(f5e,` { right: 0 `).concat(r,`; } .`).concat(g5e," .").concat(g5e,` { margin-right: 0 `).concat(r,`; } body[`).concat(Eq,`] { `).concat(Tps,": ").concat(o,`px; } `)},xut=function(){var s=parseInt(document.body.getAttribute(Eq)||"0",10);return isFinite(s)?s:0},Yps=function(){j.useEffect(function(){return document.body.setAttribute(Eq,(xut()+1).toString()),function(){var s=xut()-1;s<=0?document.body.removeAttribute(Eq):document.body.setAttribute(Eq,s.toString())}},[])},Zps=function(s){var t=s.noRelative,n=s.noImportant,r=s.gapMode,a=r===void 0?"margin":r;Yps();var i=j.useMemo(function(){return Gps(a)},[a]);return j.createElement(Wps,{styles:Kps(i,!t,a,n?"":"!important")})},bUe=!1;if(typeof window<"u")try{var soe=Object.defineProperty({},"passive",{get:function(){return bUe=!0,!0}});window.addEventListener("test",soe,soe),window.removeEventListener("test",soe,soe)}catch{bUe=!1}var Pz=bUe?{passive:!1}:!1,Xps=function(s){return s.tagName==="TEXTAREA"},lTt=function(s,t){if(!(s instanceof Element))return!1;var n=window.getComputedStyle(s);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!Xps(s)&&n[t]==="visible")},Qps=function(s){return lTt(s,"overflowY")},Jps=function(s){return lTt(s,"overflowX")},yut=function(s,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var a=cTt(s,r);if(a){var i=dTt(s,r),l=i[1],o=i[2];if(l>o)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},efs=function(s){var t=s.scrollTop,n=s.scrollHeight,r=s.clientHeight;return[t,n,r]},tfs=function(s){var t=s.scrollLeft,n=s.scrollWidth,r=s.clientWidth;return[t,n,r]},cTt=function(s,t){return s==="v"?Qps(t):Jps(t)},dTt=function(s,t){return s==="v"?efs(t):tfs(t)},sfs=function(s,t){return s==="h"&&t==="rtl"?-1:1},nfs=function(s,t,n,r,a){var i=sfs(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 p=dTt(s,o),f=p[0],x=p[1],y=p[2],v=x-y-i*f;(f||v)&&cTt(s,o)&&(h+=v,m+=f);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||!a)||!u&&(Math.abs(m)<1||!a))&&(d=!0),d},noe=function(s){return"changedTouches"in s?[s.changedTouches[0].clientX,s.changedTouches[0].clientY]:[0,0]},vut=function(s){return[s.deltaX,s.deltaY]},but=function(s){return s&&"current"in s?s.current:s},rfs=function(s,t){return s[0]===t[0]&&s[1]===t[1]},afs=function(s){return` .block-interactivity-`.concat(s,` {pointer-events: none;} .allow-interactivity-`).concat(s,` {pointer-events: all;} `)},ifs=0,Lz=[];function ofs(s){var t=j.useRef([]),n=j.useRef([0,0]),r=j.useRef(),a=j.useState(ifs++)[0],i=j.useState(oTt)[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=Aps([s.lockRef.current],(s.shards||[]).map(but),!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=noe(x),b=n.current,N="deltaX"in x?x.deltaX:b[0]-v[0],S="deltaY"in x?x.deltaY:b[1]-v[1],A,T=x.target,L=Math.abs(N)>Math.abs(S)?"h":"v";if("touches"in x&&L==="h"&&T.type==="range")return!1;var M=yut(L,T);if(!M)return!0;if(M?A=L:(A=L==="v"?"h":"v",M=yut(L,T)),!M)return!1;if(!r.current&&"changedTouches"in x&&(N||S)&&(r.current=A),!A)return!0;var I=r.current||A;return nfs(I,y,x,I==="h"?N:S,!0)},[]),c=j.useCallback(function(x){var y=x;if(!(!Lz.length||Lz[Lz.length-1]!==i)){var v="deltaY"in y?vut(y):noe(y),b=t.current.filter(function(A){return A.name===y.type&&(A.target===y.target||y.target===A.shadowParent)&&rfs(A.delta,v)})[0];if(b&&b.should){y.cancelable&&y.preventDefault();return}if(!b){var N=(l.current.shards||[]).map(but).filter(Boolean).filter(function(A){return A.contains(y.target)}),S=N.length>0?o(y,N[0]):!l.current.noIsolation;S&&y.cancelable&&y.preventDefault()}}},[]),d=j.useCallback(function(x,y,v,b){var N={name:x,delta:y,target:v,should:b,shadowParent:lfs(v)};t.current.push(N),setTimeout(function(){t.current=t.current.filter(function(S){return S!==N})},1)},[]),u=j.useCallback(function(x){n.current=noe(x),r.current=void 0},[]),h=j.useCallback(function(x){d(x.type,vut(x),x.target,o(x,s.lockRef.current))},[]),m=j.useCallback(function(x){d(x.type,noe(x),x.target,o(x,s.lockRef.current))},[]);j.useEffect(function(){return Lz.push(i),s.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:m}),document.addEventListener("wheel",c,Pz),document.addEventListener("touchmove",c,Pz),document.addEventListener("touchstart",u,Pz),function(){Lz=Lz.filter(function(x){return x!==i}),document.removeEventListener("wheel",c,Pz),document.removeEventListener("touchmove",c,Pz),document.removeEventListener("touchstart",u,Pz)}},[]);var p=s.removeScrollBar,f=s.inert;return j.createElement(j.Fragment,null,f?j.createElement(i,{styles:afs(a)}):null,p?j.createElement(Zps,{noRelative:s.noRelative,gapMode:s.gapMode}):null)}function lfs(s){for(var t=null;s!==null;)s instanceof ShadowRoot&&(t=s.host,s=s.host),s=s.parentNode;return t}const cfs=Ops(iTt,ofs);var Sne=j.forwardRef(function(s,t){return j.createElement(w6e,i4({},s,{ref:t,sideCar:cfs}))});Sne.classNames=w6e.classNames;var dfs=function(s){if(typeof document>"u")return null;var t=Array.isArray(s)?s[0]:s;return t.ownerDocument.body},Iz=new WeakMap,roe=new WeakMap,aoe={},RDe=0,uTt=function(s){return s&&(s.host||uTt(s.parentNode))},ufs=function(s,t){return t.map(function(n){if(s.contains(n))return n;var r=uTt(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})},hfs=function(s,t,n,r){var a=ufs(t,Array.isArray(s)?s:[s]);aoe[n]||(aoe[n]=new WeakMap);var i=aoe[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 p=m.getAttribute(r),f=p!==null&&p!=="false",x=(Iz.get(m)||0)+1,y=(i.get(m)||0)+1;Iz.set(m,x),i.set(m,y),l.push(m),x===1&&f&&roe.set(m,!0),y===1&&m.setAttribute(n,"true"),f||m.setAttribute(r,"true")}catch(v){console.error("aria-hidden: cannot operate on ",m,v)}})};return u(t),o.clear(),RDe++,function(){l.forEach(function(h){var m=Iz.get(h)-1,p=i.get(h)-1;Iz.set(h,m),i.set(h,p),m||(roe.has(h)||h.removeAttribute(r),roe.delete(h)),p||h.removeAttribute(n)}),RDe--,RDe||(Iz=new WeakMap,Iz=new WeakMap,roe=new WeakMap,aoe={})}},j6e=function(s,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(s)?s:[s]),a=dfs(s);return a?(r.push.apply(r,Array.from(a.querySelectorAll("[aria-live]"))),hfs(r,a,n,"aria-hidden")):function(){return null}},N6e="Dialog",[hTt,mTt]=Up(N6e),[mfs,bS]=hTt(N6e),pTt=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]=Sx({prop:r,defaultProp:a??!1,onChange:i,caller:N6e});return e.jsx(mfs,{scope:t,triggerRef:o,contentRef:c,contentId:jx(),titleId:jx(),descriptionId:jx(),open:d,onOpenChange:u,onOpenToggle:j.useCallback(()=>u(h=>!h),[u]),modal:l,children:n})};pTt.displayName=N6e;var fTt="DialogTrigger",gTt=j.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=bS(fTt,n),i=Uo(t,a.triggerRef);return e.jsx(si.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":gZe(a.open),...r,ref:i,onClick:va(s.onClick,a.onOpenToggle)})});gTt.displayName=fTt;var pZe="DialogPortal",[pfs,xTt]=hTt(pZe,{forceMount:void 0}),yTt=s=>{const{__scopeDialog:t,forceMount:n,children:r,container:a}=s,i=bS(pZe,t);return e.jsx(pfs,{scope:t,forceMount:n,children:j.Children.map(r,l=>e.jsx(Xg,{present:n||i.open,children:e.jsx(sG,{asChild:!0,container:a,children:l})}))})};yTt.displayName=pZe;var O3e="DialogOverlay",vTt=j.forwardRef((s,t)=>{const n=xTt(O3e,s.__scopeDialog),{forceMount:r=n.forceMount,...a}=s,i=bS(O3e,s.__scopeDialog);return i.modal?e.jsx(Xg,{present:r||i.open,children:e.jsx(gfs,{...a,ref:t})}):null});vTt.displayName=O3e;var ffs=rP("DialogOverlay.RemoveScroll"),gfs=j.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=bS(O3e,n);return e.jsx(Sne,{as:ffs,allowPinchZoom:!0,shards:[a.contentRef],children:e.jsx(si.div,{"data-state":gZe(a.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),x7="DialogContent",bTt=j.forwardRef((s,t)=>{const n=xTt(x7,s.__scopeDialog),{forceMount:r=n.forceMount,...a}=s,i=bS(x7,s.__scopeDialog);return e.jsx(Xg,{present:r||i.open,children:i.modal?e.jsx(xfs,{...a,ref:t}):e.jsx(yfs,{...a,ref:t})})});bTt.displayName=x7;var xfs=j.forwardRef((s,t)=>{const n=bS(x7,s.__scopeDialog),r=j.useRef(null),a=Uo(t,n.contentRef,r);return j.useEffect(()=>{const i=r.current;if(i)return j6e(i)},[]),e.jsx(_Tt,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:va(s.onCloseAutoFocus,i=>{var l;i.preventDefault(),(l=n.triggerRef.current)==null||l.focus()}),onPointerDownOutside:va(s.onPointerDownOutside,i=>{const l=i.detail.originalEvent,o=l.button===0&&l.ctrlKey===!0;(l.button===2||o)&&i.preventDefault()}),onFocusOutside:va(s.onFocusOutside,i=>i.preventDefault())})}),yfs=j.forwardRef((s,t)=>{const n=bS(x7,s.__scopeDialog),r=j.useRef(!1),a=j.useRef(!1);return e.jsx(_Tt,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var l,o;(l=s.onCloseAutoFocus)==null||l.call(s,i),i.defaultPrevented||(r.current||(o=n.triggerRef.current)==null||o.focus(),i.preventDefault()),r.current=!1,a.current=!1},onInteractOutside:i=>{var c,d;(c=s.onInteractOutside)==null||c.call(s,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const l=i.target;((d=n.triggerRef.current)==null?void 0:d.contains(l))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&a.current&&i.preventDefault()}})}),_Tt=j.forwardRef((s,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:i,...l}=s,o=bS(x7,n),c=j.useRef(null),d=Uo(t,c);return _6e(),e.jsxs(e.Fragment,{children:[e.jsx(kne,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(IP,{role:"dialog",id:o.contentId,"aria-describedby":o.descriptionId,"aria-labelledby":o.titleId,"data-state":gZe(o.open),...l,ref:d,onDismiss:()=>o.onOpenChange(!1)})}),e.jsxs(e.Fragment,{children:[e.jsx(bfs,{titleId:o.titleId}),e.jsx(wfs,{contentRef:c,descriptionId:o.descriptionId})]})]})}),fZe="DialogTitle",wTt=j.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=bS(fZe,n);return e.jsx(si.h2,{id:a.titleId,...r,ref:t})});wTt.displayName=fZe;var jTt="DialogDescription",NTt=j.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=bS(jTt,n);return e.jsx(si.p,{id:a.descriptionId,...r,ref:t})});NTt.displayName=jTt;var kTt="DialogClose",STt=j.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=bS(kTt,n);return e.jsx(si.button,{type:"button",...r,ref:t,onClick:va(s.onClick,()=>a.onOpenChange(!1))})});STt.displayName=kTt;function gZe(s){return s?"open":"closed"}var CTt="DialogTitleWarning",[vfs,ATt]=mhs(CTt,{contentName:x7,titleName:fZe,docsSlug:"dialog"}),bfs=({titleId:s})=>{const t=ATt(CTt),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users. If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component. For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return j.useEffect(()=>{s&&(document.getElementById(s)||console.error(n))},[n,s]),null},_fs="DialogDescriptionWarning",wfs=({contentRef:s,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${ATt(_fs).contentName}}.`;return j.useEffect(()=>{var i;const a=(i=s.current)==null?void 0:i.getAttribute("aria-describedby");t&&a&&(document.getElementById(t)||console.warn(r))},[r,s,t]),null},k6e=pTt,xZe=gTt,S6e=yTt,rG=vTt,aG=bTt,Cne=wTt,Ane=NTt,Ene=STt,ETt="AlertDialog",[jfs,Wfr]=Up(ETt,[mTt]),fE=mTt(),TTt=s=>{const{__scopeAlertDialog:t,...n}=s,r=fE(t);return e.jsx(k6e,{...r,...n,modal:!0})};TTt.displayName=ETt;var Nfs="AlertDialogTrigger",MTt=j.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=fE(n);return e.jsx(xZe,{...a,...r,ref:t})});MTt.displayName=Nfs;var kfs="AlertDialogPortal",PTt=s=>{const{__scopeAlertDialog:t,...n}=s,r=fE(t);return e.jsx(S6e,{...r,...n})};PTt.displayName=kfs;var Sfs="AlertDialogOverlay",LTt=j.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=fE(n);return e.jsx(rG,{...a,...r,ref:t})});LTt.displayName=Sfs;var Tq="AlertDialogContent",[Cfs,Afs]=jfs(Tq),Efs=bEt("AlertDialogContent"),ITt=j.forwardRef((s,t)=>{const{__scopeAlertDialog:n,children:r,...a}=s,i=fE(n),l=j.useRef(null),o=Uo(t,l),c=j.useRef(null);return e.jsx(vfs,{contentName:Tq,titleName:RTt,docsSlug:"alert-dialog",children:e.jsx(Cfs,{scope:n,cancelRef:c,children:e.jsxs(aG,{role:"alertdialog",...i,...a,ref:o,onOpenAutoFocus:va(a.onOpenAutoFocus,d=>{var u;d.preventDefault(),(u=c.current)==null||u.focus({preventScroll:!0})}),onPointerDownOutside:d=>d.preventDefault(),onInteractOutside:d=>d.preventDefault(),children:[e.jsx(Efs,{children:r}),e.jsx(Mfs,{contentRef:l})]})})})});ITt.displayName=Tq;var RTt="AlertDialogTitle",DTt=j.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=fE(n);return e.jsx(Cne,{...a,...r,ref:t})});DTt.displayName=RTt;var OTt="AlertDialogDescription",FTt=j.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=fE(n);return e.jsx(Ane,{...a,...r,ref:t})});FTt.displayName=OTt;var Tfs="AlertDialogAction",zTt=j.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=fE(n);return e.jsx(Ene,{...a,...r,ref:t})});zTt.displayName=Tfs;var BTt="AlertDialogCancel",UTt=j.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,{cancelRef:a}=Afs(BTt,n),i=fE(n),l=Uo(t,a);return e.jsx(Ene,{...i,...r,ref:l})});UTt.displayName=BTt;var Mfs=({contentRef:s})=>{const t=`\`${Tq}\` requires a description for the component to be accessible for screen reader users. You can add a description to the \`${Tq}\` by passing a \`${OTt}\` component as a child, which also benefits sighted users by adding visible context to the dialog. Alternatively, you can use your own component as a description by assigning it an \`id\` and passing the same value to the \`aria-describedby\` prop in \`${Tq}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component. For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return j.useEffect(()=>{var r;document.getElementById((r=s.current)==null?void 0:r.getAttribute("aria-describedby"))||console.warn(t)},[t,s]),null},Pfs=TTt,Lfs=MTt,Ifs=PTt,qTt=LTt,$Tt=ITt,VTt=zTt,HTt=UTt,GTt=DTt,WTt=FTt;const TV=u9("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"}}),U=j.forwardRef(({className:s,variant:t,size:n,asChild:r=!1,...a},i)=>{const l=r?lZe:"button";return e.jsx(l,{className:Mt(TV({variant:t,size:n,className:s})),ref:i,...a})});U.displayName="Button";const Fl=Pfs,Op=Lfs,Rfs=Ifs,KTt=j.forwardRef(({className:s,...t},n)=>e.jsx(qTt,{className:Mt("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}));KTt.displayName=qTt.displayName;const El=j.forwardRef(({className:s,...t},n)=>e.jsxs(Rfs,{children:[e.jsx(KTt,{}),e.jsx($Tt,{ref:n,className:Mt("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})]}));El.displayName=$Tt.displayName;const Tl=({className:s,...t})=>e.jsx("div",{className:Mt("flex flex-col space-y-2 text-center sm:text-left",s),...t});Tl.displayName="AlertDialogHeader";const Ml=({className:s,...t})=>e.jsx("div",{className:Mt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});Ml.displayName="AlertDialogFooter";const Pl=j.forwardRef(({className:s,...t},n)=>e.jsx(GTt,{ref:n,className:Mt("text-lg font-semibold",s),...t}));Pl.displayName=GTt.displayName;const Ll=j.forwardRef(({className:s,...t},n)=>e.jsx(WTt,{ref:n,className:Mt("text-sm text-muted-foreground",s),...t}));Ll.displayName=WTt.displayName;const _l=j.forwardRef(({className:s,...t},n)=>e.jsx(VTt,{ref:n,className:Mt(TV(),s),...t}));_l.displayName=VTt.displayName;const Il=j.forwardRef(({className:s,...t},n)=>e.jsx(HTt,{ref:n,className:Mt(TV({variant:"outline"}),"mt-2 sm:mt-0",s),...t}));Il.displayName=HTt.displayName;let F3e=null;const Dfs=["delete","remove","revoke","cannot be undone","permanently"];function Yi(s,t={}){const n=typeof s=="string"?{description:s,...t}:s,r=`${n.title??""} ${n.description??""}`.toLowerCase(),a=n.destructive??Dfs.some(i=>r.includes(i));return new Promise(i=>{if(!F3e){i(window.confirm(n.description??n.title??"Are you sure?"));return}F3e({...n,destructive:a,resolve:i})})}function Ofs(){const[s,t]=j.useState(null);j.useEffect(()=>(F3e=a=>t(a),()=>{F3e=null}),[]);const n=a=>{s==null||s.resolve(a),t(null)},r=!!(s!=null&&s.destructive);return e.jsx(Fl,{open:!!s,onOpenChange:a=>!a&&n(!1),children:e.jsxs(El,{className:"sm:max-w-md",children:[e.jsx(Tl,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Mt("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(tc,{className:"h-5 w-5"})}),e.jsxs("div",{className:"space-y-1.5 text-left",children:[e.jsx(Pl,{children:(s==null?void 0:s.title)??(r?"Are you sure?":"Please confirm")}),(s==null?void 0:s.description)&&e.jsx(Ll,{className:"leading-relaxed",children:s.description})]})]})}),e.jsxs(Ml,{className:"gap-2 sm:gap-2",children:[e.jsx(Il,{onClick:()=>n(!1),children:(s==null?void 0:s.cancelText)??"Cancel"}),e.jsx(_l,{onClick:()=>n(!0),className:Mt(r&&"bg-destructive text-destructive-foreground hover:bg-destructive/90"),children:(s==null?void 0:s.confirmText)??(r?"Delete":"Continue")})]})]})})}const Ffs=["top","right","bottom","left"],aP=Math.min,Rw=Math.max,z3e=Math.round,ioe=Math.floor,iP=s=>({x:s,y:s}),zfs={left:"right",right:"left",bottom:"top",top:"bottom"},Bfs={start:"end",end:"start"};function _Ue(s,t,n){return Rw(s,aP(t,n))}function tE(s,t){return typeof s=="function"?s(t):s}function sE(s){return s.split("-")[0]}function iG(s){return s.split("-")[1]}function yZe(s){return s==="x"?"y":"x"}function vZe(s){return s==="y"?"height":"width"}function oP(s){return["top","bottom"].includes(sE(s))?"y":"x"}function bZe(s){return yZe(oP(s))}function Ufs(s,t,n){n===void 0&&(n=!1);const r=iG(s),a=bZe(s),i=vZe(a);let l=a==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(l=B3e(l)),[l,B3e(l)]}function qfs(s){const t=B3e(s);return[wUe(s),t,wUe(t)]}function wUe(s){return s.replace(/start|end/g,t=>Bfs[t])}function $fs(s,t,n){const r=["left","right"],a=["right","left"],i=["top","bottom"],l=["bottom","top"];switch(s){case"top":case"bottom":return n?t?a:r:t?r:a;case"left":case"right":return t?i:l;default:return[]}}function Vfs(s,t,n,r){const a=iG(s);let i=$fs(sE(s),n==="start",r);return a&&(i=i.map(l=>l+"-"+a),t&&(i=i.concat(i.map(wUe)))),i}function B3e(s){return s.replace(/left|right|bottom|top/g,t=>zfs[t])}function Hfs(s){return{top:0,right:0,bottom:0,left:0,...s}}function YTt(s){return typeof s!="number"?Hfs(s):{top:s,right:s,bottom:s,left:s}}function U3e(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 _ut(s,t,n){let{reference:r,floating:a}=s;const i=oP(t),l=bZe(t),o=vZe(l),c=sE(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 p;switch(c){case"top":p={x:u,y:r.y-a.height};break;case"bottom":p={x:u,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:h};break;case"left":p={x:r.x-a.width,y:h};break;default:p={x:r.x,y:r.y}}switch(iG(t)){case"start":p[l]-=m*(n&&d?-1:1);break;case"end":p[l]+=m*(n&&d?-1:1);break}return p}const Gfs=async(s,t,n)=>{const{placement:r="bottom",strategy:a="absolute",middleware:i=[],platform:l}=n,o=i.filter(Boolean),c=await(l.isRTL==null?void 0:l.isRTL(t));let d=await l.getElementRects({reference:s,floating:t,strategy:a}),{x:u,y:h}=_ut(d,r,c),m=r,p={},f=0;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}=tE(s,t)||{};if(d==null)return{};const h=YTt(u),m={x:n,y:r},p=bZe(a),f=vZe(p),x=await l.getDimensions(d),y=p==="y",v=y?"top":"left",b=y?"bottom":"right",N=y?"clientHeight":"clientWidth",S=i.reference[f]+i.reference[p]-m[p]-i.floating[f],A=m[p]-i.reference[p],T=await(l.getOffsetParent==null?void 0:l.getOffsetParent(d));let L=T?T[N]:0;(!L||!await(l.isElement==null?void 0:l.isElement(T)))&&(L=o.floating[N]||i.floating[f]);const M=S/2-A/2,I=L/2-x[f]/2-1,R=aP(h[v],I),z=aP(h[b],I),$=R,H=L-x[f]-z,V=L/2-x[f]/2+M,K=_Ue($,V,H),Z=!c.arrow&&iG(a)!=null&&V!==K&&i.reference[f]/2-(V<$?R:z)-x[f]/2<0,Q=Z?V<$?V-$:V-H:0;return{[p]:m[p]+Q,data:{[p]:K,centerOffset:V-K-Q,...Z&&{alignmentOffset:Q}},reset:Z}}}),Kfs=function(s){return s===void 0&&(s={}),{name:"flip",options:s,async fn(t){var n,r;const{placement:a,middlewareData:i,rects:l,initialPlacement:o,platform:c,elements:d}=t,{mainAxis:u=!0,crossAxis:h=!0,fallbackPlacements:m,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:x=!0,...y}=tE(s,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const v=sE(a),b=oP(o),N=sE(o)===o,S=await(c.isRTL==null?void 0:c.isRTL(d.floating)),A=m||(N||!x?[B3e(o)]:qfs(o)),T=f!=="none";!m&&T&&A.push(...Vfs(o,x,f,S));const L=[o,...A],M=await YJ(t,y),I=[];let R=((r=i.flip)==null?void 0:r.overflows)||[];if(u&&I.push(M[v]),h){const V=Ufs(a,l,S);I.push(M[V[0]],M[V[1]])}if(R=[...R,{placement:a,overflows:I}],!I.every(V=>V<=0)){var z,$;const V=(((z=i.flip)==null?void 0:z.index)||0)+1,K=L[V];if(K)return{data:{index:V,overflows:R},reset:{placement:K}};let Z=($=R.filter(Q=>Q.overflows[0]<=0).sort((Q,le)=>Q.overflows[1]-le.overflows[1])[0])==null?void 0:$.placement;if(!Z)switch(p){case"bestFit":{var H;const Q=(H=R.filter(le=>{if(T){const ue=oP(le.placement);return ue===b||ue==="y"}return!0}).map(le=>[le.placement,le.overflows.filter(ue=>ue>0).reduce((ue,se)=>ue+se,0)]).sort((le,ue)=>le[1]-ue[1])[0])==null?void 0:H[0];Q&&(Z=Q);break}case"initialPlacement":Z=o;break}if(a!==Z)return{reset:{placement:Z}}}return{}}}};function wut(s,t){return{top:s.top-t.height,right:s.right-t.width,bottom:s.bottom-t.height,left:s.left-t.width}}function jut(s){return Ffs.some(t=>s[t]>=0)}const Yfs=function(s){return s===void 0&&(s={}),{name:"hide",options:s,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...a}=tE(s,t);switch(r){case"referenceHidden":{const i=await YJ(t,{...a,elementContext:"reference"}),l=wut(i,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:jut(l)}}}case"escaped":{const i=await YJ(t,{...a,altBoundary:!0}),l=wut(i,n.floating);return{data:{escapedOffsets:l,escaped:jut(l)}}}default:return{}}}}};async function Zfs(s,t){const{placement:n,platform:r,elements:a}=s,i=await(r.isRTL==null?void 0:r.isRTL(a.floating)),l=sE(n),o=iG(n),c=oP(n)==="y",d=["left","top"].includes(l)?-1:1,u=i&&c?-1:1,h=tE(t,s);let{mainAxis:m,crossAxis:p,alignmentAxis:f}=typeof h=="number"?{mainAxis:h,crossAxis:0,alignmentAxis:null}:{mainAxis:h.mainAxis||0,crossAxis:h.crossAxis||0,alignmentAxis:h.alignmentAxis};return o&&typeof f=="number"&&(p=o==="end"?f*-1:f),c?{x:p*u,y:m*d}:{x:m*d,y:p*u}}const Xfs=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 Zfs(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}}}}},Qfs=function(s){return s===void 0&&(s={}),{name:"shift",options:s,async fn(t){const{x:n,y:r,placement:a}=t,{mainAxis:i=!0,crossAxis:l=!1,limiter:o={fn:y=>{let{x:v,y:b}=y;return{x:v,y:b}}},...c}=tE(s,t),d={x:n,y:r},u=await YJ(t,c),h=oP(sE(a)),m=yZe(h);let p=d[m],f=d[h];if(i){const y=m==="y"?"top":"left",v=m==="y"?"bottom":"right",b=p+u[y],N=p-u[v];p=_Ue(b,p,N)}if(l){const y=h==="y"?"top":"left",v=h==="y"?"bottom":"right",b=f+u[y],N=f-u[v];f=_Ue(b,f,N)}const x=o.fn({...t,[m]:p,[h]:f});return{...x,data:{x:x.x-n,y:x.y-r,enabled:{[m]:i,[h]:l}}}}}},Jfs=function(s){return s===void 0&&(s={}),{options:s,fn(t){const{x:n,y:r,placement:a,rects:i,middlewareData:l}=t,{offset:o=0,mainAxis:c=!0,crossAxis:d=!0}=tE(s,t),u={x:n,y:r},h=oP(a),m=yZe(h);let p=u[m],f=u[h];const x=tE(o,t),y=typeof x=="number"?{mainAxis:x,crossAxis:0}:{mainAxis:0,crossAxis:0,...x};if(c){const N=m==="y"?"height":"width",S=i.reference[m]-i.floating[N]+y.mainAxis,A=i.reference[m]+i.reference[N]-y.mainAxis;pA&&(p=A)}if(d){var v,b;const N=m==="y"?"width":"height",S=["top","left"].includes(sE(a)),A=i.reference[h]-i.floating[N]+(S&&((v=l.offset)==null?void 0:v[h])||0)+(S?0:y.crossAxis),T=i.reference[h]+i.reference[N]+(S?0:((b=l.offset)==null?void 0:b[h])||0)-(S?y.crossAxis:0);fT&&(f=T)}return{[m]:p,[h]:f}}}},egs=function(s){return s===void 0&&(s={}),{name:"size",options:s,async fn(t){var n,r;const{placement:a,rects:i,platform:l,elements:o}=t,{apply:c=()=>{},...d}=tE(s,t),u=await YJ(t,d),h=sE(a),m=iG(a),p=oP(a)==="y",{width:f,height:x}=i.floating;let y,v;h==="top"||h==="bottom"?(y=h,v=m===(await(l.isRTL==null?void 0:l.isRTL(o.floating))?"start":"end")?"left":"right"):(v=h,y=m==="end"?"top":"bottom");const b=x-u.top-u.bottom,N=f-u.left-u.right,S=aP(x-u[y],b),A=aP(f-u[v],N),T=!t.middlewareData.shift;let L=S,M=A;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(M=N),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(L=b),T&&!m){const R=Rw(u.left,0),z=Rw(u.right,0),$=Rw(u.top,0),H=Rw(u.bottom,0);p?M=f-2*(R!==0||z!==0?R+z:Rw(u.left,u.right)):L=x-2*($!==0||H!==0?$+H:Rw(u.top,u.bottom))}await c({...t,availableWidth:M,availableHeight:L});const I=await l.getDimensions(o.floating);return f!==I.width||x!==I.height?{reset:{rects:!0}}:{}}}};function C6e(){return typeof window<"u"}function oG(s){return ZTt(s)?(s.nodeName||"").toLowerCase():"#document"}function nj(s){var t;return(s==null||(t=s.ownerDocument)==null?void 0:t.defaultView)||window}function i3(s){var t;return(t=(ZTt(s)?s.ownerDocument:s.document)||window.document)==null?void 0:t.documentElement}function ZTt(s){return C6e()?s instanceof Node||s instanceof nj(s).Node:!1}function hS(s){return C6e()?s instanceof Element||s instanceof nj(s).Element:!1}function W4(s){return C6e()?s instanceof HTMLElement||s instanceof nj(s).HTMLElement:!1}function Nut(s){return!C6e()||typeof ShadowRoot>"u"?!1:s instanceof ShadowRoot||s instanceof nj(s).ShadowRoot}function Tne(s){const{overflow:t,overflowX:n,overflowY:r,display:a}=mS(s);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(a)}function tgs(s){return["table","td","th"].includes(oG(s))}function A6e(s){return[":popover-open",":modal"].some(t=>{try{return s.matches(t)}catch{return!1}})}function _Ze(s){const t=wZe(),n=hS(s)?mS(s):s;return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function sgs(s){let t=lP(s);for(;W4(t)&&!MV(t);){if(_Ze(t))return t;if(A6e(t))return null;t=lP(t)}return null}function wZe(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function MV(s){return["html","body","#document"].includes(oG(s))}function mS(s){return nj(s).getComputedStyle(s)}function E6e(s){return hS(s)?{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop}:{scrollLeft:s.scrollX,scrollTop:s.scrollY}}function lP(s){if(oG(s)==="html")return s;const t=s.assignedSlot||s.parentNode||Nut(s)&&s.host||i3(s);return Nut(t)?t.host:t}function XTt(s){const t=lP(s);return MV(t)?s.ownerDocument?s.ownerDocument.body:s.body:W4(t)&&Tne(t)?t:XTt(t)}function ZJ(s,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const a=XTt(s),i=a===((r=s.ownerDocument)==null?void 0:r.body),l=nj(a);if(i){const o=jUe(l);return t.concat(l,l.visualViewport||[],Tne(a)?a:[],o&&n?ZJ(o):[])}return t.concat(a,ZJ(a,[],n))}function jUe(s){return s.parent&&Object.getPrototypeOf(s.parent)?s.frameElement:null}function QTt(s){const t=mS(s);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const a=W4(s),i=a?s.offsetWidth:n,l=a?s.offsetHeight:r,o=z3e(n)!==i||z3e(r)!==l;return o&&(n=i,r=l),{width:n,height:r,$:o}}function jZe(s){return hS(s)?s:s.contextElement}function Mq(s){const t=jZe(s);if(!W4(t))return iP(1);const n=t.getBoundingClientRect(),{width:r,height:a,$:i}=QTt(t);let l=(i?z3e(n.width):n.width)/r,o=(i?z3e(n.height):n.height)/a;return(!l||!Number.isFinite(l))&&(l=1),(!o||!Number.isFinite(o))&&(o=1),{x:l,y:o}}const ngs=iP(0);function JTt(s){const t=nj(s);return!wZe()||!t.visualViewport?ngs:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function rgs(s,t,n){return t===void 0&&(t=!1),!n||t&&n!==nj(s)?!1:t}function y7(s,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const a=s.getBoundingClientRect(),i=jZe(s);let l=iP(1);t&&(r?hS(r)&&(l=Mq(r)):l=Mq(s));const o=rgs(i,n,r)?JTt(i):iP(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){const m=nj(i),p=r&&hS(r)?nj(r):r;let f=m,x=jUe(f);for(;x&&r&&p!==f;){const y=Mq(x),v=x.getBoundingClientRect(),b=mS(x),N=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+=N,d+=S,f=nj(x),x=jUe(f)}}return U3e({width:u,height:h,x:c,y:d})}function ags(s){let{elements:t,rect:n,offsetParent:r,strategy:a}=s;const i=a==="fixed",l=i3(r),o=t?A6e(t.floating):!1;if(r===l||o&&i)return n;let c={scrollLeft:0,scrollTop:0},d=iP(1);const u=iP(0),h=W4(r);if((h||!h&&!i)&&((oG(r)!=="body"||Tne(l))&&(c=E6e(r)),W4(r))){const m=y7(r);d=Mq(r),u.x=m.x+r.clientLeft,u.y=m.y+r.clientTop}return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-c.scrollLeft*d.x+u.x,y:n.y*d.y-c.scrollTop*d.y+u.y}}function igs(s){return Array.from(s.getClientRects())}function NUe(s,t){const n=E6e(s).scrollLeft;return t?t.left+n:y7(i3(s)).left+n}function ogs(s){const t=i3(s),n=E6e(s),r=s.ownerDocument.body,a=Rw(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=Rw(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let l=-n.scrollLeft+NUe(s);const o=-n.scrollTop;return mS(r).direction==="rtl"&&(l+=Rw(t.clientWidth,r.clientWidth)-a),{width:a,height:i,x:l,y:o}}function lgs(s,t){const n=nj(s),r=i3(s),a=n.visualViewport;let i=r.clientWidth,l=r.clientHeight,o=0,c=0;if(a){i=a.width,l=a.height;const d=wZe();(!d||d&&t==="fixed")&&(o=a.offsetLeft,c=a.offsetTop)}return{width:i,height:l,x:o,y:c}}function cgs(s,t){const n=y7(s,!0,t==="fixed"),r=n.top+s.clientTop,a=n.left+s.clientLeft,i=W4(s)?Mq(s):iP(1),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 kut(s,t,n){let r;if(t==="viewport")r=lgs(s,n);else if(t==="document")r=ogs(i3(s));else if(hS(t))r=cgs(t,n);else{const a=JTt(s);r={...t,x:t.x-a.x,y:t.y-a.y}}return U3e(r)}function e6t(s,t){const n=lP(s);return n===t||!hS(n)||MV(n)?!1:mS(n).position==="fixed"||e6t(n,t)}function dgs(s,t){const n=t.get(s);if(n)return n;let r=ZJ(s,[],!1).filter(o=>hS(o)&&oG(o)!=="body"),a=null;const i=mS(s).position==="fixed";let l=i?lP(s):s;for(;hS(l)&&!MV(l);){const o=mS(l),c=_Ze(l);!c&&o.position==="fixed"&&(a=null),(i?!c&&!a:!c&&o.position==="static"&&!!a&&["absolute","fixed"].includes(a.position)||Tne(l)&&!c&&e6t(s,l))?r=r.filter(u=>u!==l):a=o,l=lP(l)}return t.set(s,r),r}function ugs(s){let{element:t,boundary:n,rootBoundary:r,strategy:a}=s;const l=[...n==="clippingAncestors"?A6e(t)?[]:dgs(t,this._c):[].concat(n),r],o=l[0],c=l.reduce((d,u)=>{const h=kut(t,u,a);return d.top=Rw(h.top,d.top),d.right=aP(h.right,d.right),d.bottom=aP(h.bottom,d.bottom),d.left=Rw(h.left,d.left),d},kut(t,o,a));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function hgs(s){const{width:t,height:n}=QTt(s);return{width:t,height:n}}function mgs(s,t,n){const r=W4(t),a=i3(t),i=n==="fixed",l=y7(s,!0,i,t);let o={scrollLeft:0,scrollTop:0};const c=iP(0);if(r||!r&&!i)if((oG(t)!=="body"||Tne(a))&&(o=E6e(t)),r){const p=y7(t,!0,i,t);c.x=p.x+t.clientLeft,c.y=p.y+t.clientTop}else a&&(c.x=NUe(a));let d=0,u=0;if(a&&!r&&!i){const p=a.getBoundingClientRect();u=p.top+o.scrollTop,d=p.left+o.scrollLeft-NUe(a,p)}const h=l.left+o.scrollLeft-c.x-d,m=l.top+o.scrollTop-c.y-u;return{x:h,y:m,width:l.width,height:l.height}}function DDe(s){return mS(s).position==="static"}function Sut(s,t){if(!W4(s)||mS(s).position==="fixed")return null;if(t)return t(s);let n=s.offsetParent;return i3(s)===n&&(n=n.ownerDocument.body),n}function t6t(s,t){const n=nj(s);if(A6e(s))return n;if(!W4(s)){let a=lP(s);for(;a&&!MV(a);){if(hS(a)&&!DDe(a))return a;a=lP(a)}return n}let r=Sut(s,t);for(;r&&tgs(r)&&DDe(r);)r=Sut(r,t);return r&&MV(r)&&DDe(r)&&!_Ze(r)?n:r||sgs(s)||n}const pgs=async function(s){const t=this.getOffsetParent||t6t,n=this.getDimensions,r=await n(s.floating);return{reference:mgs(s.reference,await t(s.floating),s.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function fgs(s){return mS(s).direction==="rtl"}const ggs={convertOffsetParentRelativeRectToViewportRelativeRect:ags,getDocumentElement:i3,getClippingRect:ugs,getOffsetParent:t6t,getElementRects:pgs,getClientRects:igs,getDimensions:hgs,getScale:Mq,isElement:hS,isRTL:fgs};function xgs(s,t){let n=null,r;const a=i3(s);function i(){var o;clearTimeout(r),(o=n)==null||o.disconnect(),n=null}function l(o,c){o===void 0&&(o=!1),c===void 0&&(c=1),i();const{left:d,top:u,width:h,height:m}=s.getBoundingClientRect();if(o||t(),!h||!m)return;const p=ioe(u),f=ioe(a.clientWidth-(d+h)),x=ioe(a.clientHeight-(u+m)),y=ioe(d),b={rootMargin:-p+"px "+-f+"px "+-x+"px "+-y+"px",threshold:Rw(0,aP(1,c))||1};let N=!0;function S(A){const T=A[0].intersectionRatio;if(T!==c){if(!N)return l();T?l(!1,T):r=setTimeout(()=>{l(!1,1e-7)},1e3)}N=!1}try{n=new IntersectionObserver(S,{...b,root:a.ownerDocument})}catch{n=new IntersectionObserver(S,b)}n.observe(s)}return l(!0),i}function ygs(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=jZe(s),u=a||i?[...d?ZJ(d):[],...ZJ(t)]:[];u.forEach(v=>{a&&v.addEventListener("scroll",n,{passive:!0}),i&&v.addEventListener("resize",n)});const h=d&&o?xgs(d,n):null;let m=-1,p=null;l&&(p=new ResizeObserver(v=>{let[b]=v;b&&b.target===d&&p&&(p.unobserve(t),cancelAnimationFrame(m),m=requestAnimationFrame(()=>{var N;(N=p)==null||N.observe(t)})),n()}),d&&!c&&p.observe(d),p.observe(t));let f,x=c?y7(s):null;c&&y();function y(){const v=y7(s);x&&(v.x!==x.x||v.y!==x.y||v.width!==x.width||v.height!==x.height)&&n(),x=v,f=requestAnimationFrame(y)}return n(),()=>{var v;u.forEach(b=>{a&&b.removeEventListener("scroll",n),i&&b.removeEventListener("resize",n)}),h==null||h(),(v=p)==null||v.disconnect(),p=null,c&&cancelAnimationFrame(f)}}const vgs=Xfs,bgs=Qfs,_gs=Kfs,wgs=egs,jgs=Yfs,Cut=Wfs,Ngs=Jfs,kgs=(s,t,n)=>{const r=new Map,a={platform:ggs,...n},i={...a.platform,_c:r};return Gfs(s,t,{...a,platform:i})};var x5e=typeof document<"u"?j.useLayoutEffect:j.useEffect;function q3e(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(!q3e(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)&&!q3e(s[i],t[i]))return!1}return!0}return s!==s&&t!==t}function s6t(s){return typeof window>"u"?1:(s.ownerDocument.defaultView||window).devicePixelRatio||1}function Aut(s,t){const n=s6t(s);return Math.round(t*n)/n}function ODe(s){const t=j.useRef(s);return x5e(()=>{t.current=s}),t}function Sgs(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,p]=j.useState(r);q3e(m,r)||p(r);const[f,x]=j.useState(null),[y,v]=j.useState(null),b=j.useCallback(le=>{le!==T.current&&(T.current=le,x(le))},[]),N=j.useCallback(le=>{le!==L.current&&(L.current=le,v(le))},[]),S=i||f,A=l||y,T=j.useRef(null),L=j.useRef(null),M=j.useRef(u),I=c!=null,R=ODe(c),z=ODe(a),$=ODe(d),H=j.useCallback(()=>{if(!T.current||!L.current)return;const le={placement:t,strategy:n,middleware:m};z.current&&(le.platform=z.current),kgs(T.current,L.current,le).then(ue=>{const se={...ue,isPositioned:$.current!==!1};V.current&&!q3e(M.current,se)&&(M.current=se,tv.flushSync(()=>{h(se)}))})},[m,t,n,z,$]);x5e(()=>{d===!1&&M.current.isPositioned&&(M.current.isPositioned=!1,h(le=>({...le,isPositioned:!1})))},[d]);const V=j.useRef(!1);x5e(()=>(V.current=!0,()=>{V.current=!1}),[]),x5e(()=>{if(S&&(T.current=S),A&&(L.current=A),S&&A){if(R.current)return R.current(S,A,H);H()}},[S,A,H,R,I]);const K=j.useMemo(()=>({reference:T,floating:L,setReference:b,setFloating:N}),[b,N]),Z=j.useMemo(()=>({reference:S,floating:A}),[S,A]),Q=j.useMemo(()=>{const le={position:n,left:0,top:0};if(!Z.floating)return le;const ue=Aut(Z.floating,u.x),se=Aut(Z.floating,u.y);return o?{...le,transform:"translate("+ue+"px, "+se+"px)",...s6t(Z.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ue,top:se}},[n,o,Z.floating,u.x,u.y]);return j.useMemo(()=>({...u,update:H,refs:K,elements:Z,floatingStyles:Q}),[u,H,K,Z,Q])}const Cgs=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?Cut({element:r.current,padding:a}).fn(n):{}:r?Cut({element:r,padding:a}).fn(n):{}}}},Ags=(s,t)=>({...vgs(s),options:[s,t]}),Egs=(s,t)=>({...bgs(s),options:[s,t]}),Tgs=(s,t)=>({...Ngs(s),options:[s,t]}),Mgs=(s,t)=>({..._gs(s),options:[s,t]}),Pgs=(s,t)=>({...wgs(s),options:[s,t]}),Lgs=(s,t)=>({...jgs(s),options:[s,t]}),Igs=(s,t)=>({...Cgs(s),options:[s,t]});var Rgs="Arrow",n6t=j.forwardRef((s,t)=>{const{children:n,width:r=10,height:a=5,...i}=s;return e.jsx(si.svg,{...i,ref:t,width:r,height:a,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:s.asChild?n:e.jsx("polygon",{points:"0,0 30,0 15,10"})})});n6t.displayName=Rgs;var Dgs=n6t;function Mne(s){const[t,n]=j.useState(void 0);return dg(()=>{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}var NZe="Popper",[r6t,o3]=Up(NZe),[Ogs,a6t]=r6t(NZe),i6t=s=>{const{__scopePopper:t,children:n}=s,[r,a]=j.useState(null);return e.jsx(Ogs,{scope:t,anchor:r,onAnchorChange:a,children:n})};i6t.displayName=NZe;var o6t="PopperAnchor",l6t=j.forwardRef((s,t)=>{const{__scopePopper:n,virtualRef:r,...a}=s,i=a6t(o6t,n),l=j.useRef(null),o=Uo(t,l);return j.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||l.current)}),r?null:e.jsx(si.div,{...a,ref:o})});l6t.displayName=o6t;var kZe="PopperContent",[Fgs,zgs]=r6t(kZe),c6t=j.forwardRef((s,t)=>{var ge,ke,Te,Me,Oe,Se;const{__scopePopper:n,side:r="bottom",sideOffset:a=0,align:i="center",alignOffset:l=0,arrowPadding:o=0,avoidCollisions:c=!0,collisionBoundary:d=[],collisionPadding:u=0,sticky:h="partial",hideWhenDetached:m=!1,updatePositionStrategy:p="optimized",onPlaced:f,...x}=s,y=a6t(kZe,n),[v,b]=j.useState(null),N=Uo(t,Qe=>b(Qe)),[S,A]=j.useState(null),T=Mne(S),L=(T==null?void 0:T.width)??0,M=(T==null?void 0:T.height)??0,I=r+(i!=="center"?"-"+i:""),R=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},z=Array.isArray(d)?d:[d],$=z.length>0,H={padding:R,boundary:z.filter(Ugs),altBoundary:$},{refs:V,floatingStyles:K,placement:Z,isPositioned:Q,middlewareData:le}=Sgs({strategy:"fixed",placement:I,whileElementsMounted:(...Qe)=>ygs(...Qe,{animationFrame:p==="always"}),elements:{reference:y.anchor},middleware:[Ags({mainAxis:a+M,alignmentAxis:l}),c&&Egs({mainAxis:!0,crossAxis:!1,limiter:h==="partial"?Tgs():void 0,...H}),c&&Mgs({...H}),Pgs({...H,apply:({elements:Qe,rects:Ae,availableWidth:Fe,availableHeight:Ne})=>{const{width:$e,height:Ve}=Ae.reference,qe=Qe.floating.style;qe.setProperty("--radix-popper-available-width",`${Fe}px`),qe.setProperty("--radix-popper-available-height",`${Ne}px`),qe.setProperty("--radix-popper-anchor-width",`${$e}px`),qe.setProperty("--radix-popper-anchor-height",`${Ve}px`)}}),S&&Igs({element:S,padding:o}),qgs({arrowWidth:L,arrowHeight:M}),m&&Lgs({strategy:"referenceHidden",...H})]}),[ue,se]=h6t(Z),ne=sg(f);dg(()=>{Q&&(ne==null||ne())},[Q,ne]);const ie=(ge=le.arrow)==null?void 0:ge.x,ce=(ke=le.arrow)==null?void 0:ke.y,je=((Te=le.arrow)==null?void 0:Te.centerOffset)!==0,[be,he]=j.useState();return dg(()=>{v&&he(window.getComputedStyle(v).zIndex)},[v]),e.jsx("div",{ref:V.setFloating,"data-radix-popper-content-wrapper":"",style:{...K,transform:Q?K.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:be,"--radix-popper-transform-origin":[(Me=le.transformOrigin)==null?void 0:Me.x,(Oe=le.transformOrigin)==null?void 0:Oe.y].join(" "),...((Se=le.hide)==null?void 0:Se.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:s.dir,children:e.jsx(Fgs,{scope:n,placedSide:ue,onArrowChange:A,arrowX:ie,arrowY:ce,shouldHideArrow:je,children:e.jsx(si.div,{"data-side":ue,"data-align":se,...x,ref:N,style:{...x.style,animation:Q?void 0:"none"}})})})});c6t.displayName=kZe;var d6t="PopperArrow",Bgs={top:"bottom",right:"left",bottom:"top",left:"right"},u6t=j.forwardRef(function(t,n){const{__scopePopper:r,...a}=t,i=zgs(d6t,r),l=Bgs[i.placedSide];return e.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[l]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:e.jsx(Dgs,{...a,ref:n,style:{...a.style,display:"block"}})})});u6t.displayName=d6t;function Ugs(s){return s!==null}var qgs=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]=h6t(n),h={start:"0%",center:"50%",end:"100%"}[u],m=(((v=a.arrow)==null?void 0:v.x)??0)+o/2,p=(((b=a.arrow)==null?void 0:b.y)??0)+c/2;let f="",x="";return d==="bottom"?(f=l?h:`${m}px`,x=`${-c}px`):d==="top"?(f=l?h:`${m}px`,x=`${r.floating.height+c}px`):d==="right"?(f=`${-c}px`,x=l?h:`${p}px`):d==="left"&&(f=`${r.floating.width+c}px`,x=l?h:`${p}px`),{data:{x:f,y:x}}}});function h6t(s){const[t,n="center"]=s.split("-");return[t,n]}var Pne=i6t,lG=l6t,Lne=c6t,Ine=u6t,[T6e,Kfr]=Up("Tooltip",[o3]),M6e=o3(),m6t="TooltipProvider",$gs=700,kUe="tooltip.open",[Vgs,SZe]=T6e(m6t),p6t=s=>{const{__scopeTooltip:t,delayDuration:n=$gs,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(Vgs,{scope:t,isOpenDelayedRef:l,delayDuration:n,onOpen:j.useCallback(()=>{window.clearTimeout(c.current),l.current=!1},[]),onClose:j.useCallback(()=>{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})};p6t.displayName=m6t;var XJ="Tooltip",[Hgs,P6e]=T6e(XJ),f6t=s=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:a,onOpenChange:i,disableHoverableContent:l,delayDuration:o}=s,c=SZe(XJ,s.__scopeTooltip),d=M6e(t),[u,h]=j.useState(null),m=jx(),p=j.useRef(0),f=l??c.disableHoverableContent,x=o??c.delayDuration,y=j.useRef(!1),[v,b]=Sx({prop:r,defaultProp:a??!1,onChange:L=>{L?(c.onOpen(),document.dispatchEvent(new CustomEvent(kUe))):c.onClose(),i==null||i(L)},caller:XJ}),N=j.useMemo(()=>v?y.current?"delayed-open":"instant-open":"closed",[v]),S=j.useCallback(()=>{window.clearTimeout(p.current),p.current=0,y.current=!1,b(!0)},[b]),A=j.useCallback(()=>{window.clearTimeout(p.current),p.current=0,b(!1)},[b]),T=j.useCallback(()=>{window.clearTimeout(p.current),p.current=window.setTimeout(()=>{y.current=!0,b(!0),p.current=0},x)},[x,b]);return j.useEffect(()=>()=>{p.current&&(window.clearTimeout(p.current),p.current=0)},[]),e.jsx(Pne,{...d,children:e.jsx(Hgs,{scope:t,contentId:m,open:v,stateAttribute:N,trigger:u,onTriggerChange:h,onTriggerEnter:j.useCallback(()=>{c.isOpenDelayedRef.current?T():S()},[c.isOpenDelayedRef,T,S]),onTriggerLeave:j.useCallback(()=>{f?A():(window.clearTimeout(p.current),p.current=0)},[A,f]),onOpen:S,onClose:A,disableHoverableContent:f,children:n})})};f6t.displayName=XJ;var SUe="TooltipTrigger",g6t=j.forwardRef((s,t)=>{const{__scopeTooltip:n,...r}=s,a=P6e(SUe,n),i=SZe(SUe,n),l=M6e(n),o=j.useRef(null),c=Uo(t,o,a.onTriggerChange),d=j.useRef(!1),u=j.useRef(!1),h=j.useCallback(()=>d.current=!1,[]);return j.useEffect(()=>()=>document.removeEventListener("pointerup",h),[h]),e.jsx(lG,{asChild:!0,...l,children:e.jsx(si.button,{"aria-describedby":a.open?a.contentId:void 0,"data-state":a.stateAttribute,...r,ref:c,onPointerMove:va(s.onPointerMove,m=>{m.pointerType!=="touch"&&!u.current&&!i.isPointerInTransitRef.current&&(a.onTriggerEnter(),u.current=!0)}),onPointerLeave:va(s.onPointerLeave,()=>{a.onTriggerLeave(),u.current=!1}),onPointerDown:va(s.onPointerDown,()=>{a.open&&a.onClose(),d.current=!0,document.addEventListener("pointerup",h,{once:!0})}),onFocus:va(s.onFocus,()=>{d.current||a.onOpen()}),onBlur:va(s.onBlur,a.onClose),onClick:va(s.onClick,a.onClose)})})});g6t.displayName=SUe;var Ggs="TooltipPortal",[Yfr,Wgs]=T6e(Ggs,{forceMount:void 0}),PV="TooltipContent",x6t=j.forwardRef((s,t)=>{const n=Wgs(PV,s.__scopeTooltip),{forceMount:r=n.forceMount,side:a="top",...i}=s,l=P6e(PV,s.__scopeTooltip);return e.jsx(Xg,{present:r||l.open,children:l.disableHoverableContent?e.jsx(y6t,{side:a,...i,ref:t}):e.jsx(Kgs,{side:a,...i,ref:t})})}),Kgs=j.forwardRef((s,t)=>{const n=P6e(PV,s.__scopeTooltip),r=SZe(PV,s.__scopeTooltip),a=j.useRef(null),i=Uo(t,a),[l,o]=j.useState(null),{trigger:c,onClose:d}=n,u=a.current,{onPointerInTransitChange:h}=r,m=j.useCallback(()=>{o(null),h(!1)},[h]),p=j.useCallback((f,x)=>{const y=f.currentTarget,v={x:f.clientX,y:f.clientY},b=Jgs(v,y.getBoundingClientRect()),N=exs(v,b),S=txs(x.getBoundingClientRect()),A=nxs([...N,...S]);o(A),h(!0)},[h]);return j.useEffect(()=>()=>m(),[m]),j.useEffect(()=>{if(c&&u){const f=y=>p(y,u),x=y=>p(y,c);return c.addEventListener("pointerleave",f),u.addEventListener("pointerleave",x),()=>{c.removeEventListener("pointerleave",f),u.removeEventListener("pointerleave",x)}}},[c,u,p,m]),j.useEffect(()=>{if(l){const f=x=>{const y=x.target,v={x:x.clientX,y:x.clientY},b=(c==null?void 0:c.contains(y))||(u==null?void 0:u.contains(y)),N=!sxs(v,l);b?m():N&&(m(),d())};return document.addEventListener("pointermove",f),()=>document.removeEventListener("pointermove",f)}},[c,u,l,d,m]),e.jsx(y6t,{...s,ref:i})}),[Ygs,Zgs]=T6e(XJ,{isInside:!1}),Xgs=bEt("TooltipContent"),y6t=j.forwardRef((s,t)=>{const{__scopeTooltip:n,children:r,"aria-label":a,onEscapeKeyDown:i,onPointerDownOutside:l,...o}=s,c=P6e(PV,n),d=M6e(n),{onClose:u}=c;return j.useEffect(()=>(document.addEventListener(kUe,u),()=>document.removeEventListener(kUe,u)),[u]),j.useEffect(()=>{if(c.trigger){const h=m=>{const p=m.target;p!=null&&p.contains(c.trigger)&&u()};return window.addEventListener("scroll",h,{capture:!0}),()=>window.removeEventListener("scroll",h,{capture:!0})}},[c.trigger,u]),e.jsx(IP,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:h=>h.preventDefault(),onDismiss:u,children:e.jsxs(Lne,{"data-state":c.stateAttribute,...d,...o,ref:t,style:{...o.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[e.jsx(Xgs,{children:r}),e.jsx(Ygs,{scope:n,isInside:!0,children:e.jsx(Ohs,{id:c.contentId,role:"tooltip",children:a||r})})]})})});x6t.displayName=PV;var v6t="TooltipArrow",Qgs=j.forwardRef((s,t)=>{const{__scopeTooltip:n,...r}=s,a=M6e(n);return Zgs(v6t,n).isInside?null:e.jsx(Ine,{...a,...r,ref:t})});Qgs.displayName=v6t;function Jgs(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")}}function exs(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}function txs(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}]}function sxs(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}function nxs(s){const t=s.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),rxs(t)}function rxs(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)}var axs=p6t,ixs=f6t,oxs=g6t,b6t=x6t;const wN=axs,Bg=ixs,Ug=oxs,ng=j.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(b6t,{ref:r,sideOffset:t,className:Mt("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}));ng.displayName=b6t.displayName;var cG=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(){}},v7=typeof window>"u"||"Deno"in globalThis;function K1(){}function lxs(s,t){return typeof s=="function"?s(t):s}function CUe(s){return typeof s=="number"&&s>=0&&s!==1/0}function _6t(s,t){return Math.max(s+(t||0)-Date.now(),0)}function FM(s,t){return typeof s=="function"?s(t):s}function w2(s,t){return typeof s=="function"?s(t):s}function Eut(s,t){const{type:n="all",exact:r,fetchStatus:a,predicate:i,queryKey:l,stale:o}=s;if(l){if(r){if(t.queryHash!==CZe(l,t.options))return!1}else if(!QJ(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 Tut(s,t){const{exact:n,status:r,predicate:a,mutationKey:i}=s;if(i){if(!t.options.mutationKey)return!1;if(n){if(b7(t.options.mutationKey)!==b7(i))return!1}else if(!QJ(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||a&&!a(t))}function CZe(s,t){return((t==null?void 0:t.queryKeyHashFn)||b7)(s)}function b7(s){return JSON.stringify(s,(t,n)=>AUe(n)?Object.keys(n).sort().reduce((r,a)=>(r[a]=n[a],r),{}):n)}function QJ(s,t){return s===t?!0:typeof s!=typeof t?!1:s&&t&&typeof s=="object"&&typeof t=="object"?Object.keys(t).every(n=>QJ(s[n],t[n])):!1}function w6t(s,t){if(s===t)return s;const n=Mut(s)&&Mut(t);if(n||AUe(s)&&AUe(t)){const r=n?s:Object.keys(s),a=r.length,i=n?t:Object.keys(t),l=i.length,o=n?[]:{},c=new Set(r);let d=0;for(let u=0;u{setTimeout(t,s)})}function EUe(s,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(s,t):n.structuralSharing!==!1?w6t(s,t):t}function dxs(s,t,n=0){const r=[...s,t];return n&&r.length>n?r.slice(1):r}function uxs(s,t,n=0){const r=[t,...s];return n&&r.length>n?r.slice(0,-1):r}var AZe=Symbol();function j6t(s,t){return!s.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!s.queryFn||s.queryFn===AZe?()=>Promise.reject(new Error(`Missing queryFn: '${s.queryHash}'`)):s.queryFn}function N6t(s,t){return typeof s=="function"?s(...t):!!s}var hO,h6,m$,W3t,hxs=(W3t=class extends cG{constructor(){super();is(this,hO);is(this,h6);is(this,m$);$t(this,m$,t=>{if(!v7&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){fe(this,h6)||this.setEventListener(fe(this,m$))}onUnsubscribe(){var t;this.hasListeners()||((t=fe(this,h6))==null||t.call(this),$t(this,h6,void 0))}setEventListener(t){var n;$t(this,m$,t),(n=fe(this,h6))==null||n.call(this),$t(this,h6,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){fe(this,hO)!==t&&($t(this,hO,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof fe(this,hO)=="boolean"?fe(this,hO):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},hO=new WeakMap,h6=new WeakMap,m$=new WeakMap,W3t),EZe=new hxs,p$,m6,f$,K3t,mxs=(K3t=class extends cG{constructor(){super();is(this,p$,!0);is(this,m6);is(this,f$);$t(this,f$,t=>{if(!v7&&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(){fe(this,m6)||this.setEventListener(fe(this,f$))}onUnsubscribe(){var t;this.hasListeners()||((t=fe(this,m6))==null||t.call(this),$t(this,m6,void 0))}setEventListener(t){var n;$t(this,f$,t),(n=fe(this,m6))==null||n.call(this),$t(this,m6,t(this.setOnline.bind(this)))}setOnline(t){fe(this,p$)!==t&&($t(this,p$,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return fe(this,p$)}},p$=new WeakMap,m6=new WeakMap,f$=new WeakMap,K3t),V3e=new mxs;function TUe(){let s,t;const n=new Promise((a,i)=>{s=a,t=i});n.status="pending",n.catch(()=>{});function r(a){Object.assign(n,a),delete n.resolve,delete n.reject}return n.resolve=a=>{r({status:"fulfilled",value:a}),s(a)},n.reject=a=>{r({status:"rejected",reason:a}),t(a)},n}function pxs(s){return Math.min(1e3*2**s,3e4)}function k6t(s){return(s??"online")==="online"?V3e.isOnline():!0}var S6t=class extends Error{constructor(s){super("CancelledError"),this.revert=s==null?void 0:s.revert,this.silent=s==null?void 0:s.silent}};function FDe(s){return s instanceof S6t}function C6t(s){let t=!1,n=0,r=!1,a;const i=TUe(),l=x=>{var y;r||(m(new S6t(x)),(y=s.abort)==null||y.call(s))},o=()=>{t=!0},c=()=>{t=!1},d=()=>EZe.isFocused()&&(s.networkMode==="always"||V3e.isOnline())&&s.canRun(),u=()=>k6t(s.networkMode)&&s.canRun(),h=x=>{var y;r||(r=!0,(y=s.onSuccess)==null||y.call(s,x),a==null||a(),i.resolve(x))},m=x=>{var y;r||(r=!0,(y=s.onError)==null||y.call(s,x),a==null||a(),i.reject(x))},p=()=>new Promise(x=>{var y;a=v=>{(r||d())&&x(v)},(y=s.onPause)==null||y.call(s)}).then(()=>{var x;a=void 0,r||(x=s.onContinue)==null||x.call(s)}),f=()=>{if(r)return;let x;const y=n===0?s.initialPromise:void 0;try{x=y??s.fn()}catch(v){x=Promise.reject(v)}Promise.resolve(x).then(h).catch(v=>{var T;if(r)return;const b=s.retry??(v7?0:3),N=s.retryDelay??pxs,S=typeof N=="function"?N(n,v):N,A=b===!0||typeof b=="number"&&nd()?void 0:p()).then(()=>{t?m(v):f()})})};return{promise:i,cancel:l,continue:()=>(a==null||a(),i),cancelRetry:o,continueRetry:c,canStart:u,start:()=>(u()?f():p().then(f),i)}}var fxs=s=>setTimeout(s,0);function gxs(){let s=[],t=0,n=o=>{o()},r=o=>{o()},a=fxs;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}}}var t0=gxs(),mO,Y3t,A6t=(Y3t=class{constructor(){is(this,mO)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),CUe(this.gcTime)&&$t(this,mO,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(s){this.gcTime=Math.max(this.gcTime||0,s??(v7?1/0:5*60*1e3))}clearGcTimeout(){fe(this,mO)&&(clearTimeout(fe(this,mO)),$t(this,mO,void 0))}},mO=new WeakMap,Y3t),g$,pO,g2,fO,Vv,ese,gO,fk,mC,Z3t,xxs=(Z3t=class extends A6t{constructor(t){super();is(this,fk);is(this,g$);is(this,pO);is(this,g2);is(this,fO);is(this,Vv);is(this,ese);is(this,gO);$t(this,gO,!1),$t(this,ese,t.defaultOptions),this.setOptions(t.options),this.observers=[],$t(this,fO,t.client),$t(this,g2,fe(this,fO).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,$t(this,g$,yxs(this.options)),this.state=t.state??fe(this,g$),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=fe(this,Vv))==null?void 0:t.promise}setOptions(t){this.options={...fe(this,ese),...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&fe(this,g2).remove(this)}setData(t,n){const r=EUe(this.state.data,t,this.options);return Xt(this,fk,mC).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){Xt(this,fk,mC).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,a;const n=(r=fe(this,Vv))==null?void 0:r.promise;return(a=fe(this,Vv))==null||a.cancel(t),n?n.then(K1).catch(K1):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(fe(this,g$))}isActive(){return this.observers.some(t=>w2(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===AZe||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>FM(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:!_6t(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=fe(this,Vv))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=fe(this,Vv))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),fe(this,g2).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(fe(this,Vv)&&(fe(this,gO)?fe(this,Vv).cancel({revert:!0}):fe(this,Vv).cancelRetry()),this.scheduleGc()),fe(this,g2).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Xt(this,fk,mC).call(this,{type:"invalidate"})}fetch(t,n){var d,u,h;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(fe(this,Vv))return fe(this,Vv).continueRetry(),fe(this,Vv).promise}if(t&&this.setOptions(t),!this.options.queryFn){const m=this.observers.find(p=>p.options.queryFn);m&&this.setOptions(m.options)}const r=new AbortController,a=m=>{Object.defineProperty(m,"signal",{enumerable:!0,get:()=>($t(this,gO,!0),r.signal)})},i=()=>{const m=j6t(this.options,n),f=(()=>{const x={client:fe(this,fO),queryKey:this.queryKey,meta:this.meta};return a(x),x})();return $t(this,gO,!1),this.options.persister?this.options.persister(m,f,this):m(f)},o=(()=>{const m={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:fe(this,fO),state:this.state,fetchFn:i};return a(m),m})();(d=this.options.behavior)==null||d.onFetch(o,this),$t(this,pO,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=o.fetchOptions)==null?void 0:u.meta))&&Xt(this,fk,mC).call(this,{type:"fetch",meta:(h=o.fetchOptions)==null?void 0:h.meta});const c=m=>{var p,f,x,y;FDe(m)&&m.silent||Xt(this,fk,mC).call(this,{type:"error",error:m}),FDe(m)||((f=(p=fe(this,g2).config).onError)==null||f.call(p,m,this),(y=(x=fe(this,g2).config).onSettled)==null||y.call(x,this.state.data,m,this)),this.scheduleGc()};return $t(this,Vv,C6t({initialPromise:n==null?void 0:n.initialPromise,fn:o.fetchFn,abort:r.abort.bind(r),onSuccess:m=>{var p,f,x,y;if(m===void 0){c(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(m)}catch(v){c(v);return}(f=(p=fe(this,g2).config).onSuccess)==null||f.call(p,m,this),(y=(x=fe(this,g2).config).onSettled)==null||y.call(x,m,this.state.error,this),this.scheduleGc()},onError:c,onFail:(m,p)=>{Xt(this,fk,mC).call(this,{type:"failed",failureCount:m,error:p})},onPause:()=>{Xt(this,fk,mC).call(this,{type:"pause"})},onContinue:()=>{Xt(this,fk,mC).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0})),fe(this,Vv).start()}},g$=new WeakMap,pO=new WeakMap,g2=new WeakMap,fO=new WeakMap,Vv=new WeakMap,ese=new WeakMap,gO=new WeakMap,fk=new WeakSet,mC=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,...E6t(r.data,this.options),fetchMeta:t.meta??null};case"success":return $t(this,pO,void 0),{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const a=t.error;return FDe(a)&&a.revert&&fe(this,pO)?{...fe(this,pO),fetchStatus:"idle"}:{...r,error:a,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:a,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),t0.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),fe(this,g2).notify({query:this,type:"updated",action:t})})},Z3t);function E6t(s,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:k6t(t.networkMode)?"fetching":"paused",...s===void 0&&{error:null,status:"pending"}}}function yxs(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 L5,X3t,vxs=(X3t=class extends cG{constructor(t={}){super();is(this,L5);this.config=t,$t(this,L5,new Map)}build(t,n,r){const a=n.queryKey,i=n.queryHash??CZe(a,n);let l=this.get(i);return l||(l=new xxs({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(a)}),this.add(l)),l}add(t){fe(this,L5).has(t.queryHash)||(fe(this,L5).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=fe(this,L5).get(t.queryHash);n&&(t.destroy(),n===t&&fe(this,L5).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){t0.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return fe(this,L5).get(t)}getAll(){return[...fe(this,L5).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>Eut(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Eut(t,r)):n}notify(t){t0.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){t0.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){t0.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},L5=new WeakMap,X3t),I5,H1,xO,R5,wT,Q3t,bxs=(Q3t=class extends A6t{constructor(t){super();is(this,R5);is(this,I5);is(this,H1);is(this,xO);this.mutationId=t.mutationId,$t(this,H1,t.mutationCache),$t(this,I5,[]),this.state=t.state||T6t(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){fe(this,I5).includes(t)||(fe(this,I5).push(t),this.clearGcTimeout(),fe(this,H1).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){$t(this,I5,fe(this,I5).filter(n=>n!==t)),this.scheduleGc(),fe(this,H1).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){fe(this,I5).length||(this.state.status==="pending"?this.scheduleGc():fe(this,H1).remove(this))}continue(){var t;return((t=fe(this,xO))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var i,l,o,c,d,u,h,m,p,f,x,y,v,b,N,S,A,T,L,M;const n=()=>{Xt(this,R5,wT).call(this,{type:"continue"})};$t(this,xO,C6t({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(I,R)=>{Xt(this,R5,wT).call(this,{type:"failed",failureCount:I,error:R})},onPause:()=>{Xt(this,R5,wT).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>fe(this,H1).canRun(this)}));const r=this.state.status==="pending",a=!fe(this,xO).canStart();try{if(r)n();else{Xt(this,R5,wT).call(this,{type:"pending",variables:t,isPaused:a}),await((l=(i=fe(this,H1).config).onMutate)==null?void 0:l.call(i,t,this));const R=await((c=(o=this.options).onMutate)==null?void 0:c.call(o,t));R!==this.state.context&&Xt(this,R5,wT).call(this,{type:"pending",context:R,variables:t,isPaused:a})}const I=await fe(this,xO).start();return await((u=(d=fe(this,H1).config).onSuccess)==null?void 0:u.call(d,I,t,this.state.context,this)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,I,t,this.state.context)),await((f=(p=fe(this,H1).config).onSettled)==null?void 0:f.call(p,I,null,this.state.variables,this.state.context,this)),await((y=(x=this.options).onSettled)==null?void 0:y.call(x,I,null,t,this.state.context)),Xt(this,R5,wT).call(this,{type:"success",data:I}),I}catch(I){try{throw await((b=(v=fe(this,H1).config).onError)==null?void 0:b.call(v,I,t,this.state.context,this)),await((S=(N=this.options).onError)==null?void 0:S.call(N,I,t,this.state.context)),await((T=(A=fe(this,H1).config).onSettled)==null?void 0:T.call(A,void 0,I,this.state.variables,this.state.context,this)),await((M=(L=this.options).onSettled)==null?void 0:M.call(L,void 0,I,t,this.state.context)),I}finally{Xt(this,R5,wT).call(this,{type:"error",error:I})}}finally{fe(this,H1).runNext(this)}}},I5=new WeakMap,H1=new WeakMap,xO=new WeakMap,R5=new WeakSet,wT=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),t0.batch(()=>{fe(this,I5).forEach(r=>{r.onMutationUpdate(t)}),fe(this,H1).notify({mutation:this,type:"updated",action:t})})},Q3t);function T6t(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var OC,gk,tse,J3t,_xs=(J3t=class extends cG{constructor(t={}){super();is(this,OC);is(this,gk);is(this,tse);this.config=t,$t(this,OC,new Set),$t(this,gk,new Map),$t(this,tse,0)}build(t,n,r){const a=new bxs({mutationCache:this,mutationId:++O0(this,tse)._,options:t.defaultMutationOptions(n),state:r});return this.add(a),a}add(t){fe(this,OC).add(t);const n=ooe(t);if(typeof n=="string"){const r=fe(this,gk).get(n);r?r.push(t):fe(this,gk).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(fe(this,OC).delete(t)){const n=ooe(t);if(typeof n=="string"){const r=fe(this,gk).get(n);if(r)if(r.length>1){const a=r.indexOf(t);a!==-1&&r.splice(a,1)}else r[0]===t&&fe(this,gk).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=ooe(t);if(typeof n=="string"){const r=fe(this,gk).get(n),a=r==null?void 0:r.find(i=>i.state.status==="pending");return!a||a===t}else return!0}runNext(t){var r;const n=ooe(t);if(typeof n=="string"){const a=(r=fe(this,gk).get(n))==null?void 0:r.find(i=>i!==t&&i.state.isPaused);return(a==null?void 0:a.continue())??Promise.resolve()}else return Promise.resolve()}clear(){t0.batch(()=>{fe(this,OC).forEach(t=>{this.notify({type:"removed",mutation:t})}),fe(this,OC).clear(),fe(this,gk).clear()})}getAll(){return Array.from(fe(this,OC))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>Tut(n,r))}findAll(t={}){return this.getAll().filter(n=>Tut(t,n))}notify(t){t0.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return t0.batch(()=>Promise.all(t.map(n=>n.continue().catch(K1))))}},OC=new WeakMap,gk=new WeakMap,tse=new WeakMap,J3t);function ooe(s){var t;return(t=s.options.scope)==null?void 0:t.id}function H3e(s){return{onFetch:(t,n)=>{var u,h,m,p,f;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=((p=t.state.data)==null?void 0:p.pages)||[],l=((f=t.state.data)==null?void 0:f.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const d=async()=>{let x=!1;const y=N=>{Object.defineProperty(N,"signal",{enumerable:!0,get:()=>(t.signal.aborted?x=!0:t.signal.addEventListener("abort",()=>{x=!0}),t.signal)})},v=j6t(t.options,t.fetchOptions),b=async(N,S,A)=>{if(x)return Promise.reject();if(S==null&&N.pages.length)return Promise.resolve(N);const L=(()=>{const z={client:t.client,queryKey:t.queryKey,pageParam:S,direction:A?"backward":"forward",meta:t.options.meta};return y(z),z})(),M=await v(L),{maxPages:I}=t.options,R=A?uxs:dxs;return{pages:R(N.pages,M,I),pageParams:R(N.pageParams,S,I)}};if(a&&i.length){const N=a==="backward",S=N?M6t:MUe,A={pages:i,pageParams:l},T=S(r,A);o=await b(A,T,N)}else{const N=s??i.length;do{const S=c===0?l[0]??r.initialPageParam:MUe(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 MUe(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 M6t(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 wxs(s,t){return t?MUe(s,t)!=null:!1}function jxs(s,t){return!t||!s.getPreviousPageParam?!1:M6t(s,t)!=null}var Kf,p6,f6,x$,y$,g6,v$,b$,eCt,Nxs=(eCt=class{constructor(s={}){is(this,Kf);is(this,p6);is(this,f6);is(this,x$);is(this,y$);is(this,g6);is(this,v$);is(this,b$);$t(this,Kf,s.queryCache||new vxs),$t(this,p6,s.mutationCache||new _xs),$t(this,f6,s.defaultOptions||{}),$t(this,x$,new Map),$t(this,y$,new Map),$t(this,g6,0)}mount(){O0(this,g6)._++,fe(this,g6)===1&&($t(this,v$,EZe.subscribe(async s=>{s&&(await this.resumePausedMutations(),fe(this,Kf).onFocus())})),$t(this,b$,V3e.subscribe(async s=>{s&&(await this.resumePausedMutations(),fe(this,Kf).onOnline())})))}unmount(){var s,t;O0(this,g6)._--,fe(this,g6)===0&&((s=fe(this,v$))==null||s.call(this),$t(this,v$,void 0),(t=fe(this,b$))==null||t.call(this),$t(this,b$,void 0))}isFetching(s){return fe(this,Kf).findAll({...s,fetchStatus:"fetching"}).length}isMutating(s){return fe(this,p6).findAll({...s,status:"pending"}).length}getQueryData(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=fe(this,Kf).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(s){const t=this.defaultQueryOptions(s),n=fe(this,Kf).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(s):(s.revalidateIfStale&&n.isStaleByTime(FM(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(s){return fe(this,Kf).findAll(s).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(s,t,n){const r=this.defaultQueryOptions({queryKey:s}),a=fe(this,Kf).get(r.queryHash),i=a==null?void 0:a.state.data,l=lxs(t,i);if(l!==void 0)return fe(this,Kf).build(this,r).setData(l,{...n,manual:!0})}setQueriesData(s,t,n){return t0.batch(()=>fe(this,Kf).findAll(s).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=fe(this,Kf).get(t.queryHash))==null?void 0:n.state}removeQueries(s){const t=fe(this,Kf);t0.batch(()=>{t.findAll(s).forEach(n=>{t.remove(n)})})}resetQueries(s,t){const n=fe(this,Kf);return t0.batch(()=>(n.findAll(s).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...s},t)))}cancelQueries(s,t={}){const n={revert:!0,...t},r=t0.batch(()=>fe(this,Kf).findAll(s).map(a=>a.cancel(n)));return Promise.all(r).then(K1).catch(K1)}invalidateQueries(s,t={}){return t0.batch(()=>(fe(this,Kf).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=t0.batch(()=>fe(this,Kf).findAll(s).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,n);return n.throwOnError||(i=i.catch(K1)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(K1)}fetchQuery(s){const t=this.defaultQueryOptions(s);t.retry===void 0&&(t.retry=!1);const n=fe(this,Kf).build(this,t);return n.isStaleByTime(FM(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(s){return this.fetchQuery(s).then(K1).catch(K1)}fetchInfiniteQuery(s){return s.behavior=H3e(s.pages),this.fetchQuery(s)}prefetchInfiniteQuery(s){return this.fetchInfiniteQuery(s).then(K1).catch(K1)}ensureInfiniteQueryData(s){return s.behavior=H3e(s.pages),this.ensureQueryData(s)}resumePausedMutations(){return V3e.isOnline()?fe(this,p6).resumePausedMutations():Promise.resolve()}getQueryCache(){return fe(this,Kf)}getMutationCache(){return fe(this,p6)}getDefaultOptions(){return fe(this,f6)}setDefaultOptions(s){$t(this,f6,s)}setQueryDefaults(s,t){fe(this,x$).set(b7(s),{queryKey:s,defaultOptions:t})}getQueryDefaults(s){const t=[...fe(this,x$).values()],n={};return t.forEach(r=>{QJ(s,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(s,t){fe(this,y$).set(b7(s),{mutationKey:s,defaultOptions:t})}getMutationDefaults(s){const t=[...fe(this,y$).values()],n={};return t.forEach(r=>{QJ(s,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(s){if(s._defaulted)return s;const t={...fe(this,f6).queries,...this.getQueryDefaults(s.queryKey),...s,_defaulted:!0};return t.queryHash||(t.queryHash=CZe(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===AZe&&(t.enabled=!1),t}defaultMutationOptions(s){return s!=null&&s._defaulted?s:{...fe(this,f6).mutations,...(s==null?void 0:s.mutationKey)&&this.getMutationDefaults(s.mutationKey),...s,_defaulted:!0}}clear(){fe(this,Kf).clear(),fe(this,p6).clear()}},Kf=new WeakMap,p6=new WeakMap,f6=new WeakMap,x$=new WeakMap,y$=new WeakMap,g6=new WeakMap,v$=new WeakMap,b$=new WeakMap,eCt),s_,Vd,sse,G1,yO,_$,x6,y6,nse,w$,j$,vO,bO,v6,N$,lh,pZ,PUe,LUe,IUe,RUe,DUe,OUe,FUe,L6t,tCt,P6t=(tCt=class extends cG{constructor(t,n){super();is(this,lh);is(this,s_);is(this,Vd);is(this,sse);is(this,G1);is(this,yO);is(this,_$);is(this,x6);is(this,y6);is(this,nse);is(this,w$);is(this,j$);is(this,vO);is(this,bO);is(this,v6);is(this,N$,new Set);this.options=n,$t(this,s_,t),$t(this,y6,null),$t(this,x6,TUe()),this.options.experimental_prefetchInRender||fe(this,x6).reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(fe(this,Vd).addObserver(this),Lut(fe(this,Vd),this.options)?Xt(this,lh,pZ).call(this):this.updateResult(),Xt(this,lh,RUe).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return zUe(fe(this,Vd),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return zUe(fe(this,Vd),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Xt(this,lh,DUe).call(this),Xt(this,lh,OUe).call(this),fe(this,Vd).removeObserver(this)}setOptions(t){const n=this.options,r=fe(this,Vd);if(this.options=fe(this,s_).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof w2(this.options.enabled,fe(this,Vd))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Xt(this,lh,FUe).call(this),fe(this,Vd).setOptions(this.options),n._defaulted&&!$3e(this.options,n)&&fe(this,s_).getQueryCache().notify({type:"observerOptionsUpdated",query:fe(this,Vd),observer:this});const a=this.hasListeners();a&&Iut(fe(this,Vd),r,this.options,n)&&Xt(this,lh,pZ).call(this),this.updateResult(),a&&(fe(this,Vd)!==r||w2(this.options.enabled,fe(this,Vd))!==w2(n.enabled,fe(this,Vd))||FM(this.options.staleTime,fe(this,Vd))!==FM(n.staleTime,fe(this,Vd)))&&Xt(this,lh,PUe).call(this);const i=Xt(this,lh,LUe).call(this);a&&(fe(this,Vd)!==r||w2(this.options.enabled,fe(this,Vd))!==w2(n.enabled,fe(this,Vd))||i!==fe(this,v6))&&Xt(this,lh,IUe).call(this,i)}getOptimisticResult(t){const n=fe(this,s_).getQueryCache().build(fe(this,s_),t),r=this.createResult(n,t);return Sxs(this,r)&&($t(this,G1,r),$t(this,_$,this.options),$t(this,yO,fe(this,Vd).state)),r}getCurrentResult(){return fe(this,G1)}trackResult(t,n){return new Proxy(t,{get:(r,a)=>(this.trackProp(a),n==null||n(a),Reflect.get(r,a))})}trackProp(t){fe(this,N$).add(t)}getCurrentQuery(){return fe(this,Vd)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=fe(this,s_).defaultQueryOptions(t),r=fe(this,s_).getQueryCache().build(fe(this,s_),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return Xt(this,lh,pZ).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),fe(this,G1)))}createResult(t,n){var I;const r=fe(this,Vd),a=this.options,i=fe(this,G1),l=fe(this,yO),o=fe(this,_$),d=t!==r?t.state:fe(this,sse),{state:u}=t;let h={...u},m=!1,p;if(n._optimisticResults){const R=this.hasListeners(),z=!R&&Lut(t,n),$=R&&Iut(t,r,n,a);(z||$)&&(h={...h,...E6t(u.data,t.options)}),n._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:f,errorUpdatedAt:x,status:y}=h;p=h.data;let v=!1;if(n.placeholderData!==void 0&&p===void 0&&y==="pending"){let R;i!=null&&i.isPlaceholderData&&n.placeholderData===(o==null?void 0:o.placeholderData)?(R=i.data,v=!0):R=typeof n.placeholderData=="function"?n.placeholderData((I=fe(this,j$))==null?void 0:I.state.data,fe(this,j$)):n.placeholderData,R!==void 0&&(y="success",p=EUe(i==null?void 0:i.data,R,n),m=!0)}if(n.select&&p!==void 0&&!v)if(i&&p===(l==null?void 0:l.data)&&n.select===fe(this,nse))p=fe(this,w$);else try{$t(this,nse,n.select),p=n.select(p),p=EUe(i==null?void 0:i.data,p,n),$t(this,w$,p),$t(this,y6,null)}catch(R){$t(this,y6,R)}fe(this,y6)&&(f=fe(this,y6),p=fe(this,w$),x=Date.now(),y="error");const b=h.fetchStatus==="fetching",N=y==="pending",S=y==="error",A=N&&b,T=p!==void 0,M={status:y,fetchStatus:h.fetchStatus,isPending:N,isSuccess:y==="success",isError:S,isInitialLoading:A,isLoading:A,data:p,dataUpdatedAt:h.dataUpdatedAt,error:f,errorUpdatedAt:x,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:b,isRefetching:b&&!N,isLoadingError:S&&!T,isPaused:h.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:S&&T,isStale:TZe(t,n),refetch:this.refetch,promise:fe(this,x6),isEnabled:w2(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const R=H=>{M.status==="error"?H.reject(M.error):M.data!==void 0&&H.resolve(M.data)},z=()=>{const H=$t(this,x6,M.promise=TUe());R(H)},$=fe(this,x6);switch($.status){case"pending":t.queryHash===r.queryHash&&R($);break;case"fulfilled":(M.status==="error"||M.data!==$.value)&&z();break;case"rejected":(M.status!=="error"||M.error!==$.reason)&&z();break}}return M}updateResult(){const t=fe(this,G1),n=this.createResult(fe(this,Vd),this.options);if($t(this,yO,fe(this,Vd).state),$t(this,_$,this.options),fe(this,yO).data!==void 0&&$t(this,j$,fe(this,Vd)),$3e(n,t))return;$t(this,G1,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:a}=this.options,i=typeof a=="function"?a():a;if(i==="all"||!i&&!fe(this,N$).size)return!0;const l=new Set(i??fe(this,N$));return this.options.throwOnError&&l.add("error"),Object.keys(fe(this,G1)).some(o=>{const c=o;return fe(this,G1)[c]!==t[c]&&l.has(c)})};Xt(this,lh,L6t).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Xt(this,lh,RUe).call(this)}},s_=new WeakMap,Vd=new WeakMap,sse=new WeakMap,G1=new WeakMap,yO=new WeakMap,_$=new WeakMap,x6=new WeakMap,y6=new WeakMap,nse=new WeakMap,w$=new WeakMap,j$=new WeakMap,vO=new WeakMap,bO=new WeakMap,v6=new WeakMap,N$=new WeakMap,lh=new WeakSet,pZ=function(t){Xt(this,lh,FUe).call(this);let n=fe(this,Vd).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(K1)),n},PUe=function(){Xt(this,lh,DUe).call(this);const t=FM(this.options.staleTime,fe(this,Vd));if(v7||fe(this,G1).isStale||!CUe(t))return;const r=_6t(fe(this,G1).dataUpdatedAt,t)+1;$t(this,vO,setTimeout(()=>{fe(this,G1).isStale||this.updateResult()},r))},LUe=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(fe(this,Vd)):this.options.refetchInterval)??!1},IUe=function(t){Xt(this,lh,OUe).call(this),$t(this,v6,t),!(v7||w2(this.options.enabled,fe(this,Vd))===!1||!CUe(fe(this,v6))||fe(this,v6)===0)&&$t(this,bO,setInterval(()=>{(this.options.refetchIntervalInBackground||EZe.isFocused())&&Xt(this,lh,pZ).call(this)},fe(this,v6)))},RUe=function(){Xt(this,lh,PUe).call(this),Xt(this,lh,IUe).call(this,Xt(this,lh,LUe).call(this))},DUe=function(){fe(this,vO)&&(clearTimeout(fe(this,vO)),$t(this,vO,void 0))},OUe=function(){fe(this,bO)&&(clearInterval(fe(this,bO)),$t(this,bO,void 0))},FUe=function(){const t=fe(this,s_).getQueryCache().build(fe(this,s_),this.options);if(t===fe(this,Vd))return;const n=fe(this,Vd);$t(this,Vd,t),$t(this,sse,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},L6t=function(t){t0.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(fe(this,G1))}),fe(this,s_).getQueryCache().notify({query:fe(this,Vd),type:"observerResultsUpdated"})})},tCt);function kxs(s,t){return w2(t.enabled,s)!==!1&&s.state.data===void 0&&!(s.state.status==="error"&&t.retryOnMount===!1)}function Lut(s,t){return kxs(s,t)||s.state.data!==void 0&&zUe(s,t,t.refetchOnMount)}function zUe(s,t,n){if(w2(t.enabled,s)!==!1&&FM(t.staleTime,s)!=="static"){const r=typeof n=="function"?n(s):n;return r==="always"||r!==!1&&TZe(s,t)}return!1}function Iut(s,t,n,r){return(s!==t||w2(r.enabled,s)===!1)&&(!n.suspense||s.state.status!=="error")&&TZe(s,n)}function TZe(s,t){return w2(t.enabled,s)!==!1&&s.isStaleByTime(FM(t.staleTime,s))}function Sxs(s,t){return!$3e(s.getCurrentResult(),t)}var Cxs=class extends P6t{constructor(s,t){super(s,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(s){super.setOptions({...s,behavior:H3e()})}getOptimisticResult(s){return s.behavior=H3e(),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,x;const{state:n}=s,r=super.createResult(s,t),{isFetching:a,isRefetching:i,isError:l,isRefetchError:o}=r,c=(x=(f=n.fetchMeta)==null?void 0:f.fetchMore)==null?void 0:x.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:wxs(t,n.data),hasPreviousPage:jxs(t,n.data),isFetchNextPageError:d,isFetchingNextPage:u,isFetchPreviousPageError:h,isFetchingPreviousPage:m,isRefetchError:o&&!d&&!h,isRefetching:i&&!u&&!m}}},b6,_6,n_,FC,WA,y5e,BUe,sCt,Axs=(sCt=class extends cG{constructor(n,r){super();is(this,WA);is(this,b6);is(this,_6);is(this,n_);is(this,FC);$t(this,b6,n),this.setOptions(r),this.bindMethods(),Xt(this,WA,y5e).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=fe(this,b6).defaultMutationOptions(n),$3e(this.options,r)||fe(this,b6).getMutationCache().notify({type:"observerOptionsUpdated",mutation:fe(this,n_),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&b7(r.mutationKey)!==b7(this.options.mutationKey)?this.reset():((a=fe(this,n_))==null?void 0:a.state.status)==="pending"&&fe(this,n_).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=fe(this,n_))==null||n.removeObserver(this)}onMutationUpdate(n){Xt(this,WA,y5e).call(this),Xt(this,WA,BUe).call(this,n)}getCurrentResult(){return fe(this,_6)}reset(){var n;(n=fe(this,n_))==null||n.removeObserver(this),$t(this,n_,void 0),Xt(this,WA,y5e).call(this),Xt(this,WA,BUe).call(this)}mutate(n,r){var a;return $t(this,FC,r),(a=fe(this,n_))==null||a.removeObserver(this),$t(this,n_,fe(this,b6).getMutationCache().build(fe(this,b6),this.options)),fe(this,n_).addObserver(this),fe(this,n_).execute(n)}},b6=new WeakMap,_6=new WeakMap,n_=new WeakMap,FC=new WeakMap,WA=new WeakSet,y5e=function(){var r;const n=((r=fe(this,n_))==null?void 0:r.state)??T6t();$t(this,_6,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},BUe=function(n){t0.batch(()=>{var r,a,i,l,o,c,d,u;if(fe(this,FC)&&this.hasListeners()){const h=fe(this,_6).variables,m=fe(this,_6).context;(n==null?void 0:n.type)==="success"?((a=(r=fe(this,FC)).onSuccess)==null||a.call(r,n.data,h,m),(l=(i=fe(this,FC)).onSettled)==null||l.call(i,n.data,null,h,m)):(n==null?void 0:n.type)==="error"&&((c=(o=fe(this,FC)).onError)==null||c.call(o,n.error,h,m),(u=(d=fe(this,FC)).onSettled)==null||u.call(d,void 0,n.error,h,m))}this.listeners.forEach(h=>{h(fe(this,_6))})})},sCt),I6t=j.createContext(void 0),Qt=s=>{const t=j.useContext(I6t);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Exs=({client:s,children:t})=>(j.useEffect(()=>(s.mount(),()=>{s.unmount()}),[s]),e.jsx(I6t.Provider,{value:s,children:t})),R6t=j.createContext(!1),Txs=()=>j.useContext(R6t);R6t.Provider;function Mxs(){let s=!1;return{clearReset:()=>{s=!1},reset:()=>{s=!0},isReset:()=>s}}var Pxs=j.createContext(Mxs()),Lxs=()=>j.useContext(Pxs),Ixs=(s,t)=>{(s.suspense||s.throwOnError||s.experimental_prefetchInRender)&&(t.isReset()||(s.retryOnMount=!1))},Rxs=s=>{j.useEffect(()=>{s.clearReset()},[s])},Dxs=({result:s,errorResetBoundary:t,throwOnError:n,query:r,suspense:a})=>s.isError&&!t.isReset()&&!s.isFetching&&r&&(a&&s.data===void 0||N6t(n,[s.error,r])),Oxs=s=>{if(s.suspense){const t=r=>r==="static"?r:Math.max(r??1e3,1e3),n=s.staleTime;s.staleTime=typeof n=="function"?(...r)=>t(n(...r)):t(n),typeof s.gcTime=="number"&&(s.gcTime=Math.max(s.gcTime,1e3))}},Fxs=(s,t)=>s.isLoading&&s.isFetching&&!t,zxs=(s,t)=>(s==null?void 0:s.suspense)&&t.isPending,Rut=(s,t,n)=>t.fetchOptimistic(s).catch(()=>{n.clearReset()});function D6t(s,t,n){var h,m,p,f,x;const r=Txs(),a=Lxs(),i=Qt(),l=i.defaultQueryOptions(s);(m=(h=i.getDefaultOptions().queries)==null?void 0:h._experimental_beforeQuery)==null||m.call(h,l),l._optimisticResults=r?"isRestoring":"optimistic",Oxs(l),Ixs(l,a),Rxs(a);const o=!i.getQueryCache().get(l.queryHash),[c]=j.useState(()=>new t(i,l)),d=c.getOptimisticResult(l),u=!r&&s.subscribed!==!1;if(j.useSyncExternalStore(j.useCallback(y=>{const v=u?c.subscribe(t0.batchCalls(y)):K1;return c.updateResult(),v},[c,u]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),j.useEffect(()=>{c.setOptions(l)},[l,c]),zxs(l,d))throw Rut(l,c,a);if(Dxs({result:d,errorResetBoundary:a,throwOnError:l.throwOnError,query:i.getQueryCache().get(l.queryHash),suspense:l.suspense}))throw d.error;if((f=(p=i.getDefaultOptions().queries)==null?void 0:p._experimental_afterQuery)==null||f.call(p,l,d),l.experimental_prefetchInRender&&!v7&&Fxs(d,r)){const y=o?Rut(l,c,a):(x=i.getQueryCache().get(l.queryHash))==null?void 0:x.promise;y==null||y.catch(K1).finally(()=>{c.updateResult()})}return l.notifyOnChangeProps?d:c.trackResult(d)}function ct(s,t){return D6t(s,P6t)}function yt(s,t){const n=Qt(),[r]=j.useState(()=>new Axs(n,s));j.useEffect(()=>{r.setOptions(s)},[r,s]);const a=j.useSyncExternalStore(j.useCallback(l=>r.subscribe(t0.batchCalls(l)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=j.useCallback((l,o)=>{r.mutate(l,o).catch(K1)},[r]);if(a.error&&N6t(r.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:i,mutateAsync:a.mutate}}function Bxs(s,t){return D6t(s,Cxs)}/** * @remix-run/router v1.23.0 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function JJ(){return JJ=Object.assign?Object.assign.bind():function(s){for(var t=1;t"u")throw new Error(t)}function O6t(s,t){if(!s){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function qxs(){return Math.random().toString(36).substr(2,8)}function Out(s,t){return{usr:s.state,key:s.key,idx:t}}function UUe(s,t,n,r){return n===void 0&&(n=null),JJ({pathname:typeof s=="string"?s:s.pathname,search:"",hash:""},typeof t=="string"?dG(t):t,{state:n,key:t&&t.key||r||qxs()})}function G3e(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 dG(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 $xs(s,t,n,r){r===void 0&&(r={});let{window:a=document.defaultView,v5Compat:i=!1}=r,l=a.history,o=X6.Pop,c=null,d=u();d==null&&(d=0,l.replaceState(JJ({},l.state,{idx:d}),""));function u(){return(l.state||{idx:null}).idx}function h(){o=X6.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=X6.Push;let b=UUe(x.location,y,v);d=u()+1;let N=Out(b,d),S=x.createHref(b);try{l.pushState(N,"",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 p(y,v){o=X6.Replace;let b=UUe(x.location,y,v);d=u();let N=Out(b,d),S=x.createHref(b);l.replaceState(N,"",S),i&&c&&c({action:o,location:x.location,delta:0})}function f(y){let v=a.location.origin!=="null"?a.location.origin:a.location.href,b=typeof y=="string"?y:G3e(y);return b=b.replace(/ $/,"%20"),Ef(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(Dut,h),c=y,()=>{a.removeEventListener(Dut,h),c=null}},createHref(y){return t(a,y)},createURL:f,encodeLocation(y){let v=f(y);return{pathname:v.pathname,search:v.search,hash:v.hash}},push:m,replace:p,go(y){return l.go(y)}};return x}var Fut;(function(s){s.data="data",s.deferred="deferred",s.redirect="redirect",s.error="error"})(Fut||(Fut={}));function Vxs(s,t,n){return n===void 0&&(n="/"),Hxs(s,t,n,!1)}function Hxs(s,t,n,r){let a=typeof t=="string"?dG(t):t,i=LV(a.pathname||"/",n);if(i==null)return null;let l=F6t(s);Gxs(l);let o=null;for(let c=0;o==null&&c{let c={relativePath:o===void 0?i.path||"":o,caseSensitive:i.caseSensitive===!0,childrenIndex:l,route:i};c.relativePath.startsWith("/")&&(Ef(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=zM([r,c.relativePath]),u=n.concat(c);i.children&&i.children.length>0&&(Ef(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),F6t(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:Jxs(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 z6t(i.path))a(i,l,c)}),t}function z6t(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=z6t(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 Gxs(s){s.sort((t,n)=>t.score!==n.score?n.score-t.score:e0s(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const Wxs=/^:[\w-]+$/,Kxs=3,Yxs=2,Zxs=1,Xxs=10,Qxs=-2,zut=s=>s==="*";function Jxs(s,t){let n=s.split("/"),r=n.length;return n.some(zut)&&(r+=Qxs),t&&(r+=Yxs),n.filter(a=>!zut(a)).reduce((a,i)=>a+(Wxs.test(i)?Kxs:i===""?Zxs:Xxs),r)}function e0s(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 t0s(s,t,n){let{routesMeta:r}=s,a={},i="/",l=[];for(let o=0;o{let{paramName:m,isOptional:p}=u;if(m==="*"){let x=o[h]||"";l=i.slice(0,i.length-x.length).replace(/(.)\/+$/,"$1")}const f=o[h];return p&&!f?d[m]=void 0:d[m]=(f||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:l,pattern:s}}function s0s(s,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),O6t(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 n0s(s){try{return s.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return O6t(!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 LV(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 r0s(s,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:a=""}=typeof s=="string"?dG(s):s;return{pathname:n?n.startsWith("/")?n:a0s(n,t):t,search:l0s(r),hash:c0s(a)}}function a0s(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 zDe(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 i0s(s){return s.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function MZe(s,t){let n=i0s(s);return t?n.map((r,a)=>a===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function PZe(s,t,n,r){r===void 0&&(r=!1);let a;typeof s=="string"?a=dG(s):(a=JJ({},s),Ef(!a.pathname||!a.pathname.includes("?"),zDe("?","pathname","search",a)),Ef(!a.pathname||!a.pathname.includes("#"),zDe("#","pathname","hash",a)),Ef(!a.search||!a.search.includes("#"),zDe("#","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=r0s(a,o),d=l&&l!=="/"&&l.endsWith("/"),u=(i||l===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}const zM=s=>s.join("/").replace(/\/\/+/g,"/"),o0s=s=>s.replace(/\/+$/,"").replace(/^\/*/,"/"),l0s=s=>!s||s==="?"?"":s.startsWith("?")?s:"?"+s,c0s=s=>!s||s==="#"?"":s.startsWith("#")?s:"#"+s;function d0s(s){return s!=null&&typeof s.status=="number"&&typeof s.statusText=="string"&&typeof s.internal=="boolean"&&"data"in s}const B6t=["post","put","patch","delete"];new Set(B6t);const u0s=["get",...B6t];new Set(u0s);/** * React Router v6.30.1 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function eee(){return eee=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=PZe(d,JSON.parse(l),i,u.relative==="path");s==null&&t!=="/"&&(h.pathname=h.pathname==="/"?t:zM([t,h.pathname])),(u.replace?r.replace:r.push)(h,u.state,u)},[t,r,l,i,s])}const p0s=j.createContext(null);function f0s(s){let t=j.useContext(l3).outlet;return t&&j.createElement(p0s.Provider,{value:s},t)}function Di(){let{matches:s}=j.useContext(l3),t=s[s.length-1];return t?t.params:{}}function R6e(s,t){let{relative:n}=t===void 0?{}:t,{future:r}=j.useContext(gE),{matches:a}=j.useContext(l3),{pathname:i}=Od(),l=JSON.stringify(MZe(a,r.v7_relativeSplatPath));return j.useMemo(()=>PZe(s,JSON.parse(l),i,n==="path"),[s,l,i,n])}function g0s(s,t){return x0s(s,t)}function x0s(s,t,n,r){uG()||Ef(!1);let{navigator:a}=j.useContext(gE),{matches:i}=j.useContext(l3),l=i[i.length-1],o=l?l.params:{};l&&l.pathname;let c=l?l.pathnameBase:"/";l&&l.route;let d=Od(),u;if(t){var h;let y=typeof t=="string"?dG(t):t;c==="/"||(h=y.pathname)!=null&&h.startsWith(c)||Ef(!1),u=y}else u=d;let m=u.pathname||"/",p=m;if(c!=="/"){let y=c.replace(/^\//,"").split("/");p="/"+m.replace(/^\//,"").split("/").slice(y.length).join("/")}let f=Vxs(s,{pathname:p}),x=w0s(f&&f.map(y=>Object.assign({},y,{params:Object.assign({},o,y.params),pathname:zM([c,a.encodeLocation?a.encodeLocation(y.pathname).pathname:y.pathname]),pathnameBase:y.pathnameBase==="/"?c:zM([c,a.encodeLocation?a.encodeLocation(y.pathnameBase).pathname:y.pathnameBase])})),i,n,r);return t&&x?j.createElement(I6e.Provider,{value:{location:eee({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:X6.Pop}},x):x}function y0s(){let s=S0s(),t=d0s(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 v0s=j.createElement(y0s,null);class b0s 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(l3.Provider,{value:this.props.routeContext},j.createElement(q6t.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function _0s(s){let{routeContext:t,match:n,children:r}=s,a=j.useContext(L6e);return a&&a.static&&a.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=n.route.id),j.createElement(l3.Provider,{value:t},r)}function w0s(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||Ef(!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 p,f=!1,x=null,y=null;n&&(p=o&&h.route.id?o[h.route.id]:void 0,x=h.route.errorElement||v0s,c&&(d<0&&m===0?(f=!0,y=null):d===m&&(f=!0,y=h.route.hydrateFallbackElement||null)));let v=t.concat(l.slice(0,m+1)),b=()=>{let N;return p?N=x:f?N=y:h.route.Component?N=j.createElement(h.route.Component,null):h.route.element?N=h.route.element:N=u,j.createElement(_0s,{match:h,routeContext:{outlet:u,matches:v,isDataRoute:n!=null},children:N})};return n&&(h.route.ErrorBoundary||h.route.errorElement||m===0)?j.createElement(b0s,{location:n.location,revalidation:n.revalidation,component:x,error:p,children:b(),routeContext:{outlet:null,matches:v,isDataRoute:!0}}):b()},null)}var V6t=function(s){return s.UseBlocker="useBlocker",s.UseRevalidator="useRevalidator",s.UseNavigateStable="useNavigate",s}(V6t||{}),K3e=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}(K3e||{});function j0s(s){let t=j.useContext(L6e);return t||Ef(!1),t}function N0s(s){let t=j.useContext(U6t);return t||Ef(!1),t}function k0s(s){let t=j.useContext(l3);return t||Ef(!1),t}function H6t(s){let t=k0s(),n=t.matches[t.matches.length-1];return n.route.id||Ef(!1),n.route.id}function S0s(){var s;let t=j.useContext(q6t),n=N0s(K3e.UseRouteError),r=H6t(K3e.UseRouteError);return t!==void 0?t:(s=n.errors)==null?void 0:s[r]}function C0s(){let{router:s}=j0s(V6t.UseNavigateStable),t=H6t(K3e.UseNavigateStable),n=j.useRef(!1);return $6t(()=>{n.current=!0}),j.useCallback(function(a,i){i===void 0&&(i={}),n.current&&(typeof a=="number"?s.navigate(a):s.navigate(a,eee({fromRouteId:t},i)))},[s,t])}function A0s(s,t){s==null||s.v7_startTransition,s==null||s.v7_relativeSplatPath}function td(s){let{to:t,replace:n,state:r,relative:a}=s;uG()||Ef(!1);let{future:i,static:l}=j.useContext(gE),{matches:o}=j.useContext(l3),{pathname:c}=Od(),d=Wn(),u=PZe(t,MZe(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 LZe(s){return f0s(s.context)}function ns(s){Ef(!1)}function E0s(s){let{basename:t="/",children:n=null,location:r,navigationType:a=X6.Pop,navigator:i,static:l=!1,future:o}=s;uG()&&Ef(!1);let c=t.replace(/^\/*/,"/"),d=j.useMemo(()=>({basename:c,navigator:i,static:l,future:eee({v7_relativeSplatPath:!1},o)}),[c,o,i,l]);typeof r=="string"&&(r=dG(r));let{pathname:u="/",search:h="",hash:m="",state:p=null,key:f="default"}=r,x=j.useMemo(()=>{let y=LV(u,c);return y==null?null:{location:{pathname:y,search:h,hash:m,state:p,key:f},navigationType:a}},[c,u,h,m,p,f,a]);return x==null?null:j.createElement(gE.Provider,{value:d},j.createElement(I6e.Provider,{children:n,value:x}))}function tee(s){let{children:t,location:n}=s;return g0s(qUe(t),n)}new Promise(()=>{});function qUe(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,qUe(r.props.children,i));return}r.type!==ns&&Ef(!1),!r.props.index||!r.props.children||Ef(!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=qUe(r.props.children,i)),n.push(l)}),n}/** * React Router DOM v6.30.1 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function Y3e(){return Y3e=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&(n[a]=s[a]);return n}function T0s(s){return!!(s.metaKey||s.altKey||s.ctrlKey||s.shiftKey)}function M0s(s,t){return s.button===0&&(!t||t==="_self")&&!T0s(s)}function $Ue(s){return s===void 0&&(s=""),new URLSearchParams(typeof s=="string"||Array.isArray(s)||s instanceof URLSearchParams?s:Object.keys(s).reduce((t,n)=>{let r=s[n];return t.concat(Array.isArray(r)?r.map(a=>[n,a]):[[n,r]])},[]))}function P0s(s,t){let n=$Ue(s);return t&&t.forEach((r,a)=>{n.has(a)||t.getAll(a).forEach(i=>{n.append(a,i)})}),n}const L0s=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],I0s=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],R0s="6";try{window.__reactRouterVersion=R0s}catch{}const D0s=j.createContext({isTransitioning:!1}),O0s="startTransition",But=gYe[O0s];function F0s(s){let{basename:t,children:n,future:r,window:a}=s,i=j.useRef();i.current==null&&(i.current=Uxs({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&&But?But(()=>c(h)):c(h)},[c,d]);return j.useLayoutEffect(()=>l.listen(u),[l,u]),j.useEffect(()=>A0s(r),[r]),j.createElement(E0s,{basename:t,children:n,location:o.location,navigationType:o.action,navigator:l,future:r})}const z0s=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",B0s=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,xr=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=G6t(t,L0s),{basename:p}=j.useContext(gE),f,x=!1;if(typeof d=="string"&&B0s.test(d)&&(f=d,z0s))try{let N=new URL(window.location.href),S=d.startsWith("//")?new URL(N.protocol+d):new URL(d),A=LV(S.pathname,p);S.origin===N.origin&&A!=null?d=A+S.search+S.hash:x=!0}catch{}let y=h0s(d,{relative:a}),v=q0s(d,{replace:l,state:o,target:c,preventScrollReset:u,relative:a,viewTransition:h});function b(N){r&&r(N),N.defaultPrevented||v(N)}return j.createElement("a",Y3e({},m,{href:f||y,onClick:x||i?r:b,ref:n,target:c}))}),BT=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=G6t(t,I0s),m=R6e(c,{relative:h.relative}),p=Od(),f=j.useContext(U6t),{navigator:x,basename:y}=j.useContext(gE),v=f!=null&&$0s(m)&&d===!0,b=x.encodeLocation?x.encodeLocation(m).pathname:m.pathname,N=p.pathname,S=f&&f.navigation&&f.navigation.location?f.navigation.location.pathname:null;a||(N=N.toLowerCase(),S=S?S.toLowerCase():null,b=b.toLowerCase()),S&&y&&(S=LV(S,y)||S);const A=b!=="/"&&b.endsWith("/")?b.length-1:b.length;let T=N===b||!l&&N.startsWith(b)&&N.charAt(A)==="/",L=S!=null&&(S===b||!l&&S.startsWith(b)&&S.charAt(b.length)==="/"),M={isActive:T,isPending:L,isTransitioning:v},I=T?r:void 0,R;typeof i=="function"?R=i(M):R=[i,T?"active":null,L?"pending":null,v?"transitioning":null].filter(Boolean).join(" ");let z=typeof o=="function"?o(M):o;return j.createElement(xr,Y3e({},h,{"aria-current":I,className:R,ref:n,style:z,to:c,viewTransition:d}),typeof u=="function"?u(M):u)});var VUe;(function(s){s.UseScrollRestoration="useScrollRestoration",s.UseSubmit="useSubmit",s.UseSubmitFetcher="useSubmitFetcher",s.UseFetcher="useFetcher",s.useViewTransitionState="useViewTransitionState"})(VUe||(VUe={}));var Uut;(function(s){s.UseFetcher="useFetcher",s.UseFetchers="useFetchers",s.UseScrollRestoration="useScrollRestoration"})(Uut||(Uut={}));function U0s(s){let t=j.useContext(L6e);return t||Ef(!1),t}function q0s(s,t){let{target:n,replace:r,state:a,preventScrollReset:i,relative:l,viewTransition:o}=t===void 0?{}:t,c=Wn(),d=Od(),u=R6e(s,{relative:l});return j.useCallback(h=>{if(M0s(h,n)){h.preventDefault();let m=r!==void 0?r:G3e(d)===G3e(u);c(s,{replace:m,state:a,preventScrollReset:i,relative:l,viewTransition:o})}},[d,c,u,r,a,n,s,i,l,o])}function fc(s){let t=j.useRef($Ue(s)),n=j.useRef(!1),r=Od(),a=j.useMemo(()=>P0s(r.search,n.current?null:t.current),[r.search]),i=Wn(),l=j.useCallback((o,c)=>{const d=$Ue(typeof o=="function"?o(a):o);n.current=!0,i("?"+d,c)},[i,a]);return[a,l]}function $0s(s,t){t===void 0&&(t={});let n=j.useContext(D0s);n==null&&Ef(!1);let{basename:r}=U0s(VUe.useViewTransitionState),a=R6e(s,{relative:t.relative});if(!n.isTransitioning)return!1;let i=LV(n.currentLocation.pathname,r)||n.currentLocation.pathname,l=LV(n.nextLocation.pathname,r)||n.nextLocation.pathname;return W3e(a.pathname,l)!=null||W3e(a.pathname,i)!=null}var V0s=typeof Element<"u",H0s=typeof Map=="function",G0s=typeof Set=="function",W0s=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function v5e(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(!v5e(s[r],t[r]))return!1;return!0}var i;if(H0s&&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(!v5e(r.value[1],t.get(r.value[0])))return!1;return!0}if(G0s&&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(W0s&&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(V0s&&s instanceof Element)return!1;for(r=n;r--!==0;)if(!((a[r]==="_owner"||a[r]==="__v"||a[r]==="__o")&&s.$$typeof)&&!v5e(s[a[r]],t[a[r]]))return!1;return!0}return s!==s&&t!==t}var K0s=function(t,n){try{return v5e(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 Y0s=od(K0s);var Z0s=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}},X0s=Z0s;const qut=od(X0s);var Q0s=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))(W6t||{}),BDe={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"]}},$ut=Object.values(W6t),IZe={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},eys=Object.entries(IZe).reduce((s,[t,n])=>(s[n]=t,s),{}),Gk="data-rh",Pq={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},Lq=(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},tys=s=>{let t=Lq(s,"title");const n=Lq(s,Pq.TITLE_TEMPLATE);if(Array.isArray(t)&&(t=t.join("")),n&&t)return n.replace(/%s/g,()=>t);const r=Lq(s,Pq.DEFAULT_TITLE);return t||r||void 0},sys=s=>Lq(s,Pq.ON_CHANGE_CLIENT_STATE)||(()=>{}),UDe=(s,t)=>t.filter(n=>typeof n[s]<"u").map(n=>n[s]).reduce((n,r)=>({...n,...r}),{}),nys=(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),BK=(s,t,n)=>{const r={};return n.filter(a=>Array.isArray(a[s])?!0:(typeof a[s]<"u"&&rys(`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:nys(["href"],s),bodyAttributes:UDe("bodyAttributes",s),defer:Lq(s,Pq.DEFER),encode:Lq(s,Pq.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:UDe("htmlAttributes",s),linkTags:BK("link",["rel","href"],s),metaTags:BK("meta",["name","charset","http-equiv","property","itemprop"],s),noscriptTags:BK("noscript",["innerHTML"],s),onChangeClientState:sys(s),scriptTags:BK("script",["src","innerHTML"],s),styleTags:BK("style",["cssText"],s),title:tys(s),titleAttributes:UDe("titleAttributes",s),prioritizeSeoTags:ays(s,Pq.PRIORITIZE_SEO_TAGS)}),K6t=s=>Array.isArray(s)?s.join(""):s,oys=(s,t)=>{const n=Object.keys(s);for(let r=0;rArray.isArray(s)?s.reduce((n,r)=>(oys(r,t)?n.priority.push(r):n.default.push(r),n),{priority:[],default:[]}):{default:s,priority:[]},Vut=(s,t)=>({...s,[t]:void 0}),lys=["noscript","script","style"],HUe=(s,t=!0)=>t===!1?String(s):String(s).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),Y6t=s=>Object.keys(s).reduce((t,n)=>{const r=typeof s[n]<"u"?`${n}="${s[n]}"`:`${n}`;return t?`${t} ${r}`:r},""),cys=(s,t,n,r)=>{const a=Y6t(n),i=K6t(t);return a?`<${s} ${Gk}="true" ${a}>${HUe(i,r)}`:`<${s} ${Gk}="true">${HUe(i,r)}`},dys=(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}="${HUe(i[u],n)}"`;return d?`${d} ${h}`:h},""),o=i.innerHTML||i.cssText||"",c=lys.indexOf(s)===-1;return`${r}<${s} ${Gk}="true" ${l}${c?"/>":`>${o}`}`},""),Z6t=(s,t={})=>Object.keys(s).reduce((n,r)=>{const a=IZe[r];return n[a||r]=s[r],n},t),uys=(s,t,n)=>{const r={key:t,[Gk]:!0},a=Z6t(n,r);return[Dt.createElement("title",a,t)]},b5e=(s,t)=>t.map((n,r)=>{const a={key:r,[Gk]:!0};return Object.keys(n).forEach(i=>{const o=IZe[i]||i;if(o==="innerHTML"||o==="cssText"){const c=n.innerHTML||n.cssText;a.dangerouslySetInnerHTML={__html:c}}else a[o]=n[i]}),Dt.createElement(s,a)}),f2=(s,t,n=!0)=>{switch(s){case"title":return{toComponent:()=>uys(s,t.title,t.titleAttributes),toString:()=>cys(s,t.title,t.titleAttributes,n)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>Z6t(t),toString:()=>Y6t(t)};default:return{toComponent:()=>b5e(s,t),toString:()=>dys(s,t,n)}}},hys=({metaTags:s,linkTags:t,scriptTags:n,encode:r})=>{const a=qDe(s,BDe.meta),i=qDe(t,BDe.link),l=qDe(n,BDe.script);return{priorityMethods:{toComponent:()=>[...b5e("meta",a.priority),...b5e("link",i.priority),...b5e("script",l.priority)],toString:()=>`${f2("meta",a.priority,r)} ${f2("link",i.priority,r)} ${f2("script",l.priority,r)}`},metaTags:a.default,linkTags:i.default,scriptTags:l.default}},mys=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,p={toComponent:()=>{},toString:()=>""};return d&&({priorityMethods:p,linkTags:u,metaTags:h,scriptTags:m}=hys(s)),{priority:p,base:f2("base",t,r),bodyAttributes:f2("bodyAttributes",n,r),htmlAttributes:f2("htmlAttributes",a,r),link:f2("link",u,r),meta:f2("meta",h,r),noscript:f2("noscript",i,r),script:f2("script",m,r),style:f2("style",l,r),title:f2("title",{title:o,titleAttributes:c},r)}},GUe=mys,loe=[],X6t=!!(typeof window<"u"&&window.document&&window.document.createElement),WUe=class{constructor(s,t){Lr(this,"instances",[]);Lr(this,"canUseDOM",X6t);Lr(this,"context");Lr(this,"value",{setHelmet:s=>{this.context.helmet=s},helmetInstances:{get:()=>this.canUseDOM?loe:this.instances,add:s=>{(this.canUseDOM?loe:this.instances).push(s)},remove:s=>{const t=(this.canUseDOM?loe:this.instances).indexOf(s);(this.canUseDOM?loe:this.instances).splice(t,1)}}});this.context=s,this.canUseDOM=t||!1,t||(s.helmet=GUe({baseTag:[],bodyAttributes:{},encodeSpecialCharacters:!0,htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},pys={},Q6t=Dt.createContext(pys),_O,J6t=(_O=class extends j.Component{constructor(n){super(n);Lr(this,"helmetData");this.helmetData=new WUe(this.props.context||{},_O.canUseDOM)}render(){return Dt.createElement(Q6t.Provider,{value:this.helmetData.value},this.props.children)}},Lr(_O,"canUseDOM",X6t),_O),Rz=(s,t)=>{const n=document.head||document.querySelector("head"),r=n.querySelectorAll(`${s}[${Gk}]`),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(Gk,"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}},KUe=(s,t)=>{const n=document.getElementsByTagName(s)[0];if(!n)return;const r=n.getAttribute(Gk),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(Gk):n.getAttribute(Gk)!==l.join(",")&&n.setAttribute(Gk,l.join(","))},fys=(s,t)=>{typeof s<"u"&&document.title!==s&&(document.title=K6t(s)),KUe("title",t)},Hut=(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;KUe("body",r),KUe("html",a),fys(h,m);const p={baseTag:Rz("base",n),linkTags:Rz("link",i),metaTags:Rz("meta",l),noscriptTags:Rz("noscript",o),scriptTags:Rz("script",d),styleTags:Rz("style",u)},f={},x={};Object.keys(p).forEach(y=>{const{newTags:v,oldTags:b}=p[y];v.length&&(f[y]=v),b.length&&(x[y]=p[y].oldTags)}),t&&t(),c(s,f,x)},UK=null,gys=s=>{UK&&cancelAnimationFrame(UK),s.defer?UK=requestAnimationFrame(()=>{Hut(s,()=>{UK=null})}):(Hut(s),UK=null)},xys=gys,Gut=class extends j.Component{constructor(){super(...arguments);Lr(this,"rendered",!1)}shouldComponentUpdate(t){return!J0s(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=iys(t.get().map(i=>{const l={...i.props};return delete l.context,l}));J6t.canUseDOM?xys(a):GUe&&(r=GUe(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}},_Be,dl=(_Be=class extends j.Component{shouldComponentUpdate(s){return!Y0s(Vut(this.props,"helmetData"),Vut(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 qut($ut.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 ${$ut.join(", ")} are allowed. Helmet does not support rendering <${s.type}> elements. Refer to our API for more information.`),qut(!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 Dt.Children.forEach(s,r=>{if(!r||!r.props)return;const{children:a,...i}=r.props,l=Object.keys(i).reduce((c,d)=>(c[eys[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 WUe)){const a=r;r=new WUe(a.context,!0),delete n.helmetData}return r?Dt.createElement(Gut,{...n,context:r.value}):Dt.createElement(Q6t.Consumer,null,a=>Dt.createElement(Gut,{...n,context:a}))}},Lr(_Be,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),_Be);const yys=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>ui(async()=>{const{default:r}=await Promise.resolve().then(()=>hG);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)};class RZe extends Error{constructor(t,n="FunctionsError",r){super(t),this.name=n,this.context=r}}class vys extends RZe{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class bys extends RZe{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class Rne extends RZe{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var YUe;(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"})(YUe||(YUe={}));var _ys=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 wys{constructor(t,{headers:n={},customFetch:r,region:a=YUe.Any}={}){this.url=t,this.headers=n,this.region=a,this.fetch=yys(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,n={}){var r;return _ys(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(f=>{throw new vys(f)}),h=u.headers.get("x-relay-error");if(h&&h==="true")throw new bys(u);if(!u.ok)throw new Rne(u);let m=((r=u.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),p;return m==="application/json"?p=yield u.json():m==="application/octet-stream"?p=yield u.blob():m==="text/event-stream"?p=u:m==="multipart/form-data"?p=yield u.formData():p=yield u.text(),{data:p,error:null}}catch(a){return{data:null,error:a}}})}}var p_={},DZe={},D6e={},Dne={},O6e={},F6e={},jys=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")},IV=jys();const Nys=IV.fetch,eMt=IV.fetch.bind(IV),tMt=IV.Headers,kys=IV.Request,Sys=IV.Response,hG=Object.freeze(Object.defineProperty({__proto__:null,Headers:tMt,Request:kys,Response:Sys,default:eMt,fetch:Nys},Symbol.toStringTag,{value:"Module"})),Cys=Lcs(hG);var z6e={};Object.defineProperty(z6e,"__esModule",{value:!0});let Ays=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}};z6e.default=Ays;var sMt=op&&op.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(F6e,"__esModule",{value:!0});const Eys=sMt(Cys),Tys=sMt(z6e);let Mys=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=Eys.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,p=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,p="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,p="OK")}catch{i.status===404&&x===""?(m=204,p="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,p="OK"),d&&this.shouldThrowOnError)throw new Tys.default(d)}return{error:d,data:u,count:h,status:m,statusText:p}});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}};F6e.default=Mys;var Pys=op&&op.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(O6e,"__esModule",{value:!0});const Lys=Pys(F6e);let Iys=class extends Lys.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}};O6e.default=Iys;var Rys=op&&op.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Dne,"__esModule",{value:!0});const Dys=Rys(O6e);let Oys=class extends Dys.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}};Dne.default=Oys;var Fys=op&&op.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(D6e,"__esModule",{value:!0});const qK=Fys(Dne);let zys=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 qK.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 qK.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 qK.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 qK.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 qK.default({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};D6e.default=zys;var B6e={},U6e={};Object.defineProperty(U6e,"__esModule",{value:!0});U6e.version=void 0;U6e.version="0.0.0-automated";Object.defineProperty(B6e,"__esModule",{value:!0});B6e.DEFAULT_HEADERS=void 0;const Bys=U6e;B6e.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Bys.version}`};var nMt=op&&op.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(DZe,"__esModule",{value:!0});const Uys=nMt(D6e),qys=nMt(Dne),$ys=B6e;let Vys=class rMt{constructor(t,{headers:n={},schema:r,fetch:a}={}){this.url=t,this.headers=Object.assign(Object.assign({},$ys.DEFAULT_HEADERS),n),this.schemaName=r,this.fetch=a}from(t){const n=new URL(`${this.url}/${t}`);return new Uys.default(n,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new rMt(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 qys.default({method:l,url:o,headers:d,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};DZe.default=Vys;var mG=op&&op.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(p_,"__esModule",{value:!0});p_.PostgrestError=p_.PostgrestBuilder=p_.PostgrestTransformBuilder=p_.PostgrestFilterBuilder=p_.PostgrestQueryBuilder=p_.PostgrestClient=void 0;const aMt=mG(DZe);p_.PostgrestClient=aMt.default;const iMt=mG(D6e);p_.PostgrestQueryBuilder=iMt.default;const oMt=mG(Dne);p_.PostgrestFilterBuilder=oMt.default;const lMt=mG(O6e);p_.PostgrestTransformBuilder=lMt.default;const cMt=mG(F6e);p_.PostgrestBuilder=cMt.default;const dMt=mG(z6e);p_.PostgrestError=dMt.default;var Hys=p_.default={PostgrestClient:aMt.default,PostgrestQueryBuilder:iMt.default,PostgrestFilterBuilder:oMt.default,PostgrestTransformBuilder:lMt.default,PostgrestBuilder:cMt.default,PostgrestError:dMt.default};const{PostgrestClient:Gys,PostgrestQueryBuilder:sgr,PostgrestFilterBuilder:ngr,PostgrestTransformBuilder:rgr,PostgrestBuilder:agr,PostgrestError:igr}=Hys;let ZUe;typeof window>"u"?ZUe=require("ws"):ZUe=window.WebSocket;const Wys=ZUe,Kys="2.11.10",Yys={"X-Client-Info":`realtime-js/${Kys}`},Zys="1.0.0",uMt=1e4,Xys=1e3;var Iq;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(Iq||(Iq={}));var $1;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})($1||($1={}));var Mk;(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"})(Mk||(Mk={}));var XUe;(function(s){s.websocket="websocket"})(XUe||(XUe={}));var ED;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(ED||(ED={}));class Qys{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 hMt{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 Nm;(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"})(Nm||(Nm={}));const Wut=(s,t,n={})=>{var r;const a=(r=n.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(t).reduce((i,l)=>(i[l]=Jys(l,s,t,a),i),{})},Jys=(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)?mMt(i,l):QUe(l)},mMt=(s,t)=>{if(s.charAt(0)==="_"){const n=s.slice(1,s.length);return nvs(t,n)}switch(s){case Nm.bool:return evs(t);case Nm.float4:case Nm.float8:case Nm.int2:case Nm.int4:case Nm.int8:case Nm.numeric:case Nm.oid:return tvs(t);case Nm.json:case Nm.jsonb:return svs(t);case Nm.timestamp:return rvs(t);case Nm.abstime:case Nm.date:case Nm.daterange:case Nm.int4range:case Nm.int8range:case Nm.money:case Nm.reltime:case Nm.text:case Nm.time:case Nm.timestamptz:case Nm.timetz:case Nm.tsrange:case Nm.tstzrange:return QUe(t);default:return QUe(t)}},QUe=s=>s,evs=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},tvs=s=>{if(typeof s=="string"){const t=parseFloat(s);if(!Number.isNaN(t))return t}return s},svs=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(t){return console.log(`JSON parse error: ${t}`),s}return s},nvs=(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=>mMt(t,o))}return s},rvs=s=>typeof s=="string"?s.replace(" ","T"):s,pMt=s=>{let t=s;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")};class $De{constructor(t,n,r={},a=uMt){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 Kut;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(Kut||(Kut={}));class vQ{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=vQ.syncState(this.state,a,i,l),this.pendingDiffs.forEach(c=>{this.state=vQ.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=vQ.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),p=h.map(y=>y.presence_ref),f=u.filter(y=>p.indexOf(y.presence_ref)<0),x=h.filter(y=>m.indexOf(y.presence_ref)<0);f.length>0&&(o[d]=f),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(p=>p.presence_ref),m=u.filter(p=>h.indexOf(p.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 Yut;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(Yut||(Yut={}));var Zut;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(Zut||(Zut={}));var _C;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(_C||(_C={}));class OZe{constructor(t,n={config:{}},r){this.topic=t,this.params=n,this.socket=r,this.bindings={},this.state=$1.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 $De(this,Mk.join,this.params,this.timeout),this.rejoinTimer=new hMt(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=$1.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=$1.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=$1.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=$1.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Mk.reply,{},(a,i)=>{this._trigger(this._replyEventName(i),a)}),this.presence=new vQ(this),this.broadcastEndpointURL=pMt(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(_C.CHANNEL_ERROR,u)),this._onClose(()=>t==null?void 0:t(_C.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(_C.SUBSCRIBED);return}else{const m=this.bindings.postgres_changes,p=(h=m==null?void 0:m.length)!==null&&h!==void 0?h:0,f=[];for(let x=0;x{this.state=$1.errored,t==null||t(_C.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(_C.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=$1.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Mk.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(r=>{const a=new $De(this,Mk.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 $De(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}=Mk;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(p=>{var f,x,y;return((f=p.filter)===null||f===void 0?void 0:f.event)==="*"||((y=(x=p.filter)===null||x===void 0?void 0:x.event)===null||y===void 0?void 0:y.toLocaleLowerCase())===l}).map(p=>p.callback(m,r)):(i=this.bindings[l])===null||i===void 0||i.filter(p=>{var f,x,y,v,b,N;if(["broadcast","presence","postgres_changes"].includes(l))if("id"in p){const S=p.id,A=(f=p.filter)===null||f===void 0?void 0:f.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=p==null?void 0:p.filter)===null||v===void 0?void 0:v.event)===null||b===void 0?void 0:b.toLocaleLowerCase();return S==="*"||S===((N=n==null?void 0:n.event)===null||N===void 0?void 0:N.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===l}).map(p=>{if(typeof m=="object"&&"ids"in m){const f=m.data,{schema:x,table:y,commit_timestamp:v,type:b,errors:N}=f;m=Object.assign(Object.assign({},{schema:x,table:y,commit_timestamp:v,eventType:b,new:{},old:{},errors:N}),this._getPayloadRecords(f))}p.callback(m,r)})}_isClosed(){return this.state===$1.closed}_isJoined(){return this.state===$1.joined}_isJoining(){return this.state===$1.joining}_isLeaving(){return this.state===$1.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&&OZe.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(Mk.close,{},t)}_onError(t){this._on(Mk.error,{},n=>t(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=$1.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=Wut(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=Wut(t.columns,t.old_record)),n}}const Xut=()=>{},avs=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class ivs{constructor(t,n){var r;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=Yys,this.params={},this.timeout=uMt,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Xut,this.ref=0,this.logger=Xut,this.conn=null,this.sendBuffer=[],this.serializer=new Qys,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let l;return i?l=i:typeof fetch>"u"?l=(...o)=>ui(async()=>{const{default:c}=await Promise.resolve().then(()=>hG);return{default:c}},void 0).then(({default:c})=>c(...o)):l=fetch,(...o)=>l(...o)},this.endPoint=`${t}/${XUe.websocket}`,this.httpEndpoint=pMt(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 hMt(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=Wys),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 ovs(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:Zys}))}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 Iq.connecting:return ED.Connecting;case Iq.open:return ED.Open;case Iq.closing:return ED.Closing;default:return ED.Closed}}isConnected(){return this.connectionState()===ED.Open}channel(t,n={config:{}}){const r=`realtime:${t}`,a=this.getChannels().find(i=>i.topic===r);if(a)return a;{const i=new OZe(`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(Mk.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(Xys,"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(Mk.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([avs],{type:"application/javascript"});n=URL.createObjectURL(r)}return n}}class ovs{constructor(t,n,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=Iq.connecting,this.send=()=>{},this.url=null,this.url=t,this.close=r.close}}class FZe extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function W0(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}class lvs extends FZe{constructor(t,n){super(t),this.name="StorageApiError",this.status=n}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class JUe extends FZe{constructor(t,n){super(t),this.name="StorageUnknownError",this.originalError=n}}var cvs=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 fMt=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>ui(async()=>{const{default:r}=await Promise.resolve().then(()=>hG);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},dvs=()=>cvs(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield ui(()=>Promise.resolve().then(()=>hG),void 0)).Response:Response}),eqe=s=>{if(Array.isArray(s))return s.map(n=>eqe(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]=eqe(r)}),t};var h9=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 VDe=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),uvs=(s,t,n)=>h9(void 0,void 0,void 0,function*(){const r=yield dvs();s instanceof r&&!(n!=null&&n.noResolveJson)?s.json().then(a=>{t(new lvs(VDe(a),s.status||500))}).catch(a=>{t(new JUe(VDe(a),a))}):t(new JUe(VDe(s),s))}),hvs=(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 One(s,t,n,r,a,i){return h9(this,void 0,void 0,function*(){return new Promise((l,o)=>{s(n,hvs(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=>uvs(c,o,r))})})}function Z3e(s,t,n,r){return h9(this,void 0,void 0,function*(){return One(s,"GET",t,n,r)})}function UT(s,t,n,r,a){return h9(this,void 0,void 0,function*(){return One(s,"POST",t,r,a,n)})}function mvs(s,t,n,r,a){return h9(this,void 0,void 0,function*(){return One(s,"PUT",t,r,a,n)})}function pvs(s,t,n,r){return h9(this,void 0,void 0,function*(){return One(s,"HEAD",t,Object.assign(Object.assign({},n),{noResolveJson:!0}),r)})}function gMt(s,t,n,r,a){return h9(this,void 0,void 0,function*(){return One(s,"DELETE",t,r,a,n)})}var Wb=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 fvs={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Qut={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class gvs{constructor(t,n={},r,a){this.url=t,this.headers=n,this.bucketId=r,this.fetch=fMt(a)}uploadOrUpdate(t,n,r,a){return Wb(this,void 0,void 0,function*(){try{let i;const l=Object.assign(Object.assign({},Qut),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(W0(i))return{data:null,error:i};throw i}})}upload(t,n,r){return Wb(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,n,r)})}uploadToSignedUrl(t,n,r,a){return Wb(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:Qut.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(W0(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(t,n){return Wb(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 UT(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 FZe("No token returned by API");return{data:{signedUrl:l.toString(),path:t,token:o},error:null}}catch(r){if(W0(r))return{data:null,error:r};throw r}})}update(t,n,r){return Wb(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,n,r)})}move(t,n,r){return Wb(this,void 0,void 0,function*(){try{return{data:yield UT(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(W0(a))return{data:null,error:a};throw a}})}copy(t,n,r){return Wb(this,void 0,void 0,function*(){try{return{data:{path:(yield UT(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(W0(a))return{data:null,error:a};throw a}})}createSignedUrl(t,n,r){return Wb(this,void 0,void 0,function*(){try{let a=this._getFinalPath(t),i=yield UT(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(W0(a))return{data:null,error:a};throw a}})}createSignedUrls(t,n,r){return Wb(this,void 0,void 0,function*(){try{const a=yield UT(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(W0(a))return{data:null,error:a};throw a}})}download(t,n){return Wb(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 Z3e(this.fetch,`${this.url}/${a}/${o}${l}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(o){if(W0(o))return{data:null,error:o};throw o}})}info(t){return Wb(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{const r=yield Z3e(this.fetch,`${this.url}/object/info/${n}`,{headers:this.headers});return{data:eqe(r),error:null}}catch(r){if(W0(r))return{data:null,error:r};throw r}})}exists(t){return Wb(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{return yield pvs(this.fetch,`${this.url}/object/${n}`,{headers:this.headers}),{data:!0,error:null}}catch(r){if(W0(r)&&r instanceof JUe){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 Wb(this,void 0,void 0,function*(){try{return{data:yield gMt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(n){if(W0(n))return{data:null,error:n};throw n}})}list(t,n,r){return Wb(this,void 0,void 0,function*(){try{const a=Object.assign(Object.assign(Object.assign({},fvs),n),{prefix:t||""});return{data:yield UT(this.fetch,`${this.url}/object/list/${this.bucketId}`,a,{headers:this.headers},r),error:null}}catch(a){if(W0(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 xvs="2.7.1",yvs={"X-Client-Info":`storage-js/${xvs}`};var Dz=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 vvs{constructor(t,n={},r){this.url=t,this.headers=Object.assign(Object.assign({},yvs),n),this.fetch=fMt(r)}listBuckets(){return Dz(this,void 0,void 0,function*(){try{return{data:yield Z3e(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(W0(t))return{data:null,error:t};throw t}})}getBucket(t){return Dz(this,void 0,void 0,function*(){try{return{data:yield Z3e(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(n){if(W0(n))return{data:null,error:n};throw n}})}createBucket(t,n={public:!1}){return Dz(this,void 0,void 0,function*(){try{return{data:yield UT(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(W0(r))return{data:null,error:r};throw r}})}updateBucket(t,n){return Dz(this,void 0,void 0,function*(){try{return{data:yield mvs(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(W0(r))return{data:null,error:r};throw r}})}emptyBucket(t){return Dz(this,void 0,void 0,function*(){try{return{data:yield UT(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(n){if(W0(n))return{data:null,error:n};throw n}})}deleteBucket(t){return Dz(this,void 0,void 0,function*(){try{return{data:yield gMt(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(n){if(W0(n))return{data:null,error:n};throw n}})}}class bvs extends vvs{constructor(t,n={},r){super(t,n,r)}from(t){return new gvs(this.url,this.headers,t,this.fetch)}}const _vs="2.49.10";let fZ="";typeof Deno<"u"?fZ="deno":typeof document<"u"?fZ="web":typeof navigator<"u"&&navigator.product==="ReactNative"?fZ="react-native":fZ="node";const wvs={"X-Client-Info":`supabase-js-${fZ}/${_vs}`},jvs={headers:wvs},Nvs={schema:"public"},kvs={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Svs={};var Cvs=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 Avs=s=>{let t;return s?t=s:typeof fetch>"u"?t=eMt:t=fetch,(...n)=>t(...n)},Evs=()=>typeof Headers>"u"?tMt:Headers,Tvs=(s,t,n)=>{const r=Avs(n),a=Evs();return(i,l)=>Cvs(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 Mvs=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 Pvs(s){return s.endsWith("/")?s:s+"/"}function Lvs(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:()=>Mvs(this,void 0,void 0,function*(){return""})};return s.accessToken?m.accessToken=s.accessToken:delete m.accessToken,m}const xMt="2.69.1",IB=30*1e3,tqe=3,HDe=tqe*IB,Ivs="http://localhost:9999",Rvs="supabase.auth.token",Dvs={"X-Client-Info":`gotrue-js/${xMt}`},sqe="X-Supabase-Api-Version",yMt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Ovs=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Fvs=6e5;class zZe extends Error{constructor(t,n,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}}function Bc(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}class zvs extends zZe{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function Bvs(s){return Bc(s)&&s.name==="AuthApiError"}class vMt extends zZe{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class RP extends zZe{constructor(t,n,r,a){super(t,r,a),this.name=n,this.status=r}}class jT extends RP{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function Uvs(s){return Bc(s)&&s.name==="AuthSessionMissingError"}class GDe extends RP{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class coe extends RP{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class doe extends RP{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 qvs(s){return Bc(s)&&s.name==="AuthImplicitGrantRedirectError"}class Jut extends RP{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 nqe extends RP{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function WDe(s){return Bc(s)&&s.name==="AuthRetryableFetchError"}class eht extends RP{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}}class bQ extends RP{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const tht="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),sht=` \r=`.split(""),$vs=(()=>{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 nht(s){const t=[],n=l=>{t.push(String.fromCodePoint(l))},r={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=l=>{Gvs(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 Hvs(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}Vvs(r,t)}}function Gvs(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 Wvs(s){const t=[],n={queue:0,queuedBits:0},r=a=>{t.push(a)};for(let a=0;at.push(n)),new Uint8Array(t)}function Yvs(s){return Math.round(Date.now()/1e3)+s}function Zvs(){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 b5=()=>typeof window<"u"&&typeof document<"u",WL={tested:!1,writable:!1},_Q=()=>{if(!b5())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(WL.tested)return WL.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),WL.tested=!0,WL.writable=!0}catch{WL.tested=!0,WL.writable=!1}return WL.writable};function Xvs(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 _Mt=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>ui(async()=>{const{default:r}=await Promise.resolve().then(()=>hG);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},Qvs=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",wMt=async(s,t,n)=>{await s.setItem(t,JSON.stringify(n))},uoe=async(s,t)=>{const n=await s.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},hoe=async(s,t)=>{await s.removeItem(t)};class q6e{constructor(){this.promise=new q6e.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}q6e.promiseConstructor=Promise;function KDe(s){const t=s.split(".");if(t.length!==3)throw new bQ("Invalid JWT structure");for(let r=0;r{setTimeout(()=>t(null),s)})}function e1s(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 t1s(s){return("0"+s.toString(16)).substr(-2)}function s1s(){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,t1s).join("")}async function n1s(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 r1s(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 n1s(s);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Oz(s,t,n=!1){const r=s1s();let a=r;n&&(a+="/PASSWORD_RECOVERY"),await wMt(s,`${t}-code-verifier`,a);const i=await r1s(r);return[i,r===i?"plain":"s256"]}const a1s=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function i1s(s){const t=s.headers.get(sqe);if(!t||!t.match(a1s))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function o1s(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 l1s(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 c1s=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),d1s=[502,503,504];async function rht(s){var t;if(!Qvs(s))throw new nqe(pD(s),0);if(d1s.includes(s.status))throw new nqe(pD(s),s.status);let n;try{n=await s.json()}catch(i){throw new vMt(pD(i),i)}let r;const a=i1s(s);if(a&&a.getTime()>=yMt["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 eht(pD(n),s.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(r==="session_not_found")throw new jT}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 eht(pD(n),s.status,n.weak_password.reasons);throw new zvs(pD(n),s.status||500,r)}const u1s=(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 Ld(s,t,n,r){var a;const i=Object.assign({},r==null?void 0:r.headers);i[sqe]||(i[sqe]=yMt["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 h1s(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 h1s(s,t,n,r,a,i){const l=u1s(t,r,a,i);let o;try{o=await s(n,Object.assign({},l))}catch(c){throw console.error(c),new nqe(pD(c),0)}if(o.ok||await rht(o),r!=null&&r.noResolveJson)return o;try{return await o.json()}catch(c){await rht(c)}}function NT(s){var t;let n=null;g1s(s)&&(n=Object.assign({},s),s.expires_at||(n.expires_at=Yvs(s.expires_in)));const r=(t=s.user)!==null&&t!==void 0?t:s;return{data:{session:n,user:r},error:null}}function aht(s){const t=NT(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 s6(s){var t;return{data:{user:(t=s.user)!==null&&t!==void 0?t:s},error:null}}function m1s(s){return{data:s,error:null}}function p1s(s){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:a,verification_type:i}=s,l=c1s(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 f1s(s){return s}function g1s(s){return s.access_token&&s.refresh_token&&s.expires_in}var x1s=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&&(p.forEach(f=>{const x=parseInt(f.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(f.split(";")[1].split("=")[1]);d[`${y}Page`]=x}),d.total=parseInt(m)),{data:Object.assign(Object.assign({},h),d),error:null}}catch(d){if(Bc(d))return{data:{users:[]},error:d};throw d}}async getUserById(t){try{return await Ld(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:s6})}catch(n){if(Bc(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){try{return await Ld(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:s6})}catch(r){if(Bc(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){try{return await Ld(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:s6})}catch(r){if(Bc(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){try{const{data:n,error:r}=await Ld(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(Bc(n))return{data:null,error:n};throw n}}async _deleteFactor(t){try{return{data:await Ld(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(n){if(Bc(n))return{data:null,error:n};throw n}}}const v1s={getItem:s=>_Q()?globalThis.localStorage.getItem(s):null,setItem:(s,t)=>{_Q()&&globalThis.localStorage.setItem(s,t)},removeItem:s=>{_Q()&&globalThis.localStorage.removeItem(s)}};function iht(s={}){return{getItem:t=>s[t]||null,setItem:(t,n)=>{s[t]=n},removeItem:t=>{delete s[t]}}}function b1s(){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 Fz={debug:!!(globalThis&&_Q()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class jMt extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class _1s extends jMt{}async function w1s(s,t,n){Fz.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),Fz.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){Fz.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,a.name);try{return await n()}finally{Fz.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,a.name)}}else{if(t===0)throw Fz.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new _1s(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(Fz.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()}}))}b1s();const j1s={url:Ivs,storageKey:Rvs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Dvs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function oht(s,t,n){return await n()}class see{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=see.nextInstanceID,see.nextInstanceID+=1,this.instanceID>0&&b5()&&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({},j1s),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 y1s({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=_Mt(a.fetch),this.lock=a.lock||oht,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,a.lock?this.lock=a.lock:b5()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=w1s:this.lock=oht,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:_Q()?this.storage=v1s:(this.memoryStorage={},this.storage=iht(this.memoryStorage)):(this.memoryStorage={},this.storage=iht(this.memoryStorage)),b5()&&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} (${xMt}) ${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=Xvs(window.location.href);let r="none";if(this._isImplicitGrantCallback(n)?r="implicit":await this._isPKCECallback(n)&&(r="pkce"),b5()&&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),qvs(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 Bc(n)?{error:n}:{error:new vMt("Unexpected error during initialization",n)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,a;try{const i=await Ld(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:NT}),{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(Bc(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 p=null,f=null;this.flowType==="pkce"&&([p,f]=await Oz(this.storage,this.storageKey)),i=await Ld(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:p,code_challenge_method:f},xform:NT})}else if("phone"in t){const{phone:u,password:h,options:m}=t;i=await Ld(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:NT})}else throw new coe("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(Bc(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 Ld(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:aht})}else if("phone"in t){const{phone:i,password:l,options:o}=t;n=await Ld(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:aht})}else throw new coe("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 GDe}:(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(Bc(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 uoe(this.storage,`${this.storageKey}-code-verifier`),[r,a]=(n??"").split("/");try{const{data:i,error:l}=await Ld(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:NT});if(await hoe(this.storage,`${this.storageKey}-code-verifier`),l)throw l;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new GDe}:(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(Bc(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 Ld(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:NT}),{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 GDe}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:d})}catch(n){if(Bc(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 Oz(this.storage,this.storageKey));const{error:h}=await Ld(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 Ld(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 coe("You must provide either an email or phone number.")}catch(o){if(Bc(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 Ld(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:NT});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(Bc(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 Oz(this.storage,this.storageKey)),await Ld(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:m1s})}catch(i){if(Bc(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 jT;const{error:a}=await Ld(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return{data:{user:null,session:null},error:a}})}catch(t){if(Bc(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 Ld(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 Ld(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 coe("You must provide either an email or phone number and a type")}catch(n){if(Bc(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 uoe(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 Ld(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:s6}):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 jT}:await Ld(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:s6})})}catch(n){if(Bc(n))return Uvs(n)&&(await this._removeSession(),await hoe(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 jT;const l=a.session;let o=null,c=null;this.flowType==="pkce"&&t.email!=null&&([o,c]=await Oz(this.storage,this.storageKey));const{data:d,error:u}=await Ld(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:s6});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(Bc(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 jT;const n=Date.now()/1e3;let r=n,a=!0,i=null;const{payload:l}=KDe(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(Bc(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 jT;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(Bc(n))return{data:{user:null,session:null},error:n};throw n}}async _getSessionFromURL(t,n){try{if(!b5())throw new doe("No browser detected.");if(t.error||t.error_description||t.error_code)throw new doe(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 Jut("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new doe("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 Jut("No code detected.");const{data:b,error:N}=await this._exchangeCodeForSession(t.code);if(N)throw N;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 doe("No session defined in URL");const u=Math.round(Date.now()/1e3),h=parseInt(o);let m=u+h;c&&(m=parseInt(c));const p=m-u;p*1e3<=IB&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${h}s`);const f=m-h;u-f>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",f,m,u):u-f<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",f,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(Bc(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 uoe(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&&!(Bvs(o)&&(o.status===404||o.status===401||o.status===403)))return{error:o}}return t!=="others"&&(await this._removeSession(),await hoe(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(t){const n=Zvs(),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 Oz(this.storage,this.storageKey,!0));try{return await Ld(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(Bc(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(Bc(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 p=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 Ld(this.fetch,"GET",p,{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 b5()&&!(!((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(Bc(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 Ld(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(Bc(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 e1s(async a=>(a>0&&await Jvs(200*Math.pow(2,a-1)),this._debug(n,"refreshing attempt",a),await Ld(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:NT})),(a,i)=>{const l=200*Math.pow(2,a);return i&&WDe(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(),IB);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)/IB);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${IB}ms, refresh threshold is ${tqe} ticks`),a<=tqe&&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 jMt)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!b5()||!(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 Oz(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 Ld(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(Bc(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 Ld(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(Bc(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 Ld(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(Bc(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 Ld(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(Bc(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}=KDe(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+Fvs>Date.now()))return r;const{data:a,error:i}=await Ld(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 bQ("JWKS is empty");if(this.jwks=a,this.jwks_cached_at=Date.now(),r=a.keys.find(l=>l.kid===t),!r)throw new bQ("No matching signing key found in JWKS");return r}async getClaims(t,n={keys:[]}){try{let r=t;if(!r){const{data:p,error:f}=await this.getSession();if(f||!p.session)return{data:null,error:f};r=p.session.access_token}const{header:a,payload:i,signature:l,raw:{header:o,payload:c}}=KDe(r);if(o1s(i.exp),!a.kid||a.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){const{error:p}=await this.getUser(r);if(p)throw p;return{data:{claims:i,header:a,signature:l},error:null}}const d=l1s(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,Kvs(`${o}.${c}`)))throw new bQ("Invalid JWT signature");return{data:{claims:i,header:a,signature:l},error:null}}catch(r){if(Bc(r))return{data:null,error:r};throw r}}}see.nextInstanceID=0;const N1s=see;class k1s extends N1s{constructor(t){super(t)}}var S1s=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 C1s{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=Pvs(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:Nvs,realtime:Svs,auth:Object.assign(Object.assign({},kvs),{storageKey:d}),global:jvs},h=Lvs(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,p)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(p)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((l=h.auth)!==null&&l!==void 0?l:{},this.headers,h.global.fetch),this.fetch=Tvs(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 Gys(new URL("rest/v1",c).href,{headers:this.headers,schema:h.db.schema,fetch:this.fetch}),h.accessToken||this._listenForAuthEvents()}get functions(){return new wys(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new bvs(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 S1s(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 k1s({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 ivs(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 A1s=(s,t,n)=>new C1s(s,t,n);function E1s(){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),p=(b,N,S)=>new Promise(A=>{const T=m();let L=!1,M;const I=$=>{L||(L=!0,clearTimeout(M),window.removeEventListener("message",R),A($))},R=$=>{if(d.indexOf($.origin)<0)return;const H=$.data;H&&H.type===u&&H.requestId===T&&I(H)};window.addEventListener("message",R);const z={type:b,requestId:T,projectId:a,key:N};S!==void 0&&(z.value=S);for(const $ of d)window.parent.postMessage(z,$);M=setTimeout(()=>I(null),h)});let f=!0;const x=250;return{getItem:async b=>{let N=await p("lovable-preview-auth:get",b);return!N&&f&&(await new Promise(S=>setTimeout(S,x)),N=await p("lovable-preview-auth:get",b)),f=!1,N&&N.ok&&typeof N.value=="string"?N.value===""?(localStorage.removeItem(b),null):N.value:localStorage.getItem(b)},setItem:(b,N)=>(localStorage.setItem(b,N),p("lovable-preview-auth:set",b,N).then(()=>{})),removeItem:b=>(localStorage.removeItem(b),p("lovable-preview-auth:remove",b).then(()=>{}))}}const T1s="https://relzejiswnotikjgvjhz.supabase.co",M1s="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",q=A1s(T1s,M1s,{auth:{storage:E1s(),persistSession:!0,autoRefreshToken:!0}}),P1s=Object.freeze(Object.defineProperty({__proto__:null,supabase:q},Symbol.toStringTag,{value:"Module"})),NMt=j.createContext(void 0),L1s=({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),[p,f]=j.useState(!1),[x,y]=j.useState(null),[v,b]=j.useState([]),[N,S]=j.useState(null),A=j.useRef(null),T=j.useRef(!1),L=j.useRef(!1),M=Wn(),I=()=>{u(!1),m(!1),f(!1),y(null),b([]),S(null),A.current=null,T.current=!1},R=async V=>{if(T.current&&A.current===V||L.current)return;L.current=!0,c(!0);const K=window.setTimeout(()=>{console.warn("Role check timeout reached — unblocking UI."),L.current=!1,c(!1)},8e3);try{console.log("Checking roles via RPC for user:",V);const[{data:Z,error:Q},{data:le,error:ue},{data:se,error:ne}]=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(Q||ue)console.error("Role RPC errors:",{isAdminError:Q,isBrokerError:ue,isCoachError:ne}),u(!1),m(!1),f(!1);else{const je=!!Z,be=!!le,he=!!se;console.log("RPC roles result:",{adminValue:je,brokerValue:be,coachValue:he}),u(je),m(be),f(he)}A.current=V,T.current=!0,window.clearTimeout(K),c(!1);const{data:ie,error:ce}=await q.from("profiles").select("brokerage_id").eq("id",V).single();if(y(!ce&&ie?ie.brokerage_id:null),le){console.log("Fetching managed brokerages for user:",V);const{data:je,error:be}=await q.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",V);if(console.log("Managed brokerage assignments result:",{assignments:je,assignmentsError:be}),be||!je){console.error("Error fetching managed brokerage assignments:",be),b([]);return}const he=Array.from(new Set(je.map(Me=>Me.brokerage_id).filter(Boolean)));if(he.length===0){b([]);return}const{data:ge,error:ke}=await q.from("brokerages").select("id, name").in("id",he);if(console.log("Managed brokerages details result:",{brokeragesData:ge,brokeragesError:ke}),ke||!ge){console.error("Error fetching managed brokerages details:",ke),b([]);return}const Te=ge.map(Me=>({id:Me.id,name:Me.name})).sort((Me,Oe)=>he.indexOf(Me.id)-he.indexOf(Oe.id));console.log("Parsed managed brokerages:",Te),b(Te),Te.length>0&&S(Me=>Me??Te[0].id)}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),b([]);A.current=V,T.current=!0}catch(Z){console.error("Unexpected error in checkRoles:",Z),I()}finally{window.clearTimeout(K),L.current=!1,c(!1)}};j.useEffect(()=>{let V=!0,K=!1;const Z=()=>{!V||K||(K=!0,l(!1))},{data:{subscription:Q}}=q.auth.onAuthStateChange((ue,se)=>{console.log("Auth event:",ue),V&&(a(se),n((se==null?void 0:se.user)??null),Z(),ue==="PASSWORD_RECOVERY"&&(console.log("Password recovery detected, redirecting to profile"),setTimeout(()=>{M("/profile?reset=true")},100)),se!=null&&se.user?(!T.current||A.current!==se.user.id)&&setTimeout(()=>{R(se.user.id)},0):(I(),c(!1)))}),le=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),Z()},8e3);return()=>{V=!1,window.clearTimeout(le),Q.unsubscribe()}},[]);const z=async(V,K)=>{const{error:Z}=await q.auth.signInWithPassword({email:V,password:K});if(Z)throw re.error(Z.message),Z;re.success("Welcome back!")},$=async(V,K,Z)=>{var ne;const Q="https://dashboard.relevelup.com/dashboard",le=localStorage.getItem("levelup_referral_code")||null,{data:ue,error:se}=await q.auth.signUp({email:V,password:K,options:{emailRedirectTo:Q,data:{name:Z,referred_by_code:le}}});if(se)throw re.error(se.message),se;if(le&&((ne=ue.user)!=null&&ne.id))try{await q.from("profiles").update({referred_by_code:le}).eq("id",ue.user.id),localStorage.removeItem("levelup_referral_code")}catch(ie){console.warn("Failed to attach referral code to profile",ie)}re.success("Account created! Welcome to LevelUp."),M("/dashboard")},H=async()=>{try{const{data:{session:V}}=await q.auth.getSession();if(V){const{error:K}=await q.auth.signOut();K?K.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",K.message):(console.error("Sign out error:",K),re.error(K.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),M("/auth")}catch(V){console.error("Unexpected sign out error:",V),M("/auth")}};return e.jsx(NMt.Provider,{value:{user:t,session:r,loading:i,rolesLoading:o,signIn:z,signUp:$,signOut:H,isAdmin:d,isBrokerageManager:h,isCoach:p,brokerageId:x,managedBrokerages:v,selectedBrokerageId:N,setSelectedBrokerageId:S},children:s})},vs=()=>{const s=j.useContext(NMt);if(s===void 0)throw new Error("useAuth must be used within an AuthProvider");return s},kMt=j.createContext({onlineUsers:[],totalOnline:0}),I1s=3*60*1e3,R1s=45*1e3,D1s=30*1e3,O1s=({children:s})=>{const{user:t,brokerageId:n,isAdmin:r}=vs(),[a,i]=j.useState([]),l=j.useRef(new Date().toISOString()),o=j.useCallback(async()=>{t&&await q.from("user_presence").upsert({user_id:t.id,last_seen_at:new Date().toISOString(),online_since:l.current,current_path:window.location.pathname},{onConflict:"user_id"})},[t==null?void 0:t.id]),c=j.useCallback(async()=>{if(!t)return;const u=new Date(Date.now()-I1s).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:p}=await q.from("profiles").select("id, name, email, avatar_url, brokerage_id").in("id",m),f=new Map((p||[]).map(x=>[x.id,x]));i(h.map(x=>{var v;const y=f.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()},R1s),p=window.setInterval(()=>{c()},D1s),f=()=>{document.visibilityState==="visible"&&h()};return document.addEventListener("visibilitychange",f),()=>{u=!0,window.clearInterval(m),window.clearInterval(p),document.removeEventListener("visibilitychange",f)}},[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(kMt.Provider,{value:{onlineUsers:d,totalOnline:d.length},children:s})},SMt=()=>j.useContext(kMt),CMt=j.createContext(void 0),KL="levelup_admin_session",tT="levelup_impersonation",YDe="levelup_impersonation_return",F1s=({children:s})=>{const[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState(!1);j.useEffect(()=>{const d=sessionStorage.getItem(tT);if(d)try{const u=JSON.parse(d);n(!0),a(u)}catch{sessionStorage.removeItem(tT)}},[]);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(KL,JSON.stringify(m)),u&&sessionStorage.setItem(YDe,u);const p=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})}),f=await p.json();if(!p.ok)throw new Error(f.error||"Failed to impersonate user");const x={id:f.targetUser.id,name:f.targetUser.name,email:f.targetUser.email};if(sessionStorage.setItem(tT,JSON.stringify(x)),f.method==="session"){const{error:y}=await q.auth.setSession({access_token:f.access_token,refresh_token:f.refresh_token});if(y)throw console.error("Set session error:",y),sessionStorage.removeItem(KL),sessionStorage.removeItem(tT),new Error("Failed to establish impersonation session")}else{const y=f.type||"recovery",{error:v}=await q.auth.verifyOtp({token_hash:f.token_hash,type:y});if(v)throw console.error("Verify OTP error:",v),sessionStorage.removeItem(KL),sessionStorage.removeItem(tT),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(KL),sessionStorage.removeItem(tT),!1}finally{l(!1)}},c=async()=>{l(!0);try{const d=sessionStorage.getItem(KL);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(KL),sessionStorage.removeItem(tT),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(YDe)||"/admin/members";sessionStorage.removeItem(YDe),window.location.href=m}catch(d){console.error("Stop impersonation error:",d),re.error("Failed to restore admin session"),sessionStorage.removeItem(KL),sessionStorage.removeItem(tT),window.location.href="/auth"}finally{l(!1)}};return e.jsx(CMt.Provider,{value:{isImpersonating:t,impersonatedUser:r,startImpersonation:o,stopImpersonation:c,isLoading:i},children:s})},$6e=()=>{const s=j.useContext(CMt);if(s===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return s},z1s=()=>{const{isImpersonating:s,impersonatedUser:t,stopImpersonation:n,isLoading:r}=$6e();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(tc,{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(U,{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(Et,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(er,{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"})]})})]})})},AMt=j.createContext(void 0),zz="levelup_acting_as",moe="levelup_acting_as_self",B1s=({children:s})=>{const{user:t}=vs(),[n,r]=j.useState(!1),[a,i]=j.useState([]),[l,o]=j.useState(null),[c,d]=j.useState({}),[u,h]=j.useState(!0),[m,p]=j.useState(()=>sessionStorage.getItem(moe)==="true");j.useEffect(()=>{if(!(t!=null&&t.id)){r(!1),i([]),o(null),d({}),h(!1);return}(async()=>{h(!0);try{const{data:N}=await q.rpc("has_role",{_user_id:t.id,_role:"assistant"});if(!N){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 T=S.map(I=>I.agent_id),{data:L}=await q.from("profiles").select("id, name, email, avatar_url").in("id",T),M=(L||[]).map(I=>({id:I.id,name:I.name||I.email||"Unknown",email:I.email||"",avatar_url:I.avatar_url}));if(i(M),sessionStorage.getItem(moe)==="true")p(!0),o(null),d({});else{const I=sessionStorage.getItem(zz);if(I){const R=M.find(z=>z.id===I);if(R){o(R);const z=S.find($=>$.agent_id===I);d((z==null?void 0:z.permissions)||{})}else if(M.length>0){o(M[0]);const z=S.find($=>$.agent_id===M[0].id);d((z==null?void 0:z.permissions)||{}),sessionStorage.setItem(zz,M[0].id)}}else if(M.length>0){o(M[0]);const R=S.find(z=>z.agent_id===M[0].id);d((R==null?void 0:R.permissions)||{}),sessionStorage.setItem(zz,M[0].id)}}}catch(N){console.error("Error loading assistant data:",N)}finally{h(!1)}})()},[t==null?void 0:t.id]);const f=b=>{o(b),p(!1),sessionStorage.removeItem(moe),b?(sessionStorage.setItem(zz,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:N})=>{d((N==null?void 0:N.permissions)||{})})):(sessionStorage.removeItem(zz),d({}))},x=()=>{p(!0),o(null),d({}),sessionStorage.setItem(moe,"true"),sessionStorage.removeItem(zz)},y=b=>!n||m?!0:c[b]===!0,v=n&&l&&!m?l.id:(t==null?void 0:t.id)||null;return e.jsx(AMt.Provider,{value:{isAssistant:n,assignedAgents:a,actingAsAgent:l,setActingAsAgent:f,effectiveUserId:v,permissions:c,hasPermission:y,isLoading:u,isActingAsSelf:m,setActingAsSelf:x},children:s})},Fne=()=>{const s=j.useContext(AMt);if(s===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return s},Sa=()=>{const{effectiveUserId:s}=Fne();return s};var EMt={exports:{}},TMt={};/** * @license React * use-sync-external-store-shim.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var RV=j;function U1s(s,t){return s===t&&(s!==0||1/s===1/t)||s!==s&&t!==t}var q1s=typeof Object.is=="function"?Object.is:U1s,$1s=RV.useState,V1s=RV.useEffect,H1s=RV.useLayoutEffect,G1s=RV.useDebugValue;function W1s(s,t){var n=t(),r=$1s({inst:{value:n,getSnapshot:t}}),a=r[0].inst,i=r[1];return H1s(function(){a.value=n,a.getSnapshot=t,ZDe(a)&&i({inst:a})},[s,n,t]),V1s(function(){return ZDe(a)&&i({inst:a}),s(function(){ZDe(a)&&i({inst:a})})},[s]),G1s(n),n}function ZDe(s){var t=s.getSnapshot;s=s.value;try{var n=t();return!q1s(s,n)}catch{return!0}}function K1s(s,t){return t()}var Y1s=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?K1s:W1s;TMt.useSyncExternalStore=RV.useSyncExternalStore!==void 0?RV.useSyncExternalStore:Y1s;EMt.exports=TMt;var Z1s=EMt.exports;function X1s(){return Z1s.useSyncExternalStore(Q1s,()=>!0,()=>!1)}function Q1s(){return()=>{}}var BZe="Avatar",[J1s,ogr]=Up(BZe),[ebs,MMt]=J1s(BZe),PMt=j.forwardRef((s,t)=>{const{__scopeAvatar:n,...r}=s,[a,i]=j.useState("idle");return e.jsx(ebs,{scope:n,imageLoadingStatus:a,onImageLoadingStatusChange:i,children:e.jsx(si.span,{...r,ref:t})})});PMt.displayName=BZe;var LMt="AvatarImage",IMt=j.forwardRef((s,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:a=()=>{},...i}=s,l=MMt(LMt,n),o=tbs(r,i),c=sg(d=>{a(d),l.onImageLoadingStatusChange(d)});return dg(()=>{o!=="idle"&&c(o)},[o,c]),o==="loaded"?e.jsx(si.img,{...i,ref:t,src:r}):null});IMt.displayName=LMt;var RMt="AvatarFallback",DMt=j.forwardRef((s,t)=>{const{__scopeAvatar:n,delayMs:r,...a}=s,i=MMt(RMt,n),[l,o]=j.useState(r===void 0);return j.useEffect(()=>{if(r!==void 0){const c=window.setTimeout(()=>o(!0),r);return()=>window.clearTimeout(c)}},[r]),l&&i.imageLoadingStatus!=="loaded"?e.jsx(si.span,{...a,ref:t}):null});DMt.displayName=RMt;function lht(s,t){return s?t?(s.src!==t&&(s.src=t),s.complete&&s.naturalWidth>0?"loaded":"loading"):"error":"idle"}function tbs(s,{referrerPolicy:t,crossOrigin:n}){const r=X1s(),a=j.useRef(null),i=r?(a.current||(a.current=new window.Image),a.current):null,[l,o]=j.useState(()=>lht(i,s));return dg(()=>{o(lht(i,s))},[i,s]),dg(()=>{const c=h=>()=>{o(h)};if(!i)return;const d=c("loaded"),u=c("error");return i.addEventListener("load",d),i.addEventListener("error",u),t&&(i.referrerPolicy=t),typeof n=="string"&&(i.crossOrigin=n),()=>{i.removeEventListener("load",d),i.removeEventListener("error",u)}},[i,n,t]),l}var OMt=PMt,FMt=IMt,zMt=DMt;const Ea=j.forwardRef(({className:s,...t},n)=>e.jsx(OMt,{ref:n,className:Mt("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",s),...t}));Ea.displayName=OMt.displayName;const Ci=j.forwardRef(({className:s,...t},n)=>e.jsx(FMt,{ref:n,className:Mt("aspect-square h-full w-full",s),...t}));Ci.displayName=FMt.displayName;const Ta=j.forwardRef(({className:s,...t},n)=>e.jsx(zMt,{ref:n,className:Mt("flex h-full w-full items-center justify-center rounded-full bg-muted",s),...t}));Ta.displayName=zMt.displayName;const sbs=u9("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function Be({className:s,variant:t,...n}){return e.jsx("div",{className:Mt(sbs({variant:t}),s),...n})}var nbs=j.createContext(void 0);function xE(s){const t=j.useContext(nbs);return s||t||"ltr"}var XDe="rovingFocusGroup.onEntryFocus",rbs={bubbles:!1,cancelable:!0},zne="RovingFocusGroup",[rqe,BMt,abs]=tG(zne),[ibs,DP]=Up(zne,[abs]),[obs,lbs]=ibs(zne),UMt=j.forwardRef((s,t)=>e.jsx(rqe.Provider,{scope:s.__scopeRovingFocusGroup,children:e.jsx(rqe.Slot,{scope:s.__scopeRovingFocusGroup,children:e.jsx(cbs,{...s,ref:t})})}));UMt.displayName=zne;var cbs=j.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:a=!1,dir:i,currentTabStopId:l,defaultCurrentTabStopId:o,onCurrentTabStopIdChange:c,onEntryFocus:d,preventScrollOnEntryFocus:u=!1,...h}=s,m=j.useRef(null),p=Uo(t,m),f=xE(i),[x,y]=Sx({prop:l,defaultProp:o??null,onChange:c,caller:zne}),[v,b]=j.useState(!1),N=sg(d),S=BMt(n),A=j.useRef(!1),[T,L]=j.useState(0);return j.useEffect(()=>{const M=m.current;if(M)return M.addEventListener(XDe,N),()=>M.removeEventListener(XDe,N)},[N]),e.jsx(obs,{scope:n,orientation:r,dir:f,loop:a,currentTabStopId:x,onItemFocus:j.useCallback(M=>y(M),[y]),onItemShiftTab:j.useCallback(()=>b(!0),[]),onFocusableItemAdd:j.useCallback(()=>L(M=>M+1),[]),onFocusableItemRemove:j.useCallback(()=>L(M=>M-1),[]),children:e.jsx(si.div,{tabIndex:v||T===0?-1:0,"data-orientation":r,...h,ref:p,style:{outline:"none",...s.style},onMouseDown:va(s.onMouseDown,()=>{A.current=!0}),onFocus:va(s.onFocus,M=>{const I=!A.current;if(M.target===M.currentTarget&&I&&!v){const R=new CustomEvent(XDe,rbs);if(M.currentTarget.dispatchEvent(R),!R.defaultPrevented){const z=S().filter(Z=>Z.focusable),$=z.find(Z=>Z.active),H=z.find(Z=>Z.id===x),K=[$,H,...z].filter(Boolean).map(Z=>Z.ref.current);VMt(K,u)}}A.current=!1}),onBlur:va(s.onBlur,()=>b(!1))})})}),qMt="RovingFocusGroupItem",$Mt=j.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:a=!1,tabStopId:i,children:l,...o}=s,c=jx(),d=i||c,u=lbs(qMt,n),h=u.currentTabStopId===d,m=BMt(n),{onFocusableItemAdd:p,onFocusableItemRemove:f,currentTabStopId:x}=u;return j.useEffect(()=>{if(r)return p(),()=>f()},[r,p,f]),e.jsx(rqe.ItemSlot,{scope:n,id:d,focusable:r,active:a,children:e.jsx(si.span,{tabIndex:h?0:-1,"data-orientation":u.orientation,...o,ref:t,onMouseDown:va(s.onMouseDown,y=>{r?u.onItemFocus(d):y.preventDefault()}),onFocus:va(s.onFocus,()=>u.onItemFocus(d)),onKeyDown:va(s.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){u.onItemShiftTab();return}if(y.target!==y.currentTarget)return;const v=hbs(y,u.orientation,u.dir);if(v!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.preventDefault();let N=m().filter(S=>S.focusable).map(S=>S.ref.current);if(v==="last")N.reverse();else if(v==="prev"||v==="next"){v==="prev"&&N.reverse();const S=N.indexOf(y.currentTarget);N=u.loop?mbs(N,S+1):N.slice(S+1)}setTimeout(()=>VMt(N))}}),children:typeof l=="function"?l({isCurrentTabStop:h,hasTabStop:x!=null}):l})})});$Mt.displayName=qMt;var dbs={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function ubs(s,t){return t!=="rtl"?s:s==="ArrowLeft"?"ArrowRight":s==="ArrowRight"?"ArrowLeft":s}function hbs(s,t,n){const r=ubs(s.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return dbs[r]}function VMt(s,t=!1){const n=document.activeElement;for(const r of s)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function mbs(s,t){return s.map((n,r)=>s[(t+r)%s.length])}var V6e=UMt,H6e=$Mt,aqe=["Enter"," "],pbs=["ArrowDown","PageUp","Home"],HMt=["ArrowUp","PageDown","End"],fbs=[...pbs,...HMt],gbs={ltr:[...aqe,"ArrowRight"],rtl:[...aqe,"ArrowLeft"]},xbs={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Bne="Menu",[nee,ybs,vbs]=tG(Bne),[m9,GMt]=Up(Bne,[vbs,o3,DP]),G6e=o3(),WMt=DP(),[bbs,p9]=m9(Bne),[_bs,Une]=m9(Bne),KMt=s=>{const{__scopeMenu:t,open:n=!1,children:r,dir:a,onOpenChange:i,modal:l=!0}=s,o=G6e(t),[c,d]=j.useState(null),u=j.useRef(!1),h=sg(i),m=xE(a);return j.useEffect(()=>{const p=()=>{u.current=!0,document.addEventListener("pointerdown",f,{capture:!0,once:!0}),document.addEventListener("pointermove",f,{capture:!0,once:!0})},f=()=>u.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",f,{capture:!0}),document.removeEventListener("pointermove",f,{capture:!0})}},[]),e.jsx(Pne,{...o,children:e.jsx(bbs,{scope:t,open:n,onOpenChange:h,content:c,onContentChange:d,children:e.jsx(_bs,{scope:t,onClose:j.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:u,dir:m,modal:l,children:r})})})};KMt.displayName=Bne;var wbs="MenuAnchor",UZe=j.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s,a=G6e(n);return e.jsx(lG,{...a,...r,ref:t})});UZe.displayName=wbs;var qZe="MenuPortal",[jbs,YMt]=m9(qZe,{forceMount:void 0}),ZMt=s=>{const{__scopeMenu:t,forceMount:n,children:r,container:a}=s,i=p9(qZe,t);return e.jsx(jbs,{scope:t,forceMount:n,children:e.jsx(Xg,{present:n||i.open,children:e.jsx(sG,{asChild:!0,container:a,children:r})})})};ZMt.displayName=qZe;var sN="MenuContent",[Nbs,$Ze]=m9(sN),XMt=j.forwardRef((s,t)=>{const n=YMt(sN,s.__scopeMenu),{forceMount:r=n.forceMount,...a}=s,i=p9(sN,s.__scopeMenu),l=Une(sN,s.__scopeMenu);return e.jsx(nee.Provider,{scope:s.__scopeMenu,children:e.jsx(Xg,{present:r||i.open,children:e.jsx(nee.Slot,{scope:s.__scopeMenu,children:l.modal?e.jsx(kbs,{...a,ref:t}):e.jsx(Sbs,{...a,ref:t})})})})}),kbs=j.forwardRef((s,t)=>{const n=p9(sN,s.__scopeMenu),r=j.useRef(null),a=Uo(t,r);return j.useEffect(()=>{const i=r.current;if(i)return j6e(i)},[]),e.jsx(VZe,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:va(s.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),Sbs=j.forwardRef((s,t)=>{const n=p9(sN,s.__scopeMenu);return e.jsx(VZe,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),Cbs=rP("MenuContent.ScrollLock"),VZe=j.forwardRef((s,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:a,onOpenAutoFocus:i,onCloseAutoFocus:l,disableOutsidePointerEvents:o,onEntryFocus:c,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:h,onInteractOutside:m,onDismiss:p,disableOutsideScroll:f,...x}=s,y=p9(sN,n),v=Une(sN,n),b=G6e(n),N=WMt(n),S=ybs(n),[A,T]=j.useState(null),L=j.useRef(null),M=Uo(t,L,y.onContentChange),I=j.useRef(0),R=j.useRef(""),z=j.useRef(0),$=j.useRef(null),H=j.useRef("right"),V=j.useRef(0),K=f?Sne:j.Fragment,Z=f?{as:Cbs,allowPinchZoom:!0}:void 0,Q=ue=>{var ge,ke;const se=R.current+ue,ne=S().filter(Te=>!Te.disabled),ie=document.activeElement,ce=(ge=ne.find(Te=>Te.ref.current===ie))==null?void 0:ge.textValue,je=ne.map(Te=>Te.textValue),be=zbs(je,se,ce),he=(ke=ne.find(Te=>Te.textValue===be))==null?void 0:ke.ref.current;(function Te(Me){R.current=Me,window.clearTimeout(I.current),Me!==""&&(I.current=window.setTimeout(()=>Te(""),1e3))})(se),he&&setTimeout(()=>he.focus())};j.useEffect(()=>()=>window.clearTimeout(I.current),[]),_6e();const le=j.useCallback(ue=>{var ne,ie;return H.current===((ne=$.current)==null?void 0:ne.side)&&Ubs(ue,(ie=$.current)==null?void 0:ie.area)},[]);return e.jsx(Nbs,{scope:n,searchRef:R,onItemEnter:j.useCallback(ue=>{le(ue)&&ue.preventDefault()},[le]),onItemLeave:j.useCallback(ue=>{var se;le(ue)||((se=L.current)==null||se.focus(),T(null))},[le]),onTriggerLeave:j.useCallback(ue=>{le(ue)&&ue.preventDefault()},[le]),pointerGraceTimerRef:z,onPointerGraceIntentChange:j.useCallback(ue=>{$.current=ue},[]),children:e.jsx(K,{...Z,children:e.jsx(kne,{asChild:!0,trapped:a,onMountAutoFocus:va(i,ue=>{var se;ue.preventDefault(),(se=L.current)==null||se.focus({preventScroll:!0})}),onUnmountAutoFocus:l,children:e.jsx(IP,{asChild:!0,disableOutsidePointerEvents:o,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:h,onInteractOutside:m,onDismiss:p,children:e.jsx(V6e,{asChild:!0,...N,dir:v.dir,orientation:"vertical",loop:r,currentTabStopId:A,onCurrentTabStopIdChange:T,onEntryFocus:va(c,ue=>{v.isUsingKeyboardRef.current||ue.preventDefault()}),preventScrollOnEntryFocus:!0,children:e.jsx(Lne,{role:"menu","aria-orientation":"vertical","data-state":mPt(y.open),"data-radix-menu-content":"",dir:v.dir,...b,...x,ref:M,style:{outline:"none",...x.style},onKeyDown:va(x.onKeyDown,ue=>{const ne=ue.target.closest("[data-radix-menu-content]")===ue.currentTarget,ie=ue.ctrlKey||ue.altKey||ue.metaKey,ce=ue.key.length===1;ne&&(ue.key==="Tab"&&ue.preventDefault(),!ie&&ce&&Q(ue.key));const je=L.current;if(ue.target!==je||!fbs.includes(ue.key))return;ue.preventDefault();const he=S().filter(ge=>!ge.disabled).map(ge=>ge.ref.current);HMt.includes(ue.key)&&he.reverse(),Obs(he)}),onBlur:va(s.onBlur,ue=>{ue.currentTarget.contains(ue.target)||(window.clearTimeout(I.current),R.current="")}),onPointerMove:va(s.onPointerMove,ree(ue=>{const se=ue.target,ne=V.current!==ue.clientX;if(ue.currentTarget.contains(se)&&ne){const ie=ue.clientX>V.current?"right":"left";H.current=ie,V.current=ue.clientX}}))})})})})})})});XMt.displayName=sN;var Abs="MenuGroup",HZe=j.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(si.div,{role:"group",...r,ref:t})});HZe.displayName=Abs;var Ebs="MenuLabel",QMt=j.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(si.div,{...r,ref:t})});QMt.displayName=Ebs;var X3e="MenuItem",cht="menu.itemSelect",W6e=j.forwardRef((s,t)=>{const{disabled:n=!1,onSelect:r,...a}=s,i=j.useRef(null),l=Une(X3e,s.__scopeMenu),o=$Ze(X3e,s.__scopeMenu),c=Uo(t,i),d=j.useRef(!1),u=()=>{const h=i.current;if(!n&&h){const m=new CustomEvent(cht,{bubbles:!0,cancelable:!0});h.addEventListener(cht,p=>r==null?void 0:r(p),{once:!0}),cZe(h,m),m.defaultPrevented?d.current=!1:l.onClose()}};return e.jsx(JMt,{...a,ref:c,disabled:n,onClick:va(s.onClick,u),onPointerDown:h=>{var m;(m=s.onPointerDown)==null||m.call(s,h),d.current=!0},onPointerUp:va(s.onPointerUp,h=>{var m;d.current||(m=h.currentTarget)==null||m.click()}),onKeyDown:va(s.onKeyDown,h=>{const m=o.searchRef.current!=="";n||m&&h.key===" "||aqe.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});W6e.displayName=X3e;var JMt=j.forwardRef((s,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:a,...i}=s,l=$Ze(X3e,n),o=WMt(n),c=j.useRef(null),d=Uo(t,c),[u,h]=j.useState(!1),[m,p]=j.useState("");return j.useEffect(()=>{const f=c.current;f&&p((f.textContent??"").trim())},[i.children]),e.jsx(nee.ItemSlot,{scope:n,disabled:r,textValue:a??m,children:e.jsx(H6e,{asChild:!0,...o,focusable:!r,children:e.jsx(si.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...i,ref:d,onPointerMove:va(s.onPointerMove,ree(f=>{r?l.onItemLeave(f):(l.onItemEnter(f),f.defaultPrevented||f.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:va(s.onPointerLeave,ree(f=>l.onItemLeave(f))),onFocus:va(s.onFocus,()=>h(!0)),onBlur:va(s.onBlur,()=>h(!1))})})})}),Tbs="MenuCheckboxItem",ePt=j.forwardRef((s,t)=>{const{checked:n=!1,onCheckedChange:r,...a}=s;return e.jsx(aPt,{scope:s.__scopeMenu,checked:n,children:e.jsx(W6e,{role:"menuitemcheckbox","aria-checked":Q3e(n)?"mixed":n,...a,ref:t,"data-state":WZe(n),onSelect:va(a.onSelect,()=>r==null?void 0:r(Q3e(n)?!0:!n),{checkForDefaultPrevented:!1})})})});ePt.displayName=Tbs;var tPt="MenuRadioGroup",[Mbs,Pbs]=m9(tPt,{value:void 0,onValueChange:()=>{}}),sPt=j.forwardRef((s,t)=>{const{value:n,onValueChange:r,...a}=s,i=sg(r);return e.jsx(Mbs,{scope:s.__scopeMenu,value:n,onValueChange:i,children:e.jsx(HZe,{...a,ref:t})})});sPt.displayName=tPt;var nPt="MenuRadioItem",rPt=j.forwardRef((s,t)=>{const{value:n,...r}=s,a=Pbs(nPt,s.__scopeMenu),i=n===a.value;return e.jsx(aPt,{scope:s.__scopeMenu,checked:i,children:e.jsx(W6e,{role:"menuitemradio","aria-checked":i,...r,ref:t,"data-state":WZe(i),onSelect:va(r.onSelect,()=>{var l;return(l=a.onValueChange)==null?void 0:l.call(a,n)},{checkForDefaultPrevented:!1})})})});rPt.displayName=nPt;var GZe="MenuItemIndicator",[aPt,Lbs]=m9(GZe,{checked:!1}),iPt=j.forwardRef((s,t)=>{const{__scopeMenu:n,forceMount:r,...a}=s,i=Lbs(GZe,n);return e.jsx(Xg,{present:r||Q3e(i.checked)||i.checked===!0,children:e.jsx(si.span,{...a,ref:t,"data-state":WZe(i.checked)})})});iPt.displayName=GZe;var Ibs="MenuSeparator",oPt=j.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(si.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});oPt.displayName=Ibs;var Rbs="MenuArrow",lPt=j.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s,a=G6e(n);return e.jsx(Ine,{...a,...r,ref:t})});lPt.displayName=Rbs;var Dbs="MenuSub",[lgr,cPt]=m9(Dbs),gZ="MenuSubTrigger",dPt=j.forwardRef((s,t)=>{const n=p9(gZ,s.__scopeMenu),r=Une(gZ,s.__scopeMenu),a=cPt(gZ,s.__scopeMenu),i=$Ze(gZ,s.__scopeMenu),l=j.useRef(null),{pointerGraceTimerRef:o,onPointerGraceIntentChange:c}=i,d={__scopeMenu:s.__scopeMenu},u=j.useCallback(()=>{l.current&&window.clearTimeout(l.current),l.current=null},[]);return j.useEffect(()=>u,[u]),j.useEffect(()=>{const h=o.current;return()=>{window.clearTimeout(h),c(null)}},[o,c]),e.jsx(UZe,{asChild:!0,...d,children:e.jsx(JMt,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":a.contentId,"data-state":mPt(n.open),...s,ref:eE(t,a.onTriggerChange),onClick:h=>{var m;(m=s.onClick)==null||m.call(s,h),!(s.disabled||h.defaultPrevented)&&(h.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:va(s.onPointerMove,ree(h=>{i.onItemEnter(h),!h.defaultPrevented&&!s.disabled&&!n.open&&!l.current&&(i.onPointerGraceIntentChange(null),l.current=window.setTimeout(()=>{n.onOpenChange(!0),u()},100))})),onPointerLeave:va(s.onPointerLeave,ree(h=>{var p,f;u();const m=(p=n.content)==null?void 0:p.getBoundingClientRect();if(m){const x=(f=n.content)==null?void 0:f.dataset.side,y=x==="right",v=y?-5:5,b=m[y?"left":"right"],N=m[y?"right":"left"];i.onPointerGraceIntentChange({area:[{x:h.clientX+v,y:h.clientY},{x:b,y:m.top},{x:N,y:m.top},{x:N,y:m.bottom},{x:b,y:m.bottom}],side:x}),window.clearTimeout(o.current),o.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(h),h.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:va(s.onKeyDown,h=>{var p;const m=i.searchRef.current!=="";s.disabled||m&&h.key===" "||gbs[r.dir].includes(h.key)&&(n.onOpenChange(!0),(p=n.content)==null||p.focus(),h.preventDefault())})})})});dPt.displayName=gZ;var uPt="MenuSubContent",hPt=j.forwardRef((s,t)=>{const n=YMt(sN,s.__scopeMenu),{forceMount:r=n.forceMount,...a}=s,i=p9(sN,s.__scopeMenu),l=Une(sN,s.__scopeMenu),o=cPt(uPt,s.__scopeMenu),c=j.useRef(null),d=Uo(t,c);return e.jsx(nee.Provider,{scope:s.__scopeMenu,children:e.jsx(Xg,{present:r||i.open,children:e.jsx(nee.Slot,{scope:s.__scopeMenu,children:e.jsx(VZe,{id:o.contentId,"aria-labelledby":o.triggerId,...a,ref:d,align:"start",side:l.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:u=>{var h;l.isUsingKeyboardRef.current&&((h=c.current)==null||h.focus()),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:va(s.onFocusOutside,u=>{u.target!==o.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:va(s.onEscapeKeyDown,u=>{l.onClose(),u.preventDefault()}),onKeyDown:va(s.onKeyDown,u=>{var p;const h=u.currentTarget.contains(u.target),m=xbs[l.dir].includes(u.key);h&&m&&(i.onOpenChange(!1),(p=o.trigger)==null||p.focus(),u.preventDefault())})})})})})});hPt.displayName=uPt;function mPt(s){return s?"open":"closed"}function Q3e(s){return s==="indeterminate"}function WZe(s){return Q3e(s)?"indeterminate":s?"checked":"unchecked"}function Obs(s){const t=document.activeElement;for(const n of s)if(n===t||(n.focus(),document.activeElement!==t))return}function Fbs(s,t){return s.map((n,r)=>s[(t+r)%s.length])}function zbs(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=Fbs(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}function Bbs(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}function Ubs(s,t){if(!t)return!1;const n={x:s.clientX,y:s.clientY};return Bbs(n,t)}function ree(s){return t=>t.pointerType==="mouse"?s(t):void 0}var qbs=KMt,$bs=UZe,Vbs=ZMt,Hbs=XMt,Gbs=HZe,Wbs=QMt,Kbs=W6e,Ybs=ePt,Zbs=sPt,Xbs=rPt,Qbs=iPt,Jbs=oPt,e_s=lPt,t_s=dPt,s_s=hPt,K6e="DropdownMenu",[n_s,cgr]=Up(K6e,[GMt]),Sb=GMt(),[r_s,pPt]=n_s(K6e),fPt=s=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:a,defaultOpen:i,onOpenChange:l,modal:o=!0}=s,c=Sb(t),d=j.useRef(null),[u,h]=Sx({prop:a,defaultProp:i??!1,onChange:l,caller:K6e});return e.jsx(r_s,{scope:t,triggerId:jx(),triggerRef:d,contentId:jx(),open:u,onOpenChange:h,onOpenToggle:j.useCallback(()=>h(m=>!m),[h]),modal:o,children:e.jsx(qbs,{...c,open:u,onOpenChange:h,dir:r,modal:o,children:n})})};fPt.displayName=K6e;var gPt="DropdownMenuTrigger",xPt=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...a}=s,i=pPt(gPt,n),l=Sb(n);return e.jsx($bs,{asChild:!0,...l,children:e.jsx(si.button,{type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...a,ref:eE(t,i.triggerRef),onPointerDown:va(s.onPointerDown,o=>{!r&&o.button===0&&o.ctrlKey===!1&&(i.onOpenToggle(),i.open||o.preventDefault())}),onKeyDown:va(s.onKeyDown,o=>{r||(["Enter"," "].includes(o.key)&&i.onOpenToggle(),o.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(o.key)&&o.preventDefault())})})})});xPt.displayName=gPt;var a_s="DropdownMenuPortal",yPt=s=>{const{__scopeDropdownMenu:t,...n}=s,r=Sb(t);return e.jsx(Vbs,{...r,...n})};yPt.displayName=a_s;var vPt="DropdownMenuContent",bPt=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=pPt(vPt,n),i=Sb(n),l=j.useRef(!1);return e.jsx(Hbs,{id:a.contentId,"aria-labelledby":a.triggerId,...i,...r,ref:t,onCloseAutoFocus:va(s.onCloseAutoFocus,o=>{var c;l.current||(c=a.triggerRef.current)==null||c.focus(),l.current=!1,o.preventDefault()}),onInteractOutside:va(s.onInteractOutside,o=>{const c=o.detail.originalEvent,d=c.button===0&&c.ctrlKey===!0,u=c.button===2||d;(!a.modal||u)&&(l.current=!0)}),style:{...s.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});bPt.displayName=vPt;var i_s="DropdownMenuGroup",o_s=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Sb(n);return e.jsx(Gbs,{...a,...r,ref:t})});o_s.displayName=i_s;var l_s="DropdownMenuLabel",_Pt=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Sb(n);return e.jsx(Wbs,{...a,...r,ref:t})});_Pt.displayName=l_s;var c_s="DropdownMenuItem",wPt=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Sb(n);return e.jsx(Kbs,{...a,...r,ref:t})});wPt.displayName=c_s;var d_s="DropdownMenuCheckboxItem",jPt=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Sb(n);return e.jsx(Ybs,{...a,...r,ref:t})});jPt.displayName=d_s;var u_s="DropdownMenuRadioGroup",h_s=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Sb(n);return e.jsx(Zbs,{...a,...r,ref:t})});h_s.displayName=u_s;var m_s="DropdownMenuRadioItem",NPt=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Sb(n);return e.jsx(Xbs,{...a,...r,ref:t})});NPt.displayName=m_s;var p_s="DropdownMenuItemIndicator",kPt=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Sb(n);return e.jsx(Qbs,{...a,...r,ref:t})});kPt.displayName=p_s;var f_s="DropdownMenuSeparator",SPt=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Sb(n);return e.jsx(Jbs,{...a,...r,ref:t})});SPt.displayName=f_s;var g_s="DropdownMenuArrow",x_s=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Sb(n);return e.jsx(e_s,{...a,...r,ref:t})});x_s.displayName=g_s;var y_s="DropdownMenuSubTrigger",CPt=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Sb(n);return e.jsx(t_s,{...a,...r,ref:t})});CPt.displayName=y_s;var v_s="DropdownMenuSubContent",APt=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Sb(n);return e.jsx(s_s,{...a,...r,ref:t,style:{...s.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});APt.displayName=v_s;var b_s=fPt,__s=xPt,w_s=yPt,EPt=bPt,TPt=_Pt,MPt=wPt,PPt=jPt,LPt=NPt,IPt=kPt,RPt=SPt,DPt=CPt,OPt=APt;const Ku=b_s,Yu=__s,j_s=j.forwardRef(({className:s,inset:t,children:n,...r},a)=>e.jsxs(DPt,{ref:a,className:Mt("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(gi,{className:"ml-auto h-4 w-4"})]}));j_s.displayName=DPt.displayName;const N_s=j.forwardRef(({className:s,...t},n)=>e.jsx(OPt,{ref:n,className:Mt("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}));N_s.displayName=OPt.displayName;const Eu=j.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(w_s,{children:e.jsx(EPt,{ref:r,sideOffset:t,className:Mt("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...n})}));Eu.displayName=EPt.displayName;const La=j.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(MPt,{ref:r,className:Mt("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}));La.displayName=MPt.displayName;const k_s=j.forwardRef(({className:s,children:t,checked:n,...r},a)=>e.jsxs(PPt,{ref:a,className:Mt("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(IPt,{children:e.jsx(Xr,{className:"h-4 w-4"})})}),t]}));k_s.displayName=PPt.displayName;const S_s=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(LPt,{ref:r,className:Mt("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(IPt,{children:e.jsx(Nf,{className:"h-2 w-2 fill-current"})})}),t]}));S_s.displayName=LPt.displayName;const DV=j.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(TPt,{ref:r,className:Mt("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",s),...n}));DV.displayName=TPt.displayName;const l1=j.forwardRef(({className:s,...t},n)=>e.jsx(RPt,{ref:n,className:Mt("-mx-1 my-1 h-px bg-muted",s),...t}));l1.displayName=RPt.displayName;const C_s=()=>{const{isAssistant:s,actingAsAgent:t,assignedAgents:n,setActingAsAgent:r,isActingAsSelf:a,setActingAsSelf:i}=Fne();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(So,{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(Bn,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium text-sm",children:"Acting as"})]}),e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsxs(U,{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(So,{className:"h-4 w-4"}),e.jsx("strong",{children:"My Account"})]}):t?e.jsxs(e.Fragment,{children:[e.jsxs(Ea,{className:"h-5 w-5",children:[e.jsx(Ci,{src:t.avatar_url||void 0}),e.jsx(Ta,{className:"text-[10px] bg-primary-foreground/30",children:l(t.name)})]}),e.jsx("strong",{children:t.name})]}):e.jsx("strong",{children:"Select..."}),e.jsx(rl,{className:"h-3 w-3"})]})}),e.jsxs(Eu,{align:"start",className:"z-[2147483647]",children:[e.jsxs(La,{onClick:i,className:"gap-2",children:[e.jsx(So,{className:"h-4 w-4"}),e.jsx("span",{children:"My Account"}),a&&e.jsx(Be,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]}),e.jsx(l1,{}),n.map(o=>e.jsxs(La,{onClick:()=>r(o),className:"gap-2",children:[e.jsxs(Ea,{className:"h-6 w-6",children:[e.jsx(Ci,{src:o.avatar_url||void 0}),e.jsx(Ta,{className:"text-[10px]",children:l(o.name)})]}),e.jsx("span",{children:o.name}),!a&&o.id===(t==null?void 0:t.id)&&e.jsx(Be,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]},o.id))]})]})]}),e.jsx(Be,{variant:"secondary",className:"bg-primary-foreground/20 text-primary-foreground border-0 text-xs",children:a?"Personal Mode":"Assistant Mode"})]})})};function _S(){var c,d;const{user:s,isAdmin:t}=vs(),{data:n,isLoading:r}=ct({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 p,f;const h=((p=n==null?void 0:n.pkg)==null?void 0:p.feature_limits)||{},m=(f=h==null?void 0:h[u])==null?void 0:f.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 KZe={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"},dgr=Object.keys(KZe),A_s={home:null,crm:"crm",deals:"deals",listings:"listing_exchange",marketing:"marketing_studio",websites:"website",academy:"learn",events:"learn",apps:null,brokerage:"community",more:null},dht={"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"},E_s={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 T_s(s){return s.id in dht?dht[s.id]:A_s[s.primaryCategory]??null}function M_s(s){return E_s[s]??null}const P_s=[["/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 FPt(s){let t=null;for(const n of P_s){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 we=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Mt("rounded-lg border bg-card text-card-foreground shadow-sm",s),...t}));we.displayName="Card";const Tt=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Mt("flex flex-col space-y-1.5 p-6",s),...t}));Tt.displayName="CardHeader";const It=j.forwardRef(({className:s,...t},n)=>e.jsx("h3",{ref:n,className:Mt("text-2xl font-semibold leading-none tracking-tight",s),...t}));It.displayName="CardTitle";const Jn=j.forwardRef(({className:s,...t},n)=>e.jsx("p",{ref:n,className:Mt("text-sm text-muted-foreground",s),...t}));Jn.displayName="CardDescription";const Ie=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Mt("p-6 pt-0",s),...t}));Ie.displayName="CardContent";const J3e=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Mt("flex items-center p-6 pt-0",s),...t}));J3e.displayName="CardFooter";const Fs=j.forwardRef(({className:s,...t},n)=>e.jsx("textarea",{className:Mt("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}));Fs.displayName="Textarea";const zs=k6e,al=xZe,L_s=S6e,ugr=Ene,zPt=j.forwardRef(({className:s,...t},n)=>e.jsx(rG,{ref:n,className:Mt("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}));zPt.displayName=rG.displayName;const Ds=j.forwardRef(({className:s,children:t,overlayClassName:n,...r},a)=>e.jsxs(L_s,{children:[e.jsx(zPt,{className:n}),e.jsxs(aG,{ref:a,className:Mt("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(Ene,{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(er,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Ds.displayName=aG.displayName;const Vs=({className:s,...t})=>e.jsx("div",{className:Mt("flex flex-col space-y-1.5 text-center sm:text-left",s),...t});Vs.displayName="DialogHeader";const Mr=({className:s,...t})=>e.jsx("div",{className:Mt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});Mr.displayName="DialogFooter";const $s=j.forwardRef(({className:s,...t},n)=>e.jsx(Cne,{ref:n,className:Mt("text-lg font-semibold leading-none tracking-tight",s),...t}));$s.displayName=Cne.displayName;const Pr=j.forwardRef(({className:s,...t},n)=>e.jsx(Ane,{ref:n,className:Mt("text-sm text-muted-foreground",s),...t}));Pr.displayName=Ane.displayName;function I_s({featureKey:s,open:t,onOpenChange:n}){const{user:r}=vs(),a=Qt(),[i,l]=j.useState(""),{data:o}=ct({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=yt({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=KZe[s]||s;return e.jsx(zs,{open:t,onOpenChange:n,children:e.jsxs(Ds,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(cn,{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(Xr,{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(Fs,{placeholder:"Anything we should know? (optional)",value:i,onChange:h=>l(h.target.value),rows:4}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>n(!1),children:"Close"}),!c&&e.jsx(U,{onClick:()=>d.mutate(),disabled:d.isPending,children:d.isPending?"Sending…":"Send request"})]})]})})}function R_s({featureKey:s}){const[t,n]=j.useState(!1),r=KZe[s]||s;return e.jsxs("div",{className:"flex items-center justify-center py-16 px-4",children:[e.jsx(we,{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(Ql,{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(U,{onClick:()=>n(!0),className:"gap-2",children:[e.jsx(cn,{className:"h-4 w-4"})," Request access"]})]})}),e.jsx(I_s,{featureKey:s,open:t,onOpenChange:n})]})}const BPt=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)}}}},UPt=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},D_s=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(),p=Math.ceil((m-h)/(1e3*60*60*24)),f=p<=0;n({isTrial:!0,isExpired:f,expiresAt:d,daysLeft:f?0:p,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},qne=()=>{const{data:s,isLoading:t}=ct({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")}},uht="community_last_seen_post_at";function O_s(){const{user:s}=vs(),t=Od(),[n,r]=j.useState(0),[a,i]=j.useState(null);j.useEffect(()=>{if(!s)return;const o=localStorage.getItem(`${uht}_${s.id}`);i(o)},[s]),j.useEffect(()=>{if(!s)return;const o=`community_unread_count_${s.id}`,c=2*60*1e3;(async()=>{try{const p=sessionStorage.getItem(o);if(p){const f=JSON.parse(p);if(f.ts&&Date.now()-f.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",p=d.content.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),f=p.length>50?p.substring(0,50)+"...":p;u||re("New Community Post",{description:`${m}: ${f}`,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(`${uht}_${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 F_s(){const{isAdmin:s}=vs(),{data:t=0}=ct({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 QDe=s=>`levelup:activeTeam:${s}`,z_s=()=>{const s=Sa();return ct({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})},Sj=()=>{const s=Sa(),t=z_s(),n=j.useMemo(()=>t.data||[],[t.data]),[r,a]=j.useState(()=>!s||typeof window>"u"?null:window.localStorage.getItem(QDe(s)));j.useEffect(()=>{!s||typeof window>"u"||a(window.localStorage.getItem(QDe(s)))},[s]);const i=j.useCallback(o=>{a(o),s&&typeof window<"u"&&window.localStorage.setItem(QDe(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}},pU="weekly_reels";function Y6e(){const{user:s,loading:t,isAdmin:n}=vs(),{data:r,isLoading:a}=ct({queryKey:["feature-entitlement",pU,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",pU).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 my=k6e,$ne=xZe,B_s=S6e,qPt=j.forwardRef(({className:s,...t},n)=>e.jsx(rG,{className:Mt("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}));qPt.displayName=rG.displayName;const U_s=u9("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"}}),g0=j.forwardRef(({side:s="right",className:t,children:n,...r},a)=>e.jsxs(B_s,{children:[e.jsx(qPt,{}),e.jsxs(aG,{ref:a,className:Mt(U_s({side:s}),t),...r,children:[n,e.jsxs(Ene,{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(er,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));g0.displayName=aG.displayName;const vv=({className:s,...t})=>e.jsx("div",{className:Mt("flex flex-col space-y-2 text-center sm:text-left",s),...t});vv.displayName="SheetHeader";const $Pt=({className:s,...t})=>e.jsx("div",{className:Mt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});$Pt.displayName="SheetFooter";const bv=j.forwardRef(({className:s,...t},n)=>e.jsx(Cne,{ref:n,className:Mt("text-lg font-semibold text-foreground",s),...t}));bv.displayName=Cne.displayName;const pG=j.forwardRef(({className:s,...t},n)=>e.jsx(Ane,{ref:n,className:Mt("text-sm text-muted-foreground",s),...t}));pG.displayName=Ane.displayName;function aee(s,[t,n]){return Math.min(n,Math.max(t,s))}function q_s(s,t){return j.useReducer((n,r)=>t[n][r]??n,s)}var YZe="ScrollArea",[VPt,hgr]=Up(YZe),[$_s,jN]=VPt(YZe),HPt=j.forwardRef((s,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:a,scrollHideDelay:i=600,...l}=s,[o,c]=j.useState(null),[d,u]=j.useState(null),[h,m]=j.useState(null),[p,f]=j.useState(null),[x,y]=j.useState(null),[v,b]=j.useState(0),[N,S]=j.useState(0),[A,T]=j.useState(!1),[L,M]=j.useState(!1),I=Uo(t,z=>c(z)),R=xE(a);return e.jsx($_s,{scope:n,type:r,dir:R,scrollHideDelay:i,scrollArea:o,viewport:d,onViewportChange:u,content:h,onContentChange:m,scrollbarX:p,onScrollbarXChange:f,scrollbarXEnabled:A,onScrollbarXEnabledChange:T,scrollbarY:x,onScrollbarYChange:y,scrollbarYEnabled:L,onScrollbarYEnabledChange:M,onCornerWidthChange:b,onCornerHeightChange:S,children:e.jsx(si.div,{dir:R,...l,ref:I,style:{position:"relative","--radix-scroll-area-corner-width":v+"px","--radix-scroll-area-corner-height":N+"px",...s.style}})})});HPt.displayName=YZe;var GPt="ScrollAreaViewport",WPt=j.forwardRef((s,t)=>{const{__scopeScrollArea:n,children:r,nonce:a,...i}=s,l=jN(GPt,n),o=j.useRef(null),c=Uo(t,o,l.onViewportChange);return e.jsxs(e.Fragment,{children:[e.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:a}),e.jsx(si.div,{"data-radix-scroll-area-viewport":"",...i,ref:c,style:{overflowX:l.scrollbarXEnabled?"scroll":"hidden",overflowY:l.scrollbarYEnabled?"scroll":"hidden",...s.style},children:e.jsx("div",{ref:l.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});WPt.displayName=GPt;var c3="ScrollAreaScrollbar",ZZe=j.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=jN(c3,s.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:l}=a,o=s.orientation==="horizontal";return j.useEffect(()=>(o?i(!0):l(!0),()=>{o?i(!1):l(!1)}),[o,i,l]),a.type==="hover"?e.jsx(V_s,{...r,ref:t,forceMount:n}):a.type==="scroll"?e.jsx(H_s,{...r,ref:t,forceMount:n}):a.type==="auto"?e.jsx(KPt,{...r,ref:t,forceMount:n}):a.type==="always"?e.jsx(XZe,{...r,ref:t}):null});ZZe.displayName=c3;var V_s=j.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=jN(c3,s.__scopeScrollArea),[i,l]=j.useState(!1);return j.useEffect(()=>{const o=a.scrollArea;let c=0;if(o){const d=()=>{window.clearTimeout(c),l(!0)},u=()=>{c=window.setTimeout(()=>l(!1),a.scrollHideDelay)};return o.addEventListener("pointerenter",d),o.addEventListener("pointerleave",u),()=>{window.clearTimeout(c),o.removeEventListener("pointerenter",d),o.removeEventListener("pointerleave",u)}}},[a.scrollArea,a.scrollHideDelay]),e.jsx(Xg,{present:n||i,children:e.jsx(KPt,{"data-state":i?"visible":"hidden",...r,ref:t})})}),H_s=j.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=jN(c3,s.__scopeScrollArea),i=s.orientation==="horizontal",l=X6e(()=>c("SCROLL_END"),100),[o,c]=q_s("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(o==="idle"){const d=window.setTimeout(()=>c("HIDE"),a.scrollHideDelay);return()=>window.clearTimeout(d)}},[o,a.scrollHideDelay,c]),j.useEffect(()=>{const d=a.viewport,u=i?"scrollLeft":"scrollTop";if(d){let h=d[u];const m=()=>{const p=d[u];h!==p&&(c("SCROLL"),l()),h=p};return d.addEventListener("scroll",m),()=>d.removeEventListener("scroll",m)}},[a.viewport,i,c,l]),e.jsx(Xg,{present:n||o!=="hidden",children:e.jsx(XZe,{"data-state":o==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:va(s.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:va(s.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),KPt=j.forwardRef((s,t)=>{const n=jN(c3,s.__scopeScrollArea),{forceMount:r,...a}=s,[i,l]=j.useState(!1),o=s.orientation==="horizontal",c=X6e(()=>{if(n.viewport){const d=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=s,a=jN(c3,s.__scopeScrollArea),i=j.useRef(null),l=j.useRef(0),[o,c]=j.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=JPt(o.viewport,o.content),u={...r,sizes:o,onSizesChange:c,hasThumb:d>0&&d<1,onThumbChange:m=>i.current=m,onThumbPointerUp:()=>l.current=0,onThumbPointerDown:m=>l.current=m};function h(m,p){return X_s(m,l.current,o,p)}return n==="horizontal"?e.jsx(G_s,{...u,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const m=a.viewport.scrollLeft,p=hht(m,o,a.dir);i.current.style.transform=`translate3d(${p}px, 0, 0)`}},onWheelScroll:m=>{a.viewport&&(a.viewport.scrollLeft=m)},onDragScroll:m=>{a.viewport&&(a.viewport.scrollLeft=h(m,a.dir))}}):n==="vertical"?e.jsx(W_s,{...u,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const m=a.viewport.scrollTop,p=hht(m,o);i.current.style.transform=`translate3d(0, ${p}px, 0)`}},onWheelScroll:m=>{a.viewport&&(a.viewport.scrollTop=m)},onDragScroll:m=>{a.viewport&&(a.viewport.scrollTop=h(m))}}):null}),G_s=j.forwardRef((s,t)=>{const{sizes:n,onSizesChange:r,...a}=s,i=jN(c3,s.__scopeScrollArea),[l,o]=j.useState(),c=j.useRef(null),d=Uo(t,c,i.onScrollbarXChange);return j.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(ZPt,{"data-orientation":"horizontal",...a,ref:d,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Z6e(n)+"px",...s.style},onThumbPointerDown:u=>s.onThumbPointerDown(u.x),onDragScroll:u=>s.onDragScroll(u.x),onWheelScroll:(u,h)=>{if(i.viewport){const m=i.viewport.scrollLeft+u.deltaX;s.onWheelScroll(m),tLt(m,h)&&u.preventDefault()}},onResize:()=>{c.current&&i.viewport&&l&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:tCe(l.paddingLeft),paddingEnd:tCe(l.paddingRight)}})}})}),W_s=j.forwardRef((s,t)=>{const{sizes:n,onSizesChange:r,...a}=s,i=jN(c3,s.__scopeScrollArea),[l,o]=j.useState(),c=j.useRef(null),d=Uo(t,c,i.onScrollbarYChange);return j.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(ZPt,{"data-orientation":"vertical",...a,ref:d,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Z6e(n)+"px",...s.style},onThumbPointerDown:u=>s.onThumbPointerDown(u.y),onDragScroll:u=>s.onDragScroll(u.y),onWheelScroll:(u,h)=>{if(i.viewport){const m=i.viewport.scrollTop+u.deltaY;s.onWheelScroll(m),tLt(m,h)&&u.preventDefault()}},onResize:()=>{c.current&&i.viewport&&l&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:tCe(l.paddingTop),paddingEnd:tCe(l.paddingBottom)}})}})}),[K_s,YPt]=VPt(c3),ZPt=j.forwardRef((s,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:a,onThumbChange:i,onThumbPointerUp:l,onThumbPointerDown:o,onThumbPositionChange:c,onDragScroll:d,onWheelScroll:u,onResize:h,...m}=s,p=jN(c3,n),[f,x]=j.useState(null),y=Uo(t,I=>x(I)),v=j.useRef(null),b=j.useRef(""),N=p.viewport,S=r.content-r.viewport,A=sg(u),T=sg(c),L=X6e(h,10);function M(I){if(v.current){const R=I.clientX-v.current.left,z=I.clientY-v.current.top;d({x:R,y:z})}}return j.useEffect(()=>{const I=R=>{const z=R.target;(f==null?void 0:f.contains(z))&&A(R,S)};return document.addEventListener("wheel",I,{passive:!1}),()=>document.removeEventListener("wheel",I,{passive:!1})},[N,f,S,A]),j.useEffect(T,[r,T]),OV(f,L),OV(p.content,L),e.jsx(K_s,{scope:n,scrollbar:f,hasThumb:a,onThumbChange:sg(i),onThumbPointerUp:sg(l),onThumbPositionChange:T,onThumbPointerDown:sg(o),children:e.jsx(si.div,{...m,ref:y,style:{position:"absolute",...m.style},onPointerDown:va(s.onPointerDown,I=>{I.button===0&&(I.target.setPointerCapture(I.pointerId),v.current=f.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",p.viewport&&(p.viewport.style.scrollBehavior="auto"),M(I))}),onPointerMove:va(s.onPointerMove,M),onPointerUp:va(s.onPointerUp,I=>{const R=I.target;R.hasPointerCapture(I.pointerId)&&R.releasePointerCapture(I.pointerId),document.body.style.webkitUserSelect=b.current,p.viewport&&(p.viewport.style.scrollBehavior=""),v.current=null})})})}),eCe="ScrollAreaThumb",XPt=j.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=YPt(eCe,s.__scopeScrollArea);return e.jsx(Xg,{present:n||a.hasThumb,children:e.jsx(Y_s,{ref:t,...r})})}),Y_s=j.forwardRef((s,t)=>{const{__scopeScrollArea:n,style:r,...a}=s,i=jN(eCe,n),l=YPt(eCe,n),{onThumbPositionChange:o}=l,c=Uo(t,h=>l.onThumbChange(h)),d=j.useRef(void 0),u=X6e(()=>{d.current&&(d.current(),d.current=void 0)},100);return j.useEffect(()=>{const h=i.viewport;if(h){const m=()=>{if(u(),!d.current){const p=Q_s(h,o);d.current=p,o()}};return o(),h.addEventListener("scroll",m),()=>h.removeEventListener("scroll",m)}},[i.viewport,u,o]),e.jsx(si.div,{"data-state":l.hasThumb?"visible":"hidden",...a,ref:c,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:va(s.onPointerDownCapture,h=>{const p=h.target.getBoundingClientRect(),f=h.clientX-p.left,x=h.clientY-p.top;l.onThumbPointerDown({x:f,y:x})}),onPointerUp:va(s.onPointerUp,l.onThumbPointerUp)})});XPt.displayName=eCe;var QZe="ScrollAreaCorner",QPt=j.forwardRef((s,t)=>{const n=jN(QZe,s.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?e.jsx(Z_s,{...s,ref:t}):null});QPt.displayName=QZe;var Z_s=j.forwardRef((s,t)=>{const{__scopeScrollArea:n,...r}=s,a=jN(QZe,n),[i,l]=j.useState(0),[o,c]=j.useState(0),d=!!(i&&o);return OV(a.scrollbarX,()=>{var h;const u=((h=a.scrollbarX)==null?void 0:h.offsetHeight)||0;a.onCornerHeightChange(u),c(u)}),OV(a.scrollbarY,()=>{var h;const u=((h=a.scrollbarY)==null?void 0:h.offsetWidth)||0;a.onCornerWidthChange(u),l(u)}),d?e.jsx(si.div,{...r,ref:t,style:{width:i,height:o,position:"absolute",right:a.dir==="ltr"?0:void 0,left:a.dir==="rtl"?0:void 0,bottom:0,...s.style}}):null});function tCe(s){return s?parseInt(s,10):0}function JPt(s,t){const n=s/t;return isNaN(n)?0:n}function Z6e(s){const t=JPt(s.viewport,s.content),n=s.scrollbar.paddingStart+s.scrollbar.paddingEnd,r=(s.scrollbar.size-n)*t;return Math.max(r,18)}function X_s(s,t,n,r="ltr"){const a=Z6e(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 eLt([c,d],h)(s)}function hht(s,t,n="ltr"){const r=Z6e(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=aee(s,c);return eLt([0,l],[0,o])(d)}function eLt(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])}}function tLt(s,t){return s>0&&s{})=>{let n={left:s.scrollLeft,top:s.scrollTop},r=0;return 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)}(),()=>window.cancelAnimationFrame(r)};function X6e(s,t){const n=sg(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])}function OV(s,t){const n=sg(t);dg(()=>{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])}var sLt=HPt,J_s=WPt,ews=QPt;const Gi=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(sLt,{ref:r,className:Mt("relative overflow-hidden",s),...n,children:[e.jsx(J_s,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(Vne,{}),e.jsx(ews,{})]}));Gi.displayName=sLt.displayName;const Vne=j.forwardRef(({className:s,orientation:t="vertical",...n},r)=>e.jsx(ZZe,{ref:r,orientation:t,className:Mt("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(XPt,{className:"relative flex-1 rounded-full bg-border"})}));Vne.displayName=ZZe.displayName;const tws="/assets/levelup-logo-Eif24dqY.png",sws="/assets/levelup-logo-icon-C-7iromj.png",nws="/assets/levelup-logo-mobile-B9skSjUG.png";var Hne=s=>s.type==="checkbox",UD=s=>s instanceof Date,Y1=s=>s==null;const nLt=s=>typeof s=="object";var Yg=s=>!Y1(s)&&!Array.isArray(s)&&nLt(s)&&!UD(s),rLt=s=>Yg(s)&&s.target?Hne(s.target)?s.target.checked:s.target.value:s,rws=s=>s.substring(0,s.search(/\.\d+(\.|$)/))||s,aLt=(s,t)=>s.has(rws(t)),aws=s=>{const t=s.constructor&&s.constructor.prototype;return Yg(t)&&t.hasOwnProperty("isPrototypeOf")},JZe=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function qx(s){let t;const n=Array.isArray(s),r=typeof FileList<"u"?s instanceof FileList:!1;if(s instanceof Date)t=new Date(s);else if(!(JZe&&(s instanceof Blob||r))&&(n||Yg(s)))if(t=n?[]:{},!n&&!aws(s))t=s;else for(const a in s)s.hasOwnProperty(a)&&(t[a]=qx(s[a]));else return s;return t}var Q6e=s=>/^\w*$/.test(s),Ag=s=>s===void 0,eXe=s=>Array.isArray(s)?s.filter(Boolean):[],tXe=s=>eXe(s.replace(/["|']|\]/g,"").split(/\.|\[/)),Ii=(s,t,n)=>{if(!t||!Yg(s))return n;const r=(Q6e(t)?[t]:tXe(t)).reduce((a,i)=>Y1(a)?a:a[i],s);return Ag(r)||r===s?Ag(s[t])?n:s[t]:r},Lw=s=>typeof s=="boolean",vh=(s,t,n)=>{let r=-1;const a=Q6e(t)?[t]:tXe(t),i=a.length,l=i-1;for(;++rDt.useContext(sXe),iws=s=>{const{children:t,...n}=s;return Dt.createElement(sXe.Provider,{value:n},t)};var iLt=(s,t,n,r=!0)=>{const a={defaultValues:t._defaultValues};for(const i in s)Object.defineProperty(a,i,{get:()=>{const l=i;return t._proxyFormState[l]!==Uk.all&&(t._proxyFormState[l]=!r||Uk.all),n&&(n[l]=!0),s[l]}});return a};const nXe=typeof window<"u"?Dt.useLayoutEffect:Dt.useEffect;function ows(s){const t=J6e(),{control:n=t.control,disabled:r,name:a,exact:i}=s||{},[l,o]=Dt.useState(n._formState),c=Dt.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return nXe(()=>n._subscribe({name:a,formState:c.current,exact:i,callback:d=>{!r&&o({...n._formState,...d})}}),[a,r,i]),Dt.useEffect(()=>{c.current.isValid&&n._setValid(!0)},[n]),Dt.useMemo(()=>iLt(l,n,c.current,!1),[l,n])}var f4=s=>typeof s=="string",oLt=(s,t,n,r,a)=>f4(s)?(r&&t.watch.add(s),Ii(n,s,a)):Array.isArray(s)?s.map(i=>(r&&t.watch.add(i),Ii(n,i))):(r&&(t.watchAll=!0),n),iqe=s=>Y1(s)||!nLt(s);function cA(s,t,n=new WeakSet){if(iqe(s)||iqe(t))return s===t;if(UD(s)&&UD(t))return s.getTime()===t.getTime();const r=Object.keys(s),a=Object.keys(t);if(r.length!==a.length)return!1;if(n.has(s)||n.has(t))return!0;n.add(s),n.add(t);for(const i of r){const l=s[i];if(!a.includes(i))return!1;if(i!=="ref"){const o=t[i];if(UD(l)&&UD(o)||Yg(l)&&Yg(o)||Array.isArray(l)&&Array.isArray(o)?!cA(l,o,n):l!==o)return!1}}return!0}function lws(s){const t=J6e(),{control:n=t.control,name:r,defaultValue:a,disabled:i,exact:l,compute:o}=s||{},c=Dt.useRef(a),d=Dt.useRef(o),u=Dt.useRef(void 0);d.current=o;const h=Dt.useMemo(()=>n._getWatch(r,c.current),[n,r]),[m,p]=Dt.useState(d.current?d.current(h):h);return nXe(()=>n._subscribe({name:r,formState:{values:!0},exact:l,callback:f=>{if(!i){const x=oLt(r,n._names,f.values||n._formValues,!1,c.current);if(d.current){const y=d.current(x);cA(y,u.current)||(p(y),u.current=y)}else p(x)}}}),[n,i,r,l]),Dt.useEffect(()=>n._removeUnmounted()),m}function cws(s){const t=J6e(),{name:n,disabled:r,control:a=t.control,shouldUnregister:i,defaultValue:l}=s,o=aLt(a._names.array,n),c=Dt.useMemo(()=>Ii(a._formValues,n,Ii(a._defaultValues,n,l)),[a,n,l]),d=lws({control:a,name:n,defaultValue:c,exact:!0}),u=ows({control:a,name:n,exact:!0}),h=Dt.useRef(s),m=Dt.useRef(a.register(n,{...s.rules,value:d,...Lw(s.disabled)?{disabled:s.disabled}:{}}));h.current=s;const p=Dt.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!Ii(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!Ii(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!Ii(u.touchedFields,n)},isValidating:{enumerable:!0,get:()=>!!Ii(u.validatingFields,n)},error:{enumerable:!0,get:()=>Ii(u.errors,n)}}),[u,n]),f=Dt.useCallback(b=>m.current.onChange({target:{value:rLt(b),name:n},type:sCe.CHANGE}),[n]),x=Dt.useCallback(()=>m.current.onBlur({target:{value:Ii(a._formValues,n),name:n},type:sCe.BLUR}),[n,a._formValues]),y=Dt.useCallback(b=>{const N=Ii(a._fields,n);N&&b&&(N._f.ref={focus:()=>b.focus&&b.focus(),select:()=>b.select&&b.select(),setCustomValidity:S=>b.setCustomValidity(S),reportValidity:()=>b.reportValidity()})},[a._fields,n]),v=Dt.useMemo(()=>({name:n,value:d,...Lw(r)||u.disabled?{disabled:u.disabled||r}:{},onChange:f,onBlur:x,ref:y}),[n,r,u.disabled,f,x,y,d]);return Dt.useEffect(()=>{const b=a._options.shouldUnregister||i;a.register(n,{...h.current.rules,...Lw(h.current.disabled)?{disabled:h.current.disabled}:{}});const N=(S,A)=>{const T=Ii(a._fields,S);T&&T._f&&(T._f.mount=A)};if(N(n,!0),b){const S=qx(Ii(a._options.defaultValues,n));vh(a._defaultValues,n,S),Ag(Ii(a._formValues,n))&&vh(a._formValues,n,S)}return!o&&a.register(n),()=>{(o?b&&!a._state.action:b)?a.unregister(n):N(n,!1)}},[n,a,o,i]),Dt.useEffect(()=>{a._setDisabledField({disabled:r,name:n})},[r,n,a]),Dt.useMemo(()=>({field:v,formState:u,fieldState:p}),[v,u,p])}const dws=s=>s.render(cws(s));var lLt=(s,t,n,r,a)=>t?{...n[s],types:{...n[s]&&n[s].types?n[s].types:{},[r]:a||!0}}:{},wQ=s=>Array.isArray(s)?s:[s],mht=()=>{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=[]}}},o_=s=>Yg(s)&&!Object.keys(s).length,rXe=s=>s.type==="file",qk=s=>typeof s=="function",nCe=s=>{if(!JZe)return!1;const t=s?s.ownerDocument:0;return s instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},cLt=s=>s.type==="select-multiple",aXe=s=>s.type==="radio",uws=s=>aXe(s)||Hne(s),JDe=s=>nCe(s)&&s.isConnected;function hws(s,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const t in s)if(qk(s[t]))return!0;return!1};function rCe(s,t={}){const n=Array.isArray(s);if(Yg(s)||n)for(const r in s)Array.isArray(s[r])||Yg(s[r])&&!dLt(s[r])?(t[r]=Array.isArray(s[r])?[]:{},rCe(s[r],t[r])):Y1(s[r])||(t[r]=!0);return t}function uLt(s,t,n){const r=Array.isArray(s);if(Yg(s)||r)for(const a in s)Array.isArray(s[a])||Yg(s[a])&&!dLt(s[a])?Ag(t)||iqe(n[a])?n[a]=Array.isArray(s[a])?rCe(s[a],[]):{...rCe(s[a])}:uLt(s[a],Y1(t)?{}:t[a],n[a]):n[a]=!cA(s[a],t[a]);return n}var $K=(s,t)=>uLt(s,t,rCe(t));const pht={value:!1,isValid:!1},fht={value:!0,isValid:!0};var hLt=s=>{if(Array.isArray(s)){if(s.length>1){const t=s.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return s[0].checked&&!s[0].disabled?s[0].attributes&&!Ag(s[0].attributes.value)?Ag(s[0].value)||s[0].value===""?fht:{value:s[0].value,isValid:!0}:fht:pht}return pht},mLt=(s,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ag(s)?s:t?s===""?NaN:s&&+s:n&&f4(s)?new Date(s):r?r(s):s;const ght={isValid:!1,value:null};var pLt=s=>Array.isArray(s)?s.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,ght):ght;function xht(s){const t=s.ref;return rXe(t)?t.files:aXe(t)?pLt(s.refs).value:cLt(t)?[...t.selectedOptions].map(({value:n})=>n):Hne(t)?hLt(s.refs).value:mLt(Ag(t.value)?s.ref.value:t.value,s)}var pws=(s,t,n,r)=>{const a={};for(const i of s){const l=Ii(t,i);l&&vh(a,i,l._f)}return{criteriaMode:n,names:[...s],fields:a,shouldUseNativeValidation:r}},aCe=s=>s instanceof RegExp,VK=s=>Ag(s)?s:aCe(s)?s.source:Yg(s)?aCe(s.value)?s.value.source:s.value:s,yht=s=>({isOnSubmit:!s||s===Uk.onSubmit,isOnBlur:s===Uk.onBlur,isOnChange:s===Uk.onChange,isOnAll:s===Uk.all,isOnTouch:s===Uk.onTouched});const vht="AsyncFunction";var fws=s=>!!s&&!!s.validate&&!!(qk(s.validate)&&s.validate.constructor.name===vht||Yg(s.validate)&&Object.values(s.validate).find(t=>t.constructor.name===vht)),gws=s=>s.mount&&(s.required||s.min||s.max||s.maxLength||s.minLength||s.pattern||s.validate),bht=(s,t,n)=>!n&&(t.watchAll||t.watch.has(s)||[...t.watch].some(r=>s.startsWith(r)&&/^\.\w+/.test(s.slice(r.length))));const jQ=(s,t,n,r)=>{for(const a of n||Object.keys(s)){const i=Ii(s,a);if(i){const{_f:l,...o}=i;if(l){if(l.refs&&l.refs[0]&&t(l.refs[0],a)&&!r)return!0;if(l.ref&&t(l.ref,l.name)&&!r)return!0;if(jQ(o,t))break}else if(Yg(o)&&jQ(o,t))break}}};function _ht(s,t,n){const r=Ii(s,n);if(r||Q6e(n))return{error:r,name:n};const a=n.split(".");for(;a.length;){const i=a.join("."),l=Ii(t,i),o=Ii(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 xws=(s,t,n,r)=>{n(s);const{name:a,...i}=s;return o_(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(l=>t[l]===(!r||Uk.all))},yws=(s,t,n)=>!s||!t||s===t||wQ(s).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r))),vws=(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,bws=(s,t)=>!eXe(Ii(s,t)).length&&ix(s,t),_ws=(s,t,n)=>{const r=wQ(Ii(s,n));return vh(r,"root",t[n]),vh(s,n,r),s},_5e=s=>f4(s);function wht(s,t,n="validate"){if(_5e(s)||Array.isArray(s)&&s.every(_5e)||Lw(s)&&!s)return{type:n,message:_5e(s)?s:"",ref:t}}var Bz=s=>Yg(s)&&!aCe(s)?s:{value:s,message:""},jht=async(s,t,n,r,a,i)=>{const{ref:l,refs:o,required:c,maxLength:d,minLength:u,min:h,max:m,pattern:p,validate:f,name:x,valueAsNumber:y,mount:v}=s._f,b=Ii(n,x);if(!v||t.has(x))return{};const N=o?o[0]:l,S=$=>{a&&N.reportValidity&&(N.setCustomValidity(Lw($)?"":$||""),N.reportValidity())},A={},T=aXe(l),L=Hne(l),M=T||L,I=(y||rXe(l))&&Ag(l.value)&&Ag(b)||nCe(l)&&l.value===""||b===""||Array.isArray(b)&&!b.length,R=lLt.bind(null,x,r,A),z=($,H,V,K=X3.maxLength,Z=X3.minLength)=>{const Q=$?H:V;A[x]={type:$?K:Z,message:Q,ref:l,...R($?K:Z,Q)}};if(i?!Array.isArray(b)||!b.length:c&&(!M&&(I||Y1(b))||Lw(b)&&!b||L&&!hLt(o).isValid||T&&!pLt(o).isValid)){const{value:$,message:H}=_5e(c)?{value:!!c,message:c}:Bz(c);if($&&(A[x]={type:X3.required,message:H,ref:N,...R(X3.required,H)},!r))return S(H),A}if(!I&&(!Y1(h)||!Y1(m))){let $,H;const V=Bz(m),K=Bz(h);if(!Y1(b)&&!isNaN(b)){const Z=l.valueAsNumber||b&&+b;Y1(V.value)||($=Z>V.value),Y1(K.value)||(H=Znew Date(new Date().toDateString()+" "+se),le=l.type=="time",ue=l.type=="week";f4(V.value)&&b&&($=le?Q(b)>Q(V.value):ue?b>V.value:Z>new Date(V.value)),f4(K.value)&&b&&(H=le?Q(b)+$.value,K=!Y1(H.value)&&b.length<+H.value;if((V||K)&&(z(V,$.message,H.message),!r))return S(A[x].message),A}if(p&&!I&&f4(b)){const{value:$,message:H}=Bz(p);if(aCe($)&&!b.match($)&&(A[x]={type:X3.pattern,message:H,ref:l,...R(X3.pattern,H)},!r))return S(H),A}if(f){if(qk(f)){const $=await f(b,n),H=wht($,N);if(H&&(A[x]={...H,...R(X3.validate,H.message)},!r))return S(H.message),A}else if(Yg(f)){let $={};for(const H in f){if(!o_($)&&!r)break;const V=wht(await f[H](b,n),N,H);V&&($={...V,...R(H,V.message)},S(V.message),r&&(A[x]=$))}if(!o_($)&&(A[x]={ref:N,...$},!r))return A}}return S(!0),A};const wws={mode:Uk.onSubmit,reValidateMode:Uk.onChange,shouldFocusError:!0};function jws(s={}){let t={...wws,...s},n={submitCount:0,isDirty:!1,isReady:!1,isLoading:qk(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},r={},a=Yg(t.defaultValues)||Yg(t.values)?qx(t.defaultValues||t.values)||{}:{},i=t.shouldUnregister?{}:qx(a),l={action:!1,mount:!1,watch:!1},o={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},c,d=0;const u={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1};let h={...u};const m={array:mht(),state:mht()},p=t.criteriaMode===Uk.all,f=Ze=>Ue=>{clearTimeout(d),d=setTimeout(Ze,Ue)},x=async Ze=>{if(!t.disabled&&(u.isValid||h.isValid||Ze)){const Ue=t.resolver?o_((await L()).errors):await I(r,!0);Ue!==n.isValid&&m.state.next({isValid:Ue})}},y=(Ze,Ue)=>{!t.disabled&&(u.isValidating||u.validatingFields||h.isValidating||h.validatingFields)&&((Ze||Array.from(o.mount)).forEach(Ye=>{Ye&&(Ue?vh(n.validatingFields,Ye,Ue):ix(n.validatingFields,Ye))}),m.state.next({validatingFields:n.validatingFields,isValidating:!o_(n.validatingFields)}))},v=(Ze,Ue=[],Ye,Ge,He=!0,tt=!0)=>{if(Ge&&Ye&&!t.disabled){if(l.action=!0,tt&&Array.isArray(Ii(r,Ze))){const pt=Ye(Ii(r,Ze),Ge.argA,Ge.argB);He&&vh(r,Ze,pt)}if(tt&&Array.isArray(Ii(n.errors,Ze))){const pt=Ye(Ii(n.errors,Ze),Ge.argA,Ge.argB);He&&vh(n.errors,Ze,pt),bws(n.errors,Ze)}if((u.touchedFields||h.touchedFields)&&tt&&Array.isArray(Ii(n.touchedFields,Ze))){const pt=Ye(Ii(n.touchedFields,Ze),Ge.argA,Ge.argB);He&&vh(n.touchedFields,Ze,pt)}(u.dirtyFields||h.dirtyFields)&&(n.dirtyFields=$K(a,i)),m.state.next({name:Ze,isDirty:z(Ze,Ue),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else vh(i,Ze,Ue)},b=(Ze,Ue)=>{vh(n.errors,Ze,Ue),m.state.next({errors:n.errors})},N=Ze=>{n.errors=Ze,m.state.next({errors:n.errors,isValid:!1})},S=(Ze,Ue,Ye,Ge)=>{const He=Ii(r,Ze);if(He){const tt=Ii(i,Ze,Ag(Ye)?Ii(a,Ze):Ye);Ag(tt)||Ge&&Ge.defaultChecked||Ue?vh(i,Ze,Ue?tt:xht(He._f)):V(Ze,tt),l.mount&&x()}},A=(Ze,Ue,Ye,Ge,He)=>{let tt=!1,pt=!1;const ft={name:Ze};if(!t.disabled){if(!Ye||Ge){(u.isDirty||h.isDirty)&&(pt=n.isDirty,n.isDirty=ft.isDirty=z(),tt=pt!==ft.isDirty);const qt=cA(Ii(a,Ze),Ue);pt=!!Ii(n.dirtyFields,Ze),qt?ix(n.dirtyFields,Ze):vh(n.dirtyFields,Ze,!0),ft.dirtyFields=n.dirtyFields,tt=tt||(u.dirtyFields||h.dirtyFields)&&pt!==!qt}if(Ye){const qt=Ii(n.touchedFields,Ze);qt||(vh(n.touchedFields,Ze,Ye),ft.touchedFields=n.touchedFields,tt=tt||(u.touchedFields||h.touchedFields)&&qt!==Ye)}tt&&He&&m.state.next(ft)}return tt?ft:{}},T=(Ze,Ue,Ye,Ge)=>{const He=Ii(n.errors,Ze),tt=(u.isValid||h.isValid)&&Lw(Ue)&&n.isValid!==Ue;if(t.delayError&&Ye?(c=f(()=>b(Ze,Ye)),c(t.delayError)):(clearTimeout(d),c=null,Ye?vh(n.errors,Ze,Ye):ix(n.errors,Ze)),(Ye?!cA(He,Ye):He)||!o_(Ge)||tt){const pt={...Ge,...tt&&Lw(Ue)?{isValid:Ue}:{},errors:n.errors,name:Ze};n={...n,...pt},m.state.next(pt)}},L=async Ze=>{y(Ze,!0);const Ue=await t.resolver(i,t.context,pws(Ze||o.mount,r,t.criteriaMode,t.shouldUseNativeValidation));return y(Ze),Ue},M=async Ze=>{const{errors:Ue}=await L(Ze);if(Ze)for(const Ye of Ze){const Ge=Ii(Ue,Ye);Ge?vh(n.errors,Ye,Ge):ix(n.errors,Ye)}else n.errors=Ue;return Ue},I=async(Ze,Ue,Ye={valid:!0})=>{for(const Ge in Ze){const He=Ze[Ge];if(He){const{_f:tt,...pt}=He;if(tt){const ft=o.array.has(tt.name),qt=He._f&&fws(He._f);qt&&u.validatingFields&&y([Ge],!0);const Ut=await jht(He,o.disabled,i,p,t.shouldUseNativeValidation&&!Ue,ft);if(qt&&u.validatingFields&&y([Ge]),Ut[tt.name]&&(Ye.valid=!1,Ue))break;!Ue&&(Ii(Ut,tt.name)?ft?_ws(n.errors,Ut,tt.name):vh(n.errors,tt.name,Ut[tt.name]):ix(n.errors,tt.name))}!o_(pt)&&await I(pt,Ue,Ye)}}return Ye.valid},R=()=>{for(const Ze of o.unMount){const Ue=Ii(r,Ze);Ue&&(Ue._f.refs?Ue._f.refs.every(Ye=>!JDe(Ye)):!JDe(Ue._f.ref))&&ge(Ze)}o.unMount=new Set},z=(Ze,Ue)=>!t.disabled&&(Ze&&Ue&&vh(i,Ze,Ue),!cA(se(),a)),$=(Ze,Ue,Ye)=>oLt(Ze,o,{...l.mount?i:Ag(Ue)?a:f4(Ze)?{[Ze]:Ue}:Ue},Ye,Ue),H=Ze=>eXe(Ii(l.mount?i:a,Ze,t.shouldUnregister?Ii(a,Ze,[]):[])),V=(Ze,Ue,Ye={})=>{const Ge=Ii(r,Ze);let He=Ue;if(Ge){const tt=Ge._f;tt&&(!tt.disabled&&vh(i,Ze,mLt(Ue,tt)),He=nCe(tt.ref)&&Y1(Ue)?"":Ue,cLt(tt.ref)?[...tt.ref.options].forEach(pt=>pt.selected=He.includes(pt.value)):tt.refs?Hne(tt.ref)?tt.refs.forEach(pt=>{(!pt.defaultChecked||!pt.disabled)&&(Array.isArray(He)?pt.checked=!!He.find(ft=>ft===pt.value):pt.checked=He===pt.value||!!He)}):tt.refs.forEach(pt=>pt.checked=pt.value===He):rXe(tt.ref)?tt.ref.value="":(tt.ref.value=He,tt.ref.type||m.state.next({name:Ze,values:qx(i)})))}(Ye.shouldDirty||Ye.shouldTouch)&&A(Ze,He,Ye.shouldTouch,Ye.shouldDirty,!0),Ye.shouldValidate&&ue(Ze)},K=(Ze,Ue,Ye)=>{for(const Ge in Ue){if(!Ue.hasOwnProperty(Ge))return;const He=Ue[Ge],tt=Ze+"."+Ge,pt=Ii(r,tt);(o.array.has(Ze)||Yg(He)||pt&&!pt._f)&&!UD(He)?K(tt,He,Ye):V(tt,He,Ye)}},Z=(Ze,Ue,Ye={})=>{const Ge=Ii(r,Ze),He=o.array.has(Ze),tt=qx(Ue);vh(i,Ze,tt),He?(m.array.next({name:Ze,values:qx(i)}),(u.isDirty||u.dirtyFields||h.isDirty||h.dirtyFields)&&Ye.shouldDirty&&m.state.next({name:Ze,dirtyFields:$K(a,i),isDirty:z(Ze,tt)})):Ge&&!Ge._f&&!Y1(tt)?K(Ze,tt,Ye):V(Ze,tt,Ye),bht(Ze,o)&&m.state.next({...n,name:Ze}),m.state.next({name:l.mount?Ze:void 0,values:qx(i)})},Q=async Ze=>{l.mount=!0;const Ue=Ze.target;let Ye=Ue.name,Ge=!0;const He=Ii(r,Ye),tt=qt=>{Ge=Number.isNaN(qt)||UD(qt)&&isNaN(qt.getTime())||cA(qt,Ii(i,Ye,qt))},pt=yht(t.mode),ft=yht(t.reValidateMode);if(He){let qt,Ut;const Wt=Ue.type?xht(He._f):rLt(Ze),us=Ze.type===sCe.BLUR||Ze.type===sCe.FOCUS_OUT,zt=!gws(He._f)&&!t.resolver&&!Ii(n.errors,Ye)&&!He._f.deps||vws(us,Ii(n.touchedFields,Ye),n.isSubmitted,ft,pt),bt=bht(Ye,o,us);vh(i,Ye,Wt),us?(He._f.onBlur&&He._f.onBlur(Ze),c&&c(0)):He._f.onChange&&He._f.onChange(Ze);const As=A(Ye,Wt,us),vt=!o_(As)||bt;if(!us&&m.state.next({name:Ye,type:Ze.type,values:qx(i)}),zt)return(u.isValid||h.isValid)&&(t.mode==="onBlur"?us&&x():us||x()),vt&&m.state.next({name:Ye,...bt?{}:As});if(!us&&bt&&m.state.next({...n}),t.resolver){const{errors:Ws}=await L([Ye]);if(tt(Wt),Ge){const on=_ht(n.errors,r,Ye),Ms=_ht(Ws,r,on.name||Ye);qt=Ms.error,Ye=Ms.name,Ut=o_(Ws)}}else y([Ye],!0),qt=(await jht(He,o.disabled,i,p,t.shouldUseNativeValidation))[Ye],y([Ye]),tt(Wt),Ge&&(qt?Ut=!1:(u.isValid||h.isValid)&&(Ut=await I(r,!0)));Ge&&(He._f.deps&&ue(He._f.deps),T(Ye,Ut,qt,As))}},le=(Ze,Ue)=>{if(Ii(n.errors,Ue)&&Ze.focus)return Ze.focus(),1},ue=async(Ze,Ue={})=>{let Ye,Ge;const He=wQ(Ze);if(t.resolver){const tt=await M(Ag(Ze)?Ze:He);Ye=o_(tt),Ge=Ze?!He.some(pt=>Ii(tt,pt)):Ye}else Ze?(Ge=(await Promise.all(He.map(async tt=>{const pt=Ii(r,tt);return await I(pt&&pt._f?{[tt]:pt}:pt)}))).every(Boolean),!(!Ge&&!n.isValid)&&x()):Ge=Ye=await I(r);return m.state.next({...!f4(Ze)||(u.isValid||h.isValid)&&Ye!==n.isValid?{}:{name:Ze},...t.resolver||!Ze?{isValid:Ye}:{},errors:n.errors}),Ue.shouldFocus&&!Ge&&jQ(r,le,Ze?He:o.mount),Ge},se=Ze=>{const Ue={...l.mount?i:a};return Ag(Ze)?Ue:f4(Ze)?Ii(Ue,Ze):Ze.map(Ye=>Ii(Ue,Ye))},ne=(Ze,Ue)=>({invalid:!!Ii((Ue||n).errors,Ze),isDirty:!!Ii((Ue||n).dirtyFields,Ze),error:Ii((Ue||n).errors,Ze),isValidating:!!Ii(n.validatingFields,Ze),isTouched:!!Ii((Ue||n).touchedFields,Ze)}),ie=Ze=>{Ze&&wQ(Ze).forEach(Ue=>ix(n.errors,Ue)),m.state.next({errors:Ze?n.errors:{}})},ce=(Ze,Ue,Ye)=>{const Ge=(Ii(r,Ze,{_f:{}})._f||{}).ref,He=Ii(n.errors,Ze)||{},{ref:tt,message:pt,type:ft,...qt}=He;vh(n.errors,Ze,{...qt,...Ue,ref:Ge}),m.state.next({name:Ze,errors:n.errors,isValid:!1}),Ye&&Ye.shouldFocus&&Ge&&Ge.focus&&Ge.focus()},je=(Ze,Ue)=>qk(Ze)?m.state.subscribe({next:Ye=>"values"in Ye&&Ze($(void 0,Ue),Ye)}):$(Ze,Ue,!0),be=Ze=>m.state.subscribe({next:Ue=>{yws(Ze.name,Ue.name,Ze.exact)&&xws(Ue,Ze.formState||u,$e,Ze.reRenderRoot)&&Ze.callback({values:{...i},...n,...Ue,defaultValues:a})}}).unsubscribe,he=Ze=>(l.mount=!0,h={...h,...Ze.formState},be({...Ze,formState:h})),ge=(Ze,Ue={})=>{for(const Ye of Ze?wQ(Ze):o.mount)o.mount.delete(Ye),o.array.delete(Ye),Ue.keepValue||(ix(r,Ye),ix(i,Ye)),!Ue.keepError&&ix(n.errors,Ye),!Ue.keepDirty&&ix(n.dirtyFields,Ye),!Ue.keepTouched&&ix(n.touchedFields,Ye),!Ue.keepIsValidating&&ix(n.validatingFields,Ye),!t.shouldUnregister&&!Ue.keepDefaultValue&&ix(a,Ye);m.state.next({values:qx(i)}),m.state.next({...n,...Ue.keepDirty?{isDirty:z()}:{}}),!Ue.keepIsValid&&x()},ke=({disabled:Ze,name:Ue})=>{(Lw(Ze)&&l.mount||Ze||o.disabled.has(Ue))&&(Ze?o.disabled.add(Ue):o.disabled.delete(Ue))},Te=(Ze,Ue={})=>{let Ye=Ii(r,Ze);const Ge=Lw(Ue.disabled)||Lw(t.disabled);return vh(r,Ze,{...Ye||{},_f:{...Ye&&Ye._f?Ye._f:{ref:{name:Ze}},name:Ze,mount:!0,...Ue}}),o.mount.add(Ze),Ye?ke({disabled:Lw(Ue.disabled)?Ue.disabled:t.disabled,name:Ze}):S(Ze,!0,Ue.value),{...Ge?{disabled:Ue.disabled||t.disabled}:{},...t.progressive?{required:!!Ue.required,min:VK(Ue.min),max:VK(Ue.max),minLength:VK(Ue.minLength),maxLength:VK(Ue.maxLength),pattern:VK(Ue.pattern)}:{},name:Ze,onChange:Q,onBlur:Q,ref:He=>{if(He){Te(Ze,Ue),Ye=Ii(r,Ze);const tt=Ag(He.value)&&He.querySelectorAll&&He.querySelectorAll("input,select,textarea")[0]||He,pt=uws(tt),ft=Ye._f.refs||[];if(pt?ft.find(qt=>qt===tt):tt===Ye._f.ref)return;vh(r,Ze,{_f:{...Ye._f,...pt?{refs:[...ft.filter(JDe),tt,...Array.isArray(Ii(a,Ze))?[{}]:[]],ref:{type:tt.type,name:Ze}}:{ref:tt}}}),S(Ze,!1,void 0,tt)}else Ye=Ii(r,Ze,{}),Ye._f&&(Ye._f.mount=!1),(t.shouldUnregister||Ue.shouldUnregister)&&!(aLt(o.array,Ze)&&l.action)&&o.unMount.add(Ze)}}},Me=()=>t.shouldFocusError&&jQ(r,le,o.mount),Oe=Ze=>{Lw(Ze)&&(m.state.next({disabled:Ze}),jQ(r,(Ue,Ye)=>{const Ge=Ii(r,Ye);Ge&&(Ue.disabled=Ge._f.disabled||Ze,Array.isArray(Ge._f.refs)&&Ge._f.refs.forEach(He=>{He.disabled=Ge._f.disabled||Ze}))},0,!1))},Se=(Ze,Ue)=>async Ye=>{let Ge;Ye&&(Ye.preventDefault&&Ye.preventDefault(),Ye.persist&&Ye.persist());let He=qx(i);if(m.state.next({isSubmitting:!0}),t.resolver){const{errors:tt,values:pt}=await L();n.errors=tt,He=qx(pt)}else await I(r);if(o.disabled.size)for(const tt of o.disabled)ix(He,tt);if(ix(n.errors,"root"),o_(n.errors)){m.state.next({errors:{}});try{await Ze(He,Ye)}catch(tt){Ge=tt}}else Ue&&await Ue({...n.errors},Ye),Me(),setTimeout(Me);if(m.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:o_(n.errors)&&!Ge,submitCount:n.submitCount+1,errors:n.errors}),Ge)throw Ge},Qe=(Ze,Ue={})=>{Ii(r,Ze)&&(Ag(Ue.defaultValue)?Z(Ze,qx(Ii(a,Ze))):(Z(Ze,Ue.defaultValue),vh(a,Ze,qx(Ue.defaultValue))),Ue.keepTouched||ix(n.touchedFields,Ze),Ue.keepDirty||(ix(n.dirtyFields,Ze),n.isDirty=Ue.defaultValue?z(Ze,qx(Ii(a,Ze))):z()),Ue.keepError||(ix(n.errors,Ze),u.isValid&&x()),m.state.next({...n}))},Ae=(Ze,Ue={})=>{const Ye=Ze?qx(Ze):a,Ge=qx(Ye),He=o_(Ze),tt=He?a:Ge;if(Ue.keepDefaultValues||(a=Ye),!Ue.keepValues){if(Ue.keepDirtyValues){const pt=new Set([...o.mount,...Object.keys($K(a,i))]);for(const ft of Array.from(pt))Ii(n.dirtyFields,ft)?vh(tt,ft,Ii(i,ft)):Z(ft,Ii(tt,ft))}else{if(JZe&&Ag(Ze))for(const pt of o.mount){const ft=Ii(r,pt);if(ft&&ft._f){const qt=Array.isArray(ft._f.refs)?ft._f.refs[0]:ft._f.ref;if(nCe(qt)){const Ut=qt.closest("form");if(Ut){Ut.reset();break}}}}if(Ue.keepFieldsRef)for(const pt of o.mount)Z(pt,Ii(tt,pt));else r={}}i=t.shouldUnregister?Ue.keepDefaultValues?qx(a):{}:qx(tt),m.array.next({values:{...tt}}),m.state.next({values:{...tt}})}o={mount:Ue.keepDirtyValues?o.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},l.mount=!u.isValid||!!Ue.keepIsValid||!!Ue.keepDirtyValues,l.watch=!!t.shouldUnregister,m.state.next({submitCount:Ue.keepSubmitCount?n.submitCount:0,isDirty:He?!1:Ue.keepDirty?n.isDirty:!!(Ue.keepDefaultValues&&!cA(Ze,a)),isSubmitted:Ue.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:He?{}:Ue.keepDirtyValues?Ue.keepDefaultValues&&i?$K(a,i):n.dirtyFields:Ue.keepDefaultValues&&Ze?$K(a,Ze):Ue.keepDirty?n.dirtyFields:{},touchedFields:Ue.keepTouched?n.touchedFields:{},errors:Ue.keepErrors?n.errors:{},isSubmitSuccessful:Ue.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1})},Fe=(Ze,Ue)=>Ae(qk(Ze)?Ze(i):Ze,Ue),Ne=(Ze,Ue={})=>{const Ye=Ii(r,Ze),Ge=Ye&&Ye._f;if(Ge){const He=Ge.refs?Ge.refs[0]:Ge.ref;He.focus&&(He.focus(),Ue.shouldSelect&&qk(He.select)&&He.select())}},$e=Ze=>{n={...n,...Ze}},qe={control:{register:Te,unregister:ge,getFieldState:ne,handleSubmit:Se,setError:ce,_subscribe:be,_runSchema:L,_focusError:Me,_getWatch:$,_getDirty:z,_setValid:x,_setFieldArray:v,_setDisabledField:ke,_setErrors:N,_getFieldArray:H,_reset:Ae,_resetDefaultValues:()=>qk(t.defaultValues)&&t.defaultValues().then(Ze=>{Fe(Ze,t.resetOptions),m.state.next({isLoading:!1})}),_removeUnmounted:R,_disableForm:Oe,_subjects:m,_proxyFormState:u,get _fields(){return r},get _formValues(){return i},get _state(){return l},set _state(Ze){l=Ze},get _defaultValues(){return a},get _names(){return o},set _names(Ze){o=Ze},get _formState(){return n},get _options(){return t},set _options(Ze){t={...t,...Ze}}},subscribe:he,trigger:ue,register:Te,handleSubmit:Se,watch:je,setValue:Z,getValues:se,reset:Fe,resetField:Qe,clearErrors:ie,unregister:ge,setError:ce,setFocus:Ne,getFieldState:ne};return{...qe,formControl:qe}}function eMe(s={}){const t=Dt.useRef(void 0),n=Dt.useRef(void 0),[r,a]=Dt.useState({isDirty:!1,isValidating:!1,isLoading:qk(s.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:s.errors||{},disabled:s.disabled||!1,isReady:!1,defaultValues:qk(s.defaultValues)?void 0:s.defaultValues});if(!t.current)if(s.formControl)t.current={...s.formControl,formState:r},s.defaultValues&&!qk(s.defaultValues)&&s.formControl.reset(s.defaultValues,s.resetOptions);else{const{formControl:l,...o}=jws(s);t.current={...o,formState:r}}const i=t.current.control;return i._options=s,nXe(()=>{const l=i._subscribe({formState:i._proxyFormState,callback:()=>a({...i._formState}),reRenderRoot:!0});return a(o=>({...o,isReady:!0})),i._formState.isReady=!0,l},[i]),Dt.useEffect(()=>i._disableForm(s.disabled),[i,s.disabled]),Dt.useEffect(()=>{s.mode&&(i._options.mode=s.mode),s.reValidateMode&&(i._options.reValidateMode=s.reValidateMode)},[i,s.mode,s.reValidateMode]),Dt.useEffect(()=>{s.errors&&(i._setErrors(s.errors),i._focusError())},[i,s.errors]),Dt.useEffect(()=>{s.shouldUnregister&&i._subjects.state.next({values:i._getWatch()})},[i,s.shouldUnregister]),Dt.useEffect(()=>{if(i._proxyFormState.isDirty){const l=i._getDirty();l!==r.isDirty&&i._subjects.state.next({isDirty:l})}},[i,r.isDirty]),Dt.useEffect(()=>{s.values&&!cA(s.values,n.current)?(i._reset(s.values,{keepFieldsRef:!0,...i._options.resetOptions}),n.current=s.values,a(l=>({...l}))):i._resetDefaultValues()},[i,s.values]),Dt.useEffect(()=>{i._state.mount||(i._setValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=iLt(r,i),t.current}const Nht=(s,t,n)=>{if(s&&"reportValidity"in s){const r=Ii(n,t);s.setCustomValidity(r&&r.message||""),s.reportValidity()}},fLt=(s,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?Nht(r.ref,n,s):r.refs&&r.refs.forEach(a=>Nht(a,n,s))}},Nws=(s,t)=>{t.shouldUseNativeValidation&&fLt(s,t);const n={};for(const r in s){const a=Ii(t.fields,r),i=Object.assign(s[r]||{},{ref:a&&a.ref});if(kws(t.names||Object.keys(s),r)){const l=Object.assign({},Ii(n,r));vh(l,"root",i),vh(n,r,l)}else vh(n,r,i)}return n},kws=(s,t)=>s.some(n=>n.startsWith(t+"."));var Sws=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]=lLt(l,t,n,a,d?[].concat(d,r.message):r.message)}s.shift()}return n},tMe=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&&fLt({},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:Nws(Sws(l.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw l}))}catch(l){return Promise.reject(l)}}},kht;function ua(s,t,n){function r(o,c){if(o._zod||Object.defineProperty(o,"_zod",{value:{def:c,constr:l,traits:new Set},enumerable:!1}),o._zod.traits.has(s))return;o._zod.traits.add(s),t(o,c);const d=l.prototype,u=Object.keys(d);for(let h=0;h{var c,d;return n!=null&&n.Parent&&o instanceof n.Parent?!0:(d=(c=o==null?void 0:o._zod)==null?void 0:c.traits)==null?void 0:d.has(s)}}),Object.defineProperty(l,"name",{value:s}),l}class Rq extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class gLt extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(kht=globalThis).__zod_globalConfig??(kht.__zod_globalConfig={});const iXe=globalThis.__zod_globalConfig;function _7(s){return iXe}function xLt(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 oqe(s,t){return typeof t=="bigint"?t.toString():t}function oXe(s){return{get value(){{const t=s();return Object.defineProperty(this,"value",{value:t}),t}}}}function lXe(s){return s==null}function cXe(s){const t=s.startsWith("^")?1:0,n=s.endsWith("$")?s.length-1:s.length;return s.slice(t,n)}function Cws(s,t){const n=s/t,r=Math.round(n),a=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r){};function iCe(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}const Ews=oXe(()=>{var s;if(iXe.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 iee(s){if(iCe(s)===!1)return!1;const t=s.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(iCe(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function vLt(s){return iee(s)?{...s}:Array.isArray(s)?[...s]:s instanceof Map?new Map(s):s instanceof Set?new Set(s):s}const Tws=new Set(["string","number","symbol"]);function FV(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function FP(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 Zo(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 Mws(s){return Object.keys(s).filter(t=>s[t]._zod.optin==="optional"&&s[t]._zod.optout==="optional")}const Pws={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]};function Lws(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=OP(s._zod.def,{get shape(){const l={};for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(l[o]=n.shape[o])}return f9(this,"shape",l),l},checks:[]});return FP(s,i)}function Iws(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=OP(s._zod.def,{get shape(){const l={...s._zod.def.shape};for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete l[o]}return f9(this,"shape",l),l},checks:[]});return FP(s,i)}function Rws(s,t){if(!iee(t))throw new Error("Invalid input to extend: expected a plain object");const n=s._zod.def.checks;if(n&&n.length>0){const i=s._zod.def.shape;for(const l in t)if(Object.getOwnPropertyDescriptor(i,l)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const a=OP(s._zod.def,{get shape(){const i={...s._zod.def.shape,...t};return f9(this,"shape",i),i}});return FP(s,a)}function Dws(s,t){if(!iee(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=OP(s._zod.def,{get shape(){const r={...s._zod.def.shape,...t};return f9(this,"shape",r),r}});return FP(s,n)}function Ows(s,t){var r;if((r=s._zod.def.checks)!=null&&r.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=OP(s._zod.def,{get shape(){const a={...s._zod.def.shape,...t._zod.def.shape};return f9(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return FP(s,n)}function Fws(s,t,n){const a=t._zod.def.checks;if(a&&a.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const l=OP(t._zod.def,{get shape(){const o=t._zod.def.shape,c={...o};if(n)for(const d in n){if(!(d in o))throw new Error(`Unrecognized key: "${d}"`);n[d]&&(c[d]=s?new s({type:"optional",innerType:o[d]}):o[d])}else for(const d in o)c[d]=s?new s({type:"optional",innerType:o[d]}):o[d];return f9(this,"shape",c),c},checks:[]});return FP(t,l)}function zws(s,t,n){const r=OP(t._zod.def,{get shape(){const a=t._zod.def.shape,i={...a};if(n)for(const l in n){if(!(l in i))throw new Error(`Unrecognized key: "${l}"`);n[l]&&(i[l]=new s({type:"nonoptional",innerType:a[l]}))}else for(const l in a)i[l]=new s({type:"nonoptional",innerType:a[l]});return f9(this,"shape",i),i}});return FP(t,r)}function fU(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 poe(s){return typeof s=="string"?s:s==null?void 0:s.message}function w7(s,t,n){var c,d,u,h,m,p;const r=s.message?s.message:poe((u=(d=(c=s.inst)==null?void 0:c._zod.def)==null?void 0:d.error)==null?void 0:u.call(d,s))??poe((h=t==null?void 0:t.error)==null?void 0:h.call(t,s))??poe((m=n.customError)==null?void 0:m.call(n,s))??poe((p=n.localeError)==null?void 0:p.call(n,s))??"Invalid input",{inst:a,continue:i,input:l,...o}=s;return o.path??(o.path=[]),o.message=r,t!=null&&t.reportInput&&(o.input=l),o}function dXe(s){return Array.isArray(s)?"array":typeof s=="string"?"string":"unknown"}function oee(...s){const[t,n,r]=s;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const _Lt=(s,t)=>{s.name="$ZodError",Object.defineProperty(s,"_zod",{value:s._zod,enumerable:!1}),Object.defineProperty(s,"issues",{value:t,enumerable:!1}),s.message=JSON.stringify(t,oqe,2),Object.defineProperty(s,"toString",{value:()=>s.message,enumerable:!1})},wLt=ua("$ZodError",_Lt),jLt=ua("$ZodError",_Lt,{Parent:Error});function Uws(s,t=n=>n.message){const n={},r=[];for(const a of s.issues)a.path.length>0?(n[a.path[0]]=n[a.path[0]]||[],n[a.path[0]].push(t(a))):r.push(t(a));return{formErrors:r,fieldErrors:n}}function qws(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(t,n,r,a)=>{const i=r?{...r,async:!1}:{async:!1},l=t._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw new Rq;if(l.issues.length){const o=new((a==null?void 0:a.Err)??s)(l.issues.map(c=>w7(c,i,_7())));throw yLt(o,a==null?void 0:a.callee),o}return l.value},hXe=s=>async(t,n,r,a)=>{const i=r?{...r,async:!0}:{async:!0};let l=t._zod.run({value:n,issues:[]},i);if(l instanceof Promise&&(l=await l),l.issues.length){const o=new((a==null?void 0:a.Err)??s)(l.issues.map(c=>w7(c,i,_7())));throw yLt(o,a==null?void 0:a.callee),o}return l.value},sMe=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 Rq;return i.issues.length?{success:!1,error:new(s??wLt)(i.issues.map(l=>w7(l,a,_7())))}:{success:!0,data:i.value}},$ws=sMe(jLt),nMe=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?{success:!1,error:new s(i.issues.map(l=>w7(l,a,_7())))}:{success:!0,data:i.value}},Vws=nMe(jLt),Hws=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return uXe(s)(t,n,a)},Gws=s=>(t,n,r)=>uXe(s)(t,n,r),Wws=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return hXe(s)(t,n,a)},Kws=s=>async(t,n,r)=>hXe(s)(t,n,r),Yws=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return sMe(s)(t,n,a)},Zws=s=>(t,n,r)=>sMe(s)(t,n,r),Xws=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return nMe(s)(t,n,a)},Qws=s=>async(t,n,r)=>nMe(s)(t,n,r),Jws=/^[cC][0-9a-z]{6,}$/,ejs=/^[0-9a-z]+$/,tjs=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,sjs=/^[0-9a-vA-V]{20}$/,njs=/^[A-Za-z0-9]{27}$/,rjs=/^[a-zA-Z0-9_-]{21}$/,ajs=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ijs=/^([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})$/,Aht=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)$/,ojs=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,ljs="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function cjs(){return new RegExp(ljs,"u")}const djs=/^(?:(?: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])$/,ujs=/^(([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}|:))$/,hjs=/^((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])$/,mjs=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,pjs=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,NLt=/^[A-Za-z0-9_-]*$/,fjs=/^https?$/,gjs=/^\+[1-9]\d{6,14}$/,kLt="(?:(?:\\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])))",xjs=new RegExp(`^${kLt}$`);function SLt(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}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function yjs(s){return new RegExp(`^${SLt(s)}$`)}function vjs(s){const t=SLt({precision:s.precision}),n=["Z"];s.local&&n.push(""),s.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${kLt}T(?:${r})$`)}const bjs=s=>{const t=s?`[\\s\\S]{${(s==null?void 0:s.minimum)??0},${(s==null?void 0:s.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},_js=/^-?\d+$/,wjs=/^-?\d+(?:\.\d+)?$/,jjs=/^(?:true|false)$/i,Njs=/^[^A-Z]*$/,kjs=/^[^a-z]*$/,R_=ua("$ZodCheck",(s,t)=>{var n;s._zod??(s._zod={}),s._zod.def=t,(n=s._zod).onattach??(n.onattach=[])}),CLt={number:"number",bigint:"bigint",object:"date"},ALt=ua("$ZodCheckLessThan",(s,t)=>{R_.init(s,t);const n=CLt[typeof t.value];s._zod.onattach.push(r=>{const a=r._zod.bag,i=(t.inclusive?a.maximum:a.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value{(t.inclusive?r.value<=t.value:r.value{R_.init(s,t);const n=CLt[typeof t.value];s._zod.onattach.push(r=>{const a=r._zod.bag,i=(t.inclusive?a.minimum:a.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?a.minimum=t.value:a.exclusiveMinimum=t.value)}),s._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin: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})}}),Sjs=ua("$ZodCheckMultipleOf",(s,t)=>{R_.init(s,t),s._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),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"?n.value%t.value===BigInt(0):Cws(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})}}),Cjs=ua("$ZodCheckNumberFormat",(s,t)=>{var l;R_.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]=Pws[t.format];s._zod.onattach.push(o=>{const c=o._zod.bag;c.format=t.format,c.minimum=a,c.maximum=i,n&&(c.pattern=_js)}),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})}}),Ajs=ua("$ZodCheckMaxLength",(s,t)=>{var n;R_.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!lXe(a)&&a.length!==void 0}),s._zod.onattach.push(r=>{const a=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const a=r.value;if(a.length<=t.maximum)return;const l=dXe(a);r.issues.push({origin:l,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),Ejs=ua("$ZodCheckMinLength",(s,t)=>{var n;R_.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!lXe(a)&&a.length!==void 0}),s._zod.onattach.push(r=>{const a=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>a&&(r._zod.bag.minimum=t.minimum)}),s._zod.check=r=>{const a=r.value;if(a.length>=t.minimum)return;const l=dXe(a);r.issues.push({origin:l,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),Tjs=ua("$ZodCheckLengthEquals",(s,t)=>{var n;R_.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!lXe(a)&&a.length!==void 0}),s._zod.onattach.push(r=>{const a=r._zod.bag;a.minimum=t.length,a.maximum=t.length,a.length=t.length}),s._zod.check=r=>{const a=r.value,i=a.length;if(i===t.length)return;const l=dXe(a),o=i>t.length;r.issues.push({origin:l,...o?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:s,continue:!t.abort})}}),rMe=ua("$ZodCheckStringFormat",(s,t)=>{var n,r;R_.init(s,t),s._zod.onattach.push(a=>{const i=a._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),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=()=>{})}),Mjs=ua("$ZodCheckRegex",(s,t)=>{rMe.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})}}),Pjs=ua("$ZodCheckLowerCase",(s,t)=>{t.pattern??(t.pattern=Njs),rMe.init(s,t)}),Ljs=ua("$ZodCheckUpperCase",(s,t)=>{t.pattern??(t.pattern=kjs),rMe.init(s,t)}),Ijs=ua("$ZodCheckIncludes",(s,t)=>{R_.init(s,t);const n=FV(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,s._zod.onattach.push(a=>{const i=a._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(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})}}),Rjs=ua("$ZodCheckStartsWith",(s,t)=>{R_.init(s,t);const n=new RegExp(`^${FV(t.prefix)}.*`);t.pattern??(t.pattern=n),s._zod.onattach.push(r=>{const a=r._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(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})}}),Djs=ua("$ZodCheckEndsWith",(s,t)=>{R_.init(s,t);const n=new RegExp(`.*${FV(t.suffix)}$`);t.pattern??(t.pattern=n),s._zod.onattach.push(r=>{const a=r._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(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})}}),Ojs=ua("$ZodCheckOverwrite",(s,t)=>{R_.init(s,t),s._zod.check=n=>{n.value=t.tx(n.value)}});class Fjs{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),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.args,a=[...((this==null?void 0:this.content)??[""]).map(i=>` ${i}`)];return new t(...n,a.join(` `))}}const zjs={major:4,minor:4,patch:3},mg=ua("$ZodType",(s,t)=>{var a;var n;s??(s={}),s._zod.def=t,s._zod.bag=s._zod.bag||{},s._zod.version=zjs;const r=[...s._zod.def.checks??[]];s._zod.traits.has("$ZodCheck")&&r.unshift(s);for(const i of r)for(const l of i._zod.onattach)l(s);if(r.length===0)(n=s._zod).deferred??(n.deferred=[]),(a=s._zod.deferred)==null||a.push(()=>{s._zod.run=s._zod.parse});else{const i=(o,c,d)=>{let u=fU(o),h;for(const m of c){if(m._zod.def.when){if(Bws(o)||!m._zod.def.when(o))continue}else if(u)continue;const p=o.issues.length,f=m._zod.check(o);if(f instanceof Promise&&(d==null?void 0:d.async)===!1)throw new Rq;if(h||f instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await f,o.issues.length!==p&&(u||(u=fU(o,p)))});else{if(o.issues.length===p)continue;u||(u=fU(o,p))}}return h?h.then(()=>o):o},l=(o,c,d)=>{if(fU(o))return o.aborted=!0,o;const u=i(c,r,d);if(u instanceof Promise){if(d.async===!1)throw new Rq;return u.then(h=>s._zod.parse(h,d))}return s._zod.parse(u,d)};s._zod.run=(o,c)=>{if(c.skipChecks)return s._zod.parse(o,c);if(c.direction==="backward"){const u=s._zod.parse({value:o.value,issues:[]},{...c,skipChecks:!0});return u instanceof Promise?u.then(h=>l(h,o,c)):l(u,o,c)}const d=s._zod.parse(o,c);if(d instanceof Promise){if(c.async===!1)throw new Rq;return d.then(u=>i(u,r,c))}return i(d,r,c)}}Wh(s,"~standard",()=>({validate:i=>{var l;try{const o=$ws(s,i);return o.success?{value:o.data}:{issues:(l=o.error)==null?void 0:l.issues}}catch{return Vws(s,i).then(c=>{var d;return c.success?{value:c.data}:{issues:(d=c.error)==null?void 0:d.issues}})}},vendor:"zod",version:1}))}),mXe=ua("$ZodString",(s,t)=>{var n;mg.init(s,t),s._zod.pattern=[...((n=s==null?void 0:s._zod.bag)==null?void 0:n.patterns)??[]].pop()??bjs(s._zod.bag),s._zod.parse=(r,a)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:s}),r}}),qp=ua("$ZodStringFormat",(s,t)=>{rMe.init(s,t),mXe.init(s,t)}),Bjs=ua("$ZodGUID",(s,t)=>{t.pattern??(t.pattern=ijs),qp.init(s,t)}),Ujs=ua("$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=Aht(r))}else t.pattern??(t.pattern=Aht());qp.init(s,t)}),qjs=ua("$ZodEmail",(s,t)=>{t.pattern??(t.pattern=ojs),qp.init(s,t)}),$js=ua("$ZodURL",(s,t)=>{qp.init(s,t),s._zod.check=n=>{var r;try{const a=n.value.trim();if(!t.normalize&&((r=t.protocol)==null?void 0:r.source)===fjs.source&&!/^https?:\/\//i.test(a)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:s,continue:!t.abort});return}const i=new URL(a);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.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&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:s,continue:!t.abort})),t.normalize?n.value=i.href:n.value=a;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:s,continue:!t.abort})}}}),Vjs=ua("$ZodEmoji",(s,t)=>{t.pattern??(t.pattern=cjs()),qp.init(s,t)}),Hjs=ua("$ZodNanoID",(s,t)=>{t.pattern??(t.pattern=rjs),qp.init(s,t)}),Gjs=ua("$ZodCUID",(s,t)=>{t.pattern??(t.pattern=Jws),qp.init(s,t)}),Wjs=ua("$ZodCUID2",(s,t)=>{t.pattern??(t.pattern=ejs),qp.init(s,t)}),Kjs=ua("$ZodULID",(s,t)=>{t.pattern??(t.pattern=tjs),qp.init(s,t)}),Yjs=ua("$ZodXID",(s,t)=>{t.pattern??(t.pattern=sjs),qp.init(s,t)}),Zjs=ua("$ZodKSUID",(s,t)=>{t.pattern??(t.pattern=njs),qp.init(s,t)}),Xjs=ua("$ZodISODateTime",(s,t)=>{t.pattern??(t.pattern=vjs(t)),qp.init(s,t)}),Qjs=ua("$ZodISODate",(s,t)=>{t.pattern??(t.pattern=xjs),qp.init(s,t)}),Jjs=ua("$ZodISOTime",(s,t)=>{t.pattern??(t.pattern=yjs(t)),qp.init(s,t)}),e2s=ua("$ZodISODuration",(s,t)=>{t.pattern??(t.pattern=ajs),qp.init(s,t)}),t2s=ua("$ZodIPv4",(s,t)=>{t.pattern??(t.pattern=djs),qp.init(s,t),s._zod.bag.format="ipv4"}),s2s=ua("$ZodIPv6",(s,t)=>{t.pattern??(t.pattern=ujs),qp.init(s,t),s._zod.bag.format="ipv6",s._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:s,continue:!t.abort})}}}),n2s=ua("$ZodCIDRv4",(s,t)=>{t.pattern??(t.pattern=hjs),qp.init(s,t)}),r2s=ua("$ZodCIDRv6",(s,t)=>{t.pattern??(t.pattern=mjs),qp.init(s,t),s._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[a,i]=r;if(!i)throw new Error;const l=Number(i);if(`${l}`!==i)throw new Error;if(l<0||l>128)throw new Error;new URL(`http://[${a}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:s,continue:!t.abort})}}});function TLt(s){if(s==="")return!0;if(/\s/.test(s)||s.length%4!==0)return!1;try{return atob(s),!0}catch{return!1}}const a2s=ua("$ZodBase64",(s,t)=>{t.pattern??(t.pattern=pjs),qp.init(s,t),s._zod.bag.contentEncoding="base64",s._zod.check=n=>{TLt(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:s,continue:!t.abort})}});function i2s(s){if(!NLt.test(s))return!1;const t=s.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return TLt(n)}const o2s=ua("$ZodBase64URL",(s,t)=>{t.pattern??(t.pattern=NLt),qp.init(s,t),s._zod.bag.contentEncoding="base64url",s._zod.check=n=>{i2s(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:s,continue:!t.abort})}}),l2s=ua("$ZodE164",(s,t)=>{t.pattern??(t.pattern=gjs),qp.init(s,t)});function c2s(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 d2s=ua("$ZodJWT",(s,t)=>{qp.init(s,t),s._zod.check=n=>{c2s(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:s,continue:!t.abort})}}),MLt=ua("$ZodNumber",(s,t)=>{mg.init(s,t),s._zod.pattern=s._zod.bag.pattern??wjs,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:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:a,inst:s,...i?{received:i}:{}}),n}}),u2s=ua("$ZodNumberFormat",(s,t)=>{Cjs.init(s,t),MLt.init(s,t)}),h2s=ua("$ZodBoolean",(s,t)=>{mg.init(s,t),s._zod.pattern=jjs,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}}),m2s=ua("$ZodUnknown",(s,t)=>{mg.init(s,t),s._zod.parse=n=>n}),p2s=ua("$ZodNever",(s,t)=>{mg.init(s,t),s._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:s}),n)});function Eht(s,t,n){s.issues.length&&t.issues.push(...bLt(n,s.issues)),t.value[n]=s.value}const f2s=ua("$ZodArray",(s,t)=>{mg.init(s,t),s._zod.parse=(n,r)=>{const a=n.value;if(!Array.isArray(a))return n.issues.push({expected:"array",code:"invalid_type",input:a,inst:s}),n;n.value=Array(a.length);const i=[];for(let l=0;lEht(d,n,l))):Eht(c,n,l)}return i.length?Promise.all(i).then(()=>n):n}});function oCe(s,t,n,r,a,i){const l=n in r;if(s.issues.length){if(a&&i&&!l)return;t.issues.push(...bLt(n,s.issues))}if(!l&&!a){s.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}s.value===void 0?l&&(t.value[n]=void 0):t.value[n]=s.value}function PLt(s){var r,a,i,l;const t=Object.keys(s.shape);for(const o of t)if(!((l=(i=(a=(r=s.shape)==null?void 0:r[o])==null?void 0:a._zod)==null?void 0:i.traits)!=null&&l.has("$ZodType")))throw new Error(`Invalid element at key "${o}": expected a Zod schema`);const n=Mws(s.shape);return{...s,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function LLt(s,t,n,r,a,i){const l=[],o=a.keySet,c=a.catchall._zod,d=c.def.type,u=c.optin==="optional",h=c.optout==="optional";for(const m in t){if(m==="__proto__"||o.has(m))continue;if(d==="never"){l.push(m);continue}const p=c.run({value:t[m],issues:[]},r);p instanceof Promise?s.push(p.then(f=>oCe(f,n,m,t,u,h))):oCe(p,n,m,t,u,h)}return l.length&&n.issues.push({code:"unrecognized_keys",keys:l,input:t,inst:i}),s.length?Promise.all(s).then(()=>n):n}const g2s=ua("$ZodObject",(s,t)=>{mg.init(s,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!(n!=null&&n.get)){const o=t.shape;Object.defineProperty(t,"shape",{get:()=>{const c={...o};return Object.defineProperty(t,"shape",{value:c}),c}})}const r=oXe(()=>PLt(t));Wh(s._zod,"propValues",()=>{const o=t.shape,c={};for(const d in o){const u=o[d]._zod;if(u.values){c[d]??(c[d]=new Set);for(const h of u.values)c[d].add(h)}}return c});const a=iCe,i=t.catchall;let l;s._zod.parse=(o,c)=>{l??(l=r.value);const d=o.value;if(!a(d))return o.issues.push({expected:"object",code:"invalid_type",input:d,inst:s}),o;o.value={};const u=[],h=l.shape;for(const m of l.keys){const p=h[m],f=p._zod.optin==="optional",x=p._zod.optout==="optional",y=p._zod.run({value:d[m],issues:[]},c);y instanceof Promise?u.push(y.then(v=>oCe(v,o,m,d,f,x))):oCe(y,o,m,d,f,x)}return i?LLt(u,d,o,c,r.value,s):u.length?Promise.all(u).then(()=>o):o}}),x2s=ua("$ZodObjectJIT",(s,t)=>{g2s.init(s,t);const n=s._zod.parse,r=oXe(()=>PLt(t)),a=m=>{var N,S;const p=new Fjs(["shape","payload","ctx"]),f=r.value,x=A=>{const T=Cht(A);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};p.write("const input = payload.value;");const y=Object.create(null);let v=0;for(const A of f.keys)y[A]=`key_${v++}`;p.write("const newResult = {};");for(const A of f.keys){const T=y[A],L=Cht(A),M=m[A],I=((N=M==null?void 0:M._zod)==null?void 0:N.optin)==="optional",R=((S=M==null?void 0:M._zod)==null?void 0:S.optout)==="optional";p.write(`const ${T} = ${x(A)};`),I&&R?p.write(` if (${T}.issues.length) { if (${L} in input) { payload.issues = payload.issues.concat(${T}.issues.map(iss => ({ ...iss, path: iss.path ? [${L}, ...iss.path] : [${L}] }))); } } if (${T}.value === undefined) { if (${L} in input) { newResult[${L}] = undefined; } } else { newResult[${L}] = ${T}.value; } `):I?p.write(` if (${T}.issues.length) { payload.issues = payload.issues.concat(${T}.issues.map(iss => ({ ...iss, path: iss.path ? [${L}, ...iss.path] : [${L}] }))); } if (${T}.value === undefined) { if (${L} in input) { newResult[${L}] = undefined; } } else { newResult[${L}] = ${T}.value; } `):p.write(` const ${T}_present = ${L} in input; if (${T}.issues.length) { payload.issues = payload.issues.concat(${T}.issues.map(iss => ({ ...iss, path: iss.path ? [${L}, ...iss.path] : [${L}] }))); } if (!${T}_present && !${T}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${L}] }); } if (${T}_present) { if (${T}.value === undefined) { newResult[${L}] = undefined; } else { newResult[${L}] = ${T}.value; } } `)}p.write("payload.value = newResult;"),p.write("return payload;");const b=p.compile();return(A,T)=>b(m,A,T)};let i;const l=iCe,o=!iXe.jitless,d=o&&Ews.value,u=t.catchall;let h;s._zod.parse=(m,p)=>{h??(h=r.value);const f=m.value;return l(f)?o&&d&&(p==null?void 0:p.async)===!1&&p.jitless!==!0?(i||(i=a(t.shape)),m=i(m,p),u?LLt([],f,m,p,h,s):m):n(m,p):(m.issues.push({expected:"object",code:"invalid_type",input:f,inst:s}),m)}});function Tht(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=>!fU(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=>w7(l,r,_7())))}),t)}const y2s=ua("$ZodUnion",(s,t)=>{mg.init(s,t),Wh(s._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Wh(s._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Wh(s._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Wh(s._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(a=>a._zod.pattern);return new RegExp(`^(${r.map(a=>cXe(a.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=>Tht(o,r,s,a)):Tht(l,r,s,a)}}),v2s=ua("$ZodIntersection",(s,t)=>{mg.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])=>Mht(n,c,d)):Mht(n,i,l)}});function lqe(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(iee(s)&&iee(t)){const n=Object.keys(t),r=Object.keys(s).filter(i=>n.indexOf(i)!==-1),a={...s,...t};for(const i of r){const l=lqe(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;ro.l&&o.r).map(([o])=>o);if(i.length&&a&&s.issues.push({...a,keys:i}),fU(s))return s;const l=lqe(t.value,n.value);if(!l.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(l.mergeErrorPath)}`);return s.value=l.data,s}const b2s=ua("$ZodEnum",(s,t)=>{mg.init(s,t);const n=xLt(t.entries),r=new Set(n);s._zod.values=r,s._zod.pattern=new RegExp(`^(${n.filter(a=>Tws.has(typeof a)).map(a=>typeof a=="string"?FV(a):a.toString()).join("|")})$`),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}}),_2s=ua("$ZodLiteral",(s,t)=>{if(mg.init(s,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);s._zod.values=n,s._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?FV(r):r?FV(r.toString()):String(r)).join("|")})$`),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}}),w2s=ua("$ZodTransform",(s,t)=>{mg.init(s,t),s._zod.optin="optional",s._zod.parse=(n,r)=>{if(r.direction==="backward")throw new gLt(s.constructor.name);const a=t.transform(n.value,n);if(r.async)return(a instanceof Promise?a:Promise.resolve(a)).then(l=>(n.value=l,n.fallback=!0,n));if(a instanceof Promise)throw new Rq;return n.value=a,n.fallback=!0,n}});function Pht(s,t){return t===void 0&&(s.issues.length||s.fallback)?{issues:[],value:void 0}:s}const ILt=ua("$ZodOptional",(s,t)=>{mg.init(s,t),s._zod.optin="optional",s._zod.optout="optional",Wh(s._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Wh(s._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${cXe(n.source)})?$`):void 0}),s._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const a=n.value,i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>Pht(l,a)):Pht(i,a)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),j2s=ua("$ZodExactOptional",(s,t)=>{ILt.init(s,t),Wh(s._zod,"values",()=>t.innerType._zod.values),Wh(s._zod,"pattern",()=>t.innerType._zod.pattern),s._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),N2s=ua("$ZodNullable",(s,t)=>{mg.init(s,t),Wh(s._zod,"optin",()=>t.innerType._zod.optin),Wh(s._zod,"optout",()=>t.innerType._zod.optout),Wh(s._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${cXe(n.source)}|null)$`):void 0}),Wh(s._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),s._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),k2s=ua("$ZodDefault",(s,t)=>{mg.init(s,t),s._zod.optin="optional",Wh(s._zod,"values",()=>t.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=>Lht(i,t)):Lht(a,t)}});function Lht(s,t){return s.value===void 0&&(s.value=t.defaultValue),s}const S2s=ua("$ZodPrefault",(s,t)=>{mg.init(s,t),s._zod.optin="optional",Wh(s._zod,"values",()=>t.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))}),C2s=ua("$ZodNonOptional",(s,t)=>{mg.init(s,t),Wh(s._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),s._zod.parse=(n,r)=>{const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(i=>Iht(i,s)):Iht(a,s)}});function Iht(s,t){return!s.issues.length&&s.value===void 0&&s.issues.push({code:"invalid_type",expected:"nonoptional",input:s.value,inst:t}),s}const A2s=ua("$ZodCatch",(s,t)=>{mg.init(s,t),s._zod.optin="optional",Wh(s._zod,"optout",()=>t.innerType._zod.optout),Wh(s._zod,"values",()=>t.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(n,r);return a instanceof Promise?a.then(i=>(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(l=>w7(l,r,_7()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=a.value,a.issues.length&&(n.value=t.catchValue({...n,error:{issues:a.issues.map(i=>w7(i,r,_7()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),E2s=ua("$ZodPipe",(s,t)=>{mg.init(s,t),Wh(s._zod,"values",()=>t.in._zod.values),Wh(s._zod,"optin",()=>t.in._zod.optin),Wh(s._zod,"optout",()=>t.out._zod.optout),Wh(s._zod,"propValues",()=>t.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=>foe(l,t.in,r)):foe(i,t.in,r)}const a=t.in._zod.run(n,r);return a instanceof Promise?a.then(i=>foe(i,t.out,r)):foe(a,t.out,r)}});function foe(s,t,n){return s.issues.length?(s.aborted=!0,s):t._zod.run({value:s.value,issues:s.issues,fallback:s.fallback},n)}const T2s=ua("$ZodReadonly",(s,t)=>{mg.init(s,t),Wh(s._zod,"propValues",()=>t.innerType._zod.propValues),Wh(s._zod,"values",()=>t.innerType._zod.values),Wh(s._zod,"optin",()=>{var n,r;return(r=(n=t.innerType)==null?void 0:n._zod)==null?void 0:r.optin}),Wh(s._zod,"optout",()=>{var n,r;return(r=(n=t.innerType)==null?void 0:n._zod)==null?void 0:r.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(Rht):Rht(a)}});function Rht(s){return s.value=Object.freeze(s.value),s}const M2s=ua("$ZodCustom",(s,t)=>{R_.init(s,t),mg.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=>Dht(i,n,r,s));Dht(a,n,r,s)}});function Dht(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(oee(a))}}var Oht;class P2s{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 L2s(){return new P2s}(Oht=globalThis).__zod_globalRegistry??(Oht.__zod_globalRegistry=L2s());const xZ=globalThis.__zod_globalRegistry;function I2s(s,t){return new s({type:"string",...Zo(t)})}function R2s(s,t){return new s({type:"string",format:"email",check:"string_format",abort:!1,...Zo(t)})}function Fht(s,t){return new s({type:"string",format:"guid",check:"string_format",abort:!1,...Zo(t)})}function D2s(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,...Zo(t)})}function O2s(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Zo(t)})}function F2s(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Zo(t)})}function z2s(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Zo(t)})}function B2s(s,t){return new s({type:"string",format:"url",check:"string_format",abort:!1,...Zo(t)})}function U2s(s,t){return new s({type:"string",format:"emoji",check:"string_format",abort:!1,...Zo(t)})}function q2s(s,t){return new s({type:"string",format:"nanoid",check:"string_format",abort:!1,...Zo(t)})}function $2s(s,t){return new s({type:"string",format:"cuid",check:"string_format",abort:!1,...Zo(t)})}function V2s(s,t){return new s({type:"string",format:"cuid2",check:"string_format",abort:!1,...Zo(t)})}function H2s(s,t){return new s({type:"string",format:"ulid",check:"string_format",abort:!1,...Zo(t)})}function G2s(s,t){return new s({type:"string",format:"xid",check:"string_format",abort:!1,...Zo(t)})}function W2s(s,t){return new s({type:"string",format:"ksuid",check:"string_format",abort:!1,...Zo(t)})}function K2s(s,t){return new s({type:"string",format:"ipv4",check:"string_format",abort:!1,...Zo(t)})}function Y2s(s,t){return new s({type:"string",format:"ipv6",check:"string_format",abort:!1,...Zo(t)})}function Z2s(s,t){return new s({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Zo(t)})}function X2s(s,t){return new s({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Zo(t)})}function Q2s(s,t){return new s({type:"string",format:"base64",check:"string_format",abort:!1,...Zo(t)})}function J2s(s,t){return new s({type:"string",format:"base64url",check:"string_format",abort:!1,...Zo(t)})}function eNs(s,t){return new s({type:"string",format:"e164",check:"string_format",abort:!1,...Zo(t)})}function tNs(s,t){return new s({type:"string",format:"jwt",check:"string_format",abort:!1,...Zo(t)})}function sNs(s,t){return new s({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Zo(t)})}function nNs(s,t){return new s({type:"string",format:"date",check:"string_format",...Zo(t)})}function rNs(s,t){return new s({type:"string",format:"time",check:"string_format",precision:null,...Zo(t)})}function aNs(s,t){return new s({type:"string",format:"duration",check:"string_format",...Zo(t)})}function iNs(s,t){return new s({type:"number",checks:[],...Zo(t)})}function oNs(s,t){return new s({type:"number",check:"number_format",abort:!1,format:"safeint",...Zo(t)})}function lNs(s,t){return new s({type:"boolean",...Zo(t)})}function cNs(s){return new s({type:"unknown"})}function dNs(s,t){return new s({type:"never",...Zo(t)})}function zht(s,t){return new ALt({check:"less_than",...Zo(t),value:s,inclusive:!1})}function eOe(s,t){return new ALt({check:"less_than",...Zo(t),value:s,inclusive:!0})}function Bht(s,t){return new ELt({check:"greater_than",...Zo(t),value:s,inclusive:!1})}function tOe(s,t){return new ELt({check:"greater_than",...Zo(t),value:s,inclusive:!0})}function Uht(s,t){return new Sjs({check:"multiple_of",...Zo(t),value:s})}function RLt(s,t){return new Ajs({check:"max_length",...Zo(t),maximum:s})}function lCe(s,t){return new Ejs({check:"min_length",...Zo(t),minimum:s})}function DLt(s,t){return new Tjs({check:"length_equals",...Zo(t),length:s})}function uNs(s,t){return new Mjs({check:"string_format",format:"regex",...Zo(t),pattern:s})}function hNs(s){return new Pjs({check:"string_format",format:"lowercase",...Zo(s)})}function mNs(s){return new Ljs({check:"string_format",format:"uppercase",...Zo(s)})}function pNs(s,t){return new Ijs({check:"string_format",format:"includes",...Zo(t),includes:s})}function fNs(s,t){return new Rjs({check:"string_format",format:"starts_with",...Zo(t),prefix:s})}function gNs(s,t){return new Djs({check:"string_format",format:"ends_with",...Zo(t),suffix:s})}function fG(s){return new Ojs({check:"overwrite",tx:s})}function xNs(s){return fG(t=>t.normalize(s))}function yNs(){return fG(s=>s.trim())}function vNs(){return fG(s=>s.toLowerCase())}function bNs(){return fG(s=>s.toUpperCase())}function _Ns(){return fG(s=>Aws(s))}function wNs(s,t,n){return new s({type:"array",element:t,...Zo(n)})}function jNs(s,t,n){return new s({type:"custom",check:"custom",fn:t,...Zo(n)})}function NNs(s,t){const n=kNs(r=>(r.addIssue=a=>{if(typeof a=="string")r.issues.push(oee(a,r.value,n._zod.def));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=n),i.continue??(i.continue=!n._zod.def.abort),r.issues.push(oee(i))}},s(r.value,r)),t);return n}function kNs(s,t){const n=new R_({check:"custom",...Zo(t)});return n._zod.check=s,n}function OLt(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)??xZ,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,cycles:(s==null?void 0:s.cycles)??"ref",reused:(s==null?void 0:s.reused)??"inline",external:(s==null?void 0:s.external)??void 0}}function _v(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);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 f=l.schema,x=t.processors[a.type];if(!x)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${a.type}`);x(s,t,f,m)}const p=s._zod.parent;p&&(l.ref||(l.ref=p),_v(p,t,m),t.seen.get(p).isParent=!0)}const c=t.metadataRegistry.get(s);return c&&Object.assign(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 FLt(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.");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??(N=>N);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}/${b}`}}if(u[1]===n)return{ref:"#"};const p=`#/${h}/`,f=u[1].schema.id??`__schema${s.counter++}`;return{defId:f,ref:p+f}},i=u=>{if(u[1].schema.$ref)return;const h=u[1],{ref:m,defId:p}=a(u);h.def={...h.schema},p&&(h.defId=p);const f=h.schema;for(const x in f)delete f[x];f.$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 p=(c=s.external.registry.get(u[0]))==null?void 0:c.id;if(t!==u[0]&&p){i(u);continue}}if((d=s.metadataRegistry.get(u[0]))==null?void 0:d.id){i(u);continue}if(h.cycle){i(u);continue}if(h.count>1&&s.reused==="ref"){i(u);continue}}}function zLt(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 p=m.def??m.schema,f={...p},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")?(p.allOf=p.allOf??[],p.allOf.push(b)):Object.assign(p,b),Object.assign(p,f),h._zod.parent===x)for(const S in p)S==="$ref"||S==="allOf"||S in f||delete p[S];if(b.$ref&&v.def)for(const S in p)S==="$ref"||S==="allOf"||S in v.def&&JSON.stringify(p[S])===JSON.stringify(v.def[S])&&delete p[S]}const y=h._zod.parent;if(y&&y!==x){r(y);const v=s.seen.get(y);if(v!=null&&v.schema.$ref&&(p.$ref=v.schema.$ref,v.def))for(const b in p)b==="$ref"||b==="allOf"||b in v.def&&JSON.stringify(p[b])===JSON.stringify(v.def[b])&&delete p[b]}s.override({zodSchema:h,jsonSchema:p,path:m.path??[]})};for(const h of[...s.seen.entries()].reverse())r(h[0]);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)}Object.assign(a,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)??{};for(const h of s.seen.entries()){const m=h[1];m.def&&m.defId&&(m.def.id===m.defId&&delete m.def.id,l[m.defId]=m.def)}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:cCe(t,"input",s.processors),output:cCe(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")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 SNs=(s,t={})=>n=>{const r=OLt({...n,processors:t});return _v(s,r),FLt(r,s),zLt(r,s)},cCe=(s,t,n={})=>r=>{const{libraryOptions:a,target:i}=r??{},l=OLt({...a??{},target:i,io:t,processors:n});return _v(s,l),FLt(l,s),zLt(l,s)},CNs={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ANs=(s,t,n,r)=>{const a=n;a.type="string";const{minimum:i,maximum:l,format:o,patterns:c,contentEncoding:d}=s._zod.bag;if(typeof i=="number"&&(a.minLength=i),typeof l=="number"&&(a.maxLength=l),o&&(a.format=CNs[o]??o,a.format===""&&delete a.format,o==="time"&&delete a.format),d&&(a.contentEncoding=d),c&&c.size>0){const u=[...c];u.length===1?a.pattern=u[0].source:u.length>1&&(a.allOf=[...u.map(h=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:h.source}))])}},ENs=(s,t,n,r)=>{const a=n,{minimum:i,maximum:l,format:o,multipleOf:c,exclusiveMaximum:d,exclusiveMinimum:u}=s._zod.bag;typeof o=="string"&&o.includes("int")?a.type="integer":a.type="number";const h=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),m=typeof d=="number"&&d<=(l??Number.POSITIVE_INFINITY),p=t.target==="draft-04"||t.target==="openapi-3.0";h?p?(a.minimum=u,a.exclusiveMinimum=!0):a.exclusiveMinimum=u:typeof i=="number"&&(a.minimum=i),m?p?(a.maximum=d,a.exclusiveMaximum=!0):a.exclusiveMaximum=d:typeof l=="number"&&(a.maximum=l),typeof c=="number"&&(a.multipleOf=c)},TNs=(s,t,n,r)=>{n.type="boolean"},MNs=(s,t,n,r)=>{n.not={}},PNs=(s,t,n,r)=>{},LNs=(s,t,n,r)=>{const a=s._zod.def,i=xLt(a.entries);i.every(l=>typeof l=="number")&&(n.type="number"),i.every(l=>typeof l=="string")&&(n.type="string"),n.enum=i},INs=(s,t,n,r)=>{const a=s._zod.def,i=[];for(const l of a.values)if(l===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof l=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");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},RNs=(s,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},DNs=(s,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},ONs=(s,t,n,r)=>{const a=n,i=s._zod.def,{minimum:l,maximum:o}=s._zod.bag;typeof l=="number"&&(a.minItems=l),typeof o=="number"&&(a.maxItems=o),a.type="array",a.items=_v(i.element,t,{...r,path:[...r.path,"items"]})},FNs=(s,t,n,r)=>{var d;const a=n,i=s._zod.def;a.type="object",a.properties={};const l=i.shape;for(const u in l)a.properties[u]=_v(l[u],t,{...r,path:[...r.path,"properties",u]});const o=new Set(Object.keys(l)),c=new Set([...o].filter(u=>{const h=i.shape[u]._zod;return t.io==="input"?h.optin===void 0:h.optout===void 0}));c.size>0&&(a.required=Array.from(c)),((d=i.catchall)==null?void 0:d._zod.def.type)==="never"?a.additionalProperties=!1:i.catchall?i.catchall&&(a.additionalProperties=_v(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(a.additionalProperties=!1)},zNs=(s,t,n,r)=>{const a=s._zod.def,i=a.inclusive===!1,l=a.options.map((o,c)=>_v(o,t,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));i?n.oneOf=l:n.anyOf=l},BNs=(s,t,n,r)=>{const a=s._zod.def,i=_v(a.left,t,{...r,path:[...r.path,"allOf",0]}),l=_v(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},UNs=(s,t,n,r)=>{const a=s._zod.def,i=_v(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"}]},qNs=(s,t,n,r)=>{const a=s._zod.def;_v(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},$Ns=(s,t,n,r)=>{const a=s._zod.def;_v(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.default=JSON.parse(JSON.stringify(a.defaultValue))},VNs=(s,t,n,r)=>{const a=s._zod.def;_v(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(a.defaultValue)))},HNs=(s,t,n,r)=>{const a=s._zod.def;_v(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType;let l;try{l=a.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=l},GNs=(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;_v(l,t,r);const o=t.seen.get(s);o.ref=l},WNs=(s,t,n,r)=>{const a=s._zod.def;_v(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.readOnly=!0},BLt=(s,t,n,r)=>{const a=s._zod.def;_v(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},KNs=ua("ZodISODateTime",(s,t)=>{Xjs.init(s,t),Pf.init(s,t)});function YNs(s){return sNs(KNs,s)}const ZNs=ua("ZodISODate",(s,t)=>{Qjs.init(s,t),Pf.init(s,t)});function XNs(s){return nNs(ZNs,s)}const QNs=ua("ZodISOTime",(s,t)=>{Jjs.init(s,t),Pf.init(s,t)});function JNs(s){return rNs(QNs,s)}const eks=ua("ZodISODuration",(s,t)=>{e2s.init(s,t),Pf.init(s,t)});function tks(s){return aNs(eks,s)}const ULt=(s,t)=>{wLt.init(s,t),s.name="ZodError",Object.defineProperties(s,{format:{value:n=>qws(s,n)},flatten:{value:n=>Uws(s,n)},addIssue:{value:n=>{s.issues.push(n),s.message=JSON.stringify(s.issues,oqe,2)}},addIssues:{value:n=>{s.issues.push(...n),s.message=JSON.stringify(s.issues,oqe,2)}},isEmpty:{get(){return s.issues.length===0}}})},sks=ua("ZodError",ULt),NN=ua("ZodError",ULt,{Parent:Error}),nks=uXe(NN),rks=hXe(NN),aks=sMe(NN),iks=nMe(NN),oks=Hws(NN),lks=Gws(NN),cks=Wws(NN),dks=Kws(NN),uks=Yws(NN),hks=Zws(NN),mks=Xws(NN),pks=Qws(NN),qht=new WeakMap;function Gne(s,t,n){const r=Object.getPrototypeOf(s);let a=qht.get(r);if(a||(a=new Set,qht.set(r,a)),!a.has(t)){a.add(t);for(const i in n){const l=n[i];Object.defineProperty(r,i,{configurable:!0,enumerable:!1,get(){const o=l.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:o}),o},set(o){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:o})}})}}}const pg=ua("ZodType",(s,t)=>(mg.init(s,t),Object.assign(s["~standard"],{jsonSchema:{input:cCe(s,"input"),output:cCe(s,"output")}}),s.toJSONSchema=SNs(s,{}),s.def=t,s.type=t.type,Object.defineProperty(s,"_def",{value:t}),s.parse=(n,r)=>nks(s,n,r,{callee:s.parse}),s.safeParse=(n,r)=>aks(s,n,r),s.parseAsync=async(n,r)=>rks(s,n,r,{callee:s.parseAsync}),s.safeParseAsync=async(n,r)=>iks(s,n,r),s.spa=s.safeParseAsync,s.encode=(n,r)=>oks(s,n,r),s.decode=(n,r)=>lks(s,n,r),s.encodeAsync=async(n,r)=>cks(s,n,r),s.decodeAsync=async(n,r)=>dks(s,n,r),s.safeEncode=(n,r)=>uks(s,n,r),s.safeDecode=(n,r)=>hks(s,n,r),s.safeEncodeAsync=async(n,r)=>mks(s,n,r),s.safeDecodeAsync=async(n,r)=>pks(s,n,r),Gne(s,"ZodType",{check(...n){const r=this.def;return this.clone(OP(r,{checks:[...r.checks??[],...n.map(a=>typeof a=="function"?{_zod:{check:a,def:{check:"custom"},onattach:[]}}:a)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return FP(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(cSs(n,r))},superRefine(n,r){return this.check(dSs(n,r))},overwrite(n){return this.check(fG(n))},optional(){return Ght(this)},exactOptional(){return Zks(this)},nullable(){return Wht(this)},nullish(){return Ght(Wht(this))},nonoptional(n){return sSs(this,n)},array(){return Bks(this)},or(n){return $ks([this,n])},and(n){return Hks(this,n)},transform(n){return Kht(this,Kks(n))},default(n){return Jks(this,n)},prefault(n){return tSs(this,n)},catch(n){return rSs(this,n)},pipe(n){return Kht(this,n)},readonly(){return oSs(this)},describe(n){const r=this.clone();return xZ.add(r,{description:n}),r},meta(...n){if(n.length===0)return xZ.get(this);const r=this.clone();return xZ.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(s,"description",{get(){var n;return(n=xZ.get(s))==null?void 0:n.description},configurable:!0}),s)),qLt=ua("_ZodString",(s,t)=>{mXe.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(r,a,i)=>ANs(s,r,a);const n=s._zod.bag;s.format=n.format??null,s.minLength=n.minimum??null,s.maxLength=n.maximum??null,Gne(s,"_ZodString",{regex(...r){return this.check(uNs(...r))},includes(...r){return this.check(pNs(...r))},startsWith(...r){return this.check(fNs(...r))},endsWith(...r){return this.check(gNs(...r))},min(...r){return this.check(lCe(...r))},max(...r){return this.check(RLt(...r))},length(...r){return this.check(DLt(...r))},nonempty(...r){return this.check(lCe(1,...r))},lowercase(r){return this.check(hNs(r))},uppercase(r){return this.check(mNs(r))},trim(){return this.check(yNs())},normalize(...r){return this.check(xNs(...r))},toLowerCase(){return this.check(vNs())},toUpperCase(){return this.check(bNs())},slugify(){return this.check(_Ns())}})}),fks=ua("ZodString",(s,t)=>{mXe.init(s,t),qLt.init(s,t),s.email=n=>s.check(R2s(gks,n)),s.url=n=>s.check(B2s(xks,n)),s.jwt=n=>s.check(tNs(Pks,n)),s.emoji=n=>s.check(U2s(yks,n)),s.guid=n=>s.check(Fht($ht,n)),s.uuid=n=>s.check(D2s(goe,n)),s.uuidv4=n=>s.check(O2s(goe,n)),s.uuidv6=n=>s.check(F2s(goe,n)),s.uuidv7=n=>s.check(z2s(goe,n)),s.nanoid=n=>s.check(q2s(vks,n)),s.guid=n=>s.check(Fht($ht,n)),s.cuid=n=>s.check($2s(bks,n)),s.cuid2=n=>s.check(V2s(_ks,n)),s.ulid=n=>s.check(H2s(wks,n)),s.base64=n=>s.check(Q2s(Eks,n)),s.base64url=n=>s.check(J2s(Tks,n)),s.xid=n=>s.check(G2s(jks,n)),s.ksuid=n=>s.check(W2s(Nks,n)),s.ipv4=n=>s.check(K2s(kks,n)),s.ipv6=n=>s.check(Y2s(Sks,n)),s.cidrv4=n=>s.check(Z2s(Cks,n)),s.cidrv6=n=>s.check(X2s(Aks,n)),s.e164=n=>s.check(eNs(Mks,n)),s.datetime=n=>s.check(YNs(n)),s.date=n=>s.check(XNs(n)),s.time=n=>s.check(JNs(n)),s.duration=n=>s.check(tks(n))});function sl(s){return I2s(fks,s)}const Pf=ua("ZodStringFormat",(s,t)=>{qp.init(s,t),qLt.init(s,t)}),gks=ua("ZodEmail",(s,t)=>{qjs.init(s,t),Pf.init(s,t)}),$ht=ua("ZodGUID",(s,t)=>{Bjs.init(s,t),Pf.init(s,t)}),goe=ua("ZodUUID",(s,t)=>{Ujs.init(s,t),Pf.init(s,t)}),xks=ua("ZodURL",(s,t)=>{$js.init(s,t),Pf.init(s,t)}),yks=ua("ZodEmoji",(s,t)=>{Vjs.init(s,t),Pf.init(s,t)}),vks=ua("ZodNanoID",(s,t)=>{Hjs.init(s,t),Pf.init(s,t)}),bks=ua("ZodCUID",(s,t)=>{Gjs.init(s,t),Pf.init(s,t)}),_ks=ua("ZodCUID2",(s,t)=>{Wjs.init(s,t),Pf.init(s,t)}),wks=ua("ZodULID",(s,t)=>{Kjs.init(s,t),Pf.init(s,t)}),jks=ua("ZodXID",(s,t)=>{Yjs.init(s,t),Pf.init(s,t)}),Nks=ua("ZodKSUID",(s,t)=>{Zjs.init(s,t),Pf.init(s,t)}),kks=ua("ZodIPv4",(s,t)=>{t2s.init(s,t),Pf.init(s,t)}),Sks=ua("ZodIPv6",(s,t)=>{s2s.init(s,t),Pf.init(s,t)}),Cks=ua("ZodCIDRv4",(s,t)=>{n2s.init(s,t),Pf.init(s,t)}),Aks=ua("ZodCIDRv6",(s,t)=>{r2s.init(s,t),Pf.init(s,t)}),Eks=ua("ZodBase64",(s,t)=>{a2s.init(s,t),Pf.init(s,t)}),Tks=ua("ZodBase64URL",(s,t)=>{o2s.init(s,t),Pf.init(s,t)}),Mks=ua("ZodE164",(s,t)=>{l2s.init(s,t),Pf.init(s,t)}),Pks=ua("ZodJWT",(s,t)=>{d2s.init(s,t),Pf.init(s,t)}),$Lt=ua("ZodNumber",(s,t)=>{MLt.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(r,a,i)=>ENs(s,r,a),Gne(s,"ZodNumber",{gt(r,a){return this.check(Bht(r,a))},gte(r,a){return this.check(tOe(r,a))},min(r,a){return this.check(tOe(r,a))},lt(r,a){return this.check(zht(r,a))},lte(r,a){return this.check(eOe(r,a))},max(r,a){return this.check(eOe(r,a))},int(r){return this.check(Vht(r))},safe(r){return this.check(Vht(r))},positive(r){return this.check(Bht(0,r))},nonnegative(r){return this.check(tOe(0,r))},negative(r){return this.check(zht(0,r))},nonpositive(r){return this.check(eOe(0,r))},multipleOf(r,a){return this.check(Uht(r,a))},step(r,a){return this.check(Uht(r,a))},finite(){return this}});const n=s._zod.bag;s.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,s.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,s.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),s.isFinite=!0,s.format=n.format??null});function NQ(s){return iNs($Lt,s)}const Lks=ua("ZodNumberFormat",(s,t)=>{u2s.init(s,t),$Lt.init(s,t)});function Vht(s){return oNs(Lks,s)}const Iks=ua("ZodBoolean",(s,t)=>{h2s.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>TNs(s,n,r)});function Rks(s){return lNs(Iks,s)}const Dks=ua("ZodUnknown",(s,t)=>{m2s.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>PNs()});function Hht(){return cNs(Dks)}const Oks=ua("ZodNever",(s,t)=>{p2s.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>MNs(s,n,r)});function Fks(s){return dNs(Oks,s)}const zks=ua("ZodArray",(s,t)=>{f2s.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>ONs(s,n,r,a),s.element=t.element,Gne(s,"ZodArray",{min(n,r){return this.check(lCe(n,r))},nonempty(n){return this.check(lCe(1,n))},max(n,r){return this.check(RLt(n,r))},length(n,r){return this.check(DLt(n,r))},unwrap(){return this.element}})});function Bks(s,t){return wNs(zks,s,t)}const Uks=ua("ZodObject",(s,t)=>{x2s.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>FNs(s,n,r,a),Wh(s,"shape",()=>t.shape),Gne(s,"ZodObject",{keyof(){return pXe(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Hht()})},loose(){return this.clone({...this._zod.def,catchall:Hht()})},strict(){return this.clone({...this._zod.def,catchall:Fks()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return Rws(this,n)},safeExtend(n){return Dws(this,n)},merge(n){return Ows(this,n)},pick(n){return Lws(this,n)},omit(n){return Iws(this,n)},partial(...n){return Fws(VLt,this,n[0])},required(...n){return zws(HLt,this,n[0])}})});function kN(s,t){const n={type:"object",shape:s??{},...Zo(t)};return new Uks(n)}const qks=ua("ZodUnion",(s,t)=>{y2s.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>zNs(s,n,r,a),s.options=t.options});function $ks(s,t){return new qks({type:"union",options:s,...Zo(t)})}const Vks=ua("ZodIntersection",(s,t)=>{v2s.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>BNs(s,n,r,a)});function Hks(s,t){return new Vks({type:"intersection",left:s,right:t})}const cqe=ua("ZodEnum",(s,t)=>{b2s.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(r,a,i)=>LNs(s,r,a),s.enum=t.entries,s.options=Object.values(t.entries);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 cqe({...t,checks:[],...Zo(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 cqe({...t,checks:[],...Zo(a),entries:i})}});function pXe(s,t){const n=Array.isArray(s)?Object.fromEntries(s.map(r=>[r,r])):s;return new cqe({type:"enum",entries:n,...Zo(t)})}const Gks=ua("ZodLiteral",(s,t)=>{_2s.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>INs(s,n,r),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 ux(s,t){return new Gks({type:"literal",values:Array.isArray(s)?s:[s],...Zo(t)})}const Wks=ua("ZodTransform",(s,t)=>{w2s.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>DNs(s,n),s._zod.parse=(n,r)=>{if(r.direction==="backward")throw new gLt(s.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(oee(i,n.value,t));else{const l=i;l.fatal&&(l.continue=!1),l.code??(l.code="custom"),l.input??(l.input=n.value),l.inst??(l.inst=s),n.issues.push(oee(l))}};const a=t.transform(n.value,n);return a instanceof Promise?a.then(i=>(n.value=i,n.fallback=!0,n)):(n.value=a,n.fallback=!0,n)}});function Kks(s){return new Wks({type:"transform",transform:s})}const VLt=ua("ZodOptional",(s,t)=>{ILt.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>BLt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Ght(s){return new VLt({type:"optional",innerType:s})}const Yks=ua("ZodExactOptional",(s,t)=>{j2s.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>BLt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Zks(s){return new Yks({type:"optional",innerType:s})}const Xks=ua("ZodNullable",(s,t)=>{N2s.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>UNs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Wht(s){return new Xks({type:"nullable",innerType:s})}const Qks=ua("ZodDefault",(s,t)=>{k2s.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>$Ns(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeDefault=s.unwrap});function Jks(s,t){return new Qks({type:"default",innerType:s,get defaultValue(){return typeof t=="function"?t():vLt(t)}})}const eSs=ua("ZodPrefault",(s,t)=>{S2s.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>VNs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function tSs(s,t){return new eSs({type:"prefault",innerType:s,get defaultValue(){return typeof t=="function"?t():vLt(t)}})}const HLt=ua("ZodNonOptional",(s,t)=>{C2s.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>qNs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function sSs(s,t){return new HLt({type:"nonoptional",innerType:s,...Zo(t)})}const nSs=ua("ZodCatch",(s,t)=>{A2s.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>HNs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeCatch=s.unwrap});function rSs(s,t){return new nSs({type:"catch",innerType:s,catchValue:typeof t=="function"?t:()=>t})}const aSs=ua("ZodPipe",(s,t)=>{E2s.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>GNs(s,n,r,a),s.in=t.in,s.out=t.out});function Kht(s,t){return new aSs({type:"pipe",in:s,out:t})}const iSs=ua("ZodReadonly",(s,t)=>{T2s.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>WNs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function oSs(s){return new iSs({type:"readonly",innerType:s})}const lSs=ua("ZodCustom",(s,t)=>{M2s.init(s,t),pg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>RNs(s,n)});function cSs(s,t={}){return jNs(lSs,s,t)}function dSs(s,t){return NNs(s,t)}var uSs="Label",GLt=j.forwardRef((s,t)=>e.jsx(si.label,{...s,ref:t,onMouseDown:n=>{var a;n.target.closest("button, input, select, textarea")||((a=s.onMouseDown)==null||a.call(s,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));GLt.displayName=uSs;var WLt=GLt;const hSs=u9("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),te=j.forwardRef(({className:s,...t},n)=>e.jsx(WLt,{ref:n,className:Mt(hSs(),s),...t}));te.displayName=WLt.displayName;const aMe=iws,KLt=j.createContext({}),hf=({...s})=>e.jsx(KLt.Provider,{value:{name:s.name},children:e.jsx(dws,{...s})}),iMe=()=>{const s=j.useContext(KLt),t=j.useContext(YLt),{getFieldState:n,formState:r}=J6e(),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}},YLt=j.createContext({}),Pp=j.forwardRef(({className:s,...t},n)=>{const r=j.useId();return e.jsx(YLt.Provider,{value:{id:r},children:e.jsx("div",{ref:n,className:Mt("space-y-2",s),...t})})});Pp.displayName="FormItem";const Lp=j.forwardRef(({className:s,...t},n)=>{const{error:r,formItemId:a}=iMe();return e.jsx(te,{ref:n,className:Mt(r&&"text-destructive",s),htmlFor:a,...t})});Lp.displayName="FormLabel";const Ip=j.forwardRef(({...s},t)=>{const{error:n,formItemId:r,formDescriptionId:a,formMessageId:i}=iMe();return e.jsx(lZe,{ref:t,id:r,"aria-describedby":n?`${a} ${i}`:`${a}`,"aria-invalid":!!n,...s})});Ip.displayName="FormControl";const w5e=j.forwardRef(({className:s,...t},n)=>{const{formDescriptionId:r}=iMe();return e.jsx("p",{ref:n,id:r,className:Mt("text-sm text-muted-foreground",s),...t})});w5e.displayName="FormDescription";const J1=j.forwardRef(({className:s,children:t,...n},r)=>{const{error:a,formMessageId:i}=iMe(),l=a?String(a==null?void 0:a.message):t;return l?e.jsx("p",{ref:r,id:i,className:Mt("text-sm font-medium text-destructive",s),...n,children:l}):null});J1.displayName="FormMessage";const xe=j.forwardRef(({className:s,type:t,...n},r)=>e.jsx("input",{type:t,className:Mt("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}));xe.displayName="Input";function Wne(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])}var mSs=[" ","Enter","ArrowUp","ArrowDown"],pSs=[" ","Enter"],j7="Select",[oMe,lMe,fSs]=tG(j7),[gG,mgr]=Up(j7,[fSs,o3]),cMe=o3(),[gSs,zP]=gG(j7),[xSs,ySs]=gG(j7),ZLt=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:p,form:f}=s,x=cMe(t),[y,v]=j.useState(null),[b,N]=j.useState(null),[S,A]=j.useState(!1),T=xE(d),[L,M]=Sx({prop:r,defaultProp:a??!1,onChange:i,caller:j7}),[I,R]=Sx({prop:l,defaultProp:o,onChange:c,caller:j7}),z=j.useRef(null),$=y?f||!!y.closest("form"):!0,[H,V]=j.useState(new Set),K=Array.from(H).map(Z=>Z.props.value).join(";");return e.jsx(Pne,{...x,children:e.jsxs(gSs,{required:p,scope:t,trigger:y,onTriggerChange:v,valueNode:b,onValueNodeChange:N,valueNodeHasChildren:S,onValueNodeHasChildrenChange:A,contentId:jx(),value:I,onValueChange:R,open:L,onOpenChange:M,dir:T,triggerPointerDownPosRef:z,disabled:m,children:[e.jsx(oMe.Provider,{scope:t,children:e.jsx(xSs,{scope:s.__scopeSelect,onNativeOptionAdd:j.useCallback(Z=>{V(Q=>new Set(Q).add(Z))},[]),onNativeOptionRemove:j.useCallback(Z=>{V(Q=>{const le=new Set(Q);return le.delete(Z),le})},[]),children:n})}),$?e.jsxs(_It,{"aria-hidden":!0,required:p,tabIndex:-1,name:u,autoComplete:h,value:I,onChange:Z=>R(Z.target.value),disabled:m,form:f,children:[I===void 0?e.jsx("option",{value:""}):null,Array.from(H)]},K):null]})})};ZLt.displayName=j7;var XLt="SelectTrigger",QLt=j.forwardRef((s,t)=>{const{__scopeSelect:n,disabled:r=!1,...a}=s,i=cMe(n),l=zP(XLt,n),o=l.disabled||r,c=Uo(t,l.onTriggerChange),d=lMe(n),u=j.useRef("touch"),[h,m,p]=jIt(x=>{const y=d().filter(N=>!N.disabled),v=y.find(N=>N.value===l.value),b=NIt(y,x,v);b!==void 0&&l.onValueChange(b.value)}),f=x=>{o||(l.onOpenChange(!0),p()),x&&(l.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)})};return e.jsx(lG,{asChild:!0,...i,children:e.jsx(si.button,{type:"button",role:"combobox","aria-controls":l.contentId,"aria-expanded":l.open,"aria-required":l.required,"aria-autocomplete":"none",dir:l.dir,"data-state":l.open?"open":"closed",disabled:o,"data-disabled":o?"":void 0,"data-placeholder":wIt(l.value)?"":void 0,...a,ref:c,onClick:va(a.onClick,x=>{x.currentTarget.focus(),u.current!=="mouse"&&f(x)}),onPointerDown:va(a.onPointerDown,x=>{u.current=x.pointerType;const y=x.target;y.hasPointerCapture(x.pointerId)&&y.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&x.pointerType==="mouse"&&(f(x),x.preventDefault())}),onKeyDown:va(a.onKeyDown,x=>{const y=h.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&m(x.key),!(y&&x.key===" ")&&mSs.includes(x.key)&&(f(),x.preventDefault())})})})});QLt.displayName=XLt;var JLt="SelectValue",eIt=j.forwardRef((s,t)=>{const{__scopeSelect:n,className:r,style:a,children:i,placeholder:l="",...o}=s,c=zP(JLt,n),{onValueNodeHasChildrenChange:d}=c,u=i!==void 0,h=Uo(t,c.onValueNodeChange);return dg(()=>{d(u)},[d,u]),e.jsx(si.span,{...o,ref:h,style:{pointerEvents:"none"},children:wIt(c.value)?e.jsx(e.Fragment,{children:l}):i})});eIt.displayName=JLt;var vSs="SelectIcon",tIt=j.forwardRef((s,t)=>{const{__scopeSelect:n,children:r,...a}=s;return e.jsx(si.span,{"aria-hidden":!0,...a,ref:t,children:r||"▼"})});tIt.displayName=vSs;var bSs="SelectPortal",sIt=s=>e.jsx(sG,{asChild:!0,...s});sIt.displayName=bSs;var N7="SelectContent",nIt=j.forwardRef((s,t)=>{const n=zP(N7,s.__scopeSelect),[r,a]=j.useState();if(dg(()=>{a(new DocumentFragment)},[]),!n.open){const i=r;return i?tv.createPortal(e.jsx(rIt,{scope:s.__scopeSelect,children:e.jsx(oMe.Slot,{scope:s.__scopeSelect,children:e.jsx("div",{children:s.children})})}),i):null}return e.jsx(aIt,{...s,ref:t})});nIt.displayName=N7;var lk=10,[rIt,BP]=gG(N7),_Ss="SelectContentImpl",wSs=rP("SelectContent.RemoveScroll"),aIt=j.forwardRef((s,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:a,onEscapeKeyDown:i,onPointerDownOutside:l,side:o,sideOffset:c,align:d,alignOffset:u,arrowPadding:h,collisionBoundary:m,collisionPadding:p,sticky:f,hideWhenDetached:x,avoidCollisions:y,...v}=s,b=zP(N7,n),[N,S]=j.useState(null),[A,T]=j.useState(null),L=Uo(t,ge=>S(ge)),[M,I]=j.useState(null),[R,z]=j.useState(null),$=lMe(n),[H,V]=j.useState(!1),K=j.useRef(!1);j.useEffect(()=>{if(N)return j6e(N)},[N]),_6e();const Z=j.useCallback(ge=>{const[ke,...Te]=$().map(Se=>Se.ref.current),[Me]=Te.slice(-1),Oe=document.activeElement;for(const Se of ge)if(Se===Oe||(Se==null||Se.scrollIntoView({block:"nearest"}),Se===ke&&A&&(A.scrollTop=0),Se===Me&&A&&(A.scrollTop=A.scrollHeight),Se==null||Se.focus(),document.activeElement!==Oe))return},[$,A]),Q=j.useCallback(()=>Z([M,N]),[Z,M,N]);j.useEffect(()=>{H&&Q()},[H,Q]);const{onOpenChange:le,triggerPointerDownPosRef:ue}=b;j.useEffect(()=>{if(N){let ge={x:0,y:0};const ke=Me=>{var Oe,Se;ge={x:Math.abs(Math.round(Me.pageX)-(((Oe=ue.current)==null?void 0:Oe.x)??0)),y:Math.abs(Math.round(Me.pageY)-(((Se=ue.current)==null?void 0:Se.y)??0))}},Te=Me=>{ge.x<=10&&ge.y<=10?Me.preventDefault():N.contains(Me.target)||le(!1),document.removeEventListener("pointermove",ke),ue.current=null};return ue.current!==null&&(document.addEventListener("pointermove",ke),document.addEventListener("pointerup",Te,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",ke),document.removeEventListener("pointerup",Te,{capture:!0})}}},[N,le,ue]),j.useEffect(()=>{const ge=()=>le(!1);return window.addEventListener("blur",ge),window.addEventListener("resize",ge),()=>{window.removeEventListener("blur",ge),window.removeEventListener("resize",ge)}},[le]);const[se,ne]=jIt(ge=>{const ke=$().filter(Oe=>!Oe.disabled),Te=ke.find(Oe=>Oe.ref.current===document.activeElement),Me=NIt(ke,ge,Te);Me&&setTimeout(()=>Me.ref.current.focus())}),ie=j.useCallback((ge,ke,Te)=>{const Me=!K.current&&!Te;(b.value!==void 0&&b.value===ke||Me)&&(I(ge),Me&&(K.current=!0))},[b.value]),ce=j.useCallback(()=>N==null?void 0:N.focus(),[N]),je=j.useCallback((ge,ke,Te)=>{const Me=!K.current&&!Te;(b.value!==void 0&&b.value===ke||Me)&&z(ge)},[b.value]),be=r==="popper"?dqe:iIt,he=be===dqe?{side:o,sideOffset:c,align:d,alignOffset:u,arrowPadding:h,collisionBoundary:m,collisionPadding:p,sticky:f,hideWhenDetached:x,avoidCollisions:y}:{};return e.jsx(rIt,{scope:n,content:N,viewport:A,onViewportChange:T,itemRefCallback:ie,selectedItem:M,onItemLeave:ce,itemTextRefCallback:je,focusSelectedItem:Q,selectedItemText:R,position:r,isPositioned:H,searchRef:se,children:e.jsx(Sne,{as:wSs,allowPinchZoom:!0,children:e.jsx(kne,{asChild:!0,trapped:b.open,onMountAutoFocus:ge=>{ge.preventDefault()},onUnmountAutoFocus:va(a,ge=>{var ke;(ke=b.trigger)==null||ke.focus({preventScroll:!0}),ge.preventDefault()}),children:e.jsx(IP,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:ge=>ge.preventDefault(),onDismiss:()=>b.onOpenChange(!1),children:e.jsx(be,{role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:ge=>ge.preventDefault(),...v,...he,onPlaced:()=>V(!0),ref:L,style:{display:"flex",flexDirection:"column",outline:"none",...v.style},onKeyDown:va(v.onKeyDown,ge=>{const ke=ge.ctrlKey||ge.altKey||ge.metaKey;if(ge.key==="Tab"&&ge.preventDefault(),!ke&&ge.key.length===1&&ne(ge.key),["ArrowUp","ArrowDown","Home","End"].includes(ge.key)){let Me=$().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);if(["ArrowUp","End"].includes(ge.key)&&(Me=Me.slice().reverse()),["ArrowUp","ArrowDown"].includes(ge.key)){const Oe=ge.target,Se=Me.indexOf(Oe);Me=Me.slice(Se+1)}setTimeout(()=>Z(Me)),ge.preventDefault()}})})})})})})});aIt.displayName=_Ss;var jSs="SelectItemAlignedPosition",iIt=j.forwardRef((s,t)=>{const{__scopeSelect:n,onPlaced:r,...a}=s,i=zP(N7,n),l=BP(N7,n),[o,c]=j.useState(null),[d,u]=j.useState(null),h=Uo(t,L=>u(L)),m=lMe(n),p=j.useRef(!1),f=j.useRef(!0),{viewport:x,selectedItem:y,selectedItemText:v,focusSelectedItem:b}=l,N=j.useCallback(()=>{if(i.trigger&&i.valueNode&&o&&d&&x&&y&&v){const L=i.trigger.getBoundingClientRect(),M=d.getBoundingClientRect(),I=i.valueNode.getBoundingClientRect(),R=v.getBoundingClientRect();if(i.dir!=="rtl"){const Oe=R.left-M.left,Se=I.left-Oe,Qe=L.left-Se,Ae=L.width+Qe,Fe=Math.max(Ae,M.width),Ne=window.innerWidth-lk,$e=aee(Se,[lk,Math.max(lk,Ne-Fe)]);o.style.minWidth=Ae+"px",o.style.left=$e+"px"}else{const Oe=M.right-R.right,Se=window.innerWidth-I.right-Oe,Qe=window.innerWidth-L.right-Se,Ae=L.width+Qe,Fe=Math.max(Ae,M.width),Ne=window.innerWidth-lk,$e=aee(Se,[lk,Math.max(lk,Ne-Fe)]);o.style.minWidth=Ae+"px",o.style.right=$e+"px"}const z=m(),$=window.innerHeight-lk*2,H=x.scrollHeight,V=window.getComputedStyle(d),K=parseInt(V.borderTopWidth,10),Z=parseInt(V.paddingTop,10),Q=parseInt(V.borderBottomWidth,10),le=parseInt(V.paddingBottom,10),ue=K+Z+H+le+Q,se=Math.min(y.offsetHeight*5,ue),ne=window.getComputedStyle(x),ie=parseInt(ne.paddingTop,10),ce=parseInt(ne.paddingBottom,10),je=L.top+L.height/2-lk,be=$-je,he=y.offsetHeight/2,ge=y.offsetTop+he,ke=K+Z+ge,Te=ue-ke;if(ke<=je){const Oe=z.length>0&&y===z[z.length-1].ref.current;o.style.bottom="0px";const Se=d.clientHeight-x.offsetTop-x.offsetHeight,Qe=Math.max(be,he+(Oe?ce:0)+Se+Q),Ae=ke+Qe;o.style.height=Ae+"px"}else{const Oe=z.length>0&&y===z[0].ref.current;o.style.top="0px";const Qe=Math.max(je,K+x.offsetTop+(Oe?ie:0)+he)+Te;o.style.height=Qe+"px",x.scrollTop=ke-je+x.offsetTop}o.style.margin=`${lk}px 0`,o.style.minHeight=se+"px",o.style.maxHeight=$+"px",r==null||r(),requestAnimationFrame(()=>p.current=!0)}},[m,i.trigger,i.valueNode,o,d,x,y,v,i.dir,r]);dg(()=>N(),[N]);const[S,A]=j.useState();dg(()=>{d&&A(window.getComputedStyle(d).zIndex)},[d]);const T=j.useCallback(L=>{L&&f.current===!0&&(N(),b==null||b(),f.current=!1)},[N,b]);return e.jsx(kSs,{scope:n,contentWrapper:o,shouldExpandOnScrollRef:p,onScrollButtonChange:T,children:e.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:S},children:e.jsx(si.div,{...a,ref:h,style:{boxSizing:"border-box",maxHeight:"100%",...a.style}})})})});iIt.displayName=jSs;var NSs="SelectPopperPosition",dqe=j.forwardRef((s,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:a=lk,...i}=s,l=cMe(n);return e.jsx(Lne,{...l,...i,ref:t,align:r,collisionPadding:a,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});dqe.displayName=NSs;var[kSs,fXe]=gG(N7,{}),uqe="SelectViewport",oIt=j.forwardRef((s,t)=>{const{__scopeSelect:n,nonce:r,...a}=s,i=BP(uqe,n),l=fXe(uqe,n),o=Uo(t,i.onViewportChange),c=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:r}),e.jsx(oMe.Slot,{scope:n,children:e.jsx(si.div,{"data-radix-select-viewport":"",role:"presentation",...a,ref:o,style:{position:"relative",flex:1,overflow:"hidden auto",...a.style},onScroll:va(a.onScroll,d=>{const u=d.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:m}=l;if(m!=null&&m.current&&h){const p=Math.abs(c.current-u.scrollTop);if(p>0){const f=window.innerHeight-lk*2,x=parseFloat(h.style.minHeight),y=parseFloat(h.style.height),v=Math.max(x,y);if(v0?S:0,h.style.justifyContent="flex-end")}}}c.current=u.scrollTop})})})]})});oIt.displayName=uqe;var lIt="SelectGroup",[SSs,CSs]=gG(lIt),cIt=j.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=jx();return e.jsx(SSs,{scope:n,id:a,children:e.jsx(si.div,{role:"group","aria-labelledby":a,...r,ref:t})})});cIt.displayName=lIt;var dIt="SelectLabel",uIt=j.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=CSs(dIt,n);return e.jsx(si.div,{id:a.id,...r,ref:t})});uIt.displayName=dIt;var dCe="SelectItem",[ASs,hIt]=gG(dCe),mIt=j.forwardRef((s,t)=>{const{__scopeSelect:n,value:r,disabled:a=!1,textValue:i,...l}=s,o=zP(dCe,n),c=BP(dCe,n),d=o.value===r,[u,h]=j.useState(i??""),[m,p]=j.useState(!1),f=Uo(t,b=>{var N;return(N=c.itemRefCallback)==null?void 0:N.call(c,b,r,a)}),x=jx(),y=j.useRef("touch"),v=()=>{a||(o.onValueChange(r),o.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return e.jsx(ASs,{scope:n,value:r,disabled:a,textId:x,isSelected:d,onItemTextChange:j.useCallback(b=>{h(N=>N||((b==null?void 0:b.textContent)??"").trim())},[]),children:e.jsx(oMe.ItemSlot,{scope:n,value:r,disabled:a,textValue:u,children:e.jsx(si.div,{role:"option","aria-labelledby":x,"data-highlighted":m?"":void 0,"aria-selected":d&&m,"data-state":d?"checked":"unchecked","aria-disabled":a||void 0,"data-disabled":a?"":void 0,tabIndex:a?void 0:-1,...l,ref:f,onFocus:va(l.onFocus,()=>p(!0)),onBlur:va(l.onBlur,()=>p(!1)),onClick:va(l.onClick,()=>{y.current!=="mouse"&&v()}),onPointerUp:va(l.onPointerUp,()=>{y.current==="mouse"&&v()}),onPointerDown:va(l.onPointerDown,b=>{y.current=b.pointerType}),onPointerMove:va(l.onPointerMove,b=>{var N;y.current=b.pointerType,a?(N=c.onItemLeave)==null||N.call(c):y.current==="mouse"&&b.currentTarget.focus({preventScroll:!0})}),onPointerLeave:va(l.onPointerLeave,b=>{var N;b.currentTarget===document.activeElement&&((N=c.onItemLeave)==null||N.call(c))}),onKeyDown:va(l.onKeyDown,b=>{var S;((S=c.searchRef)==null?void 0:S.current)!==""&&b.key===" "||(pSs.includes(b.key)&&v(),b.key===" "&&b.preventDefault())})})})})});mIt.displayName=dCe;var yZ="SelectItemText",pIt=j.forwardRef((s,t)=>{const{__scopeSelect:n,className:r,style:a,...i}=s,l=zP(yZ,n),o=BP(yZ,n),c=hIt(yZ,n),d=ySs(yZ,n),[u,h]=j.useState(null),m=Uo(t,v=>h(v),c.onItemTextChange,v=>{var b;return(b=o.itemTextRefCallback)==null?void 0:b.call(o,v,c.value,c.disabled)}),p=u==null?void 0:u.textContent,f=j.useMemo(()=>e.jsx("option",{value:c.value,disabled:c.disabled,children:p},c.value),[c.disabled,c.value,p]),{onNativeOptionAdd:x,onNativeOptionRemove:y}=d;return dg(()=>(x(f),()=>y(f)),[x,y,f]),e.jsxs(e.Fragment,{children:[e.jsx(si.span,{id:c.textId,...i,ref:m}),c.isSelected&&l.valueNode&&!l.valueNodeHasChildren?tv.createPortal(i.children,l.valueNode):null]})});pIt.displayName=yZ;var fIt="SelectItemIndicator",gIt=j.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s;return hIt(fIt,n).isSelected?e.jsx(si.span,{"aria-hidden":!0,...r,ref:t}):null});gIt.displayName=fIt;var hqe="SelectScrollUpButton",xIt=j.forwardRef((s,t)=>{const n=BP(hqe,s.__scopeSelect),r=fXe(hqe,s.__scopeSelect),[a,i]=j.useState(!1),l=Uo(t,r.onScrollButtonChange);return dg(()=>{if(n.viewport&&n.isPositioned){let o=function(){const d=c.scrollTop>0;i(d)};const c=n.viewport;return o(),c.addEventListener("scroll",o),()=>c.removeEventListener("scroll",o)}},[n.viewport,n.isPositioned]),a?e.jsx(vIt,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=n;o&&c&&(o.scrollTop=o.scrollTop-c.offsetHeight)}}):null});xIt.displayName=hqe;var mqe="SelectScrollDownButton",yIt=j.forwardRef((s,t)=>{const n=BP(mqe,s.__scopeSelect),r=fXe(mqe,s.__scopeSelect),[a,i]=j.useState(!1),l=Uo(t,r.onScrollButtonChange);return dg(()=>{if(n.viewport&&n.isPositioned){let o=function(){const d=c.scrollHeight-c.clientHeight,u=Math.ceil(c.scrollTop)c.removeEventListener("scroll",o)}},[n.viewport,n.isPositioned]),a?e.jsx(vIt,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=n;o&&c&&(o.scrollTop=o.scrollTop+c.offsetHeight)}}):null});yIt.displayName=mqe;var vIt=j.forwardRef((s,t)=>{const{__scopeSelect:n,onAutoScroll:r,...a}=s,i=BP("SelectScrollButton",n),l=j.useRef(null),o=lMe(n),c=j.useCallback(()=>{l.current!==null&&(window.clearInterval(l.current),l.current=null)},[]);return j.useEffect(()=>()=>c(),[c]),dg(()=>{var u;const d=o().find(h=>h.ref.current===document.activeElement);(u=d==null?void 0:d.ref.current)==null||u.scrollIntoView({block:"nearest"})},[o]),e.jsx(si.div,{"aria-hidden":!0,...a,ref:t,style:{flexShrink:0,...a.style},onPointerDown:va(a.onPointerDown,()=>{l.current===null&&(l.current=window.setInterval(r,50))}),onPointerMove:va(a.onPointerMove,()=>{var d;(d=i.onItemLeave)==null||d.call(i),l.current===null&&(l.current=window.setInterval(r,50))}),onPointerLeave:va(a.onPointerLeave,()=>{c()})})}),ESs="SelectSeparator",bIt=j.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s;return e.jsx(si.div,{"aria-hidden":!0,...r,ref:t})});bIt.displayName=ESs;var pqe="SelectArrow",TSs=j.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=cMe(n),i=zP(pqe,n),l=BP(pqe,n);return i.open&&l.position==="popper"?e.jsx(Ine,{...a,...r,ref:t}):null});TSs.displayName=pqe;var MSs="SelectBubbleInput",_It=j.forwardRef(({__scopeSelect:s,value:t,...n},r)=>{const a=j.useRef(null),i=Uo(r,a),l=Wne(t);return j.useEffect(()=>{const o=a.current;if(!o)return;const c=window.HTMLSelectElement.prototype,u=Object.getOwnPropertyDescriptor(c,"value").set;if(l!==t&&u){const h=new Event("change",{bubbles:!0});u.call(o,t),o.dispatchEvent(h)}},[l,t]),e.jsx(si.select,{...n,style:{...NEt,...n.style},ref:i,defaultValue:t})});_It.displayName=MSs;function wIt(s){return s===""||s===void 0}function jIt(s){const t=sg(s),n=j.useRef(""),r=j.useRef(0),a=j.useCallback(l=>{const o=n.current+l;t(o),function c(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>c(""),1e3))}(o)},[t]),i=j.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return j.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,a,i]}function NIt(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=PSs(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}function PSs(s,t){return s.map((n,r)=>s[(t+r)%s.length])}var LSs=ZLt,kIt=QLt,ISs=eIt,RSs=tIt,DSs=sIt,SIt=nIt,OSs=oIt,FSs=cIt,CIt=uIt,AIt=mIt,zSs=pIt,BSs=gIt,EIt=xIt,TIt=yIt,MIt=bIt;const Ns=LSs,USs=FSs,ks=ISs,ws=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(kIt,{ref:r,className:Mt("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(RSs,{asChild:!0,children:e.jsx(rl,{className:"h-4 w-4 opacity-50"})})]}));ws.displayName=kIt.displayName;const PIt=j.forwardRef(({className:s,...t},n)=>e.jsx(EIt,{ref:n,className:Mt("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(dv,{className:"h-4 w-4"})}));PIt.displayName=EIt.displayName;const LIt=j.forwardRef(({className:s,...t},n)=>e.jsx(TIt,{ref:n,className:Mt("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(rl,{className:"h-4 w-4"})}));LIt.displayName=TIt.displayName;const js=j.forwardRef(({className:s,children:t,position:n="popper",...r},a)=>e.jsx(DSs,{children:e.jsxs(SIt,{ref:a,className:Mt("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(PIt,{}),e.jsx(OSs,{className:Mt("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(LIt,{})]})}));js.displayName=SIt.displayName;const IIt=j.forwardRef(({className:s,...t},n)=>e.jsx(CIt,{ref:n,className:Mt("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...t}));IIt.displayName=CIt.displayName;const et=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(AIt,{ref:r,className:Mt("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(BSs,{children:e.jsx(Xr,{className:"h-4 w-4"})})}),e.jsx(zSs,{children:t})]}));et.displayName=AIt.displayName;const qSs=j.forwardRef(({className:s,...t},n)=>e.jsx(MIt,{ref:n,className:Mt("-mx-1 my-1 h-px bg-muted",s),...t}));qSs.displayName=MIt.displayName;const $Ss=kN({category:pXe(["general","technology","crm","marketing"]),subject:sl().min(5,"Subject must be at least 5 characters").max(200),description:sl().min(20,"Please provide more details (at least 20 characters)").max(2e3)}),VSs={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function fqe({trigger:s}){const[t,n]=j.useState(!1),[r,a]=j.useState(!1),{user:i}=vs(),l=eMe({resolver:tMe($Ss),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:VSs[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(al,{asChild:!0,children:s||e.jsxs(U,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(YX,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Support"})]})}),e.jsxs(Ds,{className:"sm:max-w-[500px]",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(ba,{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(aMe,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(o),className:"space-y-4",children:[e.jsx(hf,{control:l.control,name:"category",render:({field:c})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"Category"}),e.jsxs(Ns,{onValueChange:c.onChange,defaultValue:c.value,children:[e.jsx(Ip,{children:e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select a category"})})}),e.jsxs(js,{children:[e.jsx(et,{value:"general",children:"General Support"}),e.jsx(et,{value:"technology",children:"Technology Support"}),e.jsx(et,{value:"crm",children:"CRM Support"}),e.jsx(et,{value:"marketing",children:"Marketing Support"})]})]}),e.jsx(J1,{})]})}),e.jsx(hf,{control:l.control,name:"subject",render:({field:c})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"Subject"}),e.jsx(Ip,{children:e.jsx(xe,{placeholder:"Brief description of your issue",...c})}),e.jsx(J1,{})]})}),e.jsx(hf,{control:l.control,name:"description",render:({field:c})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"Description"}),e.jsx(Ip,{children:e.jsx(Fs,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...c})}),e.jsx(J1,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(U,{type:"submit",disabled:r,children:r?"Submitting...":"Submit Ticket"})]})]})})]})]})}function oo(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 Nh(s,t){return s instanceof Date?new s.constructor(t):new Date(t)}function jh(s,t){const n=oo(s);return isNaN(t)?Nh(s,NaN):(t&&n.setDate(n.getDate()+t),n)}function dy(s,t){const n=oo(s);if(isNaN(t))return Nh(s,NaN);if(!t)return n;const r=n.getDate(),a=Nh(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 RIt(s,t){const n=+oo(s);return Nh(s,n+t)}const gXe=6048e5,HSs=864e5,dMe=6e4,uMe=36e5,GSs=1e3,xoe=43200,Yht=1440;function Zht(s,t){return RIt(s,t*uMe)}let WSs={};function UP(){return WSs}function c1(s,t){var o,c,d,u;const n=UP(),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=oo(s),i=a.getDay(),l=(i=a.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function vf(s){const t=oo(s);return t.setHours(0,0,0,0),t}function cP(s){const t=oo(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 nv(s,t){const n=vf(s),r=vf(t),a=+n-cP(n),i=+r-cP(r);return Math.round((a-i)/HSs)}function KSs(s){const t=DIt(s),n=Nh(s,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),nE(n)}function Xht(s,t){return RIt(s,t*dMe)}function qD(s,t){const n=t*7;return jh(s,n)}function YSs(s,t){return dy(s,t*12)}function ZSs(s){let t;return s.forEach(function(n){const r=oo(n);(t===void 0||t{const r=oo(n);(!t||t>r||isNaN(+r))&&(t=r)}),t||new Date(NaN)}function j5e(s,t){const n=oo(s),r=oo(t),a=n.getTime()-r.getTime();return a<0?-1:a>0?1:a}function hMe(s){return Nh(s,Date.now())}function Hh(s,t){const n=vf(s),r=vf(t);return+n==+r}function xXe(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function gqe(s){if(!xXe(s)&&typeof s!="number")return!1;const t=oo(s);return!isNaN(Number(t))}function zV(s,t){const n=oo(s),r=oo(t),a=n.getFullYear()-r.getFullYear(),i=n.getMonth()-r.getMonth();return a*12+i}function QSs(s,t,n){const r=c1(s,n),a=c1(t,n),i=+r-cP(r),l=+a-cP(a);return Math.round((i-l)/gXe)}function hN(s,t){const n=oo(s),r=oo(t),a=Qht(n,r),i=Math.abs(nv(n,r));n.setDate(n.getDate()-a*i);const l=+(Qht(n,r)===-a),o=a*(i-l);return o===0?0:o}function Qht(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 JSs(s){return t=>{const r=(s?Math[s]:Math.trunc)(t);return r===0?0:r}}function e5s(s,t){return+oo(s)-+oo(t)}function t5s(s){const t=oo(s);return t.setHours(23,59,59,999),t}function u_(s){const t=oo(s),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}function s5s(s){const t=oo(s);return+t5s(t)==+u_(t)}function n5s(s,t){const n=oo(s),r=oo(t),a=j5e(n,r),i=Math.abs(zV(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=j5e(n,r)===-a;s5s(oo(s))&&i===1&&j5e(s,r)===1&&(o=!1),l=a*(i-Number(o))}return l===0?0:l}function r5s(s,t,n){const r=e5s(s,t)/1e3;return JSs(n==null?void 0:n.roundingMethod)(r)}function a5s(s,t){const n=oo(s.start),r=oo(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(oo(l)),l.setDate(l.getDate()+o),l.setHours(0,0,0,0);return a?c.reverse():c}function i5s(s){const t=oo(s),n=t.getMonth(),r=n-n%3;return t.setMonth(r,1),t.setHours(0,0,0,0),t}function Bh(s){const t=oo(s);return t.setDate(1),t.setHours(0,0,0,0),t}function yXe(s){const t=oo(s),n=Nh(s,0);return n.setFullYear(t.getFullYear(),0,1),n.setHours(0,0,0,0),n}function mMe(s,t){var o,c,d,u;const n=UP(),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=oo(s),i=a.getDay(),l=(i{let r;const a=o5s[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 sOe(s){return(t={})=>{const n=t.width?String(t.width):s.defaultWidth;return s.formats[n]||s.formats[s.defaultWidth]}}const c5s={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},d5s={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},u5s={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},h5s={date:sOe({formats:c5s,defaultWidth:"full"}),time:sOe({formats:d5s,defaultWidth:"full"}),dateTime:sOe({formats:u5s,defaultWidth:"full"})},m5s={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},p5s=(s,t,n,r)=>m5s[s];function HK(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 f5s={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},g5s={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},x5s={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"]},y5s={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"]},v5s={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"}},b5s={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"}},_5s=(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"},w5s={ordinalNumber:_5s,era:HK({values:f5s,defaultWidth:"wide"}),quarter:HK({values:g5s,defaultWidth:"wide",argumentCallback:s=>s-1}),month:HK({values:x5s,defaultWidth:"wide"}),day:HK({values:y5s,defaultWidth:"wide"}),dayPeriod:HK({values:v5s,defaultWidth:"wide",formattingValues:b5s,defaultFormattingWidth:"wide"})};function GK(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)?N5s(o,h=>h.test(l)):j5s(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 j5s(s,t){for(const n in s)if(Object.prototype.hasOwnProperty.call(s,n)&&t(s[n]))return n}function N5s(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 S5s=/^(\d+)(th|st|nd|rd)?/i,C5s=/\d+/i,A5s={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},E5s={any:[/^b/i,/^(a|c)/i]},T5s={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},M5s={any:[/1/i,/2/i,/3/i,/4/i]},P5s={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},L5s={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]},I5s={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},R5s={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]},D5s={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},O5s={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}},F5s={ordinalNumber:k5s({matchPattern:S5s,parsePattern:C5s,valueCallback:s=>parseInt(s,10)}),era:GK({matchPatterns:A5s,defaultMatchWidth:"wide",parsePatterns:E5s,defaultParseWidth:"any"}),quarter:GK({matchPatterns:T5s,defaultMatchWidth:"wide",parsePatterns:M5s,defaultParseWidth:"any",valueCallback:s=>s+1}),month:GK({matchPatterns:P5s,defaultMatchWidth:"wide",parsePatterns:L5s,defaultParseWidth:"any"}),day:GK({matchPatterns:I5s,defaultMatchWidth:"wide",parsePatterns:R5s,defaultParseWidth:"any"}),dayPeriod:GK({matchPatterns:D5s,defaultMatchWidth:"any",parsePatterns:O5s,defaultParseWidth:"any"})},pMe={code:"en-US",formatDistance:l5s,formatLong:h5s,formatRelative:p5s,localize:w5s,match:F5s,options:{weekStartsOn:0,firstWeekContainsDate:1}};function z5s(s){const t=oo(s);return nv(t,yXe(t))+1}function vXe(s){const t=oo(s),n=+nE(t)-+KSs(t);return Math.round(n/gXe)+1}function bXe(s,t){var u,h,m,p;const n=oo(s),r=n.getFullYear(),a=UP(),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??((p=(m=a.locale)==null?void 0:m.options)==null?void 0:p.firstWeekContainsDate)??1,l=Nh(s,0);l.setFullYear(r+1,0,i),l.setHours(0,0,0,0);const o=c1(l,t),c=Nh(s,0);c.setFullYear(r,0,i),c.setHours(0,0,0,0);const d=c1(c,t);return n.getTime()>=o.getTime()?r+1:n.getTime()>=d.getTime()?r:r-1}function B5s(s,t){var o,c,d,u;const n=UP(),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=bXe(s,t),i=Nh(s,0);return i.setFullYear(a,0,r),i.setHours(0,0,0,0),c1(i,t)}function _Xe(s,t){const n=oo(s),r=+c1(n,t)-+B5s(n,t);return Math.round(r/gXe)+1}function bh(s,t){const n=s<0?"-":"",r=Math.abs(s).toString().padStart(t,"0");return n+r}const sT={y(s,t){const n=s.getFullYear(),r=n>0?n:1-n;return bh(t==="yy"?r%100:r,t.length)},M(s,t){const n=s.getMonth();return t==="M"?String(n+1):bh(n+1,2)},d(s,t){return bh(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 bh(s.getHours()%12||12,t.length)},H(s,t){return bh(s.getHours(),t.length)},m(s,t){return bh(s.getMinutes(),t.length)},s(s,t){return bh(s.getSeconds(),t.length)},S(s,t){const n=t.length,r=s.getMilliseconds(),a=Math.trunc(r*Math.pow(10,n-3));return bh(a,t.length)}},Uz={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Jht={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 sT.y(s,t)},Y:function(s,t,n,r){const a=bXe(s,r),i=a>0?a:1-a;if(t==="YY"){const l=i%100;return bh(l,2)}return t==="Yo"?n.ordinalNumber(i,{unit:"year"}):bh(i,t.length)},R:function(s,t){const n=DIt(s);return bh(n,t.length)},u:function(s,t){const n=s.getFullYear();return bh(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 bh(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 bh(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 sT.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 bh(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=_Xe(s,r);return t==="wo"?n.ordinalNumber(a,{unit:"week"}):bh(a,t.length)},I:function(s,t,n){const r=vXe(s);return t==="Io"?n.ordinalNumber(r,{unit:"week"}):bh(r,t.length)},d:function(s,t,n){return t==="do"?n.ordinalNumber(s.getDate(),{unit:"date"}):sT.d(s,t)},D:function(s,t,n){const r=z5s(s);return t==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):bh(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 bh(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 bh(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 bh(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=Uz.noon:r===0?a=Uz.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=Uz.evening:r>=12?a=Uz.afternoon:r>=4?a=Uz.morning:a=Uz.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 sT.h(s,t)},H:function(s,t,n){return t==="Ho"?n.ordinalNumber(s.getHours(),{unit:"hour"}):sT.H(s,t)},K:function(s,t,n){const r=s.getHours()%12;return t==="Ko"?n.ordinalNumber(r,{unit:"hour"}):bh(r,t.length)},k:function(s,t,n){let r=s.getHours();return r===0&&(r=24),t==="ko"?n.ordinalNumber(r,{unit:"hour"}):bh(r,t.length)},m:function(s,t,n){return t==="mo"?n.ordinalNumber(s.getMinutes(),{unit:"minute"}):sT.m(s,t)},s:function(s,t,n){return t==="so"?n.ordinalNumber(s.getSeconds(),{unit:"second"}):sT.s(s,t)},S:function(s,t){return sT.S(s,t)},X:function(s,t,n){const r=s.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return tmt(r);case"XXXX":case"XX":return fD(r);case"XXXXX":case"XXX":default:return fD(r,":")}},x:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"x":return tmt(r);case"xxxx":case"xx":return fD(r);case"xxxxx":case"xxx":default:return fD(r,":")}},O:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+emt(r,":");case"OOOO":default:return"GMT"+fD(r,":")}},z:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+emt(r,":");case"zzzz":default:return"GMT"+fD(r,":")}},t:function(s,t,n){const r=Math.trunc(s.getTime()/1e3);return bh(r,t.length)},T:function(s,t,n){const r=s.getTime();return bh(r,t.length)}};function emt(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+bh(i,2)}function tmt(s,t){return s%60===0?(s>0?"-":"+")+bh(Math.abs(s)/60,2):fD(s,t)}function fD(s,t=""){const n=s>0?"-":"+",r=Math.abs(s),a=bh(Math.trunc(r/60),2),i=bh(r%60,2);return n+a+t+i}const smt=(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"})}},FIt=(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"})}},U5s=(s,t)=>{const n=s.match(/(P+)(p+)?/)||[],r=n[1],a=n[2];if(!a)return smt(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}}",smt(r,t)).replace("{{time}}",FIt(a,t))},xqe={p:FIt,P:U5s},q5s=/^D+$/,$5s=/^Y+$/,V5s=["D","DD","YY","YYYY"];function zIt(s){return q5s.test(s)}function BIt(s){return $5s.test(s)}function yqe(s,t,n){const r=H5s(s,t,n);if(console.warn(r),V5s.includes(s))throw new RangeError(r)}function H5s(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 G5s=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,W5s=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,K5s=/^'([^]*?)'?$/,Y5s=/''/g,Z5s=/[a-zA-Z]/;function Gs(s,t,n){var u,h,m,p,f,x,y,v;const r=UP(),a=(n==null?void 0:n.locale)??r.locale??pMe,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??((p=(m=r.locale)==null?void 0:m.options)==null?void 0:p.firstWeekContainsDate)??1,l=(n==null?void 0:n.weekStartsOn)??((x=(f=n==null?void 0:n.locale)==null?void 0:f.options)==null?void 0:x.weekStartsOn)??r.weekStartsOn??((v=(y=r.locale)==null?void 0:y.options)==null?void 0:v.weekStartsOn)??0,o=oo(s);if(!gqe(o))throw new RangeError("Invalid time value");let c=t.match(W5s).map(b=>{const N=b[0];if(N==="p"||N==="P"){const S=xqe[N];return S(b,a.formatLong)}return b}).join("").match(G5s).map(b=>{if(b==="''")return{isToken:!1,value:"'"};const N=b[0];if(N==="'")return{isToken:!1,value:X5s(b)};if(Jht[N])return{isToken:!0,value:b};if(N.match(Z5s))throw new RangeError("Format string contains an unescaped latin alphabet character `"+N+"`");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 N=b.value;(!(n!=null&&n.useAdditionalWeekYearTokens)&&BIt(N)||!(n!=null&&n.useAdditionalDayOfYearTokens)&&zIt(N))&&yqe(N,t,String(s));const S=Jht[N[0]];return S(o,N,a.localize,d)}).join("")}function X5s(s){const t=s.match(K5s);return t?t[1].replace(Y5s,"'"):s}function Q5s(s,t,n){const r=UP(),a=(n==null?void 0:n.locale)??r.locale??pMe,i=2520,l=j5e(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=oo(t),d=oo(s)):(c=oo(s),d=oo(t));const u=r5s(d,c),h=(cP(d)-cP(c))/1e3,m=Math.round((u-h)/60);let p;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 rS(s,t){const n=oo(s),r=oo(t);return+n<+r}function a4s(s){return+oo(s)>Date.now()}function i4s(s,t){const n=t instanceof Date?Nh(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 o4s=10;class UIt{constructor(){Lr(this,"subPriority",0)}validate(t,n){return!0}}class l4s extends UIt{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 c4s extends UIt{constructor(){super(...arguments);Lr(this,"priority",o4s);Lr(this,"subPriority",-1)}set(n,r){return r.timestampIsSet?n:Nh(n,i4s(n,Date))}}class Zu{run(t,n,r,a){const i=this.parse(t,n,r,a);return i?{setter:new l4s(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(t,n,r){return!0}}class d4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",140);Lr(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 qg={month:/^(1[0-2]|0?\d)/,date:/^(3[0-1]|[0-2]?\d)/,dayOfYear:/^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,week:/^(5[0-3]|[0-4]?\d)/,hour23h:/^(2[0-3]|[0-1]?\d)/,hour24h:/^(2[0-4]|[0-1]?\d)/,hour11h:/^(1[0-1]|0?\d)/,hour12h:/^(1[0-2]|0?\d)/,minute:/^[0-5]?\d/,second:/^[0-5]?\d/,singleDigit:/^\d/,twoDigits:/^\d{1,2}/,threeDigits:/^\d{1,3}/,fourDigits:/^\d{1,4}/,anyDigitsSigned:/^-?\d+/,singleDigitSigned:/^-?\d/,twoDigitsSigned:/^-?\d{1,2}/,threeDigitsSigned:/^-?\d{1,3}/,fourDigitsSigned:/^-?\d{1,4}/},o4={basicOptionalMinutes:/^([+-])(\d{2})(\d{2})?|Z/,basic:/^([+-])(\d{2})(\d{2})|Z/,basicOptionalSeconds:/^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,extended:/^([+-])(\d{2}):(\d{2})|Z/,extendedOptionalSeconds:/^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/};function $g(s,t){return s&&{value:t(s.value),rest:s.rest}}function yf(s,t){const n=t.match(s);return n?{value:parseInt(n[0],10),rest:t.slice(n[0].length)}:null}function l4(s,t){const n=t.match(s);if(!n)return null;if(n[0]==="Z")return{value:0,rest:t.slice(1)};const r=n[1]==="+"?1:-1,a=n[2]?parseInt(n[2],10):0,i=n[3]?parseInt(n[3],10):0,l=n[5]?parseInt(n[5],10):0;return{value:r*(a*uMe+i*dMe+l*GSs),rest:t.slice(n[0].length)}}function qIt(s){return yf(qg.anyDigitsSigned,s)}function ug(s,t){switch(s){case 1:return yf(qg.singleDigit,t);case 2:return yf(qg.twoDigits,t);case 3:return yf(qg.threeDigits,t);case 4:return yf(qg.fourDigits,t);default:return yf(new RegExp("^\\d{1,"+s+"}"),t)}}function uCe(s,t){switch(s){case 1:return yf(qg.singleDigitSigned,t);case 2:return yf(qg.twoDigitsSigned,t);case 3:return yf(qg.threeDigitsSigned,t);case 4:return yf(qg.fourDigitsSigned,t);default:return yf(new RegExp("^-?\\d{1,"+s+"}"),t)}}function wXe(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 $It(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 VIt(s){return s%400===0||s%4===0&&s%100!==0}class u4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",130);Lr(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 $g(ug(4,n),i);case"yo":return $g(a.ordinalNumber(n,{unit:"year"}),i);default:return $g(ug(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=$It(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 h4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",130);Lr(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 $g(ug(4,n),i);case"Yo":return $g(a.ordinalNumber(n,{unit:"year"}),i);default:return $g(ug(r.length,n),i)}}validate(n,r){return r.isTwoDigitYear||r.year>0}set(n,r,a,i){const l=bXe(n,i);if(a.isTwoDigitYear){const c=$It(a.year,l);return n.setFullYear(c,0,i.firstWeekContainsDate),n.setHours(0,0,0,0),c1(n,i)}const o=!("era"in r)||r.era===1?a.year:1-a.year;return n.setFullYear(o,0,i.firstWeekContainsDate),n.setHours(0,0,0,0),c1(n,i)}}class m4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",130);Lr(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(n,r){return uCe(r==="R"?4:r.length,n)}set(n,r,a){const i=Nh(n,0);return i.setFullYear(a,0,4),i.setHours(0,0,0,0),nE(i)}}class p4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",130);Lr(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(n,r){return uCe(r==="u"?4:r.length,n)}set(n,r,a){return n.setFullYear(a,0,1),n.setHours(0,0,0,0),n}}class f4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",120);Lr(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 ug(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 g4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",120);Lr(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 ug(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 x4s extends Zu{constructor(){super(...arguments);Lr(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);Lr(this,"priority",110)}parse(n,r,a){const i=l=>l-1;switch(r){case"M":return $g(yf(qg.month,n),i);case"MM":return $g(ug(2,n),i);case"Mo":return $g(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 y4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",110);Lr(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 $g(yf(qg.month,n),i);case"LL":return $g(ug(2,n),i);case"Lo":return $g(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 v4s(s,t,n){const r=oo(s),a=_Xe(r,n)-t;return r.setDate(r.getDate()-a*7),r}class b4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",100);Lr(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(n,r,a){switch(r){case"w":return yf(qg.week,n);case"wo":return a.ordinalNumber(n,{unit:"week"});default:return ug(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a,i){return c1(v4s(n,a,i),i)}}function _4s(s,t){const n=oo(s),r=vXe(n)-t;return n.setDate(n.getDate()-r*7),n}class w4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",100);Lr(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 yf(qg.week,n);case"Io":return a.ordinalNumber(n,{unit:"week"});default:return ug(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a){return nE(_4s(n,a))}}const j4s=[31,28,31,30,31,30,31,31,30,31,30,31],N4s=[31,29,31,30,31,30,31,31,30,31,30,31];class k4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",90);Lr(this,"subPriority",1);Lr(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"d":return yf(qg.date,n);case"do":return a.ordinalNumber(n,{unit:"date"});default:return ug(r.length,n)}}validate(n,r){const a=n.getFullYear(),i=VIt(a),l=n.getMonth();return i?r>=1&&r<=N4s[l]:r>=1&&r<=j4s[l]}set(n,r,a){return n.setDate(a),n.setHours(0,0,0,0),n}}class S4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",90);Lr(this,"subpriority",1);Lr(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 yf(qg.dayOfYear,n);case"Do":return a.ordinalNumber(n,{unit:"date"});default:return ug(r.length,n)}}validate(n,r){const a=n.getFullYear();return VIt(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 jXe(s,t,n){var h,m,p,f;const r=UP(),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??((f=(p=r.locale)==null?void 0:p.options)==null?void 0:f.weekStartsOn)??0,i=oo(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 jh(i,u)}class C4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",90);Lr(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=jXe(n,a,i),n.setHours(0,0,0,0),n}}class A4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",90);Lr(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 $g(ug(r.length,n),l);case"eo":return $g(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=jXe(n,a,i),n.setHours(0,0,0,0),n}}class E4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",90);Lr(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 $g(ug(r.length,n),l);case"co":return $g(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=jXe(n,a,i),n.setHours(0,0,0,0),n}}function T4s(s,t){const n=oo(s),r=t4s(n),a=t-r;return jh(n,a)}class M4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",90);Lr(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 ug(r.length,n);case"io":return a.ordinalNumber(n,{unit:"day"});case"iii":return $g(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 $g(a.day(n,{width:"narrow",context:"formatting"}),i);case"iiiiii":return $g(a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"}),i);case"iiii":default:return $g(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=T4s(n,a),n.setHours(0,0,0,0),n}}class P4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",80);Lr(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(wXe(a),0,0,0),n}}class L4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",80);Lr(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(wXe(a),0,0,0),n}}class I4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",80);Lr(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(wXe(a),0,0,0),n}}class R4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",70);Lr(this,"incompatibleTokens",["H","K","k","t","T"])}parse(n,r,a){switch(r){case"h":return yf(qg.hour12h,n);case"ho":return a.ordinalNumber(n,{unit:"hour"});default:return ug(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 D4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",70);Lr(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(n,r,a){switch(r){case"H":return yf(qg.hour23h,n);case"Ho":return a.ordinalNumber(n,{unit:"hour"});default:return ug(r.length,n)}}validate(n,r){return r>=0&&r<=23}set(n,r,a){return n.setHours(a,0,0,0),n}}class O4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",70);Lr(this,"incompatibleTokens",["h","H","k","t","T"])}parse(n,r,a){switch(r){case"K":return yf(qg.hour11h,n);case"Ko":return a.ordinalNumber(n,{unit:"hour"});default:return ug(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 F4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",70);Lr(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(n,r,a){switch(r){case"k":return yf(qg.hour24h,n);case"ko":return a.ordinalNumber(n,{unit:"hour"});default:return ug(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 z4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",60);Lr(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"m":return yf(qg.minute,n);case"mo":return a.ordinalNumber(n,{unit:"minute"});default:return ug(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setMinutes(a,0,0),n}}class B4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",50);Lr(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"s":return yf(qg.second,n);case"so":return a.ordinalNumber(n,{unit:"second"});default:return ug(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setSeconds(a,0),n}}class U4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",30);Lr(this,"incompatibleTokens",["t","T"])}parse(n,r){const a=i=>Math.trunc(i*Math.pow(10,-r.length+3));return $g(ug(r.length,n),a)}set(n,r,a){return n.setMilliseconds(a),n}}class q4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",10);Lr(this,"incompatibleTokens",["t","T","x"])}parse(n,r){switch(r){case"X":return l4(o4.basicOptionalMinutes,n);case"XX":return l4(o4.basic,n);case"XXXX":return l4(o4.basicOptionalSeconds,n);case"XXXXX":return l4(o4.extendedOptionalSeconds,n);case"XXX":default:return l4(o4.extended,n)}}set(n,r,a){return r.timestampIsSet?n:Nh(n,n.getTime()-cP(n)-a)}}class $4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",10);Lr(this,"incompatibleTokens",["t","T","X"])}parse(n,r){switch(r){case"x":return l4(o4.basicOptionalMinutes,n);case"xx":return l4(o4.basic,n);case"xxxx":return l4(o4.basicOptionalSeconds,n);case"xxxxx":return l4(o4.extendedOptionalSeconds,n);case"xxx":default:return l4(o4.extended,n)}}set(n,r,a){return r.timestampIsSet?n:Nh(n,n.getTime()-cP(n)-a)}}class V4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",40);Lr(this,"incompatibleTokens","*")}parse(n){return qIt(n)}set(n,r,a){return[Nh(n,a*1e3),{timestampIsSet:!0}]}}class H4s extends Zu{constructor(){super(...arguments);Lr(this,"priority",20);Lr(this,"incompatibleTokens","*")}parse(n){return qIt(n)}set(n,r,a){return[Nh(n,a),{timestampIsSet:!0}]}}const G4s={G:new d4s,y:new u4s,Y:new h4s,R:new m4s,u:new p4s,Q:new f4s,q:new g4s,M:new x4s,L:new y4s,w:new b4s,I:new w4s,d:new k4s,D:new S4s,E:new C4s,e:new A4s,c:new E4s,i:new M4s,a:new P4s,b:new L4s,B:new I4s,h:new R4s,H:new D4s,K:new O4s,k:new F4s,m:new z4s,s:new B4s,S:new U4s,X:new q4s,x:new $4s,t:new V4s,T:new H4s},W4s=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,K4s=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Y4s=/^'([^]*?)'?$/,Z4s=/''/g,X4s=/\S/,Q4s=/[a-zA-Z]/;function NXe(s,t,n,r){var x,y,v,b;const a=e4s(),i=a.locale??pMe,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===""?oo(n):Nh(n,NaN);const c={firstWeekContainsDate:l,weekStartsOn:o,locale:i},d=[new c4s],u=t.match(K4s).map(N=>{const S=N[0];if(S in xqe){const A=xqe[S];return A(N,i.formatLong)}return N}).join("").match(W4s),h=[];for(let N of u){BIt(N)&&yqe(N,t,s),zIt(N)&&yqe(N,t,s);const S=N[0],A=G4s[S];if(A){const{incompatibleTokens:T}=A;if(Array.isArray(T)){const M=h.find(I=>T.includes(I.token)||I.token===S);if(M)throw new RangeError(`The format string mustn't contain \`${M.fullToken}\` and \`${N}\` at the same time`)}else if(A.incompatibleTokens==="*"&&h.length>0)throw new RangeError(`The format string mustn't contain \`${N}\` and any other token at the same time`);h.push({token:S,fullToken:N});const L=A.run(s,N,i.match,c);if(!L)return Nh(n,NaN);d.push(L.setter),s=L.rest}else{if(S.match(Q4s))throw new RangeError("Format string contains an unescaped latin alphabet character `"+S+"`");if(N==="''"?N="'":S==="'"&&(N=J4s(N)),s.indexOf(N)===0)s=s.slice(N.length);else return Nh(n,NaN)}}if(s.length>0&&X4s.test(s))return Nh(n,NaN);const m=d.map(N=>N.priority).sort((N,S)=>S-N).filter((N,S,A)=>A.indexOf(N)===S).map(N=>d.filter(S=>S.priority===N).sort((S,A)=>A.subPriority-S.subPriority)).map(N=>N[0]);let p=oo(n);if(isNaN(p.getTime()))return Nh(n,NaN);const f={};for(const N of m){if(!N.validate(p,c))return Nh(n,NaN);const S=N.set(p,f,c);Array.isArray(S)?(p=S[0],Object.assign(f,S[1])):p=S}return Nh(n,p)}function J4s(s){return s.match(Y4s)[1].replace(Z4s,"'")}function z4(s){return+oo(s)i-l);return n>=r&&n<=a}function N5e(s,t){return jh(s,-t)}function ty(s,t){const r=o3s(s);let a;if(r.date){const c=l3s(r.date,2);a=c3s(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=d3s(r.time),isNaN(l)))return new Date(NaN);if(r.timezone){if(o=u3s(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 yoe={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},r3s=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,a3s=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,i3s=/^([+-])(\d{2})(?::?(\d{2}))?$/;function o3s(s){const t={},n=s.split(yoe.dateTimeDelimiter);let r;if(n.length>2)return t;if(/:/.test(n[0])?r=n[0]:(t.date=n[0],r=n[1],yoe.timeZoneDelimiter.test(t.date)&&(t.date=s.split(yoe.timeZoneDelimiter)[0],r=s.substr(t.date.length,s.length))),r){const a=yoe.timezone.exec(r);a?(t.time=r.replace(a[1],""),t.timezone=a[1]):t.time=r}return t}function l3s(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 c3s(s,t){if(t===null)return new Date(NaN);const n=s.match(r3s);if(!n)return new Date(NaN);const r=!!n[4],a=WK(n[1]),i=WK(n[2])-1,l=WK(n[3]),o=WK(n[4]),c=WK(n[5])-1;if(r)return g3s(t,o,c)?h3s(t,o,c):new Date(NaN);{const d=new Date(0);return!p3s(t,i,l)||!f3s(t,a)?new Date(NaN):(d.setUTCFullYear(t,i,Math.max(a,l)),d)}}function WK(s){return s?parseInt(s):1}function d3s(s){const t=s.match(a3s);if(!t)return NaN;const n=nOe(t[1]),r=nOe(t[2]),a=nOe(t[3]);return x3s(n,r,a)?n*uMe+r*dMe+a*1e3:NaN}function nOe(s){return s&&parseFloat(s.replace(",","."))||0}function u3s(s){if(s==="Z")return 0;const t=s.match(i3s);if(!t)return 0;const n=t[1]==="+"?-1:1,r=parseInt(t[2]),a=t[3]&&parseInt(t[3])||0;return y3s(r,a)?n*(r*uMe+a*dMe):NaN}function h3s(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 m3s=[31,null,31,30,31,30,31,31,30,31,30,31];function HIt(s){return s%400===0||s%4===0&&s%100!==0}function p3s(s,t,n){return t>=0&&t<=11&&n>=1&&n<=(m3s[t]||(HIt(s)?29:28))}function f3s(s,t){return t>=1&&t<=(HIt(s)?366:365)}function g3s(s,t,n){return t>=1&&t<=53&&n>=0&&n<=6}function x3s(s,t,n){return s===24?t===0&&n===0:n>=0&&n<60&&t>=0&&t<60&&s>=0&&s<25}function y3s(s,t){return t>=0&&t<=59}function rOe(s,t){const n=oo(s),r=n.getFullYear(),a=n.getDate(),i=Nh(s,0);i.setFullYear(r,t,15),i.setHours(0,0,0,0);const l=J5s(i);return n.setMonth(t,Math.min(a,l)),n}function GIt(s,t){const n=oo(s);return n.setHours(t),n}function WIt(s,t){const n=oo(s);return n.setMinutes(t),n}function rmt(s,t){const n=oo(s);return isNaN(+n)?Nh(s,NaN):(n.setFullYear(t),n)}function $D(s,t){return dy(s,-t)}const v3s=()=>{const{user:s}=vs(),t=Wn(),[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,N=async()=>{try{const M=sessionStorage.getItem(v);if(M){const I=JSON.parse(M);if(I.ts&&Date.now()-I.ts{r(T);const L=u.current?new Date(u.current):null,M=T.filter(I=>L?new Date(I.created_at)>L:!0);i(M.length)};N();const A=q.channel("push-notifications").on("postgres_changes",{event:"INSERT",schema:"public",table:"push_notifications"},T=>{const L=T.new;r(I=>{const R=[L,...I].slice(0,20);try{sessionStorage.setItem(v,JSON.stringify({ts:Date.now(),data:R}))}catch{}return R});const M=u.current?new Date(u.current):null;(!M||new Date(L.created_at)>M)&&i(I=>I+1),Notification.permission==="granted"&&new Notification(L.title,{body:L.body,icon:"/favicon.ico"})}).subscribe();return()=>{q.removeChannel(A)}},[s]);const h=x=>{const y=x.toLowerCase();return y.includes("community")||y.includes("post")?Ki:y.includes("academy")||y.includes("video")?Wr:y.includes("template")?$c:y.includes("event")?pa:y.includes("newsletter")?Q2:y.includes("brokerage")?og:y.includes("swag")||y.includes("social")?Ro:y.includes("toolbox")||y.includes("tool")?O4:y.includes("brief")?cn:Ki},m=x=>{o(!1),x.url&&x.url!=="/"&&t(x.url)},p=()=>{if(!s)return;const x=new Date().toISOString(),y=`notification_last_read_${s.id}`;localStorage.setItem(y,x),d(x),i(0)},f=x=>{o(x),x&&a>0&&p()};return e.jsxs(Ku,{open:l,onOpenChange:f,children:[e.jsx(Yu,{asChild:!0,children:e.jsxs(U,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(bx,{className:"h-5 w-5"}),a>0&&e.jsx(Be,{variant:"destructive",className:"absolute -top-1 -right-1 h-5 w-5 flex items-center justify-center p-0 text-xs",children:a>9?"9+":a})]})}),e.jsxs(Eu,{align:"end",className:"w-80",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[e.jsx("span",{className:"font-semibold",children:"Notifications"}),n.length>0&&e.jsx(U,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:p,children:"Mark all read"})]}),e.jsx(Gi,{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(La,{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:Nd(new Date(x.created_at),{addSuffix:!0})})]})]},x.id)})})]})]})};function b3s(s){return s!=null&&s.length?s.find(t=>t.is_active&&t.mls_provider_id&&!t.no_mls_mode)||s[0]:null}function $p(){const{user:s}=vs(),{data:t,isLoading:n}=ct({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").eq("agent_id",s.id).eq("is_active",!0).order("created_at",{ascending:!0}).limit(10);if(a)throw a;return b3s(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 fMe(s=!0){const{user:t}=vs(),{data:n,isLoading:r}=ct({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 _3s="coaching_access";function KIt(){const{user:s,loading:t,isAdmin:n,isCoach:r}=vs(),{data:a,isLoading:i}=ct({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",_3s).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 gMe=[{id:"home",label:"Home",icon:EF,route:"/dashboard",accent:"nav-home"},{id:"crm",label:"CRM",icon:ko,description:"Contacts and follow-up",accent:"nav-crm"},{id:"deals",label:"Deals",icon:P4,description:"Pipeline, transactions and tasks",accent:"nav-deals"},{id:"listings",label:"Listings",icon:_i,description:"Win and market listings",accent:"nav-listings"},{id:"marketing",label:"Marketing",icon:Th,description:"Content, email and video",accent:"nav-marketing"},{id:"websites",label:"Websites",icon:fl,description:"Your site and add-ons",accent:"nav-websites"},{id:"academy",label:"Learn",icon:Kh,description:"Training, programs and coaching",accent:"nav-academy"},{id:"events",label:"Events",icon:BF,route:"/events",accent:"nav-events"},{id:"apps",label:"Apps",icon:Aw,route:"/apps",accent:"nav-apps"},{id:"brokerage",label:"Brokerage",icon:tq,description:"Your brokerage, teams and recruiting",accent:"nav-brokerage",visible:s=>!s.isAdmin&&(!!s.brokerageId||s.isBrokerageManager||s.isOnTeam)},{id:"more",label:"More",icon:Z1,description:"Community, marketplace and help",accent:"nav-more"}],O1=s=>t=>t.hasPermission(s),w3s=[{id:"mission-control",label:"Mission Control",route:"/mission-control",icon:E4,description:"Your daily relationship command center",primaryCategory:"crm",section:"Overview",visible:O1("contacts"),searchKeywords:["agent os","mission control","dashboard"],displayOrder:10},{id:"client-portals",label:"Client Portals",route:"/mission-control/client-portals",icon:cn,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:Bn,description:"Every contact in your database",primaryCategory:"crm",section:"Contacts",visible:O1("contacts"),searchKeywords:["contacts","database","sphere","people"],displayOrder:30},{id:"relationship-report",label:"Relationship Report",route:"/mission-control/relationship-scorecard",icon:Lm,description:"See who needs attention next",primaryCategory:"crm",section:"Contacts",visible:O1("contacts"),searchKeywords:["relationship","scorecard","report"],displayOrder:40},{id:"sphere-gaps",label:"Sphere Gaps",route:"/mission-control/sphere-gaps",icon:pq,description:"Find missing info across your sphere",primaryCategory:"crm",section:"Contacts",visible:O1("contacts"),searchKeywords:["gaps","missing data"],displayOrder:50},{id:"sent-emails",label:"Sent Emails",route:"/mission-control/sent-emails",icon:$r,description:"History of everything you have sent",primaryCategory:"crm",section:"Contacts",visible:O1("contacts"),searchKeywords:["sent","email history"],displayOrder:60},{id:"connect-page",label:"Connect Page",route:"/mission-control/connect-page",icon:ad,description:"Your shareable intake and link page",primaryCategory:"crm",section:"Contacts",visible:O1("contacts"),searchKeywords:["connect","link in bio","intake"],displayOrder:70},{id:"touchplans",label:"TouchPlans",route:"/mission-control/plans",icon:nc,description:"Structured touch plans for your people",primaryCategory:"crm",section:"Follow-Up",visible:O1("contacts"),searchKeywords:["touch plan","follow up plan"],displayOrder:80},{id:"smart-drips",label:"Smart Drips",route:"/mission-control/smart-drips",icon:Af,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:ln,description:"Reusable email templates",primaryCategory:"crm",section:"Follow-Up",searchKeywords:["email template"],displayOrder:100},{id:"signals",label:"Signals",route:"/mission-control/signals",icon:cq,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:Ro,description:"Plan and log in-person pop-bys",primaryCategory:"crm",section:"Follow-Up",visible:O1("popbys"),searchKeywords:["pop by","gifts","drop off"],displayOrder:120},{id:"pipeline",label:"Deal Pipeline",route:"/mission-control/pipeline",icon:P4,description:"Track every deal from lead to close",primaryCategory:"deals",section:"Pipeline",visible:O1("pipeline"),searchKeywords:["pipeline","deals","kanban"],displayOrder:130},{id:"transactions",label:"Transactions",route:"/mission-control/transactions",icon:T4,description:"Closed and in-progress transactions",primaryCategory:"deals",section:"Pipeline",visible:O1("pipeline"),searchKeywords:["transactions","closings"],displayOrder:140},{id:"forms",label:"Forms Library",route:"/mission-control/forms",icon:Iw,description:"Your PDF form templates, filled from any deal",primaryCategory:"deals",section:"Pipeline",visible:O1("pipeline"),searchKeywords:["forms","pdf","templates","contracts","documents"],displayOrder:145},{id:"tasks",label:"Tasks",route:"/mission-control/tasks",icon:t4,description:"Everything on your plate today",primaryCategory:"deals",section:"Pipeline",visible:O1("pipeline"),searchKeywords:["tasks","to do"],displayOrder:150},{id:"scorecard",label:"Scorecard",route:"/mission-control/scorecard",icon:Cl,description:"Your production numbers at a glance",primaryCategory:"deals",section:"Pipeline",visible:O1("scorecard"),searchKeywords:["scorecard","production","goals"],displayOrder:160},{id:"my-calendar",label:"My Calendar",route:"/mission-control/calendar",icon:nc,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:nc,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:_i,description:"Publish and browse member listings",primaryCategory:"listings",section:"Manage Listings",visible:O1("listings"),searchKeywords:["listings","exchange","my listings"],displayOrder:10},{id:"listing-presentation-studio",label:"Listing Presentation Studio",route:"/apps/listing-presentation-studio",icon:hv,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:Xd,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:ra,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:Qw,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:T4,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:pc,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:$c,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:gq,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:"marketing-studio",label:"Marketing Studio",route:"/marketing-studio",icon:pc,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:i1,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:i1,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:Gh,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:Q2,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:ln,description:"Email your whole database at once",primaryCategory:"marketing",section:"Email & Mail",toolId:"mass-emails",searchKeywords:["mass email","campaign","blast"],displayOrder:60},{id:"direct-mail",label:"Direct Mail",route:"/mission-control/direct-mail",icon:$r,description:"Send postcards to your farm",primaryCategory:"marketing",section:"Email & Mail",visible:s=>s.isAdmin,toolId:"direct-mail",searchKeywords:["postcard","direct mail","farming"],displayOrder:70},{id:"card-studio",label:"Card Studio",route:"/mission-control/card-studio",icon:Ro,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:Wr,description:"All of your recorded videos",primaryCategory:"marketing",section:"Video",visible:O1("videos"),searchKeywords:["videos","library"],displayOrder:90},{id:"quickvid",label:"QuickVid",route:"/mission-control/video/record",icon:Wr,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:Gh,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:pv,description:"Capture leads with focused landing pages",primaryCategory:"marketing",section:"Lead Capture",toolId:"landing-pages",searchKeywords:["landing page","lead capture","funnel"],displayOrder:120},{id:"smart-card",label:"Smart Card",route:"/mission-control/my-card",icon:ad,description:"Your digital business card",primaryCategory:"marketing",section:"Lead Capture",toolId:"smart-card",searchKeywords:["digital card","business card","qr"],displayOrder:130},{id:"get-my-website",label:"Get My Website",route:"/get-my-website",icon:fl,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:fl,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:xa,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 Website",route:s=>`/my-website/${s.leadSiteId}/edit`,icon:ri,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:"mls-listings",label:"MLS Listings",route:"/my-website/mls-listings",icon:ra,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:Cl,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:Lm,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:i1,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:cn,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:Kh,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:ig,description:"On-demand training videos",primaryCategory:"academy",section:"Learn",searchKeywords:["academy","videos","training"],displayOrder:20},{id:"toolbox",label:"Toolbox",route:"/toolbox",icon:O4,description:"Scripts, checklists and downloads",primaryCategory:"academy",section:"Learn",searchKeywords:["toolbox","scripts","downloads"],displayOrder:30},{id:"events",label:"Events",route:"/events",icon:BF,description:"Live trainings and member events",primaryCategory:"events",section:"Events",searchKeywords:["events","live","webinar"],displayOrder:10},{id:"programs",label:"Programs",route:"/programs",icon:pv,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:Kh,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:ko,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:Ki,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:eS,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:Sr,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:xq,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:Al,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:Ro,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:sq,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:cn,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:J2,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:J2,description:"Install the LevelUp Chrome extension",primaryCategory:"more",section:"Help & Services",searchKeywords:["extension","chrome"],displayOrder:100},{id:"attract",label:"LevelUp Attract",route:"/attract",icon:cn,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:Ql,description:"Manage members, content and settings",primaryCategory:"more",section:"Admin",visible:s=>s.isAdmin,searchKeywords:["admin"],displayOrder:120},{id:"my-brokerage",label:"My Brokerage",route:"/my-brokerage",icon:_i,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:e4,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:ig,description:"Content shared by your brokerage",primaryCategory:"brokerage",section:"My Brokerage",visible:s=>!!s.brokerageId&&!s.isAdmin,searchKeywords:["brokerage content"],displayOrder:150},{id:"my-team",label:"My Team",route:"/my-team",icon:Bn,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:qc,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:Bn,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:Th,description:"Recruit and nurture agents",primaryCategory:"brokerage",section:"Manage Brokerage",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["recruiting"],displayOrder:190},{id:"brokerage-vendors",label:"Vendors",route:"/brokerage/vendors",icon:a1,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:Ur,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:og,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:cn,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:iy,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 YIt(s,t){return typeof s.route=="function"?s.route(t):s.route}function ZIt(){const{user:s,isAdmin:t,isBrokerageManager:n,isCoach:r,brokerageId:a}=vs(),{hasPermission:i}=Fne(),{isInnerCircleEnabled:l,isMarketplaceEnabled:o,isFeatureEnabled:c}=qne(),{hasAccess:d}=Y6e(),{data:u}=Sj(),{leadSite:h,hasLeadSite:m,siteUrl:p}=$p(),{hasOffer:f}=fMe(!m),x=_S(),{hasAccess:y}=KIt(),v=Qt(),{data:b}=ct({queryKey:["my-coach-nav",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:K}=await q.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1);return(K||[]).length>0}}),{data:N}=ct({queryKey:["user-tool-favorites",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:60*1e3,queryFn:async()=>{const{data:K}=await q.from("user_tool_favorites").select("tool_id").eq("user_id",s.id);return(K||[]).map(Z=>Z.tool_id)}}),S=j.useMemo(()=>new Set(N||[]),[N]),A=yt({mutationFn:async K=>{s!=null&&s.id&&(S.has(K)?await q.from("user_tool_favorites").delete().eq("user_id",s.id).eq("tool_id",K):await q.from("user_tool_favorites").insert({user_id:s.id,tool_id:K}))},onSuccess:()=>{v.invalidateQueries({queryKey:["user-tool-favorites"]}),v.invalidateQueries({queryKey:["app-catalog"]})}}),T=j.useMemo(()=>{var K,Z;return{isAdmin:!!t,isBrokerageManager:!!n,isCoach:!!r,isOnTeam:!!u,hasCoach:!!b,brokerageId:a??null,hasPermission:i,isInnerCircleEnabled:!!l,stagingStudioEnabled:c("staging_studio_enabled"),isMarketplaceEnabled:!!o,hasWeeklyReels:!!d,hasLeadSite:!!m,hasLeadSiteMLS:!!(h!=null&&h.mls_provider_id),hasFreeSiteOffer:!!f,leadSiteId:(h==null?void 0:h.id)??null,siteUrl:p??null,email:(s==null?void 0:s.email)??null,isPartnershipMember:x.isMember,hasCoachingOnboarding:x.isMember&&!!((K=x.pkg)!=null&&K.includes_coaching),hasCoachingAccess:!!y||x.isMember&&!!((Z=x.pkg)!=null&&Z.includes_coaching)}},[t,n,r,u,b,a,i,l,o,c,d,m,h,f,p,s==null?void 0:s.email,x.isMember,x.pkg,y]),L=j.useMemo(()=>w3s.filter(K=>K.visible?K.visible(T):!0).map(K=>{if(!x.isRestricted)return K;const Z=T_s(K);return!Z||x.hasFeature(Z)?K:{...K,locked:!0,route:`/upgrade/${Z}`}}).sort((K,Z)=>K.displayOrder-Z.displayOrder),[T,x.isRestricted,x.features]),M=j.useMemo(()=>gMe.filter(K=>K.visible?K.visible(T):!0),[T]),I=j.useMemo(()=>M.filter(K=>!K.route).map(K=>{const Z=L.filter(ue=>ue.primaryCategory===K.id),Q=[],le=new Map;for(const ue of Z)le.has(ue.section)||(le.set(ue.section,[]),Q.push(ue.section)),le.get(ue.section).push(ue);return{id:K.id,label:K.label,sections:Q.map(ue=>({title:ue,items:le.get(ue)}))}}),[L,M]),R=j.useMemo(()=>new Map(I.map(K=>[K.id,K])),[I]),z=K=>K.toolId||`nav:${K.id}`,$=K=>S.has(z(K));return{ctx:T,categories:I,railCategories:M,categoryMap:R,destinations:L,favorites:S,isFavorite:$,favoritesFor:K=>L.filter(Z=>Z.primaryCategory===K&&$(Z)),favoriteKey:z,toggleFavorite:K=>A.mutate(K),searchDestinations:K=>{const Z=K.trim().toLowerCase();return Z?L.map(le=>{const ue=le.label.toLowerCase(),se=(le.description||"").toLowerCase(),ne=(le.searchKeywords||[]).join(" ").toLowerCase();let ie=0;return ue===Z?ie=100:ue.startsWith(Z)?ie=80:ue.includes(Z)?ie=60:ne.includes(Z)?ie=40:se.includes(Z)?ie=20:le.section.toLowerCase().includes(Z)&&(ie=10),ie&&$(le)&&(ie+=5),{d:le,score:ie}}).filter(le=>le.score>0).sort((le,ue)=>ue.score-le.score).map(le=>le.d):[]},routeFor:K=>YIt(K,T)}}var amt=1,j3s=.9,N3s=.8,k3s=.17,aOe=.1,iOe=.999,S3s=.9999,C3s=.99,A3s=/[\\\/_+.#"@\[\(\{&]/,E3s=/[\\\/_+.#"@\[\(\{&]/g,T3s=/[\s-]/,XIt=/[\s-]/g;function vqe(s,t,n,r,a,i,l){if(i===t.length)return a===s.length?amt:C3s;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,p,f;d>=0;)h=vqe(s,t,n,r,d+1,i+1,l),h>u&&(d===a?h*=amt:A3s.test(s.charAt(d-1))?(h*=N3s,p=s.slice(a,d-1).match(E3s),p&&a>0&&(h*=Math.pow(iOe,p.length))):T3s.test(s.charAt(d-1))?(h*=j3s,f=s.slice(a,d-1).match(XIt),f&&a>0&&(h*=Math.pow(iOe,f.length))):(h*=k3s,a>0&&(h*=Math.pow(iOe,d-a))),s.charAt(d)!==t.charAt(i)&&(h*=S3s)),(hh&&(h=m*aOe)),h>u&&(u=h),d=n.indexOf(c,d+1);return l[o]=u,u}function imt(s){return s.toLowerCase().replace(XIt," ")}function M3s(s,t,n){return s=n&&n.length>0?`${s+" "+n.join(" ")}`:s,vqe(s,t,imt(s),imt(t),0,0,{})}var KK='[cmdk-group=""]',oOe='[cmdk-group-items=""]',P3s='[cmdk-group-heading=""]',QIt='[cmdk-item=""]',omt=`${QIt}:not([aria-disabled="true"])`,bqe="cmdk-item-select",RB="data-value",L3s=(s,t,n)=>M3s(s,t,n),JIt=j.createContext(void 0),Yne=()=>j.useContext(JIt),e8t=j.createContext(void 0),kXe=()=>j.useContext(e8t),t8t=j.createContext(void 0),s8t=j.forwardRef((s,t)=>{let n=DB(()=>{var ie,ce;return{search:"",value:(ce=(ie=s.value)!=null?ie:s.defaultValue)!=null?ce:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=DB(()=>new Set),a=DB(()=>new Map),i=DB(()=>new Map),l=DB(()=>new Set),o=n8t(s),{label:c,children:d,value:u,onValueChange:h,filter:m,shouldFilter:p,loop:f,disablePointerSelection:x=!1,vimBindings:y=!0,...v}=s,b=jx(),N=jx(),S=jx(),A=j.useRef(null),T=V3s();k7(()=>{if(u!==void 0){let ie=u.trim();n.current.value=ie,L.emit()}},[u]),k7(()=>{T(6,H)},[]);let L=j.useMemo(()=>({subscribe:ie=>(l.current.add(ie),()=>l.current.delete(ie)),snapshot:()=>n.current,setState:(ie,ce,je)=>{var be,he,ge,ke;if(!Object.is(n.current[ie],ce)){if(n.current[ie]=ce,ie==="search")$(),R(),T(1,z);else if(ie==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Te=document.getElementById(S);Te?Te.focus():(be=document.getElementById(b))==null||be.focus()}if(T(7,()=>{var Te;n.current.selectedItemId=(Te=V())==null?void 0:Te.id,L.emit()}),je||T(5,H),((he=o.current)==null?void 0:he.value)!==void 0){let Te=ce??"";(ke=(ge=o.current).onValueChange)==null||ke.call(ge,Te);return}}L.emit()}},emit:()=>{l.current.forEach(ie=>ie())}}),[]),M=j.useMemo(()=>({value:(ie,ce,je)=>{var be;ce!==((be=i.current.get(ie))==null?void 0:be.value)&&(i.current.set(ie,{value:ce,keywords:je}),n.current.filtered.items.set(ie,I(ce,je)),T(2,()=>{R(),L.emit()}))},item:(ie,ce)=>(r.current.add(ie),ce&&(a.current.has(ce)?a.current.get(ce).add(ie):a.current.set(ce,new Set([ie]))),T(3,()=>{$(),R(),n.current.value||z(),L.emit()}),()=>{i.current.delete(ie),r.current.delete(ie),n.current.filtered.items.delete(ie);let je=V();T(4,()=>{$(),(je==null?void 0:je.getAttribute("id"))===ie&&z(),L.emit()})}),group:ie=>(a.current.has(ie)||a.current.set(ie,new Set),()=>{i.current.delete(ie),a.current.delete(ie)}),filter:()=>o.current.shouldFilter,label:c||s["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:b,inputId:S,labelId:N,listInnerRef:A}),[]);function I(ie,ce){var je,be;let he=(be=(je=o.current)==null?void 0:je.filter)!=null?be:L3s;return ie?he(ie,n.current.search,ce):0}function R(){if(!n.current.search||o.current.shouldFilter===!1)return;let ie=n.current.filtered.items,ce=[];n.current.filtered.groups.forEach(be=>{let he=a.current.get(be),ge=0;he.forEach(ke=>{let Te=ie.get(ke);ge=Math.max(Te,ge)}),ce.push([be,ge])});let je=A.current;K().sort((be,he)=>{var ge,ke;let Te=be.getAttribute("id"),Me=he.getAttribute("id");return((ge=ie.get(Me))!=null?ge:0)-((ke=ie.get(Te))!=null?ke:0)}).forEach(be=>{let he=be.closest(oOe);he?he.appendChild(be.parentElement===he?be:be.closest(`${oOe} > *`)):je.appendChild(be.parentElement===je?be:be.closest(`${oOe} > *`))}),ce.sort((be,he)=>he[1]-be[1]).forEach(be=>{var he;let ge=(he=A.current)==null?void 0:he.querySelector(`${KK}[${RB}="${encodeURIComponent(be[0])}"]`);ge==null||ge.parentElement.appendChild(ge)})}function z(){let ie=K().find(je=>je.getAttribute("aria-disabled")!=="true"),ce=ie==null?void 0:ie.getAttribute(RB);L.setState("value",ce||void 0)}function $(){var ie,ce,je,be;if(!n.current.search||o.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let he=0;for(let ge of r.current){let ke=(ce=(ie=i.current.get(ge))==null?void 0:ie.value)!=null?ce:"",Te=(be=(je=i.current.get(ge))==null?void 0:je.keywords)!=null?be:[],Me=I(ke,Te);n.current.filtered.items.set(ge,Me),Me>0&&he++}for(let[ge,ke]of a.current)for(let Te of ke)if(n.current.filtered.items.get(Te)>0){n.current.filtered.groups.add(ge);break}n.current.filtered.count=he}function H(){var ie,ce,je;let be=V();be&&(((ie=be.parentElement)==null?void 0:ie.firstChild)===be&&((je=(ce=be.closest(KK))==null?void 0:ce.querySelector(P3s))==null||je.scrollIntoView({block:"nearest"})),be.scrollIntoView({block:"nearest"}))}function V(){var ie;return(ie=A.current)==null?void 0:ie.querySelector(`${QIt}[aria-selected="true"]`)}function K(){var ie;return Array.from(((ie=A.current)==null?void 0:ie.querySelectorAll(omt))||[])}function Z(ie){let ce=K()[ie];ce&&L.setState("value",ce.getAttribute(RB))}function Q(ie){var ce;let je=V(),be=K(),he=be.findIndex(ke=>ke===je),ge=be[he+ie];(ce=o.current)!=null&&ce.loop&&(ge=he+ie<0?be[be.length-1]:he+ie===be.length?be[0]:be[he+ie]),ge&&L.setState("value",ge.getAttribute(RB))}function le(ie){let ce=V(),je=ce==null?void 0:ce.closest(KK),be;for(;je&&!be;)je=ie>0?q3s(je,KK):$3s(je,KK),be=je==null?void 0:je.querySelector(omt);be?L.setState("value",be.getAttribute(RB)):Q(ie)}let ue=()=>Z(K().length-1),se=ie=>{ie.preventDefault(),ie.metaKey?ue():ie.altKey?le(1):Q(1)},ne=ie=>{ie.preventDefault(),ie.metaKey?Z(0):ie.altKey?le(-1):Q(-1)};return j.createElement(si.div,{ref:t,tabIndex:-1,...v,"cmdk-root":"",onKeyDown:ie=>{var ce;(ce=v.onKeyDown)==null||ce.call(v,ie);let je=ie.nativeEvent.isComposing||ie.keyCode===229;if(!(ie.defaultPrevented||je))switch(ie.key){case"n":case"j":{y&&ie.ctrlKey&&se(ie);break}case"ArrowDown":{se(ie);break}case"p":case"k":{y&&ie.ctrlKey&&ne(ie);break}case"ArrowUp":{ne(ie);break}case"Home":{ie.preventDefault(),Z(0);break}case"End":{ie.preventDefault(),ue();break}case"Enter":{ie.preventDefault();let be=V();if(be){let he=new Event(bqe);be.dispatchEvent(he)}}}}},j.createElement("label",{"cmdk-label":"",htmlFor:M.inputId,id:M.labelId,style:G3s},c),xMe(s,ie=>j.createElement(e8t.Provider,{value:L},j.createElement(JIt.Provider,{value:M},ie))))}),I3s=j.forwardRef((s,t)=>{var n,r;let a=jx(),i=j.useRef(null),l=j.useContext(t8t),o=Yne(),c=n8t(s),d=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:l==null?void 0:l.forceMount;k7(()=>{if(!d)return o.item(a,l==null?void 0:l.id)},[d]);let u=r8t(a,i,[s.value,s.children,i],s.keywords),h=kXe(),m=dP(T=>T.value&&T.value===u.current),p=dP(T=>d||o.filter()===!1?!0:T.search?T.filtered.items.get(a)>0:!0);j.useEffect(()=>{let T=i.current;if(!(!T||s.disabled))return T.addEventListener(bqe,f),()=>T.removeEventListener(bqe,f)},[p,s.onSelect,s.disabled]);function f(){var T,L;x(),(L=(T=c.current).onSelect)==null||L.call(T,u.current)}function x(){h.setState("value",u.current,!0)}if(!p)return null;let{disabled:y,value:v,onSelect:b,forceMount:N,keywords:S,...A}=s;return j.createElement(si.div,{ref:eE(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:f},s.children)}),R3s=j.forwardRef((s,t)=>{let{heading:n,children:r,forceMount:a,...i}=s,l=jx(),o=j.useRef(null),c=j.useRef(null),d=jx(),u=Yne(),h=dP(p=>a||u.filter()===!1?!0:p.search?p.filtered.groups.has(l):!0);k7(()=>u.group(l),[]),r8t(l,o,[s.value,s.heading,c]);let m=j.useMemo(()=>({id:l,forceMount:a}),[a]);return j.createElement(si.div,{ref:eE(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),xMe(s,p=>j.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?d:void 0},j.createElement(t8t.Provider,{value:m},p))))}),D3s=j.forwardRef((s,t)=>{let{alwaysRender:n,...r}=s,a=j.useRef(null),i=dP(l=>!l.search);return!n&&!i?null:j.createElement(si.div,{ref:eE(a,t),...r,"cmdk-separator":"",role:"separator"})}),O3s=j.forwardRef((s,t)=>{let{onValueChange:n,...r}=s,a=s.value!=null,i=kXe(),l=dP(d=>d.search),o=dP(d=>d.selectedItemId),c=Yne();return j.useEffect(()=>{s.value!=null&&i.setState("search",s.value)},[s.value]),j.createElement(si.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)}})}),F3s=j.forwardRef((s,t)=>{let{children:n,label:r="Suggestions",...a}=s,i=j.useRef(null),l=j.useRef(null),o=dP(d=>d.selectedItemId),c=Yne();return j.useEffect(()=>{if(l.current&&i.current){let d=l.current,u=i.current,h,m=new ResizeObserver(()=>{h=requestAnimationFrame(()=>{let p=d.offsetHeight;u.style.setProperty("--cmdk-list-height",p.toFixed(1)+"px")})});return m.observe(d),()=>{cancelAnimationFrame(h),m.unobserve(d)}}},[]),j.createElement(si.div,{ref:eE(i,t),...a,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":r,id:c.listId},xMe(s,d=>j.createElement("div",{ref:eE(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),z3s=j.forwardRef((s,t)=>{let{open:n,onOpenChange:r,overlayClassName:a,contentClassName:i,container:l,...o}=s;return j.createElement(k6e,{open:n,onOpenChange:r},j.createElement(S6e,{container:l},j.createElement(rG,{"cmdk-overlay":"",className:a}),j.createElement(aG,{"aria-label":s.label,"cmdk-dialog":"",className:i},j.createElement(s8t,{ref:t,...o}))))}),B3s=j.forwardRef((s,t)=>dP(n=>n.filtered.count===0)?j.createElement(si.div,{ref:t,...s,"cmdk-empty":"",role:"presentation"}):null),U3s=j.forwardRef((s,t)=>{let{progress:n,children:r,label:a="Loading...",...i}=s;return j.createElement(si.div,{ref:t,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":a},xMe(s,l=>j.createElement("div",{"aria-hidden":!0},l)))}),D_=Object.assign(s8t,{List:F3s,Item:I3s,Input:O3s,Group:R3s,Separator:D3s,Dialog:z3s,Empty:B3s,Loading:U3s});function q3s(s,t){let n=s.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function $3s(s,t){let n=s.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function n8t(s){let t=j.useRef(s);return k7(()=>{t.current=s}),t}var k7=typeof window>"u"?j.useEffect:j.useLayoutEffect;function DB(s){let t=j.useRef();return t.current===void 0&&(t.current=s()),t}function dP(s){let t=kXe(),n=()=>s(t.snapshot());return j.useSyncExternalStore(t.subscribe,n,n)}function r8t(s,t,n,r=[]){let a=j.useRef(),i=Yne();return k7(()=>{var l;let o=(()=>{var d;for(let u of n){if(typeof u=="string")return u.trim();if(typeof u=="object"&&"current"in u)return u.current?(d=u.current.textContent)==null?void 0:d.trim():a.current}})(),c=r.map(d=>d.trim());i.value(s,o,c),(l=t.current)==null||l.setAttribute(RB,o),a.current=o}),a}var V3s=()=>{let[s,t]=j.useState(),n=DB(()=>new Map);return k7(()=>{n.current.forEach(r=>r()),n.current=new Map},[s]),(r,a)=>{n.current.set(r,a),t({})}};function H3s(s){let t=s.type;return typeof t=="function"?t(s.props):"render"in t?t.render(s.props):s}function xMe({asChild:s,children:t},n){return s&&j.isValidElement(t)?j.cloneElement(H3s(t),{ref:t.ref},n(t.props.children)):n(t)}var G3s={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const pj=j.forwardRef(({className:s,...t},n)=>e.jsx(D_,{ref:n,className:Mt("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",s),...t}));pj.displayName=D_.displayName;const W3s=({children:s,...t})=>e.jsx(zs,{...t,children:e.jsx(Ds,{className:"overflow-hidden p-0 shadow-lg",children:e.jsx(pj,{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})})}),fj=j.forwardRef(({className:s,...t},n)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(Fr,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(D_.Input,{ref:n,className:Mt("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})]}));fj.displayName=D_.Input.displayName;const gj=j.forwardRef(({className:s,...t},n)=>e.jsx(D_.List,{ref:n,className:Mt("max-h-[300px] overflow-y-auto overflow-x-hidden",s),...t}));gj.displayName=D_.List.displayName;const xj=j.forwardRef((s,t)=>e.jsx(D_.Empty,{ref:t,className:"py-6 text-center text-sm",...s}));xj.displayName=D_.Empty.displayName;const I_=j.forwardRef(({className:s,...t},n)=>e.jsx(D_.Group,{ref:n,className:Mt("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}));I_.displayName=D_.Group.displayName;const K3s=j.forwardRef(({className:s,...t},n)=>e.jsx(D_.Separator,{ref:n,className:Mt("-mx-1 h-px bg-border",s),...t}));K3s.displayName=D_.Separator.displayName;const e1=j.forwardRef(({className:s,...t},n)=>e.jsx(D_.Item,{ref:n,className:Mt("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}));e1.displayName=D_.Item.displayName;const Y3s={event:{label:"Events",icon:nc,color:"bg-blue-500/10 text-blue-600"},template:{label:"Templates",icon:$c,color:"bg-purple-500/10 text-purple-600"},academy:{label:"Academy",icon:Kh,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:O4,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:cn,color:"bg-fuchsia-500/10 text-fuchsia-600"}},lmt=()=>{const[s,t]=j.useState(!1),[n,r]=j.useState(""),[a,i]=j.useState([]),[l,o]=j.useState(!1),c=Wn(),{searchDestinations:d,isFavorite:u,routeFor:h}=ZIt(),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 p=j.useCallback(async y=>{if(!y.trim()){i([]);return}o(!0);const v=`%${y}%`;try{const[b,N,S,A,T]=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)]),L=[];b.data&&b.data.forEach(M=>{L.push({id:M.id,title:M.title,description:M.description,type:"event",date:M.event_date,path:`/event/${M.id}`})}),N.data&&N.data.forEach(M=>{L.push({id:M.id,title:M.name,description:M.description,type:"template",date:M.publish_date,path:`/templates/${M.id}`})}),S.data&&S.data.forEach(M=>{L.push({id:M.id,title:M.title,description:M.description,type:"academy",date:M.publish_date,path:`/academy/${M.id}`})}),A.data&&A.data.forEach(M=>{L.push({id:M.id,title:M.name,description:M.description,type:"toolbox",date:M.publish_date,path:`/toolbox/${M.id}`})}),T.data&&T.data.forEach(M=>{L.push({id:M.id,title:M.title,description:M.description,type:"social-swag",date:M.publish_date,path:`/social-swag/${M.id}`})}),i(L)}catch(b){console.error("Search error:",b)}finally{o(!1)}},[]);j.useEffect(()=>{const y=setTimeout(()=>{p(n)},300);return()=>clearTimeout(y)},[n,p]);const f=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(U,{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(Fr,{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(W3s,{open:s,onOpenChange:t,children:[e.jsx(fj,{placeholder:"Search events, templates, academy, toolbox, social swag...",value:n,onValueChange:r}),e.jsxs(gj,{children:[m.length>0&&e.jsx(I_,{heading:"Go to",children:m.map(y=>{const v=y.icon;return e.jsxs(e1,{value:`nav-${y.id}-${y.label}`,onSelect:()=>{const b=h(y);y.external||y.openInNewTab?(t(!1),r(""),window.open(b,"_blank","noopener,noreferrer")):f(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(u0,{className:"h-3 w-3 fill-current text-primary"})]}),y.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate",children:y.description})]}),e.jsx(Be,{variant:"secondary",className:"text-xs shrink-0",children:y.section})]},`nav-${y.id}`)})}),l&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Searching..."}),!l&&n&&a.length===0&&m.length===0&&e.jsxs(xj,{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=Y3s[y],N=b.icon;return e.jsx(I_,{heading:b.label,children:v.map(S=>e.jsxs(e1,{value:`${S.type}-${S.id}-${S.title}`,onSelect:()=>f(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(N,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:S.title}),S.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate group-data-[selected=true]:text-primary-foreground/80",children:S.description})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[e.jsx(Be,{variant:"secondary",className:"text-xs",children:b.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Nd(new Date(S.date),{addSuffix:!0})})]})]},`${S.type}-${S.id}`))},y)})]})]})]})},Z3s=({expiresAt:s,className:t,showUpgradeButton:n=!0})=>{const[r,a]=j.useState(null),i=Wn();if(j.useEffect(()=>{const d=()=>{const h=new Date().getTime(),p=new Date(s).getTime()-h;if(p<=0){a({days:0,hours:0,minutes:0});return}const f=Math.floor(p/(1e3*60*60*24)),x=Math.floor(p%(1e3*60*60*24)/(1e3*60*60)),y=Math.floor(p%(1e3*60*60)/(1e3*60));a({days:f,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:Mt("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(tc,{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(U,{size:"sm",onClick:()=>i("/subscription"),className:"bg-primary hover:bg-primary/90 text-xs h-7 px-3",children:[e.jsx(cn,{className:"h-3 w-3 mr-1"}),"Upgrade Now"]})]}):e.jsxs("div",{className:Mt("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(Yr,{className:Mt("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:Mt("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:Mt("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.days,"d"]}),e.jsxs("span",{className:Mt("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.hours,"h"]}),e.jsxs("span",{className:Mt("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.minutes,"m"]}),e.jsx("span",{className:Mt("text-xs",o?"text-destructive/70":c?"text-amber-600/70":"text-primary/70"),children:"remaining"})]})]})]}),n&&e.jsxs(U,{size:"sm",onClick:()=>i("/subscription"),variant:o?"destructive":c?"default":"outline",className:Mt("text-xs h-7 px-3",c&&"bg-amber-500 hover:bg-amber-600 text-white"),children:[e.jsx(cn,{className:"h-3 w-3 mr-1"}),"Upgrade"]})]})},X3s=()=>{const s=Wn();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(we,{className:"w-full max-w-2xl shadow-2xl border-destructive/20 my-8",children:[e.jsxs(Tt,{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(tc,{className:"h-8 w-8 text-destructive"})}),e.jsx(It,{className:"text-2xl",children:"Your Free Trial Has Ended"}),e.jsx(Jn,{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(we,{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(Bn,{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(U,{className:"w-full",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Choose Individual"]})]})}),e.jsx(we,{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(_i,{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(U,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(_i,{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(ba,{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(ln,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})]})]})})},Q3s=({hasUnseenBrief:s,onClick:t,className:n})=>e.jsxs(Bg,{children:[e.jsx(Ug,{asChild:!0,children:e.jsxs(U,{variant:"ghost",size:"icon",onClick:t,className:Mt("relative transition-colors",s&&"text-primary hover:text-primary",n),children:[e.jsx(Th,{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(ng,{children:e.jsx("p",{children:"The LevelUp Brief"})})]});var yMe="Checkbox",[J3s,pgr]=Up(yMe),[eCs,SXe]=J3s(yMe);function tCs(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,p]=Sx({prop:n,defaultProp:a??!1,onChange:c,caller:yMe}),[f,x]=j.useState(null),[y,v]=j.useState(null),b=j.useRef(!1),N=f?!!l||!!f.closest("form"):!0,S={checked:m,disabled:i,setChecked:p,control:f,setControl:x,name:o,form:l,value:u,hasConsumerStoppedPropagationRef:b,required:d,defaultChecked:BM(a)?!1:a,isFormControl:N,bubbleInput:y,setBubbleInput:v};return e.jsx(eCs,{scope:t,...S,children:sCs(h)?h(S):r})}var a8t="CheckboxTrigger",i8t=j.forwardRef(({__scopeCheckbox:s,onKeyDown:t,onClick:n,...r},a)=>{const{control:i,value:l,disabled:o,checked:c,required:d,setControl:u,setChecked:h,hasConsumerStoppedPropagationRef:m,isFormControl:p,bubbleInput:f}=SXe(a8t,s),x=Uo(a,u),y=j.useRef(c);return j.useEffect(()=>{const v=i==null?void 0:i.form;if(v){const b=()=>h(y.current);return v.addEventListener("reset",b),()=>v.removeEventListener("reset",b)}},[i,h]),e.jsx(si.button,{type:"button",role:"checkbox","aria-checked":BM(c)?"mixed":c,"aria-required":d,"data-state":u8t(c),"data-disabled":o?"":void 0,disabled:o,value:l,...r,ref:x,onKeyDown:va(t,v=>{v.key==="Enter"&&v.preventDefault()}),onClick:va(n,v=>{h(b=>BM(b)?!0:!b),f&&p&&(m.current=v.isPropagationStopped(),m.current||v.stopPropagation())})})});i8t.displayName=a8t;var CXe=j.forwardRef((s,t)=>{const{__scopeCheckbox:n,name:r,checked:a,defaultChecked:i,required:l,disabled:o,value:c,onCheckedChange:d,form:u,...h}=s;return e.jsx(tCs,{__scopeCheckbox:n,checked:a,defaultChecked:i,disabled:o,required:l,onCheckedChange:d,name:r,form:u,value:c,internal_do_not_use_render:({isFormControl:m})=>e.jsxs(e.Fragment,{children:[e.jsx(i8t,{...h,ref:t,__scopeCheckbox:n}),m&&e.jsx(d8t,{__scopeCheckbox:n})]})})});CXe.displayName=yMe;var o8t="CheckboxIndicator",l8t=j.forwardRef((s,t)=>{const{__scopeCheckbox:n,forceMount:r,...a}=s,i=SXe(o8t,n);return e.jsx(Xg,{present:r||BM(i.checked)||i.checked===!0,children:e.jsx(si.span,{"data-state":u8t(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t,style:{pointerEvents:"none",...s.style}})})});l8t.displayName=o8t;var c8t="CheckboxBubbleInput",d8t=j.forwardRef(({__scopeCheckbox:s,...t},n)=>{const{control:r,hasConsumerStoppedPropagationRef:a,checked:i,defaultChecked:l,required:o,disabled:c,name:d,value:u,form:h,bubbleInput:m,setBubbleInput:p}=SXe(c8t,s),f=Uo(n,p),x=Wne(i),y=Mne(r);j.useEffect(()=>{const b=m;if(!b)return;const N=window.HTMLInputElement.prototype,A=Object.getOwnPropertyDescriptor(N,"checked").set,T=!a.current;if(x!==i&&A){const L=new Event("click",{bubbles:T});b.indeterminate=BM(i),A.call(b,BM(i)?!1:i),b.dispatchEvent(L)}},[m,x,i,a]);const v=j.useRef(BM(i)?!1:i);return e.jsx(si.input,{type:"checkbox","aria-hidden":!0,defaultChecked:l??v.current,required:o,disabled:c,name:d,value:u,form:h,...t,tabIndex:-1,ref:f,style:{...t.style,...y,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});d8t.displayName=c8t;function sCs(s){return typeof s=="function"}function BM(s){return s==="indeterminate"}function u8t(s){return BM(s)?"indeterminate":s?"checked":"unchecked"}const xi=j.forwardRef(({className:s,...t},n)=>e.jsx(CXe,{ref:n,className:Mt("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(l8t,{className:Mt("flex items-center justify-center text-current"),children:e.jsx(Xr,{className:"h-4 w-4"})})}));xi.displayName=CXe.displayName;var AXe="Radio",[nCs,h8t]=Up(AXe),[rCs,aCs]=nCs(AXe),m8t=j.forwardRef((s,t)=>{const{__scopeRadio:n,name:r,checked:a=!1,required:i,disabled:l,value:o="on",onCheck:c,form:d,...u}=s,[h,m]=j.useState(null),p=Uo(t,y=>m(y)),f=j.useRef(!1),x=h?d||!!h.closest("form"):!0;return e.jsxs(rCs,{scope:n,checked:a,disabled:l,children:[e.jsx(si.button,{type:"button",role:"radio","aria-checked":a,"data-state":x8t(a),"data-disabled":l?"":void 0,disabled:l,value:o,...u,ref:p,onClick:va(s.onClick,y=>{a||c==null||c(),x&&(f.current=y.isPropagationStopped(),f.current||y.stopPropagation())})}),x&&e.jsx(g8t,{control:h,bubbles:!f.current,name:r,value:o,checked:a,required:i,disabled:l,form:d,style:{transform:"translateX(-100%)"}})]})});m8t.displayName=AXe;var p8t="RadioIndicator",f8t=j.forwardRef((s,t)=>{const{__scopeRadio:n,forceMount:r,...a}=s,i=aCs(p8t,n);return e.jsx(Xg,{present:r||i.checked,children:e.jsx(si.span,{"data-state":x8t(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t})})});f8t.displayName=p8t;var iCs="RadioBubbleInput",g8t=j.forwardRef(({__scopeRadio:s,control:t,checked:n,bubbles:r=!0,...a},i)=>{const l=j.useRef(null),o=Uo(l,i),c=Wne(n),d=Mne(t);return j.useEffect(()=>{const u=l.current;if(!u)return;const h=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(h,"checked").set;if(c!==n&&p){const f=new Event("click",{bubbles:r});p.call(u,n),u.dispatchEvent(f)}},[c,n,r]),e.jsx(si.input,{type:"radio","aria-hidden":!0,defaultChecked:n,...a,tabIndex:-1,ref:o,style:{...a.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});g8t.displayName=iCs;function x8t(s){return s?"checked":"unchecked"}var oCs=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],vMe="RadioGroup",[lCs,fgr]=Up(vMe,[DP,h8t]),y8t=DP(),v8t=h8t(),[cCs,dCs]=lCs(vMe),b8t=j.forwardRef((s,t)=>{const{__scopeRadioGroup:n,name:r,defaultValue:a,value:i,required:l=!1,disabled:o=!1,orientation:c,dir:d,loop:u=!0,onValueChange:h,...m}=s,p=y8t(n),f=xE(d),[x,y]=Sx({prop:i,defaultProp:a??null,onChange:h,caller:vMe});return e.jsx(cCs,{scope:n,name:r,required:l,disabled:o,value:x,onValueChange:y,children:e.jsx(V6e,{asChild:!0,...p,orientation:c,dir:f,loop:u,children:e.jsx(si.div,{role:"radiogroup","aria-required":l,"aria-orientation":c,"data-disabled":o?"":void 0,dir:f,...m,ref:t})})})});b8t.displayName=vMe;var _8t="RadioGroupItem",w8t=j.forwardRef((s,t)=>{const{__scopeRadioGroup:n,disabled:r,...a}=s,i=dCs(_8t,n),l=i.disabled||r,o=y8t(n),c=v8t(n),d=j.useRef(null),u=Uo(t,d),h=i.value===a.value,m=j.useRef(!1);return j.useEffect(()=>{const p=x=>{oCs.includes(x.key)&&(m.current=!0)},f=()=>m.current=!1;return document.addEventListener("keydown",p),document.addEventListener("keyup",f),()=>{document.removeEventListener("keydown",p),document.removeEventListener("keyup",f)}},[]),e.jsx(H6e,{asChild:!0,...o,focusable:!l,active:h,children:e.jsx(m8t,{disabled:l,required:i.required,checked:h,...c,...a,name:i.name,ref:u,onCheck:()=>i.onValueChange(a.value),onKeyDown:va(p=>{p.key==="Enter"&&p.preventDefault()}),onFocus:va(a.onFocus,()=>{var p;m.current&&((p=d.current)==null||p.click())})})})});w8t.displayName=_8t;var uCs="RadioGroupIndicator",j8t=j.forwardRef((s,t)=>{const{__scopeRadioGroup:n,...r}=s,a=v8t(n);return e.jsx(f8t,{...a,...r,ref:t})});j8t.displayName=uCs;var N8t=b8t,k8t=w8t,hCs=j8t;const y_=j.forwardRef(({className:s,...t},n)=>e.jsx(N8t,{className:Mt("grid gap-2",s),...t,ref:n}));y_.displayName=N8t.displayName;const Fh=j.forwardRef(({className:s,...t},n)=>e.jsx(k8t,{ref:n,className:Mt("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(hCs,{className:"flex items-center justify-center",children:e.jsx(Nf,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Fh.displayName=k8t.displayName;const mCs=({brief:s,open:t,onClose:n,onDismiss:r})=>{const{user:a}=vs(),[i,l]=j.useState({}),[o,c]=j.useState({}),[d,u]=j.useState([]);j.useEffect(()=>{t&&a&&s.polls.length>0&&h()},[t,a,s.polls]);const h=async()=>{if(!a)return;const y=s.polls.map(b=>b.id),{data:v}=await q.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",a.id).in("poll_id",y);if(v){const b={};v.forEach(N=>{b[N.poll_id]||(b[N.poll_id]=[]),b[N.poll_id].push(N.option_id)}),c(b)}},m=(y,v)=>{l(b=>({...b,[y]:v}))},p=(y,v,b)=>{l(N=>{const S=N[y]||[];return b?{...N,[y]:[...S,v]}:{...N,[y]:S.filter(A=>A!==v)}})},f=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],N=b.map(A=>({poll_id:y,option_id:A,user_id:a.id})),{error:S}=await q.from("levelup_brief_poll_responses").insert(N);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(N=>N!==y))}},x=y=>(y.includes("mediadelivery.net")||y.includes("bunny"),y);return e.jsx(zs,{open:t,onOpenChange:y=>!y&&n(),children:e.jsxs(Ds,{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(er,{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(Th,{className:"h-6 w-6"})}),e.jsxs("div",{children:[e.jsx(Be,{variant:"secondary",className:"mb-1 bg-white/20 text-white border-0",children:"The LevelUp Brief"}),e.jsx($s,{className:"text-xl font-bold text-white",children:s.brief.title})]})]})]}),e.jsx(Gi,{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(U,{variant:"outline",size:"sm",onClick:()=>window.open(y.url,"_blank"),className:"gap-2",children:[e.jsx(Sr,{className:"h-4 w-4"}),y.title]},y.id))})]}),s.polls.map(y=>{var N,S;const v=((N=o[y.id])==null?void 0:N.length)>0,b=d.includes(y.id);return e.jsxs("div",{className:"space-y-3 p-4 bg-muted/50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"font-semibold text-foreground",children:y.question}),v&&e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(zr,{className:"h-3 w-3"}),"Responded"]})]}),y.poll_type==="single"?e.jsx(y_,{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(Fh,{value:A.id,id:A.id}),e.jsx(te,{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 L=(i[y.id]||o[y.id]||[]).includes(A.id);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(xi,{id:A.id,checked:L,onCheckedChange:M=>p(y.id,A.id,M)}),e.jsx(te,{htmlFor:A.id,className:"cursor-pointer",children:A.option_text})]},A.id)})}),e.jsx(U,{size:"sm",onClick:()=>f(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(U,{onClick:n,className:"w-full max-w-xs",children:"Got it!"}),e.jsx(U,{variant:"ghost",size:"sm",onClick:r,children:"Don't show again"})]})]})})},pCs=()=>{const{user:s}=vs(),[t,n]=j.useState(null),[r,a]=j.useState(!1),[i,l]=j.useState(!0),[o,c]=j.useState(!1),d=j.useCallback(async()=>{if(!s){l(!1);return}try{const{data:f,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||!f){l(!1);return}const{data:y}=await q.from("levelup_brief_views").select("*").eq("brief_id",f.id).eq("user_id",s.id).maybeSingle(),[v,b]=await Promise.all([q.from("levelup_brief_links").select("*").eq("brief_id",f.id).order("sort_order"),q.from("levelup_brief_polls").select("*").eq("brief_id",f.id).order("sort_order")]),N=[];if(b.data)for(const M of b.data){const{data:I}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",M.id).order("sort_order");N.push({...M,options:I||[]})}const S={brief:f,links:v.data||[],polls:N};n(S);const A=!!y,T=(y==null?void 0:y.dismissed_at)!=null,L=localStorage.getItem(`brief-dismissed-${f.id}`)==="true";if(T||L)c(!1),a(!1);else if(!A)a(!0),c(!0);else if(f.show_frequency==="every_login")a(!0),c(!0);else if(f.show_frequency==="daily"){const M=new Date(y.viewed_at);(new Date().getTime()-M.getTime())/(1e3*60*60)>=24&&(a(!0),c(!0))}else c(!1)}catch(f){console.error("Error fetching brief:",f)}finally{l(!1)}},[s]);j.useEffect(()=>{d()},[d]);const u=async()=>{if(!(!s||!t))try{const{data:f}=await q.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();f?await q.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",f.id):await q.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id})}catch(f){console.error("Error marking brief as viewed:",f)}};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:f,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),f){const{error:y}=await q.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",f.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(f){console.error("Error dismissing brief:",f),t&&localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}}},refetch:d}};function fCs(){const[s,t]=j.useState(!1),[n,r]=j.useState(!1),[a,i]=j.useState(null);j.useEffect(()=>{if(localStorage.getItem("install-banner-dismissed")||window.matchMedia("(display-mode: standalone)").matches||!/iPhone|iPad|iPod|Android/i.test(navigator.userAgent))return;const h=/iPhone|iPad|iPod/i.test(navigator.userAgent);r(h),t(!0);const m=p=>{p.preventDefault(),i(p)};return window.addEventListener("beforeinstallprompt",m),()=>{window.removeEventListener("beforeinstallprompt",m)}},[]);const l=()=>{localStorage.setItem("install-banner-dismissed","true"),t(!1)},o=async()=>{if(a){await a.prompt();const{outcome:c}=await a.userChoice;c==="accepted"&&l(),i(null)}};return s?e.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-50 p-4 bg-primary text-primary-foreground shadow-lg animate-in slide-in-from-bottom duration-300",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:"flex-shrink-0 p-2 bg-primary-foreground/10 rounded-full",children:e.jsx(pi,{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(oQ,{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(U,{size:"sm",variant:"secondary",onClick:o,className:"text-xs",children:"Install"}),e.jsx("button",{onClick:l,className:"p-1.5 hover:bg-primary-foreground/10 rounded-full transition-colors","aria-label":"Dismiss",children:e.jsx(er,{className:"h-4 w-4"})})]})]})}):null}const gCs=({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=Qt(),h=80,m=120,p=j.useCallback(b=>{const N=c.current;N&&N.scrollTop<=0&&(d.current=b.touches[0].clientY,r(!0))},[]),f=j.useCallback(b=>{if(!n||l)return;const N=c.current;if(!N||N.scrollTop>0){r(!1),i(0);return}const A=b.touches[0].clientY-d.current;if(A>0){const L=Math.min(A*.5,m);i(L),L>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:p,onTouchMove:f,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(no,{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})]})},S8t=()=>{const{user:s}=vs(),[t,n]=j.useState(!1),[r,a]=j.useState(!1),[i,l]=j.useState(0),[o,c]=j.useState(!0);j.useEffect(()=>{(async()=>{if(!s){c(!1);return}try{const{data:p}=await q.from("membership_reviews").select("id").eq("user_id",s.id).maybeSingle();if(p){a(!0),n(!1),c(!1);return}const{data:f}=await q.from("profiles").select("login_count").eq("id",s.id).single(),x=(f==null?void 0:f.login_count)||0;l(x);const y=sessionStorage.getItem("review-prompt-dismissed");n(x>=4&&!y)}catch(p){console.error("Error checking review eligibility:",p)}finally{c(!1)}})()},[s]);const d=j.useCallback(()=>{sessionStorage.setItem("review-prompt-dismissed","true"),n(!1)},[]),u=j.useCallback(async(m,p)=>{if(!s)return{success:!1,error:"Not authenticated"};try{const{error:f}=await q.from("membership_reviews").insert({user_id:s.id,rating:m,review_text:p});if(f)throw f;return a(!0),n(!1),{success:!0,pointsAwarded:25}}catch(f){return console.error("Error submitting review:",f),{success:!1,error:f.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}},xCs="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",yCs=()=>{const{shouldShowPrompt:s,isLoading:t,dismissPrompt:n,submitReview:r,markPostedToGoogle:a}=S8t(),[i,l]=j.useState(!1),[o,c]=j.useState("review"),[d,u]=j.useState(0),[h,m]=j.useState(0),[p,f]=j.useState(""),[x,y]=j.useState(!1),[v,b]=j.useState(!1);if(t||!s&&!v)return null;const N=async()=>{if(d===0){ka({title:"Please select a rating",variant:"destructive"});return}y(!0);const T=await r(d,p);y(!1),T.success?(b(!0),ka({title:"Thank you for your feedback!",description:"Your review helps us improve."}),c("google")):ka({title:"Error submitting review",description:T.error,variant:"destructive"})},S=async T=>{T&&(await navigator.clipboard.writeText(p||`${d} star rating for LevelUp!`),ka({title:"Review copied!",description:"Paste it on Google Reviews."}),await a(),window.open(xCs,"_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(Ua,{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(Ds,{className:"sm:max-w-md",children:o==="review"?e.jsxs(e.Fragment,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(T=>e.jsx("button",{type:"button",onClick:()=>u(T),onMouseEnter:()=>m(T),onMouseLeave:()=>m(0),className:"p-1 transition-transform hover:scale-110",children:e.jsx(Ua,{className:Mt("h-8 w-8 transition-colors",(h||d)>=T?"fill-yellow-400 text-yellow-400":"text-muted-foreground")})},T))}),e.jsx(Fs,{placeholder:"Tell us about your experience (optional)",value:p,onChange:T=>f(T.target.value),rows:4,className:"resize-none"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{variant:"outline",onClick:A,className:"flex-1",children:"Maybe Later"}),e.jsx(U,{onClick:N,disabled:x||d===0,className:"flex-1",children:x?"Submitting...":"Submit Review"})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(U,{variant:"outline",onClick:()=>S(!1),className:"flex-1",children:"No Thanks"}),e.jsx(U,{onClick:()=>S(!0),className:"flex-1",children:"Yes, Open Google"})]})]})]})})})]})};function vCs(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:N,error:S}=await q.functions.invoke("get-vapid-public-key",{body:{}});if(S)throw S;if(y=(N==null?void 0:N.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 f=await o.pushManager.getSubscription();if(f){try{await f.unsubscribe()}catch(S){console.warn("Failed to unsubscribe existing push subscription:",S)}const{error:N}=await q.from("push_subscriptions").delete().eq("user_id",s.id);N&&console.warn("Failed to cleanup push_subscriptions rows:",N)}if(Notification.permission!=="granted"){const N=await Notification.requestPermission();if(n(N),N!=="granted")return N==="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=vCs(d);let y;try{y=await o.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:x})}catch(N){console.error("PushManager.subscribe() failed:",N);const S=(N==null?void 0:N.message)||String(N);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(f){if(console.error("Error subscribing to push notifications:",f),!(f instanceof Error&&f.message.includes("toast"))){const x=f instanceof Error?f.message:"Unknown error";re.error("Failed to enable push notifications: "+x)}return!1}finally{l(!1)}},[h,o,s,d]),p=j.useCallback(async()=>{if(!o||!s)return!1;try{l(!0);const f=await o.pushManager.getSubscription();return f&&await f.unsubscribe(),await q.from("push_subscriptions").delete().eq("user_id",s.id),a(!1),re.success("Push notifications disabled"),!0}catch(f){console.error("Error unsubscribing:",f);const x=f instanceof Error?f.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:p}}const lOe="push_notification_prompt_dismissed",bCs=["/dashboard","/admin"],_Cs=()=>{const{user:s}=vs(),{isSupported:t,isSubscribed:n,isLoading:r,subscribe:a}=C8t(),i=Od(),[l,o]=j.useState(!1),[c,d]=j.useState(!1),u=bCs.some(p=>i.pathname===p||i.pathname.startsWith(`${p}/`));j.useEffect(()=>{if(u){o(!1);return}if(!s||!t||n||r||localStorage.getItem(`${lOe}_${s.id}`))return;const f=setTimeout(()=>{o(!0)},2e3);return()=>clearTimeout(f)},[s,t,n,r,u]);const h=async()=>{d(!0);const p=await a();d(!1),p&&(s&&localStorage.setItem(`${lOe}_${s.id}`,"true"),o(!1))},m=()=>{s&&localStorage.setItem(`${lOe}_${s.id}`,"true"),o(!1)};return!t||n||u?null:e.jsx(zs,{open:l,onOpenChange:p=>!p&&m(),children:e.jsxs(Ds,{className:"sm:max-w-md",children:[e.jsxs(Vs,{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(bx,{className:"h-6 w-6 text-primary"})}),e.jsx($s,{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(U,{onClick:h,disabled:c,className:"w-full",children:c?"Enabling...":"Enable Notifications"}),e.jsx(U,{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."})]})})},cmt=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(p=>p(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},wCs=s=>s?cmt(s):cmt,jCs=s=>s;function NCs(s,t=jCs){const n=Dt.useSyncExternalStore(s.subscribe,Dt.useCallback(()=>t(s.getState()),[s,t]),Dt.useCallback(()=>t(s.getInitialState()),[s,t]));return Dt.useDebugValue(n),n}const dmt=s=>{const t=wCs(s),n=r=>NCs(t,r);return Object.assign(n,t),n},kCs=s=>s?dmt(s):dmt;function SCs(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 _qe=s=>t=>{try{const n=s(t);return n instanceof Promise?n:{then(r){return _qe(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return _qe(r)(n)}}}},CCs=(s,t)=>(n,r,a)=>{let i={storage:SCs(()=>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 p=s((...y)=>(n(...y),h()),r,a);a.getInitialState=()=>p;let f;const x=()=>{var y,v;if(!u)return;const b=++o;l=!1,c.forEach(S=>{var A;return S((A=r())!=null?A:p)});const N=((v=i.onRehydrateStorage)==null?void 0:v.call(i,(y=r())!=null?y:p))||void 0;return _qe(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(T=>[!0,T]):[!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[T,L]=S;if(f=i.merge(L,(A=r())!=null?A:p),n(f,!0),T)return h()}).then(()=>{b===o&&(N==null||N(r(),void 0),f=r(),l=!0,d.forEach(S=>S(f)))}).catch(S=>{b===o&&(N==null||N(void 0,S))})};return a.persist={setOptions:y=>{i={...i,...y},y.storage&&(u=y.storage)},clearStorage:()=>{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(),f||p},ACs=CCs,bMe=kCs()(ACs((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 ECs({activeCategory:s,currentCategory:t,onSelect:n,onHover:r,badgeCounts:a,categories:i=gMe}){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:Mt("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 TCs({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=f=>{f.key==="Escape"&&r()},p=f=>{var y;if(!u.current)return;const x=f.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",p),()=>{document.removeEventListener("keydown",m),document.removeEventListener("mousedown",p)}},[r]);const h=m=>{const p=m.icon,f=m.badgeKey?(d==null?void 0:d[m.badgeKey])??0:0;return e.jsxs("div",{className:Mt("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(p,{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(Ql,{className:"h-3 w-3 text-muted-foreground","aria-label":"Upgrade required"}),f>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:f>9?"9+":f})]}),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:Mt("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(u0,{className:Mt("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(u0,{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 MCs({categories:s,railCategories:t=gMe,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:Mt("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 p=s.find(x=>x.id===h.id),f=d===h.id;return e.jsxs("div",{children:[e.jsxs("button",{type:"button","aria-expanded":f,onClick:()=>u(f?null:h.id),className:Mt("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(rl,{className:Mt("ml-auto h-4 w-4 transition-transform",f&&"rotate-180")})]}),f&&p&&e.jsx("div",{className:"space-y-3 pb-3 pl-4 pr-1",children:p.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,N=(o==null?void 0:o(y))??!1;return e.jsxs("div",{className:Mt("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":N?`Remove ${y.label} from favorites`:`Add ${y.label} to favorites`,onClick:()=>c(y),className:Mt("rounded p-2",N?"text-primary":"text-muted-foreground/60"),children:e.jsx(u0,{className:Mt("h-4 w-4",N&&"fill-current")})})]},y.id)})]},x.title))})]},h.id)})})}function A8t(){const s=Wn(),t=Od(),n=ZIt(),r=j.useCallback(o=>YIt(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 PCs({communityUnreadCount:s=0,wishlistOpenCount:t=0,flyoutTop:n=64,flyoutLeft:r=80}){const{nav:a,navigate:i,currentCategory:l,isCurrent:o,go:c}=A8t(),[d,u]=j.useState(null),h=j.useRef(null),m=x=>{const y=gMe.find(v=>v.id===x);if(y!=null&&y.route){u(null),i(y.route);return}u(v=>v===x?null:x)},p=d?a.categoryMap.get(d):void 0,f={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(ECs,{activeCategory:d,currentCategory:l,onSelect:m,categories:a.railCategories,badgeCounts:f}),p&&e.jsx(TCs,{category:p,top:n,left:r,onClose:()=>u(null),onNavigate:x=>{u(null),c(x)},isFavorite:a.isFavorite,favorites:a.favoritesFor(p.id),onToggleFavorite:x=>a.toggleFavorite(a.favoriteKey(x)),isCurrent:o,badgeCounts:{community:s,wishlist:t}})]})}function LCs({communityUnreadCount:s=0,wishlistOpenCount:t=0,onNavigated:n}){const{nav:r,navigate:a,currentCategory:i,isCurrent:l,go:o}=A8t();return e.jsx(MCs,{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 qs=({children:s,title:t})=>{var ke;const{user:n,signOut:r,isAdmin:a,isBrokerageManager:i,isCoach:l,brokerageId:o}=vs(),{isAssistant:c,actingAsAgent:d,hasPermission:u}=Fne();Y6e();const{isImpersonating:h}=$6e(),p=(c&&!!d?40:0)+(h?40:0),{avatarUrl:f}=BPt(n==null?void 0:n.id),{isTrial:x,isExpired:y,expiresAt:v}=D_s(n==null?void 0:n.id),{isInnerCircleEnabled:b,isMarketplaceEnabled:N}=qne(),{currentBrief:S,shouldShowPopup:A,hasUnseenBrief:T,openBrief:L,closeBrief:M,dismissBrief:I}=pCs(),{unreadCount:R}=O_s(),{openCount:z}=F_s();Sj();const H=bMe(Te=>Te.cartItems).reduce((Te,Me)=>Te+Me.quantity,0),{leadSite:V,hasLeadSite:K,siteUrl:Z}=$p();fMe(!K);const Q=Wn(),le=Od(),[ue,se]=j.useState(null);j.useEffect(()=>{n!=null&&n.id&&q.from("profiles").select("name").eq("id",n.id).single().then(({data:Te})=>{Te!=null&&Te.name&&se(Te.name)})},[n==null?void 0:n.id]);const ne=ue||((ke=n==null?void 0:n.user_metadata)==null?void 0:ke.name)||(n==null?void 0:n.email)||"User",[ie,ce]=j.useState(!1),je=Te=>Te.split(" ").map(Me=>Me[0]).join("").toUpperCase().slice(0,2),be=Te=>le.pathname===Te,he=()=>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:()=>Q("/dashboard"),"aria-label":"LevelUp home",children:e.jsx("img",{src:sws,alt:"LevelUp",className:"h-8 w-auto"})})}),e.jsxs(Gi,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:[e.jsx(PCs,{communityUnreadCount:R,wishlistOpenCount:z,flyoutTop:p+64,flyoutLeft:80}),x&&!y&&e.jsx("div",{className:"p-2",children:e.jsxs("button",{type:"button",onClick:()=>Q("/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(cn,{className:"h-4 w-4"}),"Upgrade"]})})]})]}),ge=({onNavigated:Te})=>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:tws,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsxs(Gi,{className:"flex-1",children:[x&&!y&&e.jsx("div",{className:"p-2",children:e.jsx("button",{type:"button",onClick:()=>{Q("/subscription"),Te==null||Te()},className:Mt("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(cn,{className:"h-4 w-4 text-amber-500"}),e.jsx("span",{className:"flex-1 text-left",children:"Ready to Upgrade?"}),v&&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((new Date(v).getTime()-Date.now())/864e5)),"d left"]})]})})}),e.jsx(LCs,{communityUnreadCount:R,wishlistOpenCount:z,onNavigated:Te})]}),e.jsxs("div",{className:"border-t border-sidebar-border p-3",children:[e.jsxs(U,{variant:"ghost",size:"sm",className:Mt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",be("/profile")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>{Q("/profile"),Te==null||Te()},children:[e.jsx(So,{className:"h-4 w-4"}),"Profile"]}),e.jsxs(U,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:r,children:[e.jsx(TF,{className:"h-4 w-4"}),"Sign Out"]})]})]});return e.jsx(wN,{children:e.jsxs("div",{className:"min-h-screen bg-background flex",children:[x&&y&&le.pathname!=="/subscription"&&e.jsx(X3s,{}),typeof document<"u"&&tv.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:`${p}px`,height:`calc(100vh - ${p}px)`},children:e.jsx(he,{})}),document.body),e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden md:ml-20",style:{height:`calc(100vh - ${p}px)`,marginTop:`${p}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(my,{open:ie,onOpenChange:ce,children:[e.jsx($ne,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"md:hidden",children:e.jsx(AA,{className:"h-5 w-5"})})}),e.jsx(g0,{side:"left",className:"w-72 p-0 bg-card",children:e.jsx(ge,{onNavigated:()=>ce(!1)})})]}),e.jsx("div",{className:"flex-1 md:hidden",children:e.jsx("img",{src:nws,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsx("div",{className:"hidden md:flex flex-1 justify-center",children:e.jsx(lmt,{})}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[x&&!y&&v&&e.jsx(Z3s,{expiresAt:v,className:"hidden lg:flex"}),e.jsx("div",{className:"md:hidden",children:e.jsx(lmt,{})}),S&&e.jsx(Q3s,{hasUnseenBrief:T,onClick:L}),N&&e.jsxs(U,{variant:"ghost",size:"icon",className:"relative",onClick:()=>Q("/marketplace/cart"),children:[e.jsx(sS,{className:"h-5 w-5"}),H>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:H>99?"99+":H})]}),e.jsx(U,{variant:"ghost",size:"icon","aria-label":"My Calendar",title:"My Calendar",onClick:()=>Q("/mission-control/calendar"),children:e.jsx(nc,{className:"h-5 w-5"})}),e.jsx(v3s,{}),e.jsx(fqe,{}),e.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",ne.split(" ")[0],"!"]}),e.jsxs(Ku,{children:[e.jsx(Yu,{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(Ea,{className:"h-9 w-9 cursor-pointer hover:opacity-80 transition-opacity",children:[e.jsx(Ci,{src:f||void 0}),e.jsx(Ta,{className:"bg-primary text-primary-foreground font-medium text-sm",children:je(ne)})]})})}),e.jsxs(Eu,{align:"end",className:"w-48",children:[e.jsxs(La,{onClick:()=>Q("/profile"),className:"cursor-pointer",children:[e.jsx(So,{className:"h-4 w-4 mr-2"}),"Profile"]}),e.jsxs(La,{onClick:()=>Q("/mission-control/integrations"),className:"cursor-pointer",children:[e.jsx(J2,{className:"h-4 w-4 mr-2"}),"Integrations"]}),e.jsxs(La,{onClick:()=>Q("/mission-control/browser-extension"),className:"cursor-pointer",children:[e.jsx(J2,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),e.jsx(l1,{}),e.jsxs(La,{onClick:r,className:"cursor-pointer text-destructive focus:text-destructive",children:[e.jsx(TF,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),e.jsx(gCs,{children:e.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:s})}),S&&e.jsx(mCs,{brief:S,open:A,onClose:M,onDismiss:I}),e.jsx(fCs,{}),e.jsx(yCs,{}),e.jsx(_Cs,{})]})]})})},pn=({children:s,requireAdmin:t=!1,requireBrokerageManager:n=!1})=>{const{user:r,loading:a,rolesLoading:i,isAdmin:l,isBrokerageManager:o}=vs(),c=Od(),d=_S();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(td,{to:"/auth",replace:!0})}if(t&&!l)return e.jsx(td,{to:"/dashboard",replace:!0});if(n&&!o&&!l)return e.jsx(td,{to:"/dashboard",replace:!0});if(d.isRestricted&&!d.isLoading){const u=FPt(c.pathname);if(u&&!d.hasFeature(u))return e.jsx(qs,{title:"Upgrade required",children:e.jsx(R_s,{featureKey:u})})}return e.jsx(e.Fragment,{children:s})};function cOe({children:s}){const{isAdmin:t,loading:n,rolesLoading:r}=vs(),{isFeatureEnabled:a,isLoading:i}=qne();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(td,{to:"/apps",replace:!0}):e.jsx(qs,{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 EXe={};(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 se=new OffscreenCanvas(1,1),ne=se.getContext("2d");ne.fillRect(0,0,1,1);var ie=se.transferToImageBitmap();ne.createPattern(ie,"no-repeat")}catch{return!1}return!0}();function c(){}function d(se){var ne=n.exports.Promise,ie=ne!==void 0?ne:t.Promise;return typeof ie=="function"?new ie(se):(se(c,c),null)}var u=function(se,ne){return{transform:function(ie){if(se)return ie;if(ne.has(ie))return ne.get(ie);var ce=new OffscreenCanvas(ie.width,ie.height),je=ce.getContext("2d");return je.drawImage(ie,0,0),ne.set(ie,ce),ce},clear:function(){ne.clear()}}}(o,new Map),h=function(){var se=Math.floor(16.666666666666668),ne,ie,ce={},je=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(ne=function(be){var he=Math.random();return ce[he]=requestAnimationFrame(function ge(ke){je===ke||je+se-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 RCs(){const s=Qt();return yt({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 DCs(){const s=Qt(),{user:t}=vs();return yt({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 OCs={points_earned:Al,listing_created:ra,deal_closed:yu,custom:Ua},hmt={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"},mmt=()=>{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 FCs(){const{user:s}=vs(),t=Qt(),{data:n}=ICs(),r=RCs(),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=j.useCallback(()=>{const p=Date.now()+3e3,f={startVelocity:30,spread:360,ticks:60,zIndex:9999},x=(v,b)=>Math.random()*(b-v)+v,y=setInterval(()=>{const v=p-Date.now();if(v<=0){clearInterval(y);return}const b=50*(v/3e3);umt({...f,particleCount:b,origin:{x:x(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),umt({...f,particleCount:b,origin:{x:x(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);j.useEffect(()=>{mmt()||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],p=>(p==null?void 0:p.filter(f=>f.id!==m))??[]),await r.mutateAsync(m)}};if(mmt()||!a)return null;const u=OCs[a.celebration_type]||Ua,h=hmt[a.celebration_type]||hmt.custom;return e.jsx(zs,{open:l,onOpenChange:m=>!m&&d(),children:e.jsxs(Ds,{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(cn,{className:"w-5 h-5 text-yellow-500 animate-pulse"}),e.jsx(cn,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-75"}),e.jsx(cn,{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(U,{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:Mt("animate-pulse rounded-md bg-muted",s),...t})}var _Me="Tabs",[zCs,ggr]=Up(_Me,[DP]),E8t=DP(),[BCs,TXe]=zCs(_Me),T8t=j.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,onValueChange:a,defaultValue:i,orientation:l="horizontal",dir:o,activationMode:c="automatic",...d}=s,u=xE(o),[h,m]=Sx({prop:r,onChange:a,defaultProp:i??"",caller:_Me});return e.jsx(BCs,{scope:n,baseId:jx(),value:h,onValueChange:m,orientation:l,dir:u,activationMode:c,children:e.jsx(si.div,{dir:u,"data-orientation":l,...d,ref:t})})});T8t.displayName=_Me;var M8t="TabsList",P8t=j.forwardRef((s,t)=>{const{__scopeTabs:n,loop:r=!0,...a}=s,i=TXe(M8t,n),l=E8t(n);return e.jsx(V6e,{asChild:!0,...l,orientation:i.orientation,dir:i.dir,loop:r,children:e.jsx(si.div,{role:"tablist","aria-orientation":i.orientation,...a,ref:t})})});P8t.displayName=M8t;var L8t="TabsTrigger",I8t=j.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,disabled:a=!1,...i}=s,l=TXe(L8t,n),o=E8t(n),c=O8t(l.baseId,r),d=F8t(l.baseId,r),u=r===l.value;return e.jsx(H6e,{asChild:!0,...o,focusable:!a,active:u,children:e.jsx(si.button,{type:"button",role:"tab","aria-selected":u,"aria-controls":d,"data-state":u?"active":"inactive","data-disabled":a?"":void 0,disabled:a,id:c,...i,ref:t,onMouseDown:va(s.onMouseDown,h=>{!a&&h.button===0&&h.ctrlKey===!1?l.onValueChange(r):h.preventDefault()}),onKeyDown:va(s.onKeyDown,h=>{[" ","Enter"].includes(h.key)&&l.onValueChange(r)}),onFocus:va(s.onFocus,()=>{const h=l.activationMode!=="manual";!u&&!a&&h&&l.onValueChange(r)})})})});I8t.displayName=L8t;var R8t="TabsContent",D8t=j.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,forceMount:a,children:i,...l}=s,o=TXe(R8t,n),c=O8t(o.baseId,r),d=F8t(o.baseId,r),u=r===o.value,h=j.useRef(u);return j.useEffect(()=>{const m=requestAnimationFrame(()=>h.current=!1);return()=>cancelAnimationFrame(m)},[]),e.jsx(Xg,{present:a||u,children:({present:m})=>e.jsx(si.div,{"data-state":u?"active":"inactive","data-orientation":o.orientation,role:"tabpanel","aria-labelledby":c,hidden:!m,id:d,tabIndex:0,...l,ref:t,style:{...s.style,animationDuration:h.current?"0s":void 0},children:m&&i})})});D8t.displayName=R8t;function O8t(s,t){return`${s}-trigger-${t}`}function F8t(s,t){return`${s}-content-${t}`}var UCs=T8t,z8t=P8t,B8t=I8t,U8t=D8t;const oa=UCs,la=j.forwardRef(({className:s,...t},n)=>e.jsx(z8t,{ref:n,className:Mt("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",s),...t}));la.displayName=z8t.displayName;const Kt=j.forwardRef(({className:s,...t},n)=>e.jsx(B8t,{ref:n,className:Mt("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}));Kt.displayName=B8t.displayName;const Zt=j.forwardRef(({className:s,...t},n)=>e.jsx(U8t,{ref:n,className:Mt("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...t}));Zt.displayName=U8t.displayName;const lee="#0d0d0d",hCe="#1a1a1a",ev="#c9a84c",Zne="#f0d78c",K4={captured:"lup_lead_captured_v1",stickyDismissed:"lup_sticky_dismissed_v1",exitShown:"lup_exit_shown_v1",savedListings:"lup_saved_listings_v1"};async function wMe(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(K4.captured,JSON.stringify({email:s.email,ts:Date.now()}))}catch{}return n}function MXe(){try{return!!localStorage.getItem(K4.captured)}catch{return!1}}function qCs(){try{const s=localStorage.getItem(K4.captured);return s?JSON.parse(s).email??null:null}catch{return null}}function PXe({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?tv.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, ${hCe} 0%, ${lee} 100%)`,border:`1px solid ${ev}33`,boxShadow:`0 30px 80px rgba(0,0,0,0.6), 0 0 0 1px ${ev}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(er,{className:"h-4 w-4"})}),n]})}),document.body):null}function LXe(){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 IXe({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(So,{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(ln,{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(ba,{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(ni,{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 RXe({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, ${Zne} 0%, ${ev} 100%)`,color:lee,boxShadow:`0 8px 24px ${ev}55`},children:s})}function pmt({open:s,onClose:t,initialCriteria:n}){const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=LXe(),[d,u]=j.useState(!1),h=async m=>{if(m.preventDefault(),!!r.email){l(!0);try{await wMe({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(K4.stickyDismissed,"1")}catch{}setTimeout(t,2200)}catch{re.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(PXe,{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(bx,{className:"h-4 w-4",style:{color:ev}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:Zne},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:`${ev}22`,border:`1px solid ${ev}55`},children:e.jsx(cn,{className:"h-5 w-5",style:{color:ev}})}),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(IXe,{values:r,setValues:a,honeypot:o,setHoneypot:c}),e.jsx(RXe,{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 $Cs(){const[s,t]=j.useState(!0),[n,r]=j.useState(!1);j.useEffect(()=>{try{const i=!!localStorage.getItem(K4.stickyDismissed)||MXe();t(i)}catch{t(!1)}},[]);const a=()=>{t(!0);try{localStorage.setItem(K4.stickyDismissed,"1")}catch{}};return s?e.jsx(pmt,{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, ${hCe} 0%, ${lee} 100%)`,borderTop:`1px solid ${ev}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:`${ev}22`,border:`1px solid ${ev}55`},children:e.jsx(bx,{className:"h-4 w-4",style:{color:ev}})}),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, ${Zne} 0%, ${ev} 100%)`,color:lee},children:"Get Alerts"}),e.jsx("button",{onClick:a,className:"p-2 text-white/50 hover:text-white transition","aria-label":"Dismiss",children:e.jsx(er,{className:"h-4 w-4"})})]})}),e.jsx(pmt,{open:n,onClose:()=>r(!1)})]})}function VCs(){const[s,t]=j.useState(!1),n=j.useRef(!1);j.useEffect(()=>{try{if(sessionStorage.getItem(K4.exitShown)||MXe())return}catch{}const m=setTimeout(()=>{n.current=!0},8e3),p=f=>{if(n.current&&!(f.clientY>0)){t(!0);try{sessionStorage.setItem(K4.exitShown,"1")}catch{}window.removeEventListener("mouseleave",p),document.removeEventListener("mouseleave",p)}};return document.addEventListener("mouseleave",p),()=>{clearTimeout(m),document.removeEventListener("mouseleave",p)}},[]);const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=LXe(),[d,u]=j.useState(!1),h=async m=>{if(m.preventDefault(),!!r.email){l(!0);try{await wMe({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(PXe,{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, ${lee} 0%, ${hCe} 60%, ${ev} 130%)`},children:e.jsx("div",{className:"absolute top-4 left-6",children:e.jsx("span",{className:"text-[10px] uppercase tracking-[0.25em]",style:{color:Zne},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:hCe,border:`1px solid ${ev}55`,boxShadow:"0 8px 24px rgba(0,0,0,0.5)"},children:e.jsx(cn,{className:"h-6 w-6",style:{color:ev}})}),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(IXe,{values:r,setValues:a,honeypot:o,setHoneypot:c,showPhone:!1}),e.jsx(RXe,{type:"submit",disabled:i||!r.email,children:i?"Sending…":"Send My List"})]})]})]})})}function HCs(){const[s,t]=j.useState([]);j.useEffect(()=>{try{const o=localStorage.getItem(K4.savedListings);o&&t(JSON.parse(o))}catch{}},[]);const n=o=>{t(o);try{localStorage.setItem(K4.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 GCs({listingId:s,listingAddress:t,className:n}){const{has:r,add:a,remove:i}=HCs(),l=r(s),[o,c]=j.useState(!1),d=()=>{if(l){i(s);return}if(MXe()){a(s),re.success("Saved to your favorites"),wMe({lead_type:"saved_listing",email:qCs()||"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(ko,{className:`h-5 w-5 ${l?"fill-current":""}`})}),e.jsx(WCs,{open:o,onClose:()=>c(!1),listingId:s,listingAddress:t,onSaved:()=>a(s)})]})}function WCs({open:s,onClose:t,listingId:n,listingAddress:r,onSaved:a}){const{values:i,setValues:l,loading:o,setLoading:c,honeypot:d,setHoneypot:u}=LXe(),h=async m=>{if(m.preventDefault(),!!i.email){c(!0);try{await wMe({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(PXe,{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(ko,{className:"h-4 w-4",style:{color:ev}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:Zne},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(IXe,{values:i,setValues:l,honeypot:d,setHoneypot:u}),e.jsx(RXe,{type:"submit",disabled:o||!i.email,children:o?"Saving…":"Save Home"})]})]})})}var q8t=["PageUp","PageDown"],$8t=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],V8t={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},xG="Slider",[wqe,KCs,YCs]=tG(xG),[H8t,xgr]=Up(xG,[YCs]),[ZCs,jMe]=H8t(xG),G8t=j.forwardRef((s,t)=>{const{name:n,min:r=0,max:a=100,step:i=1,orientation:l="horizontal",disabled:o=!1,minStepsBetweenThumbs:c=0,defaultValue:d=[r],value:u,onValueChange:h=()=>{},onValueCommit:m=()=>{},inverted:p=!1,form:f,...x}=s,y=j.useRef(new Set),v=j.useRef(0),N=l==="horizontal"?XCs:QCs,[S=[],A]=Sx({prop:u,defaultProp:d,onChange:z=>{var H;(H=[...y.current][v.current])==null||H.focus(),h(z)}}),T=j.useRef(S);function L(z){const $=nAs(S,z);R(z,$)}function M(z){R(z,v.current)}function I(){const z=T.current[v.current];S[v.current]!==z&&m(S)}function R(z,$,{commit:H}={commit:!1}){const V=oAs(i),K=lAs(Math.round((z-r)/i)*i+r,V),Z=aee(K,[r,a]);A((Q=[])=>{const le=tAs(Q,Z,$);if(iAs(le,c*i)){v.current=le.indexOf(Z);const ue=String(le)!==String(Q);return ue&&H&&m(le),ue?le:Q}else return Q})}return e.jsx(ZCs,{scope:s.__scopeSlider,name:n,disabled:o,min:r,max:a,valueIndexToChangeRef:v,thumbs:y.current,values:S,orientation:l,form:f,children:e.jsx(wqe.Provider,{scope:s.__scopeSlider,children:e.jsx(wqe.Slot,{scope:s.__scopeSlider,children:e.jsx(N,{"aria-disabled":o,"data-disabled":o?"":void 0,...x,ref:t,onPointerDown:va(x.onPointerDown,()=>{o||(T.current=S)}),min:r,max:a,inverted:p,onSlideStart:o?void 0:L,onSlideMove:o?void 0:M,onSlideEnd:o?void 0:I,onHomeKeyDown:()=>!o&&R(r,0,{commit:!0}),onEndKeyDown:()=>!o&&R(a,S.length-1,{commit:!0}),onStepKeyDown:({event:z,direction:$})=>{if(!o){const K=q8t.includes(z.key)||z.shiftKey&&$8t.includes(z.key)?10:1,Z=v.current,Q=S[Z],le=i*K*$;R(Q+le,Z,{commit:!0})}}})})})})});G8t.displayName=xG;var[W8t,K8t]=H8t(xG,{startEdge:"left",endEdge:"right",size:"width",direction:1}),XCs=j.forwardRef((s,t)=>{const{min:n,max:r,dir:a,inverted:i,onSlideStart:l,onSlideMove:o,onSlideEnd:c,onStepKeyDown:d,...u}=s,[h,m]=j.useState(null),p=Uo(t,N=>m(N)),f=j.useRef(void 0),x=xE(a),y=x==="ltr",v=y&&!i||!y&&i;function b(N){const S=f.current||h.getBoundingClientRect(),A=[0,S.width],L=DXe(A,v?[n,r]:[r,n]);return f.current=S,L(N-S.left)}return e.jsx(W8t,{scope:s.__scopeSlider,startEdge:v?"left":"right",endEdge:v?"right":"left",direction:v?1:-1,size:"width",children:e.jsx(Y8t,{dir:x,"data-orientation":"horizontal",...u,ref:p,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:N=>{const S=b(N.clientX);l==null||l(S)},onSlideMove:N=>{const S=b(N.clientX);o==null||o(S)},onSlideEnd:()=>{f.current=void 0,c==null||c()},onStepKeyDown:N=>{const A=V8t[v?"from-left":"from-right"].includes(N.key);d==null||d({event:N,direction:A?-1:1})}})})}),QCs=j.forwardRef((s,t)=>{const{min:n,max:r,inverted:a,onSlideStart:i,onSlideMove:l,onSlideEnd:o,onStepKeyDown:c,...d}=s,u=j.useRef(null),h=Uo(t,u),m=j.useRef(void 0),p=!a;function f(x){const y=m.current||u.current.getBoundingClientRect(),v=[0,y.height],N=DXe(v,p?[r,n]:[n,r]);return m.current=y,N(x-y.top)}return e.jsx(W8t,{scope:s.__scopeSlider,startEdge:p?"bottom":"top",endEdge:p?"top":"bottom",size:"height",direction:p?1:-1,children:e.jsx(Y8t,{"data-orientation":"vertical",...d,ref:h,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:x=>{const y=f(x.clientY);i==null||i(y)},onSlideMove:x=>{const y=f(x.clientY);l==null||l(y)},onSlideEnd:()=>{m.current=void 0,o==null||o()},onStepKeyDown:x=>{const v=V8t[p?"from-bottom":"from-top"].includes(x.key);c==null||c({event:x,direction:v?-1:1})}})})}),Y8t=j.forwardRef((s,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:a,onSlideEnd:i,onHomeKeyDown:l,onEndKeyDown:o,onStepKeyDown:c,...d}=s,u=jMe(xG,n);return e.jsx(si.span,{...d,ref:t,onKeyDown:va(s.onKeyDown,h=>{h.key==="Home"?(l(h),h.preventDefault()):h.key==="End"?(o(h),h.preventDefault()):q8t.concat($8t).includes(h.key)&&(c(h),h.preventDefault())}),onPointerDown:va(s.onPointerDown,h=>{const m=h.target;m.setPointerCapture(h.pointerId),h.preventDefault(),u.thumbs.has(m)?m.focus():r(h)}),onPointerMove:va(s.onPointerMove,h=>{h.target.hasPointerCapture(h.pointerId)&&a(h)}),onPointerUp:va(s.onPointerUp,h=>{const m=h.target;m.hasPointerCapture(h.pointerId)&&(m.releasePointerCapture(h.pointerId),i(h))})})}),Z8t="SliderTrack",X8t=j.forwardRef((s,t)=>{const{__scopeSlider:n,...r}=s,a=jMe(Z8t,n);return e.jsx(si.span,{"data-disabled":a.disabled?"":void 0,"data-orientation":a.orientation,...r,ref:t})});X8t.displayName=Z8t;var jqe="SliderRange",Q8t=j.forwardRef((s,t)=>{const{__scopeSlider:n,...r}=s,a=jMe(jqe,n),i=K8t(jqe,n),l=j.useRef(null),o=Uo(t,l),c=a.values.length,d=a.values.map(m=>tRt(m,a.min,a.max)),u=c>1?Math.min(...d):0,h=100-Math.max(...d);return e.jsx(si.span,{"data-orientation":a.orientation,"data-disabled":a.disabled?"":void 0,...r,ref:o,style:{...s.style,[i.startEdge]:u+"%",[i.endEdge]:h+"%"}})});Q8t.displayName=jqe;var Nqe="SliderThumb",J8t=j.forwardRef((s,t)=>{const n=KCs(s.__scopeSlider),[r,a]=j.useState(null),i=Uo(t,o=>a(o)),l=j.useMemo(()=>r?n().findIndex(o=>o.ref.current===r):-1,[n,r]);return e.jsx(JCs,{...s,ref:i,index:l})}),JCs=j.forwardRef((s,t)=>{const{__scopeSlider:n,index:r,name:a,...i}=s,l=jMe(Nqe,n),o=K8t(Nqe,n),[c,d]=j.useState(null),u=Uo(t,b=>d(b)),h=c?l.form||!!c.closest("form"):!0,m=Mne(c),p=l.values[r],f=p===void 0?0:tRt(p,l.min,l.max),x=sAs(r,l.values.length),y=m==null?void 0:m[o.size],v=y?rAs(y,f,o.direction):0;return j.useEffect(()=>{if(c)return l.thumbs.add(c),()=>{l.thumbs.delete(c)}},[c,l.thumbs]),e.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[o.startEdge]:`calc(${f}% + ${v}px)`},children:[e.jsx(wqe.ItemSlot,{scope:s.__scopeSlider,children:e.jsx(si.span,{role:"slider","aria-label":s["aria-label"]||x,"aria-valuemin":l.min,"aria-valuenow":p,"aria-valuemax":l.max,"aria-orientation":l.orientation,"data-orientation":l.orientation,"data-disabled":l.disabled?"":void 0,tabIndex:l.disabled?void 0:0,...i,ref:u,style:p===void 0?{display:"none"}:s.style,onFocus:va(s.onFocus,()=>{l.valueIndexToChangeRef.current=r})})}),h&&e.jsx(eRt,{name:a??(l.name?l.name+(l.values.length>1?"[]":""):void 0),form:l.form,value:p},r)]})});J8t.displayName=Nqe;var eAs="RadioBubbleInput",eRt=j.forwardRef(({__scopeSlider:s,value:t,...n},r)=>{const a=j.useRef(null),i=Uo(a,r),l=Wne(t);return j.useEffect(()=>{const o=a.current;if(!o)return;const c=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(c,"value").set;if(l!==t&&u){const h=new Event("input",{bubbles:!0});u.call(o,t),o.dispatchEvent(h)}},[l,t]),e.jsx(si.input,{style:{display:"none"},...n,ref:i,defaultValue:t})});eRt.displayName=eAs;function tAs(s=[],t,n){const r=[...s];return r[n]=t,r.sort((a,i)=>a-i)}function tRt(s,t,n){const i=100/(n-t)*(s-t);return aee(i,[0,100])}function sAs(s,t){return t>2?`Value ${s+1} of ${t}`:t===2?["Minimum","Maximum"][s]:void 0}function nAs(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)}function rAs(s,t,n){const r=s/2,i=DXe([0,50],[0,r]);return(r-i(t)*n)*n}function aAs(s){return s.slice(0,-1).map((t,n)=>s[n+1]-t)}function iAs(s,t){if(t>0){const n=aAs(s);return Math.min(...n)>=t}return!0}function DXe(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])}}function oAs(s){return(String(s).split(".")[1]||"").length}function lAs(s,t){const n=Math.pow(10,t);return Math.round(s*n)/n}var sRt=G8t,cAs=X8t,dAs=Q8t,uAs=J8t;const rg=j.forwardRef(({className:s,...t},n)=>e.jsxs(sRt,{ref:n,className:Mt("relative flex w-full touch-none select-none items-center",s),...t,children:[e.jsx(cAs,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(dAs,{className:"absolute h-full bg-primary"})}),e.jsx(uAs,{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"})]}));rg.displayName=sRt.displayName;const hAs=s=>ct({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}}),mAs=()=>ct({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)}}}),pAs=s=>ct({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}),fAs=()=>yt({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,p=null;if(l){const{data:v}=await q.from("listing_shares").select("id, sharing_agent_id").eq("share_token",l).eq("listing_id",s).maybeSingle();v&&(m=v.id,p=v.sharing_agent_id)}const{data:f,error:x}=await q.from("listing_leads").insert({listing_id:s,agent_id:p||t,first_name:n,last_name:r,email:a,phone:i,share_id:m,referred_by_agent_id:p,lead_type:o,preferred_date:c||null,preferred_time:d||null,showing_mode:u||null,message:h||null}).select().single();if(x)throw x;const{error:y}=await q.functions.invoke("process-listing-lead",{body:{leadId:f.id}});return y&&console.error("Error processing lead:",y),f}}),gAs=()=>yt({mutationFn:async s=>{const{error:t}=await q.rpc("increment_listing_share_click",{p_share_token:s});if(t)throw t}}),uP={sale:"For Sale",lease:"For Lease",sale_or_lease:"For Sale or Lease",investment:"Investment Offering"},qP={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"},xAs=["NNN","Modified Gross","Full Service","Gross","Absolute Net","Ground Lease"],yAs={sf_year:"/SF/YR",sf_month:"/SF/MO",month:"/MO"},kqe={om:"Offering Memorandum",flyer:"Flyer",rent_roll:"Rent Roll",financials:"Financials",survey:"Survey",site_plan:"Site Plan",lease:"Lease Documents",other:"Other"},fmt={public:"Open download",email:"Email required",nda:"NDA required"},Sqe={principal:"Principal / Investor",broker:"Broker",tenant:"Tenant / User",lender:"Lender",other:"Other"},dOe=[{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"}],k5e=[{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"}],nRt=[{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 M2(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 gmt(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`:M2(t)}function fA(s){return s==null?null:`${new Intl.NumberFormat("en-US").format(Number(s))} SF`}function mCe(s,t=2){return s==null?null:`${Number(s).toFixed(t).replace(/\.?0+$/,"")}%`}function Cqe(s){if(!(s!=null&&s.lease_rate))return null;const t=yAs[s.lease_rate_unit||"sf_year"]??"";return`${s.lease_rate_unit==="month"?M2(s.lease_rate):`$${Number(s.lease_rate).toFixed(2).replace(/\.00$/,"")}`}${t}${s.lease_type?` ${s.lease_type}`:""}`}function BV(s,t){if(!s)return M2(t)??"Price on request";if(s.deal_type==="lease")return Cqe(s)??"Rate on request";const n=s.asking_price??t;if(s.deal_type==="sale_or_lease"){const r=[M2(n),Cqe(s)].filter(Boolean);return r.length?r.join(" · "):"Price on request"}return M2(n)??"Price on request"}function UM(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?qP[t.commercial_type]:"Commercial"} Opportunity`:s.property_address||`${s.city??""}, ${s.state??""}`}function Xne(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 vAs(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 k5e)(a[l.key]||n[l.key])&&r.push(l.key);return{done:r,total:k5e.length,score:Math.round(r.length/k5e.length*100)}}const xmt={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 ymt(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 bAs="https://commercial.relevelup.com",Y4=q;function rRt(s){return ct({queryKey:["commercial-details",s],queryFn:async()=>{const{data:t,error:n}=await Y4.from("commercial_listing_details").select("*").eq("listing_id",s).maybeSingle();if(n)throw n;return t??null},enabled:!!s})}function aRt(){const s=Qt(),{user:t}=vs();return yt({mutationFn:async({listingId:n,values:r})=>{const{data:a,error:i}=await Y4.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 _As(s){return ct({queryKey:["commercial-pitch",s],queryFn:async()=>{const{data:t,error:n}=await Y4.from("commercial_pitch_details").select("*").eq("listing_id",s).maybeSingle();if(n)throw n;return t??null},enabled:!!s})}function iRt(){const s=Qt(),{user:t}=vs();return yt({mutationFn:async({listingId:n,values:r})=>{const{data:a,error:i}=await Y4.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 oRt(){const s=Qt();return yt({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 Y4.from("listings").update(l).eq("id",t);if(o)throw o;return(a||i)&&await Y4.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 wAs(){const s=Qt();return yt({mutationFn:async({listingId:t,values:n})=>{const{error:r}=await Y4.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 OXe(s,t=90){return ct({queryKey:["commercial-engagement",s,t],queryFn:async()=>{const n=new Date(Date.now()-t*864e5).toISOString(),{data:r,error:a}=await Y4.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 FXe(s){return ct({queryKey:["commercial-leads",s],queryFn:async()=>{const{data:t,error:n}=await Y4.from("listing_leads").select("*").eq("listing_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]},enabled:!!s})}const vmt="lu_commercial_session";function lRt(){try{let s=localStorage.getItem(vmt);return s||(s=crypto.randomUUID(),localStorage.setItem(vmt,s)),s}catch{return"anonymous"}}async function qz(s,t,n={}){try{await Y4.from("commercial_engagement_events").insert({listing_id:s,event_type:t,session_id:lRt(),source:typeof document<"u"&&document.referrer||null,metadata:n})}catch{}}const jAs={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 NAs({open:s,onOpenChange:t,listingId:n,kind:r,documentId:a,requiresNda:i,brokerName:l}){const o=jAs[r],[c,d]=j.useState({firstName:"",lastName:"",email:"",phone:"",company:"",role:"principal",message:""}),[u,h]=j.useState(!1),[m,p]=j.useState(!1),[f,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}p(!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:lRt()}});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{p(!1)}};return e.jsx(zs,{open:s,onOpenChange:v=>{t(v),v||x(null)},children:e.jsxs(Ds,{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:f?"Access granted":o.title}),e.jsx("p",{className:"mt-1.5 text-sm text-white/60",children:f?f.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})]}),f?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(zr,{className:"h-5 w-5 text-emerald-400"}),e.jsx("p",{className:"text-sm text-white/80",children:f.fileName??"Request received"})]}),f.signedUrl&&e.jsx(U,{className:"w-full",onClick:()=>window.open(f.signedUrl,"_blank"),children:"Download again"}),e.jsx(U,{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(YL,{label:"First name *",children:e.jsx(xe,{value:c.firstName,onChange:v=>d({...c,firstName:v.target.value}),className:"border-white/15 bg-white/5 text-white"})}),e.jsx(YL,{label:"Last name",children:e.jsx(xe,{value:c.lastName,onChange:v=>d({...c,lastName:v.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),e.jsx(YL,{label:"Email *",children:e.jsx(xe,{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(YL,{label:"Company",children:e.jsx(xe,{value:c.company,onChange:v=>d({...c,company:v.target.value}),className:"border-white/15 bg-white/5 text-white"})}),e.jsx(YL,{label:"Phone",children:e.jsx(xe,{value:c.phone,onChange:v=>d({...c,phone:v.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),e.jsx(YL,{label:"I am a *",children:e.jsxs(Ns,{value:c.role,onValueChange:v=>d({...c,role:v}),children:[e.jsx(ws,{className:"border-white/15 bg-white/5 text-white",children:e.jsx(ks,{})}),e.jsx(js,{children:Object.entries(Sqe).map(([v,b])=>e.jsx(et,{value:v,children:b},v))})]})}),r!=="om_request"&&e.jsx(YL,{label:"Message",children:e.jsx(Fs,{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(xi,{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(cg,{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(U,{className:"w-full",size:"lg",onClick:y,disabled:m,children:[m?e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ql,{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 YL({label:s,children:t}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-[11px] font-medium uppercase tracking-wider text-white/50",children:s}),t]})}function zXe(s){if(!s)return[];const t=[],n=(r,a)=>{a&&t.push({label:r,value:a})};return n("Cap Rate",mCe(s.cap_rate)),n("NOI",gmt(s.noi)),n("Occupancy",s.occupancy_pct!=null?`${Math.round(Number(s.occupancy_pct))}%`:null),n("Building SF",fA(s.building_sf)),n("Available SF",fA(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?M2(s.price_per_sf,2):null),n("Price / Unit",gmt(s.price_per_unit)),n("Lease Rate",s.deal_type!=="sale"?Cqe(s):null),n("Year Built",null),n("Zoning",s.zoning??null),t}function cRt({details:s,className:t="",tone:n="light"}){const r=zXe(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 kAs(s){return ct({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 SAs({slug:s}){var z,$;const{data:t,isLoading:n,error:r}=kAs(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,p=!!(d!=null&&d.is_confidential||d!=null&&d.hide_address),f=j.useMemo(()=>zXe(d).slice(0,8),[d]);if(j.useEffect(()=>{c!=null&&c.id&&qz(c.id,"page_view",{slug:s})},[c==null?void 0:c.id,s]),j.useEffect(()=>{if(a===null)return;const H=V=>{V.key==="Escape"&&i(null),V.key==="ArrowRight"&&i(K=>K===null?K:(K+1)%h.length),V.key==="ArrowLeft"&&i(K=>K===null?K:(K-1+h.length)%h.length)};return window.addEventListener("keydown",H),()=>window.removeEventListener("keydown",H)},[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=UM(c,d),y=Xne(c,d),v=c.latitude&&c.longitude?`${c.latitude},${c.longitude}`:p?[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=(z=h[0])==null?void 0:z.photo_url,N=(d==null?void 0:d.tenants)??[],S=(d==null?void 0:d.spaces)??[],A=(d==null?void 0:d.demographics)??{},T=(d==null?void 0:d.traffic_counts)??[],L=(d==null?void 0:d.investment_highlights)??[],M=(d==null?void 0:d.property_highlights)??[],I=["radius_1","radius_3","radius_5"].some(H=>(A==null?void 0:A[H])&&Object.values(A[H]).some(Boolean)),R=(H,V)=>{o({kind:H,documentId:V}),qz(c.id,H==="om_request"?"om_request":H,{})};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)||`${uP[(d==null?void 0:d.deal_type)??"sale"]} — ${y}`}),p&&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:uP[(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:qP[d.commercial_type]}),p&&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(Ql,{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(ni,{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:BV(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:mCe(d.cap_rate)})]})]}),e.jsxs("div",{className:"mt-9 flex flex-wrap gap-3",children:[e.jsxs(U,{size:"lg",className:"rounded-full px-7",onClick:()=>{var H;return R("om_request",((H=u.find(V=>V.doc_kind==="om"))==null?void 0:H.id)??null)},children:["Request Offering Memorandum ",e.jsx(Oa,{className:"ml-2 h-4 w-4"})]}),e.jsx(U,{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:()=>R("tour_request"),children:"Schedule a tour"})]})]})]}),f.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(f.length,4)}, minmax(0, 1fr))`},children:f.map(H=>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:H.label}),e.jsx("p",{className:"mt-2 text-2xl font-semibold tabular-nums md:text-3xl",children:H.value})]},H.label))})}),L.length>0&&e.jsx(nT,{eyebrow:"The opportunity",title:"Investment highlights",children:e.jsx("div",{className:"grid gap-x-12 gap-y-8 md:grid-cols-2",children:L.map((H,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:H})]},V))})}),(c.description||M.length>0)&&e.jsx(nT,{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((H,V)=>e.jsx("p",{children:H},V))}),M.length>0&&e.jsx("ul",{className:"space-y-3 self-start rounded-2xl border border-white/10 bg-white/[0.03] p-7",children:M.map((H,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"})," ",H]},V))})]})}),h.length>1&&e.jsx(nT,{eyebrow:"Gallery",title:"Property imagery",children:e.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:h.slice(1,10).map((H,V)=>e.jsx("button",{onClick:()=>{i(V+1),qz(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:H.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]"}`})},H.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(nT,{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:M2(d==null?void 0:d.noi)},{l:"Gross income",v:M2(d==null?void 0:d.gross_income)},{l:"Operating expenses",v:M2(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?M2(d.price_per_sf,2):null},{l:"Price per unit",v:M2(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(H=>H.v).map(H=>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:H.l}),e.jsx("p",{className:"mt-2 text-xl font-semibold tabular-nums",children:H.v})]},H.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"})]})]}),(N.length>0||S.length>0)&&e.jsx(nT,{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:N).map((H,V)=>e.jsxs("tr",{className:"text-white/80",children:[e.jsx("td",{className:"px-6 py-4 font-medium text-white",children:H.suite??H.name??"—"}),e.jsx("td",{className:"px-6 py-4 tabular-nums",children:H.sf?fA(Number(H.sf)):"—"}),e.jsx("td",{className:"px-6 py-4",children:H.rate??H.rent??"—"}),e.jsx("td",{className:"px-6 py-4",children:H.availability??H.lease_expiry??"—"})]},V))})]})})}),e.jsx(nT,{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:()=>qz(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:p?"Exact location released with the Offering Memorandum.":y}),e.jsxs("div",{className:"space-y-5",children:[(d==null?void 0:d.zoning)&&e.jsx($z,{label:"Zoning",value:d.zoning}),(d==null?void 0:d.lot_acres)!=null&&e.jsx($z,{label:"Site size",value:`${d.lot_acres} acres`}),(d==null?void 0:d.parking_spaces)!=null&&e.jsx($z,{label:"Parking",value:`${d.parking_spaces} spaces`}),(d==null?void 0:d.opportunity_zone)&&e.jsx($z,{label:"Opportunity Zone",value:"Qualified"}),T.filter(H=>H.road||H.count).map((H,V)=>e.jsx($z,{label:`Traffic count — ${H.road??"Adjacent road"}`,value:`${H.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($z,{label:"Submarket",value:(d==null?void 0:d.submarket)||y})]})]})}),I&&e.jsx(nT,{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(([H,V])=>{const K=A==null?void 0:A[H];return!K||!Object.values(K).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",K.population],["Households",K.households],["Avg. income",K.avg_income],["Daytime pop.",K.daytime_pop]].filter(([,Z])=>Z).map(([Z,Q])=>e.jsxs("div",{className:"flex justify-between gap-4",children:[e.jsx("dt",{className:"text-white/50",children:Z}),e.jsx("dd",{className:"font-medium tabular-nums",children:Q})]},Z))})]},H)})})}),u.length>0&&e.jsx(nT,{eyebrow:"Deal room",title:"Offering documents",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:u.map(H=>{const V=H.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(pi,{className:"h-5 w-5"}):H.gate_level==="nda"?e.jsx(cg,{className:"h-5 w-5"}):e.jsx(Ql,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate font-medium",children:H.title||kqe[H.doc_kind||"other"]}),e.jsx("p",{className:"text-xs text-white/45",children:V?"Available to download":H.gate_level==="nda"?"Confidentiality acknowledgement required":"Registration required"})]}),e.jsx(U,{size:"sm",variant:"outline",className:"border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>R("om_request",H.id),children:V?"Download":"Request"})]},H.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:(($=m.brokerage)==null?void 0:$.name)||m.brokerage_name})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[m.email&&e.jsxs(U,{variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>{qz(c.id,"contact_click",{}),window.location.href=`mailto:${m.email}`},children:[e.jsx(ln,{className:"mr-2 h-4 w-4"})," Email"]}),m.phone&&e.jsxs(U,{variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>{qz(c.id,"contact_click",{}),window.location.href=`tel:${m.phone}`},children:[e.jsx(ba,{className:"mr-2 h-4 w-4"})," Call"]}),e.jsx(U,{className:"rounded-full",onClick:()=>R("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:[BV(d,c.price)," · ",y]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{size:"sm",variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>R("tour_request"),children:"Tour"}),e.jsx(U,{size:"sm",className:"rounded-full",onClick:()=>{var H;return R("om_request",((H=u.find(V=>V.doc_kind==="om"))==null?void 0:H.id)??null)},children:"Request OM"})]})]})}),e.jsx(zs,{open:a!==null,onOpenChange:H=>!H&&i(null),children:e.jsx(Ds,{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(er,{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(H=>(H-1+h.length)%h.length),children:e.jsx(rd,{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(H=>(H+1)%h.length),children:e.jsx(gi,{className:"h-6 w-6"})})]})})}),l&&e.jsx(NAs,{open:!0,onOpenChange:H=>!H&&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 nT({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 $z({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 bmt="/assets/levelup-logo-color-BeKd2k_g.png",CAs={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"},AAs={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"},_mt={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},voe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),YK=s=>new Intl.NumberFormat("en-US").format(s);function BXe({slugOverride:s}={}){var qt,Ut,Wt,us,zt;const t=Di(),n=s||t.slugOrId,[r]=fc(),{data:a,isLoading:i}=pAs(n||""),l=fAs(),o=gAs(),c=r.get("ref"),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,f]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState(""),[N,S]=j.useState(""),[A,T]=j.useState(""),[L,M]=j.useState("in_person"),[I,R]=j.useState("info"),[z,$]=j.useState(!1),[H,V]=j.useState(!1),[K,Z]=j.useState(null),[Q,le]=j.useState(!1);j.useState(!1);const[ue,se]=j.useState(!1),[ne,ie]=j.useState(20),[ce,je]=j.useState(6.5),[be,he]=j.useState(30),ge=j.useRef(null),[ke,Te]=j.useState(!1);j.useEffect(()=>{const bt=()=>Te(window.scrollY>300);return window.addEventListener("scroll",bt,{passive:!0}),()=>window.removeEventListener("scroll",bt)},[]),j.useEffect(()=>{c&&o.mutate(c)},[c]),j.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[n]);const Me=(a==null?void 0:a.photos)||[],Oe=Me.find(bt=>bt.is_primary)||Me[0],Se=j.useMemo(()=>{if(!(a!=null&&a.price))return 0;const bt=a.price*(1-ne/100),As=ce/100/12,vt=be*12;return As===0?bt/vt:bt*As/(1-Math.pow(1+As,-vt))},[a==null?void 0:a.price,ne,ce,be]),Qe=async()=>{const bt=window.location.href;if(navigator.share)try{await navigator.share({title:document.title,url:bt})}catch{}else await navigator.clipboard.writeText(bt),re.success("Link copied to clipboard")},Ae=async bt=>{if(bt.preventDefault(),!d.trim()||!p.trim()||!a)return;const As=I==="showing";if(As&&!N){re.error("Please pick a preferred date for your showing");return}$(!0);try{await l.mutateAsync({listingId:a.id,agentId:a.agent_id,firstName:d.trim(),lastName:h.trim(),email:p.trim(),phone:x.trim(),shareToken:c,leadType:As?"showing_request":"info_request",preferredDate:As?N:null,preferredTime:As&&A||null,showingMode:As?L:null,message:v.trim()||null}),V(!0),re.success(As?"Showing request sent! The agent will confirm details shortly.":"Thanks! The agent will be in touch soon.")}catch(vt){console.error("Lead submission error:",vt),re.error(`Failed to submit: ${vt.message||"Please try again"}`)}finally{$(!1)}},Fe=()=>{K!==null&&Z(K===0?Me.length-1:K-1)},Ne=()=>{K!==null&&Z(K===Me.length-1?0:K+1)};if((a==null?void 0:a.listing_class)==="commercial")return e.jsx(SAs,{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(xr,{to:"/public/listings",className:"flex items-center gap-2",children:e.jsx("img",{src:bmt,alt:"LevelUp",className:"h-8"})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-24 text-center",children:[e.jsx(ra,{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(U,{asChild:!0,children:e.jsx(xr,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",children:"Browse All Listings"})})]})]});const $e=a.property_address?`${a.property_address} — ${a.city}, ${a.state}`:`${a.city}, ${a.state} Home for Sale`,Ve=((Ut=(qt=a.agent)==null?void 0:qt.brokerage)==null?void 0:Ut.name)||((Wt=a.agent)==null?void 0:Wt.brokerage_name),qe=a.latitude&&a.longitude?`https://maps.google.com/maps?q=${a.latitude},${a.longitude}&z=15&output=embed`:a.property_address?`https://maps.google.com/maps?q=${encodeURIComponent(`${a.property_address}, ${a.city}, ${a.state}`)}&z=15&output=embed`:null,Ze=a.description||"",Ue=Ze.length>420,Ye=ue||!Ue?Ze:Ze.slice(0,420).trimEnd()+"…",Ge=a.page_config||{},He=bt=>{var As;return(((As=Ge.sections)==null?void 0:As[bt])??!0)!==!1},tt=Array.isArray(Ge.addons)?Ge.addons:[],pt=Ge.custom_note||"",ft=Ge.accent_color||null;return e.jsxs(e.Fragment,{children:[e.jsxs(dl,{children:[e.jsxs("title",{children:[$e," | LevelUp Listings"]}),e.jsx("meta",{name:"description",content:`${voe(a.price)} · ${a.bedrooms||""}BD ${a.bathrooms||""}BA ${a.square_footage?a.square_footage.toLocaleString()+" sqft · ":""}${_mt[a.property_type]} in ${a.city}, ${a.state}. ${Ze.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:$e}),e.jsx("meta",{property:"og:description",content:`${voe(a.price)} · ${a.city}, ${a.state}`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:`https://listings.relevelup.com/${a.slug||a.id}`}),Oe&&e.jsx("meta",{property:"og:image",content:Oe.photo_url}),e.jsx("meta",{property:"og:site_name",content:"LevelUp Listings"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:$e}),e.jsx("meta",{name:"twitter:description",content:`${voe(a.price)} · ${a.city}, ${a.state}`}),Oe&&e.jsx("meta",{name:"twitter:image",content:Oe.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:Ze,url:`https://listings.relevelup.com/${a.slug||a.id}`,datePosted:a.created_at,image:Me.map(bt=>bt.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 ${ke?"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(xr,{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(Aa,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium hidden sm:inline",children:"All Listings"})]}),ke&&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(([bt,As])=>e.jsx("a",{href:`#${bt}`,className:"px-3 py-1.5 rounded-full text-white/70 hover:text-white hover:bg-white/10 transition",children:As},bt))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(GCs,{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:Qe,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(jd,{className:"h-4 w-4 text-white"})}),e.jsx(U,{size:"sm",onClick:()=>le(!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:ge,id:"overview",className:"relative h-[100svh] min-h-[620px] w-full overflow-hidden",children:[Oe?e.jsx("img",{src:Oe.photo_url,alt:a.property_address||`${a.city}, ${a.state}`,className:"absolute inset-0 h-full w-full object-cover kb-zoom"}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-neutral-800 to-neutral-950"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black via-black/50 to-black/20"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/40 via-transparent to-transparent"}),e.jsxs("div",{className:"absolute top-24 right-4 sm:right-8 z-10 flex flex-col items-end gap-2",children:[e.jsx(Be,{className:`${CAs[a.status]} text-white border-0 uppercase tracking-widest text-[10px] px-3 py-1 rounded-full shadow-lg`,children:AAs[a.status]}),Me.length>0&&e.jsxs("button",{onClick:()=>Z(0),className:"flex items-center gap-1.5 text-xs text-white/90 bg-black/40 backdrop-blur border border-white/20 rounded-full px-3 py-1.5 hover:bg-black/60 transition",children:[e.jsx(_x,{className:"h-3.5 w-3.5"}),Me.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:voe(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:YK(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(So,{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}),Ve&&e.jsx("p",{className:"text-xs text-white/60",children:Ve})]}),e.jsx(U,{size:"sm",onClick:()=>le(!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"]})]})})]}),He("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:Xw,label:"Bedrooms",value:a.bedrooms},a.bathrooms&&{icon:d0,label:"Bathrooms",value:a.bathrooms},a.square_footage&&{icon:db,label:"Interior",value:`${YK(a.square_footage)} sqft`},a.lot_size&&{icon:I4,label:"Lot Size",value:a.lot_size},a.year_built&&{icon:pa,label:"Year Built",value:a.year_built},!a.year_built&&a.square_footage&&{icon:Qw,label:"Price / sqft",value:`$${YK(Math.round(a.price/a.square_footage))}`}].filter(Boolean).slice(0,5).map((bt,As)=>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(bt.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:bt.label}),e.jsx("p",{className:"font-display text-2xl text-white font-light",children:bt.value})]})]},As))})}),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:[He("story")&&Ze&&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:Ye})}),Ue&&e.jsx("button",{onClick:()=>se(!ue),className:"mt-4 text-sm text-white/60 hover:text-white underline underline-offset-4",children:ue?"Show less":"Read more"}),e.jsxs("div",{className:"mt-8 flex flex-wrap gap-2",children:[e.jsxs(Be,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:[e.jsx(_i,{className:"h-3 w-3 mr-1.5"}),_mt[a.property_type]]}),a.has_hoa&&e.jsx(Be,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:"HOA"}),a.mls_link&&e.jsx(U,{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(Sr,{className:"h-3.5 w-3.5 mr-1.5"})," MLS"]})})]}),(pt||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(cn,{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:['"',pt||a.agent_notes,'"']})]})]}),He("gallery")&&Me.length>1&&e.jsxs("section",{id:"gallery",children:[e.jsxs("div",{className:"flex items-end justify-between mb-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Gallery"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white",children:"Every angle, every detail"})]}),e.jsxs("button",{onClick:()=>Z(0),className:"text-sm text-white/60 hover:text-white underline underline-offset-4 hidden sm:inline",children:["View all ",Me.length]})]}),e.jsx("div",{className:"grid grid-cols-4 gap-2 sm:gap-3",children:Me.slice(0,7).map((bt,As)=>{const vt=["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"],Ws=As===6&&Me.length>7;return e.jsxs("button",{onClick:()=>Z(As),className:`${vt[As]} relative rounded-xl overflow-hidden group bg-neutral-900`,children:[e.jsx("img",{src:bt.photo_url,alt:`Photo ${As+1}`,className:"absolute inset-0 h-full w-full object-cover group-hover:scale-[1.04] transition-transform duration-500"}),Ws&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex flex-col items-center justify-center text-white",children:[e.jsx(_x,{className:"h-6 w-6 mb-1"}),e.jsxs("span",{className:"font-medium",children:["+",Me.length-7," more"]})]})]},bt.id)})})]}),He("video")&&((us=a.video)==null?void 0:us.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"})})]}),He("map")&&qe&&e.jsxs("section",{id:"map",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Location"}),e.jsxs("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:[a.neighborhood?a.neighborhood:a.city,", ",a.state]}),e.jsx("div",{className:"rounded-2xl overflow-hidden border border-white/10 shadow-2xl aspect-[16/10]",children:e.jsx("iframe",{src:qe,className:"w-full h-full grayscale-[.2] contrast-[1.05]",loading:"lazy",title:"Map"})}),e.jsxs("div",{className:"mt-4 flex items-center gap-2 text-white/60 text-sm",children:[e.jsx(ni,{className:"h-4 w-4"}),a.property_address?`${a.property_address}, `:"",a.city,", ",a.state]})]}),He("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:["$",YK(Math.round(Se))]}),e.jsx("p",{className:"text-white/60",children:"/ month"})]}),e.jsxs("div",{className:"grid sm:grid-cols-3 gap-8",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(te,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Down Payment"}),e.jsxs("span",{className:"text-white font-medium",children:[ne,"%"]})]}),e.jsx(rg,{value:[ne],onValueChange:bt=>ie(bt[0]),min:0,max:50,step:1}),e.jsxs("p",{className:"text-xs text-white/50 mt-2",children:["$",YK(Math.round(a.price*ne/100))," down"]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(te,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Interest Rate"}),e.jsxs("span",{className:"text-white font-medium",children:[ce.toFixed(2),"%"]})]}),e.jsx(rg,{value:[ce],onValueChange:bt=>je(bt[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(te,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Loan Term"}),e.jsxs("span",{className:"text-white font-medium",children:[be," yr"]})]}),e.jsx(rg,{value:[be],onValueChange:bt=>he(bt[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."})]})]}),tt.map(bt=>{const As=bt.type,vt=bt.data||{};if(As==="extra_video"&&vt.url){const Ws=String(vt.url).includes("youtu")?`https://www.youtube.com/embed/${String(vt.url).split(/[/=]/).pop()}`:vt.url;return e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:vt.eyebrow||"Featured Video"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:vt.title||"Watch"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:Ws,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:vt.title||"Video"})})]},bt.id)}return As==="3d_tour"&&vt.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:vt.title||"Step inside"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:vt.url,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:"3D Tour"})})]},bt.id):As==="floor_plan"&&vt.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:vt.title||"Layout"}),e.jsx("img",{src:vt.image_url,alt:"Floor plan",className:"w-full rounded-2xl border border-white/10"})]},bt.id):As==="testimonial"&&vt.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:['"',vt.quote,'"']}),vt.author&&e.jsxs("p",{className:"mt-4 text-sm text-white/60",children:["— ",vt.author]})]},bt.id):As==="custom_cta"&&vt.label?e.jsxs("section",{className:"rounded-2xl p-8 text-center",style:{background:ft?`${ft}22`:"rgba(255,255,255,0.05)",border:`1px solid ${ft||"rgba(255,255,255,0.1)"}`},children:[vt.title&&e.jsx("h3",{className:"font-display text-3xl text-white mb-4",children:vt.title}),e.jsx(U,{asChild:!0,size:"lg",style:ft?{background:ft}:void 0,children:e.jsx("a",{href:vt.url||"#agent",children:vt.label})})]},bt.id):null})]}),e.jsxs("aside",{id:"agent",className:"lg:sticky lg:top-24 lg:self-start space-y-6",children:[a.agent&&e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[a.agent.avatar_url?e.jsx("img",{src:a.agent.avatar_url,alt:a.agent.name,className:"h-16 w-16 rounded-full object-cover border-2 border-white/20"}):e.jsx("div",{className:"h-16 w-16 rounded-full bg-white/10 flex items-center justify-center border-2 border-white/20",children:e.jsx(So,{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}),Ve&&e.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:Ve})]})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[a.agent.phone&&e.jsx(U,{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(ba,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),a.agent.email&&e.jsx(U,{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(ln,{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(So,{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(U,{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(ba,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),a.co_agent_email&&e.jsx(U,{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(ln,{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(wmt,{submitted:H,activeTab:I,setActiveTab:R,firstName:d,setFirstName:u,lastName:h,setLastName:m,email:p,setEmail:f,phone:x,setPhone:y,message:v,setMessage:b,preferredDate:N,setPreferredDate:S,preferredTime:A,setPreferredTime:T,showingMode:L,setShowingMode:M,isSubmitting:z,onSubmit:Ae})})]})]}),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:[((zt=a.agent)==null?void 0:zt.phone)&&e.jsx(U,{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(ba,{className:"h-4 w-4 mr-1.5"}),"Call"]})}),e.jsxs(U,{onClick:()=>le(!0),className:"bg-white text-neutral-900 hover:bg-white/90 flex-[2] font-medium",children:[e.jsx(ch,{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:bmt,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:K!==null,onOpenChange:()=>Z(null),children:e.jsxs(Ds,{className:"max-w-6xl p-0 bg-black/95 border-0",children:[e.jsx(Vs,{className:"sr-only",children:e.jsx($s,{children:"Photo Gallery"})}),e.jsx("button",{onClick:()=>Z(null),className:"absolute right-4 top-4 z-50 rounded-full bg-white/10 hover:bg-white/20 p-2 text-white",children:e.jsx(er,{className:"h-5 w-5"})}),K!==null&&Me[K]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:Me[K].photo_url,alt:`Photo ${K+1}`,className:"w-full max-h-[85vh] object-contain"}),Me.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:Fe,className:"absolute left-4 top-1/2 -translate-y-1/2 rounded-full bg-white/10 hover:bg-white/20 p-3 text-white",children:e.jsx(rd,{className:"h-6 w-6"})}),e.jsx("button",{onClick:Ne,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(gi,{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:[K+1," / ",Me.length]})]})]})]})}),e.jsx(zs,{open:Q,onOpenChange:le,children:e.jsxs(Ds,{className:"max-w-md p-0 bg-white text-neutral-900",children:[e.jsx(Vs,{className:"sr-only",children:e.jsx($s,{children:"Contact the agent"})}),e.jsx("div",{className:"p-6",children:e.jsx(wmt,{submitted:H,activeTab:I,setActiveTab:R,firstName:d,setFirstName:u,lastName:h,setLastName:m,email:p,setEmail:f,phone:x,setPhone:y,message:v,setMessage:b,preferredDate:N,setPreferredDate:S,preferredTime:A,setPreferredTime:T,showingMode:L,setShowingMode:M,isSubmitting:z,onSubmit:Ae})})]})})]})]})}function wmt(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:p,preferredDate:f,setPreferredDate:x,preferredTime:y,setPreferredTime:v,showingMode:b,setShowingMode:N,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(Xr,{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(oa,{value:n,onValueChange:T=>r(T),children:[e.jsxs(la,{className:"grid w-full grid-cols-2 mb-4",children:[e.jsxs(Kt,{value:"info",className:"gap-1.5",children:[e.jsx(Ki,{className:"h-3.5 w-3.5"})," Get Info"]}),e.jsxs(Kt,{value:"showing",className:"gap-1.5",children:[e.jsx(ch,{className:"h-3.5 w-3.5"})," Request Tour"]})]}),e.jsxs("form",{onSubmit:A,className:"space-y-3",children:[e.jsxs(Zt,{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(te,{htmlFor:"preferredDate",children:"Preferred Date *"}),e.jsx(xe,{id:"preferredDate",type:"date",value:f,onChange:T=>x(T.target.value),min:new Date().toISOString().split("T")[0],required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"preferredTime",children:"Preferred Time"}),e.jsxs(Ns,{value:y,onValueChange:v,children:[e.jsx(ws,{id:"preferredTime",children:e.jsx(ks,{placeholder:"Any time"})}),e.jsxs(js,{children:[e.jsx(et,{value:"morning",children:"Morning (9am–12pm)"}),e.jsx(et,{value:"afternoon",children:"Afternoon (12pm–5pm)"}),e.jsx(et,{value:"evening",children:"Evening (5pm–8pm)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"showingMode",children:"Tour Type"}),e.jsxs(Ns,{value:b,onValueChange:T=>N(T),children:[e.jsx(ws,{id:"showingMode",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"in_person",children:"🏡 In-person showing"}),e.jsx(et,{value:"video",children:"📱 Video tour (FaceTime/Zoom)"}),e.jsx(et,{value:"either",children:"Either works for me"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(te,{htmlFor:"firstName",children:"First Name *"}),e.jsx(xe,{id:"firstName",value:a,onChange:T=>i(T.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"lastName",children:"Last Name"}),e.jsx(xe,{id:"lastName",value:l,onChange:T=>o(T.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"email",children:"Email *"}),e.jsx(xe,{id:"email",type:"email",value:c,onChange:T=>d(T.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsxs(te,{htmlFor:"phone",children:["Phone ",n==="showing"&&"*"]}),e.jsx(xe,{id:"phone",type:"tel",value:u,onChange:T=>h(T.target.value),required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"message",children:n==="showing"?"Anything else?":"Message (optional)"}),e.jsx(Fs,{id:"message",value:m,onChange:T=>p(T.target.value),rows:2})]}),e.jsx(U,{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 UV="/assets/levelup-logo-white-C2RAgAoG.png",EAs="/assets/listings-hero-noir-BHCJrhvU.jpg";var dRt={exports:{}};(function(s,t){(function(n,r){s.exports=r()})(op,function(){let n,r,a;function i(o,c){if(!n)n=c;else if(!r)r=c;else{const d={};n(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 = {}; ("+n+")(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(["exports"],function(o){var c=1e-6,d=typeof Float32Array<"u"?Float32Array:Array;function u(k,g){var _=g[0],C=g[1],P=g[2],O=g[3],B=_*O-P*C;return B?(k[0]=O*(B=1/B),k[1]=-C*B,k[2]=-P*B,k[3]=_*B,k):null}function h(){var k=new d(9);return d!=Float32Array&&(k[1]=0,k[2]=0,k[3]=0,k[5]=0,k[6]=0,k[7]=0),k[0]=1,k[4]=1,k[8]=1,k}function m(k,g){var _=g[0],C=g[1],P=g[2],O=g[3],B=g[4],W=g[5],Y=g[6],ae=g[7],pe=g[8];return k[0]=B*pe-W*ae,k[1]=P*ae-C*pe,k[2]=C*W-P*B,k[3]=W*Y-O*pe,k[4]=_*pe-P*Y,k[5]=P*O-_*W,k[6]=O*ae-B*Y,k[7]=C*Y-_*ae,k[8]=_*B-C*O,k}function p(k,g,_){var C=g[0],P=g[1],O=g[2],B=g[3],W=g[4],Y=g[5],ae=g[6],pe=g[7],ve=g[8],_e=_[0],Pe=_[1],De=_[2],We=_[3],Je=_[4],rt=_[5],xt=_[6],ut=_[7],St=_[8];return k[0]=_e*C+Pe*B+De*ae,k[1]=_e*P+Pe*W+De*pe,k[2]=_e*O+Pe*Y+De*ve,k[3]=We*C+Je*B+rt*ae,k[4]=We*P+Je*W+rt*pe,k[5]=We*O+Je*Y+rt*ve,k[6]=xt*C+ut*B+St*ae,k[7]=xt*P+ut*W+St*pe,k[8]=xt*O+ut*Y+St*ve,k}function f(){var k=new d(16);return d!=Float32Array&&(k[1]=0,k[2]=0,k[3]=0,k[4]=0,k[6]=0,k[7]=0,k[8]=0,k[9]=0,k[11]=0,k[12]=0,k[13]=0,k[14]=0),k[0]=1,k[5]=1,k[10]=1,k[15]=1,k}function x(k){var g=new d(16);return g[0]=k[0],g[1]=k[1],g[2]=k[2],g[3]=k[3],g[4]=k[4],g[5]=k[5],g[6]=k[6],g[7]=k[7],g[8]=k[8],g[9]=k[9],g[10]=k[10],g[11]=k[11],g[12]=k[12],g[13]=k[13],g[14]=k[14],g[15]=k[15],g}function y(k){return k[0]=1,k[1]=0,k[2]=0,k[3]=0,k[4]=0,k[5]=1,k[6]=0,k[7]=0,k[8]=0,k[9]=0,k[10]=1,k[11]=0,k[12]=0,k[13]=0,k[14]=0,k[15]=1,k}function v(k,g){var _=g[0],C=g[1],P=g[2],O=g[3],B=g[4],W=g[5],Y=g[6],ae=g[7],pe=g[8],ve=g[9],_e=g[10],Pe=g[11],De=g[12],We=g[13],Je=g[14],rt=g[15],xt=_*W-C*B,ut=_*Y-P*B,St=_*ae-O*B,Rt=C*Y-P*W,Ft=C*ae-O*W,bs=P*ae-O*Y,as=pe*We-ve*De,ys=pe*Je-_e*De,hs=pe*rt-Pe*De,ms=ve*Je-_e*We,vn=ve*rt-Pe*We,Nn=_e*rt-Pe*Je,Tn=xt*Nn-ut*vn+St*ms+Rt*hs-Ft*ys+bs*as;return Tn?(k[0]=(W*Nn-Y*vn+ae*ms)*(Tn=1/Tn),k[1]=(P*vn-C*Nn-O*ms)*Tn,k[2]=(We*bs-Je*Ft+rt*Rt)*Tn,k[3]=(_e*Ft-ve*bs-Pe*Rt)*Tn,k[4]=(Y*hs-B*Nn-ae*ys)*Tn,k[5]=(_*Nn-P*hs+O*ys)*Tn,k[6]=(Je*St-De*bs-rt*ut)*Tn,k[7]=(pe*bs-_e*St+Pe*ut)*Tn,k[8]=(B*vn-W*hs+ae*as)*Tn,k[9]=(C*hs-_*vn-O*as)*Tn,k[10]=(De*Ft-We*St+rt*xt)*Tn,k[11]=(ve*St-pe*Ft-Pe*xt)*Tn,k[12]=(W*ys-B*ms-Y*as)*Tn,k[13]=(_*ms-C*ys+P*as)*Tn,k[14]=(We*ut-De*Rt-Je*xt)*Tn,k[15]=(pe*Rt-ve*ut+_e*xt)*Tn,k):null}function b(k,g,_){var C=g[0],P=g[1],O=g[2],B=g[3],W=g[4],Y=g[5],ae=g[6],pe=g[7],ve=g[8],_e=g[9],Pe=g[10],De=g[11],We=g[12],Je=g[13],rt=g[14],xt=g[15],ut=_[0],St=_[1],Rt=_[2],Ft=_[3];return k[0]=ut*C+St*W+Rt*ve+Ft*We,k[1]=ut*P+St*Y+Rt*_e+Ft*Je,k[2]=ut*O+St*ae+Rt*Pe+Ft*rt,k[3]=ut*B+St*pe+Rt*De+Ft*xt,k[4]=(ut=_[4])*C+(St=_[5])*W+(Rt=_[6])*ve+(Ft=_[7])*We,k[5]=ut*P+St*Y+Rt*_e+Ft*Je,k[6]=ut*O+St*ae+Rt*Pe+Ft*rt,k[7]=ut*B+St*pe+Rt*De+Ft*xt,k[8]=(ut=_[8])*C+(St=_[9])*W+(Rt=_[10])*ve+(Ft=_[11])*We,k[9]=ut*P+St*Y+Rt*_e+Ft*Je,k[10]=ut*O+St*ae+Rt*Pe+Ft*rt,k[11]=ut*B+St*pe+Rt*De+Ft*xt,k[12]=(ut=_[12])*C+(St=_[13])*W+(Rt=_[14])*ve+(Ft=_[15])*We,k[13]=ut*P+St*Y+Rt*_e+Ft*Je,k[14]=ut*O+St*ae+Rt*Pe+Ft*rt,k[15]=ut*B+St*pe+Rt*De+Ft*xt,k}function N(k,g,_){var C,P,O,B,W,Y,ae,pe,ve,_e,Pe,De,We=_[0],Je=_[1],rt=_[2];return g===k?(k[12]=g[0]*We+g[4]*Je+g[8]*rt+g[12],k[13]=g[1]*We+g[5]*Je+g[9]*rt+g[13],k[14]=g[2]*We+g[6]*Je+g[10]*rt+g[14],k[15]=g[3]*We+g[7]*Je+g[11]*rt+g[15]):(P=g[1],O=g[2],B=g[3],W=g[4],Y=g[5],ae=g[6],pe=g[7],ve=g[8],_e=g[9],Pe=g[10],De=g[11],k[0]=C=g[0],k[1]=P,k[2]=O,k[3]=B,k[4]=W,k[5]=Y,k[6]=ae,k[7]=pe,k[8]=ve,k[9]=_e,k[10]=Pe,k[11]=De,k[12]=C*We+W*Je+ve*rt+g[12],k[13]=P*We+Y*Je+_e*rt+g[13],k[14]=O*We+ae*Je+Pe*rt+g[14],k[15]=B*We+pe*Je+De*rt+g[15]),k}function S(k,g,_){var C=_[0],P=_[1],O=_[2];return k[0]=g[0]*C,k[1]=g[1]*C,k[2]=g[2]*C,k[3]=g[3]*C,k[4]=g[4]*P,k[5]=g[5]*P,k[6]=g[6]*P,k[7]=g[7]*P,k[8]=g[8]*O,k[9]=g[9]*O,k[10]=g[10]*O,k[11]=g[11]*O,k[12]=g[12],k[13]=g[13],k[14]=g[14],k[15]=g[15],k}function A(k,g,_){var C=Math.sin(_),P=Math.cos(_),O=g[4],B=g[5],W=g[6],Y=g[7],ae=g[8],pe=g[9],ve=g[10],_e=g[11];return g!==k&&(k[0]=g[0],k[1]=g[1],k[2]=g[2],k[3]=g[3],k[12]=g[12],k[13]=g[13],k[14]=g[14],k[15]=g[15]),k[4]=O*P+ae*C,k[5]=B*P+pe*C,k[6]=W*P+ve*C,k[7]=Y*P+_e*C,k[8]=ae*P-O*C,k[9]=pe*P-B*C,k[10]=ve*P-W*C,k[11]=_e*P-Y*C,k}function T(k,g,_){var C=Math.sin(_),P=Math.cos(_),O=g[0],B=g[1],W=g[2],Y=g[3],ae=g[8],pe=g[9],ve=g[10],_e=g[11];return g!==k&&(k[4]=g[4],k[5]=g[5],k[6]=g[6],k[7]=g[7],k[12]=g[12],k[13]=g[13],k[14]=g[14],k[15]=g[15]),k[0]=O*P-ae*C,k[1]=B*P-pe*C,k[2]=W*P-ve*C,k[3]=Y*P-_e*C,k[8]=O*C+ae*P,k[9]=B*C+pe*P,k[10]=W*C+ve*P,k[11]=Y*C+_e*P,k}function L(k,g,_){var C=Math.sin(_),P=Math.cos(_),O=g[0],B=g[1],W=g[2],Y=g[3],ae=g[4],pe=g[5],ve=g[6],_e=g[7];return g!==k&&(k[8]=g[8],k[9]=g[9],k[10]=g[10],k[11]=g[11],k[12]=g[12],k[13]=g[13],k[14]=g[14],k[15]=g[15]),k[0]=O*P+ae*C,k[1]=B*P+pe*C,k[2]=W*P+ve*C,k[3]=Y*P+_e*C,k[4]=ae*P-O*C,k[5]=pe*P-B*C,k[6]=ve*P-W*C,k[7]=_e*P-Y*C,k}function M(k,g){return k[0]=g[0],k[1]=0,k[2]=0,k[3]=0,k[4]=0,k[5]=g[1],k[6]=0,k[7]=0,k[8]=0,k[9]=0,k[10]=g[2],k[11]=0,k[12]=0,k[13]=0,k[14]=0,k[15]=1,k}function I(k,g,_){var C,P,O,B=_[0],W=_[1],Y=_[2],ae=Math.sqrt(B*B+W*W+Y*Y);return ae0&&(O=1/Math.sqrt(O)),k[0]=g[0]*O,k[1]=g[1]*O,k[2]=g[2]*O,k}function Me(k,g){return k[0]*g[0]+k[1]*g[1]+k[2]*g[2]}function Oe(k,g,_){var C=g[0],P=g[1],O=g[2],B=_[0],W=_[1],Y=_[2];return k[0]=P*Y-O*W,k[1]=O*B-C*Y,k[2]=C*W-P*B,k}function Se(k,g,_,C){var P=g[0],O=g[1],B=g[2];return k[0]=P+C*(_[0]-P),k[1]=O+C*(_[1]-O),k[2]=B+C*(_[2]-B),k}function Qe(k,g,_){var C=g[0],P=g[1],O=g[2],B=_[3]*C+_[7]*P+_[11]*O+_[15];return k[0]=(_[0]*C+_[4]*P+_[8]*O+_[12])/(B=B||1),k[1]=(_[1]*C+_[5]*P+_[9]*O+_[13])/B,k[2]=(_[2]*C+_[6]*P+_[10]*O+_[14])/B,k}function Ae(k,g,_){var C=g[0],P=g[1],O=g[2];return k[0]=C*_[0]+P*_[3]+O*_[6],k[1]=C*_[1]+P*_[4]+O*_[7],k[2]=C*_[2]+P*_[5]+O*_[8],k}function Fe(k,g,_){var C=_[0],P=_[1],O=_[2],B=_[3],W=g[0],Y=g[1],ae=g[2],pe=P*ae-O*Y,ve=O*W-C*ae,_e=C*Y-P*W;return k[0]=W+B*(pe+=pe)+P*(_e+=_e)-O*(ve+=ve),k[1]=Y+B*ve+O*pe-C*_e,k[2]=ae+B*_e+C*ve-P*pe,k}function Ne(k){return k[0]=0,k[1]=0,k[2]=0,k}function $e(k,g){return k[0]===g[0]&&k[1]===g[1]&&k[2]===g[2]}var Ve=ue,qe=se,Ze=K;function Ue(){var k=new d(4);return d!=Float32Array&&(k[0]=0,k[1]=0,k[2]=0,k[3]=0),k}function Ye(k,g,_){return k[0]=g[0]*_,k[1]=g[1]*_,k[2]=g[2]*_,k[3]=g[3]*_,k}function Ge(k,g){var _=g[0],C=g[1],P=g[2],O=g[3],B=_*_+C*C+P*P+O*O;return B>0&&(B=1/Math.sqrt(B)),k[0]=_*B,k[1]=C*B,k[2]=P*B,k[3]=O*B,k}function He(k,g){return k[0]*g[0]+k[1]*g[1]+k[2]*g[2]+k[3]*g[3]}function tt(k,g,_){var C=g[0],P=g[1],O=g[2],B=g[3];return k[0]=_[0]*C+_[4]*P+_[8]*O+_[12]*B,k[1]=_[1]*C+_[5]*P+_[9]*O+_[13]*B,k[2]=_[2]*C+_[6]*P+_[10]*O+_[14]*B,k[3]=_[3]*C+_[7]*P+_[11]*O+_[15]*B,k}function pt(){var k=new d(4);return d!=Float32Array&&(k[0]=0,k[1]=0,k[2]=0),k[3]=1,k}function ft(k){return k[0]=0,k[1]=0,k[2]=0,k[3]=1,k}function qt(k,g,_){_*=.5;var C=g[0],P=g[1],O=g[2],B=g[3],W=Math.sin(_),Y=Math.cos(_);return k[0]=C*Y+B*W,k[1]=P*Y+O*W,k[2]=O*Y-P*W,k[3]=B*Y-C*W,k}function Ut(k,g,_){_*=.5;var C=g[0],P=g[1],O=g[2],B=g[3],W=Math.sin(_),Y=Math.cos(_);return k[0]=C*Y-O*W,k[1]=P*Y+B*W,k[2]=O*Y+C*W,k[3]=B*Y-P*W,k}H(),Ue();var Wt,us,zt,bt=Ge,As=(Wt=H(),us=Z(1,0,0),zt=Z(0,1,0),function(k,g,_){var C=Me(g,_);return C<-.999999?(Oe(Wt,us,g),Ze(Wt)<1e-6&&Oe(Wt,zt,g),Te(Wt,Wt),function(P,O,B){B*=.5;var W=Math.sin(B);P[0]=W*O[0],P[1]=W*O[1],P[2]=W*O[2],P[3]=Math.cos(B)}(k,Wt,Math.PI),k):C>.999999?(k[0]=0,k[1]=0,k[2]=0,k[3]=1,k):(Oe(Wt,g,_),k[0]=Wt[0],k[1]=Wt[1],k[2]=Wt[2],k[3]=1+C,bt(k,k))});function vt(){var k=new d(2);return d!=Float32Array&&(k[0]=0,k[1]=0),k}function Ws(k,g){var _=new d(2);return _[0]=k,_[1]=g,_}function on(k,g,_){return k[0]=g,k[1]=_,k}function Ms(k,g,_){return k[0]=g[0]+_[0],k[1]=g[1]+_[1],k}function dn(k,g,_){return k[0]=g[0]-_[0],k[1]=g[1]-_[1],k}function rn(k,g,_){return k[0]=g[0]*_,k[1]=g[1]*_,k}function br(k){var g=k[0],_=k[1];return Math.sqrt(g*g+_*_)}function Gn(k,g){var _=g[0],C=g[1],P=_*_+C*C;return P>0&&(P=1/Math.sqrt(P)),k[0]=g[0]*P,k[1]=g[1]*P,k}function On(k,g){return k[0]*g[0]+k[1]*g[1]}pt(),pt(),h();var Rr,cr,Hs=dn;function _r(k){return k&&k.__esModule&&Object.prototype.hasOwnProperty.call(k,"default")?k.default:k}vt();var nn=function(){if(cr)return Rr;function k(g,_,C,P){this.cx=3*g,this.bx=3*(C-g)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*_,this.by=3*(P-_)-this.cy,this.ay=1-this.cy-this.by,this.p1x=g,this.p1y=_,this.p2x=C,this.p2y=P}return cr=1,Rr=k,k.prototype={sampleCurveX:function(g){return((this.ax*g+this.bx)*g+this.cx)*g},sampleCurveY:function(g){return((this.ay*g+this.by)*g+this.cy)*g},sampleCurveDerivativeX:function(g){return(3*this.ax*g+2*this.bx)*g+this.cx},solveCurveX:function(g,_){if(_===void 0&&(_=1e-6),g<0)return 0;if(g>1)return 1;for(var C=g,P=0;P<8;P++){var O=this.sampleCurveX(C)-g;if(Math.abs(O)<_)return C;var B=this.sampleCurveDerivativeX(C);if(Math.abs(B)<1e-6)break;C-=O/B}var W=0,Y=1;for(C=g,P=0;P<20&&(O=this.sampleCurveX(C),!(Math.abs(O-g)<_));P++)g>O?W=C:Y=C,C=.5*(Y-W)+W;return C},solve:function(g,_){return this.sampleCurveY(this.solveCurveX(g,_))}},Rr}(),Zn=_r(nn);function es(k,g){this.x=k,this.y=g}function ar(k,g){if(Array.isArray(k)){if(!Array.isArray(g)||k.length!==g.length)return!1;for(let _=0;_=1)return 1;const g=k*k,_=g*k;return 4*(k<.5?_:3*(k-g)+_-.75)}function fs(k,g,_,C){const P=new Zn(k,g,_,C);return function(O){return P.solve(O)}}const ot=fs(.25,.1,.25,1);function mt(k,g,_){return Math.min(_,Math.max(g,k))}function Nt(k,g,_){return(_=mt((_-k)/(g-k),0,1))*_*(3-2*_)}function Pt(k,g,_){const C=_-g,P=((k-g)%C+C)%C+g;return P===g?_:P}function ts(k,g,_){if(!k.length)return _(null,[]);let C=k.length;const P=new Array(k.length);let O=null;k.forEach((B,W)=>{g(B,(Y,ae)=>{Y&&(O=Y),P[W]=ae,--C===0&&_(O,P)})})}let ls=1;function Is(){return ls++}function ps(k){return k<=1?1:Math.pow(2,Math.ceil(Math.log2(k)))}function Ht(k,g){k.forEach(_=>{g[_]&&(g[_]=g[_].bind(g))})}function Xs(k,g,_){const C={};for(const P in k)C[P]=g.call(this,k[P],P,k);return C}function Rs(k,g,_){const C={};for(const P in k)g.call(this,k[P],P,k)&&(C[P]=k[P]);return C}function zn(k){return Array.isArray(k)?k.map(zn):typeof k=="object"&&k?Xs(k,zn):k}function Qr(k,g){for(let _=0;_=0)return!0;return!1}const ma={};function qr(k){ma[k]||(typeof console<"u"&&console.warn(k),ma[k]=!0)}function Zr(k,g,_){return(_.y-k.y)*(g.x-k.x)>(g.y-k.y)*(_.x-k.x)}function Jr(k){let g=0;for(let _,C,P=0,O=k.length,B=O-1;P@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(_,C,P,O)=>{const B=P||O;return g[C]=!B||B.toLowerCase(),""}),g["max-age"]){const _=parseInt(g["max-age"],10);isNaN(_)?delete g["max-age"]:g["max-age"]=_}return g}let Xo,Vi=null;function Ja(k,g){return[k[4*g],k[4*g+1],k[4*g+2],k[4*g+3]]}function Co(k,g,_,C){for(;g<_;){const P=g+_>>1;k[P]>1;k[P]<=C?g=P+1:_=P}return g}function hi(k){return k>0?1/(1.001-k):1+k}function Qo(k){return k>0?1-1/(1.001-k):-k}function Ao(k,g,_){return(k-g.min)*(_.max-_.min)/(g.max-g.min)+_.min}const _a={API_URL:"https://api.mapbox.com",get API_URL_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/|\?|$)/i},get API_TILEJSON_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/v[0-9]*\/.*\.json.*$)/i},get API_SPRITE_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/styles\/v[0-9]*\/)(.*\/sprite.*\..*$)/i},get API_FONTS_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/fonts\/v[0-9]*\/)(.*\.pbf.*$)/i},get API_STYLE_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/styles\/v[0-9]*\/)(.*$)/i},get API_CDN_URL_REGEX(){return/^((https?:)?\/\/)?api\.mapbox\.c(n|om)(\/mapbox-gl-js\/)(.*$)/i},get EVENTS_URL(){if(!_a.API_URL)return null;try{const k=new URL(_a.API_URL);return k.hostname==="api.mapbox.cn"?"https://events.mapbox.cn/events/v2":k.hostname==="api.mapbox.com"?"https://events.mapbox.com/events/v2":null}catch{return null}},SESSION_PATH:"/map-sessions/v1",FEEDBACK_URL:"https://apps.mapbox.com/feedback",TILE_URL_VERSION:"v4",RASTER_URL_PREFIX:"raster/v1",RASTERARRAYS_URL_PREFIX:"rasterarrays/v1",REQUIRE_ACCESS_TOKEN:!0,ACCESS_TOKEN:null,DEFAULT_STYLE:"mapbox://styles/mapbox/standard",MAX_PARALLEL_IMAGE_REQUESTS:16,DRACO_URL:"/mapbox-gl-js/draco_decoder_gltf_v1.5.6.wasm",MESHOPT_URL:"/mapbox-gl-js/meshopt_base_v0.20.wasm",MESHOPT_SIMD_URL:"/mapbox-gl-js/meshopt_simd_v0.20.wasm",BUILDING_GEN_URL:"/mapbox-gl-js/building-gen/building_gen_v1.2.4.wasm",GLYPHS_URL:"mapbox://fonts/mapbox/{fontstack}/{range}.pbf",TILES3D_URL_PREFIX:"3dtiles/v1",TILE_PROVIDER_URLS:Object.assign(Object.create(null),{pmtiles:"/mapbox-gl-js/mapbox-gl-pmtiles-provider-v0.0.1.js"})};function ir(){return new URL(_a.DRACO_URL,_a.API_URL).href}function li(){if(typeof WebAssembly!="object")throw new Error("WebAssembly not supported, cannot instantiate meshoptimizer");return new URL(function(){if(Xo===void 0){if(typeof WebAssembly!="object")return!1;const k=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,12,1,0,10,22,2,12,0,65,0,65,0,65,0,252,10,0,0,11,7,0,65,0,253,15,26,11]);Xo=WebAssembly.validate(k)}return Xo}()?_a.MESHOPT_SIMD_URL:_a.MESHOPT_URL,_a.API_URL).href}function Eo(){return new URL(_a.BUILDING_GEN_URL,_a.API_URL).href}function gl(k){return _a.API_URL_REGEX.test(k)}function ds(k){return _a.API_SPRITE_REGEX.test(k)}let Gr,ji,ya,Wi,wi,di;function Dc(){return Gr==null&&(Gr=self.OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),Gr}const fd={now:()=>Wi!==void 0?Wi:performance.now(),setNow(k){Wi=k},restoreNow(){Wi=void 0},frame(k){const g=requestAnimationFrame(k);return{cancel:()=>cancelAnimationFrame(g)}},getImageData(k,g=0){const{width:_,height:C}=k;wi||(wi=document.createElement("canvas"));const P=wi.getContext("2d",{willReadFrequently:!0});if(!P)throw new Error("failed to create canvas 2d context");return(_>wi.width||C>wi.height)&&(wi.width=_,wi.height=C),P.clearRect(-g,-g,_+2*g,C+2*g),P.drawImage(k,0,0,_,C),P.getImageData(-g,-g,_+2*g,C+2*g)},resolveURL:k=>(ji||(ji=document.createElement("a")),ji.href=k,ji.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(ya==null&&(ya=window.matchMedia("(prefers-reduced-motion: reduce)")),ya.matches)},hasCanvasFingerprintNoise(){if(di!==void 0)return di;if(!Dc())return di=!1,!1;const k=new OffscreenCanvas(85,1),g=k.getContext("2d",{willReadFrequently:!0});let _=0;for(let P=0;P0?`?${O}`:""}`}const Jo="mapbox-tiles";let il=500,Hp=50;const fg=["language","worldview","jobid"];let Lh;function by(){try{return caches}catch{}}function qo(){const k=by();k&&Lh==null&&(Lh=k.open(Jo))}let bo=1/0;const Ex={supported:!1,testSupport:function(k){!gg&&up&&(Vl?Jd(k):dp=k)}};let dp,up,gg=!1,Vl=!1;const hp=typeof self<"u"?self:{};function Jd(k){const g=k.createTexture();k.bindTexture(k.TEXTURE_2D,g);try{if(k.texImage2D(k.TEXTURE_2D,0,k.RGBA,k.RGBA,k.UNSIGNED_BYTE,up),k.isContextLost())return;Ex.supported=!0}catch{}k.deleteTexture(g),gg=!0}hp.document&&(up=hp.document.createElement("img"),up.onload=function(){dp&&Jd(dp),dp=null,Vl=!0},up.onerror=function(){gg=!0,dp=null},up.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");const Mu={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(Mu);class kv extends Error{constructor(g,_,C){_===401&&gl(C)&&(g+=": you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes"),super(g),this.status=_,this.url=C}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}function _u(k){return typeof k=="object"&&k!==null&&"status"in k&&k.status===404}const zi=Fa()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,zm=function(k,g){return/^file:/.test(_=k.url)||/^file:/.test(zi())&&!/^\w+:/.test(_)?function(C,P){const O=new XMLHttpRequest;O.open(C.method||"GET",C.url,!0),C.type==="arrayBuffer"&&(O.responseType="arraybuffer");for(const B in C.headers)O.setRequestHeader(B,C.headers[B]);return C.type==="json"&&(O.responseType="text",O.setRequestHeader("Accept","application/json")),O.withCredentials=C.credentials==="include",O.onerror=()=>{P(new Error(O.statusText))},O.onload=()=>{if((O.status>=200&&O.status<300||O.status===0)&&O.response!==null){let B=O.response;if(C.type==="json")try{B=JSON.parse(O.response)}catch(Y){return P(Y)}const W=new Headers;O.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(Y=>{const ae=Y.split(": "),pe=ae.shift(),ve=ae.join(": ");W.append(pe,ve)}),P(null,B,W)}else P(new kv(O.statusText,O.status,C.url))},O.send(C.body),{cancel:()=>O.abort()}}(k,g):function(C,P){const O=new AbortController,B=new Request(C.url,{method:C.method||"GET",body:C.body,credentials:C.credentials,headers:C.headers,referrer:zi(),referrerPolicy:C.referrerPolicy,signal:O.signal});let W=!1,Y=!1;const ae=(pe=B.url).indexOf("sku=")>0&&gl(pe);var pe;C.type==="json"&&B.headers.set("Accept","application/json");const ve=(Pe,De,We)=>{if(Y)return;if(Pe&&Pe.message!=="SecurityError"&&qr(Pe.toString()),De&&We)return _e(De);const Je=Date.now();fetch(B).then(rt=>{if(rt.ok){const xt=ae?rt.clone():null;return _e(rt,xt,Je)}return P(new kv(rt.statusText,rt.status,C.url))}).catch(rt=>{rt.name!=="AbortError"&&P(new Error(`${rt.message} ${C.url}`))})},_e=(Pe,De,We)=>{(C.type==="arrayBuffer"?Pe.arrayBuffer():C.type==="json"?Pe.json():Pe.text()).then(Je=>{Y||(De&&We&&function(rt,xt,ut){if(qo(),Lh==null)return;const St=Fo(xt.headers.get("cache-control")||"");if(St["no-store"])return;const Rt={status:xt.status,statusText:xt.statusText,headers:new Headers};xt.headers.forEach((hs,ms)=>Rt.headers.set(ms,hs)),St["max-age"]&&Rt.headers.set("Expires",new Date(ut+1e3*St["max-age"]).toUTCString());const Ft=Rt.headers.get("expires");if(!Ft||new Date(Ft).getTime()-ut<42e4)return;let bs=vy(rt.url,{persistentParams:fg});if(xt.status===206){const hs=rt.headers.get("Range");if(!hs)return;Rt.status=200,bs=Vp(bs,{range:hs})}const as=new Response((ys=xt.status)!==200&&ys!==404&&[101,103,204,205,304].includes(ys)?null:xt.body,Rt);var ys;qo(),Lh!=null&&Lh.then(hs=>hs.put(bs,as)).catch(hs=>qr(hs.message))}(B,De,We),W=!0,P(null,Je,Pe.headers))}).catch(Je=>{Y||P(new Error(Je.message))})};return ae?function(Pe,De){if(qo(),Lh==null)return De(null);Lh.then(We=>{let Je=vy(Pe.url,{persistentParams:fg});const rt=Pe.headers.get("Range");rt&&(Je=Vp(Je,{range:rt})),We.match(Je).then(xt=>{const ut=function(St){if(!St)return!1;const Rt=new Date(St.headers.get("expires")||0),Ft=Fo(St.headers.get("cache-control")||"");return Number(Rt)>Date.now()&&!Ft["no-cache"]}(xt);We.delete(Je).catch(De),ut&&We.put(Je,xt.clone()).catch(De),De(null,xt,ut)}).catch(De)}).catch(De)}(B,ve):ve(null,null),{cancel:()=>{Y=!0,W||O.abort()}}}(k,g);var _},Qh=function(k,g){return zm(Object.assign(k,{type:"arrayBuffer"}),g)};function mp(k){const g=document.createElement("a");return g.href=k,g.protocol===location.protocol&&g.host===location.host}let If,Jh;If=[],Jh=0;const Bm=function(k,g){if(Ex.supported&&(k.headers||(k.headers={}),k.headers.accept="image/webp,*/*"),Jh>=_a.MAX_PARALLEL_IMAGE_REQUESTS){const O={requestParameters:k,callback:g,cancelled:!1,cancel(){this.cancelled=!0}};return If.push(O),O}Jh++;let _=!1;const C=()=>{if(!_)for(_=!0,Jh--;If.length&&Jh<_a.MAX_PARALLEL_IMAGE_REQUESTS;){const O=If.shift(),{requestParameters:B,callback:W,cancelled:Y}=O;Y||(O.cancel=Bm(B,W).cancel)}},P=Qh(k,(O,B,W)=>{C(),O?g(O):B&&function(Y,ae){const pe=new Blob([new Uint8Array(Y)],{type:"image/png"});createImageBitmap(pe).then(ve=>{ae(null,ve)}).catch(ve=>{ae(new Error(`Could not load image because of ${ve.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`))})}(B,(Y,ae)=>g(Y,ae,W))});return{cancel:()=>{P.cancel(),C()}}};var j0,N0,pp,Um={exports:{}},Tx={exports:{}},Qg={exports:{}},_y=function(){if(pp)return Um.exports;pp=1;var k=(j0||(j0=1,Tx.exports=function(_,C){var P,O,B,W,Y,ae,pe,ve;for(O=_.length-(P=3&_.length),B=C,Y=3432918353,ae=461845907,ve=0;ve>>16)*Y&65535)<<16)&4294967295)<<15|pe>>>17))*ae+(((pe>>>16)*ae&65535)<<16)&4294967295)<<13|B>>>19))+((5*(B>>>16)&65535)<<16)&4294967295))+(((W>>>16)+58964&65535)<<16);switch(pe=0,P){case 3:pe^=(255&_.charCodeAt(ve+2))<<16;case 2:pe^=(255&_.charCodeAt(ve+1))<<8;case 1:B^=pe=(65535&(pe=(pe=(65535&(pe^=255&_.charCodeAt(ve)))*Y+(((pe>>>16)*Y&65535)<<16)&4294967295)<<15|pe>>>17))*ae+(((pe>>>16)*ae&65535)<<16)&4294967295}return B^=_.length,B=2246822507*(65535&(B^=B>>>16))+((2246822507*(B>>>16)&65535)<<16)&4294967295,B=3266489909*(65535&(B^=B>>>13))+((3266489909*(B>>>16)&65535)<<16)&4294967295,(B^=B>>>16)>>>0}),Tx.exports),g=(N0||(N0=1,Qg.exports=function(_,C){for(var P,O=_.length,B=C^O,W=0;O>=4;)P=1540483477*(65535&(P=255&_.charCodeAt(W)|(255&_.charCodeAt(++W))<<8|(255&_.charCodeAt(++W))<<16|(255&_.charCodeAt(++W))<<24))+((1540483477*(P>>>16)&65535)<<16),B=1540483477*(65535&B)+((1540483477*(B>>>16)&65535)<<16)^(P=1540483477*(65535&(P^=P>>>24))+((1540483477*(P>>>16)&65535)<<16)),O-=4,++W;switch(O){case 3:B^=(255&_.charCodeAt(W+2))<<16;case 2:B^=(255&_.charCodeAt(W+1))<<8;case 1:B=1540483477*(65535&(B^=255&_.charCodeAt(W)))+((1540483477*(B>>>16)&65535)<<16)}return B=1540483477*(65535&(B^=B>>>13))+((1540483477*(B>>>16)&65535)<<16),(B^=B>>>15)>>>0}),Qg.exports);return Um.exports=k,Um.exports.murmur3=k,Um.exports.murmur2=g,Um.exports}(),zd=_r(_y);class ld{constructor(g,..._){Object.assign(this,_[0]||{}),this.type=g}}class Gp extends ld{constructor(g,_={}){super("error",Object.assign({error:g},_))}}function eu(k,g,_){_[k]&&_[k].indexOf(g)!==-1||(_[k]=_[k]||[],_[k].push(g))}function Wp(k,g,_){if(_&&_[k]){const C=_[k].indexOf(g);C!==-1&&_[k].splice(C,1)}}class qm{on(g,_){return this._listeners=this._listeners||{},eu(g,_,this._listeners),this}off(g,_){return Wp(g,_,this._listeners),Wp(g,_,this._oneTimeListeners),this}once(g,_){return _?(this._oneTimeListeners=this._oneTimeListeners||{},eu(g,_,this._oneTimeListeners),this):new Promise(C=>{this.once(g,C)})}fire(g,_){const C=typeof g=="string"?new ld(g,_):g,P=C.type;if(this.listens(P)){C.target=this;const O=this._listeners&&this._listeners[P]?this._listeners[P].slice():[];for(const Y of O)Y.call(this,C);const B=this._oneTimeListeners&&this._oneTimeListeners[P]?this._oneTimeListeners[P].slice():[];for(const Y of B)Wp(P,Y,this._oneTimeListeners),Y.call(this,C);const W=this._eventedParent;if(W){const Y=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(C,Y),W.fire(C)}}else C instanceof Gp&&console.error(C.error);return this}listens(g){return!!(this._listeners&&this._listeners[g]&&this._listeners[g].length>0||this._oneTimeListeners&&this._oneTimeListeners[g]&&this._oneTimeListeners[g].length>0||this._eventedParent&&this._eventedParent.listens(g))}setEventedParent(g,_){return this._eventedParent=g,this._eventedParentData=_,this}}class ym{constructor(g){typeof g=="string"?this.name=g:(this.name=g.name,this.iconsetId=g.iconsetId)}static from(g){return new ym(g)}static toString(g){return g.iconsetId?`${g.name}${g.iconsetId}`:g.name}static parse(g){const[_,C]=g.split("");return new ym({name:_,iconsetId:C})}static isEqual(g,_){return g.name===_.name&&g.iconsetId===_.iconsetId}toString(){return ym.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var at,Yt={},Bs=function(){if(at)return Yt;at=1;var k={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 g(O){return(O=Math.round(O))<0?0:O>255?255:O}function _(O){return g(O[O.length-1]==="%"?parseFloat(O)/100*255:parseInt(O))}function C(O){return(B=O[O.length-1]==="%"?parseFloat(O)/100:parseFloat(O))<0?0:B>1?1:B;var B}function P(O,B,W){return W<0?W+=1:W>1&&(W-=1),6*W<1?O+(B-O)*W*6:2*W<1?B:3*W<2?O+(B-O)*(2/3-W)*6:O}try{Yt.parseCSSColor=function(O){var B,W=O.replace(/ /g,"").toLowerCase();if(W in k)return k[W].slice();if(W[0]==="#")return W.length===4?(B=parseInt(W.substr(1),16))>=0&&B<=4095?[(3840&B)>>4|(3840&B)>>8,240&B|(240&B)>>4,15&B|(15&B)<<4,1]:null:W.length===7&&(B=parseInt(W.substr(1),16))>=0&&B<=16777215?[(16711680&B)>>16,(65280&B)>>8,255&B,1]:null;var Y=W.indexOf("("),ae=W.indexOf(")");if(Y!==-1&&ae+1===W.length){var pe=W.substr(0,Y),ve=W.substr(Y+1,ae-(Y+1)).split(","),_e=1;switch(pe){case"rgba":if(ve.length!==4)return null;_e=C(ve.pop());case"rgb":return ve.length!==3?null:[_(ve[0]),_(ve[1]),_(ve[2]),_e];case"hsla":if(ve.length!==4)return null;_e=C(ve.pop());case"hsl":if(ve.length!==3)return null;var Pe=(parseFloat(ve[0])%360+360)%360/360,De=C(ve[1]),We=C(ve[2]),Je=We<=.5?We*(De+1):We+De-We*De,rt=2*We-Je;return[g(255*P(rt,Je,Pe+1/3)),g(255*P(rt,Je,Pe)),g(255*P(rt,Je,Pe-1/3)),_e];default:return null}}return null}}catch{}return Yt}();class Zs{constructor(g,_,C,P=1){this.r=g,this.g=_,this.b=C,this.a=P}static parse(g){if(!g)return;if(g instanceof Zs)return g;if(typeof g!="string")return;const _=Bs.parseCSSColor(g);return _?new Zs(_[0]/255,_[1]/255,_[2]/255,_[3]):void 0}toString(){const[g,_,C,P]=[this.r,this.g,this.b,this.a];return`rgba(${Math.round(255*g)},${Math.round(255*_)},${Math.round(255*C)},${P})`}toNonPremultipliedRenderColor(g){const{r:_,g:C,b:P,a:O}=this;return new Dr(g,_,C,P,O)}toPremultipliedRenderColor(g){const{r:_,g:C,b:P,a:O}=this;return new kt(g,_*O,C*O,P*O,O)}clone(){return new Zs(this.r,this.g,this.b,this.a)}}class Sn{constructor(g,_,C,P,O,B=!1){if(this.premultiplied=!1,this.premultiplied=B,g){const W=g.image.height,Y=W*W;this.premultiplied?(_=O===0?0:_/O*(W-1),C=O===0?0:C/O*(W-1),P=O===0?0:P/O*(W-1)):(_*=W-1,C*=W-1,P*=W-1),_=Math.max(0,Math.min(W-1,_)),C=Math.max(0,Math.min(W-1,C)),P=Math.max(0,Math.min(W-1,P));const ae=Math.floor(_),pe=Math.floor(C),ve=Math.floor(P),_e=Math.ceil(_),Pe=Math.ceil(C),De=Math.ceil(P),We=_-ae,Je=C-pe,rt=P-ve,xt=g.image.data,ut=4*(ae+pe*Y+ve*W),St=4*(ae+pe*Y+De*W),Rt=4*(ae+Pe*Y+ve*W),Ft=4*(ae+Pe*Y+De*W),bs=4*(_e+pe*Y+ve*W),as=4*(_e+pe*Y+De*W),ys=4*(_e+Pe*Y+ve*W),hs=4*(_e+Pe*Y+De*W);this.r=Es(Es(Es(xt[ut],xt[St],rt),Es(xt[Rt],xt[Ft],rt),Je),Es(Es(xt[bs],xt[as],rt),Es(xt[ys],xt[hs],rt),Je),We)/255*(this.premultiplied?O:1),this.g=Es(Es(Es(xt[ut+1],xt[St+1],rt),Es(xt[Rt+1],xt[Ft+1],rt),Je),Es(Es(xt[bs+1],xt[as+1],rt),Es(xt[ys+1],xt[hs+1],rt),Je),We)/255*(this.premultiplied?O:1),this.b=Es(Es(Es(xt[ut+2],xt[St+2],rt),Es(xt[Rt+2],xt[Ft+2],rt),Je),Es(Es(xt[bs+2],xt[as+2],rt),Es(xt[ys+2],xt[hs+2],rt),Je),We)/255*(this.premultiplied?O:1),this.a=O}else this.r=_,this.g=C,this.b=P,this.a=O}toArray(){const{r:g,g:_,b:C,a:P}=this;return[255*g,255*_,255*C,P]}toHslaArray(){let{r:g,g:_,b:C,a:P}=this;if(this.premultiplied){if(P===0)return[0,0,0,0];const De=1/P;g*=De,_*=De,C*=De}const O=Math.min(Math.max(g,0),1),B=Math.min(Math.max(_,0),1),W=Math.min(Math.max(C,0),1),Y=Math.min(O,B,W),ae=Math.max(O,B,W),pe=ae-Y,ve=.5*(Y+ae);if(pe===0)return[0,0,100*ve,P];const _e=ve>.5?pe/(2-ae-Y):pe/(ae+Y);let Pe;switch(ae){case O:Pe=60*((B-W)/pe+(BEs(C,g[P],_))}Zs.black=new Zs(0,0,0,1),Zs.white=new Zs(1,1,1,1),Zs.transparent=new Zs(0,0,0,0),Zs.red=new Zs(1,0,0,1),Zs.blue=new Zs(0,0,1,1);var Br=Object.freeze({__proto__:null,array:bn,color:function(k,g,_){return new Zs(Es(k.r,g.r,_),Es(k.g,g.g,_),Es(k.b,g.b,_),Es(k.a,g.a,_))},number:Es});class Or extends Error{constructor(g,_){super(_),this.message=_,this.key=g}}class Ma{constructor(g,_=[]){this.parent=g,this.bindings={};for(const[C,P]of _)this.bindings[C]=P}concat(g){return new Ma(this,g)}get(g){if(this.bindings[g])return this.bindings[g];if(this.parent)return this.parent.get(g);throw new Error(`${g} not found in scope.`)}has(g){return!!this.bindings[g]||!!this.parent&&this.parent.has(g)}}const Ra={kind:"null"},nr={kind:"number"},Va={kind:"string"},mi={kind:"boolean"},ol={kind:"color"},vc={kind:"object"},ao={kind:"value"},$m={kind:"collator"},k0={kind:"formatted"},S0={kind:"resolvedImage"};function Xu(k,g){return{kind:"array",itemType:k,N:g}}function Ac(k){if(k.kind==="array"){const g=Ac(k.itemType);return typeof k.N=="number"?`array<${g}, ${k.N}>`:k.itemType.kind==="value"?"array":`array<${g}>`}return k.kind}const Ab=[Ra,nr,Va,mi,ol,k0,vc,Xu(ao),S0];function Mx(k,g){if(g.kind==="error")return null;if(k.kind==="array"){if(g.kind==="array"&&(g.N===0&&g.itemType.kind==="value"||!Mx(k.itemType,g.itemType))&&(typeof k.N!="number"||k.N===g.N))return null}else{if(k.kind===g.kind)return null;if(k.kind==="value"){for(const _ of Ab)if(!Mx(_,g))return null}}return`Expected ${Ac(k)} but found ${Ac(g)} instead.`}function wy(k,g){return g.some(_=>_.kind===k.kind)}function wu(k,g){return g.some(_=>_==="null"?k===null:_==="array"?Array.isArray(k):_==="object"?k&&!Array.isArray(k)&&typeof k=="object":_===typeof k)}function Kp(k,g){return k.kind==="array"&&g.kind==="array"?k.N===g.N&&Kp(k.itemType,g.itemType):k.kind===g.kind}class jy{constructor(g,_,C){this.sensitivity=g?_?"variant":"case":_?"accent":"base",this.locale=C,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(g,_){return this.collator.compare(g,_)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class Sv{constructor(g,_,C,P,O){this.text=g.normalize?g.normalize():g,this.image=_,this.scale=C,this.fontStack=P,this.textColor=O}}class Bd{constructor(g){this.sections=g}static fromString(g){return new Bd([new Sv(g,null,null,null,null)])}isEmpty(){return this.sections.length===0||!this.sections.some(g=>g.text.length!==0||!!g.image&&g.image.hasPrimary())}static factory(g){return g instanceof Bd?g:Bd.fromString(g)}toString(){return this.sections.length===0?"":this.sections.map(g=>g.text).join("")}serialize(){const g=["format"];for(const _ of this.sections){if(_.image){const P=_.image.getPrimary().id.toString();g.push(["image",P]);continue}g.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())),g.push(C)}return g}}class tu{constructor(g,_={}){this.id=ym.from(g),this.params=_.params,this.sx=_.sx||1,this.sy=_.sy||1}toString(){return JSON.stringify(this)}static parse(g){let _,C,P,O;try{({id:_,params:C,sx:P,sy:O}=JSON.parse(g)||{})}catch{return null}return _?new tu(_,{params:C,sx:P,sy:O}):null}scaleSelf(g,_=g){return this.sx*=g,this.sy*=_,this}}class uh{constructor(g,_,C,P,O=!1){this.primaryId=ym.from(g),this.primaryOptions=_,C&&(this.secondaryId=ym.from(C)),this.secondaryOptions=P,this.available=O}toString(){return this.primaryId&&this.secondaryId?`[${this.primaryId.name},${this.secondaryId.name}]`:this.primaryId.name}hasPrimary(){return!!this.primaryId}getPrimary(){return new tu(this.primaryId,this.primaryOptions)}hasSecondary(){return!!this.secondaryId}getSecondary(){return this.secondaryId?new tu(this.secondaryId,this.secondaryOptions):null}static from(g){return typeof g=="string"?uh.build({name:g}):g}static build(g,_,C,P){return!g||typeof g=="object"&&!("name"in g)?null:new uh(g,C,_,P)}}function fp(k,g,_,C){return typeof k=="number"&&k>=0&&k<=255&&typeof g=="number"&&g>=0&&g<=255&&typeof _=="number"&&_>=0&&_<=255?C===void 0||typeof C=="number"&&C>=0&&C<=1?null:`Invalid rgba value [${[k,g,_,C].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof C=="number"?[k,g,_,C]:[k,g,_]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function xg(k){if(k===null||typeof k=="string"||typeof k=="boolean"||typeof k=="number"||k instanceof Zs||k instanceof jy||k instanceof Bd||k instanceof uh)return!0;if(Array.isArray(k)){for(const g of k)if(!xg(g))return!1;return!0}if(typeof k=="object"){for(const g in k)if(!xg(k[g]))return!1;return!0}return!1}function Hl(k){if(k===null)return Ra;if(typeof k=="string")return Va;if(typeof k=="boolean")return mi;if(typeof k=="number")return nr;if(k instanceof Zs)return ol;if(k instanceof jy)return $m;if(k instanceof Bd)return k0;if(k instanceof uh)return S0;if(Array.isArray(k)){const g=k.length;let _;for(const C of k){const P=Hl(C);if(_){if(_===P)continue;_=ao;break}_=P}return Xu(_||ao,g)}return vc}function Ia(k){const g=typeof k;return k===null?"":g==="string"||g==="number"||g==="boolean"?String(k):k instanceof Bd||k instanceof uh||k instanceof Zs?k.toString():JSON.stringify(k)}class Hr{constructor(g,_){this.type=g,this.value=_}static parse(g,_){if(g.length!==2)return _.error(`'literal' expression requires exactly one argument, but found ${g.length-1} instead.`);if(!xg(g[1]))return _.error("invalid value");const C=g[1];let P=Hl(C);const O=_.expectedType;return P.kind!=="array"||P.N!==0||!O||O.kind!=="array"||typeof O.N=="number"&&O.N!==0||(P=O),new Hr(P,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 Zs?["rgba"].concat(this.value.toNonPremultipliedRenderColor(null).toArray()):this.value instanceof Bd?this.value.serialize():this.value}}class bc{constructor(g){this.name="ExpressionEvaluationError",this.message=g}toJSON(){return this.message}}const Da={string:Va,number:nr,boolean:mi,object:vc};class gp{constructor(g,_){this.type=g,this.args=_}static parse(g,_){if(g.length<2)return _.error("Expected at least one argument.");let C,P=1;const O=g[0];if(O==="array"){let W,Y;if(g.length>2){const ae=g[1];if(typeof ae!="string"||!(ae in Da)||ae==="object")return _.error('The item type argument of "array" must be one of string, number, boolean',1);W=Da[ae],P++}else W=ao;if(g.length>3){if(g[2]!==null&&(typeof g[2]!="number"||g[2]<0||g[2]!==Math.floor(g[2])))return _.error('The length argument to "array" must be a positive integer literal',2);Y=g[2],P++}C=Xu(W,Y)}else C=Da[O];const B=[];for(;Pg.outputDefined())}serialize(){const g=this.type,_=[g.kind];if(g.kind==="array"){const C=g.itemType;if(C.kind==="string"||C.kind==="number"||C.kind==="boolean"){_.push(C.kind);const P=g.N;(typeof P=="number"||this.args.length>1)&&_.push(P)}}return _.concat(this.args.map(C=>C.serialize()))}}class Ud{constructor(g){this.type=k0,this.sections=g}static parse(g,_){if(g.length<2)return _.error("Expected at least one argument.");const C=g[1];if(!Array.isArray(C)&&typeof C=="object")return _.error("First argument must be an image or text section.");const P=[];let O=!1;for(let B=1;B<=g.length-1;++B){const W=g[B];if(O&&typeof W=="object"&&!Array.isArray(W)){O=!1;let Y=null;if(W["font-scale"]&&(Y=_.parseObjectValue(W["font-scale"],B,"font-scale",nr),!Y))return null;let ae=null;if(W["text-font"]&&(ae=_.parseObjectValue(W["text-font"],B,"text-font",Xu(Va)),!ae))return null;let pe=null;if(W["text-color"]&&(pe=_.parseObjectValue(W["text-color"],B,"text-color",ol),!pe))return null;const ve=P[P.length-1];ve.scale=Y,ve.font=ae,ve.textColor=pe}else{const Y=_.parse(g[B],B,ao);if(!Y)return null;const ae=Y.type.kind;if(ae!=="string"&&ae!=="value"&&ae!=="null"&&ae!=="resolvedImage")return _.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");O=!0,P.push({content:Y,scale:null,font:null,textColor:null})}}return new Ud(P)}evaluate(g){return new Bd(this.sections.map(_=>{const C=_.content.evaluate(g);return Kp(Hl(C),S0)?new Sv("",C,null,null,null):new Sv(Ia(C),null,_.scale?_.scale.evaluate(g):null,_.font?_.font.evaluate(g).join(","):null,_.textColor?_.textColor.evaluate(g):null)}))}eachChild(g){for(const _ of this.sections)g(_.content),_.scale&&g(_.scale),_.font&&g(_.font),_.textColor&&g(_.textColor)}outputDefined(){return!1}serialize(){const g=["format"];for(const _ of this.sections){g.push(_.content.serialize());const C={};_.scale&&(C["font-scale"]=_.scale.serialize()),_.font&&(C["text-font"]=_.font.serialize()),_.textColor&&(C["text-color"]=_.textColor.serialize()),g.push(C)}return g}}class fa{constructor(g,_,C,P){this._imageWarnHistory={},this.type=S0,this.namePrimary=g,this.nameSecondary=_,C&&(this.paramsPrimary=C.params,this.iconsetIdPrimary=C.iconset?C.iconset.id:void 0),P&&(this.paramsSecondary=P.params,this.iconsetIdSecondary=P.iconset?P.iconset.id:void 0)}static parse(g,_){if(g.length<2)return _.error("Expected two or more arguments.");let C=1;const P=[];function O(){if(Cym.isEqual(B,O)),P.available){const B=P.getSecondary()?P.getSecondary().id:null;B&&(P.available=g.availableImages.some(W=>ym.isEqual(W,B)))}}return P}eachChild(g){if(g(this.namePrimary),this.paramsPrimary)for(const _ in this.paramsPrimary)this.paramsPrimary[_]&&g(this.paramsPrimary[_]);if(this.nameSecondary&&(g(this.nameSecondary),this.paramsSecondary))for(const _ in this.paramsSecondary)this.paramsSecondary[_]&&g(this.paramsSecondary[_])}outputDefined(){return!1}serializeOptions(g,_){const C={};if(_&&(C.iconset={id:_}),g){C.params={};for(const P in g)g[P]&&(C.params[P]=g[P].serialize())}return Object.keys(C).length>0?C:void 0}serialize(){const g=["image",this.namePrimary.serialize()];if(this.paramsPrimary||this.iconsetIdPrimary){const _=this.serializeOptions(this.paramsPrimary,this.iconsetIdPrimary);_&&g.push(_)}if(this.nameSecondary&&(g.push(this.nameSecondary.serialize()),this.paramsSecondary||this.iconsetIdSecondary)){const _=this.serializeOptions(this.paramsSecondary,this.iconsetIdSecondary);_&&g.push(_)}return g}}function Px(k){return Jg(k)?"string":Ny(k)?"number":yg(k)?"boolean":Array.isArray(k)?"array":k===null?"null":C0(k)?"object":typeof k}function C0(k){return k!=null&&!Array.isArray(k)&&typeof k!="function"&&!(k instanceof String||k instanceof Number||k instanceof Boolean)&&typeof k=="object"}function Jg(k){return typeof k=="string"||k instanceof String}function Ny(k){return typeof k=="number"||k instanceof Number}function yg(k){return typeof k=="boolean"||k instanceof Boolean}const gd={"to-boolean":mi,"to-color":ol,"to-number":nr,"to-string":Va};class Yp{constructor(g,_){this.type=g,this.args=_}static parse(g,_){if(g.length<2)return _.error("Expected at least one argument.");const C=g[0],P=[];let O=Ra;if(C==="to-array"){if(!Array.isArray(g[1]))return null;const B=g[1].length;if(_.expectedType){if(_.expectedType.kind!=="array")return _.error(`Expected ${_.expectedType.kind} but found array.`);O=Xu(_.expectedType.itemType,B)}else{if(!(B>0&&xg(g[1][0])))return null;O=Xu(Hl(g[1][0]),B)}for(let W=0;W4?`Invalid rbga value ${JSON.stringify(_)}: expected an array containing either three or four numeric values.`:fp(_[0],_[1],_[2],_[3]),!C))return new Zs(_[0]/255,_[1]/255,_[2]/255,_[3])}throw new bc(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(g),_===null)return 0;const P=Number(_);if(!isNaN(P))return P}throw new bc(`Could not convert ${JSON.stringify(_)} to number.`)}return this.type.kind==="formatted"?Bd.fromString(Ia(this.args[0].evaluate(g))):this.type.kind==="resolvedImage"?uh.build(Ia(this.args[0].evaluate(g))):this.type.kind==="array"?this.args.map(_=>_.evaluate(g)):Ia(this.args[0].evaluate(g))}eachChild(g){this.args.forEach(g)}outputDefined(){return this.args.every(g=>g.outputDefined())}serialize(){if(this.type.kind==="formatted")return new Ud([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new fa(this.args[0]).serialize();const g=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(_=>{g.push(_.serialize())}),g}}const em=["Unknown","Point","LineString","Polygon"];class Qu{constructor(g,_,C){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache={},this.availableImages=null,this.canonical=null,this.featureTileCoord=null,this.featureDistanceData=null,this.scope=g,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"?em[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(g){return this.globals.brightness||0}distanceFromCenter(){if(this.featureTileCoord&&this.featureDistanceData){const g=this.featureDistanceData.center,_=this.featureDistanceData.scale,{x:C,y:P}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(C*_-g[0])+this.featureDistanceData.bearing[1]*(P*_-g[1])}return 0}parseColor(g){let _=this._parseColorCache[g];return _||(_=this._parseColorCache[g]=Zs.parse(g)),_}getConfig(g){return this.options?this.options.get(g):null}}class Sd{constructor(g,_,C,P,O){this.name=g,this.type=_,this._evaluate=C,this.args=P,this._overloadIndex=O}evaluate(g){if(!this._evaluate){const _=Sd.definitions[this.name];this._evaluate=Array.isArray(_)?_[2]:_.overloads[this._overloadIndex][1]}return this._evaluate(g,this.args)}eachChild(g){this.args.forEach(g)}outputDefined(){return!1}serialize(){return[this.name].concat(this.args.map(g=>g.serialize()))}static parse(g,_){const C=g[0],P=Sd.definitions[C];if(!P)return _.error(`Unknown expression "${C}". If you wanted a literal array, use ["literal", [...]].`,0);const O=Array.isArray(P)?P[0]:P.type,B=Array.isArray(P)?[[P[1],P[2]]]:P.overloads,W=[];let Y=null,ae=-1;for(const[pe,ve]of B){if(Array.isArray(pe)&&pe.length!==g.length-1)continue;W.push(pe),ae++,Y=new FN(_.registry,_.path,null,_.scope,void 0,_._scope,_.options,_.iconImageUseTheme);const _e=[];let Pe=!1;for(let De=1;De_e)).map(Zp).join(" | "),ve=[];for(let _e=1;_e_;){if(C-_>600){const Y=C-_+1,ae=g-_+1,pe=Math.log(Y),ve=.5*Math.exp(2*pe/3),_e=.5*Math.sqrt(pe*ve*(Y-ve)/Y)*(ae-Y/2<0?-1:1);b1(k,g,Math.max(_,Math.floor(g-ae*ve/Y+_e)),Math.min(C,Math.floor(g+(Y-ae)*ve/Y+_e)),P)}const O=k[g];let B=_,W=C;for(Xc(k,_,g),P(k[C],O)>0&&Xc(k,_,C);B0;)W--}P(k[_],O)===0?Xc(k,_,W):(W++,Xc(k,W,C)),W<=g&&(_=W+1),g<=W&&(C=W-1)}}function Xc(k,g,_){const C=k[g];k[g]=k[_],k[_]=C}function Lx(k,g){return kg?1:0}function ky(k){let g=0;for(let _,C,P=0,O=k.length,B=O-1;P=g[2]||k[1]<=g[1]||k[3]>=g[3])}function Eb(k,g,_){const C=k[0]-g[0],P=k[1]-g[1],O=k[0]-_[0],B=k[1]-_[1];return C*B-O*P===0&&C*O<=0&&P*B<=0}function Ju(k,g,_){return g[1]>k[1]!=_[1]>k[1]&&k[0]<(_[0]-g[0])*(k[1]-g[1])/(_[1]-g[1])+g[0]}function _c(k,g,_=!1){let C=!1;for(let P=0,O=g.length;P0&&W<0||B<0&&W>0}function ll(k,g,_,C){return(P=[C[0]-_[0],C[1]-_[1]])[0]*(O=[g[0]-k[0],g[1]-k[1]])[1]-P[1]*O[0]!==0&&!(!xl(k,g,_,C)||!xl(_,C,k,g));var P,O}function ju(k){const g=new es(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),_=new es(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const C of k[0])g.x>C.x&&(g.x=C.x),g.y>C.y&&(g.y=C.y),_.x_[2]){const P=.5*C;let O=k[0]-_[0]>P?-C:_[0]-k[0]>P?C:0;O===0&&(O=k[0]-_[2]>P?-C:_[2]-k[0]>P?C:0),k[0]+=O}tm(g,k)}function Cy(k,g,_,C){const P=Math.pow(2,C.z)*Cd,O=[C.x*Cd,C.y*Cd],B=[];if(!k)return B;for(const W of k)for(const Y of W){const ae=[Y.x+O[0],Y.y+O[1]];eh(ae,g,_,P),B.push(ae)}return B}function Mj(k,g,_,C){const P=Math.pow(2,C.z)*Cd,O=[C.x*Cd,C.y*Cd],B=[];if(!k)return B;for(const Y of k){const ae=[];for(const pe of Y){const ve=[pe.x+O[0],pe.y+O[1]];tm(g,ve),ae.push(ve)}B.push(ae)}if(g[2]-g[0]<=P/2){(W=g)[0]=W[1]=1/0,W[2]=W[3]=-1/0;for(const Y of B)for(const ae of Y)eh(ae,g,_,P)}var W;return B}class Ay{constructor(g,_){this.type=mi,this.geojson=g,this.geometries=_}static parse(g,_){if(g.length!==2)return _.error(`'within' expression requires exactly one argument, but found ${g.length-1} instead.`);if(xg(g[1])){const C=g[1];if(C.type==="FeatureCollection")for(let P=0;P_)return G_(O,B,(_-(C-W))/W)}return g[g.length-1]}pointToSegmentDistance(g,_,C){let[P,O]=_,B=Xp(C[0]-P)*this.kx,W=(C[1]-O)*this.ky;if(B!==0||W!==0){const Y=(Xp(g[0]-P)*this.kx*B+(g[1]-O)*this.ky*W)/(B*B+W*W);Y>1?(P=C[0],O=C[1]):Y>0&&(P+=B/this.kx*Y,O+=W/this.ky*Y)}return B=Xp(g[0]-P)*this.kx,W=(g[1]-O)*this.ky,Math.sqrt(B*B+W*W)}pointOnLine(g,_){let C=1/0,P=g[0][0],O=g[0][1],B=0,W=0;for(let Y=0;Y1?(ae=g[Y+1][0],pe=g[Y+1][1]):Pe>0&&(ae+=ve/this.kx*Pe,pe+=_e/this.ky*Pe)),ve=Xp(_[0]-ae)*this.kx,_e=(_[1]-pe)*this.ky;const De=ve*ve+_e*_e;DeO.index||P.index===O.index&&P.t>O.t){const ae=P;P=O,O=ae}const B=[P.point],W=P.index+1,Y=O.index;!RN(C[W],B[0])&&W<=Y&&B.push(C[W]);for(let ae=W+1;ae<=Y;ae++)B.push(C[ae]);return RN(C[Y],O.point)||B.push(O.point),B}lineSliceAlong(g,_,C){let P=0;const O=[];for(let B=0;Bg&&O.length===0&&O.push(G_(W,Y,(g-(P-ae))/ae)),P>=_)return O.push(G_(W,Y,(_-(P-ae))/ae)),O;P>g&&O.push(Y)}return O}bufferPoint(g,_){const C=_/this.ky,P=_/this.kx;return[g[0]-P,g[1]-C,g[0]+P,g[1]+C]}bufferBBox(g,_){const C=_/this.ky,P=_/this.kx;return[g[0]-P,g[1]-C,g[2]+P,g[3]+C]}insideBBox(g,_){return Xp(g[0]-_[0])>=0&&Xp(g[0]-_[2])<=0&&g[1]>=_[1]&&g[1]<=_[3]}}function RN(k,g){return k[0]===g[0]&&k[1]===g[1]}function G_(k,g,_){const C=Xp(g[0]-k[0]);return[k[0]+C*_,k[1]+(g[1]-k[1])*_]}function Xp(k){for(;k<-180;)k+=360;for(;k>180;)k-=360;return k}class nm{constructor(g=[],_=(C,P)=>CP?1:0){if(this.data=g,this.length=this.data.length,this.compare=_,this.length>0)for(let C=(this.length>>1)-1;C>=0;C--)this._down(C)}push(g){this.data.push(g),this._up(this.length++)}pop(){if(this.length===0)return;const g=this.data[0],_=this.data.pop();return--this.length>0&&(this.data[0]=_,this._down(0)),g}peek(){return this.data[0]}_up(g){const{data:_,compare:C}=this,P=_[g];for(;g>0;){const O=g-1>>1,B=_[O];if(C(P,B)>=0)break;_[g]=B,g=O}_[g]=P}_down(g){const{data:_,compare:C}=this,P=this.length>>1,O=_[g];for(;g=0)break;_[g]=_[B],g=B}_[g]=O}}var dr=8192;function Pb(k,g){return g.dist-k.dist}function Lb(k){const g=[1/0,1/0,-1/0,-1/0];if(g.length!==k.length)return!1;for(let _=0;_=k[0]&&k[1]k[1])return[null,null];const _=_1(k);if(g){if(_===2)return[k,null];const C=Math.floor(_/2);return[[k[0],k[0]+C],[k[0]+C,k[1]]]}{if(_===1)return[k,null];const C=Math.floor(_/2)-1;return[[k[0],k[0]+C],[k[0]+C+1,k[1]]]}}function Ey(k,g){const _=[1/0,1/0,-1/0,-1/0];if(!Rf(g,k.length))return _;for(let C=g[0];C<=g[1];++C)tm(_,k[C]);return _}function W_(k){const g=[1/0,1/0,-1/0,-1/0];for(let _=0;_g[2]&&(C=k[0]-g[2]),k[1]>g[3]&&(P=k[1]-g[3]),k[3]=C)return C;if(vg(P,O)){if(K_(k,g))return 0}else if(K_(g,k))return 0;let B=C;for(const W of k)for(let Y=0,ae=W.length,pe=ae-1;Y=O)continue;const pe=ae.range1;if(_1(pe)<=W){if(!Rf(pe,k.length))return NaN;if(g){const ve=Qc(k,pe,_,C);if((O=Math.min(O,ve))===0)return O}else for(let ve=pe[0];ve<=pe[1];++ve){const _e=ME(k[ve],_,C);if((O=Math.min(O,_e))===0)return O}}else{const ve=Cv(pe,g);if(ve[0]!==null){const _e=w1(Ey(k,ve[0]),Y,C);_e=B)continue;const ve=pe.range1,_e=pe.range2;if(_1(ve)<=Y&&_1(_e)<=ae){if(!Rf(ve,k.length)||!Rf(_e,_.length))return NaN;if(g&&C?B=Math.min(B,xL(k,ve,_,_e,P)):g||C?g&&!C?B=Math.min(B,IS(_,_e,k,ve,P)):!g&&C&&(B=Math.min(B,IS(k,ve,_,_e,P))):B=Math.min(B,C3(k,ve,_,_e,P)),B===0)return B}else{const Pe=Cv(ve,g),De=Cv(_e,C);Ib(W,B,P,k,_,Pe[0],De[0]),Ib(W,B,P,k,_,Pe[0],De[1]),Ib(W,B,P,k,_,Pe[1],De[0]),Ib(W,B,P,k,_,Pe[1],De[1])}}return B}function Lj(k,g,_,C,P=1/0){let O=P;const B=Ey(k,[0,k.length-1]);for(const W of _)if(!(O!==1/0&&w1(B,Ey(W,[0,W.length-1]),C)>=O)&&(O=Math.min(O,E0(k,g,W,!0,C,O)),O===0))return O;return O}function Y_(k,g,_,C,P=1/0){let O=P;const B=Ey(k,[0,k.length-1]);for(const W of _){if(O!==1/0&&w1(B,W_(W),C)>=O)continue;const Y=yL(k,g,W,C,O);if(isNaN(Y))return Y;if((O=Math.min(O,Y))===0)return O}return O}function RS(k){return k==="Point"||k==="MultiPoint"||k==="LineString"||k==="MultiLineString"||k==="Polygon"||k==="MultiPolygon"}class Rb{constructor(g,_){this.type=nr,this.geojson=g,this.geometries=_}static parse(g,_){if(g.length!==2)return _.error(`'distance' expression requires either one argument, but found ' ${g.length-1} instead.`);if(xg(g[1])){const C=g[1];if(C.type==="FeatureCollection"){for(let P=0;P{g&&!Db(_)&&(g=!1)}),g}function bg(k){if(k instanceof Sd&&k.name==="feature-state")return!1;let g=!0;return k.eachChild(_=>{g&&!bg(_)&&(g=!1)}),g}function Pu(k,g){if(k instanceof Sd&&g.indexOf(k.name)>=0)return!1;let _=!0;return k.eachChild(C=>{_&&!Pu(C,g)&&(_=!1)}),_}function T0(k,g,_){return[k,g,_].filter(Boolean).join("")}function ON(k,g){switch(k){case"string":return Ia(g);case"number":return+g;case"boolean":return!!g;case"color":return Zs.parse(g);case"formatted":return Bd.fromString(Ia(g));case"resolvedImage":return uh.build(Ia(g))}return g}function E3(k,g,_,C){return C!==void 0&&(k=C*Math.round(k/C)),g!==void 0&&k_&&(k=_),k}class ex{constructor(g,_,C,P=!1){this.type=g,this.key=_,this.scope=C,this.featureConstant=P}static parse(g,_){let C=_.expectedType;if(C==null&&(C=ao),g.length<2||g.length>3)return _.error("Invalid number of arguments for 'config' expression.");const P=_.parse(g[1],1);if(!(P instanceof Hr))return _.error("Key name of 'config' expression must be a string literal.");let O,B=!0;const W=Ia(P.value);if(g.length>=3){const Y=_.parse(g[2],2);if(!(Y instanceof Hr))return _.error("Scope of 'config' expression must be a string literal.");O=Ia(Y.value)}if(_.options){const Y=T0(W,O,_._scope),ae=_.options.get(Y);ae&&(B=Db(ae.value||ae.default))}return new ex(C,W,O,B)}evaluate(g){const _=T0(this.key,this.scope,g.scope),C=g.getConfig(_);if(!C)return null;const{type:P,value:O,values:B,minValue:W,maxValue:Y,stepValue:ae}=C,pe=C.default.evaluate(g);let ve=pe;if(O){const _e=g.scope;g.scope=(_e||"").split("").slice(1).join(""),ve=O.evaluate(g),g.scope=_e}return P&&(ve=ON(P,ve)),ve===void 0||W===void 0&&Y===void 0&&ae===void 0||(typeof ve=="number"?ve=E3(ve,W,Y,ae):Array.isArray(ve)&&(ve=ve.map(_e=>typeof _e=="number"?E3(_e,W,Y,ae):_e))),O!==void 0&&ve!==void 0&&B&&!B.includes(ve)&&(ve=pe,P&&(ve=ON(P,ve))),(P&&P!==this.type||ve!==void 0&&!Kp(Hl(ve),this.type))&&(ve=ON(this.type.kind,ve)),ve}eachChild(){}outputDefined(){return!1}serialize(){const g=["config",this.key];return this.scope&&g.concat(this.scope),g}}class Df{constructor(g,_){this.type=_.type,this.name=g,this.boundExpression=_}static parse(g,_){if(g.length!==2||typeof g[1]!="string")return _.error("'var' expression requires exactly one string literal argument.");const C=g[1];return _.scope.has(C)?new Df(C,_.scope.get(C)):_.error(`Unknown variable "${C}". Make sure "${C}" has been bound in an enclosing "let" expression before using it.`,1)}evaluate(g){return this.boundExpression.evaluate(g)}eachChild(){}outputDefined(){return!1}serialize(){return["var",this.name]}}class FN{constructor(g,_=[],C,P=new Ma,O=[],B,W,Y){this.registry=g,this.path=_,this.key=_.map(ae=>typeof ae=="string"?`['${ae}']`:`[${ae}]`).join(""),this.scope=P,this.errors=O,this.expectedType=C,this._scope=B,this.options=W,this.iconImageUseTheme=Y}parse(g,_,C,P,O={}){return _||C?this.concat(_,null,C,P)._parse(g,O):this._parse(g,O)}parseObjectValue(g,_,C,P,O,B={}){return this.concat(_,C,P,O)._parse(g,B)}_parse(g,_){function C(P,O,B){return B==="assert"?new gp(O,[P]):B==="coerce"?new Yp(O,[P]):P}if(g!==null&&typeof g!="string"&&typeof g!="boolean"&&typeof g!="number"||(g=["literal",g]),Array.isArray(g)){if(g.length===0)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const P=typeof g[0]=="string"?this.registry[g[0]]:void 0;if(P){let O=P.parse(g,this);if(!O)return null;if(this.expectedType){const B=this.expectedType,W=O.type;if(B.kind!=="string"&&B.kind!=="number"&&B.kind!=="boolean"&&B.kind!=="object"&&B.kind!=="array"||W.kind!=="value")if(B.kind!=="color"&&B.kind!=="formatted"&&B.kind!=="resolvedImage"||W.kind!=="value"&&W.kind!=="string"){if(this.checkSubtype(B,W))return null}else O=C(O,B,_.typeAnnotation||"coerce");else O=C(O,B,_.typeAnnotation||"assert")}if(!(O instanceof Hr)&&O.type.kind!=="resolvedImage"&&DS(O)){const B=new Qu(this._scope,this.options,this.iconImageUseTheme);try{O=new Hr(O.type,O.evaluate(B))}catch(W){return this.error(W.message),null}}return O}return Yp.parse(["to-array",g],this)}return this.error(g===void 0?"'undefined' value invalid. Use null instead.":typeof g=="object"?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof g} instead.`)}concat(g,_,C,P){let O=typeof g=="number"?this.path.concat(g):this.path;O=typeof _=="string"?O.concat(_):O;const B=P?this.scope.concat(P):this.scope;return new FN(this.registry,O,C||null,B,this.errors,this._scope,this.options,this.iconImageUseTheme)}error(g,..._){const C=`${this.key}${_.map(P=>`[${P}]`).join("")}`;this.errors.push(new Or(C,g))}checkSubtype(g,_){const C=Mx(g,_);return C&&this.error(C),C}}function DS(k){if(k instanceof Df)return DS(k.boundExpression);if(k instanceof Sd&&k.name==="error"||k instanceof v1||k instanceof Ay||k instanceof Rb||k instanceof ex)return!1;const g=k instanceof Yp||k instanceof gp;let _=!0;return k.eachChild(C=>{_=g?_&&DS(C):_&&C instanceof Hr}),!!_&&Db(k)&&Pu(k,["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 Ij(k,g){const _=k.length-1;let C,P,O=0,B=_,W=0;for(;O<=B;)if(W=Math.floor((O+B)/2),C=k[W],P=k[W+1],C<=g){if(W===_||gg))throw new bc("Input is not a number.");B=W-1}return 0}class Rj{constructor(g,_,C){this.type=g,this.input=_,this.labels=[],this.outputs=[];for(const[P,O]of C)this.labels.push(P),this.outputs.push(O)}static parse(g,_){if(g.length-1<4)return _.error(`Expected at least 4 arguments, but found only ${g.length-1}.`);if((g.length-1)%2!=0)return _.error("Expected an even number of arguments.");const C=_.parse(g[1],1,nr);if(!C)return null;const P=[];let O=null;_.expectedType&&_.expectedType.kind!=="value"&&(O=_.expectedType);for(let B=1;B=W)return _.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',ae);const ve=_.parse(Y,pe,O);if(!ve)return null;O=O||ve.type,P.push([W,ve])}return new Rj(O,C,P)}evaluate(g){const _=this.labels,C=this.outputs;if(_.length===1)return C[0].evaluate(g);const P=this.input.evaluate(g);if(P<=_[0])return C[0].evaluate(g);const O=_.length;return P>=_[O-1]?C[O-1].evaluate(g):C[Ij(_,P)].evaluate(g)}eachChild(g){g(this.input);for(const _ of this.outputs)g(_)}outputDefined(){return this.outputs.every(g=>g.outputDefined())}serialize(){const g=["step",this.input.serialize()];for(let _=0;_0&&g.push(this.labels[_]),g.push(this.outputs[_].serialize());return g}}const Of=.95047,Qp=1.08883,T3=4/29,Av=6/29,Dj=3*Av*Av,Oj=Av*Av*Av,OS=Math.PI/180,FS=180/Math.PI;function zS(k){return k>Oj?Math.pow(k,1/3):k/Dj+T3}function Fj(k){return k>Av?k*k*k:Dj*(k-T3)}function zj(k){return 255*(k<=.0031308?12.92*k:1.055*Math.pow(k,1/2.4)-.055)}function Z_(k){return(k/=255)<=.04045?k/12.92:Math.pow((k+.055)/1.055,2.4)}function zN(k){const g=Z_(k.r),_=Z_(k.g),C=Z_(k.b),P=zS((.4124564*g+.3575761*_+.1804375*C)/Of),O=zS((.2126729*g+.7151522*_+.072175*C)/1);return{l:116*O-16,a:500*(P-O),b:200*(O-zS((.0193339*g+.119192*_+.9503041*C)/Qp)),alpha:k.a}}function BS(k){let g=(k.l+16)/116,_=isNaN(k.a)?g:g+k.a/500,C=isNaN(k.b)?g:g-k.b/200;return g=1*Fj(g),_=Of*Fj(_),C=Qp*Fj(C),new Zs(zj(3.2404542*_-1.5371385*g-.4985314*C),zj(-.969266*_+1.8760108*g+.041556*C),zj(.0556434*_-.2040259*g+1.0572252*C),k.alpha)}function PE(k,g,_){const C=g-k;return k+_*(C>180||C<-180?C-360*Math.round(C/360):C)}const X_={forward:zN,reverse:BS,interpolate:function(k,g,_){return{l:Es(k.l,g.l,_),a:Es(k.a,g.a,_),b:Es(k.b,g.b,_),alpha:Es(k.alpha,g.alpha,_)}}},Ev={forward:function(k){const{l:g,a:_,b:C}=zN(k),P=Math.atan2(C,_)*FS;return{h:P<0?P+360:P,c:Math.sqrt(_*_+C*C),l:g,alpha:k.a}},reverse:function(k){const g=k.h*OS,_=k.c;return BS({l:k.l,a:Math.cos(g)*_,b:Math.sin(g)*_,alpha:k.alpha})},interpolate:function(k,g,_){return{h:PE(k.h,g.h,_),c:Es(k.c,g.c,_),l:Es(k.l,g.l,_),alpha:Es(k.alpha,g.alpha,_)}}};var Bj=Object.freeze({__proto__:null,hcl:Ev,lab:X_});class Vm{constructor(g,_,C,P,O){this.type=g,this.operator=_,this.interpolation=C,this.input=P,this.labels=[],this.outputs=[];for(const[B,W]of O)this.labels.push(B),this.outputs.push(W)}static interpolationFactor(g,_,C,P){let O=0;if(g.name==="exponential")O=Uj(_,g.base,C,P);else if(g.name==="linear")O=Uj(_,1,C,P);else if(g.name==="cubic-bezier"){const B=g.controlPoints;O=new Zn(B[0],B[1],B[2],B[3]).solve(Uj(_,1,C,P))}return O}static parse(g,_){let[C,P,O,...B]=g;if(!Array.isArray(P)||P.length===0)return _.error("Expected an interpolation type expression.",1);if(P[0]==="linear")P={name:"linear"};else if(P[0]==="exponential"){const ae=P[1];if(typeof ae!="number")return _.error("Exponential interpolation requires a numeric base.",1,1);P={name:"exponential",base:ae}}else{if(P[0]!=="cubic-bezier")return _.error(`Unknown interpolation type ${String(P[0])}`,1,0);{const ae=P.slice(1);if(ae.length!==4||ae.some(pe=>typeof pe!="number"||pe<0||pe>1))return _.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);P={name:"cubic-bezier",controlPoints:ae}}}if(g.length-1<4)return _.error(`Expected at least 4 arguments, but found only ${g.length-1}.`);if(g.length-1>3&&(g.length-1)%2!=0)return _.error("Expected an even number of arguments.");if(O=_.parse(O,2,nr),!O)return null;const W=[];let Y=null;C==="interpolate-hcl"||C==="interpolate-lab"?Y=ol:_.expectedType&&_.expectedType.kind!=="value"&&(Y=_.expectedType);for(let ae=0;ae=pe)return _.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',_e);const De=_.parse(ve,Pe,Y);if(!De)return null;Y=Y||De.type,W.push([pe,De])}return Y.kind==="number"||Y.kind==="color"||Y.kind==="array"&&Y.itemType.kind==="number"&&typeof Y.N=="number"?new Vm(Y,C,P,O,W):_.error(`Type ${Ac(Y)} is not interpolatable.`)}evaluate(g){const _=this.labels,C=this.outputs;if(_.length===1)return C[0].evaluate(g);const P=this.input.evaluate(g);if(P<=_[0])return C[0].evaluate(g);const O=_.length;if(P>=_[O-1])return C[O-1].evaluate(g);const B=Ij(_,P),W=Vm.interpolationFactor(this.interpolation,P,_[B],_[B+1]),Y=C[B].evaluate(g),ae=C[B+1].evaluate(g);return this.operator==="interpolate"?Br[this.type.kind.toLowerCase()](Y,ae,W):this.operator==="interpolate-hcl"?Ev.reverse(Ev.interpolate(Ev.forward(Y),Ev.forward(ae),W)):X_.reverse(X_.interpolate(X_.forward(Y),X_.forward(ae),W))}eachChild(g){g(this.input);for(const _ of this.outputs)g(_)}outputDefined(){return this.outputs.every(g=>g.outputDefined())}serialize(){let g;g=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,g,this.input.serialize()];for(let C=0;CMx(P,W.type));return new Q_(B?ao:C,O)}evaluate(g){let _,C=null,P=0;for(const O of this.args){if(P++,C=O.evaluate(g),C&&C instanceof uh&&!C.available&&(_||(_=C),C=null,P===this.args.length))return _;if(C!==null)break}return C}eachChild(g){this.args.forEach(g)}outputDefined(){return this.args.every(g=>g.outputDefined())}serialize(){const g=["coalesce"];return this.eachChild(_=>{g.push(_.serialize())}),g}}class Ee{constructor(g,_){this.type=_.type,this.bindings=[].concat(g),this.result=_}evaluate(g){return this.result.evaluate(g)}eachChild(g){for(const _ of this.bindings)g(_[1]);g(this.result)}static parse(g,_){if(g.length<4)return _.error(`Expected at least 3 arguments, but found ${g.length-1} instead.`);const C=[];for(let O=1;O=C.length)throw new bc("Array index out of bounds: index exceeds array size");if(_!==Math.floor(_))throw new bc("Array index must be an integer. Use at-interpolated for fractional indices");return C[_]}eachChild(g){g(this.index),g(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class ht{constructor(g,_,C){this.type=g,this.index=_,this.input=C}static parse(g,_){if(g.length!==3)return _.error(`Expected 2 arguments, but found ${g.length-1} instead.`);const C=_.parse(g[1],1,nr),P=_.parse(g[2],2,Xu(_.expectedType||ao));return C&&P?new ht(P.type.itemType,C,P):null}evaluate(g){const _=this.index.evaluate(g),C=this.input.evaluate(g);if(_<0)throw new bc(`Array index out of bounds: ${_} < 0.`);if(_>C.length-1)throw new bc(`Array index out of bounds: ${_} > ${C.length-1}.`);if(_===Math.floor(_))return C[_];const P=Math.floor(_),O=Math.ceil(_),B=C[P],W=C[O];if(typeof B!="number"||typeof W!="number")throw new bc(`Cannot interpolate between non-number values at index ${_}.`);const Y=_-P;return B*(1-Y)+W*Y}eachChild(g){g(this.index),g(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class _t{constructor(g,_){this.type=mi,this.needle=g,this.haystack=_}static parse(g,_){if(g.length!==3)return _.error(`Expected 2 arguments, but found ${g.length-1} instead.`),null;const C=_.parse(g[1],1,ao),P=_.parse(g[2],2,ao);return C&&P?wy(C.type,[mi,Va,nr,Ra,ao])?new _t(C,P):(_.error(`Expected first argument to be of type boolean, string, number or null, but found ${Ac(C.type)} instead`),null):null}evaluate(g){const _=this.needle.evaluate(g),C=this.haystack.evaluate(g);if(C==null)return!1;if(!wu(_,["boolean","string","number","null"]))throw new bc(`Expected first argument to be of type boolean, string, number or null, but found ${Ac(Hl(_))} instead.`);if(!wu(C,["string","array"]))throw new bc(`Expected second argument to be of type array or string, but found ${Ac(Hl(C))} instead.`);return C.indexOf(_)>=0}eachChild(g){g(this.needle),g(this.haystack)}outputDefined(){return!0}serialize(){return["in",this.needle.serialize(),this.haystack.serialize()]}}class Jt{constructor(g,_,C){this.type=nr,this.needle=g,this.haystack=_,this.fromIndex=C}static parse(g,_){if(g.length<=2||g.length>=5)return _.error(`Expected 3 or 4 arguments, but found ${g.length-1} instead.`),null;const C=_.parse(g[1],1,ao),P=_.parse(g[2],2,ao);if(!C||!P)return null;if(!wy(C.type,[mi,Va,nr,Ra,ao]))return _.error(`Expected first argument to be of type boolean, string, number or null, but found ${Ac(C.type)} instead`),null;if(g.length===4){const O=_.parse(g[3],3,nr);return O?new Jt(C,P,O):null}return new Jt(C,P)}evaluate(g){const _=this.needle.evaluate(g),C=this.haystack.evaluate(g);if(!wu(_,["boolean","string","number","null"]))throw new bc(`Expected first argument to be of type boolean, string, number or null, but found ${Ac(Hl(_))} instead.`);if(!wu(C,["string","array"]))throw new bc(`Expected second argument to be of type array or string, but found ${Ac(Hl(C))} instead.`);if(this.fromIndex){const P=this.fromIndex.evaluate(g);return C.indexOf(_,P)}return C.indexOf(_)}eachChild(g){g(this.needle),g(this.haystack),this.fromIndex&&g(this.fromIndex)}outputDefined(){return!1}serialize(){if(this.fromIndex!=null&&this.fromIndex!==void 0){const g=this.fromIndex.serialize();return["index-of",this.needle.serialize(),this.haystack.serialize(),g]}return["index-of",this.needle.serialize(),this.haystack.serialize()]}}class cs{constructor(g,_,C,P,O,B){this.inputType=g,this.type=_,this.input=C,this.cases=P,this.outputs=O,this.otherwise=B}static parse(g,_){if(g.length<5)return _.error(`Expected at least 4 arguments, but found only ${g.length-1}.`);if(g.length%2!=1)return _.error("Expected an even number of arguments.");let C,P;_.expectedType&&_.expectedType.kind!=="value"&&(P=_.expectedType);const O={},B=[];for(let ae=2;aeNumber.MAX_SAFE_INTEGER)return _e.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if(typeof De=="number"&&Math.floor(De)!==De)return _e.error("Numeric branch labels must be integer values.");if(C){if(_e.checkSubtype(C,Hl(De)))return null}else C=Hl(De);if(O[String(De)]!==void 0)return _e.error("Branch labels must be unique.");O[String(De)]=B.length}const Pe=_.parse(ve,ae,P);if(!Pe)return null;P=P||Pe.type,B.push(Pe)}const W=_.parse(g[1],1,ao);if(!W)return null;const Y=_.parse(g[g.length-1],g.length-1,P);return Y?W.type.kind!=="value"&&_.concat(1).checkSubtype(C,W.type)?null:new cs(C,P,W,O,B,Y):null}evaluate(g){const _=this.input.evaluate(g);return(Kp(Hl(_),this.inputType)&&this.outputs[this.cases[_]]||this.otherwise).evaluate(g)}eachChild(g){g(this.input),this.outputs.forEach(g),g(this.otherwise)}outputDefined(){return this.outputs.every(g=>g.outputDefined())&&this.otherwise.outputDefined()}serialize(){const g=["match",this.input.serialize()],_=Object.keys(this.cases).sort(),C=[],P={};for(const B of _){const W=P[this.cases[B]];W===void 0?(P[this.cases[B]]=C.length,C.push([this.cases[B],[B]])):C[W][1].push(B)}const O=B=>this.inputType.kind==="number"?Number(B):B;for(const[B,W]of C)g.push(W.length===1?O(W[0]):W.map(O)),g.push(this.outputs[B].serialize());return g.push(this.otherwise.serialize()),g}}class gs{constructor(g,_,C){this.type=g,this.branches=_,this.otherwise=C}static parse(g,_){if(g.length<4)return _.error(`Expected at least 3 arguments, but found only ${g.length-1}.`),null;if(g.length%2!=0)return _.error("Expected an odd number of arguments."),null;let C;_.expectedType&&_.expectedType.kind!=="value"&&(C=_.expectedType);const P=[];for(let B=1;B_.outputDefined())&&this.otherwise.outputDefined()}serialize(){const g=["case"];return this.eachChild(_=>{g.push(_.serialize())}),g}}class Cs{constructor(g,_,C,P){this.type=g,this.input=_,this.beginIndex=C,this.endIndex=P}static parse(g,_){if(g.length<=2||g.length>=5)return _.error(`Expected 3 or 4 arguments, but found ${g.length-1} instead.`),null;const C=_.parse(g[1],1,ao),P=_.parse(g[2],2,nr);if(!C||!P)return null;if(!wy(C.type,[Xu(ao),Va,ao]))return _.error(`Expected first argument to be of type array or string, but found ${Ac(C.type)} instead`),null;if(g.length===4){const O=_.parse(g[3],3,nr);return O?new Cs(C.type,C,P,O):null}return new Cs(C.type,C,P)}evaluate(g){const _=this.input.evaluate(g),C=this.beginIndex.evaluate(g);if(!wu(_,["string","array"]))throw new bc(`Expected first argument to be of type array or string, but found ${Ac(Hl(_))} instead.`);if(this.endIndex){const P=this.endIndex.evaluate(g);return _.slice(C,P)}return _.slice(C)}eachChild(g){g(this.input),g(this.beginIndex),this.endIndex&&g(this.endIndex)}outputDefined(){return!1}serialize(){if(this.endIndex!=null&&this.endIndex!==void 0){const g=this.endIndex.serialize();return["slice",this.input.serialize(),this.beginIndex.serialize(),g]}return["slice",this.input.serialize(),this.beginIndex.serialize()]}}class Ps{constructor(g,_){this.type=Xu(Va),this.str=g,this.delimiter=_}static parse(g,_){if(g.length!==3)return _.error(`Expected 2 arguments, but found ${g.length-1} instead.`);const C=_.parse(g[1],1,Va),P=_.parse(g[2],2,Va);return C&&P?new Ps(C,P):void 0}evaluate(g){const _=this.str.evaluate(g),C=this.delimiter.evaluate(g);return _.split(C)}eachChild(g){g(this.str),g(this.delimiter)}outputDefined(){return!1}serialize(){return["split",this.str.serialize(),this.delimiter.serialize()]}}function Qs(k,g){return k==="=="||k==="!="?g.kind==="boolean"||g.kind==="string"||g.kind==="number"||g.kind==="null"||g.kind==="value":g.kind==="string"||g.kind==="number"||g.kind==="value"}function En(k,g,_,C){return C.compare(g,_)===0}function Xn(k,g,_){const C=k!=="=="&&k!=="!=";return class uRt{constructor(O,B,W){this.type=mi,this.lhs=O,this.rhs=B,this.collator=W,this.hasUntypedArgument=O.type.kind==="value"||B.type.kind==="value"}static parse(O,B){if(O.length!==3&&O.length!==4)return B.error("Expected two or three arguments.");const W=O[0];let Y=B.parse(O[1],1,ao);if(!Y)return null;if(!Qs(W,Y.type))return B.concat(1).error(`"${W}" comparisons are not supported for type '${Ac(Y.type)}'.`);let ae=B.parse(O[2],2,ao);if(!ae)return null;if(!Qs(W,ae.type))return B.concat(2).error(`"${W}" comparisons are not supported for type '${Ac(ae.type)}'.`);if(Y.type.kind!==ae.type.kind&&Y.type.kind!=="value"&&ae.type.kind!=="value")return B.error(`Cannot compare types '${Ac(Y.type)}' and '${Ac(ae.type)}'.`);C&&(Y.type.kind==="value"&&ae.type.kind!=="value"?Y=new gp(ae.type,[Y]):Y.type.kind!=="value"&&ae.type.kind==="value"&&(ae=new gp(Y.type,[ae])));let pe=null;if(O.length===4){if(Y.type.kind!=="string"&&ae.type.kind!=="string"&&Y.type.kind!=="value"&&ae.type.kind!=="value")return B.error("Cannot use collator to compare non-string types.");if(pe=B.parse(O[3],3,$m),!pe)return null}return new uRt(Y,ae,pe)}evaluate(O){const B=this.lhs.evaluate(O),W=this.rhs.evaluate(O);if(C&&this.hasUntypedArgument){const Y=Hl(B),ae=Hl(W);if(Y.kind!==ae.kind||Y.kind!=="string"&&Y.kind!=="number")throw new bc(`Expected arguments for "${k}" to be (string, string) or (number, number), but found (${Y.kind}, ${ae.kind}) instead.`)}if(this.collator&&!C&&this.hasUntypedArgument){const Y=Hl(B),ae=Hl(W);if(Y.kind!=="string"||ae.kind!=="string")return g(O,B,W)}return this.collator?_(O,B,W,this.collator.evaluate(O)):g(O,B,W)}eachChild(O){O(this.lhs),O(this.rhs),this.collator&&O(this.collator)}outputDefined(){return!0}serialize(){const O=[k];return this.eachChild(B=>{O.push(B.serialize())}),O}}}const Js=Xn("==",function(k,g,_){return g===_},En),Fn=Xn("!=",function(k,g,_){return g!==_},function(k,g,_,C){return!En(0,g,_,C)}),rr=Xn("<",function(k,g,_){return g<_},function(k,g,_,C){return C.compare(g,_)<0}),Tr=Xn(">",function(k,g,_){return g>_},function(k,g,_,C){return C.compare(g,_)>0}),vr=Xn("<=",function(k,g,_){return g<=_},function(k,g,_,C){return C.compare(g,_)<=0}),qn=Xn(">=",function(k,g,_){return g>=_},function(k,g,_,C){return C.compare(g,_)>=0});class Vr{constructor(g,_,C,P,O,B){this.type=Va,this.number=g,this.locale=_,this.currency=C,this.unit=P,this.minFractionDigits=O,this.maxFractionDigits=B}static parse(g,_){if(g.length!==3)return _.error("Expected two arguments.");const C=_.parse(g[1],1,nr);if(!C)return null;const P=g[2];if(typeof P!="object"||Array.isArray(P))return _.error("NumberFormat options argument must be an object.");let O=null;if(P.locale&&(O=_.parseObjectValue(P.locale,2,"locale",Va),!O))return null;let B=null;if(P.currency&&(B=_.parseObjectValue(P.currency,2,"currency",Va),!B))return null;let W=null;if(P.unit&&(W=_.parseObjectValue(P.unit,2,"unit",Va),!W))return null;let Y=null;if(P["min-fraction-digits"]&&(Y=_.parseObjectValue(P["min-fraction-digits"],2,"min-fraction-digits",nr),!Y))return null;let ae=null;return P["max-fraction-digits"]&&(ae=_.parseObjectValue(P["max-fraction-digits"],2,"max-fraction-digits",nr),!ae)?null:new Vr(C,O,B,W,Y,ae)}evaluate(g){return new Intl.NumberFormat(this.locale?this.locale.evaluate(g):[],{style:(this.currency?"currency":this.unit&&"unit")||"decimal",currency:this.currency?this.currency.evaluate(g):void 0,unit:this.unit?this.unit.evaluate(g):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(g):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(g):void 0}).format(this.number.evaluate(g))}eachChild(g){g(this.number),this.locale&&g(this.locale),this.currency&&g(this.currency),this.unit&&g(this.unit),this.minFractionDigits&&g(this.minFractionDigits),this.maxFractionDigits&&g(this.maxFractionDigits)}outputDefined(){return!1}serialize(){const g={};return this.locale&&(g.locale=this.locale.serialize()),this.currency&&(g.currency=this.currency.serialize()),this.unit&&(g.unit=this.unit.serialize()),this.minFractionDigits&&(g["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(g["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),g]}}class wa{constructor(g){this.type=nr,this.input=g}static parse(g,_){if(g.length!==2)return _.error(`Expected 1 argument, but found ${g.length-1} instead.`),null;const C=_.parse(g[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 ${Ac(C.type)} instead.`),null):new wa(C):null}evaluate(g){const _=this.input.evaluate(g);if(typeof _=="string"||Array.isArray(_))return _.length;throw new bc(`Expected value to be of type string or array, but found ${Ac(Hl(_))} instead.`)}eachChild(g){g(this.input)}outputDefined(){return!1}serialize(){const g=["length"];return this.eachChild(_=>{g.push(_.serialize())}),g}}function ga(k){return function(){k=1831565813+(k|=0)|0;let g=Math.imul(k^k>>>15,1|k);return g=g+Math.imul(g^g>>>7,61|g)^g,((g^g>>>14)>>>0)/4294967296}}const Xi={"==":Js,"!=":Fn,">":Tr,"<":rr,">=":qn,"<=":vr,array:gp,at:ze,"at-interpolated":ht,boolean:gp,case:gs,coalesce:Q_,collator:v1,format:Ud,image:fa,in:_t,"index-of":Jt,interpolate:Vm,"interpolate-hcl":Vm,"interpolate-lab":Vm,length:wa,let:Ee,literal:Hr,match:cs,number:gp,"number-format":Vr,object:gp,slice:Cs,step:Rj,string:gp,"to-boolean":Yp,"to-color":Yp,"to-number":Yp,"to-string":Yp,var:Df,within:Ay,distance:Rb,config:ex,split:Ps};function Mi(k,[g,_,C,P]){g=g.evaluate(k),_=_.evaluate(k),C=C.evaluate(k);const O=P?P.evaluate(k):1,B=fp(g,_,C,O);if(B)throw new bc(B);return new Zs(g/255,_/255,C/255,O)}function yl(k,[g,_,C,P]){g=g.evaluate(k),_=_.evaluate(k),C=C.evaluate(k);const O=P?P.evaluate(k):1,B=function(ae,pe,ve,_e){return typeof ae=="number"&&ae>=0&&ae<=360?typeof pe=="number"&&pe>=0&&pe<=100&&typeof ve=="number"&&ve>=0&&ve<=100?_e===void 0||typeof _e=="number"&&_e>=0&&_e<=1?null:`Invalid hsla value [${[ae,pe,ve,_e].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof _e=="number"?[ae,pe,ve,_e]:[ae,pe,ve]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof _e=="number"?[ae,pe,ve,_e]:[ae,pe,ve]).join(", ")}]: 'h' must be between 0 and 360.`}(g,_,C,O);if(B)throw new bc(B);const W=`hsla(${g}, ${_}%, ${C}%, ${O})`,Y=Zs.parse(W);if(!Y)throw new bc(`Failed to parse HSLA color: ${W}`);return Y}function Ui(k,g){return k in g}function ic(k,g){const _=g[k];return _===void 0?null:_}function cu(k){return{type:k}}function vl(k){if(k instanceof ex)return new Set([k.key]);let g=new Set;return k.eachChild(_=>{g=new Set([...g,...vl(_)])}),g}function Hi(k){if(k instanceof Sd&&k.name==="is-active-floor")return!0;let g=!1;return k.eachChild(_=>{!g&&Hi(_)&&(g=!0)}),g}function ci(k){return{result:"success",value:k}}function wl(k){return{result:"error",value:k}}function vo(k,g){return!!k&&!!k.parameters&&k.parameters.indexOf(g)>-1}function ul(k){return k["property-type"]==="data-driven"}function su(k){return vo(k.expression,"measure-light")}function vm(k){return vo(k.expression,"zoom")}function nu(k){return!!k.expression&&k.expression.interpolated}function Lu(k){return typeof k=="object"&&k!==null&&!Array.isArray(k)}function Nu(k){return k}function Ff(k,g){const _=g.type==="color",C=k.stops&&typeof k.stops[0][0]=="object",P=C||!(C||k.property!==void 0),O=k.type||(nu(g)?"exponential":"interval");if(_&&((k=Object.assign({},k)).stops&&(k.stops=k.stops.map(ae=>[ae[0],Zs.parse(ae[1])])),k.default=Zs.parse(k.default?k.default:g.default)),k.colorSpace&&k.colorSpace!=="rgb"&&!Bj[k.colorSpace])throw new Error(`Unknown color space: ${k.colorSpace}`);let B,W,Y;if(O==="exponential")B=th;else if(O==="interval")B=Ad;else if(O==="categorical"){B=Vc,W=Object.create(null);for(const ae of k.stops)W[ae[0]]=ae[1];Y=typeof k.stops[0][0]}else{if(O!=="identity")throw new Error(`Unknown function type "${O}"`);B=Jc}if(C){const ae={},pe=[];for(let Pe=0;PePe[0]),evaluate:({zoom:Pe},De)=>th({stops:ve,base:k.base},g,Pe).evaluate(Pe,De)}}if(P){const ae=O==="exponential"?{name:"exponential",base:k.base!==void 0?k.base:1}:null;return{kind:"camera",interpolationType:ae,interpolationFactor:Vm.interpolationFactor.bind(void 0,ae),zoomStops:k.stops.map(pe=>pe[0]),evaluate:({zoom:pe})=>B(k,g,pe,W,Y)}}return{kind:"source",evaluate(ae,pe){const ve=pe&&pe.properties?pe.properties[k.property]:void 0;return ve===void 0?qd(k.default,g.default):B(k,g,ve,W,Y)}}}function qd(k,g,_){return k!==void 0?k:g!==void 0?g:_!==void 0?_:void 0}function Vc(k,g,_,C,P){return qd(typeof _===P?C[_]:void 0,k.default,g.default)}function Ad(k,g,_){if(!Ny(_))return qd(k.default,g.default);const C=k.stops.length;if(C===1||_<=k.stops[0][0])return k.stops[0][1];if(_>=k.stops[C-1][0])return k.stops[C-1][1];const P=Ij(k.stops.map(O=>O[0]),_);return k.stops[P][1]}function th(k,g,_){const C=k.base!==void 0?k.base:1;if(!Ny(_))return qd(k.default,g.default);const P=k.stops.length;if(P===1||_<=k.stops[0][0])return k.stops[0][1];if(_>=k.stops[P-1][0])return k.stops[P-1][1];const O=Ij(k.stops.map(pe=>pe[0]),_),B=function(pe,ve,_e,Pe){const De=Pe-_e,We=pe-_e;return De===0?0:ve===1?We/De:(Math.pow(ve,We)-1)/(Math.pow(ve,De)-1)}(_,C,k.stops[O][0],k.stops[O+1][0]),W=k.stops[O][1],Y=k.stops[O+1][1];let ae=Br[g.type]||Nu;if(k.colorSpace&&k.colorSpace!=="rgb"){const pe=Bj[k.colorSpace];ae=(ve,_e)=>pe.reverse(pe.interpolate(pe.forward(ve),pe.forward(_e),B))}return typeof W.evaluate=="function"?{evaluate(...pe){const ve=W.evaluate.apply(void 0,pe),_e=Y.evaluate.apply(void 0,pe);if(ve!==void 0&&_e!==void 0)return ae(ve,_e,B)}}:ae(W,Y,B)}function Jc(k,g,_){return g.type==="color"?_=Zs.parse(_):g.type==="formatted"?_=Bd.fromString(_.toString()):g.type==="resolvedImage"?_=uh.build(_.toString()):Px(_)===g.type||g.type==="enum"&&g.values[_]||(_=void 0),qd(_,k.default,g.default)}Sd.register(Xi,{error:[{kind:"error"},[Va],(k,[g])=>{throw new bc(g.evaluate(k))}],typeof:[Va,[ao],(k,[g])=>Ac(Hl(g.evaluate(k)))],"to-rgba":[Xu(nr,4),[ol],(k,[g])=>g.evaluate(k).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[Xu(nr,4),[ol],(k,[g])=>g.evaluate(k).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[ol,[nr,nr,nr],Mi],rgba:[ol,[nr,nr,nr,nr],Mi],hsl:[ol,[nr,nr,nr],yl],hsla:[ol,[nr,nr,nr,nr],yl],has:{type:mi,overloads:[[[Va],(k,[g])=>Ui(g.evaluate(k),k.properties())],[[Va,vc],(k,[g,_])=>Ui(g.evaluate(k),_.evaluate(k))]]},get:{type:ao,overloads:[[[Va],(k,[g])=>ic(g.evaluate(k),k.properties())],[[Va,vc],(k,[g,_])=>ic(g.evaluate(k),_.evaluate(k))]]},"feature-state":[ao,[Va],(k,[g])=>ic(g.evaluate(k),k.featureState||{})],properties:[vc,[],k=>k.properties()],"geometry-type":[Va,[],k=>k.geometryType()],worldview:[Va,[],k=>k.globals.worldview||""],"is-active-floor":[mi,cu(Va),(k,g)=>{if(!(k.globals&&k.globals.activeFloors&&k.globals.activeFloors.size>0))return!1;if(g.length===0)return!0;const _=k.globals.activeFloors;return g.some(C=>{const P=C.evaluate(k);return _.has(P)})}],id:[ao,[],k=>k.id()],zoom:[nr,[],k=>k.globals.zoom],pitch:[nr,[],k=>k.globals.pitch||0],"distance-from-center":[nr,[],k=>k.distanceFromCenter()],"measure-light":[nr,[Va],(k,[g])=>k.measureLight(g.evaluate(k))],"heatmap-density":[nr,[],k=>k.globals.heatmapDensity||0],"line-progress":[nr,[],k=>k.globals.lineProgress||0],"raster-value":[nr,[],k=>k.globals.rasterValue||0],"raster-particle-speed":[nr,[],k=>k.globals.rasterParticleSpeed||0],"sky-radial-progress":[nr,[],k=>k.globals.skyRadialProgress||0],accumulated:[ao,[],k=>k.globals.accumulated===void 0?null:k.globals.accumulated],"+":[nr,cu(nr),(k,g)=>{let _=0;for(const C of g)_+=C.evaluate(k);return _}],"*":[nr,cu(nr),(k,g)=>{let _=1;for(const C of g)_*=C.evaluate(k);return _}],"-":{type:nr,overloads:[[[nr,nr],(k,[g,_])=>g.evaluate(k)-_.evaluate(k)],[[nr],(k,[g])=>-g.evaluate(k)]]},"/":[nr,[nr,nr],(k,[g,_])=>g.evaluate(k)/_.evaluate(k)],"%":[nr,[nr,nr],(k,[g,_])=>g.evaluate(k)%_.evaluate(k)],ln2:[nr,[],()=>Math.LN2],pi:[nr,[],()=>Math.PI],e:[nr,[],()=>Math.E],"^":[nr,[nr,nr],(k,[g,_])=>Math.pow(g.evaluate(k),_.evaluate(k))],sqrt:[nr,[nr],(k,[g])=>Math.sqrt(g.evaluate(k))],log10:[nr,[nr],(k,[g])=>Math.log(g.evaluate(k))/Math.LN10],ln:[nr,[nr],(k,[g])=>Math.log(g.evaluate(k))],log2:[nr,[nr],(k,[g])=>Math.log2(g.evaluate(k))],sin:[nr,[nr],(k,[g])=>Math.sin(g.evaluate(k))],cos:[nr,[nr],(k,[g])=>Math.cos(g.evaluate(k))],tan:[nr,[nr],(k,[g])=>Math.tan(g.evaluate(k))],asin:[nr,[nr],(k,[g])=>Math.asin(g.evaluate(k))],acos:[nr,[nr],(k,[g])=>Math.acos(g.evaluate(k))],atan:[nr,[nr],(k,[g])=>Math.atan(g.evaluate(k))],min:[nr,cu(nr),(k,g)=>Math.min(...g.map(_=>_.evaluate(k)))],max:[nr,cu(nr),(k,g)=>Math.max(...g.map(_=>_.evaluate(k)))],abs:[nr,[nr],(k,[g])=>Math.abs(g.evaluate(k))],round:[nr,[nr],(k,[g])=>{const _=g.evaluate(k);return _<0?-Math.round(-_):Math.round(_)}],floor:[nr,[nr],(k,[g])=>Math.floor(g.evaluate(k))],ceil:[nr,[nr],(k,[g])=>Math.ceil(g.evaluate(k))],"filter-==":[mi,[Va,ao],(k,[g,_])=>k.properties()[g.value]===_.value],"filter-id-==":[mi,[ao],(k,[g])=>k.id()===g.value],"filter-type-==":[mi,[Va],(k,[g])=>k.geometryType()===g.value],"filter-<":[mi,[Va,ao],(k,[g,_])=>{const C=k.properties()[g.value],P=_.value;return typeof C==typeof P&&C{const _=k.id(),C=g.value;return typeof _==typeof C&&_":[mi,[Va,ao],(k,[g,_])=>{const C=k.properties()[g.value],P=_.value;return typeof C==typeof P&&C>P}],"filter-id->":[mi,[ao],(k,[g])=>{const _=k.id(),C=g.value;return typeof _==typeof C&&_>C}],"filter-<=":[mi,[Va,ao],(k,[g,_])=>{const C=k.properties()[g.value],P=_.value;return typeof C==typeof P&&C<=P}],"filter-id-<=":[mi,[ao],(k,[g])=>{const _=k.id(),C=g.value;return typeof _==typeof C&&_<=C}],"filter->=":[mi,[Va,ao],(k,[g,_])=>{const C=k.properties()[g.value],P=_.value;return typeof C==typeof P&&C>=P}],"filter-id->=":[mi,[ao],(k,[g])=>{const _=k.id(),C=g.value;return typeof _==typeof C&&_>=C}],"filter-has":[mi,[ao],(k,[g])=>g.value in k.properties()],"filter-has-id":[mi,[],k=>k.id()!==null&&k.id()!==void 0],"filter-type-in":[mi,[Xu(Va)],(k,[g])=>g.value.indexOf(k.geometryType())>=0],"filter-id-in":[mi,[Xu(ao)],(k,[g])=>g.value.indexOf(k.id())>=0],"filter-in-small":[mi,[Va,Xu(ao)],(k,[g,_])=>_.value.indexOf(k.properties()[g.value])>=0],"filter-in-large":[mi,[Va,Xu(ao)],(k,[g,_])=>function(C,P,O,B){for(;O<=B;){const W=O+B>>1;if(P[W]===C)return!0;P[W]>C?B=W-1:O=W+1}return!1}(k.properties()[g.value],_.value,0,_.value.length-1)],all:{type:mi,overloads:[[[mi,mi],(k,[g,_])=>g.evaluate(k)&&_.evaluate(k)],[cu(mi),(k,g)=>{for(const _ of g)if(!_.evaluate(k))return!1;return!0}]]},any:{type:mi,overloads:[[[mi,mi],(k,[g,_])=>g.evaluate(k)||_.evaluate(k)],[cu(mi),(k,g)=>{for(const _ of g)if(_.evaluate(k))return!0;return!1}]]},"!":[mi,[mi],(k,[g])=>!g.evaluate(k)],"is-supported-script":[mi,[Va],(k,[g])=>{const _=k.globals&&k.globals.isSupportedScript;return!_||_(g.evaluate(k))}],upcase:[Va,[Va],(k,[g])=>g.evaluate(k).toUpperCase()],downcase:[Va,[Va],(k,[g])=>g.evaluate(k).toLowerCase()],concat:[Va,cu(ao),(k,g)=>g.map(_=>Ia(_.evaluate(k))).join("")],"resolved-locale":[Va,[$m],(k,[g])=>g.evaluate(k).resolvedLocale()],random:[nr,[nr,nr,ao],(k,g)=>{const[_,C,P]=g.map(B=>B.evaluate(k));if(_>C||_===C)return _;let O;if(typeof P=="string")O=function(B){let W=0;if(B.length===0)return W;for(let Y=0;YJSON.stringify(ve)).join(", ")}, but found ${JSON.stringify(pe)} instead.`);return pe}catch(pe){const ve=pe;return this._warningHistory[ve.message]||(this._warningHistory[ve.message]=!0,typeof console<"u"&&console.warn(`Failed to evaluate expression "${JSON.stringify(this.expression.serialize())}". ${ve.message}`)),this._defaultValue}}}function xp(k){return Array.isArray(k)&&k.length>0&&typeof k[0]=="string"&&k[0]in Xi}function xd(k,g,_,C,P){const O=new FN(Xi,[],g?function(W){const Y={color:ol,string:Va,number:nr,enum:Va,boolean:mi,formatted:k0,resolvedImage:S0};return W.type==="array"?Xu(Y[W.value]||ao,W.length):Y[W.type]}(g):void 0,void 0,void 0,_,C,P),B=O.parse(k,void 0,void 0,void 0,g&&g.type==="string"?{typeAnnotation:"coerce"}:void 0);return B?ci(new hh(B,g,_,C,P)):wl(O.errors)}class Ih{constructor(g,_,C,P){this.kind=g,this._styleExpression=_,this.isLightConstant=C,this.isLineProgressConstant=P,this.isStateDependent=g!=="constant"&&!bg(_.expression),this.configDependencies=vl(_.expression),this.isIndoorDependent=Hi(_.expression)}evaluateWithoutErrorHandling(g,_,C,P,O,B){return this._styleExpression.evaluateWithoutErrorHandling(g,_,C,P,O,B)}evaluate(g,_,C,P,O,B,W){return this._styleExpression.evaluate(g,_,C,P,O,B,void 0,void 0,W)}}class wc{constructor(g,_,C,P,O,B){this.kind=g,this.zoomStops=C,this._styleExpression=_,this.isStateDependent=g!=="camera"&&!bg(_.expression),this.isIndoorDependent=Hi(_.expression),this.isLightConstant=O,this.isLineProgressConstant=B,this.configDependencies=vl(_.expression),this.interpolationType=P}evaluateWithoutErrorHandling(g,_,C,P,O,B){return this._styleExpression.evaluateWithoutErrorHandling(g,_,C,P,O,B)}evaluate(g,_,C,P,O,B){return this._styleExpression.evaluate(g,_,C,P,O,B)}interpolationFactor(g,_,C){return this.interpolationType?Vm.interpolationFactor(this.interpolationType,g,_,C):0}}function mh(k,g,_,C,P){if((k=xd(k,g,_,C,P)).result==="error")return k;const O=k.value.expression,B=Db(O);if(!B&&!ul(g))return wl([new Or("","data expressions not supported")]);const W=Pu(O,["zoom","pitch","distance-from-center"]);if(!W&&!vm(g))return wl([new Or("","zoom expressions not supported")]);const Y=Pu(O,["measure-light"]);if(!Y&&!su(g))return wl([new Or("","measure-light expression not supported")]);const ae=Pu(O,["line-progress"]);if(!ae&&!function(_e){return vo(_e.expression,"line-progress")}(g))return wl([new Or("","line-progress expression not supported")]);const pe=g.expression&&g.expression.relaxZoomRestriction,ve=du(O);return ve||W||pe?ve instanceof Or?wl([ve]):ve instanceof Vm&&!nu(g)?wl([new Or("",'"interpolate" expressions cannot be used with this property')]):ci(ve?new wc(B&&ae?"camera":"composite",k.value,ve.labels,ve instanceof Vm?ve.interpolation:void 0,Y,ae):new Ih(B&&ae?"constant":"source",k.value,Y,ae)):wl([new Or("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class yp{constructor(g,_){this._parameters=g,this._specification=_,Object.assign(this,Ff(this._parameters,this._specification))}static deserialize(g){return new yp(g._parameters,g._specification)}static serialize(g){return{_parameters:g._parameters,_specification:g._specification}}}function du(k){let g=null;if(k instanceof Ee)g=du(k.result);else if(k instanceof Q_){for(const _ of k.args)if(g=du(_),g)break}else(k instanceof Rj||k instanceof Vm)&&k.input instanceof Sd&&k.input.name==="zoom"&&(g=k);return g instanceof Or||k.eachChild(_=>{const C=du(_);C instanceof Or?g=C:g&&C&&g!==C&&(g=new Or("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),g}var zf,Bf,vp=function(){if(Bf)return zf;Bf=1,zf=g;var k=3;function g(_,C,P){var O=this.cells=[];if(_ instanceof ArrayBuffer){this.arrayBuffer=_;var B=new Int32Array(this.arrayBuffer);_=B[0],this.d=(C=B[1])+2*(P=B[2]);for(var W=0;W=_e[We+0]&&O>=_e[We+1])?(Y[De]=!0,W.push(ve[De])):Y[De]=!1}}},g.prototype._forEachCell=function(_,C,P,O,B,W,Y,ae){for(var pe=this._convertToCellCoord(_),ve=this._convertToCellCoord(C),_e=this._convertToCellCoord(P),Pe=this._convertToCellCoord(O),De=pe;De<=_e;De++)for(var We=ve;We<=Pe;We++){var Je=this.d*We+De;if((!ae||ae(this._convertFromCellCoord(De),this._convertFromCellCoord(We),this._convertFromCellCoord(De+1),this._convertFromCellCoord(We+1)))&&B.call(this,_,C,P,O,Je,W,Y,ae))return}},g.prototype._convertFromCellCoord=function(_){return(_-this.padding)/this.scale},g.prototype._convertToCellCoord=function(_){return Math.max(0,Math.min(this.d-1,Math.floor(_*this.scale)+this.padding))},g.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var _=this.cells,C=k+this.cells.length+1+1,P=0,O=0;O=0||(P[O]=cd(k[O],g)));k instanceof Error&&(P.message=k.message)}if(P.$name)throw new Error("$name property is reserved for worker serialization logic.");return C!=="Object"&&(P.$name=C),P}throw new Error("can't serialize object of type "+typeof k)}function Oc(k){if(k==null||typeof k=="boolean"||typeof k=="number"||typeof k=="string"||k instanceof Boolean||k instanceof Number||k instanceof String||k instanceof Date||k instanceof RegExp||To(k)||k instanceof ImageBitmap||ArrayBuffer.isView(k)||k instanceof ImageData)return k;if(Array.isArray(k))return k.map(Oc);if(typeof k=="object"){const g=k.$name||"Object";if(g==="Map"){const P=k.entries||[],O=new Map;for(let B=0;Bk>=1536&&k<=1791,Hm=k=>k>=1872&&k<=1919,Ty=k=>k>=2208&&k<=2303,Iu=k=>k>=11904&&k<=12031,Jp=k=>k>=12032&&k<=12255,j1=k=>k>=12272&&k<=12287,Ob=k=>k>=12288&&k<=12351,N1=k=>k>=12352&&k<=12447,bp=k=>k>=12448&&k<=12543,Uf=k=>k>=12544&&k<=12591,qj=k=>k>=12704&&k<=12735,M0=k=>k>=12736&&k<=12783,My=k=>k>=12784&&k<=12799,Tv=k=>k>=12800&&k<=13055,$j=k=>k>=13056&&k<=13311,Vj=k=>k>=13312&&k<=19903,tx=k=>k>=19968&&k<=40959,Mv=k=>k>=40960&&k<=42127,sx=k=>k>=42128&&k<=42191,J_=k=>k>=44032&&k<=55215,Fb=k=>k>=63744&&k<=64255,zb=k=>k>=64336&&k<=65023,Hj=k=>k>=65040&&k<=65055,Bb=k=>k>=65072&&k<=65103,sh=k=>k>=65104&&k<=65135,Py=k=>k>=65136&&k<=65279,_g=k=>k>=65280&&k<=65519;function qf(k){for(const g of k)if(US(g.charCodeAt(0)))return!0;return!1}function M3(k){for(const g of k)if(!Ub(g.charCodeAt(0)))return!1;return!0}function Ub(k){return!(Gc(k)||Hm(k)||Ty(k)||zb(k)||Py(k))}function P3(k){return!(k<11904||!(qj(k)||Uf(k)||Bb(k)||Fb(k)||$j(k)||Iu(k)||M0(k)||Ob(k)||Vj(k)||tx(k)||Tv(k)||_g(k)||N1(k)||j1(k)||Jp(k)||My(k)||bp(k)||Hj(k)||sx(k)||Mv(k)))}function US(k){return!(k!==746&&k!==747&&(k<4352||!(qj(k)||Uf(k)||Bb(k)&&!(k>=65097&&k<=65103)||Fb(k)||$j(k)||Iu(k)||M0(k)||!(!Ob(k)||k>=12296&&k<=12305||k>=12308&&k<=12319||k===12336)||Vj(k)||tx(k)||Tv(k)||(g=>g>=12592&&g<=12687)(k)||(g=>g>=43360&&g<=43391)(k)||(g=>g>=55216&&g<=55295)(k)||(g=>g>=4352&&g<=4607)(k)||J_(k)||N1(k)||j1(k)||(g=>g>=12688&&g<=12703)(k)||Jp(k)||My(k)||bp(k)&&k!==12540||!(!_g(k)||k===65288||k===65289||k===65293||k>=65306&&k<=65310||k===65339||k===65341||k===65343||k>=65371&&k<=65503||k===65507||k>=65512&&k<=65519)||!(!sh(k)||k>=65112&&k<=65118||k>=65123&&k<=65126)||(g=>g>=5120&&g<=5759)(k)||(g=>g>=6320&&g<=6399)(k)||Hj(k)||(g=>g>=19904&&g<=19967)(k)||Mv(k)||sx(k))))}function k1(k){return k===12312||k===12313||k===12316||k===12540||k===12448}function S1(k){return!(US(k)||function(g){return!!((_=>_>=128&&_<=255)(g)&&(g===167||g===169||g===174||g===177||g===188||g===189||g===190||g===215||g===247)||(_=>_>=8192&&_<=8303)(g)&&(g===8214||g===8224||g===8225||g===8240||g===8241||g===8251||g===8252||g===8258||g===8263||g===8264||g===8265||g===8273)||(_=>_>=8448&&_<=8527)(g)||(_=>_>=8528&&_<=8591)(g)||(_=>_>=8960&&_<=9215)(g)&&(g>=8960&&g<=8967||g>=8972&&g<=8991||g>=8996&&g<=9e3||g===9003||g>=9085&&g<=9114||g>=9150&&g<=9165||g===9167||g>=9169&&g<=9179||g>=9186&&g<=9215)||(_=>_>=9216&&_<=9279)(g)&&g!==9251||(_=>_>=9280&&_<=9311)(g)||(_=>_>=9312&&_<=9471)(g)||(_=>_>=9632&&_<=9727)(g)||(_=>_>=9728&&_<=9983)(g)&&!(g>=9754&&g<=9759)||(_=>_>=11008&&_<=11263)(g)&&(g>=11026&&g<=11055||g>=11088&&g<=11097||g>=11192&&g<=11243)||Ob(g)||bp(g)||(_=>_>=57344&&_<=63743)(g)||Bb(g)||sh(g)||_g(g)||g===8734||g===8756||g===8757||g>=9984&&g<=10087||g>=10102&&g<=10131||g===65532||g===65533)}(k))}function L3(k){return Gc(k)||Hm(k)||Ty(k)||zb(k)||Py(k)}function C1(k){return k>=1424&&k<=2303||zb(k)||Py(k)}function P0(k,g){return!(!g&&C1(k)||k>=2304&&k<=3583||k>=3840&&k<=4255||(_=>_>=6016&&_<=6143)(k))}function BN(k){for(const g of k)if(C1(g.charCodeAt(0)))return!0;return!1}const ph={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let Gm=null,uu=ph.unavailable,$f=null;const qS=function(k){k&&typeof k=="string"&&k.indexOf("NetworkError")>-1&&(uu=ph.error),Gm&&Gm(k)};function UN(){$S.fire(new ld("pluginStateChange",{pluginStatus:uu,pluginURL:$f}))}const $S=new qm,Ly=function(){return uu},VS=function(){if(uu!==ph.deferred||!$f)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");uu=ph.loading,UN(),$f&&Qh({url:$f},k=>{k?qS(k):(uu=ph.loaded,UN())})},Dx={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>uu===ph.loaded||Dx.applyArabicShaping!=null,isLoading:()=>uu===ph.loading,setState(k){uu=k.pluginStatus,$f=k.pluginURL},isParsing:()=>uu===ph.parsing,isParsed:()=>uu===ph.parsed,getPluginURL:()=>$f},vL=function(){Dx.isLoading()||Dx.isLoaded()||Ly()!=="deferred"||VS()};class Oi{constructor(g,_){this.zoom=g,_?(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(g){return function(_,C){for(const P of _)if(!P0(P.charCodeAt(0),C))return!1;return!0}(g,Dx.isLoaded())}}class HS{constructor(g,_,C,P,O){this.property=g,this.value=_,this.expression=function(B,W,Y,ae,pe){if(Lu(B))return new yp(B,W);if(xp(B)||Array.isArray(B)&&B.length>0){const ve=mh(B,W,Y,ae,pe);if(ve.result==="error")throw new Error(ve.value.map(_e=>`${_e.key}: ${_e.message}`).join(", "));return ve.value}{let ve=B;return typeof B=="string"&&W.type==="color"&&(ve=Zs.parse(B)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>ve}}}(_===void 0?g.specification.default:_,g.specification,C,P,O)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(g,_,C,P){return this.property.possiblyEvaluate(this,g,_,C,P)}}class I3{constructor(g,_,C,P){this.property=g,this.value=new HS(g,void 0,_,C,P)}transitioned(g,_){return new GS(this.property,this.value,_,Object.assign({},g.transition,this.transition),g.now)}untransitioned(){return new GS(this.property,this.value,null,{},0)}}class LE{constructor(g,_,C,P){this._properties=g,this._values=Object.create(g.defaultTransitionablePropertyValues),this._scope=_,this._options=C,this._iconImageUseTheme=P,this._isIndoorDependent=!1,this.configDependencies=new Set}getValue(g){return zn(this._values[g].value.value)}setValue(g,_){this._values.hasOwnProperty(g)||(this._values[g]=new I3(this._values[g].property,this._scope,this._options,this._iconImageUseTheme)),this._values[g].value=new HS(this._values[g].property,_===null?void 0:zn(_),this._scope,this._options,this._iconImageUseTheme),this._values[g].value.expression.configDependencies&&(this.configDependencies=new Set([...this.configDependencies,...this._values[g].value.expression.configDependencies]),this._isIndoorDependent=this._isIndoorDependent||this._values[g].value.isIndoorDependent())}setTransitionOrValue(g,_){_&&(this._options=_);const C=this._properties.properties;if(g)for(const P in g){const O=g[P];if(P.endsWith("-transition")){const B=P.slice(0,-11);C[B]&&this.setTransition(B,O)}else C.hasOwnProperty(P)&&this.setValue(P,O)}}getTransition(g){return zn(this._values[g].transition)}setTransition(g,_){this._values.hasOwnProperty(g)||(this._values[g]=new I3(this._values[g].property)),this._values[g].transition=zn(_)||void 0}serialize(){const g={};for(const _ of Object.keys(this._values)){const C=this.getValue(_);C!==void 0&&(g[_]=C);const P=this.getTransition(_);P!==void 0&&(g[`${_}-transition`]=P)}return g}transitioned(g,_){const C=new IE(this._properties);for(const P of Object.keys(this._values))C._values[P]=this._values[P].transitioned(g,_._values[P]);return C}untransitioned(){const g=new IE(this._properties);for(const _ of Object.keys(this._values))g._values[_]=this._values[_].untransitioned();return g}isIndoorDependent(){return this._isIndoorDependent}}class GS{constructor(g,_,C,P,O){const B=P.delay||0,W=P.duration||0;O=O||0,this.property=g,this.value=_,this.begin=O+B,this.end=this.begin+W,g.specification.transition&&(P.delay||P.duration)&&(this.prior=C)}possiblyEvaluate(g,_,C){const P=g.now||0,O=this.value.possiblyEvaluate(g,_,C),B=this.prior;if(B){if(P>this.end)return this.prior=null,O;if(this.value.isDataDriven())return this.prior=null,O;if(P":1,">=":1,"<":1,"<=":1,"in":1,"!in":1,"all":1,"any":1,"none":1,"has":1,"!has":1}},"geometry_type":{"type":"enum","values":{"Point":1,"LineString":1,"Polygon":1}},"function":{"expression":{"type":"expression"},"stops":{"type":"array","value":"function_stop"},"base":{"type":"number","default":1,"minimum":0},"property":{"type":"string","default":"$zoom"},"type":{"type":"enum","values":{"identity":1,"exponential":1,"interval":1,"categorical":1},"default":"exponential"},"colorSpace":{"type":"enum","values":{"rgb":1,"lab":1,"hcl":1},"default":"rgb"},"default":{"type":"*"}},"function_stop":{"type":"array","minimum":0,"maximum":24,"value":["number","color"],"length":2},"expression":{"type":"array","value":"*","minimum":1},"fog":{"range":{"type":"array","default":[0.5,10],"minimum":-20,"maximum":20,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"high-color":{"type":"color","default":"#245cdf","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"space-color":{"type":"color","default":["interpolate",["linear"],["zoom"],4,"#010b19",7,"#367ab9"],"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"horizon-blend":{"type":"number","default":["interpolate",["linear"],["zoom"],4,0.2,7,0.1],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"star-intensity":{"type":"number","default":["interpolate",["linear"],["zoom"],5,0.35,6,0],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vertical-range":{"type":"array","default":[0,0],"minimum":0,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}}},"snow":{"density":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.85],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.3],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette-color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"center-thinning":{"type":"number","default":0.4,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"direction":{"type":"array","default":[0,50],"minimum":0,"maximum":360,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"flake-size":{"type":"number","default":0.71,"minimum":0,"maximum":5,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true}},"rain":{"density":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.5],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"color":{"type":"color","default":["interpolate",["linear"],["measure-light","brightness"],0,"#03113d",0.3,"#a8adbc"],"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"opacity":{"type":"number","default":["interpolate",["linear"],["measure-light","brightness"],0,0.88,1,0.7],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,1],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette-color":{"type":"color","default":["interpolate",["linear"],["measure-light","brightness"],0,"#001736",0.3,"#464646"],"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"center-thinning":{"type":"number","default":0.57,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"direction":{"type":"array","default":[0,80],"minimum":0,"maximum":360,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"droplet-size":{"type":"array","default":[2.6,18.2],"minimum":0,"maximum":50,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"distortion-strength":{"type":"number","default":0.7,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true}},"camera":{"camera-projection":{"type":"enum","values":{"perspective":1,"orthographic":1},"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"default":"perspective"}},"colorTheme":{"data":{"type":"string","expression":{}}},"indoor_source":{"sourceId":{"type":"string"},"sourceLayers":{"type":"array","value":"string"}},"indoor":{"*":{"type":"indoor_source"}},"light":{"anchor":{"type":"enum","default":"viewport","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"position":{"type":"array","default":[1.15,210,30],"length":3,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom"]},"use-theme":true,"transition":true},"intensity":{"type":"number","default":0.5,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true}},"projection":{"name":{"type":"enum","values":{"albers":1,"equalEarth":1,"equirectangular":1,"lambertConformalConic":1,"mercator":1,"naturalEarth":1,"winkelTripel":1,"globe":1},"default":"mercator"},"center":{"type":"array","length":2,"value":"number","minimum":[-180,-90],"maximum":[180,90]},"parallels":{"type":"array","length":2,"value":"number","minimum":[-90,-90],"maximum":[90,90]}},"terrain":{"source":{"type":"string"},"exaggeration":{"type":"number","default":1,"minimum":0,"maximum":1000,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true}},"paint":["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_building","paint_symbol","paint_raster","paint_raster-particle","paint_hillshade","paint_background","paint_sky","paint_model"],"paint_fill":{"fill-antialias":{"type":"boolean","default":true,"expression":{"parameters":["zoom"]}},"fill-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-outline-color":{"type":"color","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"fill-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"fill-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-z-offset":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"},"fill-bridge-guard-rail-color":{"type":"color","default":"rgba(241, 236, 225, 255)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature"]},"property-type":"data-driven"},"fill-tunnel-structure-color":{"type":"color","default":"rgba(241, 236, 225, 255)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature"]},"property-type":"data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-extrusion-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"fill-extrusion-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"fill-extrusion-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-extrusion-height":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-height-alignment":{"type":"enum","values":{"terrain":1,"flat":1},"default":"flat"},"fill-extrusion-base-alignment":{"type":"enum","values":{"terrain":1,"flat":1},"default":"terrain"},"fill-extrusion-vertical-gradient":{"type":"boolean","default":true,"expression":{"parameters":["zoom"]}},"fill-extrusion-ambient-occlusion-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-wall-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-ground-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-flood-light-color":{"type":"color","default":"#ffffff","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-extrusion-flood-light-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-extrusion-flood-light-wall-radius":{"property-type":"data-driven","type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["feature","feature-state"]}},"fill-extrusion-flood-light-ground-radius":{"property-type":"data-driven","type":"number","default":0,"transition":true,"expression":{"interpolated":true,"parameters":["feature","feature-state"]}},"fill-extrusion-flood-light-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-vertical-scale":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-rounded-roof":{"type":"boolean","default":true,"expression":{"parameters":["zoom"]}},"fill-extrusion-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{}},"fill-extrusion-front-cutoff":{"type":"array","value":"number","expression":{"interpolated":true,"parameters":["zoom"]},"length":3,"default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1]},"fill-extrusion-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature-state"]},"property-type":"data-driven"},"fill-extrusion-line-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-extrusion-cast-shadows":{"type":"boolean","default":true}},"paint_building":{"building-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"building-ambient-occlusion-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"parameters":[]},"transition":true},"building-ambient-occlusion-ground-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"building-ambient-occlusion-ground-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"building-ambient-occlusion-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"building-vertical-scale":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"building-cast-shadows":{"type":"boolean","default":true},"building-color":{"type":"color","default":"rgba(193, 154, 127, 1)","use-theme":true,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"property-type":"data-driven"},"building-emissive-strength":{"type":"number","default":0,"minimum":0,"maximum":5,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"property-type":"data-driven"},"building-facade-emissive-chance":{"type":"number","default":0.35,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["measure-light","zoom"]}},"building-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{}},"building-front-cutoff":{"type":"array","value":"number","expression":{"interpolated":true,"parameters":["zoom"]},"length":3,"default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1]},"building-flood-light-color":{"type":"color","default":"#ffffff","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"building-flood-light-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"building-flood-light-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_line":{"line-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"line-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"line-width":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light","line-progress"]},"property-type":"data-driven"},"line-gap-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-offset":{"type":"number","default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-blur":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-dasharray":{"type":"array","value":"number","minimum":0,"expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"line-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"line-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"line-gradient":{"type":"color","use-theme":true,"expression":{"interpolated":true,"parameters":["line-progress"]}},"line-trim-offset":{"type":"array","value":"number","length":2,"default":[0,0],"minimum":[0,0],"maximum":[1,1]},"line-trim-fade-range":{"type":"array","value":"number","length":2,"default":[0,0],"minimum":[0,0],"maximum":[1,1],"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"line-trim-color":{"type":"color","default":"transparent","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"line-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-driven"},"line-border-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-border-color":{"type":"color","default":"rgba(0, 0, 0, 0)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-occlusion-opacity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"line-blend-mode":{"type":"enum","values":{"default":1,"multiply":1,"additive":1},"default":"default","expression":{"parameters":["zoom"]}}},"paint_circle":{"circle-radius":{"type":"number","default":5,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-blur":{"type":"number","default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"circle-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"circle-pitch-scale":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"circle-pitch-alignment":{"type":"enum","values":{"map":1,"viewport":1},"default":"viewport","expression":{"parameters":["zoom"]}},"circle-stroke-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-stroke-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-stroke-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}}},"paint_heatmap":{"heatmap-radius":{"type":"number","default":30,"minimum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"heatmap-weight":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"heatmap-intensity":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"heatmap-color":{"type":"color","default":["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",0.1,"royalblue",0.3,"cyan",0.5,"lime",0.7,"yellow",1,"red"],"use-theme":true,"expression":{"interpolated":true,"parameters":["heatmap-density"]}},"heatmap-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_symbol":{"icon-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-occlusion-opacity":{"type":"number","minimum":0,"maximum":1,"default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-emissive-strength":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature-state"]},"appearance":true,"property-type":"data-driven"},"text-emissive-strength":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature-state"]},"appearance":true,"property-type":"data-driven"},"icon-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-halo-color":{"type":"color","default":"rgba(0, 0, 0, 0)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-halo-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-halo-blur":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"appearance":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"icon-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"icon-image-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"text-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-occlusion-opacity":{"type":"number","minimum":0,"maximum":1,"default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"overridable":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-halo-color":{"type":"color","default":"rgba(0, 0, 0, 0)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-halo-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-halo-blur":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"appearance":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"text-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"icon-color-saturation":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":{}},"icon-color-contrast":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":{}},"icon-color-brightness-min":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{}},"icon-color-brightness-max":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{}},"symbol-z-offset":{"type":"number","default":0,"minimum":0,"transition":true,"appearance":true,"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"}},"paint_raster":{"raster-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-color":{"type":"color","use-theme":true,"expression":{"interpolated":true,"parameters":["raster-value"]}},"raster-color-mix":{"type":"array","default":[0.2126,0.7152,0.0722,0],"length":4,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-color-range":{"type":"array","length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-hue-rotate":{"type":"number","default":0,"period":360,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-brightness-min":{"type":"number","default":0,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-brightness-max":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-saturation":{"type":"number","default":0,"minimum":-1,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-contrast":{"type":"number","default":0,"minimum":-1,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-resampling":{"type":"enum","values":{"linear":1,"nearest":1},"default":"linear","expression":{"parameters":["zoom"]}},"raster-fade-duration":{"type":"number","default":300,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"raster-array-band":{"type":"string"},"raster-elevation":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-elevation-reference":{"type":"enum","values":{"sea":1,"ground":1},"default":"sea","expression":{}}},"paint_raster-particle":{"raster-particle-array-band":{"type":"string"},"raster-particle-count":{"type":"number","default":512,"minimum":1},"raster-particle-color":{"type":"color","use-theme":true,"expression":{"interpolated":true,"parameters":["raster-particle-speed"]}},"raster-particle-max-speed":{"type":"number","default":1,"minimum":1},"raster-particle-speed-factor":{"type":"number","default":0.2,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-particle-fade-opacity-factor":{"type":"number","default":0.98,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-particle-reset-rate-factor":{"type":"number","default":0.8,"minimum":0,"maximum":1},"raster-particle-elevation":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_hillshade":{"hillshade-illumination-direction":{"type":"number","default":335,"minimum":0,"maximum":359,"expression":{"interpolated":true,"parameters":["zoom"]}},"hillshade-illumination-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"viewport","expression":{"parameters":["zoom"]}},"hillshade-exaggeration":{"type":"number","default":0.5,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"hillshade-shadow-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"hillshade-highlight-color":{"type":"color","default":"#FFFFFF","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"hillshade-accent-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"hillshade-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}}},"paint_background":{"background-pitch-alignment":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":[]}},"background-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"background-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom"]}},"background-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"background-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}}},"paint_sky":{"sky-type":{"type":"enum","values":{"gradient":1,"atmosphere":1},"default":"atmosphere","expression":{"parameters":["zoom"]}},"sky-atmosphere-sun":{"type":"array","value":"number","length":2,"minimum":[0,0],"maximum":[360,180],"expression":{"parameters":["zoom"]}},"sky-atmosphere-sun-intensity":{"type":"number","default":10,"minimum":0,"maximum":100},"sky-gradient-center":{"type":"array","value":"number","default":[0,0],"length":2,"minimum":[0,0],"maximum":[360,180],"expression":{"parameters":["zoom"]}},"sky-gradient-radius":{"type":"number","default":90,"minimum":0,"maximum":180,"expression":{"parameters":["zoom"]}},"sky-gradient":{"type":"color","default":["interpolate",["linear"],["sky-radial-progress"],0.8,"#87ceeb",1,"white"],"use-theme":true,"expression":{"interpolated":true,"parameters":["sky-radial-progress"]}},"sky-atmosphere-halo-color":{"type":"color","default":"white","use-theme":true},"sky-atmosphere-color":{"type":"color","default":"white","use-theme":true},"sky-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_model":{"model-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"property-type":"data-driven"},"model-rotation":{"type":"array","value":"number","length":3,"default":[0,0,0],"period":360,"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"transition":true},"model-scale":{"type":"array","value":"number","length":3,"default":[1,1,1],"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"transition":true},"model-translation":{"type":"array","value":"number","length":3,"default":[0,0,0],"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"transition":true},"model-color":{"type":"color","default":"#ffffff","property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light","zoom"]},"use-theme":true,"transition":true},"model-color-mix-intensity":{"type":"number","property-type":"data-driven","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"transition":true},"model-type":{"type":"enum","values":{"common-3d":1,"location-indicator":1},"default":"common-3d"},"model-cast-shadows":{"type":"boolean","default":true},"model-receive-shadows":{"type":"boolean","default":true},"model-ambient-occlusion-intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"model-emissive-strength":{"type":"number","property-type":"data-driven","default":0,"minimum":0,"maximum":5,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"transition":true},"model-roughness":{"type":"number","default":1,"minimum":0,"maximum":1,"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state"]},"transition":true},"model-height-based-emissive-strength-multiplier":{"type":"array","default":[1,1,1,1,0],"length":5,"value":"number","property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"transition":true},"model-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{}},"model-front-cutoff":{"type":"array","value":"number","expression":{"interpolated":true,"parameters":["zoom"]},"length":3,"default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1]},"model-elevation-reference":{"type":"enum","values":{"sea":1,"ground":1,"hd-road-markup":1},"default":"ground","expression":{}},"model-ignore-line-cutout":{"type":"boolean","default":false,"expression":{}}},"transition":{"duration":{"type":"number","default":300,"minimum":0},"delay":{"type":"number","default":0,"minimum":0}},"promoteId":{"*":{"type":"*"}}}');function R3(k){return k instanceof Number||k instanceof String||k instanceof Boolean?k.valueOf():k}function WS(k){if(Array.isArray(k))return k.map(WS);if(k instanceof Object&&!(k instanceof Number||k instanceof String||k instanceof Boolean)){const g={};for(const _ in k)g[_]=WS(k[_]);return g}return R3(k)}function D3(k){if(k===!0||k===!1)return!0;if(!Array.isArray(k)||k.length===0)return!1;switch(k[0]){case"has":return k.length>=2&&k[1]!=="$id"&&k[1]!=="$type";case"in":return k.length>=3&&(typeof k[1]!="string"||Array.isArray(k[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return k.length!==3||Array.isArray(k[1])||Array.isArray(k[2]);case"any":case"all":for(const g of k.slice(1))if(!D3(g)&&typeof g!="boolean")return!1;return!0;default:return!0}}function DE(k,g="",_=null,C="fill"){if(k==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};D3(k)||(k=FE(k));const P=k;let O=!0;try{O=function(pe){if(!$N(pe))return pe;let ve=WS(pe);return _L(ve),ve=bL(ve),ve}(P)}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(P,null,2)} `)}let B=null,W=null;if(C!=="background"&&C!=="sky"&&C!=="slot"){W=Us[`filter_${C}`];const pe=xd(O,W,g,_);if(pe.result==="error")throw new Error(pe.value.map(ve=>`${ve.key}: ${ve.message}`).join(", "));B=(ve,_e,Pe)=>pe.value.evaluate(ve,_e,{},Pe)}let Y=null,ae=null;if(O!==P){const pe=xd(P,W,g,_);if(pe.result==="error")throw new Error(pe.value.map(ve=>`${ve.key}: ${ve.message}`).join(", "));Y=(ve,_e,Pe,De,We)=>pe.value.evaluate(ve,_e,{},Pe,void 0,void 0,De,We),ae=!Db(pe.value.expression)}return{filter:B,dynamicFilter:Y||void 0,needGeometry:Y9(O),needFeature:!!ae}}function bL(k){if(!Array.isArray(k))return k;const g=function(_){if(wL.has(_[0])){for(let C=1;C<_.length;C++)if($N(_[C]))return!0}return _}(k);return g===!0?g:g.map(_=>bL(_))}function _L(k){let g=!1;const _=[];if(k[0]==="case"){for(let C=1;C",">=","<","<=","to-boolean"]);function OE(k,g){return kg?1:0}function Y9(k){if(!Array.isArray(k))return!1;if(k[0]==="within"||k[0]==="distance")return!0;for(let g=1;g"||g==="<="||g===">="?ee(k[1],k[2],g):g==="any"?(_=k.slice(1),["any"].concat(_.map(FE))):g==="all"?["all"].concat(k.slice(1).map(FE)):g==="none"?["all"].concat(k.slice(1).map(FE).map(nt)):g==="in"?oe(k[1],k.slice(2)):g==="!in"?nt(oe(k[1],k.slice(2))):g==="has"?Re(k[1]):g!=="!has"||nt(Re(k[1]));var _}function ee(k,g,_){switch(k){case"$type":return[`filter-type-${_}`,g];case"$id":return[`filter-id-${_}`,g];default:return[`filter-${_}`,k,g]}}function oe(k,g){if(g.length===0)return!1;switch(k){case"$type":return["filter-type-in",["literal",g]];case"$id":return["filter-id-in",["literal",g]];default:return g.length>200&&!g.some(_=>typeof _!=typeof g[0])?["filter-in-large",k,["literal",g.sort(OE)]]:["filter-in-small",k,["literal",g]]}}function Re(k){switch(k){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",k]}}function nt(k){return["!",k]}const lt="";function At(k,g){return g?`${k}${lt}${g}`:k}function Os(k){const g=k.indexOf(lt);return g>=0?k.slice(g+1):""}let Yn;const Ir=()=>Yn||(Yn=new Wc({"icon-size":new or(Us.layout_symbol["icon-size"]),"icon-image":new or(Us.layout_symbol["icon-image"]),"icon-rotate":new or(Us.layout_symbol["icon-rotate"]),"icon-offset":new or(Us.layout_symbol["icon-offset"]),"text-size":new or(Us.layout_symbol["text-size"]),"text-rotate":new or(Us.layout_symbol["text-rotate"]),"text-offset":new or(Us.layout_symbol["text-offset"])}));let za;const Zi=()=>za||(za=new Wc({"icon-opacity":new or(Us.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new or(Us.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new or(Us.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new or(Us.paint_symbol["text-emissive-strength"]),"icon-color":new or(Us.paint_symbol["icon-color"]),"icon-halo-color":new or(Us.paint_symbol["icon-halo-color"]),"icon-halo-width":new or(Us.paint_symbol["icon-halo-width"]),"icon-halo-blur":new or(Us.paint_symbol["icon-halo-blur"]),"icon-translate":new or(Us.paint_symbol["icon-translate"]),"text-opacity":new or(Us.paint_symbol["text-opacity"]),"text-occlusion-opacity":new or(Us.paint_symbol["text-occlusion-opacity"]),"text-color":new or(Us.paint_symbol["text-color"],{runtimeType:ol,getOverride:k=>k.textColor,hasOverride:k=>!!k.textColor}),"text-halo-color":new or(Us.paint_symbol["text-halo-color"]),"text-halo-width":new or(Us.paint_symbol["text-halo-width"]),"text-halo-blur":new or(Us.paint_symbol["text-halo-blur"]),"text-translate":new or(Us.paint_symbol["text-translate"]),"symbol-z-offset":new or(Us.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new or({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new or({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new or({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new or({type:"string",default:"default","property-type":"data-driven"})}));class Gl{constructor(g,_,C,P,O,B){this._conditionSpec=g,this._propertiesSpec=C;const W=xd(g,Us.appearance.condition);if(W.result==="success"&&(this.condition=W.value),this.name=_,C){this.layoutProperties=new _p(Ir()),this.unevaluatedLayout=new RE(Ir(),P,O,B),this.paintProperties=new _p(Zi()),this.unevaluatedPaint=new RE(Zi(),P,O,"");for(const Y in C)Y in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(Y,C[Y]):Y in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(Y,C[Y])}}isActive(g){return!(this.condition||!g.isHidden||this.name!=="hidden")||this.condition.evaluate(g.globals,g.feature,g.featureState,g.canonical)}getCondition(){return this.condition}getName(){return this.name}getLayoutProperty(g){return this.layoutProperties.get(g)}getPaintProperty(g){return this.paintProperties.get(g)}getUnevaluatedLayoutProperties(){return this.unevaluatedLayout}getUnevaluatedLayoutProperty(g){return this.unevaluatedLayout._values[g]}getUnevaluatedPaintProperty(g){return this.unevaluatedPaint._values[g]}recalculate(g,_,C){this.unevaluatedLayout&&(this.layoutProperties=this.unevaluatedLayout.possiblyEvaluate(g,void 0,_,C)),this.unevaluatedPaint&&(this.paintProperties=this.unevaluatedPaint.possiblyEvaluate(g,void 0,_,""))}serialize(){const g={};g.condition=this.condition.expression.serialize(),this.name&&(g.name=this.name);const _=this.unevaluatedLayout?this.unevaluatedLayout.serialize():{},C=this.unevaluatedPaint?this.unevaluatedPaint.serialize():{},P=Object.assign({},_,C);return Object.keys(P).length>0&&(g.properties=P),g}hasIconLayoutProperties(){const g=this.hasLayoutProperty("icon-image"),_=this.hasLayoutProperty("icon-size"),C=this.hasLayoutProperty("icon-offset"),P=this.hasLayoutProperty("icon-rotate");return g||_||C||P}hasTextLayoutProperties(){const g=this.hasLayoutProperty("text-size"),_=this.hasLayoutProperty("text-offset"),C=this.hasLayoutProperty("text-rotate");return g||_||C}hasIconPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(g=>!g.endsWith("-use-theme")).some(g=>(g.startsWith("icon-")||g==="symbol-z-offset")&&this.hasPaintProperty(g))}hasTextPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(g=>!g.endsWith("-use-theme")).some(g=>(g.startsWith("text-")||g==="symbol-z-offset")&&this.hasPaintProperty(g))}hasLayoutProperty(g){return this.unevaluatedLayout&&this.unevaluatedLayout._values[g].value!==void 0}hasPaintProperty(g){return this.unevaluatedPaint&&this.unevaluatedPaint._values[g].value!==void 0}}const Ei="-transition",fh=new Set(["fill","line","background","hillshade","raster"]);class Wl extends qm{constructor(g,_,C,P,O,B){if(super(),this.id=g.id,this.fqid=At(this.id,C),this.type=g.type,this.scope=C,this.lut=P,this.options=O,this.iconImageUseTheme=B,this.appearances=new Array,this.appearancesVersion=0,this._featureFilter={filter:()=>!0,needGeometry:!1,needFeature:!1},this._filterCompiled=!1,this.expressionDependencies={isIndoorDependent:!1,configDependencies:new Set},g.type!=="custom"){if(this.metadata=g.metadata,this.minzoom=g.minzoom,this.maxzoom=g.maxzoom,g.type&&g.type!=="background"&&g.type!=="sky"&&g.type!=="slot"){this.source=g.source,this.sourceLayer=g["source-layer"],this.filter=g.filter;const W=xd(this.filter,Us[`filter_${g.type}`]);W.result!=="error"&&(this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...W.value.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||W.value.isIndoorDependent)}if(g.slot&&(this.slot=g.slot),g.appearances&&this.setAppearances(g.appearances),_.layout&&(this._unevaluatedLayout=new RE(_.layout,this.scope,O,this.iconImageUseTheme),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...this._unevaluatedLayout.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||this._unevaluatedLayout.isIndoorDependent()),_.paint){this._transitionablePaint=new LE(_.paint,this.scope,O);for(const W in g.paint)this.setPaintProperty(W,g.paint[W]);for(const W in g.layout)this.setLayoutProperty(W,g.layout[W]);this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...this._transitionablePaint.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||this._transitionablePaint.isIndoorDependent(),this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new _p(_.paint)}}}onAdd(g){}onRemove(g){}isDraped(g){return!this.is3D(!0)&&fh.has(this.type)}getLayoutProperty(g){return g==="visibility"?this.visibility:this._unevaluatedLayout.getValue(g)}setLayoutProperty(g,_){if(this.type==="custom"&&g==="visibility")return void(this.visibility=_);const C=this._unevaluatedLayout;C._properties.properties[g]&&(C.setValue(g,_),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...C.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||C.isIndoorDependent(),g==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(g){this.appearances=[],g.forEach(_=>{this.appearances.push(new Gl(_.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(g){return g.endsWith(Ei)?this._transitionablePaint.getTransition(g.slice(0,-11)):this._transitionablePaint.getValue(g)}isPaintProperty(g){return!!this._transitionablePaint._properties.properties[g]}setPaintProperty(g,_){const C=this._transitionablePaint,P=C._properties.properties;if(g.endsWith(Ei)){const ve=g.slice(0,-11);return P[ve]&&C.setTransition(ve,_||void 0),!1}if(!P[g])return!1;const O=C._values[g],B=O.value.isDataDriven(),W=O.value;C.setValue(g,_),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...C.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||C.isIndoorDependent(),this._handleSpecialPaintPropertyUpdate(g);const Y=C._values[g].value,ae=Y.isDataDriven(),pe=g.endsWith("pattern")||g==="line-dasharray";return ae||B||pe||this._handleOverridablePaintPropertyUpdate(g,W,Y)}_handleSpecialPaintPropertyUpdate(g){}getProgramIds(){return null}getDefaultProgramParams(g,_,C){return null}_handleOverridablePaintPropertyUpdate(g,_,C){return!1}isHidden(g){return!!(this.minzoom&&g=this.maxzoom)||this.visibility==="none"}updateTransitions(g){this._transitioningPaint=this._transitionablePaint.transitioned(g,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(g,_){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(g,void 0,_,this.iconImageUseTheme)),this.paint=this._transitioningPaint.possiblyEvaluate(g,void 0,_)}serialize(){const g={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&&(g.appearances=this.appearances.map(_=>_.serialize())),Rs(g,(_,C)=>!(_===void 0||C==="layout"&&!Object.keys(_).length||C==="paint"&&!Object.keys(_).length))}is3D(g){return!1}hasElevation(){return!1}isSky(){return!1}isTileClipped(){return!1}hasOffscreenPass(){return!1}hasShadowPass(){return!1}canCastShadows(){return!1}hasLightBeamPass(){return!1}cutoffRange(){return 0}tileCoverLift(){return 0}resize(){}_clear(){}isStateDependent(){for(const g in this.paint._values){const _=this.paint.get(g);if(_ instanceof qN&&ul(_.property.specification)&&(_.value.kind==="source"||_.value.kind==="composite")&&_.value.isStateDependent)return!0}for(const g of this.appearances)if(!bg(g.condition.expression))return!0;return!1}compileFilter(g){this._filterCompiled||(this._featureFilter=DE(this.filter,this.scope,g),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(g){this._stats&&(g.renderPass==="shadow"?this._stats.numRenderedVerticesInShadowPass=0:this._stats.numRenderedVerticesInTransparentPass=0)}getAppearances(){return this.appearances}queryRenderedFeatures(g,_,C){return{}}queryRadius(g){}queryIntersectsFeature(g,_,C,P,O,B,W,Y,ae,pe){}}const wg={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Ry{constructor(g,_){this._structArray=g,this._pos1=_*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}const Er=new ArrayBuffer(0);class Cn{constructor(){this._reallocCount=0,this.capacity=0,this.length=0}static serialize(g,_){return g._trim(),_&&g.arrayBuffer&&_.add(g.arrayBuffer),{length:g.length,arrayBuffer:g.arrayBuffer}}static deserialize(g){const _=Object.create(this.prototype);return _.arrayBuffer=g.arrayBuffer,_.length=g.length,g.arrayBuffer?_.capacity=g.arrayBuffer.byteLength/_.bytesPerElement:(_.capacity=0,_.arrayBuffer=Er),_._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(g){this.reserve(g),this.length=g}reserve(g){if(g>this.capacity){this._reallocCount++,this.capacity=Math.max(g,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const _=this.uint8;this._refreshViews(),_&&this.uint8.set(_)}}reserveForAdditional(g){this.reserve(this.length+g)}_refreshViews(){throw new Error("StructArray#_refreshViews() must be implemented by each concrete StructArray layout")}emplace(...g){throw new Error("StructArray#emplace() must be implemented by each concrete StructArray layout")}emplaceBack(...g){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 $n(k,g=1){let _=0,C=0;return{members:k.map(P=>{const O=wg[P.type].BYTES_PER_ELEMENT,B=_=Fi(_,Math.max(g,O)),W=P.components||1;return C=Math.max(C,O),_+=O*W,{name:P.name,type:P.type,components:W,offset:B}}),size:Fi(_,Math.max(C,g)),alignment:g}}function Fi(k,g){return Math.ceil(k/g)*g}class Qi extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(g,_){const C=this.length;return this.resize(C+1),this.emplace(C,g,_)}emplace(g,_,C){const P=2*g;return this.int16[P+0]=_,this.int16[P+1]=C,g}}Qi.prototype.bytesPerElement=4,wr(Qi,"StructArrayLayout2i4");class cl extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(g,_,C){const P=this.length;return this.resize(P+1),this.emplace(P,g,_,C)}emplace(g,_,C,P){const O=3*g;return this.int16[O+0]=_,this.int16[O+1]=C,this.int16[O+2]=P,g}}cl.prototype.bytesPerElement=6,wr(cl,"StructArrayLayout3i6");class ho extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(g,_,C,P){const O=this.length;return this.resize(O+1),this.emplace(O,g,_,C,P)}emplace(g,_,C,P,O){const B=4*g;return this.int16[B+0]=_,this.int16[B+1]=C,this.uint16[B+2]=P,this.uint16[B+3]=O,g}}ho.prototype.bytesPerElement=8,wr(ho,"StructArrayLayout2i2ui8");class Bl extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(g){const _=this.length;return this.resize(_+1),this.emplace(_,g)}emplace(g,_){return this.float32[1*g+0]=_,g}}Bl.prototype.bytesPerElement=4,wr(Bl,"StructArrayLayout1f4");class wp extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(g,_,C){const P=this.length;return this.resize(P+1),this.emplace(P,g,_,C)}emplace(g,_,C,P){const O=4*g,B=2*g;return this.int16[O+0]=_,this.int16[O+1]=C,this.float32[B+1]=P,g}}wp.prototype.bytesPerElement=8,wr(wp,"StructArrayLayout2i1f8");class dd extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(g,_,C){const P=this.length;return this.resize(P+1),this.emplace(P,g,_,C)}emplace(g,_,C,P){const O=4*g;return this.int16[O+0]=_,this.int16[O+1]=C,this.int16[O+2]=P,g}}dd.prototype.bytesPerElement=8,wr(dd,"StructArrayLayout3i8");class qb extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(g,_,C,P){const O=this.length;return this.resize(O+1),this.emplace(O,g,_,C,P)}emplace(g,_,C,P,O){const B=4*g;return this.int16[B+0]=_,this.int16[B+1]=C,this.int16[B+2]=P,this.int16[B+3]=O,g}}qb.prototype.bytesPerElement=8,wr(qb,"StructArrayLayout4i8");class jL extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(g,_,C,P,O){const B=this.length;return this.resize(B+1),this.emplace(B,g,_,C,P,O)}emplace(g,_,C,P,O,B){const W=5*g;return this.int16[W+0]=_,this.int16[W+1]=C,this.int16[W+2]=P,this.int16[W+3]=O,this.int16[W+4]=B,g}}jL.prototype.bytesPerElement=10,wr(jL,"StructArrayLayout5i10");class NL extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(g,_,C,P,O,B,W){const Y=this.length;return this.resize(Y+1),this.emplace(Y,g,_,C,P,O,B,W)}emplace(g,_,C,P,O,B,W,Y){const ae=6*g,pe=12*g,ve=3*g;return this.int16[ae+0]=_,this.int16[ae+1]=C,this.uint8[pe+4]=P,this.uint8[pe+5]=O,this.uint8[pe+6]=B,this.uint8[pe+7]=W,this.float32[ve+2]=Y,g}}NL.prototype.bytesPerElement=12,wr(NL,"StructArrayLayout2i4ub1f12");class $b extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(g,_,C){const P=this.length;return this.resize(P+1),this.emplace(P,g,_,C)}emplace(g,_,C,P){const O=3*g;return this.float32[O+0]=_,this.float32[O+1]=C,this.float32[O+2]=P,g}}$b.prototype.bytesPerElement=12,wr($b,"StructArrayLayout3f12");class Gj extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(g,_,C,P,O){const B=this.length;return this.resize(B+1),this.emplace(B,g,_,C,P,O)}emplace(g,_,C,P,O,B){const W=6*g,Y=3*g;return this.uint16[W+0]=_,this.uint16[W+1]=C,this.uint16[W+2]=P,this.uint16[W+3]=O,this.float32[Y+2]=B,g}}Gj.prototype.bytesPerElement=12,wr(Gj,"StructArrayLayout4ui1f12");class zE extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(g,_,C,P){const O=this.length;return this.resize(O+1),this.emplace(O,g,_,C,P)}emplace(g,_,C,P,O){const B=4*g;return this.uint16[B+0]=_,this.uint16[B+1]=C,this.uint16[B+2]=P,this.uint16[B+3]=O,g}}zE.prototype.bytesPerElement=8,wr(zE,"StructArrayLayout4ui8");class Z9 extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(g,_,C,P,O,B){const W=this.length;return this.resize(W+1),this.emplace(W,g,_,C,P,O,B)}emplace(g,_,C,P,O,B,W){const Y=6*g;return this.int16[Y+0]=_,this.int16[Y+1]=C,this.int16[Y+2]=P,this.int16[Y+3]=O,this.int16[Y+4]=B,this.int16[Y+5]=W,g}}Z9.prototype.bytesPerElement=12,wr(Z9,"StructArrayLayout6i12");class EW extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(g,_,C,P,O,B,W,Y,ae,pe,ve,_e){const Pe=this.length;return this.resize(Pe+1),this.emplace(Pe,g,_,C,P,O,B,W,Y,ae,pe,ve,_e)}emplace(g,_,C,P,O,B,W,Y,ae,pe,ve,_e,Pe){const De=12*g;return this.int16[De+0]=_,this.int16[De+1]=C,this.int16[De+2]=P,this.int16[De+3]=O,this.uint16[De+4]=B,this.uint16[De+5]=W,this.uint16[De+6]=Y,this.uint16[De+7]=ae,this.int16[De+8]=pe,this.int16[De+9]=ve,this.int16[De+10]=_e,this.int16[De+11]=Pe,g}}EW.prototype.bytesPerElement=24,wr(EW,"StructArrayLayout4i4ui4i24");class TW extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(g,_,C,P,O,B){const W=this.length;return this.resize(W+1),this.emplace(W,g,_,C,P,O,B)}emplace(g,_,C,P,O,B,W){const Y=10*g,ae=5*g;return this.int16[Y+0]=_,this.int16[Y+1]=C,this.int16[Y+2]=P,this.float32[ae+2]=O,this.float32[ae+3]=B,this.float32[ae+4]=W,g}}TW.prototype.bytesPerElement=20,wr(TW,"StructArrayLayout3i3f20");class VN extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(g,_,C,P){const O=this.length;return this.resize(O+1),this.emplace(O,g,_,C,P)}emplace(g,_,C,P,O){const B=4*g;return this.float32[B+0]=_,this.float32[B+1]=C,this.float32[B+2]=P,this.float32[B+3]=O,g}}VN.prototype.bytesPerElement=16,wr(VN,"StructArrayLayout4f16");class kL extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(g){const _=this.length;return this.resize(_+1),this.emplace(_,g)}emplace(g,_){return this.uint32[1*g+0]=_,g}}kL.prototype.bytesPerElement=4,wr(kL,"StructArrayLayout1ul4");class Vb extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(g,_){const C=this.length;return this.resize(C+1),this.emplace(C,g,_)}emplace(g,_,C){const P=2*g;return this.uint16[P+0]=_,this.uint16[P+1]=C,g}}Vb.prototype.bytesPerElement=4,wr(Vb,"StructArrayLayout2ui4");class X9 extends Cn{_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(g,_,C,P,O,B,W,Y,ae,pe,ve,_e,Pe){const De=this.length;return this.resize(De+1),this.emplace(De,g,_,C,P,O,B,W,Y,ae,pe,ve,_e,Pe)}emplace(g,_,C,P,O,B,W,Y,ae,pe,ve,_e,Pe,De){const We=20*g,Je=10*g;return this.int16[We+0]=_,this.int16[We+1]=C,this.int16[We+2]=P,this.int16[We+3]=O,this.int16[We+4]=B,this.float32[Je+3]=W,this.float32[Je+4]=Y,this.float32[Je+5]=ae,this.float32[Je+6]=pe,this.int16[We+14]=ve,this.uint32[Je+8]=_e,this.uint16[We+18]=Pe,this.uint16[We+19]=De,g}}X9.prototype.bytesPerElement=40,wr(X9,"StructArrayLayout5i4f1i1ul2ui40");class SL extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(g,_,C,P,O,B,W){const Y=this.length;return this.resize(Y+1),this.emplace(Y,g,_,C,P,O,B,W)}emplace(g,_,C,P,O,B,W,Y){const ae=8*g;return this.int16[ae+0]=_,this.int16[ae+1]=C,this.int16[ae+2]=P,this.int16[ae+4]=O,this.int16[ae+5]=B,this.int16[ae+6]=W,this.int16[ae+7]=Y,g}}SL.prototype.bytesPerElement=16,wr(SL,"StructArrayLayout3i2i2i16");class MW extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(g,_,C,P,O){const B=this.length;return this.resize(B+1),this.emplace(B,g,_,C,P,O)}emplace(g,_,C,P,O,B){const W=4*g,Y=8*g;return this.float32[W+0]=_,this.float32[W+1]=C,this.float32[W+2]=P,this.int16[Y+6]=O,this.int16[Y+7]=B,g}}MW.prototype.bytesPerElement=16,wr(MW,"StructArrayLayout2f1f2i16");class CL extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(g,_,C,P,O,B){const W=this.length;return this.resize(W+1),this.emplace(W,g,_,C,P,O,B)}emplace(g,_,C,P,O,B,W){const Y=20*g,ae=5*g;return this.uint8[Y+0]=_,this.uint8[Y+1]=C,this.float32[ae+1]=P,this.float32[ae+2]=O,this.float32[ae+3]=B,this.float32[ae+4]=W,g}}CL.prototype.bytesPerElement=20,wr(CL,"StructArrayLayout2ub4f20");class Ru extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(g,_,C){const P=this.length;return this.resize(P+1),this.emplace(P,g,_,C)}emplace(g,_,C,P){const O=3*g;return this.uint16[O+0]=_,this.uint16[O+1]=C,this.uint16[O+2]=P,g}}Ru.prototype.bytesPerElement=6,wr(Ru,"StructArrayLayout3ui6");class Q9 extends Cn{_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(g,_,C,P,O,B,W,Y,ae,pe,ve,_e,Pe,De,We,Je,rt,xt,ut,St,Rt){const Ft=this.length;return this.resize(Ft+1),this.emplace(Ft,g,_,C,P,O,B,W,Y,ae,pe,ve,_e,Pe,De,We,Je,rt,xt,ut,St,Rt)}emplace(g,_,C,P,O,B,W,Y,ae,pe,ve,_e,Pe,De,We,Je,rt,xt,ut,St,Rt,Ft){const bs=30*g,as=15*g,ys=60*g;return this.int16[bs+0]=_,this.int16[bs+1]=C,this.int16[bs+2]=P,this.float32[as+2]=O,this.float32[as+3]=B,this.uint16[bs+8]=W,this.uint16[bs+9]=Y,this.uint32[as+5]=ae,this.uint32[as+6]=pe,this.uint32[as+7]=ve,this.uint16[bs+16]=_e,this.uint16[bs+17]=Pe,this.uint16[bs+18]=De,this.float32[as+10]=We,this.float32[as+11]=Je,this.uint8[ys+48]=rt,this.uint8[ys+49]=xt,this.uint8[ys+50]=ut,this.uint32[as+13]=St,this.int16[bs+28]=Rt,this.uint8[ys+58]=Ft,g}}Q9.prototype.bytesPerElement=60,wr(Q9,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class PW extends Cn{_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(g,_,C,P,O,B,W,Y,ae,pe,ve,_e,Pe,De,We,Je,rt,xt,ut,St,Rt,Ft,bs,as,ys,hs,ms,vn,Nn,Tn,Ln,Mn,Qn){const fn=this.length;return this.resize(fn+1),this.emplace(fn,g,_,C,P,O,B,W,Y,ae,pe,ve,_e,Pe,De,We,Je,rt,xt,ut,St,Rt,Ft,bs,as,ys,hs,ms,vn,Nn,Tn,Ln,Mn,Qn)}emplace(g,_,C,P,O,B,W,Y,ae,pe,ve,_e,Pe,De,We,Je,rt,xt,ut,St,Rt,Ft,bs,as,ys,hs,ms,vn,Nn,Tn,Ln,Mn,Qn,fn){const Pn=20*g,Dn=40*g,tr=80*g;return this.float32[Pn+0]=_,this.float32[Pn+1]=C,this.int16[Dn+4]=P,this.int16[Dn+5]=O,this.int16[Dn+6]=B,this.int16[Dn+7]=W,this.int16[Dn+8]=Y,this.int16[Dn+9]=ae,this.int16[Dn+10]=pe,this.int16[Dn+11]=ve,this.int16[Dn+12]=_e,this.uint16[Dn+13]=Pe,this.uint16[Dn+14]=De,this.uint16[Dn+15]=We,this.uint16[Dn+16]=Je,this.uint16[Dn+17]=rt,this.uint16[Dn+18]=xt,this.uint16[Dn+19]=ut,this.uint16[Dn+20]=St,this.uint16[Dn+21]=Rt,this.uint16[Dn+22]=Ft,this.uint16[Dn+23]=bs,this.uint16[Dn+24]=as,this.uint16[Dn+25]=ys,this.uint16[Dn+26]=hs,this.uint16[Dn+27]=ms,this.uint32[Pn+14]=vn,this.float32[Pn+15]=Nn,this.float32[Pn+16]=Tn,this.float32[Pn+17]=Ln,this.float32[Pn+18]=Mn,this.uint8[tr+76]=Qn,this.uint16[Dn+39]=fn,g}}PW.prototype.bytesPerElement=80,wr(PW,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class J9 extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(g,_,C,P,O,B){const W=this.length;return this.resize(W+1),this.emplace(W,g,_,C,P,O,B)}emplace(g,_,C,P,O,B,W){const Y=6*g;return this.float32[Y+0]=_,this.float32[Y+1]=C,this.float32[Y+2]=P,this.float32[Y+3]=O,this.float32[Y+4]=B,this.float32[Y+5]=W,g}}J9.prototype.bytesPerElement=24,wr(J9,"StructArrayLayout6f24");class O3 extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(g,_,C,P,O){const B=this.length;return this.resize(B+1),this.emplace(B,g,_,C,P,O)}emplace(g,_,C,P,O,B){const W=5*g;return this.float32[W+0]=_,this.float32[W+1]=C,this.float32[W+2]=P,this.float32[W+3]=O,this.float32[W+4]=B,g}}O3.prototype.bytesPerElement=20,wr(O3,"StructArrayLayout5f20");class AL extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(g,_,C,P,O,B,W){const Y=this.length;return this.resize(Y+1),this.emplace(Y,g,_,C,P,O,B,W)}emplace(g,_,C,P,O,B,W,Y){const ae=7*g;return this.float32[ae+0]=_,this.float32[ae+1]=C,this.float32[ae+2]=P,this.float32[ae+3]=O,this.float32[ae+4]=B,this.float32[ae+5]=W,this.float32[ae+6]=Y,g}}AL.prototype.bytesPerElement=28,wr(AL,"StructArrayLayout7f28");class LW extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(g,_,C,P,O,B,W,Y,ae,pe,ve){const _e=this.length;return this.resize(_e+1),this.emplace(_e,g,_,C,P,O,B,W,Y,ae,pe,ve)}emplace(g,_,C,P,O,B,W,Y,ae,pe,ve,_e){const Pe=11*g;return this.float32[Pe+0]=_,this.float32[Pe+1]=C,this.float32[Pe+2]=P,this.float32[Pe+3]=O,this.float32[Pe+4]=B,this.float32[Pe+5]=W,this.float32[Pe+6]=Y,this.float32[Pe+7]=ae,this.float32[Pe+8]=pe,this.float32[Pe+9]=ve,this.float32[Pe+10]=_e,g}}LW.prototype.bytesPerElement=44,wr(LW,"StructArrayLayout11f44");class IW extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(g,_,C,P,O,B,W,Y,ae){const pe=this.length;return this.resize(pe+1),this.emplace(pe,g,_,C,P,O,B,W,Y,ae)}emplace(g,_,C,P,O,B,W,Y,ae,pe){const ve=9*g;return this.float32[ve+0]=_,this.float32[ve+1]=C,this.float32[ve+2]=P,this.float32[ve+3]=O,this.float32[ve+4]=B,this.float32[ve+5]=W,this.float32[ve+6]=Y,this.float32[ve+7]=ae,this.float32[ve+8]=pe,g}}IW.prototype.bytesPerElement=36,wr(IW,"StructArrayLayout9f36");class F3 extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(g,_){const C=this.length;return this.resize(C+1),this.emplace(C,g,_)}emplace(g,_,C){const P=2*g;return this.float32[P+0]=_,this.float32[P+1]=C,g}}F3.prototype.bytesPerElement=8,wr(F3,"StructArrayLayout2f8");class RW extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(g,_,C,P){const O=this.length;return this.resize(O+1),this.emplace(O,g,_,C,P)}emplace(g,_,C,P,O){const B=6*g;return this.uint32[3*g+0]=_,this.uint16[B+2]=C,this.uint16[B+3]=P,this.uint16[B+4]=O,g}}RW.prototype.bytesPerElement=12,wr(RW,"StructArrayLayout1ul3ui12");class z3 extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(g){const _=this.length;return this.resize(_+1),this.emplace(_,g)}emplace(g,_){return this.uint16[1*g+0]=_,g}}z3.prototype.bytesPerElement=2,wr(z3,"StructArrayLayout1ui2");class DW extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(g,_,C,P,O,B,W,Y,ae,pe,ve,_e,Pe,De,We,Je){const rt=this.length;return this.resize(rt+1),this.emplace(rt,g,_,C,P,O,B,W,Y,ae,pe,ve,_e,Pe,De,We,Je)}emplace(g,_,C,P,O,B,W,Y,ae,pe,ve,_e,Pe,De,We,Je,rt){const xt=16*g;return this.float32[xt+0]=_,this.float32[xt+1]=C,this.float32[xt+2]=P,this.float32[xt+3]=O,this.float32[xt+4]=B,this.float32[xt+5]=W,this.float32[xt+6]=Y,this.float32[xt+7]=ae,this.float32[xt+8]=pe,this.float32[xt+9]=ve,this.float32[xt+10]=_e,this.float32[xt+11]=Pe,this.float32[xt+12]=De,this.float32[xt+13]=We,this.float32[xt+14]=Je,this.float32[xt+15]=rt,g}}DW.prototype.bytesPerElement=64,wr(DW,"StructArrayLayout16f64");class ez extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(g,_,C,P,O,B,W){const Y=this.length;return this.resize(Y+1),this.emplace(Y,g,_,C,P,O,B,W)}emplace(g,_,C,P,O,B,W,Y){const ae=10*g,pe=5*g;return this.uint16[ae+0]=_,this.uint16[ae+1]=C,this.uint16[ae+2]=P,this.uint16[ae+3]=O,this.float32[pe+2]=B,this.float32[pe+3]=W,this.float32[pe+4]=Y,g}}ez.prototype.bytesPerElement=20,wr(ez,"StructArrayLayout4ui3f20");class tz extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(g){const _=this.length;return this.resize(_+1),this.emplace(_,g)}emplace(g,_){return this.int16[1*g+0]=_,g}}tz.prototype.bytesPerElement=2,wr(tz,"StructArrayLayout1i2");class sz extends Cn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer)}emplaceBack(g){const _=this.length;return this.resize(_+1),this.emplace(_,g)}emplace(g,_){return this.uint8[1*g+0]=_,g}}sz.prototype.bytesPerElement=1,wr(sz,"StructArrayLayout1ub1");class yae extends Ry{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]}}yae.prototype.size=40;class OW extends X9{get(g){return new yae(this,g)}}wr(OW,"CollisionBoxArray");class vae extends Ry{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(g){this._structArray.uint8[this._pos1+49]=g}get hidden(){return this._structArray.uint8[this._pos1+50]}set hidden(g){this._structArray.uint8[this._pos1+50]=g}get crossTileID(){return this._structArray.uint32[this._pos4+13]}set crossTileID(g){this._structArray.uint32[this._pos4+13]=g}get associatedIconIndex(){return this._structArray.int16[this._pos2+28]}get flipState(){return this._structArray.uint8[this._pos1+58]}set flipState(g){this._structArray.uint8[this._pos1+58]=g}}vae.prototype.size=60;class bae extends Q9{get(g){return new vae(this,g)}}wr(bae,"PlacedSymbolArray");class EL extends Ry{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(g){this._structArray.uint32[this._pos4+14]=g}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(g){this._structArray.float32[this._pos4+18]=g}get hasIconTextFit(){return this._structArray.uint8[this._pos1+76]}get elevationFeatureIndex(){return this._structArray.uint16[this._pos2+39]}}EL.prototype.size=80;class _ae extends PW{get(g){return new EL(this,g)}}wr(_ae,"SymbolInstanceArray");class wae extends Bl{getoffsetX(g){return this.float32[1*g+0]}}wr(wae,"GlyphOffsetArray");class TL extends Qi{getx(g){return this.int16[2*g+0]}gety(g){return this.int16[2*g+1]}}wr(TL,"SymbolLineVertexArray");class jae extends Ry{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]}}jae.prototype.size=12;class FW extends RW{get(g){return new jae(this,g)}}wr(FW,"FeatureIndexArray");class Nae extends Vb{geta_centroid_pos0(g){return this.uint16[2*g+0]}geta_centroid_pos1(g){return this.uint16[2*g+1]}}wr(Nae,"FillExtrusionCentroidArray");class zW extends Ry{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]}}zW.prototype.size=6;class BW extends cl{get(g){return new zW(this,g)}}wr(BW,"FillExtrusionWallArray");const kae=$n([{name:"a_pos",components:2,type:"Int16"}],4),m8e=$n([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),p8e=$n([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class Ec{constructor(g=[]){this.segments=g}_prepareSegment(g,_,C,P,O){let B=this.segments[this.segments.length-1];return g>Ec.MAX_VERTEX_ARRAY_LENGTH&&qr(`Max vertices per segment is ${Ec.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${g}`),(!B||B.vertexLength+g>Ec.MAX_VERTEX_ARRAY_LENGTH||B.sortKey!==P||O!==void 0&&B&&B.batchIndex!==void 0&&B.batchIndex!==O)&&(B={vertexOffset:_,primitiveOffset:C,vertexLength:0,primitiveLength:0},P!==void 0&&(B.sortKey=P),O!==void 0&&(B.batchIndex=O),this.segments.push(B)),B}prepareSegment(g,_,C,P,O){return this._prepareSegment(g,_.length,C.length,P,O)}get(){return this.segments}destroy(){for(const g of this.segments)for(const _ in g.vaos)g.vaos[_].destroy()}static simpleSegment(g,_,C,P){return new Ec([{vertexOffset:g,primitiveOffset:_,vertexLength:C,primitiveLength:P,vaos:{},sortKey:0}])}}function nz(k,g){return 256*(k=mt(Math.floor(k),0,255))+mt(Math.floor(g),0,255)}Ec.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,wr(Ec,"SegmentVector");const f8e=$n([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),g8e=$n([{name:"a_pattern_b",components:4,type:"Uint16"}]),x8e=$n([{name:"a_dash",components:4,type:"Uint16"}]);class ML{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(g,_,C,P){this.ids.push(UW(g)),this.positions.push(_,C,P)}eachPosition(g,_){const C=UW(g);let P=0,O=this.ids.length-1;for(;P>1;this.ids[B]>=C?O=B:P=B+1}for(;this.ids[P]===C;)_(this.positions[3*P],this.positions[3*P+1],this.positions[3*P+2]),P++}static serialize(g,_){const C=new Float64Array(g.ids),P=new Uint32Array(g.positions);return PL(C,P,0,C.length-1),_&&(_.add(C.buffer),_.add(P.buffer)),{ids:C,positions:P}}static deserialize(g){const _=new ML;let C;_.ids=g.ids,_.positions=g.positions;for(const P of _.ids)P!==C&&_.uniqueIds.push(P),C=P;return _.indexed=!0,_}}function UW(k){const g=+k;return Number.isSafeInteger(g)?g:zd(String(k))}function PL(k,g,_,C){for(;_>1];let O=_-1,B=C+1;for(;;){do O++;while(k[O]P);if(O>=B)break;A1(k,O,B),A1(g,3*O,3*B),A1(g,3*O+1,3*B+1),A1(g,3*O+2,3*B+2)}B-_`u_${O}`),this.type=C,this.context=P}setUniform(g,_,C,P,O){const B=P.constantOr(this.value);_.set(g,O,B instanceof Zs?B.toPremultipliedRenderColor(this.lutExpression&&this.lutExpression.kind==="constant"&&this.lutExpression.value==="none"?null:this.context.lut):B)}getBinding(g,_){return this.type==="color"?new v8e(g):new bm(g)}}class ye{constructor(g,_){this.uniformNames=_.map(C=>`u_${C}`),this.pattern=null,this.patternTransition=null,this.pixelRatio=1}setConstantPatternPositions(g,_){this.pixelRatio=g.pixelRatio||1,this.pattern=g.tl.concat(g.br),this.patternTransition=_?_.tl.concat(_.br):this.pattern}setUniform(g,_,C,P,O){let B=null;O!=="u_pattern"&&O!=="u_dash"||(B=this.pattern),O==="u_pattern_b"&&(B=this.patternTransition),O==="u_pixel_ratio"&&(B=this.pixelRatio),B&&_.set(g,O,B)}getBinding(g,_){return _==="u_pattern"||_==="u_pattern_b"||_==="u_dash"?new y8e(g):new bm(g)}}class Ce{constructor(g,_,C,P){this.expression=g,this.type=C,this.maxValue=0,this.paintVertexAttributes=_.map(O=>({name:`a_${O}`,type:"Float32",components:C==="color"?2:1,offset:0})),this.paintVertexArray=new P}populatePaintArray(g,_,C,P,O,B,W,Y){const ae=this.paintVertexArray.length,pe=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new Oi(0,{brightness:B,worldview:Y}),_,{},O,P,W):this.expression.kind==="constant"&&this.expression.value,ve=J(this.lutExpression,_,{},P,O,B,W,Y);this.paintVertexArray.resize(g),this._setPaintValue(ae,g,pe,ve?null:this.context.lut)}updatePaintArray(g,_,C,P,O,B,W,Y){const ae=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:W,worldview:Y},C,P,void 0,O):this.expression.kind==="constant"&&this.expression.value,pe=J(this.lutExpression,C,P,O,void 0,W,void 0,Y);this._setPaintValue(g,_,ae,pe?null:this.context.lut)}_setPaintValue(g,_,C,P){if(this.type==="color"){const O=X(C.toPremultipliedRenderColor(P));for(let B=g;B<_;B++)this.paintVertexArray.emplace(B,O[0],O[1])}else{for(let O=g;O<_;O++)this.paintVertexArray.emplace(O,C);this.maxValue=Math.max(this.maxValue,Math.abs(C))}}upload(g){this.paintVertexArray&&this.paintVertexArray.arrayBuffer&&(this.paintVertexBuffer&&this.paintVertexBuffer.buffer?this.paintVertexBuffer.updateData(this.paintVertexArray):this.paintVertexBuffer=g.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 Le{constructor(g,_,C,P,O,B){this.expression=g,this.uniformNames=_.map(W=>`u_${W}_t`),this.type=C,this.useIntegerZoom=P,this.context=O,this.maxValue=0,this.paintVertexAttributes=_.map(W=>({name:`a_${W}`,type:"Float32",components:C==="color"?4:2,offset:0})),this.paintVertexArray=new B}populatePaintArray(g,_,C,P,O,B,W,Y){const ae=this.expression.evaluate(new Oi(this.context.zoom,{brightness:B,worldview:Y}),_,{},O,P,W),pe=this.expression.evaluate(new Oi(this.context.zoom+1,{brightness:B,worldview:Y}),_,{},O,P,W),ve=J(this.lutExpression,_,{},P,O,B,W,Y),_e=this.paintVertexArray.length;this.paintVertexArray.resize(g),this._setPaintValue(_e,g,ae,pe,ve?null:this.context.lut)}updatePaintArray(g,_,C,P,O,B,W,Y){const ae=this.expression.evaluate({zoom:this.context.zoom,brightness:W,worldview:Y},C,P,void 0,O),pe=this.expression.evaluate({zoom:this.context.zoom+1,brightness:W,worldview:Y},C,P,void 0,O),ve=J(this.lutExpression,C,P,O,void 0,W,void 0,Y);this._setPaintValue(g,_,ae,pe,ve?null:this.context.lut)}_setPaintValue(g,_,C,P,O){if(this.type==="color"){const B=X(C.toPremultipliedRenderColor(O)),W=X(P.toPremultipliedRenderColor(O));for(let Y=g;Y<_;Y++)this.paintVertexArray.emplace(Y,B[0],B[1],W[0],W[1])}else{for(let B=g;B<_;B++)this.paintVertexArray.emplace(B,C,P);this.maxValue=Math.max(this.maxValue,Math.abs(C),Math.abs(P))}}upload(g){this.paintVertexArray&&this.paintVertexArray.arrayBuffer&&(this.paintVertexBuffer&&this.paintVertexBuffer.buffer?this.paintVertexBuffer.updateData(this.paintVertexArray):this.paintVertexBuffer=g.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes,this.expression.isStateDependent||!this.expression.isLightConstant))}destroy(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy()}setUniform(g,_,C,P,O){const B=this.useIntegerZoom?Math.floor(C.zoom):C.zoom,W=mt(this.expression.interpolationFactor(B,this.context.zoom,this.context.zoom+1),0,1);_.set(g,O,W)}getBinding(g,_){return new bm(g)}}class Xe{constructor(g,_,C,P,O){this.expression=g,this.layerId=O,this.paintVertexAttributes=(C==="array"?x8e:f8e).members;for(let B=0;B<_.length;++B);this.paintVertexArray=new P,this.paintTransitionVertexArray=new zE}populatePaintArray(g,_,C,P){const O=this.paintVertexArray.length;this.paintVertexArray.resize(g),this._setPaintValues(O,g,_.patterns&&_.patterns[this.layerId],C)}updatePaintArray(g,_,C,P,O,B,W){this._setPaintValues(g,_,C.patterns&&C.patterns[this.layerId],B)}_setPaintValues(g,_,C,P){if(!P||!C)return;const O=P[C[0]],B=P[C[1]];if(O){if(O){const{tl:W,br:Y,pixelRatio:ae}=O;for(let pe=g;pe<_;pe++)this.paintVertexArray.emplace(pe,W[0],W[1],Y[0],Y[1],ae)}if(B){this.paintTransitionVertexArray.resize(this.paintVertexArray.length);const{tl:W,br:Y}=B;for(let ae=g;ae<_;ae++)this.paintTransitionVertexArray.emplace(ae,W[0],W[1],Y[0],Y[1])}}}upload(g){const _=this.expression.isStateDependent||!this.expression.isLightConstant;this.paintVertexArray&&this.paintVertexArray.arrayBuffer&&(this.paintVertexBuffer=g.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes,_)),this.paintTransitionVertexArray&&this.paintTransitionVertexArray.length&&(this.paintTransitionVertexBuffer=g.createVertexBuffer(this.paintTransitionVertexArray,g8e.members,_))}destroy(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy(),this.paintTransitionVertexBuffer&&this.paintTransitionVertexBuffer.destroy()}}class Ke{constructor(g,_,C=()=>!0){this.binders={},this._buffers=[],this.context=_;const P=[],O=g;for(const B in g.paint._values){const W=O.paint.get(B);if(B.endsWith("-use-theme")||!C(B)||!(W instanceof qN&&ul(W.property.specification)))continue;const Y=it(B,g.type),ae=W.value,pe=W.property.specification.type,ve=!!W.property.useIntegerZoom,_e=B==="line-dasharray"||B.endsWith("pattern"),Pe=O.paint.get(`${B}-use-theme`),De=B==="line-dasharray"&&O.layout.get("line-cap").value.kind!=="constant"||Pe&&Pe.value.kind!=="constant";if(ae.kind!=="constant"||De)if(ae.kind==="source"||De||_e){const We=Bt(B,pe,"source");this.binders[B]=_e?new Xe(ae,Y,pe,We,g.id):new Ce(ae,Y,pe,We),P.push(`/a_${B}`)}else{const We=Bt(B,pe,"composite");this.binders[B]=new Le(ae,Y,pe,ve,_,We),P.push(`/z_${B}`)}else this.binders[B]=_e?new ye(ae.value,Y):new de(ae.value,Y,pe,_),P.push(`/u_${B}`);Pe&&(this.binders[B].lutExpression=Pe.value)}this.cacheKey=P.sort().join("")}getMaxValue(g){const _=this.binders[g];return _ instanceof Ce||_ instanceof Le?_.maxValue:0}populatePaintArrays(g,_,C,P,O,B,W,Y){for(const ae in this.binders){const pe=this.binders[ae];pe.context=this.context,(pe instanceof Ce||pe instanceof Le||pe instanceof Xe)&&pe.populatePaintArray(g,_,C,P,O,B,W,Y)}}setConstantPatternPositions(g,_){for(const C in this.binders){const P=this.binders[C];P instanceof ye&&P.setConstantPatternPositions(g,_)}}getPatternTransitionVertexBuffer(g){const _=this.binders[g];return _ instanceof Xe?_.paintTransitionVertexBuffer:null}updatePaintArrays(g,_,C,P,O,B,W,Y,ae,pe){let ve=!1;const _e=Object.keys(g),Pe=_e.length!==0&&!Y,De=Pe?_e:_.uniqueIds;this.context.lut=O.lut;for(const We in this.binders){const Je=this.binders[We];if(Je.context=this.context,(Je instanceof Ce||Je instanceof Le||Je instanceof Xe)&&Je.expression&&Je.expression.kind&&Je.expression.kind!=="constant"&&(Je.expression.isStateDependent===!0||Je.expression.isLightConstant===!1)){const rt=O.paint.get(We);Je.expression=rt.value;for(const xt of De){const ut=g[xt.toString()];_.eachPosition(xt,(St,Rt,Ft)=>{const bs=P.feature(St);Je.updatePaintArray(Rt,Ft,bs,ut,B,W,ae,pe)})}if(!Pe)for(const xt of C.uniqueIds){const ut=g[xt.toString()];C.eachPosition(xt,(St,Rt,Ft)=>{const bs=P.feature(St);Je.updatePaintArray(Rt,Ft,bs,ut,B,W,ae,pe)})}ve=!0}}return ve}defines(){const g=[];for(const _ in this.binders){const C=this.binders[_];(C instanceof de||C instanceof ye)&&g.push(...C.uniformNames.map(P=>`#define HAS_UNIFORM_${P}`))}return g}getPaintVertexBuffers(){return this._buffers}getUniforms(g){const _=[];for(const C in this.binders){const P=this.binders[C];if(P instanceof de||P instanceof ye||P instanceof Le)for(const O of P.uniformNames)_.push({name:O,property:C,binding:P.getBinding(g,O)})}return _}setUniforms(g,_,C,P,O){for(const{name:B,property:W,binding:Y}of C)this.binders[W].setUniform(g,Y,O,P.get(W),B)}updatePaintBuffers(){this._buffers=[];for(const g in this.binders){const _=this.binders[g];(_ instanceof Ce||_ instanceof Le||_ instanceof Xe)&&_.paintVertexBuffer&&this._buffers.push(_.paintVertexBuffer),_ instanceof Xe&&_.paintTransitionVertexBuffer&&this._buffers.push(_.paintTransitionVertexBuffer)}}upload(g){for(const _ in this.binders){const C=this.binders[_];(C instanceof Ce||C instanceof Le||C instanceof Xe)&&C.upload(g)}this.updatePaintBuffers()}destroy(){for(const g in this.binders){const _=this.binders[g];(_ instanceof Ce||_ instanceof Le||_ instanceof Xe)&&_.destroy()}}}class st{constructor(g,_,C=()=>!0){this.programConfigurations={};for(const P of g)this.programConfigurations[P.id]=new Ke(P,_,C);this.needsUpload=!1,this._featureMap=new ML,this._featureMapWithoutIds=new ML,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(g,_,C,P,O,B,W,Y,ae){for(const pe in this.programConfigurations)this.programConfigurations[pe].populatePaintArrays(g,_,P,O,B,W,Y,ae);_.id!==void 0?this._featureMap.add(_.id,C,this._bufferOffset,g):(this._featureMapWithoutIds.add(this._idlessCounter,C,this._bufferOffset,g),this._idlessCounter+=1),this._bufferOffset=g,this.needsUpload=!0}updatePaintArrays(g,_,C,P,O,B,W,Y){for(const ae of C)this.needsUpload=this.programConfigurations[ae.id].updatePaintArrays(g,this._featureMap,this._featureMapWithoutIds,_,ae,P,O,B,W||0,Y)||this.needsUpload}get(g){return this.programConfigurations[g]}upload(g){if(this.needsUpload){for(const _ in this.programConfigurations)this.programConfigurations[_].upload(g);this.needsUpload=!1}}destroy(){for(const g in this.programConfigurations)this.programConfigurations[g].destroy()}}const dt={"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 it(k,g){return dt[k]||[k.replace(`${g}-`,"").replace(/-/g,"_")]}const jt={"line-pattern":{source:Gj,composite:Gj},"fill-pattern":{source:Gj,composite:Gj},"fill-extrusion-pattern":{source:Gj,composite:Gj},"line-dasharray":{source:zE,composite:zE}},wt={color:{source:F3,composite:VN},number:{source:Bl,composite:F3}};function Bt(k,g,_){const C=jt[k];return C&&C[_]||wt[g][_]}wr(de,"ConstantBinder"),wr(ye,"PatternConstantBinder"),wr(Ce,"SourceExpressionBinder"),wr(Xe,"PatternCompositeBinder"),wr(Le,"CompositeExpressionBinder"),wr(Ke,"ProgramConfiguration",{omit:["_buffers"]}),wr(st,"ProgramConfigurationSet");const Vt=dr/Math.PI/2,Ct=64,Ss=[Ct,32,16],rs=-Vt,_s=Vt;function Gt(k,g,_,C=Vt){return _=Un(_),[k*Math.sin(_)*C,-g*C,k*Math.cos(_)*C]}function ss(k,g,_){return Gt(Math.cos(Un(k)),Math.sin(Un(k)),g,_)}const xs=63710088e-1,Ks=2*Math.PI*xs;class Ts{constructor(g,_){if(isNaN(g)||isNaN(_))throw new Error(`Invalid LngLat object: (${g}, ${_})`);if(this.lng=+g,this.lat=+_,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new Ts(Pt(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(g){const _=Math.PI/180,C=this.lat*_,P=g.lat*_,O=Math.sin(C)*Math.sin(P)+Math.cos(C)*Math.cos(P)*Math.cos((g.lng-this.lng)*_);return xs*Math.acos(Math.min(O,1))}toBounds(g=0){const _=360*g/40075017,C=_/Math.cos(Math.PI/180*this.lat);return new _n({lng:this.lng-C,lat:this.lat-_},{lng:this.lng+C,lat:this.lat+_})}toEcef(g){return ss(this.lat,this.lng,Vt+g*Vt/xs)}static convert(g){if(g instanceof Ts)return g;if(Array.isArray(g)&&(g.length===2||g.length===3))return new Ts(Number(g[0]),Number(g[1]));if(!Array.isArray(g)&&typeof g=="object"&&g!==null)return new Ts(Number("lng"in g?g.lng:g.lon),Number(g.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 _n{constructor(g,_){g&&(_?this.setSouthWest(g).setNorthEast(_):Array.isArray(g)&&g.length===4?this.setSouthWest([g[0],g[1]]).setNorthEast([g[2],g[3]]):this.setSouthWest(g[0]).setNorthEast(g[1]))}setNorthEast(g){return this._ne=g instanceof Ts?new Ts(g.lng,g.lat):Ts.convert(g),this}setSouthWest(g){return this._sw=g instanceof Ts?new Ts(g.lng,g.lat):Ts.convert(g),this}extend(g){const _=this._sw,C=this._ne;let P,O;if(g instanceof Ts)P=g,O=g;else{if(!(g instanceof _n))return Array.isArray(g)?g.length===4||g.every(Array.isArray)?this.extend(_n.convert(g)):this.extend(Ts.convert(g)):typeof g=="object"&&g!==null&&g.hasOwnProperty("lat")&&(g.hasOwnProperty("lon")||g.hasOwnProperty("lng"))?this.extend(Ts.convert(g)):this;if(P=g._sw,O=g._ne,!P||!O)return this}return _||C?(_.lng=Math.min(P.lng,_.lng),_.lat=Math.min(P.lat,_.lat),C.lng=Math.max(O.lng,C.lng),C.lat=Math.max(O.lat,C.lat)):(this._sw=new Ts(P.lng,P.lat),this._ne=new Ts(O.lng,O.lat)),this}getCenter(){return new Ts((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 Ts(this.getWest(),this.getNorth())}getSouthEast(){return new Ts(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(g){const{lng:_,lat:C}=Ts.convert(g);let P=this._sw.lng<=_&&_<=this._ne.lng;return this._sw.lng>this._ne.lng&&(P=this._sw.lng>=_&&_>=this._ne.lng),this._sw.lat<=C&&C<=this._ne.lat&&P}static convert(g){if(g)return g instanceof _n?g:new _n(g)}}function hn(k){return Ks*Math.cos(k*Math.PI/180)}function Rn(k){return(180+k)/360}function Kn(k){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+k*Math.PI/360)))/360}function en(k,g){return k/hn(g)}function Ls(k){return 360*k-180}function yn(k){return 360/Math.PI*Math.atan(Math.exp((180-360*k)*Math.PI/180))-90}function jn(k,g){return k*hn(yn(g))}const An=85.051129;function jr(k){return Math.cos(Un(mt(k,-85.051129,An)))}function ur(k,g){const _=mt(g,0,25.5),C=Math.pow(2,_);return jr(k)*Ks/(512*C)}function hr(k){return 1/Math.cos(k*Math.PI/180)}function Vn(k,g=0){const _=Math.exp(Math.PI*(1-(k.y+g/dr)/(1<=Y?(Na(k,g,_,ae,pe,O,ve,W,Y),Na(k,ae,pe,C,P,ve,B,W,Y)):k.push(B)}function ea(k,g,_){let C=k[0],P=C.x,O=C.y;g(C);const B=[C];for(let W=1;Wk.x+1||Ck.y+1)&&qr("Geometry exceeds allowed extent, reduce your vector tile buffer size"),k}function Ha(k,g,_){const C=k.loadGeometry(),P=k.extent,O=dr/P;if(g&&_&&_.projection.isReprojectedInTileSpace){const B=1<{const Pe=Ls((g.x+_e.x/P)/B),De=yn((g.y+_e.y/P)/B),We=pe.project(Pe,De);_e.x=(We.x*W-Y)*P,_e.y=(We.y*W-ae)*P};for(let _e=0;_e=P||De.y<0||De.y>=P||(ve(De),Pe.push(De));C[_e]=Pe}}for(const B of C)for(const W of B)Ji(W,O);return C}function eo(k,g){return{type:k.type,id:k.id,properties:k.properties,geometry:g?Ha(k):[]}}class vi{constructor(g,_,C,P,O){this.properties={},this.extent=C,this.type=0,this.id=void 0,this._pbf=g,this._geometry=-1,this._keys=P,this._values=O,g.readFields(Wo,this,_)}loadGeometry(){const g=this._pbf;g.pos=this._geometry;const _=g.readVarint()+g.pos,C=[];let P,O=1,B=0,W=0,Y=0;for(;g.pos<_;){if(B<=0){const ae=g.readVarint();O=7&ae,B=ae>>3}if(B--,O===1||O===2)W+=g.readSVarint(),Y+=g.readSVarint(),O===1&&(P&&C.push(P),P=[]),P&&P.push(new es(W,Y));else{if(O!==7)throw new Error(`unknown command ${O}`);P&&P.push(P[0].clone())}}return P&&C.push(P),C}bbox(){const g=this._pbf;g.pos=this._geometry;const _=g.readVarint()+g.pos;let C=1,P=0,O=0,B=0,W=1/0,Y=-1/0,ae=1/0,pe=-1/0;for(;g.pos<_;){if(P<=0){const ve=g.readVarint();C=7&ve,P=ve>>3}if(P--,C===1||C===2)O+=g.readSVarint(),B+=g.readSVarint(),OY&&(Y=O),Bpe&&(pe=B);else if(C!==7)throw new Error(`unknown command ${C}`)}return[W,ae,Y,pe]}toGeoJSON(g,_,C){const P=this.extent*Math.pow(2,C),O=this.extent*g,B=this.extent*_,W=this.loadGeometry();function Y(_e){return[360*(_e.x+O)/P-180,360/Math.PI*Math.atan(Math.exp((1-2*(_e.y+B)/P)*Math.PI))-90]}function ae(_e){return _e.map(Y)}let pe;if(this.type===1){const _e=[];for(const De of W)_e.push(De[0]);const Pe=ae(_e);pe=_e.length===1?{type:"Point",coordinates:Pe[0]}:{type:"MultiPoint",coordinates:Pe}}else if(this.type===2){const _e=W.map(ae);pe=_e.length===1?{type:"LineString",coordinates:_e[0]}:{type:"MultiLineString",coordinates:_e}}else{if(this.type!==3)throw new Error("unknown feature type");{const _e=function(De){const We=De.length;if(We<=1)return[De];const Je=[];let rt,xt;for(let ut=0;ut=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[g];const _=this._pbf.readVarint()+this._pbf.pos;return new vi(this._pbf,_,this.extent,this._keys,this._values)}}function Tc(k,g,_){k===15?g.version=_.readVarint():k===1?g.name=_.readString():k===5?g.extent=_.readVarint():k===2?g._features.push(_.pos):k===3?g._keys.push(_.readString()):k===4&&g._values.push(function(C){let P=null;const O=C.readVarint()+C.pos;for(;C.pos>3;P=B===1?C.readString():B===2?C.readFloat():B===3?C.readDouble():B===4?C.readVarint64():B===5?C.readVarint():B===6?C.readSVarint():B===7?C.readBoolean():null}if(P==null)throw new Error("unknown feature value");return P}(_))}class hl{constructor(g,_){this.layers=g.readFields(qi,{},_)}}function qi(k,g,_){if(k===3){const C=new Ed(_,_.readVarint()+_.pos);C.length&&(g[C.name]=C)}}const $i="3d_elevation_id",Mc="level";class $d{constructor(){this._valid=!1}reset(g){return this.feature=g,this._valid=!0,this._geometry=g.loadGeometry(),this._geometry.length!==0&&this._geometry[0].length!==0||(this._valid=!1),this}geometry(g,_){return this._valid&&g(_(this._geometry)),this}require(g,_,C){return this.get(g,!0,_,C)}optional(g,_,C){return this.get(g,!1,_,C)}success(){return this._valid}get(g,_,C,P){const O=this.feature.properties.hasOwnProperty(g)?+this.feature.properties[g]:void 0;return this._valid&&O!==void 0&&!Number.isNaN(O)?C(P?P(O):O):_&&(this._valid=!1),this}}class ml{constructor(g,_){this.featureFunc=g,this.vertexFunc=_}parseFeature(g,_,C){return this.featureFunc(g,_,C)}parseVertex(g,_,C){return this.vertexFunc(g,_,C)}}const Ti=new ml((k,g,_)=>k.reset(g).require($i,C=>{_.id=C}).optional("fixed_height_relative",C=>{_.constantHeight=C},lc.decodeRelativeHeight).geometry(C=>{_.bounds=C},ju).success(),(k,g,_)=>k.reset(g).require($i,C=>{_.id=C}).require("elevation_idx",C=>{_.idx=C}).require("extent",C=>{_.extent=C}).require("height_relative",C=>{_.height=C},lc.decodeRelativeHeight).geometry(C=>{_.position=C},lc.getPoint).success()),yd=new ml((k,g,_)=>k.reset(g).require($i,C=>{_.id=C}).optional("fixed_height",C=>{_.constantHeight=C},lc.decodeMetricHeight).geometry(C=>{_.bounds=C},ju).success(),(k,g,_)=>k.reset(g).require($i,C=>{_.id=C}).require("elevation_idx",C=>{_.idx=C}).require("extent",C=>{_.extent=C}).require("height",C=>{_.height=C},lc.decodeMetricHeight).geometry(C=>{_.position=C},lc.getPoint).success());class lc{static getPoint(g){return Ws(g[0][0].x,g[0][0].y)}static decodeRelativeHeight(g){return 1e-4*g*5}static decodeMetricHeight(g){return 1e-4*g}static getVersionSchema(g){return g?g==="1.0.1"?yd:void 0:Ti}static parse(g){const _=[],C=[],P=g.length,O=new $d;for(let B=0;B=0);if(O===0)return 0;O!==g.length&&(_=!1)}return _?2:1}function _m(k,g){for(const _ of k.projections){const C=am(g,k.points[0],_.axis);if(_.projection[1]C[1])return 0}return 1}function ef(k,g){let _=0;const C=[0,0,0,0];for(let P=0;P=0&&_++;return _}class Pv{constructor(g,_){this.points=g||new Array(8).fill([0,0,0]),this.planes=_||new Array(6).fill([0,0,0,0]),this.bounds=Rl.fromPoints(this.points),this.projections=[],this.frustumEdges=[Ve([],this.points[2],this.points[3]),Ve([],this.points[0],this.points[3]),Ve([],this.points[4],this.points[0]),Ve([],this.points[5],this.points[1]),Ve([],this.points[6],this.points[2]),Ve([],this.points[7],this.points[3])];for(const C of this.frustumEdges){const P=[0,-C[2],C[1]],O=[C[2],0,-C[0]];this.projections.push({axis:P,projection:am(this.points,this.points[0],P)}),this.projections.push({axis:O,projection:am(this.points,this.points[0],O)})}}static fromInvProjectionMatrix(g,_,C,P){const O=Math.pow(2,C),B=[[-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(ae=>{const pe=tt([],ae,g),ve=1/pe[3]/_*O;return(_e=pe)[0]=(Pe=pe)[0]*(De=[ve,ve,P?1/pe[3]:ve,ve])[0],_e[1]=Pe[1]*De[1],_e[2]=Pe[2]*De[2],_e[3]=Pe[3]*De[3],_e;var _e,Pe,De}),W=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(ae=>{const pe=Te([],Oe([],Ve([],B[ae[0]],B[ae[1]]),Ve([],B[ae[2]],B[ae[1]]))),ve=-Me(pe,B[ae[1]]);return pe.concat(ve)}),Y=[];for(let ae=0;aeae[1]||ae[0]>Y[1])return 0}return 1}containsPoint(g){for(const _ of this.planes){const C=_[3];if(Me([_[0],_[1],_[2]],g)+C<0)return!1}return!0}}class Rl{static fromPoints(g){const _=[1/0,1/0,1/0],C=[-1/0,-1/0,-1/0];for(const P of g)ne(_,_,P),ie(C,C,P);return new Rl(_,C)}static fromTileIdAndHeight(g,_,C){const P=1<g.max[_]||g.min[_]>this.max[_])return!1;return!0}intersectsAabbXY(g){return!(this.min[0]>g.max[0]||g.min[0]>this.max[0]||this.min[1]>g.max[1]||g.min[1]>this.max[1])}encapsulate(g){for(let _=0;_<3;_++)this.min[_]=Math.min(this.min[_],g.min[_]),this.max[_]=Math.max(this.max[_],g.max[_])}encapsulatePoint(g){for(let _=0;_<3;_++)this.min[_]=Math.min(this.min[_],g[_]),this.max[_]=Math.max(this.max[_],g[_])}closestPoint(g){return[Math.max(Math.min(this.max[0],g[0]),this.min[0]),Math.max(Math.min(this.max[1],g[1]),this.min[1]),Math.max(Math.min(this.max[2],g[2]),this.min[2])]}}wr(Rl,"Aabb");class E1{constructor(g,_){this.feature=g,this.metersToTile=_,this.index=0}get(){const g=this.feature.vertices[this.index],_=this.feature.vertexProps[this.index].dir,C=_[1],P=-_[0],O=(g.extent+1)*this.metersToTile;return[new es(Math.trunc(g.position[0]+C*O),Math.trunc(g.position[1]+P*O)),new es(Math.trunc(g.position[0]-C*O),Math.trunc(g.position[1]-P*O))]}next(){this.index++}valid(){return this.index{return W.a0?ce(Y,Y,1/ae):Q(Y,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(g){if(this.edges.length===0)return;let _=0,C=Number.POSITIVE_INFINITY,P=0;const[O,B,W,Y,ae,pe,ve]=this._tmpVec2;on(ve,g.x,g.y);const _e=new gh(ve,null);for(let Pe=0;Pe0?On(Y,W)/St:0,Ft=mt(Rt,0,1),bs=Math.abs((Rt-Ft)*this.edgeProps[Pe].len);dn(ae,ve,Je),on(pe,We[1],-We[0]);const as=bs+Math.abs(On(ae,pe));as=0;--B){const W=this.edges[B].a,Y=this.edges[B].b,{position:ae,height:pe,extent:ve}=this.vertices[W],{position:_e,height:Pe,extent:De}=this.vertices[Y],We=this.vertexProps[W].dir,Je=this.vertexProps[Y].dir;if(Q(_,ae[0]/g,ae[1]/g,pe),Q(C,_e[0]/g,_e[1]/g,Pe),Q(P,We[1],-We[0],0),ce(P,P,ve),Q(O,Je[1],-Je[0],0),ce(O,O,De),this.distSqLines(Z(_[0]+.5*P[0],_[1]+.5*P[1],_[2]+.5*P[2]),Z(C[0]-.5*O[0],C[1]-.5*O[1],C[2]-.5*O[2]),Z(_[0]-.5*P[0],_[1]-.5*P[1],_[2]-.5*P[2]),Z(C[0]+.5*O[0],C[1]+.5*O[1],C[2]+.5*O[2]))<=.0025000000000000005)continue;const rt=this.vertices.length,xt=Ms(vt(),ae,_e);this.vertices.push({position:rn(xt,xt,.5),height:.5*(pe+Pe),extent:.5*(ve+De)});const ut=Ms(vt(),We,Je);this.vertexProps.push({dir:Gn(ut,ut)}),this.edges.splice(B,1),this.edgeProps.splice(B,1),this.edges.push({a:W,b:rt}),this.edges.push({a:rt,b:Y});const St=dn(vt(),this.vertices[rt].position,ae),Rt=br(St),Ft={vec:St,dir:rn(vt(),St,1/Rt),len:Rt};this.edgeProps.push(Ft),this.edgeProps.push(Ft)}}distSqLines(g,_,C,P){const O=ue(H(),_,g),B=ue(H(),P,C),W=ue(H(),g,C),Y=Me(O,O),ae=Me(O,B),pe=Me(O,W),ve=Me(B,B),_e=Me(B,W),Pe=Y*ve-ae*ae;if(Pe===0)return he(Se(O,C,P,Me(W,B)/Me(B,B)),g);const De=(Y*_e-ae*pe)/Pe;return he(Se(O,g,_,(ae*_e-pe*ve)/Pe),Se(B,C,P,De))}}class Fc{static parseFrom(g,_){const C=lc.parse(g);if(!C)return[];let{vertices:P,features:O}=C;const B=1/Vn(_);O.sort((pe,ve)=>pe.id-ve.id),P.sort((pe,ve)=>pe.id-ve.id||pe.idx-ve.idx),P=P.filter((pe,ve,_e)=>ve===_e.findIndex(Pe=>Pe.id===pe.id&&Pe.idx===pe.idx));const W=new Array;let Y=0;const ae=P.length;for(const pe of O){if(pe.constantHeight){W.push(new T1(pe.id,pe.bounds,pe.constantHeight));continue}for(;Y!==ae&&P[Y].idP.id===C)}}class Kc{constructor(g,_){this.zScale=1,this.xOffset=0,this.yOffset=0,g.equals(_)||(this.zScale=Math.pow(2,_.z-g.z),this.xOffset=(g.x*this.zScale-_.x)*dr,this.yOffset=(g.y*this.zScale-_.y)*dr)}constantElevation(g,_){if(g.constantHeight!=null)return this.computeBiasedHeight(g.constantHeight,_)}pointElevation(g,_,C){const P=this.constantElevation(_,C);return P??(g.x=g.x*this.zScale+this.xOffset,g.y=g.y*this.zScale+this.yOffset,this.computeBiasedHeight(_.pointElevation(g),C))}computeBiasedHeight(g,_){return _<=0?g:g+_*Nt(0,_,g>=0?g:Math.abs(.5*g))}}wr(T1,"ElevationFeature");class Kl{constructor(g){this.zoom=g.zoom,this.overscaling=g.overscaling,this.layers=g.layers,this.layerIds=this.layers.map(_=>_.fqid),this.index=g.index,this.hasPattern=!1,this.projection=g.projection,this.layoutVertexArray=new Qi,this.indexArray=new Ru,this.segments=new Ec,this.programConfigurations=new st(g.layers,{zoom:g.zoom,lut:g.lut}),this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.elevationMode=this.layers[0].layout.get("circle-elevation-reference"),this.hasElevation=!1,this.elevationMode!=="none"&&(this.elevatedLayoutVertexArray=new Bl),this.worldview=g.worldview,this.hasAppearances=null}updateFootprints(g,_){}updateAppearances(g,_,C,P){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(g,_,C,P){const O=this.layers[0],B=[];let W=null;O.type==="circle"&&(W=O.layout.get("circle-sort-key"));for(const{feature:ae,id:pe,index:ve,sourceLayerIndex:_e}of g){const Pe=this.layers[0]._featureFilter.needGeometry,De=eo(ae,Pe);if(!this.layers[0]._featureFilter.filter(new Oi(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),De,C))continue;const We=W?W.evaluate(De,{},C):void 0,Je={id:pe,properties:ae.properties,type:ae.type,sourceLayerIndex:_e,index:ve,geometry:Pe?De.geometry:Ha(ae,C,P),patterns:{},sortKey:We};B.push(Je)}W&&B.sort((ae,pe)=>ae.sortKey-pe.sortKey);let Y=null;P.projection.name==="globe"&&(this.globeExtVertexArray=new Z9,Y=P.projection);for(const ae of B){const{geometry:pe,index:ve,sourceLayerIndex:_e}=ae,Pe=g[ve].feature;this.addFeature(ae,pe,ve,_.availableImages,C,Y,_.brightness,_.elevationFeatures),_.featureIndex.insert(Pe,pe,ve,_e,this.index)}this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}update(g,_,C,P,O,B,W){this.programConfigurations.updatePaintArrays(g,_,O,C,P,B,W,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(g){this.uploaded||(this.layoutVertexBuffer=g.createVertexBuffer(this.layoutVertexArray,kae.members),this.indexBuffer=g.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=g.createVertexBuffer(this.globeExtVertexArray,p8e.members)),this.elevatedLayoutVertexArray&&(this.elevatedLayoutVertexBuffer=g.createVertexBuffer(this.elevatedLayoutVertexArray,m8e.members))),this.programConfigurations.upload(g),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy())}addFeature(g,_,C,P,O,B,W,Y){let ae;this.elevationMode!=="none"&&(ae=Fc.getElevationFeature(g,Y));for(const pe of _)for(const ve of pe){const _e=ve.x,Pe=ve.y;if(_e<0||_e>=dr||Pe<0||Pe>=dr)continue;if(B){const Je=B.projectTilePoint(_e,Pe,O),rt=B.upVector(O,_e,Pe);this.addGlobeExtVertex(Je,rt),this.addGlobeExtVertex(Je,rt),this.addGlobeExtVertex(Je,rt),this.addGlobeExtVertex(Je,rt)}const De=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,g.sortKey),We=De.vertexLength;if(this.addCircleVertex(_e,Pe,-1,-1),this.addCircleVertex(_e,Pe,1,-1),this.addCircleVertex(_e,Pe,1,1),this.addCircleVertex(_e,Pe,-1,1),this.elevationMode!=="none"){const Je=ae?ae.pointElevation(new es(_e,Pe)):0;this.hasElevation=this.hasElevation||Je!==0;for(let rt=0;rt<4;rt++)this.elevatedLayoutVertexArray.emplaceBack(Je)}this.indexArray.emplaceBack(We,We+1,We+2),this.indexArray.emplaceBack(We,We+2,We+3),De.vertexLength+=4,De.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,g,C,{},P,O,W,void 0,this.worldview)}addCircleVertex(g,_,C,P){this.layoutVertexArray.emplaceBack(2*g+(C+1)/2,2*_+(P+1)/2)}addGlobeExtVertex(g,_){this.globeExtVertexArray.emplaceBack(g.x,g.y,g.z,_[0]*16384,_[1]*16384,_[2]*16384)}}function nh(k,g){for(let _=0;_1){if(KS(k,g))return!0;for(let C=0;C1?_:_.sub(g)._mult(P)._add(g))}function UE(k,g){let _,C,P,O=!1;for(let B=0;Bg.y!=P.y>g.y&&g.x<(P.x-C.x)*(g.y-C.y)/(P.y-C.y)+C.x&&(O=!O)}return O}function Dy(k,g){let _=!1;for(let C=0,P=k.length-1;Cg.y!=B.y>g.y&&g.x<(B.x-O.x)*(g.y-O.y)/(B.y-O.y)+O.x&&(_=!_)}return _}function YS(k,g,_,C,P){for(const B of k)if(g<=B.x&&_<=B.y&&C>=B.x&&P>=B.y)return!0;const O=[new es(g,_),new es(g,P),new es(C,P),new es(C,_)];if(k.length>2){for(const B of O)if(Dy(k,B))return!0}for(let B=0;BP.x&&g.x>P.x||k.yP.y&&g.y>P.y)return!1;const O=Zr(k,g,_[0]);return O!==Zr(k,g,_[1])||O!==Zr(k,g,_[2])||O!==Zr(k,g,_[3])}function XS(k,g,_,C,P,O){let B=g.y-k.y,W=k.x-g.x;if(O=O||0){const Y=B*B+W*W;if(Y===0)return!0;const ae=Math.sqrt(Y);B/=ae,W/=ae}return!((_.x-k.x)*B+(_.y-k.y)*W-O<0||(C.x-k.x)*B+(C.y-k.y)*W-O<0||(P.x-k.x)*B+(P.y-k.y)*W-O<0)}function az(k,g,_,C,P,O,B){return!(XS(k,g,C,P,O,B)||XS(g,_,C,P,O,B)||XS(_,k,C,P,O,B)||XS(C,P,k,g,_,B)||XS(P,O,k,g,_,B)||XS(O,C,k,g,_,B))}function qE(k,g,_){const C=g.paint.get(k).value;return C.kind==="constant"?C.value:_.programConfigurations.get(g.id).getMaxValue(k)}function Sae(k){return Math.sqrt(k[0]*k[0]+k[1]*k[1])}function Eat(k,g,_,C,P){if(!g[0]&&!g[1])return k;const O=es.convert(g)._mult(P);_==="viewport"&&O._rotate(-C);const B=[];for(let W=0;W>_&&g.y===this.y>>_}url(g,_){const C=function(O,B,W){const Y=2**W,ae=2*Math.PI*6378137,pe=ae*(O/Y-.5),ve=ae*(.5-(B+1)/Y);return`${pe},${ve},${pe+ae/Y},${ve+ae/Y}`}(this.x,this.y,this.z),P=function(O,B,W){let Y,ae="";for(let pe=O;pe>0;pe--)Y=1<this.canonical.z?new L0(g,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new L0(g,this.wrap,g,this.canonical.x>>_,this.canonical.y>>_)}calculateScaledKey(g,_=!0){if(this.overscaledZ===g&&_)return this.key;if(g>this.canonical.z)return iz(this.wrap*+_,g,this.canonical.z,this.canonical.x,this.canonical.y);{const C=this.canonical.z-g;return iz(this.wrap*+_,g,g,this.canonical.x>>C,this.canonical.y>>C)}}isChildOf(g){if(g.wrap!==this.wrap)return!1;const _=this.canonical.z-g.canonical.z;return g.overscaledZ===0||g.overscaledZ>_&&g.canonical.y===this.canonical.y>>_}children(g){if(this.overscaledZ>=g)return[new L0(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const _=this.canonical.z+1,C=2*this.canonical.x,P=2*this.canonical.y;return[new L0(_,this.wrap,_,C,P),new L0(_,this.wrap,_,C+1,P),new L0(_,this.wrap,_,C,P+1),new L0(_,this.wrap,_,C+1,P+1)]}isLessThan(g){return this.wrapg.wrap)&&(this.overscaledZg.overscaledZ)&&(this.canonical.xg.canonical.x)&&this.canonical.y{let g=k.canonical.x-1,_=k.wrap;return g<0&&(g=(1<{let g=k.canonical.x+1,_=k.wrap;return g===1<new L0(k.overscaledZ,k.wrap,k.canonical.z,k.canonical.x,(k.canonical.y===0?1<new L0(k.overscaledZ,k.wrap,k.canonical.z,k.canonical.x,k.canonical.y===(1<1?null:function(C,P,O,B){const W=Math.sin(O);return C*(Math.sin((1-B)*O)/W)+P*(Math.sin(B*O)/W)}(k.a[g],k.b[g],k.angle,mt(_,0,1))+k.center[g]}function QS(k){if(k.z<=1)return Las[k.z+2*k.y+k.x];const g=_8e(Eae(k));return Rl.fromPoints(g)}function q3(k,g,_){return ce(k,k,1-_),je(k,k,g,_)}function Dat(k,g){const _=$3(g.zoom);if(_===0)return QS(k);const C=Eae(k),P=_8e(C),O=Rn(C.getWest())*g.worldSize,B=Rn(C.getEast())*g.worldSize,W=Kn(C.getNorth())*g.worldSize,Y=Kn(C.getSouth())*g.worldSize,ae=[O,W,0],pe=[B,W,0],ve=[O,Y,0],_e=[B,Y,0],Pe=v([],g.globeMatrix);return Qe(ae,ae,Pe),Qe(pe,pe,Pe),Qe(ve,ve,Pe),Qe(_e,_e,Pe),P[0]=q3(P[0],ve,_),P[1]=q3(P[1],_e,_),P[2]=q3(P[2],pe,_),P[3]=q3(P[3],ae,_),Rl.fromPoints(P)}function Oat(k,g,_){for(const C of k)Qe(C,C,g),ce(C,C,_)}function Fat(k,g,_,C){const P=g/k.worldSize,O=k.globeMatrix;if(_.z<=1){const ys=QS(_).getCorners();return Oat(ys,O,P),Rl.fromPoints(ys)}const B=Eae(_,C),W=_8e(B,Vt+Aae(k._tileCoverLift));Oat(W,O,P);const Y=Number.MAX_VALUE,ae=[-Y,-Y,-Y],pe=[Y,Y,Y];if(B.contains(k.center)){for(const ms of W)ne(pe,pe,ms),ie(ae,ae,ms);ae[2]=0;const ys=k.point,hs=[ys.x*P,ys.y*P,0];return ne(pe,pe,hs),ie(ae,ae,hs),new Rl(pe,ae)}if(k._tileCoverLift>0){for(const ys of W)ne(pe,pe,ys),ie(ae,ae,ys);return new Rl(pe,ae)}const ve=[O[12]*P,O[13]*P,O[14]*P],_e=B.getCenter(),Pe=mt(k.center.lat,-85.051129,An),De=mt(_e.lat,-85.051129,An),We=Rn(k.center.lng),Je=Kn(Pe);let rt=We-Rn(_e.lng);const xt=Je-Kn(De);rt>.5?rt-=1:rt<-.5&&(rt+=1);let ut=0;Math.abs(rt)>Math.abs(xt)?ut=rt>=0?1:3:(ut=xt>=0?0:2,je(ve,ve,[O[4]*P,O[5]*P,O[6]*P],-Math.sin(Un(xt>=0?B.getSouth():B.getNorth()))*Vt));const St=W[ut],Rt=W[(ut+1)%4],Ft=new Ias(St,Rt,ve),bs=[b8e(Ft,0)||St[0],b8e(Ft,1)||St[1],b8e(Ft,2)||St[2]],as=$3(k.zoom);if(as>0){const ys=function({x:ms,y:vn,z:Nn},Tn,Ln,Mn,Qn){const fn=1/(1<.5?ta=-1:Cr<-.5&&(ta=1),Pn=((Pn+ta)*Tn-(Mn*=Tn))*Ln+Mn,Dn=((Dn+ta)*Tn-Mn)*Ln+Mn,tr=(tr*Tn-(Qn*=Tn))*Ln+Qn,mr=(mr*Tn-Qn)*Ln+Qn,[[Pn,mr,0],[Dn,mr,0],[Dn,tr,0],[Pn,tr,0]]}(_,g,k._pixelsPerMercatorPixel,We,Je);for(let ms=0;msMath.PI/2*1.01}const $at=Un(85),Ras=Math.cos($at),Das=Math.sin($at),Oas=f(),Vat=k=>{const g=[];return k.paint.get("circle-pitch-alignment")==="map"&&g.push("PITCH_WITH_MAP"),k.paint.get("circle-pitch-scale")==="map"&&g.push("SCALE_WITH_MAP"),g};function Hat(k,g,_,C,P,O,B,W,Y){if(O&&k.queryGeometry.isAboveHorizon)return!1;O&&(Y*=k.pixelToTileUnitsFactor);const ae=k.tileID.canonical,pe=_.projection.upVectorScale(ae,_.center.lat,_.worldSize).metersToTile;for(const ve of g)for(const _e of ve){const Pe=_e.add(W),De=P&&_.elevation?_.elevation.exaggeration()*P.getElevationAt(Pe.x,Pe.y,!0):0,We=_.projection.projectTilePoint(Pe.x,Pe.y,ae);if(De>0){const ut=_.projection.upVector(ae,Pe.x,Pe.y);We.x+=ut[0]*pe*De,We.y+=ut[1]*pe*De,We.z+=ut[2]*pe*De}const Je=O?Pe:Fas(We.x,We.y,We.z,C),rt=O?k.tilespaceRays.map(ut=>Bas(ut,De)):k.queryGeometry.screenGeometry,xt=tt([],[We.x,We.y,We.z,1],C);if(!B&&O?Y*=xt[3]/_.cameraToCenterDistance:B&&!O&&(Y*=_.cameraToCenterDistance/xt[3]),O){const ut=yn((_e.y/dr+ae.y)/(1<k.width||P.height>k.height||_.x>k.width-P.width||_.y>k.height-P.height)throw new RangeError("out of range source coordinates for image copy");if(P.width>g.width||P.height>g.height||C.x>g.width-P.width||C.y>g.height-P.height)throw new RangeError("out of range destination coordinates for image copy");const Y=k.data,ae=g.data,pe=O===4&&W;for(let ve=0;ve{g[k.evaluationKey]=Y;const ae=k.expression.evaluate(g),pe=ae?ae.toNonPremultipliedRenderColor(null):null;pe&&(P.data[B+W+0]=Math.floor(255*pe.r),P.data[B+W+1]=Math.floor(255*pe.g),P.data[B+W+2]=Math.floor(255*pe.b),P.data[B+W+3]=Math.floor(255*pe.a))};if(k.clips)for(let B=0,W=0;B80*_){W=k[0],Y=k[1];let pe=W,ve=Y;for(let _e=_;_epe&&(pe=Pe),De>ve&&(ve=De)}ae=Math.max(pe-W,ve-Y),ae=ae!==0?32767/ae:0}return GW(O,B,_,W,Y,ae,0),B}function tit(k,g,_,C,P){let O;if(P===function(B,W,Y,ae){let pe=0;for(let ve=W,_e=Y-ae;ve0)for(let B=g;B<_;B+=C)O=ait(B/C|0,k[B],k[B+1],O);else for(let B=_-C;B>=g;B-=C)O=ait(B/C|0,k[B],k[B+1],O);return O&&lz(O,O.next)&&(YW(O),O=O.next),O}function DL(k,g){if(!k)return k;g||(g=k);let _,C=k;do if(_=!1,C.steiner||!lz(C,C.next)&&tf(C.prev,C,C.next)!==0)C=C.next;else{if(YW(C),C=g=C.prev,C===C.next)break;_=!0}while(_||C!==g);return g}function GW(k,g,_,C,P,O,B){if(!k)return;!B&&O&&function(Y,ae,pe,ve){let _e=Y;do _e.z===0&&(_e.z=S8e(_e.x,_e.y,ae,pe,ve)),_e.prevZ=_e.prev,_e.nextZ=_e.next,_e=_e.next;while(_e!==Y);_e.prevZ.nextZ=null,_e.prevZ=null,function(Pe){let De,We=1;do{let Je,rt=Pe;Pe=null;let xt=null;for(De=0;rt;){De++;let ut=rt,St=0;for(let Ft=0;Ft0||Rt>0&&ut;)St!==0&&(Rt===0||!ut||rt.z<=ut.z)?(Je=rt,rt=rt.nextZ,St--):(Je=ut,ut=ut.nextZ,Rt--),xt?xt.nextZ=Je:Pe=Je,Je.prevZ=xt,xt=Je;rt=ut}xt.nextZ=null,We*=2}while(De>1)}(_e)}(k,C,P,O);let W=k;for(;k.prev!==k.next;){const Y=k.prev,ae=k.next;if(O?Gas(k,C,P,O):Has(k))g.push(Y.i,k.i,ae.i),YW(k),k=ae.next,W=ae.next;else if((k=ae)===W){B?B===1?GW(k=Was(DL(k),g),g,_,C,P,O,2):B===2&&Kas(k,g,_,C,P,O):GW(DL(k),g,_,C,P,O,1);break}}}function Has(k){const g=k.prev,_=k,C=k.next;if(tf(g,_,C)>=0)return!1;const P=g.x,O=_.x,B=C.x,W=g.y,Y=_.y,ae=C.y,pe=Math.min(P,O,B),ve=Math.min(W,Y,ae),_e=Math.max(P,O,B),Pe=Math.max(W,Y,ae);let De=C.next;for(;De!==g;){if(De.x>=pe&&De.x<=_e&&De.y>=ve&&De.y<=Pe&&WW(P,W,O,Y,B,ae,De.x,De.y)&&tf(De.prev,De,De.next)>=0)return!1;De=De.next}return!0}function Gas(k,g,_,C){const P=k.prev,O=k,B=k.next;if(tf(P,O,B)>=0)return!1;const W=P.x,Y=O.x,ae=B.x,pe=P.y,ve=O.y,_e=B.y,Pe=Math.min(W,Y,ae),De=Math.min(pe,ve,_e),We=Math.max(W,Y,ae),Je=Math.max(pe,ve,_e),rt=S8e(Pe,De,g,_,C),xt=S8e(We,Je,g,_,C);let ut=k.prevZ,St=k.nextZ;for(;ut&&ut.z>=rt&&St&&St.z<=xt;){if(ut.x>=Pe&&ut.x<=We&&ut.y>=De&&ut.y<=Je&&ut!==P&&ut!==B&&WW(W,pe,Y,ve,ae,_e,ut.x,ut.y)&&tf(ut.prev,ut,ut.next)>=0||(ut=ut.prevZ,St.x>=Pe&&St.x<=We&&St.y>=De&&St.y<=Je&&St!==P&&St!==B&&WW(W,pe,Y,ve,ae,_e,St.x,St.y)&&tf(St.prev,St,St.next)>=0))return!1;St=St.nextZ}for(;ut&&ut.z>=rt;){if(ut.x>=Pe&&ut.x<=We&&ut.y>=De&&ut.y<=Je&&ut!==P&&ut!==B&&WW(W,pe,Y,ve,ae,_e,ut.x,ut.y)&&tf(ut.prev,ut,ut.next)>=0)return!1;ut=ut.prevZ}for(;St&&St.z<=xt;){if(St.x>=Pe&&St.x<=We&&St.y>=De&&St.y<=Je&&St!==P&&St!==B&&WW(W,pe,Y,ve,ae,_e,St.x,St.y)&&tf(St.prev,St,St.next)>=0)return!1;St=St.nextZ}return!0}function Was(k,g){let _=k;do{const C=_.prev,P=_.next.next;!lz(C,P)&&nit(C,_,_.next,P)&&KW(C,P)&&KW(P,C)&&(g.push(C.i,_.i,P.i),YW(_),YW(_.next),_=k=P),_=_.next}while(_!==k);return DL(_)}function Kas(k,g,_,C,P,O){let B=k;do{let W=B.next.next;for(;W!==B.prev;){if(B.i!==W.i&&Jas(B,W)){let Y=rit(B,W);return B=DL(B,B.next),Y=DL(Y,Y.next),GW(B,g,_,C,P,O,0),void GW(Y,g,_,C,P,O,0)}W=W.next}B=B.next}while(B!==k)}function Yas(k,g){let _=k.x-g.x;return _===0&&(_=k.y-g.y,_===0)&&(_=(k.next.y-k.y)/(k.next.x-k.x)-(g.next.y-g.y)/(g.next.x-g.x)),_}function Zas(k,g){const _=function(P,O){let B=O;const W=P.x,Y=P.y;let ae,pe=-1/0;if(lz(P,B))return B;do{if(lz(P,B.next))return B.next;if(Y<=B.y&&Y>=B.next.y&&B.next.y!==B.y){const We=B.x+(Y-B.y)*(B.next.x-B.x)/(B.next.y-B.y);if(We<=W&&We>pe&&(pe=We,ae=B.x=B.x&&B.x>=_e&&W!==B.x&&sit(Yae.x||B.x===ae.x&&Xas(ae,B)))&&(ae=B,De=We)}B=B.next}while(B!==ve);return ae}(k,g);if(!_)return g;const C=rit(_,k);return DL(C,C.next),DL(_,_.next)}function Xas(k,g){return tf(k.prev,k,g.prev)<0&&tf(g.next,k,k.next)<0}function S8e(k,g,_,C,P){return(k=1431655765&((k=858993459&((k=252645135&((k=16711935&((k=(k-_)*P|0)|k<<8))|k<<4))|k<<2))|k<<1))|(g=1431655765&((g=858993459&((g=252645135&((g=16711935&((g=(g-C)*P|0)|g<<8))|g<<4))|g<<2))|g<<1))<<1}function Qas(k){let g=k,_=k;do(g.x<_.x||g.x===_.x&&g.y<_.y)&&(_=g),g=g.next;while(g!==k);return _}function sit(k,g,_,C,P,O,B,W){return(P-B)*(g-W)>=(k-B)*(O-W)&&(k-B)*(C-W)>=(_-B)*(g-W)&&(_-B)*(O-W)>=(P-B)*(C-W)}function WW(k,g,_,C,P,O,B,W){return!(k===B&&g===W)&&sit(k,g,_,C,P,O,B,W)}function Jas(k,g){return k.next.i!==g.i&&k.prev.i!==g.i&&!function(_,C){let P=_;do{if(P.i!==_.i&&P.next.i!==_.i&&P.i!==C.i&&P.next.i!==C.i&&nit(P,P.next,_,C))return!0;P=P.next}while(P!==_);return!1}(k,g)&&(KW(k,g)&&KW(g,k)&&function(_,C){let P=_,O=!1;const B=(_.x+C.x)/2,W=(_.y+C.y)/2;do P.y>W!=P.next.y>W&&P.next.y!==P.y&&B<(P.next.x-P.x)*(W-P.y)/(P.next.y-P.y)+P.x&&(O=!O),P=P.next;while(P!==_);return O}(k,g)&&(tf(k.prev,k,g.prev)||tf(k,g.prev,g))||lz(k,g)&&tf(k.prev,k,k.next)>0&&tf(g.prev,g,g.next)>0)}function tf(k,g,_){return(g.y-k.y)*(_.x-g.x)-(g.x-k.x)*(_.y-g.y)}function lz(k,g){return k.x===g.x&&k.y===g.y}function nit(k,g,_,C){const P=Pae(tf(k,g,_)),O=Pae(tf(k,g,C)),B=Pae(tf(_,C,k)),W=Pae(tf(_,C,g));return P!==O&&B!==W||!(P!==0||!Mae(k,_,g))||!(O!==0||!Mae(k,C,g))||!(B!==0||!Mae(_,k,C))||!(W!==0||!Mae(_,g,C))}function Mae(k,g,_){return g.x<=Math.max(k.x,_.x)&&g.x>=Math.min(k.x,_.x)&&g.y<=Math.max(k.y,_.y)&&g.y>=Math.min(k.y,_.y)}function Pae(k){return k>0?1:k<0?-1:0}function KW(k,g){return tf(k.prev,k,k.next)<0?tf(k,g,k.next)>=0&&tf(k,k.prev,g)>=0:tf(k,g,k.prev)<0||tf(k,k.next,g)<0}function rit(k,g){const _=C8e(k.i,k.x,k.y),C=C8e(g.i,g.x,g.y),P=k.next,O=g.prev;return k.next=g,g.prev=k,_.next=P,P.prev=_,C.next=_,_.prev=C,O.next=C,C.prev=O,C}function ait(k,g,_,C){const P=C8e(k,g,_);return C?(P.next=C.next,P.prev=C,C.next.prev=P,C.next=P):(P.prev=P,P.next=P),P}function YW(k){k.next.prev=k.prev,k.prev.next=k.next,k.prevZ&&(k.prevZ.nextZ=k.nextZ),k.nextZ&&(k.nextZ.prevZ=k.prevZ)}function C8e(k,g,_){return{i:k,x:g,y:_,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function ZW(k,g){const _=k.length;if(_<=1)return[k];const C=[];let P,O;for(let B=0;B<_;B++){const W=Jr(k[B]);W!==0&&(k[B].area=Math.abs(W),O===void 0&&(O=W<0),O===W<0?(P&&C.push(P),P=[k[B]]):P.push(k[B]))}if(P&&C.push(P),g>1)for(let B=0;B=dr&&_>=dr}static evaluate(g){if(g.length===0)return new V3;let _=[];for(const Y of g)_.push(...Y.portals);if(_.length===0)return new V3;for(const Y of _){const ae=Y.va,pe=Y.vb;(V3.isOnBorder(ae.x,pe.x)||V3.isOnBorder(ae.y,pe.y))&&(Y.type="border")}const C=_.filter(Y=>Y.type!=="unevaluated"),P=_.filter(Y=>Y.type==="unevaluated");if(P.length===0)return new V3;P.sort((Y,ae)=>Y.hash===ae.hash?Y.isTunnel===ae.isTunnel?0:Y.isTunnel?-1:1:Y.hashY.hashO!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new st(_,{zoom:C,lut:P},O=>O!=="fill-bridge-guard-rail-color")}addVertices(g,_){const C=this.unevalVertices.length;for(let P=0;P=O.min.x&&ve.x<=O.max.x&&ve.y>=O.min.y&&ve.y<=O.max.y||_e.x>=O.min.x&&_e.x<=O.max.x&&_e.y>=O.min.y&&_e.y<=O.max.y||ZS(ve,_e,W))||this.isOnBorder(ve.x,_e.x)||this.isOnBorder(ve.y,_e.y))continue;const Pe=M1.computeEdgeHash(this.unevalVertices[ae],this.unevalVertices[pe]);let De,We=this.vertexHashLookup.get(M1.computePosHash(ve));We!=null?De=We.next:(We=this.vertexHashLookup.get(M1.computePosHash(_e)),De=We!=null?We.prev:Pe),this.unevalEdges.push({polygonIdx:g,a:ae,b:pe,hash:Pe,portalHash:De,isTunnel:P,type:"unevaluated",featureInfo:B})}}addPortalCandidates(g,_,C,P,O){if(_.length!==0){this.vertexHashLookup.clear();for(const B of _){if(B.length===0)continue;const W=B[0];let Y=M1.computeEdgeHash(W[W.length-2],W[W.length-1]);for(let ae=0;ae({vertexOffset:0,primitiveOffset:this.indexArray.length}),C=_e=>{_e.primitiveLength=this.indexArray.length-_e.primitiveOffset},P=new tis(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(g.portals,this.unevalEdges);const O=_(),B=_(),W=_(),Y=(_e,Pe)=>{_e.sort((We,Je)=>We.type===Pe&&Je.type!==Pe?-1:We.type!==Pe&&Je.type===Pe?1:0);const De=_e.findIndex(We=>We.type!==Pe);return De>=0?De:_e.length};let ae=0;this.unevalEdges.length>0&&(ae=Y(this.unevalEdges,"none"),this.constructBridgeStructures(P,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:ae},this.tileToMeters)),C(W);const pe=_(),ve=_();if(this.unevalEdges.length>0){const _e=this.unevalEdges.splice(ae),Pe=Y(_e,"tunnel")+ae;this.unevalEdges.push(..._e),this.constructTunnelStructures(P,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:ae},{min:ae,max:Pe})}C(pe),P.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),C(ve),P.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),C(B),P.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,[-.1]),C(O),this.maskSegments=Ec.simpleSegment(0,ve.primitiveOffset,0,ve.primitiveLength),this.depthSegments=Ec.simpleSegment(0,B.primitiveOffset,0,B.primitiveLength),this.renderableBridgeSegments=Ec.simpleSegment(0,W.primitiveOffset,0,W.primitiveLength),this.renderableTunnelSegments=Ec.simpleSegment(0,pe.primitiveOffset,0,pe.primitiveLength),this.shadowCasterSegments=Ec.simpleSegment(0,O.primitiveOffset,0,O.primitiveLength)}update(g,_,C,P,O,B,W,Y){this.bridgeProgramConfigurations.updatePaintArrays(g,_,O,C,P,B,W,Y),this.tunnelProgramConfigurations.updatePaintArrays(g,_,O,C,P,B,W,Y)}upload(g){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=g.createVertexBuffer(this.vertexPositions,$as.members),this.vertexBufferNormal=g.createVertexBuffer(this.vertexNormals,Vas.members),this.indexBuffer=g.createIndexBuffer(this.indexArray),this.bridgeProgramConfigurations.upload(g),this.tunnelProgramConfigurations.upload(g))}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(g,_,C,P,O){const B=(W,Y)=>{for(let ae=0;aeQ(Ln,_[Mn].x,_[Mn].y,C[Mn]*Y),ve=H(),_e=H(),Pe=H(),De=H(),We=H(),Je=(Ln,Mn)=>{const Qn=W.get(M1.computePosHash(_[Mn])),fn=Qn.from,Pn=Qn.to;if(!fn||!Pn)return;pe(ve,fn),pe(_e,Mn),pe(Pe,Pn),Ne(De),$e(ve,_e)||(Ve(We,_e,ve),Te(De,We)),$e(Pe,_e)||(Ve(We,Pe,_e),le(De,De,Te(We,We)));const Dn=Ze(De);return Dn>0?ce(Ln,De,1/Dn):void 0};let rt=Number.POSITIVE_INFINITY;this.sortSubarray(P,O.min,O.max,(Ln,Mn)=>Ln.featureInfo.featureIndex-Mn.featureInfo.featureIndex);const xt=H(),ut=H(),St=H(),Rt=H(),Ft=H(),bs=H(),as=H(),ys=H(),hs=H(),ms=[H(),H(),H(),H()],vn=[H(),H(),H(),H()],Nn=[{coord:new es(0,0),height:0},{coord:new es(0,0),height:0}],Tn=(Ln,Mn)=>Ln>Mn;for(let Ln=O.min;Lnrt.featureInfo.featureIndex-xt.featureInfo.featureIndex;this.sortSubarray(P,O.min,O.max,Y),this.sortSubarray(P,B.min,B.max,Y);const ae=rt=>Te(rt,rt),pe=[{coord:new es(0,0),height:0},{coord:new es(0,0),height:0}],ve=(rt,xt)=>rtW.hash===Y.hash?Y.polygonIdx-W.polygonIdx:Y.hash>W.hash?1:-1);let C=0,P=0,O=0,B=_[C].polygonIdx;do P++,(P===_.length||_[C].hash!==_[P].hash)&&((P-C===1||_[P-1].polygonIdx!==B)&&(Oae.portalHashpe.hash?W++:pe.hash>ae.portalHash?Y++:(ae.type=pe.type,W++)}}}isOnBorder(g,_){return g<=0&&_<=0||g>=dr&&_>=dr}addFeatureSection(g,_,C,P){return g!==_&&(_=g,C.push({featureIndex:g,vertexStart:P.getVertexCount()}),P.clearVertexLookup()),_}sortSubarray(g,_,C,P){const O=g.slice(_,C);O.sort(P),g.splice(_,O.length,...O)}static computeEdgeHash(g,_){return(g.y===_.y&&g.x>_.x||g.y>_.y)&&([g,_]=[_,g]),BigInt(M1.computePosHash(g))<<32n|BigInt(M1.computePosHash(_))}static computePosHash(g){return((65535&g.x)<<16|65535&g.y)>>>0}}function sis(k,g){return k>g?1:k0))return _;_=_.left}}return null}contains(g){for(var _=this._root,C=this._compare;_;){var P=C(g,_.key);if(P===0)return!0;_=P<0?_.left:_.right}return!1}remove(g){var _=this.find(g);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(g){if(!g)return!1;if(this.splay(g),g.left)if(g.right){var _=this.minNode(g.right);_.parent!==g&&(this.replace(_,_.right),_.right=g.right,_.right.parent=_),this.replace(g,_),_.left=g.left,_.left.parent=_}else this.replace(g,g.left);else this.replace(g,g.right);return this._size--,!0}erase(g){var _=this.find(g);if(_){this.splay(_);var C=_.left,P=_.right,O=null;C&&(C.parent=null,O=this.maxNode(C),this.splay(O),this._root=O),P&&(C?O.right=P:this._root=P,P.parent=O),this._size--}}pop(){var g=this._root,_=null;if(g){for(;g.left;)g=g.left;_={key:g.key,data:g.data},this.remove(g.key)}return _}next(g){var _=g;if(_)if(_.right)for(_=_.right;_&&_.left;)_=_.left;else for(_=g.parent;_&&_.right===g;)g=_,_=_.parent;return _}prev(g){var _=g;if(_)if(_.left)for(_=_.left;_&&_.right;)_=_.right;else for(_=g.parent;_&&_.left===g;)g=_,_=_.parent;return _}forEach(g){for(var _=this._root,C=[],P=!1,O=0;!P;)_?(C.push(_),_=_.left):C.length>0?(g(_=C.pop(),O++),_=_.right):P=!0;return this}range(g,_,C,P){const O=[],B=this._compare;let W,Y=this._root;for(;O.length!==0||Y;)if(Y)O.push(Y),Y=Y.left;else{if(Y=O.pop(),W=B(Y.key,_),W>0)break;if(B(Y.key,g)>=0&&C.call(P,Y))return this;Y=Y.right}return this}keys(){for(var g=this._root,_=[],C=[],P=!1;!P;)g?(_.push(g),g=g.left):_.length>0?(g=_.pop(),C.push(g.key),g=g.right):P=!0;return C}values(){for(var g=this._root,_=[],C=[],P=!1;!P;)g?(_.push(g),g=g.left):_.length>0?(g=_.pop(),C.push(g.data),g=g.right):P=!0;return C}at(g){for(var _=this._root,C=[],P=!1,O=0;!P;)if(_)C.push(_),_=_.left;else if(C.length>0){if(_=C.pop(),O===g)return _;O++,_=_.right}else P=!0;return null}load(g=[],_=[],C=!1){if(this._size!==0)throw new Error("bulk-load: tree is not empty");const P=g.length;return C&&P8e(g,_,0,P-1,this._compare),this._root=M8e(null,g,_,0,P),this._size=P,this}min(){var g=this.minNode(this._root);return g?g.key:null}max(){var g=this.maxNode(this._root);return g?g.key:null}isEmpty(){return this._root===null}get size(){return this._size}static createTree(g,_,C,P,O){return new T8e(C,O).load(g,_,P)}}function M8e(k,g,_,C,P){const O=P-C;if(O>0){const B=C+Math.floor(O/2),W={key:g[B],data:_[B],parent:k};return W.left=M8e(W,g,_,C,B),W.right=M8e(W,g,_,B+1,P),W}return null}function P8e(k,g,_,C,P){if(_>=C)return;const O=k[_+C>>1];let B=_-1,W=C+1;for(;;){do B++;while(P(k[B],O)<0);do W--;while(P(k[W],O)>0);if(B>=W)break;let Y=k[B];k[B]=k[W],k[W]=Y,Y=g[B],g[B]=g[W],g[W]=Y}P8e(k,g,_,W,P),P8e(k,g,W+1,C,P)}const oit=11102230246251565e-32,Iv=134217729,nis=(3+8*oit)*oit;function L8e(k,g,_,C,P){let O,B,W,Y,ae=g[0],pe=C[0],ve=0,_e=0;pe>ae==pe>-ae?(O=ae,ae=g[++ve]):(O=pe,pe=C[++_e]);let Pe=0;if(veae==pe>-ae?(B=ae+O,W=O-(B-ae),ae=g[++ve]):(B=pe+O,W=O-(B-pe),pe=C[++_e]),O=B,W!==0&&(P[Pe++]=W);veae==pe>-ae?(B=O+ae,Y=B-O,W=O-(B-Y)+(ae-Y),ae=g[++ve]):(B=O+pe,Y=B-O,W=O-(B-Y)+(pe-Y),pe=C[++_e]),O=B,W!==0&&(P[Pe++]=W);for(;ve0:(C[0]-g[0])*(_[1]-g[1])-(_[0]-g[0])*(C[1]-g[1])>0}isAbove(g){return!this.isBelow(g)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return this.resultTransition!==0}clone(){const g=new dz(this.point,this.left,this.otherEvent,this.isSubject,this.type);return g.contourId=this.contourId,g.resultTransition=this.resultTransition,g.prevInResult=this.prevInResult,g.isExteriorRing=this.isExteriorRing,g.inOut=this.inOut,g.otherInOut=this.otherInOut,g}}function JS(k,g){return k[0]===g[0]&&k[1]===g[1]}function I8e(k,g,_){const C=function(P,O,B,W,Y,ae){const pe=(O-ae)*(B-Y),ve=(P-Y)*(W-ae),_e=pe-ve;if(pe===0||ve===0||pe>0!=ve>0)return _e;const Pe=Math.abs(pe+ve);return Math.abs(_e)>=33306690738754716e-32*Pe?_e:-function(De,We,Je,rt,xt,ut,St){let Rt,Ft,bs,as,ys,hs,ms,vn,Nn,Tn,Ln,Mn,Qn,fn,Pn,Dn,tr,mr;const ta=De-xt,Cr=Je-xt,Nr=We-ut,pr=rt-ut;fn=ta*pr,hs=Iv*ta,ms=hs-(hs-ta),vn=ta-ms,hs=Iv*pr,Nn=hs-(hs-pr),Tn=pr-Nn,Pn=vn*Tn-(fn-ms*Nn-vn*Nn-ms*Tn),Dn=Nr*Cr,hs=Iv*Nr,ms=hs-(hs-Nr),vn=Nr-ms,hs=Iv*Cr,Nn=hs-(hs-Cr),Tn=Cr-Nn,tr=vn*Tn-(Dn-ms*Nn-vn*Nn-ms*Tn),Ln=Pn-tr,ys=Pn-Ln,cz[0]=Pn-(Ln+ys)+(ys-tr),Mn=fn+Ln,ys=Mn-fn,Qn=fn-(Mn-ys)+(Ln-ys),Ln=Qn-Dn,ys=Qn-Ln,cz[1]=Qn-(Ln+ys)+(ys-Dn),mr=Mn+Ln,ys=mr-Mn,cz[2]=Mn-(mr-ys)+(Ln-ys),cz[3]=mr;let Kr=function(zo,Li){let $o=Li[0];for(let to=1;to<4;to++)$o+=Li[to];return $o}(0,cz),da=22204460492503146e-32*St;if(Kr>=da||-Kr>=da||(ys=De-ta,Rt=De-(ta+ys)+(ys-xt),ys=Je-Cr,bs=Je-(Cr+ys)+(ys-xt),ys=We-Nr,Ft=We-(Nr+ys)+(ys-ut),ys=rt-pr,as=rt-(pr+ys)+(ys-ut),Rt===0&&Ft===0&&bs===0&&as===0)||(da=11093356479670487e-47*St+nis*Math.abs(Kr),Kr+=ta*as+pr*Rt-(Nr*bs+Cr*Ft),Kr>=da||-Kr>=da))return Kr;fn=Rt*pr,hs=Iv*Rt,ms=hs-(hs-Rt),vn=Rt-ms,hs=Iv*pr,Nn=hs-(hs-pr),Tn=pr-Nn,Pn=vn*Tn-(fn-ms*Nn-vn*Nn-ms*Tn),Dn=Ft*Cr,hs=Iv*Ft,ms=hs-(hs-Ft),vn=Ft-ms,hs=Iv*Cr,Nn=hs-(hs-Cr),Tn=Cr-Nn,tr=vn*Tn-(Dn-ms*Nn-vn*Nn-ms*Tn),Ln=Pn-tr,ys=Pn-Ln,P1[0]=Pn-(Ln+ys)+(ys-tr),Mn=fn+Ln,ys=Mn-fn,Qn=fn-(Mn-ys)+(Ln-ys),Ln=Qn-Dn,ys=Qn-Ln,P1[1]=Qn-(Ln+ys)+(ys-Dn),mr=Mn+Ln,ys=mr-Mn,P1[2]=Mn-(mr-ys)+(Ln-ys),P1[3]=mr;const $a=L8e(4,cz,4,P1,lit);fn=ta*as,hs=Iv*ta,ms=hs-(hs-ta),vn=ta-ms,hs=Iv*as,Nn=hs-(hs-as),Tn=as-Nn,Pn=vn*Tn-(fn-ms*Nn-vn*Nn-ms*Tn),Dn=Nr*bs,hs=Iv*Nr,ms=hs-(hs-Nr),vn=Nr-ms,hs=Iv*bs,Nn=hs-(hs-bs),Tn=bs-Nn,tr=vn*Tn-(Dn-ms*Nn-vn*Nn-ms*Tn),Ln=Pn-tr,ys=Pn-Ln,P1[0]=Pn-(Ln+ys)+(ys-tr),Mn=fn+Ln,ys=Mn-fn,Qn=fn-(Mn-ys)+(Ln-ys),Ln=Qn-Dn,ys=Qn-Ln,P1[1]=Qn-(Ln+ys)+(ys-Dn),mr=Mn+Ln,ys=mr-Mn,P1[2]=Mn-(mr-ys)+(Ln-ys),P1[3]=mr;const ja=L8e($a,lit,4,P1,cit);fn=Rt*as,hs=Iv*Rt,ms=hs-(hs-Rt),vn=Rt-ms,hs=Iv*as,Nn=hs-(hs-as),Tn=as-Nn,Pn=vn*Tn-(fn-ms*Nn-vn*Nn-ms*Tn),Dn=Ft*bs,hs=Iv*Ft,ms=hs-(hs-Ft),vn=Ft-ms,hs=Iv*bs,Nn=hs-(hs-bs),Tn=bs-Nn,tr=vn*Tn-(Dn-ms*Nn-vn*Nn-ms*Tn),Ln=Pn-tr,ys=Pn-Ln,P1[0]=Pn-(Ln+ys)+(ys-tr),Mn=fn+Ln,ys=Mn-fn,Qn=fn-(Mn-ys)+(Ln-ys),Ln=Qn-Dn,ys=Qn-Ln,P1[1]=Qn-(Ln+ys)+(ys-Dn),mr=Mn+Ln,ys=mr-Mn,P1[2]=Mn-(mr-ys)+(Ln-ys),P1[3]=mr;const Pi=L8e(ja,cit,4,P1,dit);return dit[Pi-1]}(P,O,B,W,Y,ae,Pe)}(k[0],k[1],g[0],g[1],_[0],_[1]);return C>0?-1:C<0?1:0}function VE(k,g){const _=k.point,C=g.point;return _[0]>C[0]?1:_[0]C[1]?1:-1:function(P,O,B){return P.left!==O.left?P.left?1:-1:I8e(B,P.otherEvent.point,O.otherEvent.point)!==0?P.isBelow(O.otherEvent.point)?-1:1:!P.isSubject&&O.isSubject?1:-1}(k,g,_)}function HE(k,g,_){const C=new dz(g,!1,k,k.isSubject),P=new dz(g,!0,k.otherEvent,k.isSubject);return JS(k.point,k.otherEvent.point)&&console.warn("what is that, a collapsed segment?",k),C.contourId=P.contourId=k.contourId,VE(P,k.otherEvent)>0&&(k.otherEvent.left=!0,P.left=!1),k.otherEvent.otherEvent=P,k.otherEvent=C,_.push(P),_.push(C),_}function Lae(k,g){return k[0]*g[1]-k[1]*g[0]}function R8e(k,g){return k[0]*g[0]+k[1]*g[1]}function D8e(k,g,_){const C=function(Y,ae,pe,ve){const _e=[ae[0]-Y[0],ae[1]-Y[1]],Pe=[ve[0]-pe[0],ve[1]-pe[1]];function De(bs,as,ys){return[bs[0]+as*ys[0],bs[1]+as*ys[1]]}const We=[pe[0]-Y[0],pe[1]-Y[1]];let Je=Lae(_e,Pe),rt=Je*Je;const xt=R8e(_e,_e);if(rt>0){const bs=Lae(We,Pe)/Je;if(bs<0||bs>1)return null;const as=Lae(We,_e)/Je;return as<0||as>1?null:bs===0||bs===1?[De(Y,bs,_e)]:as===0||as===1?[De(pe,as,Pe)]:[De(Y,bs,_e)]}if(Je=Lae(We,_e),rt=Je*Je,rt>0)return null;const ut=R8e(_e,We)/xt,St=ut+R8e(_e,Pe)/xt,Rt=Math.min(ut,St),Ft=Math.max(ut,St);return Rt<=1&&Ft>=0?Rt===1?[De(Y,Rt>0?Rt:0,_e)]:Ft===0?[De(Y,Ft<1?Ft:1,_e)]:[De(Y,Rt>0?Rt:0,_e),De(Y,Ft<1?Ft:1,_e)]:null}(k.point,k.otherEvent.point,g.point,g.otherEvent.point),P=C?C.length:0;if(P===0||P===1&&(JS(k.point,g.point)||JS(k.otherEvent.point,g.otherEvent.point))||P===2&&k.isSubject===g.isSubject)return 0;if(P===1)return!JS(k.point,C[0])&&!JS(k.otherEvent.point,C[0])&&HE(k,C[0],_),!JS(g.point,C[0])&&!JS(g.otherEvent.point,C[0])&&HE(g,C[0],_),1;const O=[];let B=!1,W=!1;return JS(k.point,g.point)?B=!0:VE(k,g)===1?O.push(g,k):O.push(k,g),JS(k.otherEvent.point,g.otherEvent.point)?W=!0:VE(k.otherEvent,g.otherEvent)===1?O.push(g.otherEvent,k.otherEvent):O.push(k.otherEvent,g.otherEvent),B&&W||B?(g.type=1,k.type=g.inOut===k.inOut?2:3,B&&!W&&HE(O[1].otherEvent,O[0].point,_),2):W?(HE(O[0],O[1].point,_),3):O[0]!==O[3].otherEvent?(HE(O[0],O[1].point,_),HE(O[1],O[2].point,_),3):(HE(O[0],O[1].point,_),HE(O[3].otherEvent,O[2].point,_),3)}function ris(k,g){if(k===g)return 0;if(I8e(k.point,k.otherEvent.point,g.point)!==0||I8e(k.point,k.otherEvent.point,g.otherEvent.point)!==0)return JS(k.point,g.point)?k.isBelow(g.otherEvent.point)?-1:1:k.point[0]===g.point[0]?k.point[1](g.contourId??0)?1:-1}return VE(k,g)===1?1:-1}class ais{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return this.holeOf==null}}function iis(k,g,_,C){let P,O=k+1,B=g[k].point;const W=g.length;for(OC;)O--;return O}function ois(k,g,_){const C=new ais;if(k.prevInResult!=null){const P=k.prevInResult,O=P.outputContourId;if(P.resultTransition>0){const B=g[O];if(B.holeOf!=null){const W=B.holeOf;g[W].holeIds.push(_),C.holeOf=W,C.depth=g[O].depth}else g[O].holeIds.push(_),C.holeOf=O,C.depth=g[O].depth+1}else C.holeOf=null,C.depth=g[O].depth}else C.holeOf=null,C.depth=0;return C}const hit=Math.max,mit=Math.min;let Iae=0;function pit(k,g,_,C,P,O){let B,W,Y,ae,pe,ve;for(B=0,W=k.length-1;B0?ve.left=!0:pe.left=!0;const _e=Y[0],Pe=Y[1];P[0]=mit(P[0],_e),P[1]=mit(P[1],Pe),P[2]=hit(P[2],_e),P[3]=hit(P[3],Pe),C.push(pe),C.push(ve)}}const Rae=[];function fit(k,g,_){let C=k,P=g;typeof k[0][0][0]=="number"&&(C=[k]),typeof g[0][0][0]=="number"&&(P=[g]);let O=function(_e,Pe,De){let We=null;return _e.length*Pe.length===0&&(De===0?We=Rae:De===2?We=_e:(De===1||De===3)&&(We=_e.length===0?Pe:_e)),We}(C,P,_);if(O)return O===Rae?null:O;const B=[1/0,1/0,-1/0,-1/0],W=[1/0,1/0,-1/0,-1/0],Y=function(_e,Pe,De,We,Je){const rt=new nm(void 0,VE);let xt,ut,St,Rt,Ft,bs;for(St=0,Rt=_e.length;StWe[2]||We[0]>De[2]||De[1]>We[3]||We[1]>De[3])&&(Je===0?rt=Rae:Je===2?rt=_e:(Je===1||Je===3)&&(rt=_e.concat(Pe))),rt}(C,P,B,W,_),O)return O===Rae?null:O;const ae=function(_e,Pe,De,We,Je,rt){const xt=new T8e(ris),ut=[],St=Math.min(We[2],Je[2]);let Rt,Ft,bs;for(;_e.length!==0;){let as=_e.pop();if(ut.push(as),rt===0&&as.point[0]>St||rt===2&&as.point[0]>We[2])break;if(as.left){Ft=Rt=xt.insert(as),bs=xt.minNode(),Rt=Rt!==bs?xt.prev(Rt):null,Ft=xt.next(Ft);const ys=Rt?Rt.key:null;let hs;if(QW(as,ys,rt),Ft&&D8e(as,Ft.key,_e)===2&&(QW(as,ys,rt),QW(Ft.key,as,rt)),Rt&&D8e(Rt.key,as,_e)===2){let ms=Rt;ms=ms!==bs?xt.prev(ms):null,hs=ms?ms.key:null,QW(ys,hs,rt),QW(as,ys,rt)}}else as=as.otherEvent,Ft=Rt=xt.find(as),Rt&&Ft&&(Rt=Rt!==bs?xt.prev(Rt):null,Ft=xt.next(Ft),xt.remove(as),Ft&&Rt&&D8e(Rt.key,Ft.key,_e))}return ut}(Y,0,0,B,W,_),pe=function(_e){let Pe,De;const We=function(xt){let ut,St,Rt,Ft,bs;const as=[];for(St=0,Rt=xt.length;St{Je[bs]=!0,bs=We.length)&&We[Rt];);rt.push(ut)}return rt}(ae),ve=[];for(let _e=0;_e{B.push(new es(ve,Y+(ve-W)/(ae-W)*(pe-Y)))}:(B,W,Y,ae,pe,ve)=>{B.push(new es(W+(ve-Y)/(pe-Y)*(ae-W),ve))};for(const B of k){const W=[];for(const Y of B){if(Y.length<=2)continue;const ae=[];for(let _e=0;_eg&&O(ae,Pe,De,We,Je,g):rt>_?xt<_&&O(ae,Pe,De,We,Je,_):ae.push(Y[_e]),xt=g&&O(ae,Pe,De,We,Je,g),xt>_&&rt<=_&&O(ae,Pe,De,We,Je,_)}let pe=Y[Y.length-1];const ve=C===0?pe.x:pe.y;ve>=g&&ve<=_&&ae.push(pe),ae.length&&(pe=ae[ae.length-1],ae[0].x===pe.x&&ae[0].y===pe.y||ae.push(ae[0]),W.push(ae))}W.length&&P.push(W)}return P}function lis(k,g){const _=fit(O8e(k),O8e([g]),0);return _==null?[]:git(_)}function cis(k,g,_=0){let P=O8e(k,65536);const O=[];for(;g.valid();g.next()){const[B,W]=g.get();let Y=B.x*65536,ae=B.y*65536,pe=W.x*65536,ve=W.y*65536;const _e=pe-Y,Pe=ve-ae,De=Math.hypot(_e,Pe);if(De===0)continue;Y-=_e*_,ae-=Pe*_,pe+=_e*_,ve+=Pe*_;const We=Math.trunc(Pe/De*3),Je=-Math.trunc(_e/De*3);O.push([[[Y,ae],[pe,ve],[pe+We,ve+Je],[Y+We,ae+Je],[Y,ae]]])}return O.length>0&&(P=fit(P,O,2)),git(P,1/65536,128)}function O8e(k,g=1){return[k.map(_=>_.map(C=>[C.x*g,C.y*g]))]}function git(k,g=1,_){return k.map(C=>C.map((P,O)=>{const B=P.map(W=>{let Y=W[0],ae=W[1];return _&&(Y=Math.round(Y/_)*_,ae=Math.round(ae/_)*_),new es(Y*g,ae*g)._round()});return O>0&&B.reverse(),B}))}class F8e{constructor(g,_){this.layoutVertexArray=new Qi,this.indexArray=new Ru,this.lineIndexArray=new Vb,this.triangleSegments=new Ec,this.lineSegments=new Ec,this.programConfigurations=new st(g.layers,{zoom:g.zoom,lut:g.lut}),this.uploaded=!1,_&&(this.elevatedLayoutVertexArray=new Bl)}update(g,_,C,P,O,B,W,Y){this.programConfigurations.updatePaintArrays(g,_,O,C,P,B,W,Y)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(g){this.uploaded||(this.layoutVertexBuffer=g.createVertexBuffer(this.layoutVertexArray,Uas.members),this.indexBuffer=g.createIndexBuffer(this.indexArray),this.lineIndexBuffer=g.createIndexBuffer(this.lineIndexArray),this.elevatedLayoutVertexArray&&this.elevatedLayoutVertexArray.length>0&&(this.elevatedLayoutVertexBuffer=g.createVertexBuffer(this.elevatedLayoutVertexArray,qas.members))),this.programConfigurations.upload(g),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy(),this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.lineIndexBuffer.destroy(),this.programConfigurations.destroy(),this.triangleSegments.destroy(),this.lineSegments.destroy())}populatePaintArrays(g,_,C,P,O,B,W){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,g,_,C,P,O,B,void 0,W)}}class Oae{constructor(g){this.zoom=g.zoom,this.pixelRatio=g.pixelRatio,this.overscaling=g.overscaling,this.layers=g.layers,this.layerIds=this.layers.map(_=>_.fqid),this.index=g.index,this.hasPattern=!1,this.patternFeatures=[],this.lut=g.lut,this.bufferData=new F8e(g,!1),this.elevationBufferData=new F8e(g,!0),this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.projection=g.projection,this.elevationMode=this.layers[0].layout.get("fill-elevation-reference"),this.sourceLayerIndex=g.sourceLayerIndex,this.worldview=g.worldview,this.hasAppearances=null}updateFootprints(g,_){}updateAppearances(g,_,C,P){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(g,_,C,P){this.hasPattern=A8e("fill",this.layers,this.pixelRatio,_);const O=this.layers[0].layout.get("fill-sort-key"),B=[];for(const{feature:W,id:Y,index:ae,sourceLayerIndex:pe}of g){const ve=this.layers[0]._featureFilter.needGeometry,_e=eo(W,ve);if(!this.layers[0]._featureFilter.filter(new Oi(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),_e,C))continue;const Pe=O?O.evaluate(_e,{},C,_.availableImages):void 0,De={id:Y,properties:W.properties,type:W.type,sourceLayerIndex:pe,index:ae,geometry:ve?_e.geometry:Ha(W,C,P),patterns:{},sortKey:Pe};B.push(De)}O&&B.sort((W,Y)=>W.sortKey-Y.sortKey);for(const W of B){const{geometry:Y,index:ae,sourceLayerIndex:pe}=W;if(this.hasPattern){const ve=E8e("fill",this.layers,W,this.zoom,this.pixelRatio,_);this.patternFeatures.push(ve)}else this.addFeature(W,Y,ae,C,{},_.availableImages,_.brightness,_.elevationFeatures);_.featureIndex.insert(g[ae].feature,Y,ae,pe,this.index)}}update(g,_,C,P,O,B,W){this.bufferData.update(g,_,C,P,O,B,W,this.worldview),this.elevationBufferData.update(g,_,C,P,O,B,W,this.worldview),this.elevatedStructures&&this.elevatedStructures.update(g,_,C,P,O,B,W,this.worldview)}addFeatures(g,_,C,P,O,B){for(const W of this.patternFeatures)this.addFeature(W,W.geometry,W.index,_,C,P,B,g.elevationFeatures)}isEmpty(){return this.bufferData.isEmpty()&&this.elevationBufferData.isEmpty()}uploadPending(){return!this.uploaded||this.bufferData.needsUpload()||this.elevationBufferData.needsUpload()}upload(g){this.bufferData.upload(g),this.elevationBufferData.upload(g),this.elevatedStructures&&this.elevatedStructures.upload(g)}destroy(){this.bufferData.destroy(),this.elevationBufferData.destroy(),this.elevatedStructures&&this.elevatedStructures.destroy()}addFeature(g,_,C,P,O,B=[],W,Y){const ae=ZW(_,500);this.elevationMode!=="none"?this.addElevatedRoadFeature(g,ae,P,C,Y):this.addGeometry(ae,this.bufferData),this.bufferData.populatePaintArrays(g,C,O,B,P,W,this.worldview),this.elevationBufferData.populatePaintArrays(g,C,O,B,P,W,this.worldview)}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}setEvaluatedPortalGraph(g,_,C,P,O){this.elevatedStructures&&(this.elevatedStructures.construct(g),this.elevatedStructures.populatePaintArrays(_,C,P,O,this.worldview))}addElevatedRoadFeature(g,_,C,P,O){const B=new Array,W=Fc.getElevationFeature(g,O);if(!W)return void this.addGeometry(_,this.bufferData);{const ae=this.clipPolygonsToTile(_,1);ae.length>0&&B.push({polygons:ae,elevationFeature:W,elevationTileID:C})}const Y={guardRailEnabled:this.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(g,{},C),featureIndex:P};for(const ae of B)if(ae.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new M1(ae.elevationTileID,this.layers,this.zoom,this.lut));const ve=ae.elevationFeature.isTunnel();let _e=0;g.properties.hasOwnProperty(Mc)&&(_e=+g.properties[Mc]),this.elevatedStructures.addPortalCandidates(ae.elevationFeature.id,ae.polygons,ve,ae.elevationFeature,_e)}ae.elevationFeature.constantHeight==null&&(ae.polygons=this.prepareElevatedPolygons(ae.polygons,ae.elevationFeature,ae.elevationTileID));const pe=new Kc(C,ae.elevationTileID);this.addElevatedGeometry(ae.polygons,pe,ae.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,P,Y)}}addElevatedGeometry(g,_,C,P,O,B){const W={elevation:C,elevationSampler:_,bias:P,index:O,featureInfo:B},[Y,ae]=this.addGeometry(g,this.elevationBufferData,W);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:Y,max:ae}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,Y),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,ae))}addGeometry(g,_,C){let P=Number.POSITIVE_INFINITY,O=Number.NEGATIVE_INFINITY,B=null;C&&(B=C.elevationSampler.constantElevation(C.elevation,C.bias),B!=null&&(P=B,O=B));const W=(Y,ae,pe)=>{if(C!=null)if(ae.push(Y),B!=null)_.elevatedLayoutVertexArray.emplaceBack(B),pe.push(B);else{const ve=C.elevationSampler.pointElevation(Y,C.elevation,C.bias);_.elevatedLayoutVertexArray.emplaceBack(ve),pe.push(ve),P=Math.min(P,ve),O=Math.max(O,ve)}};for(const Y of g){let ae=0;for(const ut of Y)ae+=ut.length;const pe=_.triangleSegments.prepareSegment(ae,_.layoutVertexArray,_.indexArray),ve=pe.vertexLength,_e=[],Pe=[],De=[],We=[],Je=[],rt=_.layoutVertexArray.length;for(const ut of Y){if(ut.length===0)continue;ut!==Y[0]&&Pe.push(_e.length/2);const St=_.lineSegments.prepareSegment(ut.length,_.layoutVertexArray,_.lineIndexArray),Rt=St.vertexLength;C&&Je.push(_.layoutVertexArray.length-rt),W(ut[0],De,We),_.layoutVertexArray.emplaceBack(ut[0].x,ut[0].y),_.lineIndexArray.emplaceBack(Rt+ut.length-1,Rt),_e.push(ut[0].x),_e.push(ut[0].y);for(let Ft=1;Ft0&&C&&this.elevationMode==="hd-road-base"){const ut=C.elevation.isTunnel(),St=C.elevation.safeArea,Rt=this.elevatedStructures.addVertices(De,We);this.elevatedStructures.addTriangles(xt,Rt,ut);const Ft=Je.length;if(Ft>0){for(let bs=0;bs=C&&Pe.max.x<=O&&Pe.min.y>=P&&Pe.max.y<=B?Y:ae).push(_e)}if(Y.length===g.length)return g;const pe=[new es(C,P),new es(O,P),new es(O,B),new es(C,B),new es(C,P)],ve=Y;for(const _e of ae)ve.push(...lis(_e,pe));return ve}}let xit,yit,vit,bit;wr(Oae,"FillBucket",{omit:["layers","patternFeatures"]}),wr(F8e,"FillBufferData"),wr(M1,"ElevatedStructures");class Fae{constructor(g,_,C,P){if(this.triangleCount=_.length/3,this.min=new es(0,0),this.max=new es(0,0),this.xScale=0,this.yScale=0,this.cellsX=0,this.cellsY=0,this.cells=[],this.payload=[],this.triangleCount===0||g.length===0)return;const[O,B]=[g[0].clone(),g[0].clone()];for(let ve=1;veve.cellIdx-_e.cellIdx||ve.triIdx-_e.triIdx);let pe=0;for(;pethis.max.x||this.min.x>g.x||g.y>this.max.y||this.min.y>g.y)return;const C=e5(g.x-this.min.x,this.xScale,this.cellsX),P=e5(g.y-this.min.y,this.yScale,this.cellsY),O=this.cells[P*this.cellsX+C];if(O){this._lazyInitLookup();for(let B=0;Bthis.max.x||this.min.x>_.x||g.y>this.max.y||this.min.y>_.y)return;this._lazyInitLookup();const P=e5(g.x-this.min.x,this.xScale,this.cellsX),O=e5(_.x-this.min.x,this.xScale,this.cellsX),B=e5(g.y-this.min.y,this.yScale,this.cellsY),W=e5(_.y-this.min.y,this.yScale,this.cellsY);for(let Y=B;Y<=W;Y++)for(let ae=P;ae<=O;ae++){const pe=this.cells[Y*this.cellsX+ae];if(pe)for(let ve=0;ve_.fqid),this.index=g.index,this.hasPattern=!1,this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.footprints=[],this.worldview=g.worldview,this.hasAppearances=null}updateFootprints(g,_){for(const C of this.footprints)_.push({footprint:C,id:g})}updateAppearances(g,_,C,P){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(g,_,C,P){const O=[];for(const{feature:B,id:W,index:Y,sourceLayerIndex:ae}of g){const pe=this.layers[0]._featureFilter.needGeometry,ve=eo(B,pe);if(!this.layers[0]._featureFilter.filter(new Oi(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),ve,C))continue;const _e={id:W,properties:B.properties,type:B.type,sourceLayerIndex:ae,index:Y,geometry:pe?ve.geometry:Ha(B,C,P),patterns:{}};O.push(_e)}for(const B of O){const{geometry:W,index:Y,sourceLayerIndex:ae}=B;this.addFeature(B,W,Y,C,{},_.availableImages,_.brightness),_.featureIndex.insert(g[Y].feature,W,Y,ae,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(g){}update(g,_,C,P,O,B,W){}destroy(){}addFeature(g,_,C,P,O,B=[],W){for(const Y of ZW(_,2)){const ae=[],pe=[],ve=[],_e=new es(1/0,1/0),Pe=new es(-1/0,-1/0);for(const Je of Y)if(Je.length!==0){Je!==Y[0]&&ve.push(pe.length/2);for(let rt=0;rtg.max.x||k.max.xg.max.y||k.max.ynew es((Y.x+O.x*dr)*W-B.x*dr,(Y.y+O.y*dr)*W-B.y*dr))}return B8e(_,P,k.indices,0,k.indices.length,0,0)}function Sit(k,g,_,C){const P=Math.pow(2,C.z-_.z);return new es((k+_.x*dr)*P-C.x*dr,(g+_.y*dr)*P-C.y*dr)}function Cit(k,g){const _=[];g.grid.queryPoint(k,_);const C=g.indices,P=g.vertices;for(let O=0;O<_.length;O++){const B=_[O];if(Dy([P[C[3*B+0]],P[C[3*B+1]],P[C[3*B+2]]],k))return!0}return!1}const Uae={None:0,Model:1,Symbol:2,FillExtrusion:4},U8e=[new es(0,0),new es(dr,0),new es(dr,dr),new es(0,dr)];function Ait(k,g){const _=[];let C=[];if(!g||k.length<2)return[k];if(k.length===2)return ZS(k[0],k[1],U8e)?[k]:[];for(let P=0;P0&&(C.length>1&&_.push(C),C=[])}return C.length>1&&_.push(C),_}const q8e=vi.types,bis=["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"],_is=["fill-extrusion-flood-light-ground-radius"],wis=Math.pow(2,13),jis=Math.pow(2,15)-1,qae=new es(0,1),H3=2147483648,$ae=1073741824;function eK(k,g,_,C,P,O,B,W){k.emplaceBack((g<<1)+B,(_<<1)+O,(Math.floor(C*wis)<<1)+P,Math.round(W))}function tK(k,g,_){k.emplaceBack(g.x*dr,g.y*dr,_?1:0)}function Vae(k,g,_,C,P,O){k.emplaceBack(g.x,g.y,(_.x<<1)+C,(_.y<<1)+P,O)}function sK(k,g,_){k.emplaceBack(g.x,g.y,g.z,_[0]*16384,_[1]*16384,_[2]*16384)}class Eit{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class $8e{constructor(){this.centroidXY=new es(0,0),this.vertexArrayOffset=0,this.vertexCount=0,this.groundVertexArrayOffset=0,this.groundVertexCount=0,this.flags=0,this.footprintSegIdx=-1,this.footprintSegLen=0,this.polygonSegIdx=-1,this.polygonSegLen=0,this.min=new es(Number.MAX_VALUE,Number.MAX_VALUE),this.max=new es(-Number.MAX_VALUE,-Number.MAX_VALUE),this.height=0,this.buildingId=0,this.groupCentroidPos=new es(0,0)}span(){return new es(this.max.x-this.min.x,this.max.y-this.min.y)}}class V8e{constructor(){this.acc=new es(0,0),this.accCount=0,this.centroidDataIndex=0}startRing(g,_){g.min.x===Number.MAX_VALUE&&(g.min.x=g.max.x=_.x,g.min.y=g.max.y=_.y)}appendEdge(g,_,C){this.accCount++,this.acc._add(_);let P=!!this.borders;_.xg.max.x&&(g.max.x=_.x,P=!0),_.yg.max.y&&(g.max.y=_.y,P=!0),((_.x===0||_.x===dr)&&_.x===C.x)!=((_.y===0||_.y===dr)&&_.y===C.y)&&this.processBorderOverlap(_,C),P&&this.checkBorderIntersection(_,C)}checkBorderIntersection(g,_){_.x<0!=g.x<0&&this.addBorderIntersection(0,Es(_.y,g.y,(0-_.x)/(g.x-_.x))),_.x>dr!=g.x>dr&&this.addBorderIntersection(1,Es(_.y,g.y,(dr-_.x)/(g.x-_.x))),_.y<0!=g.y<0&&this.addBorderIntersection(2,Es(_.x,g.x,(0-_.y)/(g.y-_.y))),_.y>dr!=g.y>dr&&this.addBorderIntersection(3,Es(_.x,g.x,(dr-_.y)/(g.y-_.y)))}addBorderIntersection(g,_){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[g];_C[1]&&(C[1]=_)}processBorderOverlap(g,_){if(g.x===_.x){if(g.y===_.y)return;const C=g.x===0?0:1;this.addBorderIntersection(C,_.y),this.addBorderIntersection(C,g.y)}else{const C=g.y===0?2:3;this.addBorderIntersection(C,_.x),this.addBorderIntersection(C,g.x)}}centroid(){return this.accCount===0?new es(0,0):new es(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((g,_)=>g+ +(_[0]!==Number.MAX_VALUE),0):0}}function Tit(k,g){const _=k.add(g)._unit(),C=mt(k.x*_.x+k.y*_.y,-1,1);var P,O,B;return B=Math.acos(C),Math.min(4,Math.max(-4,Math.tan(B)))/4*jis*((P=k).x*(O=g).y-P.y*O.x<0?-1:1)}const Nis=[k=>k.x<0,k=>k.x>dr,k=>k.y<0,k=>k.y>dr];function kis(k,g,_,C){const P=[4];if(C===0)return P;_._mult(C);const O=k.sub(_),B=g.sub(_),W=[k,g,O,B];for(let Y=0;Y<4;Y++)for(const ae of W)if(Nis[Y](ae)){P.push(Y);break}return P}class H8e{constructor(g){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new jL,this.indexArray=new Ru,this.programConfigurations=new st(g.layers,{zoom:g.zoom,lut:g.lut},_=>_is.includes(_)),this._segments=new Ec,this.hiddenByLandmarkVertexArray=new sz,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new Ec}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(g,_,C,P=!1){const O=g.length;if(O>2){let B=Math.max(0,this._segments.get().length-1);const W=this._segments._prepareSegment(4*O,this.vertexArray.length,2*this._segmentToGroundQuads[B].length);let Y;B!==this._segments.get().length-1&&(B++,this._segmentToGroundQuads[B]=[],this._segmentToRegionTriCounts[B]=[0,0,0,0,0]);{const ae=g[0],pe=g[1];Y=Tit(ae.sub(g[O-1])._perp()._unit(),pe.sub(ae)._perp()._unit())}for(let ae=0;aeP.region-O.region);for(let C=0;C<_;C++){const P=this._segmentToGroundQuads[C],O=g[C],B=this._segmentToRegionTriCounts[C];B.reduce((Y,ae)=>Y+ae,0);let W=0;for(let Y=0;Y<=4;Y++){const ae=B[Y];if(ae!==0){let pe=this.regionSegments[Y];pe||(pe=this.regionSegments[Y]=new Ec);const ve={vertexOffset:O.vertexOffset,primitiveOffset:O.primitiveOffset+W,vertexLength:O.vertexLength,primitiveLength:ae};pe.get().push(ve)}W+=ae}for(let Y=0;Y0?this.hiddenByLandmarkVertexBuffer=g.createVertexBuffer(this.hiddenByLandmarkVertexArray,fis.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 g=0;g<=4;g++){const _=this.regionSegments[g];_&&_.destroy()}}}}class Hae{constructor(g){this.zoom=g.zoom,this.canonical=g.canonical,this.overscaling=g.overscaling,this.layers=g.layers,this.pixelRatio=g.pixelRatio,this.layerIds=this.layers.map(_=>_.fqid),this.index=g.index,this.hasPattern=!1,this.edgeRadius=0,this.projection=g.projection,this.activeReplacements=[],this.replacementUpdateTime=0,this.centroidData=[],this.footprintIndices=new Ru,this.footprintVertices=new Qi,this.footprintSegments=[],this.layoutVertexArray=new qb,this.centroidVertexArray=new Nae,this.wallVertexArray=new BW,this.indexArray=new Ru,this.programConfigurations=new st(g.layers,{zoom:g.zoom,lut:g.lut},_=>bis.includes(_)),this.segments=new Ec,this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.groundEffect=new H8e(g),this.maxHeight=0,this.partLookup={},this.triangleSubSegments=[],this.polygonSegments=[],this.buildingGroups=new Map,this.worldview=g.worldview,this.hasAppearances=null}updateFootprints(g,_){}updateAppearances(g,_,C,P){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(g,_,C,P){this.features=[],this.hasPattern=A8e("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=Vn(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:O,id:B,index:W,sourceLayerIndex:Y}of g){const ae=this.layers[0]._featureFilter.needGeometry,pe=eo(O,ae);if(!this.layers[0]._featureFilter.filter(new Oi(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),pe,C))continue;const ve={id:B,sourceLayerIndex:Y,index:W,geometry:ae?pe.geometry:Ha(O,C,P),properties:O.properties,type:O.type,patterns:{}},_e=this.layoutVertexArray.length,Pe=q8e[ve.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:O.id,feature:E8e("fill-extrusion",this.layers,ve,this.zoom,this.pixelRatio,_)});else if(this.wallMode)for(const De of ve.geometry)for(const We of Ait(De,Pe))this.addFeature(O.id,ve,[We],W,C,{},_.availableImages,P,_.brightness);else this.addFeature(O.id,ve,ve.geometry,W,C,{},_.availableImages,P,_.brightness);_.featureIndex.insert(O,ve.geometry,W,Y,this.index,_e)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(g,_,C,P,O,B){for(const{featureId:W,feature:Y}of this.features){const ae=q8e[Y.type]==="Polygon",{geometry:pe}=Y;if(this.wallMode)for(const ve of pe)for(const _e of Ait(ve,ae))this.addFeature(W,Y,[_e],Y.index,_,C,P,O,B);else this.addFeature(W,Y,pe,Y.index,_,C,P,O,B)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(g,_,C,P,O,B,W){this.programConfigurations.updatePaintArrays(g,_,O,C,P,B,W,this.worldview),this.groundEffect.update(g,_,O,C,P,B,W,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(g){this.uploaded||(this.layoutVertexBuffer=g.createVertexBuffer(this.layoutVertexArray,xis),this.indexBuffer=g.createIndexBuffer(this.indexArray),this.wallVertexBuffer=g.createVertexBuffer(this.wallVertexArray,pis.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=g.createVertexBuffer(this.layoutVertexExtArray,gis.members,!0)),this.groundEffect.upload(g)),this.groundEffect.uploadPaintProperties(g),this.programConfigurations.upload(g),this.uploaded=!0}uploadCentroid(g){this.groundEffect.uploadHiddenByLandmark(g),this.needsCentroidUpdate&&(!this.centroidVertexBuffer&&this.centroidVertexArray.length>0?this.centroidVertexBuffer=g.createVertexBuffer(this.centroidVertexArray,mis.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(g,_,C,P,O,B,W,Y,ae){const pe=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(_,{})/this.tileToMeter,ve=[new es(0,0),new es(dr,dr)],_e=Y.projection,Pe=_e.name==="globe",De=this.wallMode||q8e[_.type]==="Polygon",We=new V8e;We.centroidDataIndex=this.centroidData.length;const Je=new $8e;Je.buildingId=g,_.properties&&_.properties.hasOwnProperty("building_id")&&(Je.buildingId=Number(_.properties.building_id)),We.buildingId=Je.buildingId;const rt=this.layers[0].paint.get("fill-extrusion-base").evaluate(_,{},O)<=0,xt=this.layers[0].paint.get("fill-extrusion-height").evaluate(_,{},O);let ut;if(Je.height=xt,Je.vertexArrayOffset=this.layoutVertexArray.length,Je.groundVertexArrayOffset=this.groundEffect.vertexArray.length,Pe&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new Z9),this.wallMode){if(Pe)return void qr("Non zero fill-extrusion-line-width is not yet supported on globe.");if(C.length!==1)return;ut=function(hs){const ms=hs[0].x===hs[hs.length-1].x&&hs[0].y===hs[hs.length-1].y;(function(Nr){let pr=0;const Kr=Nr.length;for(let da=0;da=0})(hs)||(hs=hs.reverse());const Nn={geometry:[],joinNormals:[],indices:[]},Tn=[],Ln=[],Mn=[];let Qn=hs.length;for(;Qn>=2&&hs[Qn-1].equals(hs[Qn-2]);)Qn--;if(Qn<(ms?3:2))return Nn;let fn,Pn,Dn,tr,mr,ta=0;for(;ta0;let ja="miter";const Pi=2;ja==="miter"&&da>Pi&&(ja="bevel"),ja==="bevel"&&(da>100&&(ja="flipbevel"),da{const jl=new es(Li.x,Li.y),el=new es(Li.x,Li.y);jl.x+=$o.x*mu,jl.y+=$o.y*mu,el.x-=$o.x*Math.max(to,1),el.y-=$o.y*Math.max(to,1),Mn.push($o),Tn.push(jl),Ln.push(el)};if(ja==="miter")pr._mult(da),zo(fn,pr,0,0);else if(ja==="flipbevel")pr=mr.mult(-1),zo(fn,pr,0,0),zo(fn,pr.mult(-1),0,0);else{const Li=-Math.sqrt(da*da-1),$o=$a?Li:0,to=$a?0:Li;Pn&&zo(fn,tr,$o,to),Dn&&zo(fn,mr,$o,to)}}Nn.geometry=[...Tn,...Ln.reverse(),Tn[0]],Nn.joinNormals=[...Mn,...Mn.reverse(),Mn[Mn.length-1]];const Cr=Nn.geometry.length-1;for(let Nr=0;Nrhs<(ms.length-1)/2||hs===ms.length-1,Rt=this.wallMode?[C]:ZW(C,500);for(let hs=Rt.length-1;hs>=0;hs--){const ms=Rt[hs];(ms.length===0||Cis(ms[0]))&&Rt.splice(hs,1)}let Ft;if(Pe)Ft=Oit(Rt,ve,O);else{Ft=[];for(const hs of Rt)Ft.push({polygon:hs,bounds:ve})}const bs=De?this.edgeRadius:0,as=bs>0&&this.zoom<17,ys=(hs,ms)=>{if(hs.length===0)return!1;const vn=hs[hs.length-1];return ms.x===vn.x&&ms.y===vn.y};for(const{polygon:hs,bounds:ms}of Ft){let vn=0,Nn=0;for(const Qn of hs)De&&!Qn[0].equals(Qn[Qn.length-1])&&Qn.push(Qn[0]),Nn+=De?Qn.length-1:Qn.length;const Tn=this.segments.prepareSegment((De?5:4)*Nn,this.layoutVertexArray,this.indexArray);Je.footprintSegIdx<0&&(Je.footprintSegIdx=this.footprintSegments.length),Je.polygonSegIdx<0&&(Je.polygonSegIdx=this.polygonSegments.length);const Ln={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},Mn=new Eit;if(Mn.vertexOffset=this.footprintVertices.length,Mn.indexOffset=3*this.footprintIndices.length,Mn.ringIndices=[],De){const Qn=[],fn=[];vn=Tn.vertexLength;for(let Dn=0;Dn4&&Iit(fn[fn.length-2],fn[0],fn[1]),Dn=bs?Sis(fn[fn.length-2],fn[0],fn[1],bs):0;const tr=[];let mr,ta,Cr;ta=fn[1].sub(fn[0])._perp()._unit();let Nr=!0;for(let pr=1,Kr=0;pr0?1:0,$o=da.dist($a);if(Kr+$o>32768&&(Kr=0),bs){Cr=ja.sub($a)._perp()._unit();let el=Pit(da,$a,ja,Mit(ta,Cr),bs);isNaN(el)&&(el=0);const Pc=$a.sub(da)._unit();da=da.add(Pc.mult(Dn))._round(),$a=$a.add(Pc.mult(-el))._round(),Dn=el,ta=Cr,rt&&this.zoom>=17&&(ys(tr,da)||tr.push(da),ys(tr,$a)||tr.push($a))}const to=Tn.vertexLength,mu=fn.length>4&&Iit(da,$a,ja);let jl=Rit(Kr,Pn,Nr);if(eK(this.layoutVertexArray,da.x,da.y,zo,Li,0,0,jl),eK(this.layoutVertexArray,da.x,da.y,zo,Li,0,1,jl),this.wallMode){const el=St(pr-1,fn),Pc=ut.joinNormals[pr-1];tK(this.wallVertexArray,Pc,el),tK(this.wallVertexArray,Pc,el)}if(Kr+=$o,jl=Rit(Kr,mu,!Nr),Pn=mu,eK(this.layoutVertexArray,$a.x,$a.y,zo,Li,0,0,jl),eK(this.layoutVertexArray,$a.x,$a.y,zo,Li,0,1,jl),this.wallMode){const el=St(pr,fn),Pc=ut.joinNormals[pr];tK(this.wallVertexArray,Pc,el),tK(this.wallVertexArray,Pc,el)}if(Tn.vertexLength+=4,this.indexArray.emplaceBack(to+0,to+1,to+2),this.indexArray.emplaceBack(to+1,to+3,to+2),Tn.primitiveLength+=2,bs){const el=vn+(pr===1?fn.length-2:pr-2),Pc=pr===1?vn:el+1;if(this.indexArray.emplaceBack(to+1,el,to+3),this.indexArray.emplaceBack(el,Pc,to+3),Tn.primitiveLength+=2,mr===void 0&&(mr=to),!G8e(ja,fn[pr],ms)){const ru=pr===fn.length-1?mr:Tn.vertexLength;this.indexArray.emplaceBack(to+2,to+3,ru),this.indexArray.emplaceBack(to+3,ru+1,ru),this.indexArray.emplaceBack(to+3,Pc,ru+1),Tn.primitiveLength+=3}Nr=!Nr}if(Pe){const el=this.layoutVertexExtArray,Pc=_e.projectTilePoint(da.x,da.y,O),ru=_e.projectTilePoint($a.x,$a.y,O),Np=_e.upVector(O,da.x,da.y),au=_e.upVector(O,$a.x,$a.y);sK(el,Pc,Np),sK(el,Pc,Np),sK(el,ru,au),sK(el,ru,au)}}De&&(vn+=fn.length-1),rt&&bs&&this.zoom>=17&&(tr.length!==0&&ys(tr,tr[0])&&tr.pop(),this.groundEffect.addData(tr,ms,pe,bs>0))}this.footprintSegments.push(Mn),Ln.triangleCount=this.indexArray.length-Ln.triangleArrayOffset,this.polygonSegments.push(Ln),++Je.footprintSegLen,++Je.polygonSegLen}if(Je.vertexCount=this.layoutVertexArray.length-Je.vertexArrayOffset,Je.groundVertexCount=this.groundEffect.vertexArray.length-Je.groundVertexArrayOffset,Je.vertexCount!==0){if(Je.centroidXY=We.borders?qae:this.encodeCentroid(We,Je),_.properties&&_.properties.hasOwnProperty("building_id")){const hs=Je.buildingId;let ms=this.buildingGroups.get(hs);ms||(ms={accX:0,accY:0,accCount:0,mergedMin:new es(Number.MAX_VALUE,Number.MAX_VALUE),mergedMax:new es(-Number.MAX_VALUE,-Number.MAX_VALUE),partIndices:[]},this.buildingGroups.set(hs,ms)),ms.accX+=We.acc.x,ms.accY+=We.acc.y,ms.accCount+=We.accCount,ms.mergedMin.x=Math.min(ms.mergedMin.x,Je.min.x),ms.mergedMin.y=Math.min(ms.mergedMin.y,Je.min.y),ms.mergedMax.x=Math.max(ms.mergedMax.x,Je.max.x),ms.mergedMax.y=Math.max(ms.mergedMax.y,Je.max.y),ms.partIndices.push(this.centroidData.length)}if(this.centroidData.push(Je),We.borders){this.featuresOnBorder.push(We);const hs=this.featuresOnBorder.length-1;for(let ms=0;msthis.featuresOnBorder[_].borders[g][0]-this.featuresOnBorder[C].borders[g][0])}splitToSubtiles(){const g=[];for(let W=0;Wdr),pe=2*ae+(+(Y.min.x+Y.max.x>dr)^ae);for(let ve=0;veW.triangleSegmentIdx===Y.triangleSegmentIdx?W.subtile-Y.subtile:W.triangleSegmentIdx-Y.triangleSegmentIdx);let C=0,P=0,O=0;for(const W of g){if(W.triangleSegmentIdx!==C)break;O++}const B=g.length;for(;P!==g.length;){C=g[P].triangleSegmentIdx;let W=0,Y=P,ae=P;for(let pe=Y;pe0&&this.triangleSubSegments.push({segment:Pe,min:ve,max:_e}),Y=ae;for(let De=Y;De[We[0]*(1-rt[0])+Je[0]*rt[0],We[1]*(1-rt[1])+Je[1]*rt[1]],Pe=[],De=[];for(const We of this.triangleSubSegments){Pe[0]=We.min.x/dr,Pe[1]=We.min.y/dr,De[0]=We.max.x/dr,De[1]=We.max.y/dr;const Je=_e(pe,ve,Pe),rt=_e(pe,ve,De);if(new Rl([Je[0],Je[1],O],[rt[0],rt[1],B]).intersectsPrecise(C)===0){ae&&(P.segments.push(ae),ae=void 0);continue}const xt=We.segment;ae&&ae.vertexOffset!==xt.vertexOffset&&(P.segments.push(ae),ae=void 0),ae?(ae.vertexLength+=xt.vertexLength,ae.primitiveLength+=xt.primitiveLength):ae={vertexOffset:xt.vertexOffset,primitiveLength:xt.primitiveLength,vertexLength:xt.vertexLength,primitiveOffset:xt.primitiveOffset,sortKey:void 0,vaos:{}}}return ae&&P.segments.push(ae),P}encodeCentroid(g,_){const C=g.centroid(),P=_.span(),O=Math.min(7,Math.round(P.x*this.tileToMeter/10)),B=Math.min(6,Math.round(P.y*this.tileToMeter/10));return new es(mt(C.x,1,8191)<<3|O,mt(C.y,1,8191)<<3|B)}encodeBorderCentroid(g){if(!g.borders)return new es(0,0);const _=g.borders,C=Number.MAX_VALUE;if(_[0][0]!==C||_[1][0]!==C){const P=_[0][0]!==C?0:1;return new es(6|(_[0][0]!==C?0:65528),(_[P][0]+_[P][1])/2<<3|6)}{const P=_[2][0]!==C?2:3;return new es((_[P][0]+_[P][1])/2<<3|6,6|(_[2][0]!==C?0:65528))}}showCentroid(g){const _=this.centroidData[g.centroidDataIndex];if(_.flags&=H3,_.groupCentroidPos.x!==0||_.groupCentroidPos.y!==0){const C=_.span(),P=Math.min(7,Math.round(C.x*this.tileToMeter/10)),O=Math.min(6,Math.round(C.y*this.tileToMeter/10));_.centroidXY=new es(mt(_.groupCentroidPos.x,1,8191)<<3|P,mt(_.groupCentroidPos.y,1,8191)<<3|O)}else _.centroidXY=new es(0,0);this.writeCentroidToBuffer(_)}writeCentroidToBuffer(g){this.groundEffect.updateHiddenByLandmark(g);const _=g.vertexArrayOffset,C=g.vertexCount+g.vertexArrayOffset,P=-1073741824&g.flags?qae:g.centroidXY,O=this.centroidVertexArray.geta_centroid_pos0(_);if(this.centroidVertexArray.geta_centroid_pos1(_)!==P.y||O!==P.x){for(let B=_;BY.max.x||Y.min.x>B.max.x||B.min.y>Y.max.y||Y.min.y>B.max.y||B.footprint.buildingIds.has(Y.buildingId)&&(Y.flags|=B.clipMask!==Uae.None?-1073741824:H3);else for(const Y of this.centroidData)if(!(Y.flags&H3||Y.flags&$ae||B.min.x>Y.max.x||Y.min.x>B.max.x||B.min.y>Y.max.y||Y.min.y>B.max.y))for(let ae=0;ae_!=Pe>_&&g<(this.footprintVertices.int16[2*(pe+B.vertexOffset)+0]-ve)*(_-_e)/(Pe-_e)+ve&&(P=!P)}W=Y}}return P}getHeightAtTileCoord(g,_){let C=Number.NEGATIVE_INFINITY,P=!0;const O=4*(g+dr)*dr+(_+dr);if(this.partLookup.hasOwnProperty(O)){const B=this.partLookup[O];return B?{height:B.height,hidden:!!(B.flags&H3)}:void 0}for(const B of this.centroidData)g>B.max.x||B.min.x>g||_>B.max.y||B.min.y>_||B.height<=C||this.footprintContainsPoint(g,_,B)&&(C=B.height,this.partLookup[O]=B,P=!!(B.flags&H3));if(C!==Number.NEGATIVE_INFINITY)return{height:C,hidden:P};this.partLookup[O]=void 0}}function Mit(k,g){const _=k.add(g)._unit();return k.x*_.x+k.y*_.y}function Sis(k,g,_,C){const P=g.sub(k)._perp()._unit(),O=_.sub(g)._perp()._unit();return Pit(k,g,_,Mit(P,O),C)}function Pit(k,g,_,C,P){const O=Math.sqrt(1-C*C);return Math.min(k.dist(g)/3,g.dist(_)/3,P*O/C)}function G8e(k,g,_){return k.x<_[0].x&&g.x<_[0].x||k.x>_[1].x&&g.x>_[1].x||k.y<_[0].y&&g.y<_[0].y||k.y>_[1].y&&g.y>_[1].y}function Lit(k,g){return k.xg[1].x||k.yg[1].y}function Cis(k){return k.every(g=>g.x<=0)||k.every(g=>g.x>=dr)||k.every(g=>g.y<=0)||k.every(g=>g.y>=dr)}function Iit(k,g,_){if(k.x<0||k.x>=dr||g.x<0||g.x>=dr||_.x<0||_.x>=dr)return!1;const C=_.sub(g),P=C.perp(),O=k.sub(g);return(C.x*O.x+C.y*O.y)/Math.sqrt((C.x*C.x+C.y*C.y)*(O.x*O.x+O.y*O.y))>-.866&&P.x*O.x+P.y*O.y<0}function Rit(k,g,_){const C=g?2|k:-3&k;return _?1|C:-2&C}function Dit(){const k=Math.PI/32,g=Math.tan(k),_=xs;return _*Math.sqrt(1+2*g*g)-_}function Oit(k,g,_){const C=1<<_.z,P=Ls(_.x/C),O=Ls((_.x+1)/C),B=yn(_.y/C),W=yn((_.y+1)/C);return function(Y,ae,pe,ve,_e=0,Pe){const De=[];if(!Y.length||!pe||!ve)return De;const We=(Ft,bs)=>{for(const as of Ft)De.push({polygon:as,bounds:bs})},Je=Math.ceil(Math.log2(pe)),rt=Math.ceil(Math.log2(ve)),xt=Je-rt,ut=[];for(let Ft=0;Ft0?0:1);for(let Ft=0;Ftbs+1?Rt.push({polygons:Tn,bounds:Mn,depth:bs+1}):We(Tn,Mn)}if(Ln.length){const Mn=[new es(as===0?Nn:ys.x,as===1?Nn:ys.y),hs];ut.length>bs+1?Rt.push({polygons:Ln,bounds:Mn,depth:bs+1}):We(Ln,Mn)}}return De}(k,g,Math.ceil((O-P)/11.25),Math.ceil((B-W)/11.25),1,(Y,ae,pe)=>{if(Y===0)return .5*(ae+pe);{const ve=yn((_.y+ae/dr)/C);return(Kn(.5*(yn((_.y+pe/dr)/C)+ve))*C-_.y)*dr}})}function Ais(k,g,_,C,P,O){const B=Math.pow(2,C.z-P.z);for(let W=0;W<_;W++){let Y=k.int16[2*(W+g)+0],ae=k.int16[2*(W+g)+1];Y=(Y+P.x*dr)*B-C.x*dr,ae=(ae+P.y*dr)*B-C.y*dr,O.push(new es(Y,ae))}}let Fit,zit;wr(Hae,"FillExtrusionBucket",{omit:["layers","features"]}),wr($8e,"PartData"),wr(Eit,"FootprintSegment"),wr(V8e,"BorderCentroidData"),wr(H8e,"GroundEffect");class OL extends es{constructor(g,_,C){super(g,_),this.z=C}}class Bit extends OL{constructor(g,_,C,P){super(g,_,C),this.w=P}}function Uit(k,g,_,C){const P=_==="x"?"y":"x",O=(C-k[_])/(g[_]-k[_]);k[P]=Math.round(k[P]+(g[P]-k[P])*O),k[_]=C,k.hasOwnProperty("z")&&(k.z=Es(k.z,g.z,O)),k.hasOwnProperty("w")&&(k.w=Es(k.w,g.w,O))}function qit(k,g,_,C){const P=_,O=C;for(const B of["x","y"]){let W=k,Y=g;W[B]>=Y[B]&&(W=g,Y=k),W[B]P&&Uit(W,Y,B,P),W[B]O&&Uit(Y,W,B,O)}}function Gae(k,g,_,C,P,O){const B=[];for(let W=0;W=C&&De.x>=C||(Pe.x>=C?Pe=new es(C,Pe.y+(C-Pe.x)/(De.x-Pe.x)*(De.y-Pe.y))._round():De.x>=C&&(De=new es(C,Pe.y+(C-Pe.x)/(De.x-Pe.x)*(De.y-Pe.y))._round()),Pe.y>=P&&De.y>=P||(Pe.y>=P?Pe=new es(Pe.x+(P-Pe.y)/(De.y-Pe.y)*(De.x-Pe.x),P)._round():De.y>=P&&(De=new es(Pe.x+(P-Pe.y)/(De.y-Pe.y)*(De.x-Pe.x),P)._round()),ae&&Pe.equals(ae[ae.length-1])||(ae=[Pe],B.push(ae),O&&O.push({progress:{min:Je+$it(rt,xt,Pe)*We,max:1},parentIndex:W,prevPoint:rt,nextPoint:xt})),ae.push(De),O&&(O[O.length-1].progress.max=Je+$it(rt,xt,De)*We,O[O.length-1].nextPoint=xt)))))}if(O&&ve>0)for(let _e=pe;_eae.t-pe.t);let B=0,W=0,Y=[];for(C.push(Y);B!==k.length;){if(W===O.length){for(;B!==k.length;)Y.length!==0&&Y[Y.length-1].equals(k[B])||Y.push(k[B]),B++;break}O[W].t<=B?(Y.length!==0&&Y[Y.length-1].equals(O[W].point)||Y.push(O[W].point),Math.trunc(O[W].t),W++):(Y.length!==0&&Y[Y.length-1].equals(k[B])||Y.push(k[B]),B++)}}function $it(k,g,_){return k.x!==g.x?(_.x-k.x)/(g.x-k.x):k.y!==g.y?(_.y-k.y)/(g.y-k.y):0}function nK(k,g){return k.x*g.x+k.y*g.y}function Vit(k,g){if(k.length===1){let _=0;const C=g[_++];let P;for(;!P||C.equals(P);)if(P=g[_++],!P)return 1/0;for(;_{Nn[0]=Tn,Nn[1]=Ln,Nn[2]=Mn,Nn[3]=1},vn=Dit();Pe>0&&(Pe+=vn),De+=vn;for(const Nn of _e){const Tn=[],Ln=[];for(const Mn of Nn){const Qn=Mn.x+We.x,fn=Mn.y+We.y,Pn=ve.projection.projectTilePoint(Qn,fn,Rt),Dn=ve.projection.upVector(Rt,Mn.x,Mn.y);let tr=Pe,mr=De;if(rt){const ta=Wit(Qn,fn,Pe,De,rt,xt,ut,St);tr+=ta.base,mr+=ta.top}Pe!==0?ms(ys,Pn.x+Dn[0]*as*tr,Pn.y+Dn[1]*as*tr,Pn.z+Dn[2]*as*tr):ms(ys,Pn.x,Pn.y,Pn.z),ms(hs,Pn.x+Dn[0]*as*mr,Pn.y+Dn[1]*as*mr,Pn.z+Dn[2]*as*mr),Qe(ys,ys,Je),Qe(hs,hs,Je),Tn.push(new OL(ys[0],ys[1],ys[2])),Ln.push(new OL(hs[0],hs[1],hs[2]))}Ft.push(Tn),bs.push(Ln)}return[Ft,bs]}(k,g,_,C,P,O,B,W,Y,ae,pe):B?function(ve,_e,Pe,De,We,Je,rt,xt,ut){const St=[],Rt=[],Ft=[0,0,0,1];for(const bs of ve){const as=[],ys=[];for(const hs of bs){const ms=hs.x+De.x,vn=hs.y+De.y,Nn=Wit(ms,vn,_e,Pe,Je,rt,xt,ut);Ft[0]=ms,Ft[1]=vn,Ft[2]=Nn.base,Ft[3]=1,tt(Ft,Ft,We),Ft[3]=Math.max(Ft[3],1e-5);const Tn=new OL(Ft[0]/Ft[3],Ft[1]/Ft[3],Ft[2]/Ft[3]);Ft[0]=ms,Ft[1]=vn,Ft[2]=Nn.top,Ft[3]=1,tt(Ft,Ft,We),Ft[3]=Math.max(Ft[3],1e-5);const Ln=new OL(Ft[0]/Ft[3],Ft[1]/Ft[3],Ft[2]/Ft[3]);as.push(Tn),ys.push(Ln)}St.push(as),Rt.push(ys)}return[St,Rt]}(g,_,C,P,O,B,W,Y,ae):function(ve,_e,Pe,De,We){const Je=[],rt=[],xt=We[8]*_e,ut=We[9]*_e,St=We[10]*_e,Rt=We[11]*_e,Ft=We[8]*Pe,bs=We[9]*Pe,as=We[10]*Pe,ys=We[11]*Pe;for(const hs of ve){const ms=[],vn=[];for(const Nn of hs){const Tn=Nn.x+De.x,Ln=Nn.y+De.y,Mn=We[0]*Tn+We[4]*Ln+We[12],Qn=We[1]*Tn+We[5]*Ln+We[13],fn=We[2]*Tn+We[6]*Ln+We[14],Pn=We[3]*Tn+We[7]*Ln+We[15],Dn=Mn+xt,tr=Qn+ut,mr=fn+St,ta=Math.max(Pn+Rt,1e-5),Cr=Mn+Ft,Nr=Qn+bs,pr=fn+as,Kr=Math.max(Pn+ys,1e-5);ms.push(new OL(Dn/ta,tr/ta,mr/ta)),vn.push(new OL(Cr/Kr,Nr/Kr,pr/Kr))}Je.push(ms),rt.push(vn)}return[Je,rt]}(g,_,C,P,O)}function Wit(k,g,_,C,P,O,B,W){const Y=B*P.getElevationAt(k,g,!0,!0),ae=O[0]!==0,pe=ae?O[1]===0?B*(O[0]/7-450):B*function(ve,_e,Pe){const De=Math.floor(_e[0]/8),We=Math.floor(_e[1]/8),Je=10*(_e[0]-8*De),rt=10*(_e[1]-8*We),xt=ve.getElevationAt(De,We,!0,!0),ut=ve.getMeterToDEM(Pe),St=Math.floor(.5*(Je*ut-1)),Rt=Math.floor(.5*(rt*ut-1)),Ft=ve.tileCoordToPixel(De,We),bs=2*St+1,as=2*Rt+1,ys=function(Ln,Mn,Qn,fn,Pn){return[Ln.getElevationAtPixel(Mn,Qn,!0),Ln.getElevationAtPixel(Mn+Pn,Qn,!0),Ln.getElevationAtPixel(Mn,Qn+Pn,!0),Ln.getElevationAtPixel(Mn+fn,Qn+Pn,!0)]}(ve,Ft.x-St,Ft.y-Rt,bs,as),hs=Math.abs(ys[0]-ys[1]),ms=Math.abs(ys[2]-ys[3]),vn=Math.abs(ys[0]-ys[2])+Math.abs(ys[1]-ys[3]),Nn=Math.min(.25,.5*ut*(hs+ms)/bs),Tn=Math.min(.25,.5*ut*vn/as);return xt+Math.max(Nn*Je,Tn*rt)}(P,O,W):Y;return{base:Y+(_===0?-1:_),top:ae?Math.max(pe+C,Y+_+2):Y+C}}const W8e=4096;class Tis{constructor(g){this.module=g,this.memoryStack=this.module.malloc(W8e),this.memoryStackNextFree=this.memoryStack}createIntArray(g){const _=this.memoryStackNextFree;return this.memoryStackNextFree+=g.length*Int32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>W8e?-1:(new Int32Array(this.module.heap32.buffer,_,g.length).set(g),_)}createFloatArray(g){const _=this.memoryStackNextFree;return this.memoryStackNextFree+=g.length*Float32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>W8e?-1:(new Float32Array(this.module.heapF32.buffer,_,g.length).set(g),_)}readStringBuffer(g){let _="";for(;this.module.heapU8[g]!==0;)_+=String.fromCharCode(this.module.heapU8[g]),++g;return _}setStyle(g){const _=g.normalScale;this.module.setStyle(_[0],_[1],_[2],g.tileToMeters)}setAOOptions(g,_){this.module.setAOOptions(g?1:0,_)}setMetricOptions(g,_){this.module.setMetricOptions(g?1:0,_)}setStructuralOptions(g){this.module.setStructuralOptions(g?1:0)}setFacadeOptions(g,_){this.module.setFacadeOptions(g,_?1:0)}setFauxFacadeOptions(g,_,C){this.module.setFauxFacadeOptions(g?1:0,_?1:0,C)}setFacadeClassifierOptions(g){this.module.setFacadeClassifierOptions(g)}generateMesh(g,_){this.memoryStackNextFree=this.memoryStack;for(const W of g){const Y=this.createIntArray(W.ringIndices),ae=this.createFloatArray(W.coordinates);if(Y===-1||ae===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature(W.id,W.sourceId,W.minHeight,W.height,W.roofType,ae,Y,W.ringIndices.length-1)}for(const W of _){let Y;Y=W.entrances?JSON.parse(W.entrances):[];const ae=this.createFloatArray(Y),pe=this.createFloatArray(W.coordinates);if(ae===-1||pe===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(W.sourceId,W.crossPerc,W.distanceToRoad,ae,Y.length,pe,W.coordinates.length)}if(!this.module.generateMesh()){const W=this.module.getLastError();return this.readStringBuffer(W)}const C=this.module.getMeshCount(),P=new Array(C);for(let W=0;W>2)-3,Je=Pe[De++]>>2;if(De++,P.json=JSON.parse(not.decode(Pe.subarray(De,De+Je))),De+=Je,De>>0,Math.ceil(1.2*St)),Ft=Math.ceil((Rt-St)/65536);try{return We.grow(Ft),Je(),!0}catch{return!1}},b:rt}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(Pe,xt):Pe.then(ut=>ut.arrayBuffer()).then(ut=>WebAssembly.instantiate(ut,xt))).then(ut=>{const{Rb:St,Qb:Rt,P:Ft,T:bs,X:as,Ja:ys,La:hs,Qa:ms,Va:vn,Wa:Nn,eb:Tn,jb:Ln,f:Mn,e:Qn,yb:fn,zb:Pn,Ab:Dn,Bb:tr,Db:mr,Gb:ta}=ut.instance.exports;We=Qn;const Cr=(()=>{let Nr=0,pr=0,Kr=0,da=0;return $a=>{Kr&&(St(da),St(Nr),pr+=Kr,Kr=Nr=0),Nr||(pr+=128,Nr=Rt(pr));const ja=$a.length+7&-8;let Pi=Nr;ja>=pr&&(Kr=ja,Pi=da=Rt(ja));for(let zo=0;zo<$a.length;zo++)De[Pi+zo]=$a[zo];return Pi}})();return Je(),Mn(),{memory:Qn,_free:St,_malloc:Rt,Mesh:class{constructor(){this.ptr=Ft()}destroy(){bs(this.ptr)}},Decoder:class{constructor(){this.ptr=ys()}destroy(){Ln(this.ptr)}DecodeArrayToMesh(Nr,pr,Kr){const da=Cr(Nr),$a=hs(this.ptr,da,pr,Kr.ptr);return!!as($a)}GetAttributeByUniqueId(Nr,pr){return{ptr:ms(this.ptr,Nr.ptr,pr)}}GetTrianglesUInt16Array(Nr,pr,Kr){vn(this.ptr,Nr.ptr,pr,Kr)}GetTrianglesUInt32Array(Nr,pr,Kr){Nn(this.ptr,Nr.ptr,pr,Kr)}GetAttributeDataArrayForAllPoints(Nr,pr,Kr,da,$a){Tn(this.ptr,Nr.ptr,pr.ptr,Kr,da,$a)}},DT_INT8:fn(),DT_UINT8:Pn(),DT_INT16:Dn(),DT_UINT16:tr(),DT_UINT32:mr(),DT_FLOAT32:ta()}})}(fetch(ir())),rK.then(Pe=>{GN=Pe,rK=void 0}))}()),_e&&pe.push(function(){if(K8e)return;const Pe=function(De){let We;const Je=WebAssembly.instantiateStreaming(De,{}).then(ut=>{We=ut.instance,We.exports.__wasm_call_ctors()}),rt={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},xt={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"};return{ready:Je,supported:!0,decodeGltfBuffer(ut,St,Rt,Ft,bs,as){(function(ys,hs,ms,vn,Nn,Tn,Ln){const Mn=ys.exports.sbrk,Qn=vn+3&-4,fn=Mn(Qn*Nn),Pn=Mn(Tn.length),Dn=new Uint8Array(ys.exports.memory.buffer);Dn.set(Tn,Pn);const tr=hs(fn,vn,Nn,Pn,Tn.length);if(tr===0&&Ln&&Ln(fn,Qn,Nn),ms.set(Dn.subarray(fn,fn+vn*Nn)),Mn(fn-Mn(0)),tr!==0)throw new Error(`Malformed buffer data: ${tr}`)})(We,We.exports[xt[bs]],ut,St,Rt,Ft,We.exports[rt[as]])}}}(fetch(li()));return Pe.ready.then(()=>{K8e=Pe})}()),B)for(let Pe=0;Pe{const W=zm(C,(Y,ae)=>{Y?B(Y):O(ae)});P&&P.addEventListener("abort",()=>{W.cancel(),B(new DOMException("Aborted","AbortError"))},{once:!0})})}({url:k,type:"arrayBuffer"},g);return iot(_,0,k,g)}function Z8e(k){switch(k){case WebGL2RenderingContext.RGBA8:case WebGL2RenderingContext.RGBA16F:return WebGL2RenderingContext.RGBA;case WebGL2RenderingContext.DEPTH_COMPONENT16:return WebGL2RenderingContext.DEPTH_COMPONENT;case WebGL2RenderingContext.DEPTH24_STENCIL8:return WebGL2RenderingContext.DEPTH_STENCIL;case WebGL2RenderingContext.R8:case WebGL2RenderingContext.R32F:return WebGL2RenderingContext.RED}}function X8e(k){switch(k){case WebGL2RenderingContext.RGBA8:return WebGL2RenderingContext.UNSIGNED_BYTE;case WebGL2RenderingContext.RGBA16F:return WebGL2RenderingContext.HALF_FLOAT;case WebGL2RenderingContext.DEPTH_COMPONENT16:return WebGL2RenderingContext.UNSIGNED_SHORT;case WebGL2RenderingContext.DEPTH24_STENCIL8:return WebGL2RenderingContext.UNSIGNED_INT_24_8;case WebGL2RenderingContext.R8:return WebGL2RenderingContext.UNSIGNED_BYTE;case WebGL2RenderingContext.R32F:return WebGL2RenderingContext.FLOAT}}class t5{constructor(g,_,C,P){this.context=g,this.format=C,this.useMipmap=P&&P.useMipmap,this.texture=g.gl.createTexture(),this.update(_,{premultiply:P&&P.premultiply})}update(g,_){const C=g&&g instanceof HTMLVideoElement&&g.width===0?g.videoWidth:g.width,P=g&&g instanceof HTMLVideoElement&&g.height===0?g.videoHeight:g.height,{context:O}=this,{gl:B}=O,{x:W,y:Y}=_&&_.position?_.position:{x:0,y:0},ae=W+C,pe=Y+P;this.size&&(this.size[0]!==ae||this.size[1]!==pe)&&(!_||_.recreateWhenResize===void 0||_.recreateWhenResize)&&(B.bindTexture(B.TEXTURE_2D,null),B.deleteTexture(this.texture),this.texture=B.createTexture(),this.size=null),B.bindTexture(B.TEXTURE_2D,this.texture),O.pixelStoreUnpackFlipY.set(!1),O.pixelStoreUnpack.set(1),O.pixelStoreUnpackPremultiplyAlpha.set(this.format===B.RGBA8&&(!_||_.premultiply!==!1));const ve=g instanceof HTMLImageElement||g instanceof HTMLCanvasElement||g instanceof HTMLVideoElement||g instanceof ImageData||ImageBitmap&&g instanceof ImageBitmap;if(!this.size&&ae>0&&pe>0){const _e=this.useMipmap?Math.floor(Math.log2(Math.max(ae,pe)))+1:1;B.texStorage2D(B.TEXTURE_2D,_e,this.format,ae,pe),this.size=[ae,pe]}this.size&&(ve?B.texSubImage2D(B.TEXTURE_2D,0,W,Y,Z8e(this.format),X8e(this.format),g):"data"in g&&g.data&&B.texSubImage2D(B.TEXTURE_2D,0,W,Y,C,P,Z8e(this.format),X8e(this.format),g.data)),this.useMipmap&&B.generateMipmap(B.TEXTURE_2D)}bind(g,_,C=!1){const{context:P}=this,{gl:O}=P;O.bindTexture(O.TEXTURE_2D,this.texture),g!==this.minFilter&&(O.texParameteri(O.TEXTURE_2D,O.TEXTURE_MAG_FILTER,g),O.texParameteri(O.TEXTURE_2D,O.TEXTURE_MIN_FILTER,this.useMipmap&&!C?g===O.NEAREST?O.NEAREST_MIPMAP_NEAREST:O.LINEAR_MIPMAP_LINEAR:g),this.minFilter=g),_!==this.wrapS&&(O.texParameteri(O.TEXTURE_2D,O.TEXTURE_WRAP_S,_),O.texParameteri(O.TEXTURE_2D,O.TEXTURE_WRAP_T,_),this.wrapS=_)}bindExtraParam(g,_,C,P,O){const{context:B}=this,{gl:W}=B;W.bindTexture(W.TEXTURE_2D,this.texture),_!==this.magFilter&&(W.texParameteri(W.TEXTURE_2D,W.TEXTURE_MAG_FILTER,_),this.magFilter=_),g!==this.minFilter&&(W.texParameteri(W.TEXTURE_2D,W.TEXTURE_MIN_FILTER,this.useMipmap?g===W.NEAREST?W.NEAREST_MIPMAP_NEAREST:W.LINEAR_MIPMAP_LINEAR:g),this.minFilter=g),C!==this.wrapS&&(W.texParameteri(W.TEXTURE_2D,W.TEXTURE_WRAP_S,C),this.wrapS=C),P!==this.wrapT&&(W.texParameteri(W.TEXTURE_2D,W.TEXTURE_WRAP_T,P),this.wrapT=P),O!==this.compareMode&&(O?(W.texParameteri(W.TEXTURE_2D,W.TEXTURE_COMPARE_MODE,W.COMPARE_REF_TO_TEXTURE),W.texParameteri(W.TEXTURE_2D,W.TEXTURE_COMPARE_FUNC,O)):W.texParameteri(W.TEXTURE_2D,W.TEXTURE_COMPARE_MODE,W.NONE),this.compareMode=O)}destroy(){const{gl:g}=this.context;g.deleteTexture(this.texture),this.texture=null}}class iK{constructor(g,_){this.context=g,this.texture=_}bind(g,_){const{context:C}=this,{gl:P}=C;P.bindTexture(P.TEXTURE_2D,this.texture),g!==this.minFilter&&(P.texParameteri(P.TEXTURE_2D,P.TEXTURE_MAG_FILTER,g),P.texParameteri(P.TEXTURE_2D,P.TEXTURE_MIN_FILTER,g),this.minFilter=g),_!==this.wrapS&&(P.texParameteri(P.TEXTURE_2D,P.TEXTURE_WRAP_S,_),P.texParameteri(P.TEXTURE_2D,P.TEXTURE_WRAP_T,_),this.wrapS=_)}}const Ois=$n([{name:"a_pos_3f",components:3,type:"Float32"}]),Fis=$n([{name:"a_color_3f",components:3,type:"Float32"}]),zis=$n([{name:"a_color_4f",components:4,type:"Float32"}]),Bis=$n([{name:"a_uv_2f",components:2,type:"Float32"}]),Uis=$n([{name:"a_normal_3f",components:3,type:"Float32"}]),qis=$n([{name:"a_normal_matrix0",components:4,type:"Float32"},{name:"a_normal_matrix1",components:4,type:"Float32"},{name:"a_normal_matrix2",components:4,type:"Float32"},{name:"a_normal_matrix3",components:4,type:"Float32"}]),$is=$n([{name:"a_pbr",components:4,type:"Uint16"},{name:"a_heightBasedEmissiveStrength",components:3,type:"Float32"}]);function lot(k,g){const _=Zae(k.projection,k.zoom,k.width,k.height),C=function(O,B,W,Y,ae){const pe=new Ts(W.lng-180*GE,W.lat),ve=new Ts(W.lng+180*GE,W.lat),_e=O.project(pe.lng,pe.lat),Pe=O.project(ve.lng,ve.lat),De=-Math.atan2(Pe.y-_e.y,Pe.x-_e.x),We=ca.fromLngLat(W);We.y=mt(We.y,-1+GE,1-GE);const Je=We.toLngLat(),rt=O.project(Je.lng,Je.lat),xt=ca.fromLngLat(Je);xt.x+=GE;const ut=xt.toLngLat(),St=O.project(ut.lng,ut.lat),Rt=dot(St.x-rt.x,St.y-rt.y,De),Ft=ca.fromLngLat(Je);Ft.y+=GE;const bs=Ft.toLngLat(),as=O.project(bs.lng,bs.lat),ys=dot(as.x-rt.x,as.y-rt.y,De),hs=Math.abs(Rt.x)/Math.abs(ys.y),ms=y([]);L(ms,ms,-De*(1-(ae?0:Y)));const vn=y([]);return S(vn,vn,[1,1-(1-hs)*Y,1]),vn[4]=-ys.x/ys.y*Y,L(vn,vn,De),b(vn,ms,vn),vn}(k.projection,0,k.center,_,g),P=cot(k);return S(C,C,[P,P,1]),C}function cot(k){const g=k.projection,_=Zae(k.projection,k.zoom,k.width,k.height),C=Q8e(g,k.center),P=Q8e(g,Ts.convert(g.center));return Math.pow(2,C*_+(1-_)*P)}function Zae(k,g,_,C,P=1/0){const O=k.range;if(!O)return 0;const B=Math.min(P,Math.max(_,C)),W=Math.log2(B/1024);return Nt(O[0]+W,O[1]+W,g)}const GE=1/4e4;function Q8e(k,g){const _=mt(g.lat,-85.051129,An),C=new Ts(g.lng-180*GE,_),P=new Ts(g.lng+180*GE,_),O=k.project(C.lng,_),B=k.project(P.lng,_),W=ca.fromLngLat(C),Y=ca.fromLngLat(P),ae=B.x-O.x,pe=B.y-O.y,ve=Y.x-W.x,_e=Y.y-W.y,Pe=Math.sqrt((ve*ve+_e*_e)/(ae*ae+pe*pe));return Math.log2(Pe)}function dot(k,g,_){const C=Math.cos(_),P=Math.sin(_);return{x:k*C-g*P,y:k*P+g*C}}function uot(k,g,_){y(k),L(k,k,Un(g[2])),A(k,k,Un(g[0])),T(k,k,Un(g[1])),S(k,k,_),b(k,k,[1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1])}function Xae(k,g,_,C,P,O,B,W){const Y=[_[0]-g[0],_[1]-g[1],0],ae=[C[0]-g[0],C[1]-g[1],0];if(K(Y)<1e-12||K(ae)<1e-12)return ft(k);const pe=Oe([],Y,ae);Te(pe,pe),ue(ae,C,g),Y[2]=(O-P)*W,ae[2]=(B-P)*W;const ve=Y;return Oe(ve,Y,ae),Te(ve,ve),As(k,pe,ve)}function Qae(k,g,_=!1){const C=$3(g.zoom),P=function(O,B,W){const Y=B.worldSize,ae=[O[12],O[13],O[14]],pe=yn(ae[1]/Y),ve=Ls(ae[0]/Y),_e=y([]),Pe=en(1,pe)*Y,De=en(1,0)*Y*ur(pe,B.zoom),We=1/j8e(Y);let Je=De*We;if(W){const St=Zae(B.projection,B.zoom,B.width,B.height,1024);Je=We*B.projection.pixelSpaceConversion(B.center.lat,Y,St)}const rt=ss(pe,ve);le(rt,rt,ce([],Te([],rt),Pe*Je*ae[2]));const xt=function(St){const Rt=[St[0],St[1],St[2]];let Ft=[0,1,0];const bs=Oe([],Ft,Rt);return Oe(Ft,Rt,bs),ge(Ft)===0&&(Ft=[0,1,0],Oe(bs,Rt,Ft)),Te(bs,bs),Te(Ft,Ft),Te(Rt,Rt),[bs[0],bs[1],bs[2],0,Ft[0],Ft[1],Ft[2],0,Rt[0],Rt[1],Rt[2],0,St[0],St[1],St[2],1]}(rt);S(_e,_e,[Je,Je,Je*Pe]),N(_e,_e,[-ae[0],-ae[1],-ae[2]]);const ut=b([],B.globeMatrix,xt);return b(ut,ut,_e),b(ut,ut,O),ut}(k,g,_);if(C>0){const O=function(B,W){const Y=W.worldSize,ae=en(1,0)*Y*ur(W.center.lat,W.zoom)/j8e(Y),pe=en(1,W.center.lat)*Y,ve=y([]);T(ve,ve,Un(W.center.lng)),A(ve,ve,Un(W.center.lat)),N(ve,ve,[0,0,Vt]),S(ve,ve,[ae,ae,ae*pe]);const _e=W.point;return N(ve,ve,[-_e.x,-_e.y,0]),b(ve,ve,B),b(ve,W.globeMatrix,ve)}(k,g);return function(B,W,Y){const ae=(De,We,Je)=>{const rt=K(De),xt=K(We),ut=q3(De,We,Je);return ce(ut,ut,1/K(ut)*Es(rt,xt,Je))},pe=ae([B[0],B[1],B[2]],[W[0],W[1],W[2]],Y),ve=ae([B[4],B[5],B[6]],[W[4],W[5],W[6]],Y),_e=ae([B[8],B[9],B[10]],[W[8],W[9],W[10]],Y),Pe=q3([B[12],B[13],B[14]],[W[12],W[13],W[14]],Y);return[pe[0],pe[1],pe[2],0,ve[0],ve[1],ve[2],0,_e[0],_e[1],_e[2],0,Pe[0],Pe[1],Pe[2],1]}(P,O,C)}return P}function J8e(k,g,_,C){const P=Rl.projectAabbCorners(C,_);let O=Number.MAX_VALUE;for(let W=0;W0||Je===0&&De[0]*We[0]+De[1]*We[1]>=0&&De[0]*De[0]+De[1]*De[1]>We[0]*We[0]+We[1]*We[1])&&(pe=Pe)}ve=pe}while(ve!==ae);return Y.length>0&&Y.push(Y[0]),Y}(P);if(nh(k,B))return O}const FL=64,hz={CoordinateSpaceTile:1,HasMapboxMeshFeatures:4,HasMeshoptCompression:8};function Jae(k,g,_,C,P,O,B,W,Y,ae=!1){const pe=_.zoom,ve=_.project(C),_e=ur(C.lat,pe),Pe=1/_e;y(k),N(k,k,[ve.x+B[0]*Pe,ve.y+B[1]*Pe,B[2]]);let De=1,We=1;const Je=_.worldSize;if(ae){if(_.projection.name==="mercator"){let St=0;_.elevation&&(St=_.elevation.getAtPointOrZero(new ca(ve.x/Je,ve.y/Je),0));const Rt=tt([],[ve.x,ve.y,St,1],_.projMatrix)[3]/_.cameraToCenterDistance;De=Rt,We=Rt*ur(_.center.lat,pe)}else if(_.projection.name==="globe"){const St=Qae(k,_),Rt=[0,0,0,1];tt(Rt,Rt,b([],_.projMatrix,St));const Ft=Rt[3]/_.cameraToCenterDistance,bs=$3(pe),as=_.projection.pixelsPerMeter(C.lat,Je)*ur(C.lat,pe),ys=_.projection.pixelsPerMeter(_.center.lat,Je)*ur(_.center.lat,pe);De=Ft/Es(as,jr(_.center.lat),bs),We=Ft*_e/as,De*=ys,We*=ys}}else De=Pe;S(k,k,[De,De,We]);const rt=[...k],xt=g.orientation,ut=[];if(uot(ut,[xt[0]+(P?P[0]:0),xt[1]+(P?P[1]:0),xt[2]+(P?P[2]:0)],O),b(k,rt,ut),W&&_.elevation){let St=0;const Rt=[];if(Y&&_.elevation){St=function(bs,as,ys,hs,ms){const vn=as.elevation;if(!vn)return 0;const Nn=Rl.projectAabbCorners(ys,hs),Tn=en(1,ms.lat)*as.worldSize,Ln=function(pr,Kr){const da=[0,0,1],$a=[{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 ja of $a){const Pi=pr[ja.corners[0]],zo=pr[ja.corners[1]],Li=pr[ja.corners[2]],$o=[zo[0]-Pi[0],zo[1]-Pi[1],Kr*(zo[2]-Pi[2])],to=Oe($o,$o,[Li[0]-Pi[0],Li[1]-Pi[1],Kr*(Li[2]-Pi[2])]);Te(to,to),ja.dotProductWithUp=Me(to,da)}return $a.sort((ja,Pi)=>ja.dotProductWithUp-Pi.dotProductWithUp),$a[0].corners}(Nn,Tn),Mn=Nn[Ln[0]],Qn=Nn[Ln[1]],fn=Nn[Ln[2]],Pn=Nn[Ln[3]],Dn=vn.getAtPointOrZero(new ca(Mn[0]/as.worldSize,Mn[1]/as.worldSize),0),tr=vn.getAtPointOrZero(new ca(Qn[0]/as.worldSize,Qn[1]/as.worldSize),0),mr=vn.getAtPointOrZero(new ca(fn[0]/as.worldSize,fn[1]/as.worldSize),0),ta=vn.getAtPointOrZero(new ca(Pn[0]/as.worldSize,Pn[1]/as.worldSize),0),Cr=(Dn+ta)/2,Nr=(tr+mr)/2;return Cr>Nr?tr=g.gl.NEAREST_MIPMAP_NEAREST}),k.uploaded=!0,k.image=null)}function Vis(k,g,_){k.indexBuffer=g.createIndexBuffer(k.indexArray,!1,!0),k.vertexBuffer=g.createVertexBuffer(k.vertexArray,Ois.members,!1,!0),k.normalArray&&(k.normalBuffer=g.createVertexBuffer(k.normalArray,Uis.members,!1,!0)),k.texcoordArray&&(k.texcoordBuffer=g.createVertexBuffer(k.texcoordArray,Bis.members,!1,!0)),k.colorArray&&(k.colorBuffer=g.createVertexBuffer(k.colorArray,(k.colorArray.bytesPerElement===12?Fis:zis).members,!1,!0)),k.featureArray&&(k.pbrBuffer=g.createVertexBuffer(k.featureArray,$is.members,!0)),k.segments=Ec.simpleSegment(0,0,k.vertexArray.length,k.indexArray.length);const C=k.material;C.pbrMetallicRoughness.baseColorTexture&&oK(C.pbrMetallicRoughness.baseColorTexture,g),C.pbrMetallicRoughness.metallicRoughnessTexture&&oK(C.pbrMetallicRoughness.metallicRoughnessTexture,g),C.normalTexture&&oK(C.normalTexture,g),C.occlusionTexture&&oK(C.occlusionTexture,g,_),C.emissionTexture&&oK(C.emissionTexture,g)}function eRe(k,g,_){if(k.meshes)for(const C of k.meshes)Vis(C,g,_);if(k.children)for(const C of k.children)eRe(C,g,_)}function eie(k){if(k.meshes)for(const g of k.meshes)g.indexArray.destroy(),g.vertexArray.destroy(),g.colorArray&&g.colorArray.destroy(),g.normalArray&&g.normalArray.destroy(),g.texcoordArray&&g.texcoordArray.destroy(),g.featureArray&&g.featureArray.destroy();if(k.children)for(const g of k.children)eie(g)}function His(k){k.pbrMetallicRoughness.baseColorTexture&&k.pbrMetallicRoughness.baseColorTexture.gfxTexture&&k.pbrMetallicRoughness.baseColorTexture.gfxTexture.destroy(),k.pbrMetallicRoughness.metallicRoughnessTexture&&k.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture&&k.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture.destroy(),k.normalTexture&&k.normalTexture.gfxTexture&&k.normalTexture.gfxTexture.destroy(),k.emissionTexture&&k.emissionTexture.gfxTexture&&k.emissionTexture.gfxTexture.destroy(),k.occlusionTexture&&k.occlusionTexture.gfxTexture&&k.occlusionTexture.gfxTexture.destroy()}function tRe(k){if(k.meshes)for(const g of k.meshes)g.vertexBuffer&&(g.vertexBuffer.destroy(),g.indexBuffer.destroy(),g.normalBuffer&&g.normalBuffer.destroy(),g.texcoordBuffer&&g.texcoordBuffer.destroy(),g.colorBuffer&&g.colorBuffer.destroy(),g.pbrBuffer&&g.pbrBuffer.destroy(),g.segments.destroy(),g.material&&His(g.material));if(k.footprintDebugMesh&&(k.footprintDebugMesh.vertexBuffer.destroy(),k.footprintDebugMesh.indexBuffer.destroy(),k.footprintDebugMesh.segments.destroy()),k.children)for(const g of k.children)tRe(g)}function zL(k,g){const _=k.json.bufferViews[g.bufferView],C=Kae[g.componentType];return new C(k.buffers[_.buffer],(g.byteOffset||0)+(_.byteOffset||0),g.count*(_.byteStride&&_.byteStride!==aK[g.type]*C.BYTES_PER_ELEMENT?_.byteStride/C.BYTES_PER_ELEMENT:aK[g.type]))}function sRe(k,g,_,C){const P=Kae[g.componentType],O=function(pe){switch(pe){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:return 1}}(P),B=k.json.bufferViews[g.bufferView],W=B.byteStride?B.byteStride/P.BYTES_PER_ELEMENT:aK[g.type],Y=_.float32,ae=Y.length/_.capacity;for(let pe=0,ve=0;pe0){for(let Je=0;Je0){O.texcoordArray=new F3;const _e=g.json.accessors[P.TEXCOORD_0];O.texcoordArray.resize(_e.count);const Pe=zL(g,_e);sRe(g,_e,O.texcoordArray,Pe)}if(P._FEATURE_ID_RGBA4444!==void 0){const _e=g.json.accessors[P._FEATURE_ID_RGBA4444];g.json.extensionsUsed&&g.json.extensionsUsed.includes("EXT_meshopt_compression")&&(O.featureData=zL(g,_e))}P._FEATURE_RGBA4444!==void 0&&(O.featureData=new Uint32Array(zL(g,g.json.accessors[P._FEATURE_RGBA4444]).buffer));const ve=k.material;return O.material=function(_e,Pe){const{emissiveFactor:De=[0,0,0],alphaMode:We="OPAQUE",alphaCutoff:Je=.5,normalTexture:rt,occlusionTexture:xt,emissiveTexture:ut,doubleSided:St,name:Rt}=_e,{baseColorFactor:Ft=[1,1,1,1],metallicFactor:bs=1,roughnessFactor:as=1,baseColorTexture:ys,metallicRoughnessTexture:hs}=_e.pbrMetallicRoughness||{},ms=xt?Pe[xt.index]:void 0;if(xt&&xt.extensions&&xt.extensions.KHR_texture_transform&&ms){const vn=xt.extensions.KHR_texture_transform;ms.offsetScale=[vn.offset[0],vn.offset[1],vn.scale[0],vn.scale[1]]}return{name:Rt,pbrMetallicRoughness:{baseColorFactor:new Zs(...Ft),metallicFactor:bs,roughnessFactor:as,baseColorTexture:ys?Pe[ys.index]:void 0,metallicRoughnessTexture:hs?Pe[hs.index]:void 0},doubleSided:St,emissiveFactor:new Zs(...De),alphaMode:We,alphaCutoff:Je,normalTexture:rt?Pe[rt.index]:void 0,occlusionTexture:ms,emissionTexture:ut?Pe[ut.index]:void 0,defined:_e.defined===void 0}}(ve!==void 0?g.json.materials[ve]:{defined:!1},_),O}function mot(k,g,_){const{matrix:C,rotation:P,translation:O,scale:B,mesh:W,extras:Y,children:ae,name:pe}=k,ve={};if(ve.name=pe,ve.localMatrix=C||function(_e,Pe,De,We){var Je=Pe[0],rt=Pe[1],xt=Pe[2],ut=Pe[3],St=Je+Je,Rt=rt+rt,Ft=xt+xt,bs=Je*St,as=Je*Rt,ys=Je*Ft,hs=rt*Rt,ms=rt*Ft,vn=xt*Ft,Nn=ut*St,Tn=ut*Rt,Ln=ut*Ft,Mn=We[0],Qn=We[1],fn=We[2];return _e[0]=(1-(hs+vn))*Mn,_e[1]=(as+Ln)*Mn,_e[2]=(ys-Tn)*Mn,_e[3]=0,_e[4]=(as-Ln)*Qn,_e[5]=(1-(bs+vn))*Qn,_e[6]=(ms+Nn)*Qn,_e[7]=0,_e[8]=(ys+Tn)*fn,_e[9]=(ms-Nn)*fn,_e[10]=(1-(bs+hs))*fn,_e[11]=0,_e[12]=De[0],_e[13]=De[1],_e[14]=De[2],_e[15]=1,_e}([],P||[0,0,0,1],O||[0,0,0],B||[1,1,1]),ve.globalMatrix=x(ve.localMatrix),W!==void 0){ve.meshes=_[W];const _e=ve.anchor=[0,0];for(const Pe of ve.meshes){const{min:De,max:We}=Pe.aabb;_e[0]+=De[0]+We[0],_e[1]+=De[1]+We[1]}_e[0]=Math.floor(_e[0]/ve.meshes.length/2),_e[1]=Math.floor(_e[1]/ve.meshes.length/2)}if(Y&&(Y.id&&(ve.id=Y.id),Y.lights&&(ve.lights=function(_e){if(!_e.length)return[];const Pe=function(xt){const ut=atob(xt),St=new Uint8Array(ut.length);for(let Rt=0;Rt1&&C[C.length-1].equals(C[0])&&C.pop();let P=0;for(let B=0;B0&&C.reverse();const O=oz(C.flatMap(B=>[B.x,B.y]),[]);return O.length===0?null:{vertices:C,indices:O}}function Yis(k,g){const _=[],C=[];let P=0;const O=[];for(const B of k){P=_.length;const W=B.vertexArray.float32,Y=B.indexArray.uint16;for(let ae=0;ae0&&([C[B+1],C[B+2]]=[C[B+2],C[B+1]])}return{vertices:_,indices:C}}function nRe(k){const g=function(Y,ae){const pe=[],ve=WebGL2RenderingContext;if(Y.json.textures)for(const _e of Y.json.textures){const Pe={magFilter:ve.LINEAR,minFilter:ve.NEAREST,wrapS:ve.REPEAT,wrapT:ve.REPEAT};_e.sampler!==void 0&&Object.assign(Pe,Y.json.samplers[_e.sampler]),pe.push({image:ae[_e.source],sampler:Pe,uploaded:!1})}return pe}(k,k.images),_=function(Y,ae){const pe=[];for(const ve of Y.json.meshes){const _e=[];for(const Pe of ve.primitives)_e.push(Gis(Pe,Y,ae));pe.push(_e)}return pe}(k,g),{scenes:C,scene:P,nodes:O}=k.json,B=C?C[P||0].nodes:[...O.keys()],W=[];for(const Y of B)W.push(mot(O[Y],k,_));return function(Y,ae,pe){const ve={},_e=new Set;for(let Pe=0;Pe0){const Pe=Array.from(_e.values()).sort((De,We)=>De-We);for(let De=Pe.length-1;De>=0;De--)Y.splice(Pe[De],1)}}(W,B,k.json.nodes),W}function Zis(k){k.heightmap=new Float32Array(4096),k.heightmap.fill(-1);const g=k.vertexArray.float32,_=k.aabb.min[0]-1,C=k.aabb.min[1]-1,P=FL/(k.aabb.max[0]-_+2),O=FL/(k.aabb.max[1]-C+2);for(let B=0;Bk.heightmap[ae*FL+Y]&&(k.heightmap[ae*FL+Y]=W)}}function pot(k,g,_,C,P){_.reserve(_.length+4*k.length),C.reserve(C.length+10*k.length),P.reserve(P.length+10*k.length);let O=C.length;for(const B of k){const W=Math.min(10,Math.max(4,1.3*B.height))*g,Y=[-B.normal[1],B.normal[0],0],ae=Math.min(.29,.1*B.width/B.depth),pe=B.width-2*B.depth*g*(ae+.01),ve=je([],B.pos,Y,pe/2),_e=je([],B.pos,Y,-pe/2),Pe=[ve[0],ve[1],ve[2]+B.height],De=[_e[0],_e[1],_e[2]+B.height],We=je([],B.normal,Y,ae);ce(We,We,W);const Je=je([],B.normal,Y,-ae);ce(Je,Je,W),le(We,ve,We),le(Je,_e,Je),ve[2]+=.1,_e[2]+=.1,C.emplaceBack(We[0],We[1],We[2]),C.emplaceBack(Je[0],Je[1],Je[2]),C.emplaceBack(ve[0],ve[1],ve[2]),C.emplaceBack(_e[0],_e[1],_e[2]),C.emplaceBack(Pe[0],Pe[1],Pe[2]),C.emplaceBack(De[0],De[1],De[2]),C.emplaceBack(ve[0],ve[1],ve[2]),C.emplaceBack(_e[0],_e[1],_e[2]),C.emplaceBack(We[0],We[1],We[2]),C.emplaceBack(Je[0],Je[1],Je[2]);const rt=pe/W/2;P.emplaceBack(-rt-ae,-1,rt,.8),P.emplaceBack(rt+ae,-1,rt,.8),P.emplaceBack(-rt,0,rt,1.3),P.emplaceBack(rt,0,rt,1.3),P.emplaceBack(rt+ae,-.8,rt,.7),P.emplaceBack(rt+ae,-.8,rt,.7),P.emplaceBack(0,0,rt,1.3),P.emplaceBack(0,0,rt,1.3),P.emplaceBack(rt+ae,-1.2,rt,.8),P.emplaceBack(rt+ae,-1.2,rt,.8),_.emplaceBack(6+O,4+O,8+O),_.emplaceBack(7+O,9+O,5+O),_.emplaceBack(0+O,1+O,2+O),_.emplaceBack(1+O,3+O,2+O),O+=10}}function Xis(k,g){const _={};_.indexArray=new Ru,_.vertexArray=new $b,_.colorArray=new VN,pot(k,g,_.indexArray,_.vertexArray,_.colorArray);const C={defined:!0};C.emissiveFactor=Zs.black;const P={};return P.baseColorFactor=Zs.white,C.pbrMetallicRoughness=P,_.material=C,_.aabb=new Rl([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),_}const fot=$n([{name:"a_pos_3f",components:3,type:"Float32"}]),Qis=$n([{name:"a_normal_3",components:3,type:"Int16"}]),Jis=$n([{name:"a_centroid_3",components:3,type:"Int16"}]),got=$n([{name:"a_part_color_emissive",components:2,type:"Uint16"}]),eos=$n([{name:"a_faux_facade_color_emissive",components:2,type:"Uint16"}]),tos=$n([{name:"a_faux_facade_data",components:4,type:"Uint16"}]),sos=$n([{name:"a_faux_facade_vertical_range",components:2,type:"Uint16"}]),nos=$n([{name:"a_bloom_attenuation",components:4,type:"Float32"}]),ros=$n([{name:"a_flood_light_wall_radius_1i16",components:1,type:"Int16"}]),xot=vi.types,tie=32767;function aos(k,g){const _=dr+g;for(const C of k)for(const P of C)if(P.x<-g||P.x>_||P.y<-g||P.y>_)return!1;return!0}function ios(k){switch(k){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: ${k}`)}}class rRe{constructor(){this.layoutVertexArray=new $b,this.layoutAttenuationArray=new VN,this.layoutColorArray=new Vb,this.indexArray=new Ru,this.indexArrayForConflation=new Ru,this.segmentsBucket=new Ec}}class aRe{constructor(g){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new Ec,this.entranceBloom=new rRe;const _=66560;this.layoutVertexArray=new $b,this.layoutVertexArray.reserve(_),this.layoutNormalArray=new cl,this.layoutNormalArray.reserve(_),this.layoutCentroidArray=new cl,this.layoutCentroidArray.reserve(_),this.layoutColorArray=new Vb,this.layoutColorArray.reserve(_),this.layoutFloodLightDataArray=new tz,this.layoutFloodLightDataArray.reserve(_),this.layoutAOArray=new sz,this.layoutAOArray.reserve(_),this.indexArray=new Ru,this.indexArray.reserve(66560),this.indexArrayForConflation=new Ru,this.segmentsBucket=new Ec,this.entranceBloom=new rRe,g&&(this.layoutFacadePaintArray=new Vb,this.layoutFacadeDataArray=new zE,this.layoutFacadeVerticalRangeArray=new Vb)}reserve(g,_,C){this.layoutVertexArray.reserveForAdditional(g),this.layoutCentroidArray.reserveForAdditional(g),this.layoutFloodLightDataArray.reserveForAdditional(g),this.layoutNormalArray.reserveForAdditional(g),this.layoutAOArray.reserveForAdditional(g),this.layoutColorArray.reserveForAdditional(g),this.indexArray.reserveForAdditional(_),C&&(this.layoutFacadePaintArray.reserveForAdditional(g),this.layoutFacadeDataArray.reserveForAdditional(g),this.layoutFacadeVerticalRangeArray.reserveForAdditional(g))}}class yot{constructor(g){this.colorBufferUploaded=!1,this.maxHeight=0,this.replacementUpdateTime=0,this.activeReplacements=[],this.footprints=[],this.footprintsVertices=new F3,this.footprintsIndices=new z3,this.footprintsMin=new es(1/0,1/0),this.footprintsMax=new es(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new aRe(!1),this.buildingWithFacade=new aRe(!0),this.indexArrayForConflationUploaded=!1,this.featureFootprintLookup=new Map,this.buildingIds=new Set,this.footprintLookup={},this.zoom=g.zoom,this.canonical=g.canonical,this.layers=g.layers,this.layerIds=this.layers.map(_=>_.fqid),this.index=g.index,this.hasPattern=!1,this.worldview=g.worldview,this.lut=g.lut,this.programConfigurations=new st(g.layers,{zoom:g.zoom,lut:g.lut}),this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.projection=g.projection,this.groundEffect=new H8e(g),this.groundEffect.groundRadiusArray=new Bl,this.hasAppearances=null}updateFootprints(g,_){const C=new Fae([],[],1),P={vertices:[],indices:new Uint32Array(0),grid:C,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};_.push({footprint:P,id:g})}updateAppearances(g,_,C,P){return{hasLayoutChanges:!1,hasUboChanges:!1}}prepare(){return function(){if(Wae!=null||Kit!=null)return null;if(uz!=null)return uz;const g=fetch(Eo());return uz=function(_){let C,P,O,B,W;function Y(){C=new Uint8Array(W.buffer),P=new Int16Array(W.buffer),O=new Int32Array(W.buffer),B=new Float32Array(W.buffer)}function ae(){throw new Error("Unexpected BuildingGen error.")}const pe=()=>{},ve={a:{a:ae,f:function(_e){const Pe=C.length,De=Math.max(_e>>>0,Math.ceil(1.2*Pe)),We=Math.ceil((De-Pe)/65536);try{return W.grow(We),Y(),!0}catch{return!1}},g:ae,b:pe,c:pe,d:pe,e:pe}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(_,ve):_.then(_e=>_e.arrayBuffer()).then(_e=>WebAssembly.instantiate(_e,ve))).then(_e=>{const Pe=_e.instance.exports;return(0,Pe.g)(),W=Pe.f,Y(),new Tis({setStyle:Pe.h,setAOOptions:Pe.i,setMetricOptions:Pe.j,setStructuralOptions:Pe.k,setFacadeOptions:Pe.l,setFauxFacadeOptions:Pe.m,setFacadeClassifierOptions:Pe.n,addFeature:Pe.o,addFacade:Pe.p,generateMesh:Pe.q,getLastError:Pe.r,getOuterRingLength:Pe.s,getMeshCount:Pe.t,getPositionsPtr:Pe.u,getPositionsLength:Pe.v,getNormalsPtr:Pe.w,getNormalsLength:Pe.x,getAOPtr:Pe.y,getAOLength:Pe.z,getUVPtr:Pe.A,getUVLength:Pe.B,getFauxFacadePtr:Pe.C,getFauxFacadeLength:Pe.D,getIndicesPtr:Pe.E,getIndicesLength:Pe.F,getBuildingPart:Pe.G,getRingCount:Pe.H,getRingPtr:Pe.I,getRingLength:Pe.J,malloc:Pe.K,free:Pe.L,heapU8:C,heap16:P,heap32:O,heapF32:B})})}(g).then(_=>(uz=null,Wae=_,Wae)).catch(_=>{qr("Could not load building-gen"),uz=null,Kit=_ instanceof Error?_:new Error("Unknown error")}),uz}()}populate(g,_,C,P){const O=Mis();if(!O)return;const B=Vn(C);this.tileToMeter=B,this.brightness=_.brightness,O.setStyle({normalScale:[1,-1,B],tileToMeters:B}),O.setAOOptions(!1,.3),O.setMetricOptions(!1,16),O.setStructuralOptions(!0),O.setFacadeClassifierOptions(3);const W=new Map,Y=new Map;let ae=0;for(const{feature:rt}of g){if(xot[rt.type]!=="LineString"){W.set(rt.id,rt.properties.source_id);continue}const xt=this.layers[0]._featureFilter.needGeometry;if(xt&&!this.layers[0]._featureFilter.filter(new Oi(this.zoom),rt,C))continue;const ut=eo(rt,xt);if(!xt&&!this.layers[0]._featureFilter.filter(new Oi(this.zoom),ut,C))continue;const St=xt?ut.geometry:Ha(rt,C,P),Rt=[];for(const ys of St)for(const hs of ys)Rt.push(hs.x),Rt.push(hs.y);const Ft={coordinates:Rt,crossPerc:rt.properties.cross_perc,distanceToRoad:rt.properties.distance_to_road,entrances:rt.properties.entrances,sourceId:0},bs=rt.properties.source_id;let as=Y.get(bs);as||(as=[],Y.set(bs,as)),as.push(Ft),++ae}this.maxHeight=0;const pe=new Array,ve=new Set,_e=rt=>{rt!=null&&ve.add(rt)},Pe=(rt,xt)=>{rt!=null&&pe.push({buildingId:rt,footprintIndex:xt})},De=64*(g.length-ae),We=De/2;this.buildingWithFacade.reserve(De,We,!0),this.buildingWithoutFacade.reserve(2*De,2*We,!1),this.footprintsIndices.reserve(16*(g.length-ae)),this.footprintsVertices.reserve(8*(g.length-ae));for(const{feature:rt,id:xt,index:ut,sourceLayerIndex:St}of g){if(xot[rt.type]==="LineString")continue;const Rt=this.layers[0]._featureFilter.needGeometry;if(Rt&&!this.layers[0]._featureFilter.filter(new Oi(this.zoom),rt,C))continue;let Ft=null;if(rt.properties&&rt.properties.hasOwnProperty("building_id")&&(Ft=Number(rt.properties.building_id),ve.has(Ft)))continue;const bs=eo(rt,Rt);if(!Rt&&!this.layers[0]._featureFilter.filter(new Oi(this.zoom),bs,C))continue;const as=Rt?bs.geometry:Ha(rt,C,P),ys=ZW(as,500);let hs=!1;for(const mo of ys)if(mo.length!==1){hs=!0;break}if(hs){_e(Ft);continue}if(!aos(as,163)){_e(Ft);continue}const ms=this.layers[0],vn=ios(ms.layout.get("building-roof-shape").evaluate(rt,{},C)),Nn=ms.layout.get("building-base").evaluate(rt,{},C),Tn=ms.layout.get("building-height").evaluate(rt,{},C),Ln=ms.layout.get("building-flood-light-ground-radius").evaluate(rt,{},C),Mn=ms.paint.get("building-ambient-occlusion-intensity"),Qn=Ln/this.tileToMeter;rt.properties["building-part"]="roof";const fn=ms.paint.get("building-color").evaluate(rt,{},this.canonical).toPremultipliedRenderColor(this.lut),Pn=ms.paint.get("building-emissive-strength").evaluate(rt,{},this.canonical);rt.properties["building-part"]="wall";const Dn=ms.paint.get("building-color").evaluate(rt,{},this.canonical).toPremultipliedRenderColor(this.lut),tr=ms.paint.get("building-emissive-strength").evaluate(rt,{},this.canonical);rt.properties["building-part"]="window";const mr=ms.paint.get("building-color").evaluate(rt,{},this.canonical).toPremultipliedRenderColor(this.lut),ta=ms.paint.get("building-emissive-strength").evaluate(rt,{},this.canonical);rt.properties["building-part"]="door";const Cr=ms.paint.get("building-color").evaluate(rt,{},this.canonical).toPremultipliedRenderColor(this.lut),Nr=ms.paint.get("building-emissive-strength").evaluate(rt,{},this.canonical);let pr=ms.layout.get("building-flood-light-wall-radius").evaluate(rt,{},C);pr=mt(pr,0,2048);const Kr=pr/2048*tie,da=W.get(xt),$a=Y.get(da)||[],ja=$a.length!==0&&ms.layout.get("building-facade").evaluate(rt,{},C);O.setFacadeOptions(4,!0),O.setFauxFacadeOptions(ja,!1,1);let Pi=0,zo=0,Li=0,$o=0,to=0,mu=0,jl=0,el=0,Pc=0,ru=0,Np=0;if(ja){let mo=Math.round(ms.layout.get("building-facade-floors").evaluate(rt,{},C));if(Nn===0){mo=Math.max(1,mo-($a.length>0?1:0));let Fu=4;if(Tn>100){const Km=[10,13,15];Fu=Km[rt.id?rt.id%Km.length:0]}else Tn<=10&&(Fu=3);O.setFacadeOptions(Fu,!0),to=(Tn<15?1.3:1.61803)*Fu/B}else to=Nn/B;mu=Tn/B,to=Math.min(to,mu),Li=ms.layout.get("building-facade-unit-width").evaluate(rt,{},C)/B,$o=(mu-to)/mo,O.setFauxFacadeOptions(!0,!0,Li);const rf=ms.layout.get("building-facade-window").evaluate(rt,{},C);Pi=rf[0],zo=rf[1],jl=Math.floor(65535*Math.min(1,to/dr)),el=Math.floor(65535*Math.min(1,mu/dr)),Pc=Math.floor(255*Pi)<<8|Math.floor(255*zo),ru=Math.floor(65535*Math.min(1,Li/dr)),Np=Math.floor(65535*Math.min(1,$o/dr))}const au=Array(ys.length),Du={x:1/0,y:1/0},Rh={x:-1/0,y:-1/0},Ou={x:0,y:0};let Ng=0;for(let mo=0;mo0){const Fu=[],Km=Array(rf.length+1);Km[0]=0;for(let nw=0;nwdr||Du.y<0||Rh.y>dr)&&this.featuresOnBorder.push({featureId:rt.id,footprintIndex:this.footprints.length});{const mo=oz(Y3,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+mo.length),this.footprintsIndices.uint16.set(mo,kz),this.buildingIds.add(Ft??rt.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,tw.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,tw.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,sw.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,sw.y);const rf={footprintVertexOffset:K3,footprintVertexLength:this.footprintsVertices.length-K3,footprintIndexOffset:kz,footprintIndexLength:this.footprintsIndices.length-kz,min:tw,max:sw,hiddenFlags:0,indicesOffset:Tie,indicesLength:YRe,bloomIndicesOffset:kg,bloomIndicesLength:pu,groundEffectVertexOffset:GL,groundEffectVertexLength:Sz,hasFauxFacade:ja,height:Nz,promoteId:xt,feature:bs,parts:sf,buildingBloom:R0},Fu=this.footprints.length;rt.id!==void 0&&this.featureFootprintLookup.set(rt.id,Fu),Pe(Ft,Fu),this.footprints.push(rf)}this.programConfigurations.populatePaintArrays(lo.layoutVertexArray.length,rt,ut,{},_.availableImages,C,_.brightness),this.groundEffect.addPaintPropertiesData(rt,ut,{},_.availableImages,C,_.brightness),_.featureIndex.insert(rt,as,ut,St,this.index,Ox)}pe.forEach(({buildingId:rt,footprintIndex:xt})=>{ve.has(rt)&&(this.footprints[xt].hiddenFlags|=4)});const Je=new Set;this.buildingIds.forEach((rt,xt,ut)=>{ve.has(rt)||Je.add(rt)}),this.buildingIds=Je,this.groundEffect.prepareBorderSegments()}update(g,_,C,P,O,B,W){this.programConfigurations.updatePaintArrays(g,_,O,C,P,B,W),this.groundEffect.update(g,_,O,C,P,B,W),this.evaluate(this.layers[0],g),this.colorBufferUploaded=!1}isEmpty(){return this.buildingWithoutFacade.layoutVertexArray.length===0&&this.buildingWithFacade.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(g){const _=C=>{C.layoutVertexBuffer=g.createVertexBuffer(C.layoutVertexArray,fot.members),C.layoutNormalBuffer=g.createVertexBuffer(C.layoutNormalArray,Qis.members),C.layoutCentroidBuffer=g.createVertexBuffer(C.layoutCentroidArray,Jis.members),C.layoutFloodLightDataBuffer=g.createVertexBuffer(C.layoutFloodLightDataArray,ros.members),C.layoutFacadeDataArray&&C.layoutFacadeDataArray.length&&(C.layoutFacadeDataBuffer=g.createVertexBuffer(C.layoutFacadeDataArray,tos.members)),C.layoutFacadeVerticalRangeArray&&C.layoutFacadeVerticalRangeArray.length&&(C.layoutFacadeVerticalRangeBuffer=g.createVertexBuffer(C.layoutFacadeVerticalRangeArray,sos.members)),C.entranceBloom.layoutVertexArray.length&&(C.entranceBloom.layoutVertexBuffer=g.createVertexBuffer(C.entranceBloom.layoutVertexArray,fot.members),C.entranceBloom.layoutAttenuationBuffer=g.createVertexBuffer(C.entranceBloom.layoutAttenuationArray,nos.members)),this.uploadUpdatedColorBuffer(g),this.uploadUpdatedIndexBuffer(g)};this.uploaded||(_(this.buildingWithoutFacade),_(this.buildingWithFacade),this.groundEffect.upload(g)),this.groundEffect.uploadPaintProperties(g),this.programConfigurations.upload(g),this.uploaded=!0}destroy(){const g=_=>{_.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()))};g(this.buildingWithoutFacade),g(this.buildingWithFacade),this.groundEffect.destroy(),this.programConfigurations.destroy()}updateFootprintHiddenFlags(g,_,C=!0){let P=!1;const O=C?_:0,B=0|(C?-1:~_);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const W of g){const Y=this.footprints[W],ae=Y.hiddenFlags&B|O;Y.hiddenFlags!==ae&&(Y.hiddenFlags=ae,P=!0,this.groundEffect.updateHiddenByLandmarkRange(Y.groundEffectVertexOffset,Y.groundEffectVertexLength,Y.hiddenFlags!==0))}return P&&(this.indexArrayForConflationUploaded=!1),P}uploadUpdatedIndexBuffer(g){if(this.groundEffect.uploadHiddenByLandmark(g),this.indexArrayForConflationUploaded)return;const _=P=>{P.indexArray.length!==0&&(P.indexArrayForConflation.resize(P.indexArray.length),P.indexArrayForConflation.uint16.set(P.indexArray.uint16),P.entranceBloom.indexArrayForConflation.resize(P.entranceBloom.indexArray.length),P.entranceBloom.indexArrayForConflation.uint16.set(P.entranceBloom.indexArray.uint16))};_(this.buildingWithoutFacade),_(this.buildingWithFacade);for(const P of this.footprints){const O=P.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade,B=P.indicesOffset+P.indicesLength;if(P.hiddenFlags!==0){for(let Y=P.indicesOffset;Y{P.indexArray.length!==0&&(P.indexBuffer?P.indexBuffer.updateData(P.indexArrayForConflation):P.indexBuffer=g.createIndexBuffer(P.indexArrayForConflation,!0),P.entranceBloom.indexBuffer?P.entranceBloom.indexBuffer.updateData(P.entranceBloom.indexArrayForConflation):P.entranceBloom.indexBuffer=g.createIndexBuffer(P.entranceBloom.indexArrayForConflation,!0))};C(this.buildingWithoutFacade),C(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(g){const _=C=>{C.layoutColorBuffer?C.layoutColorBuffer.updateData(C.layoutColorArray):C.layoutColorBuffer=g.createVertexBuffer(C.layoutColorArray,got.members,!0),C.layoutFacadePaintArray&&(C.layoutFacadePaintBuffer?C.layoutFacadePaintBuffer.updateData(C.layoutFacadePaintArray):C.layoutFacadePaintBuffer=g.createVertexBuffer(C.layoutFacadePaintArray,eos.members,!0)),C.entranceBloom.layoutColorBuffer?C.entranceBloom.layoutColorBuffer.updateData(C.entranceBloom.layoutColorArray):C.entranceBloom.layoutColorBuffer=g.createVertexBuffer(C.entranceBloom.layoutColorArray,got.members,!0)};_(this.buildingWithoutFacade),_(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(g,_){const C=g.paint.get("building-ambient-occlusion-intensity");for(const P of this.footprints){if(4&P.hiddenFlags)continue;const O=_[P.promoteId],B=P.feature;B.properties["building-part"]="roof";const W=g.paint.get("building-color").evaluate(B,O,this.canonical).toPremultipliedRenderColor(this.lut),Y=g.paint.get("building-emissive-strength").evaluate(B,O,this.canonical);B.properties["building-part"]="wall";const ae=g.paint.get("building-color").evaluate(B,O,this.canonical).toPremultipliedRenderColor(this.lut),pe=g.paint.get("building-emissive-strength").evaluate(B,O,this.canonical);B.properties["building-part"]="window";const ve=g.paint.get("building-color").evaluate(B,O,this.canonical).toPremultipliedRenderColor(this.lut),_e=g.paint.get("building-emissive-strength").evaluate(B,O,this.canonical);B.properties["building-part"]="door";const Pe=g.paint.get("building-color").evaluate(B,O,this.canonical).toPremultipliedRenderColor(this.lut),De=g.paint.get("building-emissive-strength").evaluate(B,O,this.canonical),We=P.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const rt of P.parts){let xt,ut=W;rt.part===1?(ut=W,xt=Y):rt.part===0?(ut=ae,xt=pe):rt.part===2?(ut=ve,xt=_e):rt.part===3&&(ut=Pe,xt=De),xt=mt(xt,0,1);for(let St=0;StB.max.x||Y.max.xB.max.y||Y.max.yW.max.x||W.min.x>g||_>W.max.y||W.min.y>_||W.height<=C||oos(B,this.footprintsVertices.float32.subarray(2*W.footprintVertexOffset,2*(W.footprintVertexOffset+W.footprintVertexLength)),this.footprintsIndices.uint16.subarray(W.footprintIndexOffset,W.footprintIndexOffset+W.footprintIndexLength))&&(C=W.height,this.footprintLookup[O]=W,P=W.hiddenFlags!==0);if(C!==Number.NEGATIVE_INFINITY)return{height:C,hidden:P};this.footprintLookup[O]=void 0}}function oos(k,g,_){for(let C=0;C<_.length;C+=3){const P=_[C],O=_[C+1],B=_[C+2],W=g[2*P+0],Y=g[2*P+1],ae=g[2*O+0],pe=g[2*O+1],ve=g[2*B+0],_e=g[2*B+1],Pe=(W-ve)*(k.y-_e)-(Y-_e)*(k.x-ve),De=(ae-W)*(k.y-Y)-(pe-Y)*(k.x-W);if(Pe<0!=De<0&&Pe!==0&&De!==0)continue;const We=(ve-ae)*(k.y-pe)-(_e-pe)*(k.x-ae);if(We===0||We<0==Pe+De<=0)return!0}return!1}function los(k,g,_,C,P,O){const B=Math.pow(2,C.z-P.z);for(let W=0;W<_;W++){let Y=k.float32[2*(W+g)+0],ae=k.float32[2*(W+g)+1];Y=(Y+P.x*dr)*B-C.x*dr,ae=(ae+P.y*dr)*B-C.y*dr,O.push(new es(Y,ae))}}let vot,bot;wr(yot,"BuildingBucket",{omit:["layers"]}),wr(aRe,"BuildingGeometry"),wr(rRe,"BuildingBloomGeometry");const cos=$n([{name:"a_pos_normal",components:2,type:"Int16"},{name:"a_data",components:4,type:"Uint8"},{name:"a_linesofar",components:1,type:"Float32"}],4),dos=$n([{name:"a_z_offset_width",components:3,type:"Float32"}],4),uos=$n([{name:"a_elevation_ground_scale",components:1,type:"Float32"}],4),{members:hos}=cos,mos=$n([{name:"a_packed",components:3,type:"Float32"}]),{members:pos}=mos,fos=$n([{name:"a_pattern_data",components:3,type:"Float32"}]),{members:gos}=fos;class _ot{constructor(g,_){this.width=g,this.height=_,this.nextRow=0,this.image=new $E({width:g,height:_}),this.positions={},this.uploaded=!1}getDash(g,_){const C=this.getKey(g,_);return this.positions[C]}trim(){const g=this.width,_=this.height=ps(this.nextRow);this.image.resize({width:g,height:_})}getKey(g,_){return g.join(",")+_}getDashRanges(g,_,C){const P=[];let O=g.length%2==1?-g[g.length-1]*C:0,B=g[0]*C,W=!0;P.push({left:O,right:B,isDash:W,zeroLength:g[0]===0});let Y=g[0];for(let ae=1;ae1&&(Y=g[++W]);const pe=Math.abs(ae-Y.left),ve=Math.abs(ae-Y.right),_e=Math.min(pe,ve);let Pe;const De=O/C*(P+1);if(Y.isDash){const We=P-Math.abs(De);Pe=Math.sqrt(_e*_e+We*We)}else Pe=P-Math.sqrt(_e*_e+De*De);this.image.data[B+ae]=Math.max(0,Math.min(255,Pe+128))}}}addRegularDash(g,_){for(let Y=g.length-1;Y>=0;--Y){const ae=g[Y],pe=g[Y+1];ae.zeroLength?g.splice(Y,1):pe&&pe.isDash===ae.isDash&&(pe.left=ae.left,g.splice(Y,1))}const C=g[0],P=g[g.length-1];C.isDash===P.isDash&&(C.left=P.left-this.width,P.right=C.right+this.width);const O=this.width*this.nextRow;let B=0,W=g[B];for(let Y=0;Y1&&(W=g[++B]);const ae=Math.abs(Y-W.left),pe=Math.abs(Y-W.right),ve=Math.min(ae,pe);this.image.data[O+Y]=Math.max(0,Math.min(255,(W.isDash?ve:-ve)+_+128))}}addDash(g,_){const C=this.getKey(g,_);if(this.positions[C])return this.positions[C];const P=_==="round",O=P?7:0,B=2*O+1;if(this.nextRow+B>this.height)return qr("LineAtlas out of space"),null;g.length===0&&g.push(1);let W=0;for(let ve=0;ve_.fqid),this.index=g.index,this.projection=g.projection,this.hasPattern=!1,this.hasCrossSlope=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach(_=>{this.gradients[_.id]={}}),this.layoutVertexArray=new NL,this.layoutVertexArray2=new $b,this.patternVertexArray=new $b,this.indexArray=new Ru,this.programConfigurations=new st(g.layers,{zoom:g.zoom,lut:g.lut}),this.segments=new Ec,this.maxLineLength=0,this.zOffsetVertexArray=new $b,this.elevationGroundScaleVertexArray=new Bl,this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.tessellationStep=g.tessellationStep?g.tessellationStep:128,this.worldview=g.worldview,this.hasAppearances=null}updateFootprints(g,_){}updateAppearances(g,_,C,P){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(g,_,C,P){this.hasPattern=A8e("line",this.layers,this.pixelRatio,_);const O=this.layers[0].layout.get("line-sort-key");this.tileToMeter=Vn(C);const B=this.layers[0].layout.get("line-elevation-reference");if(B==="hd-road-markup")this.elevationType="road";else{const _e=this.layers[0].layout.get("line-z-offset"),Pe=_e.isConstant()&&!_e.constantOr(0);this.elevationType=B!=="sea"&&B!=="ground"&&Pe?"none":"offset",this.elevationType==="offset"&&B==="none"&&qr(`line-elevation-reference: ground is used for the layer ${this.layerIds[0]} because non-zero line-z-offset value was found.`),this.isSeaLevelReference=B==="sea"}const W=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&W!==void 0;const Y=[];for(const{feature:_e,id:Pe,index:De,sourceLayerIndex:We}of g){const Je=this.layers[0]._featureFilter.needGeometry,rt=eo(_e,Je);if(!this.layers[0]._featureFilter.filter(new Oi(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),rt,C))continue;const xt=O?O.evaluate(rt,{},C):void 0,ut={id:Pe,properties:_e.properties,type:_e.type,sourceLayerIndex:We,index:De,geometry:Je?rt.geometry:Ha(_e,C,P),patterns:{},sortKey:xt};Y.push(ut)}O&&Y.sort((_e,Pe)=>_e.sortKey-Pe.sortKey);const{lineAtlas:ae,featureIndex:pe}=_,ve=this.addConstantDashes(ae);for(const _e of Y){const{geometry:Pe,index:De,sourceLayerIndex:We}=_e;if(ve&&this.addFeatureDashes(_e,ae),this.hasPattern){const Je=E8e("line",this.layers,_e,this.zoom,this.pixelRatio,_);this.patternFeatures.push(Je)}else this.addFeature(_e,Pe,De,C,ae.positions,_.availableImages,_.brightness,_.elevationFeatures);pe.insert(g[De].feature,Pe,De,We,this.index)}}addConstantDashes(g){let _=!1;for(const C of this.layers){const P=C.paint.get("line-dasharray").value,O=C.layout.get("line-cap").value;if(P.kind!=="constant"||O.kind!=="constant")_=!0;else{const B=O.value,W=P.value;if(!W)continue;g.addDash(W,B)}}return _}addFeatureDashes(g,_){const C=this.zoom;for(const P of this.layers){const O=P.paint.get("line-dasharray").value,B=P.layout.get("line-cap").value;if(O.kind==="constant"&&B.kind==="constant")continue;let W,Y;if(O.kind==="constant"){if(W=O.value,!W)continue}else W=O.evaluate({zoom:C},g);Y=B.kind==="constant"?B.value:B.evaluate({zoom:C},g),_.addDash(W,Y),g.patterns[P.id]=[_.getKey(W,Y)]}}update(g,_,C,P,O,B,W,Y,ae){this.programConfigurations.updatePaintArrays(g,_,O,C,P,B,W,ae)}addFeatures(g,_,C,P,O,B){for(const W of this.patternFeatures)this.addFeature(W,W.geometry,W.index,_,C,P,B,g.elevationFeatures)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(g){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=g.createVertexBuffer(this.layoutVertexArray2,pos)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=g.createVertexBuffer(this.patternVertexArray,gos)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=g.createVertexBuffer(this.zOffsetVertexArray,dos.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=g.createVertexBuffer(this.elevationGroundScaleVertexArray,uos.members,!0)),this.layoutVertexBuffer=g.createVertexBuffer(this.layoutVertexArray,hos),this.indexBuffer=g.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(g),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.zOffsetVertexBuffer&&this.zOffsetVertexBuffer.destroy(),this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexBuffer.destroy(),this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}lineFeatureClips(g,_){let C,P;if(_&&_>0?(C=`mapbox_clip_start_${_}`,P=`mapbox_clip_end_${_}`):(C="mapbox_clip_start",P="mapbox_clip_end"),g.properties&&g.properties.hasOwnProperty(C)&&g.properties.hasOwnProperty(P))return{start:+g.properties[C],end:+g.properties[P]}}addFeature(g,_,C,P,O,B,W,Y){const ae=this.layers[0].layout,pe=ae.get("line-join").evaluate(g,{}),ve=ae.get("line-cap").evaluate(g,{}),_e=ae.get("line-miter-limit"),Pe=ae.get("line-round-limit");this.lineClips=this.lineFeatureClips(g),this.lineFeature=g;const De=!(!g.properties||!g.properties.hasOwnProperty("mapbox_line_metrics"))&&g.properties.mapbox_line_metrics;this.zOffsetValue=ae.get("line-z-offset").value;const We=this.layers[0].paint.get("line-width").value;if(We.kind!=="constant"&&We.isLineProgressConstant===!1&&(this.variableWidthValue=We),this.isSeaLevelReference){const Je=ae.get("line-elevation-ground-scale").value;Je.kind==="constant"&&Je.value===0||(this.elevationGroundScaleValue=Je)}if(this.elevationType==="road"){const Je=this.layoutVertexArray.length;if(!this.addElevatedRoadFeature(g,_,P,Y,pe,ve,_e,Pe)){const[rt,xt]=this.clipRuntimeLinesToTile(_,1);for(let ut=0;ut0?Rt.parentIndex:null)}this.fillNonElevatedRoadSegment(Je)}}else for(let Je=0;Je<_.length;Je++)this.addLine(_[Je],g,P,pe,ve,_e,Pe,void 0,De&&Je>0?Je:null);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,g,C,O,B,P,W,void 0,this.worldview)}computeSegNextDir(g,_){return g.nextPoint.sub(_.at(-2)).unit()}computeSegPrevDir(g,_){return _[1].sub(g.prevPoint).unit()}clipLinesToTile(g,_){return Gae(g,-_,-_,dr+_,dr+_)}clipRuntimeLinesToTile(g,_){const C=[];return[Gae(g,-_,-_,dr+_,dr+_,C),C]}addElevatedRoadFeature(g,_,C,P,O,B,W,Y){const ae=[],pe=Fc.getElevationFeature(g,P);if(pe){const ve=this.clipLinesToTile(_,1),_e=this.prepareElevatedLines(ve,pe,C);for(const Pe of _e)ae.push({geometry:Pe,elevation:pe,elevationTileID:C,segment:{progress:{min:0,max:1},nextDir:void 0,prevDir:void 0}})}if(ae.length===0)return!1;for(const ve of ae){const _e=this.layoutVertexArray.length;this.addLine(ve.geometry,g,C,O,B,W,Y);const Pe=new Kc(C,ve.elevationTileID);if(ve.elevation)for(let De=_e;De>1,this.layoutVertexArray.int16[6*De+1]>>1),Je=Pe.pointElevation(We,ve.elevation,.05);this.updateHeightRange(Je),this.zOffsetVertexArray.emplaceBack(Je,0,0)}else this.fillNonElevatedRoadSegment(_e)}return!0}prepareElevatedLines(g,_,C){if(_.constantHeight!=null)return g;const P=[],O=1/Vn(C);for(const B of g)Eis(B,new E1(_,O),0,P);return P}fillNonElevatedRoadSegment(g){for(let _=g;_0,_e=Y&&Y.progress.max<1;if(this.lineClips){let ys={min:this.lineClips.start,max:this.lineClips.end},hs=1;if(Y){const Nn=this.lineClips.end-this.lineClips.start;ys=function(Tn,Ln,Mn){return{min:Ao(Tn.min,Ln,Mn),max:Ao(Tn.max,Ln,Mn)}}(Y.progress,{min:0,max:1},ys),Nn>0&&(hs=(ys.max-ys.min)/Nn)}const ms=+_.properties.mapbox_clip_feature_len,vn=+_.properties.mapbox_clip_seg_len;if(Number.isNaN(ms)||Number.isNaN(vn)){for(let Tn=0;Tn=2&&g[De-1].equals(g[De-2]);)De--;let We=0;for(;We0,Pn=this.overscaling<=16?122880/(512*this.overscaling):0;if(hs&&ms==="round"){if(LnB&&(ms="bevel"),ms==="bevel"&&(Ln>2&&(ms="flipbevel"),Ln2*Pn){const mr=rt.sub(rt.sub(xt)._mult(Pn/Dn)._round());this.updateDistance(xt,mr),this.addCurrentVertex(mr,St,0,0,Je,as),xt=mr}this.updateDistance(xt,rt),Nn._mult(Ln),this.addCurrentVertex(rt,Nn,0,0,Je,as);const tr=rt.dist(ut);if(tr>2*Pn){const mr=rt.add(ut.sub(rt)._mult(Pn/tr)._round());this.updateDistance(rt,mr),this.addCurrentVertex(mr,Rt,0,0,Je,as),rt=mr}}else Nn._mult(Ln),this.addCurrentVertex(rt,Nn,0,0,Je,as);else if(ms==="flipbevel"){if(Ln>100)Nn=Rt.mult(-1);else{const Dn=Ln*St.add(Rt).mag()/St.sub(Rt).mag();Nn._perp()._mult(Dn*(fn?-1:1))}this.addCurrentVertex(rt,Nn,0,0,Je,as),this.addCurrentVertex(rt,Nn.mult(-1),0,0,Je,as)}else if(ms==="bevel"||ms==="fakeround"){const Dn=rt.dist(xt);let tr=1;if(this.elevationType==="offset"&&ms==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&as!=null&&xt&&ut){const Kr=4*Pn;Dn1){this.lineSoFar=g.w;const We=(_.x-g.x)/ve,Je=(_.y-g.y)/ve,rt=(_.z-g.z)/ve,xt=(_.w-g.w)/ve,ut=_.x-g.x,St=_.y-g.y,Rt=Math.sqrt(ut*ut+St*St);if(Rt===0)return;const Ft=-St/Rt,bs=ut/Rt,as=Ft,ys=bs,hs=-Ft,ms=-bs;for(let vn=1;vn=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,pe),Y.primitiveLength++),B?this.e2=pe:this.e1=pe,ae!=null&&this.zOffsetVertexArray.emplaceBack(ae.zOffset,ae.variableWidth,ae.variableWidth),this.elevationGroundScaleValue){const ve=ae?ae.elevationGroundScale:this.evaluateElevationGroundScale();this.elevationGroundScaleVertexArray.emplaceBack(ve)}}updateScaledDistance(){this.lineClips?(this.scaledDistance=this.distance/this.totalDistance,this.lineSoFar=this.totalFeatureLength*this.lineClips.start+this.distance):this.lineSoFar=this.distance}updateDistance(g,_){this.prevDistance=this.distance,this.distance+=g.dist(_),this.updateScaledDistance()}}function iRe(k,g,_){return k.x_||k.y_}let wot,jot;function Not(k,g,_){return g*(dr/(k.tileSize*Math.pow(2,_-k.tileID.overscaledZ)))}wr(sie,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const kot=(k,g,_)=>(1-_)*k+_*g;function Sot(k,g){return 1/Not(k,1,g.tileZoom)}function Cot(k,g,_,C){return k.translatePosMatrix(C||g.tileID.projMatrix,g,_.paint.get("line-translate"),_.paint.get("line-translate-anchor"))}const Aot=k=>{const g=[];Eot(k)&&g.push("RENDER_LINE_DASH"),k.paint.get("line-gradient")&&g.push("RENDER_LINE_GRADIENT"),k.paint.get("line-blend-mode")==="multiply"&&g.push("LINE_BLEND_MULTIPLY");const _=k.paint.get("line-trim-offset");_[0]===0&&_[1]===0||g.push("RENDER_LINE_TRIM_OFFSET"),k.paint.get("line-border-width").constantOr(1)!==0&&g.push("RENDER_LINE_BORDER");const C=k.layout.get("line-join").constantOr("miter")==="none",P=!!k.paint.get("line-pattern").constantOr(1);return C&&P&&g.push("LINE_JOIN_NONE"),g};function Eot(k){const g=k.paint.get("line-dasharray").value;return g.kind!=="constant"||g.value}let oRe;const Tot=()=>oRe||(oRe={layout:wot||(wot=new Wc({"line-cap":new or(Us.layout_line["line-cap"]),"line-join":new or(Us.layout_line["line-join"]),"line-miter-limit":new lr(Us.layout_line["line-miter-limit"]),"line-round-limit":new lr(Us.layout_line["line-round-limit"]),"line-sort-key":new or(Us.layout_line["line-sort-key"]),"line-z-offset":new or(Us.layout_line["line-z-offset"]),"line-elevation-reference":new lr(Us.layout_line["line-elevation-reference"]),"line-cross-slope":new lr(Us.layout_line["line-cross-slope"]),visibility:new lr(Us.layout_line.visibility),"line-width-unit":new lr(Us.layout_line["line-width-unit"]),"line-elevation-ground-scale":new or(Us.layout_line["line-elevation-ground-scale"])})),paint:jot||(jot=new Wc({"line-opacity":new or(Us.paint_line["line-opacity"]),"line-color":new or(Us.paint_line["line-color"]),"line-translate":new lr(Us.paint_line["line-translate"]),"line-translate-anchor":new lr(Us.paint_line["line-translate-anchor"]),"line-width":new or(Us.paint_line["line-width"]),"line-gap-width":new or(Us.paint_line["line-gap-width"]),"line-offset":new or(Us.paint_line["line-offset"]),"line-blur":new or(Us.paint_line["line-blur"]),"line-dasharray":new or(Us.paint_line["line-dasharray"]),"line-pattern":new or(Us.paint_line["line-pattern"]),"line-pattern-cross-fade":new lr(Us.paint_line["line-pattern-cross-fade"]),"line-gradient":new Iy(Us.paint_line["line-gradient"]),"line-trim-offset":new lr(Us.paint_line["line-trim-offset"]),"line-trim-fade-range":new lr(Us.paint_line["line-trim-fade-range"]),"line-trim-color":new lr(Us.paint_line["line-trim-color"]),"line-emissive-strength":new or(Us.paint_line["line-emissive-strength"]),"line-border-width":new or(Us.paint_line["line-border-width"]),"line-border-color":new or(Us.paint_line["line-border-color"]),"line-occlusion-opacity":new lr(Us.paint_line["line-occlusion-opacity"]),"line-blend-mode":new lr(Us.paint_line["line-blend-mode"]),"line-color-use-theme":new or({type:"string",default:"default","property-type":"data-driven"}),"line-gradient-use-theme":new or({type:"string",default:"default","property-type":"data-driven"}),"line-trim-color-use-theme":new or({type:"string",default:"default","property-type":"data-driven"}),"line-border-color-use-theme":new or({type:"string",default:"default","property-type":"data-driven"})}))},oRe);class bos extends or{possiblyEvaluate(g,_){return _=new Oi(Math.floor(_.zoom),{now:_.now,fadeDuration:_.fadeDuration,transition:_.transition,worldview:_.worldview}),super.possiblyEvaluate(g,_)}evaluate(g,_,C,P){return _=Object.assign({},_,{zoom:Math.floor(_.zoom)}),super.evaluate(g,_,C,P)}}let lK;function Mot(k,g){return g>0?g+2*k:k}const _os=$n([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_tex_size",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),wos=$n([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),jos=$n([{name:"a_projected_pos",components:4,type:"Float32"}],4);$n([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const Nos=$n([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),kos=$n([{name:"a_feature_index",components:1,type:"Float32"}],4),Sos=$n([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),Cos=$n([{name:"a_texb",components:2,type:"Uint16"}]),Aos=$n([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),Eos=$n([{name:"a_size_scale",components:1,type:"Float32"},{name:"a_padding",components:2,type:"Float32"},{name:"a_auto_z_offset",components:1,type:"Float32"}]);$n([{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 Pot=$n([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),Tos=$n([{name:"a_pos_2f",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);$n([{name:"triangle",components:3,type:"Uint16"}]),$n([{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"}]),$n([{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"}]),$n([{type:"Float32",name:"offsetX"}]),$n([{type:"Int16",name:"x"},{type:"Int16",name:"y"}]);const lRe=class S5e{constructor(g=null,_=0,C=4096){this.batchIndex=_,this.headerBuffer=null,this.propertiesBuffer=null,this.blockIndicesBuffer=null,this.context=g||null,this.propsDwords=C,this.totalBytes=4*this.propsDwords,this.headerData=new Uint32Array(S5e.HEADER_DWORDS),this.propertiesData=new Float32Array(this.propsDwords),this.blockIndicesData=new Uint32Array(this.propsDwords);for(let P=0;Pg.maxUniformBlockSize)throw new Error(`UBO size ${this.totalBytes} exceeds device limit ${g.maxUniformBlockSize}`);if(this.headerBuffer=_.createBuffer(),!this.headerBuffer)throw new Error("Failed to create header UBO buffer");if(_.bindBuffer(_.UNIFORM_BUFFER,this.headerBuffer),_.bufferData(_.UNIFORM_BUFFER,S5e.HEADER_BYTES,_.DYNAMIC_DRAW),this.propertiesBuffer=_.createBuffer(),!this.propertiesBuffer)throw new Error("Failed to create properties UBO buffer");if(_.bindBuffer(_.UNIFORM_BUFFER,this.propertiesBuffer),_.bufferData(_.UNIFORM_BUFFER,this.totalBytes,_.DYNAMIC_DRAW),this.blockIndicesBuffer=_.createBuffer(),!this.blockIndicesBuffer)throw new Error("Failed to create block-indices UBO buffer");_.bindBuffer(_.UNIFORM_BUFFER,this.blockIndicesBuffer),_.bufferData(_.UNIFORM_BUFFER,this.totalBytes,_.DYNAMIC_DRAW),_.bindBuffer(_.UNIFORM_BUFFER,null)}writeHeader(g){const _=this.headerData;_[0]=g.dataDrivenMask,_[1]=g.zoomDependentMask,_[2]=g.dataDrivenBlockSizeVec4,_[3]=g.offsets[0],_[4]=g.offsets[1],_[5]=g.offsets[2],_[6]=g.offsets[3],_[7]=g.offsets[4],_[8]=g.offsets[5],_[9]=g.offsets[6],_[10]=g.offsets[7],_[11]=g.offsets[8]}writeDataDrivenBlock(g,_,C){const P=4*C.dataDrivenBlockSizeVec4;if(P===0)return;const O=_*P;if(O+P>this.propertiesData.length)throw new Error(`UBO write out of bounds: feature index ${_} exceeds propertiesData capacity`);for(let B=0;B<9;B++)C.dataDrivenMask&1<{if(!W)return;const ae=C.getUniformBlockIndex(_,B);ae!==C.INVALID_INDEX&&(C.uniformBlockBinding(_,ae,Y),C.bindBufferBase(C.UNIFORM_BUFFER,Y,W))},O=3*this.batchIndex;P("SymbolPaintPropertiesHeaderUniform",this.headerBuffer,O),P("SymbolPaintPropertiesUniform",this.propertiesBuffer,O+1),P("SymbolPaintPropertiesIndexUniform",this.blockIndicesBuffer,O+2)}destroy(){if(this.context){const g=this.context.gl;this.headerBuffer&&(g.deleteBuffer(this.headerBuffer),this.headerBuffer=null),this.propertiesBuffer&&(g.deleteBuffer(this.propertiesBuffer),this.propertiesBuffer=null),this.blockIndicesBuffer&&(g.deleteBuffer(this.blockIndicesBuffer),this.blockIndicesBuffer=null)}}};lRe.HEADER_DWORDS=12,lRe.HEADER_BYTES=48;let cRe=lRe;function dRe(k,g,_,C){return[nz(255*k,255*g),nz(255*_,255*C)]}function Lot(k,g,_,C,P,O,B,W){return!!k&&(k.kind==="constant"?k.value==="none":k.kind==="composite"||k.kind==="source"?k.evaluate({zoom:0,brightness:O,worldview:W},g,_,P,C,B)==="none":typeof k=="string"&&k==="none")}wr(cRe,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});class uRe{constructor(g,_,C,P,O="",B,W){this.layer=g,this.zoom=_,this.lut=C,this.isText=P,this.propDefs=this._getPropDefs(),this.worldview=O,this.maxUniformBufferBindings=B||24,this.uboSizeDwords=W||4096,this.featureVertexRangesFromId=new Map,this.allFeatures=[],this.ubos=[],this.featureCount=0,this.cachedHeader=null,this.maxFeaturesPerBatch=0,this.propertyHashToUBOIndex=new Map,this.canDeduplicate=this._checkIfAllPropertiesAreConstant(g,P),this.cachedParams=null,this.cachedParamsNext=null,this.cachedBrightness=void 0,this.cachedConstantUniforms=null,this.cachedConstantRenderZoom=null,this.cachedConstantBrightness=void 0,this.activeAppearanceByVtIndex=new Map}_getPropDefs(){const g=this.isText?"text":"icon";return[{name:`${g}-color`,useThemeName:`${g}-color-use-theme`,isColor:!0},{name:`${g}-halo-color`,useThemeName:`${g}-halo-color-use-theme`,isColor:!0},{name:`${g}-opacity`,useThemeName:null,isColor:!1},{name:`${g}-halo-width`,useThemeName:null,isColor:!1},{name:`${g}-halo-blur`,useThemeName:null,isColor:!1},{name:`${g}-emissive-strength`,useThemeName:null,isColor:!1},{name:`${g}-occlusion-opacity`,useThemeName:null,isColor:!1},{name:"symbol-z-offset",useThemeName:null,isColor:!1},{name:`${g}-translate`,useThemeName:null,isColor:!1,isVec2:!0}]}buildHeader(){const g=this.layer.paint,_=this.propDefs;let C=0,P=0,O=0,B=0;const W=[0,0,0,0,0,0,0,0,0];for(let Y=0;Y<9;Y++){const{name:ae,isColor:pe,isVec2:ve}=_[Y],_e=g.get(ae),Pe=!(!_e||typeof _e.isConstant!="function"||_e.isConstant()),De=this._appearancesHavePaintProperties(ae),We=Pe||De,Je=!(!_e||!_e.value||_e.value.kind!=="composite"),rt=this.layer._transitionablePaint._values[ae],xt=!We&&(rt&&rt.value&&rt.value.expression&&rt.value.expression.kind)==="camera";We?(C|=1<_.hasPaintProperty(g):this.isText?_=>_.hasTextPaintProperties():_=>_.hasIconPaintProperties())}_checkIfAllPropertiesAreConstant(g,_){const C=g.paint,P=_?"text":"icon",O=[`${P}-color`,`${P}-halo-color`,`${P}-opacity`,`${P}-halo-width`,`${P}-halo-blur`,`${P}-emissive-strength`,`${P}-occlusion-opacity`,"symbol-z-offset",`${P}-translate`];for(const B of O){const W=C.get(B);if(W&&typeof W=="object"&&"isConstant"in W&&!W.isConstant())return!1}return!this._appearancesHavePaintProperties()}_hashDataDrivenValues(g,_){if(_.dataDrivenMask===0)return"";const C=[];for(let P=0;P<9;P++){if(!(_.dataDrivenMask&1<=De){qr(`Too many symbol features: batch ${_e} requires binding points up to ${3*_e+2}, device limit ${De}. Some features will render incorrectly.`);const Je={batchIndex:0,localFeatureIndex:0,vtFeatureIndex:_,featureId:Y};return this.allFeatures.push(Je),Y!=null&&(this.featureVertexRangesFromId.has(Y)||this.featureVertexRangesFromId.set(Y,[]),this.featureVertexRangesFromId.get(Y).push(Je)),0}this.ubos[_e]||(this.ubos[_e]=new cRe(W,_e,this.uboSizeDwords),this.ubos[_e].writeHeader(ae)),this.ubos[_e].writeDataDrivenBlock(pe,Pe,ae);const We={batchIndex:_e,localFeatureIndex:Pe,vtFeatureIndex:_,featureId:Y};return this.allFeatures.push(We),Y!=null&&(this.featureVertexRangesFromId.has(Y)||this.featureVertexRangesFromId.set(Y,[]),this.featureVertexRangesFromId.get(Y).push(We)),Pe}updateFeatures(g,_,C,P,O,B,W){if(this.layer=_,this.cachedConstantUniforms=null,!this.cachedHeader)return;const Y=this.cachedHeader;for(const ae of g){const pe=this.featureVertexRangesFromId.get(ae);if(!pe)continue;const ve=B[ae]||{};for(const _e of pe){if(!C)continue;const Pe=C.feature(_e.vtFeatureIndex);if(!Pe)continue;const De={type:Pe.type,id:ae,properties:Pe.properties||{},geometry:[]},We=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(_e.vtFeatureIndex):void 0,Je=this.evaluateAllProperties(De,ve,P,O,W,void 0,We);this.ubos[_e.batchIndex]&&this.ubos[_e.batchIndex].writeDataDrivenBlock(Je,_e.localFeatureIndex,Y)}}}updateDynamicExpressions(g,_,C,P,O,B){if(this.layer=g,this.cachedConstantUniforms=null,!this.cachedHeader)return;const W=this.cachedHeader;for(const Y of this.allFeatures){if(!_)continue;const ae=_.feature(Y.vtFeatureIndex);if(!ae)continue;const pe=Y.featureId!=null&&O[Y.featureId]||{},ve={type:ae.type,id:Y.featureId,properties:ae.properties||{},geometry:[]},_e=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(Y.vtFeatureIndex):void 0,Pe=this.evaluateAllProperties(ve,pe,C,P,B,void 0,_e);this.ubos[Y.batchIndex]&&this.ubos[Y.batchIndex].writeDataDrivenBlock(Pe,Y.localFeatureIndex,W)}}updateFeaturePaintForAppearance(g,_,C,P,O,B,W){if(!this.layer||(this.activeAppearanceByVtIndex||(this.activeAppearanceByVtIndex=new Map),this.activeAppearanceByVtIndex.set(g,W||null),!this.cachedHeader))return!1;const Y=this.cachedHeader;if(Y.dataDrivenMask===0)return!1;let ae=!1;for(const pe of this.allFeatures){if(pe.vtFeatureIndex!==g)continue;const ve=this.evaluateAllProperties(_,C,P,O,B,void 0,W);this.ubos[pe.batchIndex]&&(this.ubos[pe.batchIndex].writeDataDrivenBlock(ve,pe.localFeatureIndex,Y),ae=!0)}return ae}getConstantUniformValues(g,_){const C=this.cachedHeader,P=!(!C||!C.cameraMask);if(this.cachedConstantUniforms&&this.cachedConstantBrightness===_&&(!P||this.cachedConstantRenderZoom===g))return this.cachedConstantUniforms;const O=this.layer.paint,B=this.propDefs,W=P?new Oi(g,{brightness:_,worldview:this.worldview}):null,Y={type:1,id:void 0,properties:{},geometry:[]},ae=_e=>{const Pe=B[_e],De=O.get(Pe.name);if(!De)return[0,0,0,1];const We=Pe.useThemeName?O.get(Pe.useThemeName):void 0,Je=Lot(We&&typeof We!="string"?We.value:void 0,Y,{},[],void 0,_,void 0,this.worldview)?null:this.lut;let rt;rt=C&&C.cameraMask&1<<_e&&W?De.property.evaluate(De.value,W,Y,{},void 0,[]):De.constantOr(Zs.transparent);const xt=(rt||Zs.transparent).toNonPremultipliedRenderColor(Je);return[xt.r,xt.g,xt.b,xt.a]},pe=(_e,Pe)=>{const De=O.get(B[_e].name);if(!De)return Pe;if(C&&C.cameraMask&1<<_e&&W){const We=De.property.evaluate(De.value,W,Y,{},void 0,[]);return We??Pe}return De.constantOr(Pe)},ve={fill_np_color:ae(0),halo_np_color:ae(1),opacity:pe(2,1),halo_width:pe(3,0),halo_blur:pe(4,0),emissive_strength:pe(5,0),occlusion_opacity:pe(6,1),z_offset:pe(7,0)};return this.cachedConstantUniforms=ve,this.cachedConstantRenderZoom=g,this.cachedConstantBrightness=_,ve}upload(g){for(const _ of this.ubos)_.upload(g)}bind(g,_,C=0){this.ubos[C]&&this.ubos[C].bind(g,_)}destroy(){for(const g of this.ubos)g.destroy();this.ubos=[],this.featureVertexRangesFromId.clear(),this.allFeatures=[],this.featureCount=0,this.cachedHeader=null,this.maxFeaturesPerBatch=0,this.propertyHashToUBOIndex&&this.propertyHashToUBOIndex.clear()}}wr(uRe,"SymbolPropertyBinderUBO",{omit:["layer","cachedParams","cachedParamsNext","cachedBrightness","propertyHashToUBOIndex","cachedConstantUniforms","cachedConstantRenderZoom","cachedConstantBrightness","activeAppearanceByVtIndex"]});var jp=24;function Mos(k,g,_){return k.sections.forEach(C=>{C.text=function(P,O,B){const W=O.layout.get("text-transform").evaluate(B,{});return W==="uppercase"?P=P.toLocaleUpperCase():W==="lowercase"&&(P=P.toLocaleLowerCase()),Dx.applyArabicShaping&&(P=Dx.applyArabicShaping(P)),P}(C.text,g,_)}),k}const cK={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂","←":"↑","→":"↓"};function Pos(k){return k==="︶"||k==="﹈"||k==="︸"||k==="﹄"||k==="﹂"||k==="︾"||k==="︼"||k==="︺"||k==="︘"||k==="﹀"||k==="︐"||k==="︓"||k==="︔"||k==="`"||k===" ̄"||k==="︑"||k==="︒"}function Los(k){return k==="︵"||k==="﹇"||k==="︷"||k==="﹃"||k==="﹁"||k==="︽"||k==="︻"||k==="︹"||k==="︗"||k==="︿"}const hRe=4294967296,Iot=1/hRe,Rot=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");let nie=class{constructor(k=new Uint8Array(16)){this.buf=ArrayBuffer.isView(k)?k:new Uint8Array(k),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(k,g,_=this.length){for(;this.pos<_;){const C=this.readVarint(),P=C>>3,O=this.pos;this.type=7&C,k(P,g,this),this.pos===O&&this.skip(C)}return g}readMessage(k,g){return this.readFields(k,g,this.readVarint()+this.pos)}readFixed32(){const k=this.dataView.getUint32(this.pos,!0);return this.pos+=4,k}readSFixed32(){const k=this.dataView.getInt32(this.pos,!0);return this.pos+=4,k}readFixed64(){const k=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*hRe;return this.pos+=8,k}readSFixed64(){const k=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*hRe;return this.pos+=8,k}readFloat(){const k=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,k}readDouble(){const k=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,k}readVarint(k){const g=this.buf;let _,C;return C=g[this.pos++],_=127&C,C<128?_:(C=g[this.pos++],_|=(127&C)<<7,C<128?_:(C=g[this.pos++],_|=(127&C)<<14,C<128?_:(C=g[this.pos++],_|=(127&C)<<21,C<128?_:(C=g[this.pos],_|=(15&C)<<28,function(P,O,B){const W=B.buf;let Y,ae;if(ae=W[B.pos++],Y=(112&ae)>>4,ae<128||(ae=W[B.pos++],Y|=(127&ae)<<3,ae<128)||(ae=W[B.pos++],Y|=(127&ae)<<10,ae<128)||(ae=W[B.pos++],Y|=(127&ae)<<17,ae<128)||(ae=W[B.pos++],Y|=(127&ae)<<24,ae<128)||(ae=W[B.pos++],Y|=(1&ae)<<31,ae<128))return mz(P,Y,O);throw new Error("Expected varint not more than 10 bytes")}(_,k,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const k=this.readVarint();return k%2==1?(k+1)/-2:k/2}readBoolean(){return!!this.readVarint()}readString(){const k=this.readVarint()+this.pos,g=this.pos;return this.pos=k,k-g>=12&&Rot?Rot.decode(this.buf.subarray(g,k)):function(_,C,P){let O="",B=C;for(;B239?4:W>223?3:W>191?2:1;if(B+_e>P)break;_e===1?W<128&&(ve=W):_e===2?(Y=_[B+1],(192&Y)==128&&(ve=(31&W)<<6|63&Y,ve<=127&&(ve=null))):_e===3?(Y=_[B+1],ae=_[B+2],(192&Y)==128&&(192&ae)==128&&(ve=(15&W)<<12|(63&Y)<<6|63&ae,(ve<=2047||ve>=55296&&ve<=57343)&&(ve=null))):_e===4&&(Y=_[B+1],ae=_[B+2],pe=_[B+3],(192&Y)==128&&(192&ae)==128&&(192&pe)==128&&(ve=(15&W)<<18|(63&Y)<<12|(63&ae)<<6|63&pe,(ve<=65535||ve>=1114112)&&(ve=null))),ve===null?(ve=65533,_e=1):ve>65535&&(ve-=65536,O+=String.fromCharCode(ve>>>10&1023|55296),ve=56320|1023&ve),O+=String.fromCharCode(ve),B+=_e}return O}(this.buf,g,k)}readBytes(){const k=this.readVarint()+this.pos,g=this.buf.subarray(this.pos,k);return this.pos=k,g}readPackedVarint(k=[],g){const _=this.readPackedEnd();for(;this.pos<_;)k.push(this.readVarint(g));return k}readPackedSVarint(k=[]){const g=this.readPackedEnd();for(;this.pos127;);else if(g===2)this.pos=this.readVarint()+this.pos;else if(g===5)this.pos+=4;else{if(g!==1)throw new Error(`Unimplemented type: ${g}`);this.pos+=8}}writeTag(k,g){this.writeVarint(k<<3|g)}realloc(k){let g=this.length||16;for(;g268435455||k<0?function(g,_){let C,P;if(g>=0?(C=g%4294967296|0,P=g/4294967296|0):(C=~(-g%4294967296),P=~(-g/4294967296),4294967295^C?C=C+1|0:(C=0,P=P+1|0)),g>=18446744073709552e3||g<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");_.realloc(10),function(O,B,W){W.buf[W.pos++]=127&O|128,O>>>=7,W.buf[W.pos++]=127&O|128,O>>>=7,W.buf[W.pos++]=127&O|128,O>>>=7,W.buf[W.pos++]=127&O|128,W.buf[W.pos]=127&(O>>>=7)}(C,0,_),function(O,B){const W=(7&O)<<4;B.buf[B.pos++]|=W|((O>>>=3)?128:0),O&&(B.buf[B.pos++]=127&O|((O>>>=7)?128:0),O&&(B.buf[B.pos++]=127&O|((O>>>=7)?128:0),O&&(B.buf[B.pos++]=127&O|((O>>>=7)?128:0),O&&(B.buf[B.pos++]=127&O|((O>>>=7)?128:0),O&&(B.buf[B.pos++]=127&O)))))}(P,_)}(k,this):(this.realloc(4),this.buf[this.pos++]=127&k|(k>127?128:0),k<=127||(this.buf[this.pos++]=127&(k>>>=7)|(k>127?128:0),k<=127||(this.buf[this.pos++]=127&(k>>>=7)|(k>127?128:0),k<=127||(this.buf[this.pos++]=k>>>7&127))))}writeSVarint(k){this.writeVarint(k<0?2*-k-1:2*k)}writeBoolean(k){this.writeVarint(+k)}writeString(k){k=String(k),this.realloc(4*k.length),this.pos++;const g=this.pos;this.pos=function(C,P,O){for(let B,W,Y=0;Y55295&&B<57344){if(!W){B>56319||Y+1===P.length?(C[O++]=239,C[O++]=191,C[O++]=189):W=B;continue}if(B<56320){C[O++]=239,C[O++]=191,C[O++]=189,W=B;continue}B=W-55296<<10|B-56320|65536,W=null}else W&&(C[O++]=239,C[O++]=191,C[O++]=189,W=null);B<128?C[O++]=B:(B<2048?C[O++]=B>>6|192:(B<65536?C[O++]=B>>12|224:(C[O++]=B>>18|240,C[O++]=B>>12&63|128),C[O++]=B>>6&63|128),C[O++]=63&B|128)}return O}(this.buf,k,this.pos);const _=this.pos-g;_>=128&&Dot(g,_,this),this.pos=g-1,this.writeVarint(_),this.pos+=_}writeFloat(k){this.realloc(4),this.dataView.setFloat32(this.pos,k,!0),this.pos+=4}writeDouble(k){this.realloc(8),this.dataView.setFloat64(this.pos,k,!0),this.pos+=8}writeBytes(k){const g=k.length;this.writeVarint(g),this.realloc(g);for(let _=0;_=128&&Dot(_,C,this),this.pos=_-1,this.writeVarint(C),this.pos+=C}writeMessage(k,g,_){this.writeTag(k,2),this.writeRawMessage(g,_)}writePackedVarint(k,g){g.length&&this.writeMessage(k,Ios,g)}writePackedSVarint(k,g){g.length&&this.writeMessage(k,Ros,g)}writePackedBoolean(k,g){g.length&&this.writeMessage(k,Fos,g)}writePackedFloat(k,g){g.length&&this.writeMessage(k,Dos,g)}writePackedDouble(k,g){g.length&&this.writeMessage(k,Oos,g)}writePackedFixed32(k,g){g.length&&this.writeMessage(k,zos,g)}writePackedSFixed32(k,g){g.length&&this.writeMessage(k,Bos,g)}writePackedFixed64(k,g){g.length&&this.writeMessage(k,Uos,g)}writePackedSFixed64(k,g){g.length&&this.writeMessage(k,qos,g)}writeBytesField(k,g){this.writeTag(k,2),this.writeBytes(g)}writeFixed32Field(k,g){this.writeTag(k,5),this.writeFixed32(g)}writeSFixed32Field(k,g){this.writeTag(k,5),this.writeSFixed32(g)}writeFixed64Field(k,g){this.writeTag(k,1),this.writeFixed64(g)}writeSFixed64Field(k,g){this.writeTag(k,1),this.writeSFixed64(g)}writeVarintField(k,g){this.writeTag(k,0),this.writeVarint(g)}writeSVarintField(k,g){this.writeTag(k,0),this.writeSVarint(g)}writeStringField(k,g){this.writeTag(k,2),this.writeString(g)}writeFloatField(k,g){this.writeTag(k,5),this.writeFloat(g)}writeDoubleField(k,g){this.writeTag(k,1),this.writeDouble(g)}writeBooleanField(k,g){this.writeVarintField(k,+g)}};function mz(k,g,_){return _?4294967296*g+(k>>>0):4294967296*(g>>>0)+(k>>>0)}function Dot(k,g,_){const C=g<=16383?1:g<=2097151?2:g<=268435455?3:Math.floor(Math.log(g)/(7*Math.LN2));_.realloc(C);for(let P=_.pos-1;P>=k;P--)_.buf[P+C]=_.buf[P]}function Ios(k,g){for(let _=0;_=0&&C>=g&&rie[this.text.charCodeAt(C)];C--)_--;this.text=this.text.substring(g,_),this.sectionIndex=this.sectionIndex.slice(g,_)}substring(g,_){const C=new pz;return C.text=this.text.substring(g,_),C.sectionIndex=this.sectionIndex.slice(g,_),C.sections=this.sections,C}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((g,_)=>Math.max(g,this.sections[_].scale),0)}addTextSection(g,_){this.text+=g.text,this.sections.push(dK.forText(g.scale,g.fontStack||_));const C=this.sections.length-1;for(let P=0;P=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function mRe(k,g,_,C,P,O,B,W,Y,ae,pe,ve,_e,Pe,De,We=1,Je=1){const rt=pz.fromFeature(k,P,We,Je);ve===L1.vertical&&rt.verticalizePunctuation(_e);let xt=[];const ut=function(as,ys,hs,ms,vn,Nn,Tn=1){if(!as)return[];const Ln=[],Mn=function(Pn,Dn,tr,mr,ta,Cr,Nr=1){let pr=0;for(let Kr=0;Kr=0;let fn=0;for(let Pn=0;Pn0&&Ox>to&&(to=Ox)}else{const sf=hs[ru.fontStack];if(!sf)continue;sf[au]&&(Ou=sf[au]);const R0=ys[ru.fontStack];if(!R0)continue;const kg=R0.glyphs[au];if(!kg)continue;if(Rh=kg.metrics,kp=au!==8203?jp:0,Nr){const pu=R0.ascender!==void 0?Math.abs(R0.ascender):0,Ox=R0.descender!==void 0?Math.abs(R0.descender):0,nf=(pu+Ox)*Du;mu-_/2;){if(B--,B<0)return!1;W-=k[B].dist(O),O=k[B]}W+=k[B].dist(k[B+1]),B++;const Y=[];let ae=0;for(;W<_/2;){const pe=k[B],ve=k[B+1];if(!ve)return!1;let _e=k[B-1].angleTo(pe)-pe.angleTo(ve);for(_e=Math.abs((_e+3*Math.PI)%(2*Math.PI)-Math.PI),Y.push({distance:W,angleDelta:_e}),ae+=_e;W-Y[0].distance>C;)ae-=Y.shift().angleDelta;if(ae>P)return!1;B++,W+=pe.dist(ve)}return!0}function Got(k){let g=0;for(let _=0;_ae){const De=(ae-Y)/Pe,We=Es(ve.x,_e.x,De),Je=Es(ve.y,_e.y,De),rt=new W3(We,Je,0,_e.angleTo(ve),pe);return!B||Hot(k,rt,W,B,g)?rt:void 0}Y+=Pe}}function Yos(k,g,_,C,P,O,B,W,Y){const ae=Wot(C,O,B),pe=Kot(C,P),ve=pe*B,_e=k[0].x===0||k[0].x===Y||k[0].y===0||k[0].y===Y;return g-ve=0&&St=0&&Rt=0&&_e+ae<=pe){const Ft=new W3(St,Rt,0,xt,De);C&&!Hot(k,Ft,O,C,P)||Pe.push(Ft)}}ve+=rt}return W||Pe.length||B||(Pe=Yot(k,ve/2,_,C,P,O,B,!0,Y)),Pe}function Zot(k){let g=0,_=0;for(const B of k)g+=B.w*B.h,_=Math.max(_,B.w);k.sort((B,W)=>W.h-B.h);const C=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(g/.95)),_),h:1/0}];let P=0,O=0;for(const B of k)for(let W=C.length-1;W>=0;W--){const Y=C[W];if(!(B.w>Y.w||B.h>Y.h)){if(B.x=Y.x,B.y=Y.y,O=Math.max(O,B.y+B.h),P=Math.max(P,B.x+B.w),B.w===Y.w&&B.h===Y.h){const ae=C.pop();ae&&Wg.id?1:k.versiong.version?1:k.sxg.sx?1:k.syg.sy?1:0}function yRe(k){let g=0;for(let _=0;_0,Xot(g,C,this.iconDescriptors,O),Xot(_,C,this.patternDescriptors,O),this.iconDescriptors.sort(iie),this.patternDescriptors.sort(iie);let B=0;const W=P?P.data:"";W&&(B=WN(B,yRe(W))),B=WN(B,1);for(const Y of this.iconDescriptors)B=WN(B,yRe(Y.id)),B=WN(B,Y.version),B=WN(B,Y.sx),B=WN(B,Y.sy);B=WN(B,1);for(const Y of this.patternDescriptors)B=WN(B,yRe(Y.id)),B=WN(B,Y.version),B=WN(B,Y.sx),B=WN(B,Y.sy);this.hash=B}subsetOf(g){return this.isSubsetArray(this.iconDescriptors,g.iconDescriptors,iie)&&this.isSubsetArray(this.patternDescriptors,g.patternDescriptors,iie)}isSubsetArray(g,_,C){let P=0,O=0;if(g.length>_.length)return!1;for(;P{const B=P.variant.id.toString().localeCompare(O.variant.id.toString());return B!==0?B:P.variant.sx!==O.variant.sx?P.variant.sx-O.variant.sx:P.variant.sy!==O.variant.sy?P.variant.sy-O.variant.sy:0});const C=new Map;for(const P of _)C.set(P.key,P.value);return C}class Qot{constructor(g){this.sourceAtlasHash=g}}class Jot{constructor(g,_,C,P){const O=new Map,B=new Map;this.haveRenderCallbacks=[];const W=[],Y=P!==void 0,ae=Y?new Map:void 0,pe=Y?_Re(g,ae):g,ve=Y?_Re(_,ae):_;this.addImages(pe,O,1,W),this.addImages(ve,B,2,W);const{w:_e,h:Pe}=Zot(W),De=new rx({width:_e||1,height:Pe||1});for(const[We,Je]of pe.entries()){const rt=O.get(We).paddedRect;rx.copy(Je.data,De,{x:0,y:0},{x:rt.x+1,y:rt.y+1},Je.data,null,Je.sdf)}for(const[We,Je]of ve.entries()){const rt=B.get(We),xt=rt.paddedRect;let ut=rt.padding;const St=xt.x+ut,Rt=xt.y+ut,Ft=Je.data.width,bs=Je.data.height;ut=ut>1?ut-1:ut,rx.copy(Je.data,De,{x:0,y:0},{x:St,y:Rt},Je.data,C),rx.copy(Je.data,De,{x:0,y:bs-ut},{x:St,y:Rt-ut},{width:Ft,height:ut},C),rx.copy(Je.data,De,{x:0,y:0},{x:St,y:Rt+bs},{width:Ft,height:ut},C),rx.copy(Je.data,De,{x:Ft-ut,y:0},{x:St-ut,y:Rt},{width:ut,height:bs},C),rx.copy(Je.data,De,{x:0,y:0},{x:St+Ft,y:Rt},{width:ut,height:bs},C),rx.copy(Je.data,De,{x:Ft-ut,y:bs-ut},{x:St-ut,y:Rt-ut},{width:ut,height:ut},C),rx.copy(Je.data,De,{x:0,y:bs-ut},{x:St+Ft,y:Rt-ut},{width:ut,height:ut},C),rx.copy(Je.data,De,{x:0,y:0},{x:St+Ft,y:Rt+bs},{width:ut,height:ut},C),rx.copy(Je.data,De,{x:Ft-ut,y:0},{x:St-ut,y:Rt+bs},{width:ut,height:ut},C)}this.lut=C,this.image=De,this.iconPositions=O,this.patternPositions=B,Y&&(this.contentDescriptor=new vRe(pe,ve,P,C,ae))}addImages(g,_,C,P){for(const[O,B]of g.entries()){const{bin:W,imagePosition:Y,imageVariant:ae}=bRe(O,B,C);_.set(O,Y),P.push(W),B.hasRenderCallback&&this.haveRenderCallbacks.push(ae.id)}}patchUpdatedImages(g,_,C,P){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(O=>g.hasImage(O,C)),g.dispatchRenderCallbacks(this.haveRenderCallbacks,C);for(const O of g.getUpdatedImages(C)){for(const B of this.iconPositions.keys()){const W=tu.parse(B);if(ym.isEqual(W.id,O)){const Y=g.getImage(O,C);this.patchUpdatedImage(this.iconPositions.get(B),Y,_,null)}}for(const B of this.patternPositions.keys()){const W=tu.parse(B);if(ym.isEqual(W.id,O)){const Y=g.getImage(O,C);this.patchUpdatedImage(this.patternPositions.get(B),Y,_,P||this.lut)}}}}patchUpdatedImage(g,_,C,P=null){if(!g||!_||g.version===_.version)return;g.version=_.version;const[O,B]=g.tl,W=g.sdf;if(this.lut||W){const Y={width:_.data.width,height:_.data.height},ae=new rx(Y);rx.copy(_.data,ae,{x:0,y:0},{x:0,y:0},Y,P,W),C.update(ae,{position:{x:O,y:B},recreateWhenResize:!1})}else C.update(_.data,{position:{x:O,y:B},recreateWhenResize:!1})}}wr(uK,"ImagePosition"),wr(Jot,"ImageAtlas",{omit:["lut"]}),wr(Qot,"ImageAtlasReference");class hK{constructor(g){this.pendingRequests=new Map,this.cachedRanges=new Map,this.useServerFontComposition=!g||g.useServerFontComposition===void 0||g.useServerFontComposition}loadGlyphRange(g,_,C,P,O){if(this.useServerFontComposition)return void hK.loadGlyphRange(g,_,C,P,O);const B=g.split(",").map(W=>W.trim()).filter(W=>W.length>0);B.length!==0?B.length!==1?this._loadMultipleFonts(B,_,C,P,O):this._loadFont(B[0],_,C,P,O):O(new Error("Empty fontstack"))}_loadMultipleFonts(g,_,C,P,O){const B=g.map(()=>null),W={completed:0,firstError:null,callbackCalled:!1},Y=(ae,pe,ve)=>{if(!W.callbackCalled&&(pe&&!W.firstError&&(W.firstError=pe),ve&&(B[ae]=ve),W.completed++,W.completed===g.length)){W.callbackCalled=!0;const _e=B.filter(De=>De!==null);if(_e.length===0)return void O(W.firstError||new Error("All fonts failed to load"));const Pe=this._composeGlyphs(_e);O(null,Pe)}};for(let ae=0;ae{Y(ae,pe,ve)})}_loadFont(g,_,C,P,O){const B=`${g}:${_}`;if(this.cachedRanges.has(B)){const Y=this.cachedRanges.get(B);return void fd.frame(()=>O(null,Y))}const W=this.pendingRequests.get(B);W?W.push(O):(this.pendingRequests.set(B,[O]),hK.loadGlyphRange(g,_,C,P,(Y,ae)=>{Y||this.cachedRanges.set(B,ae||null);const pe=this.pendingRequests.get(B);if(this.pendingRequests.delete(B),pe)for(const ve of pe)ve(Y,ae)}))}_composeGlyphs(g){const _={};let C,P;for(const O of g)if(C===void 0&&O.ascender!==void 0&&(C=O.ascender),P===void 0&&O.descender!==void 0&&(P=O.descender),O.glyphs)for(const B in O.glyphs)_[B]===void 0&&(_[B]=O.glyphs[B]);return{glyphs:_,ascender:C,descender:P}}}hK.loadGlyphRange=function(k,g,_,C,P){const O=256*g,B=O+255,W=C.transformRequest(C.normalizeGlyphsURL(_).replace("{fontstack}",k).replace("{range}",`${O}-${B}`),Mu.Glyphs);Qh(W,(Y,ae)=>{if(Y)P(Y);else if(ae){const pe={},ve=function(_e){return new nie(_e).readFields($os,{})}(ae);for(const _e of ve.glyphs)pe[_e.id]=_e;P(null,{glyphs:pe,ascender:ve.ascender,descender:ve.descender})}})};const mK=1e20;function elt(k,g,_,C,P,O,B,W,Y){for(let ae=g;ae-1);Y++,O[Y]=W,B[Y]=ae,B[Y+1]=mK}for(let W=0,Y=0;W{if(B){P.ascender=B.ascender,P.descender=B.descender;for(const W in B.glyphs)this._doesCharSupportLocalGlyph(+W)||(P.glyphs[+W]=B.glyphs[+W]);P.ranges[_]=!0}for(const W of P.requests[_]||[])W(O,B);delete P.requests[_]}))}getGlyphs(g,_){const C=[],P=this.url||_a.GLYPHS_URL;for(const O in g)for(const B of g[O])C.push({stack:O,id:B});ts(C,({stack:O,id:B},W)=>{let Y=this.entries[O];Y||(Y=this.entries[O]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let ae=Y.glyphs[B];if(ae!==void 0)return void W(null,{stack:O,id:B,glyph:ae});if(ae=this._tinySDF(Y,O,B),ae)return Y.glyphs[B]=ae,void W(null,{stack:O,id:B,glyph:ae});const pe=Math.floor(B/256);if(256*pe>65535)return qr("glyphs > 65535 not supported"),void W(null,{stack:O,id:B,glyph:ae});if(Y.ranges[pe])return void W(null,{stack:O,id:B,glyph:ae});let ve=Y.requests[pe];ve||(ve=Y.requests[pe]=[],this.glyphLoader.loadGlyphRange(O,pe,P,this.requestManager,(_e,Pe)=>{if(Pe){Y.ascender=Pe.ascender,Y.descender=Pe.descender;for(const De in Pe.glyphs)this._doesCharSupportLocalGlyph(+De)||(Y.glyphs[+De]=Pe.glyphs[+De]);Y.ranges[pe]=!0}for(const De of ve)De(_e,Pe);delete Y.requests[pe]})),ve.push((_e,Pe)=>{_e?W(_e):Pe&&W(null,{stack:O,id:B,glyph:Pe.glyphs[B]||null})})},(O,B)=>{if(O)_(O);else if(B){const W={};for(const{stack:Y,id:ae,glyph:pe}of B)W[Y]===void 0&&(W[Y]={}),W[Y].glyphs===void 0&&(W[Y].glyphs={}),W[Y].glyphs[ae]=pe&&{id:pe.id,bitmap:pe.bitmap.clone(),metrics:pe.metrics},W[Y].ascender=this.entries[Y].ascender,W[Y].descender=this.entries[Y].descender;_(null,W)}})}_doesCharSupportLocalGlyph(g){return this.localGlyphMode!==wRe.none&&(this.localGlyphMode===wRe.all?!!this.localFontFamily:!!this.localFontFamily&&(tx(g)||J_(g)||N1(g)||bp(g)||Ob(g)||Vj(g)||(_=g)>=131072&&_<=173791||(C=>C>=66736&&C<=66815)(g)));var _}_tinySDF(g,_,C){const P=this.localFontFamily;if(!P||!this._doesCharSupportLocalGlyph(C))return;let O=g.tinySDF;if(!O){let Je="400";/bold/i.test(_)?Je="900":/medium/i.test(_)?Je="500":/light/i.test(_)&&(Je="200"),O=g.tinySDF=new oie.TinySDF({fontFamily:P,fontWeight:Je,fontSize:48,buffer:6,radius:16}),O.fontWeight=Je}const B=O.fontWeight;if(this.localGlyphs[B][C])return this.localGlyphs[B][C];const W=String.fromCodePoint(C),{data:Y,width:ae,height:pe,glyphWidth:ve,glyphHeight:_e,glyphLeft:Pe,glyphTop:De,glyphAdvance:We}=O.draw(W);return this.localGlyphs[B][C]={id:C,bitmap:new $E({width:ae,height:pe},Y),metrics:{width:ve/2,height:_e/2,left:Pe/2,top:De/2-27,advance:We/2,localGlyph:!0}}}}function slt(k,g){return k+g[1]-g[0]}function jRe(k,g,_,C,P=1){const O=[],B=k.imagePrimary,W=B.pixelRatio,Y=B.paddedRect.w-2,ae=B.paddedRect.h-2,pe=(k.right-k.left)*P,ve=(k.bottom-k.top)*P,_e=B.stretchX||[[0,Y]],Pe=B.stretchY||[[0,ae]],De=_e.reduce(slt,0),We=Pe.reduce(slt,0),Je=Y-De,rt=ae-We;let xt=0,ut=De,St=0,Rt=We,Ft=0,bs=Je,as=0,ys=rt;if(B.content&&C){const ms=B.content;xt=lie(_e,0,ms[0]),St=lie(Pe,0,ms[1]),ut=lie(_e,ms[0],ms[2]),Rt=lie(Pe,ms[1],ms[3]),Ft=ms[0]-xt,as=ms[1]-St,bs=ms[2]-ms[0]-ut,ys=ms[3]-ms[1]-Rt}const hs=(ms,vn,Nn,Tn)=>{const Ln=cie(ms.stretch-xt,ut,pe,k.left*P),Mn=die(ms.fixed-Ft,bs,ms.stretch,De),Qn=cie(vn.stretch-St,Rt,ve,k.top*P),fn=die(vn.fixed-as,ys,vn.stretch,We),Pn=cie(Nn.stretch-xt,ut,pe,k.left*P),Dn=die(Nn.fixed-Ft,bs,Nn.stretch,De),tr=cie(Tn.stretch-St,Rt,ve,k.top*P),mr=die(Tn.fixed-as,ys,Tn.stretch,We),ta=new es(Ln,Qn),Cr=new es(Pn,Qn),Nr=new es(Pn,tr),pr=new es(Ln,tr),Kr=new es(Mn/W,fn/W),da=new es(Dn/W,mr/W),$a=g*Math.PI/180;if($a){const to=Math.sin($a),mu=Math.cos($a),jl=[mu,-to,to,mu];ta._matMult(jl),Cr._matMult(jl),pr._matMult(jl),Nr._matMult(jl)}const ja=ms.stretch+ms.fixed,Pi=Nn.stretch+Nn.fixed,zo=vn.stretch+vn.fixed,Li=Tn.stretch+Tn.fixed,$o=k.imageSecondary;return{tl:ta,tr:Cr,bl:pr,br:Nr,texPrimary:{x:B.paddedRect.x+1+ja,y:B.paddedRect.y+1+zo,w:Pi-ja,h:Li-zo},texSecondary:$o?{x:$o.paddedRect.x+1+ja,y:$o.paddedRect.y+1+zo,w:Pi-ja,h:Li-zo}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:Kr,pixelOffsetBR:da,minFontScaleX:bs/W/pe,minFontScaleY:ys/W/ve,isSDF:_}};if(B.stretchX||B.stretchY){const ms=nlt(_e,Je,De),vn=nlt(Pe,rt,We);for(let Nn=0;Nn0?[xt,-ut]:St<0?[-xt,ut]:xt===0?[ut,xt]:[ut,-xt]}(_);let Pe=Math.abs(g.top-g.bottom);for(const rt of g.positionedLines)Pe-=rt.lineOffset;const De=g.positionedLines.length,We=Pe/De;let Je=g.top-_[1];for(let rt=0;rtO)&&(O=De.x),(!Pe||De.y>B)&&(B=De.y)}const Y=Math.min(O-C,B-P);let ae=Y/2;const pe=new nm([],Jos);if(Y===0)return new es(C,P);for(let Pe=C;Peve.d||!ve.d)&&(ve=Pe,_&&console.log("found best %d after %d probes",Math.round(1e4*Pe.d)/1e4,_e)),Pe.max-ve.d<=g||(ae=Pe.h/2,pe.push(new gz(Pe.p.x-ae,Pe.p.y-ae,ae,k)),pe.push(new gz(Pe.p.x+ae,Pe.p.y-ae,ae,k)),pe.push(new gz(Pe.p.x-ae,Pe.p.y+ae,ae,k)),pe.push(new gz(Pe.p.x+ae,Pe.p.y+ae,ae,k)),_e+=4)}return _&&(console.log(`num probes: ${_e}`),console.log(`best distance: ${ve.d}`)),ve.p}function Jos(k,g){return g.max-k.max}oie.TinySDF=class{constructor({fontSize:k=24,buffer:g=3,radius:_=8,cutoff:C=.25,fontFamily:P="sans-serif",fontWeight:O="normal",fontStyle:B="normal",lang:W=null}={}){this.buffer=g,this.cutoff=C,this.radius=_,this.lang=W;const Y=this.size=k+4*g,ae=this._createCanvas(Y),pe=this.ctx=ae.getContext("2d",{willReadFrequently:!0});pe.font=`${B} ${O} ${k}px ${P}`,pe.textBaseline="alphabetic",pe.textAlign="left",pe.fillStyle="black",this.gridOuter=new Float64Array(Y*Y),this.gridInner=new Float64Array(Y*Y),this.f=new Float64Array(Y),this.z=new Float64Array(Y+1),this.v=new Uint16Array(Y)}_createCanvas(k){const g=document.createElement("canvas");return g.width=g.height=k,g}draw(k){const{width:g,actualBoundingBoxAscent:_,actualBoundingBoxDescent:C,actualBoundingBoxLeft:P,actualBoundingBoxRight:O}=this.ctx.measureText(k),B=Math.ceil(_),W=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(O-P))),Y=Math.min(this.size-this.buffer,B+Math.ceil(C)),ae=W+2*this.buffer,pe=Y+2*this.buffer,ve=Math.max(ae*pe,0),_e=new Uint8ClampedArray(ve),Pe={data:_e,width:ae,height:pe,glyphWidth:W,glyphHeight:Y,glyphTop:B,glyphLeft:0,glyphAdvance:g};if(W===0||Y===0)return Pe;const{ctx:De,buffer:We,gridInner:Je,gridOuter:rt}=this;this.lang&&(De.lang=this.lang),De.clearRect(We,We,W,Y),De.fillText(k,We,We+B);const xt=De.getImageData(We,We,W,Y);rt.fill(mK,0,ve),Je.fill(0,0,ve);for(let ut=0;ut0?bs*bs:0,Je[Ft]=bs<0?bs*bs:0}}elt(rt,0,0,ae,pe,ae,this.f,this.v,this.z),elt(Je,We,We,W,Y,ae,this.f,this.v,this.z);for(let ut=0;utO.y!=We.y>O.y&&O.x<(We.x-De.x)*(O.y-De.y)/(We.y-De.y)+De.x&&(W=!W),Y=Math.min(Y,Wj(O,De,We))}}return(W?1:-1)*Math.sqrt(Y)}(this.p,P),this.max=this.d+this.h*Math.SQRT2}}const els=Object.keys,NRe=Number.POSITIVE_INFINITY,tls=Math.sqrt(2);function WE(k,g,_,C,P,O){const B=fRe(k)&&k.collisionPadding?k.collisionPadding:[0,0,0,0],W={top:k.top-B[1],bottom:k.bottom+B[3],left:k.left-B[0],right:k.right+B[2],scaled:!1};return C!==void 0&&function(Y,ae){Y.top*=ae,Y.bottom*=ae,Y.left*=ae,Y.right*=ae,Y.scaled=!0}(W,C),O&&(W.left+=O[0],W.right+=O[0],W.top+=O[1],W.bottom+=O[1]),_&&function(Y,ae,pe){if(!ae)return;const ve=Un(ae),_e=new es(pe?pe[0]:0,pe?pe[1]:0),Pe=new es(Y.left,Y.top),De=new es(Y.right,Y.top),We=new es(Y.left,Y.bottom),Je=new es(Y.right,Y.bottom);Pe._rotateAround(ve,_e),De._rotateAround(ve,_e),We._rotateAround(ve,_e),Je._rotateAround(ve,_e),Y.left=Math.min(Pe.x,De.x,We.x,Je.x),Y.right=Math.max(Pe.x,De.x,We.x,Je.x),Y.top=Math.min(Pe.y,De.y,We.y,Je.y),Y.bottom=Math.max(Pe.y,De.y,We.y,Je.y)}(W,_,P),g?{top:Math.min(g.top,W.top),bottom:Math.max(g.bottom,W.bottom),left:Math.min(g.left,W.left),right:Math.max(g.right,W.right),scaled:g.scaled||W.scaled}:W}function ilt(k,[g,_]){let C=0,P=0;if(_===NRe){g<0&&(g=0);const O=g/tls;switch(k){case"top-right":case"top-left":P=O-7;break;case"bottom-right":case"bottom-left":P=7-O;break;case"bottom":P=7-g;break;case"top":P=g-7}switch(k){case"top-right":case"bottom-right":C=-O;break;case"top-left":case"bottom-left":C=O;break;case"left":C=g;break;case"right":C=-g}}else{switch(g=Math.abs(g),_=Math.abs(_),k){case"top-right":case"top-left":case"top":P=_-7;break;case"bottom-right":case"bottom-left":case"bottom":P=7-_}switch(k){case"top-right":case"bottom-right":case"right":C=-g;break;case"top-left":case"bottom-left":case"left":C=g}}return[C,P]}function sls(k,g,_,C,P,O,B,W,Y,ae,pe,ve,_e,Pe,De){const We=k.layers[0],Je=We.appearances;if(Je.length===0)return{iconBBox:null,iconVerticalBBox:null,textBBox:null,textVerticalBBox:null};const rt={iconBBox:null,iconVerticalBBox:null},xt={textBBox:null,textVerticalBBox:null},{baseIconRotate:ut,baseTextRotate:St,iconScaleFactor:Rt}=function(bs,as,ys){const hs=bs.get("icon-rotate").evaluate(as,{},ys),ms=bs.get("text-rotate").evaluate(as,{},ys),[vn,Nn]=bs.get("icon-size-scale-range");return{baseIconRotate:hs,baseTextRotate:ms,iconScaleFactor:mt(1,vn,Nn)}}(C,P,O);g&&(rt.iconBBox=WE(g,rt.iconBBox,ut),_)&&(rt.iconVerticalBBox=WE(_,rt.iconVerticalBBox,ut+90));const Ft=hie(ve.horizontal);Ft&&(xt.textBBox=WE(Ft,xt.textBBox,St,1,Pe)),ve.vertical&&(xt.textVerticalBBox=WE(ve.vertical,xt.textVerticalBBox,St+90,1,Pe));for(const bs of Je)bs.hasIconLayoutProperties()&&nls(rt,k,We,bs,P,O,W,ut,B,Y,g,ae,Rt,pe,De),bs.hasTextLayoutProperties()&&rls(xt,We,bs,P,O,Pe,St,_e,Ft,ve.vertical);return{iconBBox:rt.iconBBox,iconVerticalBBox:rt.iconVerticalBBox,textBBox:xt.textBBox,textVerticalBBox:xt.textVerticalBBox}}function nls(k,g,_,C,P,O,B,W,Y,ae,pe,ve,_e,Pe,De){const{appearanceIconOffset:We,appearanceIconRotate:Je,appearanceIconSize:rt}=olt(C,_,P,O,B,W,Y,ae.iconScaleFactor);let xt=null,ut=null,St=null;C.hasLayoutProperty("icon-image")?St=function(Ft,bs,as,ys,hs,ms,vn,Nn){let Tn=null;const Ln=bs.getAppearanceValueAndResolveTokens(as,"icon-image",ys,hs,Nn);if(Ln){const Mn=Ft.getResolvedImageFromTokens(Ln),Qn=as.hasLayoutProperty("icon-size")?as.getUnevaluatedLayoutProperty("icon-size"):bs._unevaluatedLayout._values["icon-size"],fn=pK(Mn,BL(Ft.zoom,Qn,Ft.worldview,Nn),Qn,hs,Ft.zoom,ys,Ft.pixelRatio,vn,Ft.worldview,Nn);Tn=ms.get(fn.iconPrimary.toString())}return Tn}(g,_,C,P,O,ve,_e,De):pe&&(St=pe.imagePrimary),St&&(xt=aie(St,null,We,Pe),g.allowVerticalPlacement&&(ut=aie(St,null,We,Pe)));const Rt=Y>0?rt/Y:1;xt&&(k.iconBBox=WE(xt,k.iconBBox,Je,Rt!==1?Rt:void 0)),ut&&(k.iconVerticalBBox=WE(ut,k.iconVerticalBBox,Je+90,Rt!==1?Rt:void 0))}function olt(k,g,_,C,P,O,B,W){const Y=k.hasLayoutProperty("icon-offset")?g.getAppearanceValueAndResolveTokens(k,"icon-offset",_,C,[]):null,ae=Y&&Array.isArray(Y)?Y:P,pe=k.hasLayoutProperty("icon-rotate")?g.getAppearanceValueAndResolveTokens(k,"icon-rotate",_,C,[]):null,ve=typeof pe=="number"?pe:O,_e=k.hasLayoutProperty("icon-size")?g.getAppearanceValueAndResolveTokens(k,"icon-size",_,C,[]):null;return{appearanceIconOffset:ae,appearanceIconRotate:ve,appearanceIconSize:typeof _e=="number"?_e*W:B}}function rls(k,g,_,C,P,O,B,W,Y,ae){const{appearanceTextOffset:pe,appearanceTextRotate:ve,appearanceTextSize:_e}=llt(_,g,C,P,O,B,W),Pe=_e/W,De=[(pe[0]-O[0])*Pe,(pe[1]-O[1])*Pe],We=De[0]!==0||De[1]!==0;Y&&(k.textBBox=WE(Y,k.textBBox,ve,Pe,pe,We?De:void 0)),ae&&(k.textVerticalBBox=WE(ae,k.textVerticalBBox,ve+90,Pe,pe,We?De:void 0))}function llt(k,g,_,C,P,O,B){const W=k.hasLayoutProperty("text-offset")?g.getAppearanceValueAndResolveTokens(k,"text-offset",_,C,[]):null,Y=W&&Array.isArray(W)?[W[0]*jp,W[1]*jp]:P,ae=k.hasLayoutProperty("text-rotate")?g.getAppearanceValueAndResolveTokens(k,"text-rotate",_,C,[]):null,pe=typeof ae=="number"?ae:O,ve=k.hasLayoutProperty("text-size")?g.getAppearanceValueAndResolveTokens(k,"text-size",_,C,[]):null;return{appearanceTextOffset:Y,appearanceTextRotate:pe,appearanceTextSize:typeof ve=="number"?ve:B}}function uie(k,g,_,C,P,O,B,W,Y){if(!g||!g.usvg)return;const ae=Vot(C),pe=Vot(P),ve=O!=="both"&&O!=="width"||!qot(C)?1:pe.width/ae.width,_e=O!=="both"&&O!=="height"||!$ot(C)?1:pe.height/ae.height;_.scaleSelf(ve,_e);const Pe=_.toString();B.set(Pe,_),W.set(Pe,g);const{imagePosition:De}=bRe(Pe,g,1);Y.set(Pe,De)}function clt(k,g,_,C,P,O,B,W,Y,ae){if(!k)return;const pe=function(ve,_e,Pe,De,We,Je,rt){if(ve.kind==="camera")return ve.maxSize;if(ve.kind==="composite"){const xt=_e.possiblyEvaluate(new Oi(ve.maxZoom,{worldview:Je}),Pe,rt).evaluate(We,{},Pe,rt),ut=_e.possiblyEvaluate(new Oi(ve.minZoom,{worldview:Je}),Pe,rt).evaluate(We,{},Pe,rt);return Math.max(xt,ut)}return _e.possiblyEvaluate(new Oi(De,{worldview:Je}),Pe,rt).evaluate(We,{},Pe,rt)}(g,_,C,P,O,Y,ae);return k.scaleSelf(pe*W*B)}function pK(k,g,_,C,P,O,B,W,Y,ae){return{iconPrimary:clt(k.getPrimary(),g,_,C,P,O,B,W,Y,ae),iconSecondary:clt(k.getSecondary(),g,_,C,P,O,B,W,Y,ae)}}function als(k,g,_){if(!g)return;const C=_.get(k.toString()),P=_.get(g.toString());C&&P&&(C.paddedRect.w===P.paddedRect.w&&C.paddedRect.h===P.paddedRect.h||qr(`Mismatch in icon variant sizes: ${k.toString()} and ${g.toString()}`),C.usvg!==P.usvg&&qr(`Mismatch in icon variant image types: ${k.id} and ${g.id}`))}function dlt(k,g,_,C){if(!k)return;const P=g.get(_.toString());if(P&&(k.imagePrimary=P),C){const O=g.get(C.toString());k.imageSecondary=O}}function ils(k,g){for(const _ in k.horizontal)ult(k.horizontal[_],g);ult(k.vertical,g)}function ult(k,g){if(k){for(const _ of k.positionedLines)for(const C of _.positionedGlyphs)if(C.image!==null){const P=C.image.toString();C.rect=g.get(P).paddedRect}}}function kRe(k){switch(k){case"right":case"top-right":case"bottom-right":return"right";case"left":case"top-left":case"bottom-left":return"left"}return"center"}function ols(k,g,_,C,P,O,B,W,Y){const ae=hie(O.horizontal)||O.vertical,pe=_.get("icon-text-fit-padding").evaluate(C,{},P);let ve,_e=g;return g&&Y!=="none"&&(k.allowVerticalPlacement&&O.vertical&&(ve=gRe(g,O.vertical,Y,pe,W,B)),ae&&(_e=gRe(g,ae,Y,pe,W,B))),{defaultShapedIcon:_e,verticallyShapedIcon:ve}}function hlt(k,g){return k*g/24}function lls(k,g,_,C,P,O,B,W,Y,ae,pe,ve,_e,Pe,De,We,Je,rt,xt,ut,St,Rt,Ft,bs){let as=B.textMaxSize.evaluate(g,{},_e);as===void 0?as=W*B.textScaleFactor:as*=B.textScaleFactor;const ys=k.layers[0].layout,hs=hlt(W,B.textScaleFactor),ms=hie(_.horizontal)||_.vertical,vn=k.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),Nn=k.getAppearanceFeatureData(g.index);(Je!=="none"||vn)&&Nn&&(Nn.textShaping=ms,Nn.iconTextFitPadding=ys.get("icon-text-fit-padding").evaluate(g,{},_e),Nn.fontScale=hs,Nn.textScaleFactor=B.textScaleFactor);const Tn=Pe.name==="globe",Ln=k.tilePixelRatio*as/24,Mn=(mr=k.overscaling,k.zoom>18&&mr>2&&(mr>>=1),Math.max(dr/(512*mr),1)*ys.get("symbol-spacing")),Qn=ys.get("text-padding")*k.tilePixelRatio,fn=ys.get("icon-padding")*k.tilePixelRatio,Pn=Un(ys.get("text-max-angle")),Dn=ys.get("icon-rotation-alignment")==="map"&&ut!=="point",tr=Mn/2;var mr;k.hasAnyIconTextFit===!1&&Je!=="none"&&(k.hasAnyIconTextFit=!0);const ta=g.properties?+g.properties[$i]:null,Cr=ta&&k.elevationFeatureIdToIndex?k.elevationFeatureIdToIndex.get(ta):65535,Nr=(pr,Kr,da)=>{if(Kr.x<0||Kr.x>=dr||Kr.y<0||Kr.y>=dr)return;let $a=null;if(Tn){const{x:ja,y:Pi,z:zo}=Pe.projectTilePoint(Kr.x,Kr.y,da);$a={anchor:new W3(ja,Pi,zo,0,void 0),up:Pe.upVector(da,Kr.x,Kr.y)}}(function(ja,Pi,zo,Li,$o,to,mu,jl,el,Pc,ru,Np,au,Du,Rh,Ou,Ng,kp,lo,I0,rh,sf,R0,kg,pu,Ox,nf,Tie,Nz,Oy,YRe,kz){const K3=ja.addToLineVertexArray(Pi,Li);let Y3,tw,sw,GL,Sz,mo,rf,Fu=0,Km=0,nw=0,I1=0,R1=-1,D1=-1;const Zj={};let Mie=zd("");const XN=zo?zo.anchor:Pi,Cz=Tie!=="none";let Az=0,wm=0;if(el._unevaluatedLayout.getValue("text-radial-offset")===void 0){const ah=el.layout.get("text-offset").evaluate(rh,{},pu);Az=ah[0]*jp,wm=ah[1]*jp}else Az=el.layout.get("text-radial-offset").evaluate(rh,{},pu)*jp,wm=NRe;if(ja.allowVerticalPlacement&&$o.vertical){const ah=$o.vertical;if(Rh)mo=ARe(ah),jl&&(rf=ARe(jl));else{const D0=el.layout.get("text-rotate").evaluate(rh,{},pu)+90;sw=mie(Pc,XN,Pi,ru,Np,au,ah,Du,D0,Ou,kz),jl&&(GL=mie(Pc,XN,Pi,ru,Np,au,jl,kp,D0,null,YRe))}}if(to){const ah=el.layout.get("icon-rotate").evaluate(rh,{},pu),D0=jRe(to,ah,R0,Cz,sf.iconScaleFactor),Fy=jl?jRe(jl,ah,R0,Cz,sf.iconScaleFactor):void 0;tw=mie(Pc,XN,Pi,ru,Np,au,to,kp,ah,null,Oy);const Qj=function(QN,EK,Ez,jcs,Ncs,Lct,Ict,kcs,$fr,XRe){const Rct=QN.layers[0],Dct=Rct.appearances;let Tz=EK.length;if(Ez&&(Tz=Math.max(Tz,Ez.length)),Dct.length===0)return Tz;const[Scs,Ccs]=jcs.get("icon-size-scale-range"),Acs=mt(1,Scs,Ccs);for(const Rie of Dct)if(Rie.hasLayoutProperty("icon-image")){const Oct=Rct.getAppearanceValueAndResolveTokens(Rie,"icon-image",Lct,Ict,XRe);if(Oct){const Fct=QN.getResolvedImageFromTokens(Oct);if(Fct){const zct=Rie.hasLayoutProperty("icon-size")?Rie.getUnevaluatedLayoutProperty("icon-size"):Ncs._values["icon-size"],Ecs=pK(Fct,BL(QN.zoom,zct,QN.worldview,XRe),zct,Ict,QN.zoom,Lct,QN.pixelRatio,Acs,QN.worldview,XRe),Bct=kcs.get(Ecs.iconPrimary.toString());Bct&&(Tz=Math.max(Tz,Zos(Bct)))}}}return Tz}(ja,D0,Fy,el.layout,el._unevaluatedLayout,rh,pu,ja.iconAtlasPositions,0,kg);Fu=4*Qj;const Pie=el.layout.get("icon-size").evaluate(rh,{},pu,kg),Lie=sf.compositeIconSizes?sf.compositeIconSizes[0].evaluate(rh,{},pu,kg):0,ZRe=sf.compositeIconSizes?sf.compositeIconSizes[1].evaluate(rh,{},pu,kg):0,Iie=CRe(ja.layerIds[0],ja.iconSizeData,Pie,sf.iconScaleFactor,Lie,ZRe);ja.addSymbols(ja.icon,D0,Iie,I0,lo,rh,void 0,zo,Pi,K3.lineStartIndex,K3.lineLength,-1,kg,pu,Ox,nf,ja.symbolInstances.length,Qj),R1=ja.icon.placedSymbolArray.length-1,Fy&&(Km=4*Qj,ja.addSymbols(ja.icon,Fy,Iie,I0,lo,rh,L1.vertical,zo,Pi,K3.lineStartIndex,K3.lineLength,-1,kg,pu,Ox,nf,ja.symbolInstances.length,Qj),D1=ja.icon.placedSymbolArray.length-1)}for(const ah in $o.horizontal){const D0=ah,Fy=$o.horizontal[D0];Y3||(Mie=zd(Fy.text),Rh?Sz=ARe(Fy):Y3=mie(Pc,XN,Pi,ru,Np,au,Fy,Du,el.layout.get("text-rotate").evaluate(rh,{},pu),Ou,kz));const Qj=Fy.positionedLines.length===1;if(nw+=mlt(ja,zo,Pi,Fy,mu,el,Rh,rh,Ou,K3,$o.vertical?L1.horizontal:L1.horizontalOnly,Qj?els($o.horizontal):[D0],Zj,R1,sf,kg,pu,ja.symbolInstances.length,Ox),Qj)break}$o.vertical&&(I1+=mlt(ja,zo,Pi,$o.vertical,mu,el,Rh,rh,Ou,K3,L1.vertical,["vertical"],Zj,D1,sf,kg,pu,ja.symbolInstances.length,Ox));let im=-1;const Ym=(ah,D0)=>ah?Math.max(ah,D0):D0;im=Ym(Sz,im),im=Ym(mo,im),im=Ym(rf,im);const Xj=im>-1?1:0;ja.glyphOffsetArray.length>=65535&&qr("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),rh.sortKey!==void 0&&ja.addToSortKeyRanges(ja.symbolInstances.length,rh.sortKey),ja.symbolInstances.emplaceBack(Pi.x,Pi.y,XN.x,XN.y,XN.z,Zj.right>=0?Zj.right:-1,Zj.center>=0?Zj.center:-1,Zj.left>=0?Zj.left:-1,Zj.vertical>=0?Zj.vertical:-1,R1,D1,Mie,Y3!==void 0?Y3:ja.collisionBoxArray.length,Y3!==void 0?Y3+1:ja.collisionBoxArray.length,sw!==void 0?sw:ja.collisionBoxArray.length,sw!==void 0?sw+1:ja.collisionBoxArray.length,tw!==void 0?tw:ja.collisionBoxArray.length,tw!==void 0?tw+1:ja.collisionBoxArray.length,GL||ja.collisionBoxArray.length,GL?GL+1:ja.collisionBoxArray.length,ru,nw,I1,Fu,Km,Xj,0,Az,wm,im,0,Cz?1:0,Nz)})(k,Kr,$a,pr,_,C,O,P,k.layers[0],k.collisionBoxArray,g.index,g.sourceLayerIndex,k.index,Qn,xt,ae,0,fn,Dn,rt,g,B,pe,ve,_e,De,We,Je,Cr,St,Rt,Ft)};if(ut==="line")for(const pr of Gae(g.geometry,0,0,dr,dr)){const Kr=Yos(pr,Mn,Pn,_.vertical||ms,C,24,Ln,k.overscaling,dr);for(const da of Kr)ms&&cls(k,ms.text,tr,da)||Nr(pr,da,_e)}else if(ut==="line-center"){for(const pr of g.geometry)if(pr.length>1){const Kr=Kos(pr,Pn,_.vertical||ms,C,24,Ln);Kr&&Nr(pr,Kr,_e)}}else if(g.type==="Polygon")for(const pr of ZW(g.geometry,0)){const Kr=Qos(pr,16);Nr(pr[0],new W3(Kr.x,Kr.y,0,0,void 0),_e)}else if(g.type==="LineString")for(const pr of g.geometry)Nr(pr,new W3(pr[0].x,pr[0].y,0,0,void 0),_e);else if(g.type==="Point")for(const pr of g.geometry)for(const Kr of pr)Nr([Kr],new W3(Kr.x,Kr.y,0,0,void 0),_e)}const SRe=255,UL=SRe*G3;function mlt(k,g,_,C,P,O,B,W,Y,ae,pe,ve,_e,Pe,De,We,Je,rt,xt){const ut=alt(0,C,Y,O,B,W,P,k.allowVerticalPlacement,void 0,De.textScaleFactor),St=O.layout.get("text-size").evaluate(W,{},Je),Rt=De.compositeTextSizes?De.compositeTextSizes[0].evaluate(W,{},Je):0,Ft=De.compositeTextSizes?De.compositeTextSizes[1].evaluate(W,{},Je):0,bs=CRe(k.layerIds[0],k.textSizeData,St,De.textScaleFactor,Rt,Ft);k.addSymbols(k.text,ut,bs,Y,B,W,pe,g,_,ae.lineStartIndex,ae.lineLength,Pe,We,Je,xt,!1,rt,ut.length);for(const as of ve)_e[as]=k.text.placedSymbolArray.length-1;return 4*ut.length}function CRe(k,g,_,C,P,O){const B=g;let W=null;return B.kind==="source"?(W=[G3*_*C],W[0]>UL&&qr(`${k}: Value for "text-size" is >= ${SRe}. Reduce your "text-size".`)):B.kind==="composite"&&(W=[G3*P*C,G3*O*C],(W[0]>UL||W[1]>UL)&&qr(`${k}: Value for "text-size" is >= ${SRe}. Reduce your "text-size".`)),W}function hie(k){for(const g in k)return k[g];return null}function mie(k,g,_,C,P,O,B,W,Y,ae,pe){let ve,_e,Pe,De;if(ve=pe?pe.top:B.top,_e=pe?pe.bottom:B.bottom,Pe=pe?pe.left:B.left,De=pe?pe.right:B.right,fRe(B)&&B.collisionPadding){const We=B.collisionPadding;Pe-=We[0],ve-=We[1],De+=We[2],_e+=We[3]}if(Y){const We=new es(Pe,ve),Je=new es(De,ve),rt=new es(Pe,_e),xt=new es(De,_e),ut=Un(Y);let St=new es(0,0);ae&&(St=new es(ae[0],ae[1])),We._rotateAround(ut,St),Je._rotateAround(ut,St),rt._rotateAround(ut,St),xt._rotateAround(ut,St),Pe=Math.min(We.x,Je.x,rt.x,xt.x),De=Math.max(We.x,Je.x,rt.x,xt.x),ve=Math.min(We.y,Je.y,rt.y,xt.y),_e=Math.max(We.y,Je.y,rt.y,xt.y)}return k.emplaceBack(g.x,g.y,g.z,_.x,_.y,Pe,ve,De,_e,W,C,P,O),k.length-1}function ARe(k){fRe(k)&&k.collisionPadding&&(k.top-=k.collisionPadding[1],k.bottom+=k.collisionPadding[3]);const g=k.bottom-k.top;return g>0?Math.max(10,g):null}function cls(k,g,_,C){const P=k.compareText;if(g in P){const O=P[g];for(let B=O.length-1;B>=0;B--)if(C.dist(O[B])<_)return!0}else P[g]=[];return P[g].push(C),!1}function plt(k,g){const _=k.fovAboveCenter,C=k.elevation?k.elevation.getMinElevationBelowMSL()*g:0,P=Math.min(C,k.isOrthographic?-10*g:0),O=(k._camera.position[2]*k.worldSize-P)/Math.cos(k._pitch),B=Math.sin(_)*O/Math.sin(Math.max(Math.PI/2-k._pitch-_,.01));let W=Math.sin(k._pitch)*B+O;const Y=O*(1/k._horizonShift);if(!k.elevation||k.elevation.exaggeration()===0){let ae=Math.max(k.zoom-17,0);k.isOrthographic&&(ae/=10),W*=1+ae}return Math.min(1.01*W,Y)}function qL(k,g){if(!g.isReprojectedInTileSpace)return{scale:1<ut&&(St(Ft,Tn,as,ys,vn,Nn),St(Tn,bs,vn,Nn,hs,ms))}St(ve,_e,C,O,P,O),St(_e,Pe,P,O,P,B),St(Pe,De,P,B,C,B),St(De,ve,C,B,C,O),We-=ut,Je-=ut,rt+=ut,xt+=ut;const Rt=1/Math.max(rt-We,xt-Je);return{scale:Rt,x:We*Rt,y:Je*Rt,x2:rt*Rt,y2:xt*Rt,projection:g}}function flt(k,{x:g,y:_},C=0){return new es(((g-C)*k.scale-k.x)*dr,(_*k.scale-k.y)*dr)}const dls=y(new Float32Array(16));class KE{constructor(g){this.spec=g,this.name=g.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(g,_){return{x:0,y:0,z:0}}unproject(g,_){return new Ts(0,0)}projectTilePoint(g,_,C){return{x:g,y:_,z:0}}locationPoint(g,_,C,P=!0){return g._coordinatePoint(g.locationCoordinate(_,C),P)}pixelsPerMeter(g,_){return en(1,g)*_}pixelSpaceConversion(g,_,C){return 1}farthestPixelDistance(g){return plt(g,g.pixelsPerMeter)}pointCoordinate(g,_,C,P){const O=g.horizonLineFromTop(!1),B=new es(_,Math.max(O,C));return g.rayIntersectionCoordinate(g.pointRayIntersection(B,P))}pointCoordinate3D(g,_,C){const P=new es(_,C);if(g.elevation)return g.elevation.pointCoordinate(P);{const O=this.pointCoordinate(g,P.x,P.y,0);return[O.x,O.y,O.z]}}isPointAboveHorizon(g,_){if(g.elevation&&g.elevation.visibleDemTiles.length)return!this.pointCoordinate3D(g,_.x,_.y);const C=g.horizonLineFromTop();return _.y0?_<-xz+C&&(_=-xz+C):_>xz-C&&(_=xz-C);const B=O/Math.pow(fie(_),P);let W=B*Math.sin(P*g),Y=O-B*Math.cos(P*g);return W=.5*(W/Math.PI+.5),Y=.5*(Y/Math.PI+.5),{x:W,y:this.southernCenter?Y:1-Y,z:0}}unproject(g,_){g=(2*g-.5)*Math.PI,this.southernCenter&&(_=1-_),_=(2*(1-_)-.5)*Math.PI;const{n:C,f:P}=this,O=P-_,B=Math.sign(O),W=Math.sign(C)*Math.sqrt(g*g+O*O);let Y=Math.atan2(g,Math.abs(O))*B;O*C<0&&(Y-=Math.PI*Math.sign(g)*B);const ae=mt(sn(Y/C)+this.center[0],-180,180),pe=mt(sn(2*Math.atan(Math.pow(P/W,1/C))-xz),-85.051129,An);return new Ts(ae,this.southernCenter?-pe:pe)}}class glt extends KE{constructor(g){super(g),this.wrap=!0,this.supportsWorldCopies=!0,this.supportsTerrain=!0,this.supportsFog=!0,this.supportsFreeCamera=!0,this.isReprojectedInTileSpace=!1,this.unsupportedLayers=[],this.range=null}project(g,_){return{x:Rn(g),y:Kn(_),z:0}}unproject(g,_){const C=Ls(g),P=yn(_);return new Ts(C,P)}}const xlt=Un(An);class fls extends KE{project(g,_){const C=(_=Un(_))*_,P=C*C;return{x:.5*((g=Un(g))*(.8707-.131979*C+P*(P*(.003971*C-.001529*P)-.013791))/Math.PI+.5),y:1-.5*(_*(1.007226+C*(.015085+P*(.028874*C-.044475-.005916*P)))/Math.PI+1),z:0}}unproject(g,_){g=(2*g-.5)*Math.PI;let C=_=(2*(1-_)-1)*Math.PI,P=25,O=0,B=C*C;do{B=C*C;const ae=B*B;O=(C*(1.007226+B*(.015085+ae*(.028874*B-.044475-.005916*ae)))-_)/(1.007226+B*(.045255+ae*(.259866*B-.311325-.005916*11*ae))),C=mt(C-O,-xlt,xlt)}while(Math.abs(O)>1e-6&&--P>0);B=C*C;const W=mt(sn(g/(.8707+B*(B*(B*B*B*(.003971-.001529*B)-.013791)-.131979))),-180,180),Y=sn(C);return new Ts(W,Y)}}const ylt=Un(An);class gls extends KE{project(g,_){_=Un(_),g=Un(g);const C=Math.cos(_),P=2/Math.PI,O=Math.acos(C*Math.cos(g/2)),B=Math.sin(O)/O,W=.5*(g*P+2*C*Math.sin(g/2)/B)||0,Y=.5*(_+Math.sin(_)/B)||0;return{x:.5*(W/Math.PI+.5),y:1-.5*(Y/Math.PI+1),z:0}}unproject(g,_){let C=g=(2*g-.5)*Math.PI,P=_=(2*(1-_)-1)*Math.PI,O=25;const B=1e-6;let W=0,Y=0;do{const ae=Math.cos(P),pe=Math.sin(P),ve=2*pe*ae,_e=pe*pe,Pe=ae*ae,De=Math.cos(C/2),We=Math.sin(C/2),Je=2*De*We,rt=We*We,xt=1-Pe*De*De,ut=xt?1/xt:0,St=xt?Math.acos(ae*De)*Math.sqrt(1/xt):0,Rt=.5*(2*St*ae*We+2*C/Math.PI)-g,Ft=.5*(St*pe+P)-_,bs=.5*ut*(Pe*rt+St*ae*De*_e)+1/Math.PI,as=ut*(Je*ve/4-St*pe*We),ys=.125*ut*(ve*We-St*pe*Pe*Je),hs=.5*ut*(_e*De+St*rt*ae)+.5,ms=as*ys-hs*bs;W=(Ft*as-Rt*hs)/ms,Y=(Rt*ys-Ft*bs)/ms,C=mt(C-W,-Math.PI,Math.PI),P=mt(P-Y,-ylt,ylt)}while((Math.abs(W)>B||Math.abs(Y)>B)&&--O>0);return new Ts(sn(C),sn(P))}}class vlt extends KE{constructor(g){super(g),this.center=g.center||[0,0],this.parallels=g.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(Un(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0}project(g,_){const{scale:C,cosPhi:P}=this;return{x:Un(g)*P*C+.5,y:-Math.sin(Un(_))/P*C+.5,z:0}}unproject(g,_){const{scale:C,cosPhi:P}=this,O=-(_-.5)/C,B=mt(sn((g-.5)/C)/P,-180,180),W=Math.asin(mt(O*P,-1,1)),Y=mt(sn(W),-85.051129,An);return new Ts(B,Y)}}class xls extends glt{constructor(g){super(g),this.requiresDraping=!0,this.supportsWorldCopies=!1,this.supportsFog=!0,this.zAxisUnit="pixels",this.unsupportedLayers=["debug"],this.range=[3,5]}projectTilePoint(g,_,C){const P=$W(g,_,C);return Qe(P,P,VW(QS(C))),{x:P[0],y:P[1],z:P[2]}}locationPoint(g,_,C){const P=ss(_.lat,_.lng),O=Te([],P),B=C?g._centerAltitude+C:g.elevation?g.elevation.getAtPointOrZero(g.locationCoordinate(_),g._centerAltitude):g._centerAltitude;je(P,P,O,en(1,0)*dr*B);const W=y(new Float64Array(16));return b(W,g.pixelMatrix,g.globeMatrix),Qe(P,P,W),new es(P[0],P[1])}pixelsPerMeter(g,_){return en(1,0)*_}pixelSpaceConversion(g,_,C){const P=en(1,g)*_,O=Es(en(1,45)*_,P,C);return this.pixelsPerMeter(g,_)/O}createTileMatrix(g,_,C){const P=w8e(QS(C.canonical));return b(new Float64Array(16),g.globeMatrix,P)}createInversionMatrix(g,_){const{center:C}=g,P=VW(QS(_));return T(P,P,Un(C.lng)),A(P,P,Un(C.lat)),S(P,P,[g._pixelsPerMercatorPixel,g._pixelsPerMercatorPixel,1]),Float32Array.from(P)}pointCoordinate(g,_,C,P){return Rat(g,_,C,!0)||new ca(0,0)}pointCoordinate3D(g,_,C){const P=this.pointCoordinate(g,_,C,0);return[P.x,P.y,P.z]}isPointAboveHorizon(g,_){return!Rat(g,_.x,_.y,!1)}farthestPixelDistance(g){const _=function(P,O){const B=P.cameraToCenterDistance,W=P._centerAltitude*O,Y=P._camera,ae=P._camera.forward(),pe=le([],ce([],ae,-B),[0,0,W]),ve=P.worldSize/(2*Math.PI),_e=[0,0,-ve],Pe=P.width/P.height,De=Math.tan(P.fovAboveCenter),We=ce([],Y.up(),De),Je=ce([],Y.right(),De*Pe),rt=Te([],le([],le([],ae,We),Je)),xt=[];let ut;if(new po(pe,rt).closestPointOnSphere(_e,ve,xt)){const St=le([],xt,_e),Rt=Ve([],St,pe);ut=Math.cos(P.fovAboveCenter)*K(Rt)}else{const St=Ve([],pe,_e),Rt=Ve([],_e,pe);Te(Rt,Rt);const Ft=K(St)-ve;ut=Math.sqrt(Ft*(Ft+2*ve));const bs=Math.acos(ut/(ve+Ft))-Math.acos(Me(ae,Rt));ut*=Math.cos(bs)}return 1.01*ut}(g,this.pixelsPerMeter(g.center.lat,g.worldSize)),C=$3(g.zoom);if(C>0){const P=plt(g,en(1,g.center.lat)*g.worldSize),O=g.worldSize/(2*Math.PI),B=Math.max(g.width,g.height)/g.worldSize*Math.PI;return Es(_,P+O*(1-Math.cos(B)),Math.pow(C,10))}return _}upVector(g,_,C){return $W(_,C,g,1)}upVectorScale(g){return{metersToTile:Aae(Tae(QS(g)))}}}function blt(k){const g=k.parallels,_=!!g&&Math.abs(g[0]+g[1])<.01;switch(k.name){case"mercator":return new glt(k);case"equirectangular":return new mls(k);case"naturalEarth":return new fls(k);case"equalEarth":return new hls(k);case"winkelTripel":return new gls(k);case"albers":return _?new vlt(k):new uls(k);case"lambertConformalConic":return _?new vlt(k):new pls(k);case"globe":return new xls(k)}throw new Error(`Invalid projection name: ${k.name}`)}class yls{constructor(g,_){this.lastParams=null,this.lastAllFeaturesIndex=-2,this.appearancesVersion=_,this.appearances=g;const C=g.map(P=>function(O){if(!O.condition)return{featureDependent:!1,stateDependent:!1,zoomDependent:!1,pitchDependent:!1,brightnessDependent:!1,worldviewDependent:!1};const B=O.condition.expression;return{featureDependent:!Db(B),stateDependent:!bg(B),zoomDependent:!Pu(B,["zoom"]),pitchDependent:!Pu(B,["pitch"]),brightnessDependent:!Pu(B,["brightness","measure-light"]),worldviewDependent:!Pu(B,["worldview"])}}(P));this.anyFeatureDependent=C.some(P=>P.featureDependent),this.anyStateDependent=C.some(P=>P.stateDependent)}update(g,_){const C=this.lastParams,P=!C||C.zoom!==g.zoom||C.pitch!==(g.pitch||0)||C.brightness!==(g.brightness||0)||C.worldview!==g.worldview;this.lastParams={zoom:g.zoom,pitch:g.pitch||0,brightness:g.brightness||0,worldview:g.worldview};const O=_&&this.anyStateDependent;if(!P&&!O&&this.lastAllFeaturesIndex!==-2)return{kind:"no-changes"};if(!this.anyFeatureDependent&&!O){const B=this.evaluateAllFeatures(g);return B===this.lastAllFeaturesIndex?{kind:"no-changes"}:(this.lastAllFeaturesIndex=B,{kind:"all-features",appearanceIndex:B})}return{kind:"per-feature"}}evaluateAllFeatures(g){for(let _=0;_{for(let P=0;PB-W),O=new Map;for(const B of P){const W=C.get(B);O.set(B,new Ec(W))}return _&&(this.cachedBatchIndices=P,this.cachedBatchSegments=O),{batchIndices:P,batchSegments:O}}snapshotSymbolVertexData(g,_){const C=g*vz;return this.layoutVertexArray.uint16.slice(C,C+_*vz)}restoreSymbolVertexData(g,_){this.layoutVertexArray.uint16.set(_,g*vz)}updateSymbolVertexData(g,_,C,P,O,B,W,Y,ae,pe,ve,_e,Pe){const De=this.layoutVertexArray.uint16,We=g*vz;De[We]=_,De[We+1]=C,De[We+2]=P,De[We+3]=O,De[We+4]=B,De[We+5]=W,De[We+6]=Y,De[We+7]=ae,De[We+8]=pe,De[We+9]=ve,De[We+10]=_e,De[We+11]=Pe}upload(g,_,C,P,O,B){this.isEmpty()||(C&&(this.cachedBatchIndices=null,this.cachedBatchSegments=null,this.layoutVertexBuffer=g.createVertexBuffer(this.layoutVertexArray,_os.members,!!B),this.indexBuffer=g.createIndexBuffer(this.indexArray,_),this.dynamicLayoutVertexBuffer=g.createVertexBuffer(this.dynamicLayoutVertexArray,jos.members,!0),this.opacityVertexBuffer=g.createVertexBuffer(this.opacityVertexArray,bls,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=g.createVertexBuffer(this.iconTransitioningVertexArray,Cos.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=g.createVertexBuffer(this.globeExtVertexArray,wos.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||O)&&(this.zOffsetVertexBuffer=g.createVertexBuffer(this.zOffsetVertexArray,Nos.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=g.createVertexBuffer(this.orientationVertexArray,Sos.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray&&this.featureIdArray.length>0&&(this.featureIdBuffer=g.createVertexBuffer(this.featureIdArray,kos.members,!1))),(C||P)&&(this.programConfigurations.upload(g),this.uboBinder&&this.uboBinder.upload(g)))}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())}}wr(ERe,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class TRe{constructor(g,_,C){this.layoutVertexArray=new g,this.layoutAttributes=_,this.indexArray=new C,this.segments=new Ec,this.collisionVertexArray=new CL,this.collisionVertexArrayExt=new VN}upload(g){this.layoutVertexBuffer=g.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=g.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=g.createVertexBuffer(this.collisionVertexArray,Aos.members,!0),this.collisionVertexBufferExt=g.createVertexBuffer(this.collisionVertexArrayExt,Eos.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}wr(TRe,"CollisionBuffers");class KN{constructor(g){this.collisionBoxArray=g.collisionBoxArray,this.zoom=g.zoom,this.overscaling=g.overscaling,this.layers=g.layers,this.layerIds=this.layers.map(B=>B.fqid),this.index=g.index,this.pixelRatio=g.pixelRatio,this.sourceLayerIndex=g.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.fullyClipped=!1,this.hasAnyIconTextFit=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=y([]),this.placementViewportMatrix=y([]);const _=this.layers[0]._unevaluatedLayout._values;this.worldview=g.worldview,this.localizable=g.localizable,this.maxUniformBufferBindings=g.maxUniformBufferBindings,this.maxUniformBlockSizeDwords=g.maxUniformBlockSizeDwords,this.disableSymbolUBO=g.disableSymbolUBO,this.textSizeData=BL(this.zoom,_["text-size"],this.worldview,g.availableImages),this.iconSizeData=BL(this.zoom,_["icon-size"],this.worldview,g.availableImages);const C=this.layers[0].layout,P=C.get("symbol-sort-key"),O=C.get("symbol-z-order");this.lut=g.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=O!=="viewport-y"&&P.constantOr(1)!==void 0,this.sortFeaturesByY=(O==="viewport-y"||O==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=C.get("text-writing-mode").map(B=>L1[B]),this.stateDependentLayerIds=this.layers.filter(B=>B.isStateDependent()).map(B=>B.id),this.sourceID=g.sourceID,this.projection=g.projection,this.hasAnyZOffset=!1,this.zOffsetSortDirty=!1,this.zOffsetBuffersNeedUpload=!1,this.elevationType="none",this.elevationStateComplete=!1,this.activeReplacements=[],this.replacementUpdateTime=0,this.hasAnySecondaryIcon=!1,this.hasAppearances=null,this.featureAppearances=null,this.featureAppearanceData=new Map}hasAnyAppearanceLayoutProperty(g){const _=this.layers[0].getAppearances();if(!_||_.length===0)return!1;const C=Array.isArray(g)?g:[g];return _.some(P=>C.some(O=>P.hasLayoutProperty(O)))}getAppearanceFeatureData(g){return this.featureAppearanceData.get(g)}createArrays(){this.text=new ERe(new st(this.layers,{zoom:this.zoom,lut:this.lut},g=>g.startsWith("text")||g.startsWith("symbol"))),this.icon=new ERe(new st(this.layers,{zoom:this.zoom,lut:this.lut},g=>g.startsWith("icon")||g.startsWith("symbol"))),this.disableSymbolUBO||(this.text.uboBinder=new uRe(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.icon.uboBinder=new uRe(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords)),this.glyphOffsetArray=new wae,this.lineVertexArray=new TL,this.symbolInstances=new _ae}calculateGlyphDependencies(g,_,C,P,O){for(const B of g){const W=B.codePointAt(0);if(W===void 0)break;if(_[W]=!0,P&&O&&W<=65535){const Y=cK[B];Y&&(_[Y.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(g,_,C,P,O,B,W){if(!g.hasLayoutProperty("icon-size"))return W*B;let Y=1;const ae=g.getUnevaluatedLayoutProperty("icon-size"),pe=BL(this.zoom,ae,this.worldview,O),ve=fz(pe,_);if(pe.kind!=="constant"&&pe.kind!=="camera"||(Y=ve.uSize),pe.kind==="composite"){const{minZoom:_e,maxZoom:Pe}=pe,De=ae.possiblyEvaluate(new Oi(_e,{worldview:this.worldview}),P),We=ae.possiblyEvaluate(new Oi(Pe,{worldview:this.worldview}),P),Je=De.evaluate(C,{},P,O);Y=Je+(We.evaluate(C,{},P,O)-Je)*ve.uSizeT}return pe.kind==="source"&&(Y=ae.possiblyEvaluate(new Oi(this.zoom,{worldview:this.worldview}),P).evaluate(C,{},P,O)),Y*B}updateFootprints(g,_){}updateReplacement(g,_){if(_.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=_.updateTime;const C=_.getReplacementRegionsForTile(g.toUnwrapped(),!0);return!Bae(this.activeReplacements,C)&&(this.activeReplacements=C,!0)}getResolvedImageFromTokens(g){return typeof g=="string"?uh.build(g):g}populate(g,_,C,P){const O=this.layers[0],B=O.layout,W=this.projection.name==="globe",Y=B.get("text-font"),ae=B.get("text-field"),pe=B.get("icon-image"),[ve,_e]=B.get("icon-size-scale-range"),Pe=mt(_.scaleFactor||1,ve,_e),[De,We]=B.get("text-size-scale-range"),Je=mt(_.scaleFactor||1,De,We),rt=(ae.value.kind!=="constant"||ae.value.value instanceof Bd&&!ae.value.value.isEmpty()||ae.value.value.toString().length>0)&&(Y.value.kind!=="constant"||Y.value.value.length>0),xt=pe.value.kind!=="constant"||!!pe.value.value||Object.keys(pe.parameters).length>0,ut=this.hasAnyAppearanceLayoutProperty("icon-image"),St=B.get("symbol-sort-key");if(this.features=[],this.featureAppearanceData=new Map,!rt&&!xt&&!ut)return;const Rt=_.iconDependencies,Ft=_.glyphDependencies,bs=_.availableImages,as=new Oi(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),ys=hs=>{const ms=hs.id.toString();Rt.has(ms)?Rt.get(ms).push(hs):Rt.set(ms,[hs])};for(const hs of g){const{feature:ms,id:vn,index:Nn,sourceLayerIndex:Tn}=hs,Ln=O._featureFilter.needGeometry,Mn=eo(ms,Ln);if(!O._featureFilter.filter(as,Mn,C))continue;if(Ln||(Mn.geometry=Ha(ms,C,P)),W&&ms.type!==1&&C.z<=5){const Cr=Mn.geometry,Nr=.98078528056,pr=(Kr,da)=>Me($W(Kr.x,Kr.y,C,1),$W(da.x,da.y,C,1)){if(!Cr.getLayoutProperty("icon-image"))return;const Nr=this.getCombinedIconPrimary(Cr,Pn,Mn,C,bs,mr,Pe);Nr&&ys(Nr)}),Qn){const Cr=Y.evaluate(Mn,{},C).join(","),Nr=B.get("text-rotation-alignment")==="map"&&B.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(L1.vertical)>=0;for(const pr of Qn.sections)if(pr.image){const Kr=pr.image.getPrimary().scaleSelf(this.pixelRatio*Je),da=Kr.id.toString(),$a=Rt.get(da)||[];$a.push(Kr),Rt.set(da,$a)}else{const Kr=qf(Qn.toString()),da=pr.fontStack||Cr,$a=Ft[da]=Ft[da]||{};this.calculateGlyphDependencies(pr.text,$a,Nr,this.allowVerticalPlacement,Kr)}}}if(B.get("symbol-placement")==="line"&&(this.features=function(hs){const ms={},vn={},Nn=[];let Tn=0;function Ln(Pn){Nn.push(hs[Pn]),Tn++}function Mn(Pn,Dn,tr){const mr=vn[Pn];return delete vn[Pn],vn[Dn]=mr,Nn[mr].geometry[0].pop(),Nn[mr].geometry[0]=Nn[mr].geometry[0].concat(tr[0]),mr}function Qn(Pn,Dn,tr){const mr=ms[Dn];return delete ms[Dn],ms[Pn]=mr,Nn[mr].geometry[0].shift(),Nn[mr].geometry[0]=tr[0].concat(Nn[mr].geometry[0]),mr}function fn(Pn,Dn,tr){const mr=tr?Dn[0][Dn[0].length-1]:Dn[0][0];return`${Pn}:${mr.x}:${mr.y}`}for(let Pn=0;PnPn.geometry)}(this.features)),B.get("symbol-elevation-reference")==="hd-road-markup"){if(this.elevationType="road",_.elevationFeatures){!this.elevationFeatures&&_.elevationFeatures.length>0&&(this.elevationFeatures=[],this.elevationFeatureIdToIndex=new Map);for(const hs of _.elevationFeatures)this.elevationFeatureIdToIndex.set(hs.id,this.elevationFeatures.length),this.elevationFeatures.push(hs)}}else B.get("symbol-z-elevate")&&(this.elevationType="offset");this.elevationType!=="none"&&(this.zOffsetBuffersNeedUpload=!0),this.sortFeaturesByKey&&this.features.sort((hs,ms)=>hs.sortKey-ms.sortKey)}getCombinedIconPrimary(g,_,C,P,O,B,W){let Y,ae;if(g.hasLayoutProperty("icon-image")){const pe=_.getAppearanceValueAndResolveTokens(g,"icon-image",C,P,O);Y=this.getResolvedImageFromTokens(pe)}else{const pe=_.getValueAndResolveTokens("icon-image",C,P,O);Y=this.getResolvedImageFromTokens(pe)}if(Y){const pe=g.hasLayoutProperty("icon-size")?g.getUnevaluatedLayoutProperty("icon-size"):_._unevaluatedLayout._values["icon-size"];ae=pK(Y,BL(this.zoom,pe,this.worldview,O),pe,P,this.zoom,B,this.pixelRatio,W,this.worldview,O).iconPrimary}return ae}updateSymbolInstanceIconVertices(g,_,C,P,O,B){const{canonical:W,availableImages:Y,globalProperties:ae,layer:pe,iconScaleFactor:ve,featureState:_e,layoutIconOffset:Pe,layoutIconSize:De,layoutIconRotate:We}=B;if(g.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(_.activeAppearanceIndex===C)return{vertexOffsetDelta:g.numIconVertices,hasChanges:!1};const Je=C>=0?pe.appearances[C]:null;if(Je){const rt=this.getCombinedIconPrimary(Je,pe,P,W,Y,{sortKey:void 0,text:void 0,icon:null,index:g.featureIndex,sourceLayerIndex:g.featureIndex,geometry:[],properties:_.properties,type:"Point",id:_.id},ve);if(!rt)return{vertexOffsetDelta:0,hasChanges:!1};const xt=rt.toString(),ut=this.iconAtlasPositions&&this.iconAtlasPositions.get(xt);if(ut){const{appearanceIconOffset:St,appearanceIconRotate:Rt}=olt(Je,pe,P,W,Pe,We,De,ve);let Ft=aie(ut,void 0,St,pe.layout.get("icon-anchor").evaluate(P,_e,W));const bs=ut.sdf,as=pe.layout.get("icon-text-fit").constantOr("none");as!=="none"&&_.textShaping&&_.iconTextFitPadding&&_.fontScale&&(Ft=gRe(Ft,_.textShaping,as,_.iconTextFitPadding,St,_.fontScale));const ys=this.calculateEffectiveAppearanceIconSize(Je,ae.zoom,P,W,Y,ve,De),hs=0,ms=1+(Math.min(UL,Math.round(ys*G3))<<1),vn=jRe(Ft,Rt,bs,as!=="none",ve);_.isUsingAppearanceIconVertexData||(_.isUsingAppearanceIconVertexData=!0,_.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(O,g.numIconVertices));const Nn=Math.floor(g.numIconVertices/4),Tn=Math.min(vn.length,Nn);let Ln=O;for(let Qn=0;Qn0||g.numVerticalGlyphVertices>0;if(!St)return{vertexOffsetDelta:St?g.numHorizontalGlyphVertices+g.numVerticalGlyphVertices:0,hasChanges:!1};if(_.activeAppearanceIndex===C)return{vertexOffsetDelta:g.numHorizontalGlyphVertices+g.numVerticalGlyphVertices,hasChanges:!1};const Rt=C>=0?Y.appearances[C]:null;if(Rt&&_.textShaping){const{appearanceTextOffset:Ft,appearanceTextRotate:bs,appearanceTextSize:as}=llt(Rt,Y,P,W,_e,De,Pe);_.fontScale=hlt(as,_.textScaleFactor);const ys=Rt.getUnevaluatedLayoutProperty("text-size");let hs=this.textSizeData,ms=rt,vn=xt;Rt.hasLayoutProperty("text-size")&&(hs=BL(this.zoom,ys,this.worldview,ut),ms=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,vn=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0);const Nn=_.textShaping.bottom-_e[1],Tn=_.textShaping.left-_e[0],Ln=_.textShaping.right-_e[0];_.textShaping.top=Ft[1]+(_.textShaping.top-_e[1]),_.textShaping.bottom=Ft[1]+Nn,_.textShaping.left=Ft[0]+Tn,_.textShaping.right=Ft[0]+Ln;const Mn=alt(0,_.textShaping,Ft,Y,!1,P,pe,this.allowVerticalPlacement,bs),Qn=as&&hs.kind==="composite"?ys.possiblyEvaluate(new Oi(ms,{}),W).evaluate(P,ve,W):We,fn=as&&hs.kind==="composite"?ys.possiblyEvaluate(new Oi(vn,{}),W).evaluate(P,ve,W):Je,Pn=CRe(Rt.name,hs,as,ae,Qn,fn),Dn=Array.isArray(Pn)?Pn[1]:as,tr=0,mr=1+(Math.min(UL,Math.round(Dn*G3))<<1);_.isUsingAppearanceTextVertexData||(_.isUsingAppearanceTextVertexData=!0,_.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(O,g.numHorizontalGlyphVertices+g.numVerticalGlyphVertices));for(let ta=0;ta0){const ae=new Set(Object.keys(g).map(pe=>{const ve=Number(pe);return!isNaN(ve)&&Number.isSafeInteger(ve)&&String(ve)===pe?ve:pe}));this.text.uboBinder&&this.text.uboBinder.updateFeatures(ae,O[0],_,Y,C,g,W),this.icon.uboBinder&&this.icon.uboBinder.updateFeatures(ae,O[0],_,Y,C,g,W)}}}updateRoadElevation(g){if(this.elevationType!=="road"||!this.elevationFeatures||this.elevationStateComplete)return;this.elevationStateComplete=!0,this.hasAnyZOffset=!1;let _=!1;const C=Vn(g),P=1/C;let O=!1,B=!1;for(let W=0;W0||_e>0,Je=Pe>0,rt=this.elevationFeatures[Y.elevationFeatureIndex];if(rt){const xt=new es(Y.tileAnchorX,Y.tileAnchorY),ut=.075+rt.pointElevation(xt);Y.zOffset!==ut&&(_=!0,Y.zOffset=ut),ut!==0&&(this.hasAnyZOffset=!0);const St=rt.computeSlopeNormal(xt,P),Rt=As(pt(),Z(0,0,1),St);Fe(ae,ae,Rt),Fe(pe,pe,Rt),ae[2]*=C,pe[2]*=C,ae[0]===1&&ae[1]===0&&ae[2]===0&&pe[0]===0&&pe[1]===1&&pe[2]===0||(O=O||We,B=B||Je)}if(We&&(gie(this.text.orientationVertexArray,ve,ae,pe),gie(this.text.orientationVertexArray,_e,ae,pe)),Je){const{placedIconSymbolIndex:xt,verticalPlacedIconSymbolIndex:ut}=Y;xt>=0&&gie(this.icon.orientationVertexArray,Pe,ae,pe),ut>=0&&gie(this.icon.orientationVertexArray,De,ae,pe)}}O||(this.text.orientationVertexArray=void 0),B||(this.icon.orientationVertexArray=void 0),_&&(this.zOffsetBuffersNeedUpload=!0,this.zOffsetSortDirty=!0)}updateZOffset(){const g=(O,B,W)=>{C+=B,C>O.length&&O.resize(C);for(let Y=-B;Y<0;Y++)O.emplace(Y+C,W)},_=(O,B,W)=>{P+=B,P>O.length&&O.resize(P);for(let Y=-B;Y<0;Y++)O.emplace(Y+P,W)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let C=0,P=0;for(let O=0;O0;if((W>0||Y>0)&&(g(this.text.zOffsetVertexArray,W,pe),g(this.text.zOffsetVertexArray,Y,pe)),ve){const{placedIconSymbolIndex:_e,verticalPlacedIconSymbolIndex:Pe}=B;_e>=0&&_(this.icon.zOffsetVertexArray,ae,pe),Pe>=0&&_(this.icon.zOffsetVertexArray,B.numVerticalIconVertices,pe)}}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(g,_,C,P,O){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(g),this.iconCollisionBox.upload(g)),this.text.upload(g,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.hasAppearances===null&&(this.hasAppearances=this.layers.some(B=>B.appearances&&B.appearances.length>0)),this.icon.upload(g,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.uploaded=!0}updateAppearances(g,_,C,P,O,B=!1){const W={hasLayoutChanges:!1,hasUboChanges:!1};if(!g||!C||!this.featureAppearanceData)return W;const Y=_||{},ae=this.icon.layoutVertexArray&&this.icon.layoutVertexArray.length>0&&this.icon.layoutVertexArray.arrayBuffer,pe=this.text.layoutVertexArray&&this.text.layoutVertexArray.length>0&&this.text.layoutVertexArray.arrayBuffer;if(!ae&&!pe)return W;const ve=this.layers[0],_e=ve.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===ve.appearancesVersion||(this.featureAppearances=new yls(ve.appearances,ve.appearancesVersion));const Pe=this.featureAppearances.update(P,B);if(Pe.kind==="no-changes")return W;let De=1,We=0,Je=!1,rt=!1;if(ae){const[Ft,bs]=_e.get("icon-size-scale-range");De=mt(1,Ft,bs)}let xt=1,ut=0,St=!1;if(pe){const[Ft,bs]=_e.get("text-size-scale-range");xt=mt(1,Ft,bs)}const Rt=new Map;if(O&&C)for(const Ft of C){const bs=O.getImage(Ft,ve.scope);if(bs){const as=new tu(Ft.toString());Rt.set(as.toString(),bs)}}for(let Ft=0;FtLn.isActive({globals:P,feature:ms,canonical:g,featureState:hs})):-1;vn=Tn>=0?Tn:-1}const Nn=as.activeAppearanceIndex!==vn;if(pe){const Tn=_e.get("text-size"),Ln=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Mn=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,Qn={canonical:g,layer:ve,featureState:hs,availableImages:C,textScaleFactor:xt,imageMap:Rt,layoutTextOffset:_e.get("text-offset").evaluate(ms,hs,g).map(Pn=>Pn*jp),layoutTextSize:Tn.evaluate(ms,hs,g),layoutTextRotate:_e.get("text-rotate").evaluate(ms,hs,g),layoutMinZoomSize:Tn.evaluate(ms,{zoom:Ln},g),layoutMaxZoomSize:Tn.evaluate(ms,{zoom:Mn},g),layoutTextSizeMinZoom:Ln,layoutTextSizeMaxZoom:Mn},fn=this.updateSymbolInstanceTextVertices(bs,as,vn,ms,ut,Qn);ut+=fn.vertexOffsetDelta,St=St||fn.hasChanges}if(ae){const Tn={canonical:g,layer:ve,featureState:hs,availableImages:C,globalProperties:P,iconScaleFactor:De,layoutIconOffset:_e.get("icon-offset").evaluate(ms,hs,g),layoutIconSize:_e.get("icon-size").evaluate(ms,hs,g,C),layoutIconRotate:_e.get("icon-rotate").evaluate(ms,hs,g)},Ln=this.updateSymbolInstanceIconVertices(bs,as,vn,ms,We,Tn);We+=Ln.vertexOffsetDelta,Je=Je||Ln.hasChanges}if(Nn){const Tn=bs.featureIndex,Ln=P?P.brightness:null,Mn=hs||{},Qn=vn>=0?ve.appearances[vn]:null;this.text.uboBinder&&(this.text.uboBinder.layer=ve,rt=this.text.uboBinder.updateFeaturePaintForAppearance(Tn,ms,Mn,g,C,Ln,Qn)||rt),this.icon.uboBinder&&(this.icon.uboBinder.layer=ve,rt=this.icon.uboBinder.updateFeaturePaintForAppearance(Tn,ms,Mn,g,C,Ln,Qn)||rt)}as.activeAppearanceIndex=vn}return Je&&this.icon.layoutVertexBuffer&&this.icon.layoutVertexArray.arrayBuffer!==null&&this.icon.layoutVertexArray.length===this.icon.layoutVertexBuffer.length&&this.icon.layoutVertexBuffer.updateData(this.icon.layoutVertexArray),St&&this.text.layoutVertexBuffer&&this.text.layoutVertexArray.arrayBuffer!==null&&this.text.layoutVertexArray.length===this.text.layoutVertexBuffer.length&&this.text.layoutVertexBuffer.updateData(this.text.layoutVertexArray),{hasLayoutChanges:Je||St,hasUboChanges:rt}}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}getProjection(){return this.projectionInstance||(this.projectionInstance=blt(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(g,_){const C=this.lineVertexArray.length;if(g.segment!==void 0)for(const{x:P,y:O}of _)this.lineVertexArray.emplaceBack(P,O);return{lineStartIndex:C,lineLength:this.lineVertexArray.length-C}}addSymbols(g,_,C,P,O,B,W,Y,ae,pe,ve,_e,Pe,De,We,Je,rt,xt){const ut=g.indexArray,St=g.layoutVertexArray,Rt=g.globeExtVertexArray,Ft=xt,bs=g.uboBinder?g.uboBinder.getCurrentBatchIndex():void 0,as=g.segments.prepareSegment(4*Ft,St,ut,this.canOverlap?B.sortKey:void 0,bs),ys=this.glyphOffsetArray.length,hs=as.vertexLength,ms=this.allowVerticalPlacement&&W===L1.vertical?Math.PI/2:0,vn=B.text&&B.text.sections;let Nn=St.length,Tn=-1;for(let Qn=0;Qn<_.length;Qn++){const{tl:fn,tr:Pn,bl:Dn,br:tr,texPrimary:mr,texSecondary:ta,pixelOffsetTL:Cr,pixelOffsetBR:Nr,minFontScaleX:pr,minFontScaleY:Kr,glyphOffset:da,isSDF:$a,sectionIndex:ja}=_[Qn],Pi=as.vertexLength,zo=da[1];if(vK(St,ae.x,ae.y,fn.x,zo+fn.y,mr.x,mr.y,C,$a,Cr.x,Cr.y,pr,Kr),vK(St,ae.x,ae.y,Pn.x,zo+Pn.y,mr.x+mr.w,mr.y,C,$a,Nr.x,Cr.y,pr,Kr),vK(St,ae.x,ae.y,Dn.x,zo+Dn.y,mr.x,mr.y+mr.h,C,$a,Cr.x,Nr.y,pr,Kr),vK(St,ae.x,ae.y,tr.x,zo+tr.y,mr.x+mr.w,mr.y+mr.h,C,$a,Nr.x,Nr.y,pr,Kr),Y){const{x:Li,y:$o,z:to}=Y.anchor,[mu,jl,el]=Y.up;_K(Rt,Li,$o,to,mu,jl,el),_K(Rt,Li,$o,to,mu,jl,el),_K(Rt,Li,$o,to,mu,jl,el),_K(Rt,Li,$o,to,mu,jl,el),yz(g.dynamicLayoutVertexArray,Li,$o,to,ms)}else yz(g.dynamicLayoutVertexArray,ae.x,ae.y,ae.z,ms);if(Je){const Li=ta||mr;bK(g.iconTransitioningVertexArray,Li.x,Li.y),bK(g.iconTransitioningVertexArray,Li.x+Li.w,Li.y),bK(g.iconTransitioningVertexArray,Li.x,Li.y+Li.h),bK(g.iconTransitioningVertexArray,Li.x+Li.w,Li.y+Li.h)}if(ut.emplaceBack(Pi,Pi+1,Pi+2),ut.emplaceBack(Pi+1,Pi+2,Pi+3),as.vertexLength+=4,as.primitiveLength+=2,this.glyphOffsetArray.emplaceBack(da[0]),(Qn===_.length-1||ja!==_[Qn+1].sectionIndex)&&(g.programConfigurations.populatePaintArrays(St.length,B,B.index,{},Pe,De,We,vn&&vn[ja],this.worldview),g.uboBinder&&g.featureIdArray)){const Li=g.uboBinder.populateUBO(B,B.index,De,Pe,We,vn&&vn[ja],void 0);Tn=Li;const $o=St.length-Nn;for(let to=0;to<$o;to++)g.featureIdArray.emplaceBack(Li);Nn=St.length}}const Ln=xt-_.length;if(Ln!==0&&(this._addNullVertices(Ln,St,C,Y,Rt,g,Je,as,ut),g.uboBinder&&g.featureIdArray&&Tn>=0)){const Qn=4*Ln;for(let fn=0;fn=0?_.rightJustifiedTextSymbolIndex:_.centerJustifiedTextSymbolIndex>=0?_.centerJustifiedTextSymbolIndex:_.leftJustifiedTextSymbolIndex>=0?_.leftJustifiedTextSymbolIndex:_.verticalPlacedTextSymbolIndex>=0?_.verticalPlacedTextSymbolIndex:P),B=xRe(this.textSizeData,g,O)/jp;return this.tilePixelRatio*B}getSymbolInstanceIconSize(g,_,C){const P=this.icon.placedSymbolArray.get(C),O=xRe(this.iconSizeData,g,P);return this.tilePixelRatio*O}_commitDebugCollisionVertexUpdate(g,_,C,P){g.emplaceBack(_,-C,-C,P),g.emplaceBack(_,C,-C,P),g.emplaceBack(_,C,C,P),g.emplaceBack(_,-C,C,P)}_updateTextDebugCollisionBoxes(g,_,C,P,O,B,W){for(let Y=P;Y0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}hasIconTextFit(){return this.hasAnyIconTextFit}addIndicesForPlacedSymbol(g,_){const C=g.placedSymbolArray.get(_),P=C.vertexStartIndex+4*C.numGlyphs;for(let O=C.vertexStartIndex;OP[W]-P[Y]||O[Y]-O[W]),B}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let g=0;gthis.symbolInstances.get(_).zOffset-this.symbolInstances.get(g).zOffset)}addToSortKeyRanges(g,_){const C=this.sortKeyRanges[this.sortKeyRanges.length-1];C&&C.sortKey===_?C.symbolInstanceEnd=g+1:this.sortKeyRanges.push({sortKey:_,symbolInstanceStart:g,symbolInstanceEnd:g+1})}sortFeatures(g){if(this.sortFeaturesByY&&this.sortedAngle!==g)if(this.text.segments.get().length>1||this.icon.segments.get().length>1)this.sortFeaturesWithinSegments();else{this.symbolInstanceIndexes=this.getSortedSymbolIndexes(g),this.sortedAngle=g,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:P,centerJustifiedTextSymbolIndex:O,leftJustifiedTextSymbolIndex:B,verticalPlacedTextSymbolIndex:W,placedIconSymbolIndex:Y,verticalPlacedIconSymbolIndex:ae}=C;P>=0&&this.addIndicesForPlacedSymbol(this.text,P),O>=0&&O!==P&&this.addIndicesForPlacedSymbol(this.text,O),B>=0&&B!==O&&B!==P&&this.addIndicesForPlacedSymbol(this.text,B),W>=0&&this.addIndicesForPlacedSymbol(this.text,W),Y>=0&&this.addIndicesForPlacedSymbol(this.icon,Y),ae>=0&&this.addIndicesForPlacedSymbol(this.icon,ae)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}getOrCreateSortedSymbolsByBatch(g,_){const C=(this.text.uboBinder&&this.text.uboBinder.maxFeaturesPerBatch>0?this.text.uboBinder:this.icon.uboBinder&&this.icon.uboBinder.maxFeaturesPerBatch>0?this.icon.uboBinder:null).maxFeaturesPerBatch;if(this.symbolsByBatch)for(const P of this.symbolsByBatch.values())for(const O of P){const B=this.symbolInstances.get(O.index);O.rotatedY=0|Math.round(g*B.tileAnchorX+_*B.tileAnchorY)}else{this.symbolsByBatch=new Map;for(let P=0;PO.rotatedY-B.rotatedY||B.featureIndex-O.featureIndex);return this.symbolsByBatch}rebuildTextSegmentIndices(g,_){for(const C of g){const P=C.batchIndex;if(P===void 0)continue;const O=_.get(P);if(!O){C.primitiveOffset=this.text.indexArray.length,C.primitiveLength=0;continue}C.primitiveOffset=this.text.indexArray.length;const B=this.text.indexArray.length;for(const{index:W}of O){const Y=this.symbolInstances.get(W),{rightJustifiedTextSymbolIndex:ae,centerJustifiedTextSymbolIndex:pe,leftJustifiedTextSymbolIndex:ve,verticalPlacedTextSymbolIndex:_e}=Y;ae>=0&&this.addIndicesForPlacedSymbol(this.text,ae),pe>=0&&pe!==ae&&this.addIndicesForPlacedSymbol(this.text,pe),ve>=0&&ve!==pe&&ve!==ae&&this.addIndicesForPlacedSymbol(this.text,ve),_e>=0&&this.addIndicesForPlacedSymbol(this.text,_e)}C.primitiveLength=this.text.indexArray.length-B}}rebuildIconSegmentIndices(g,_){for(const C of g){const P=C.batchIndex;if(P===void 0)continue;const O=_.get(P);if(!O){C.primitiveOffset=this.icon.indexArray.length,C.primitiveLength=0;continue}C.primitiveOffset=this.icon.indexArray.length;const B=this.icon.indexArray.length;for(const{index:W}of O){const Y=this.symbolInstances.get(W),{placedIconSymbolIndex:ae,verticalPlacedIconSymbolIndex:pe}=Y;ae>=0&&this.addIndicesForPlacedSymbol(this.icon,ae),pe>=0&&this.addIndicesForPlacedSymbol(this.icon,pe)}C.primitiveLength=this.icon.indexArray.length-B}}sortFeaturesWithinSegments(){this.featureSortOrder=[];const g=Math.sin(this.sortedAngle),_=Math.cos(this.sortedAngle),C=this.getOrCreateSortedSymbolsByBatch(g,_),P=Array.from(C.keys()).sort((O,B)=>O-B);for(const O of P){const B=C.get(O);for(const{index:W}of B){const Y=this.symbolInstances.get(W);this.featureSortOrder.push(Y.featureIndex)}}this.text.indexArray.clear(),this.icon.indexArray.clear(),this.rebuildTextSegmentIndices(this.text.segments.get(),C),this.rebuildIconSegmentIndices(this.icon.segments.get(),C),this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}getElevationFeatureForText(g){const _=this.symbolInstances.get(this.text.symbolInstanceIndices[g]).elevationFeatureIndex;let C;return this.elevationFeatures&&_C in k?String(k[C]):"")}let wlt,jlt,MRe;wr(KN,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),KN.addDynamicAttributes=yz;class Nlt{constructor(g){this.type=g.property.overrides?g.property.overrides.runtimeType:Ra,this.defaultValue=g}evaluate(g){if(g.formattedSection){const _=this.defaultValue.property.overrides;if(_&&_.hasOverride(g.formattedSection))return _.getOverride(g.formattedSection)}return g.feature&&g.featureState?this.defaultValue.evaluate(g.feature,g.featureState):this.defaultValue.property.specification.default}eachChild(g){this.defaultValue.isConstant()||g(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}wr(Nlt,"FormatSectionOverride",{omit:["defaultValue"]});const PRe=()=>MRe||(MRe={layout:wlt||(wlt=new Wc({"symbol-placement":new lr(Us.layout_symbol["symbol-placement"]),"symbol-spacing":new lr(Us.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new lr(Us.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new or(Us.layout_symbol["symbol-sort-key"]),"symbol-z-order":new lr(Us.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new lr(Us.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new lr(Us.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new lr(Us.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new lr(Us.layout_symbol["icon-ignore-placement"]),"icon-optional":new lr(Us.layout_symbol["icon-optional"]),"icon-rotation-alignment":new lr(Us.layout_symbol["icon-rotation-alignment"]),"icon-size":new or(Us.layout_symbol["icon-size"]),"icon-size-scale-range":new lr(Us.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new or(Us.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new or(Us.layout_symbol["icon-text-fit-padding"]),"icon-image":new or(Us.layout_symbol["icon-image"]),"icon-image-use-theme":new lr({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new or(Us.layout_symbol["icon-rotate"]),"icon-padding":new lr(Us.layout_symbol["icon-padding"]),"icon-keep-upright":new lr(Us.layout_symbol["icon-keep-upright"]),"icon-offset":new or(Us.layout_symbol["icon-offset"]),"icon-anchor":new or(Us.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new lr(Us.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new lr(Us.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new lr(Us.layout_symbol["text-rotation-alignment"]),"text-field":new or(Us.layout_symbol["text-field"]),"text-font":new or(Us.layout_symbol["text-font"]),"text-size":new or(Us.layout_symbol["text-size"]),"text-size-scale-range":new lr(Us.layout_symbol["text-size-scale-range"]),"text-max-width":new or(Us.layout_symbol["text-max-width"]),"text-line-height":new or(Us.layout_symbol["text-line-height"]),"text-letter-spacing":new or(Us.layout_symbol["text-letter-spacing"]),"text-justify":new or(Us.layout_symbol["text-justify"]),"text-radial-offset":new or(Us.layout_symbol["text-radial-offset"]),"text-variable-anchor":new lr(Us.layout_symbol["text-variable-anchor"]),"text-anchor":new or(Us.layout_symbol["text-anchor"]),"text-max-angle":new lr(Us.layout_symbol["text-max-angle"]),"text-writing-mode":new lr(Us.layout_symbol["text-writing-mode"]),"text-rotate":new or(Us.layout_symbol["text-rotate"]),"text-padding":new lr(Us.layout_symbol["text-padding"]),"text-keep-upright":new lr(Us.layout_symbol["text-keep-upright"]),"text-transform":new or(Us.layout_symbol["text-transform"]),"text-offset":new or(Us.layout_symbol["text-offset"]),"text-allow-overlap":new lr(Us.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new lr(Us.layout_symbol["text-ignore-placement"]),"text-optional":new lr(Us.layout_symbol["text-optional"]),visibility:new lr(Us.layout_symbol.visibility)})),paint:jlt||(jlt=new Wc({"icon-opacity":new or(Us.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new or(Us.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new or(Us.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new or(Us.paint_symbol["text-emissive-strength"]),"icon-color":new or(Us.paint_symbol["icon-color"]),"icon-halo-color":new or(Us.paint_symbol["icon-halo-color"]),"icon-halo-width":new or(Us.paint_symbol["icon-halo-width"]),"icon-halo-blur":new or(Us.paint_symbol["icon-halo-blur"]),"icon-translate":new lr(Us.paint_symbol["icon-translate"]),"icon-translate-anchor":new lr(Us.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new lr(Us.paint_symbol["icon-image-cross-fade"]),"text-opacity":new or(Us.paint_symbol["text-opacity"]),"text-occlusion-opacity":new or(Us.paint_symbol["text-occlusion-opacity"]),"text-color":new or(Us.paint_symbol["text-color"],{runtimeType:ol,getOverride:k=>k.textColor,hasOverride:k=>!!k.textColor}),"text-halo-color":new or(Us.paint_symbol["text-halo-color"]),"text-halo-width":new or(Us.paint_symbol["text-halo-width"]),"text-halo-blur":new or(Us.paint_symbol["text-halo-blur"]),"text-translate":new lr(Us.paint_symbol["text-translate"]),"text-translate-anchor":new lr(Us.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new lr(Us.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new lr(Us.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new lr(Us.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new lr(Us.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new or(Us.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new or({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new or({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new or({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new or({type:"string",default:"default","property-type":"data-driven"})}))},MRe);class xie extends Wl{constructor(g,_,C,P){super(g,PRe(),_,C,P,g.layout?g.layout["icon-image-use-theme"]:null),this._colorAdjustmentMatrix=y([]),this.hasOcclusionOpacityProperties=g.paint!==void 0&&("icon-occlusion-opacity"in g.paint||"text-occlusion-opacity"in g.paint)}_handleSpecialPaintPropertyUpdate(g){g!=="icon-occlusion-opacity"&&g!=="text-occlusion-opacity"||(this.hasOcclusionOpacityProperties=!0)}recalculate(g,_){super.recalculate(g,_),this.appearances&&this.appearances.forEach(P=>{P.recalculate(g,_,this.iconImageUseTheme)}),this.layout.get("icon-rotation-alignment")==="auto"&&(this.layout._values["icon-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-rotation-alignment")==="auto"&&(this.layout._values["text-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-pitch-alignment")==="auto"&&(this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")),this.layout.get("icon-pitch-alignment")==="auto"&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment"));const C=this.layout.get("text-writing-mode");if(C){const P=[];for(const O of C)P.indexOf(O)<0&&P.push(O);this.layout._values["text-writing-mode"]=P}else this.layout._values["text-writing-mode"]=this.layout.get("symbol-placement")==="point"?["horizontal"]:["horizontal","vertical"];this._setPaintOverrides()}getColorAdjustmentMatrix(g,_,C,P){return this._saturation===g&&this._contrast===_&&this._brightnessMin===C&&this._brightnessMax===P||(this._colorAdjustmentMatrix=function(O,B,W,Y){O=Qo(O),B=hi(B);const ae=f(),pe=O/3,ve=1-2*pe,_e=[ve,pe,pe,0,pe,ve,pe,0,pe,pe,ve,0,0,0,0,1],Pe=.5-.5*B,De=Y-W;return b(ae,[De,0,0,0,0,De,0,0,0,0,De,0,W,W,W,1],[B,0,0,0,0,B,0,0,0,0,B,0,Pe,Pe,Pe,1]),b(ae,ae,_e),ae}(g,_,C,P),this._saturation=g,this._contrast=_,this._brightnessMin=C,this._brightnessMax=P),this._colorAdjustmentMatrix}getValueAndResolveTokens(g,_,C,P){const O=this.layout.get(g).evaluate(_,{},C,P),B=this._unevaluatedLayout._values[g];return B.isDataDriven()||xp(B.value)||!O?O:_lt(_.properties,O)}getAppearanceValueAndResolveTokens(g,_,C,P,O){const B=g.getLayoutProperty(_);if(!B)return;const W=B.evaluate(C,{},P,O),Y=g.getUnevaluatedLayoutProperties()._values[_];return Y.isDataDriven()||xp(Y.value)||!W||typeof W!="string"?W:_lt(C.properties,W)}createBucket(g){return new KN(g)}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const g of PRe().paint.overridableProperties){if(!xie.hasPaintOverride(this.layout,g))continue;const _=this.paint.get(g),C=new Nlt(_),P=new hh(C,_.property.specification,this.scope,this.options,this.layout.get("icon-image-use-theme"));let O=null;O=_.value.kind==="constant"||_.value.kind==="source"?new Ih("source",P):new wc("composite",P,_.value.zoomStops,_.value.interpolationType),this.paint._values[g]=new qN(_.property,O,_.parameters)}}_handleOverridablePaintPropertyUpdate(g,_,C){return!(!this.layout||_.isDataDriven()||C.isDataDriven())&&xie.hasPaintOverride(this.layout,g)}static hasPaintOverride(g,_){const C=g.get("text-field"),P=PRe().paint.properties[_];let O=!1;const B=W=>{for(const Y of W)if(P.overrides&&P.overrides.hasOverride(Y))return void(O=!0)};if(C.value.kind==="constant"&&C.value.value instanceof Bd)B(C.value.value.sections);else if(C.value.kind==="source"){const W=ae=>{O||(ae instanceof Hr&&Hl(ae.value)===k0?B(ae.value.sections):ae instanceof Ud?B(ae.sections):ae.eachChild(W))},Y=C.value;Y._styleExpression&&W(Y._styleExpression.expression)}return O}getProgramIds(){return["symbol"]}getDefaultProgramParams(g,_,C){return{config:new Ke(this,{zoom:_,lut:C}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}}let klt,Slt,Clt,Alt;var yie=$n([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);function vie(k,g,_,C,P,O,B,W){const Y=[k,g,1,_,C,1,P,O,1],ae=[B,W,1],pe=m([],Y),[ve,_e,Pe]=Ae(ae,ae,pe);return p(Y,Y,[ve,0,0,0,_e,0,0,0,Pe])}function Elt(k,g,_,C,P,O,B,W){const Y=function(ae,pe,ve,_e,Pe,De,We,Je){const rt=vie(0,0,1,0,1,1,0,1),xt=vie(ae,pe,ve,_e,Pe,De,We,Je);return p(xt,xt,m([],rt))}(k,g,_,C,P,O,B,W);return[Y[2]/Y[8]/dr,Y[5]/Y[8]/dr]}function bie(k){return[k[0],Math.min(Math.max(k[1],-85.051129),An)]}class Tlt extends qm{constructor(g,_,C,P){super(),this.id=g,this.dispatcher=C,this.coordinates=_.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(P),this.options=_,this._dirty=!1}load(g,_){if(this._loaded=_||!1,this.fire(new ld("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return g&&(this.coordinates=g),this._loaded=!0,void this._finishLoading();this._imageRequest=Bm(this.map._requestManager.transformRequest(this.url,Mu.Image),(C,P)=>{this._imageRequest=null,this._loaded=!0,C?this.fire(new Gp(C)):P&&(this.image=P,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,g&&(this.coordinates=g),this._finishLoading())})}loaded(){return this._loaded}updateImage(g){return g.url?(this._imageRequest&&g.url!==this.options.url&&(this._imageRequest.cancel(),this._imageRequest=null),this.options.url=g.url,this.load(g.coordinates,this._loaded),this):this}setTexture(g){if(!(g.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new iK(this.map.painter.context,g.handle),this.width=g.dimensions[0],this.height=g.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new ld("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(g){this.map=g,this.load()}onRemove(g){this._imageRequest&&(this._imageRequest.cancel(),this._imageRequest=null),!this.texture||this.texture instanceof iK||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(g){if(this.coordinates=g,this._boundsArray=void 0,this._unsupportedCoords=!1,!g.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let _=g[0][1],C=g[0][1];for(const O of g)O[1]>C&&(C=O[1]),O[1]<_&&(_=O[1]);const P=(C+_)/2;if(P>An?this.onNorthPole=!0:P<-85.051129&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const O=g.map(ca.fromLngLat);this.tileID=function(B){let W=1/0,Y=1/0,ae=-1/0,pe=-1/0;for(const We of B)W=Math.min(W,We.x),Y=Math.min(Y,We.y),ae=Math.max(ae,We.x),pe=Math.max(pe,We.y);const ve=Math.max(ae-W,pe-Y),_e=Math.max(0,Math.floor(-Math.log2(ve))),Pe=Math.pow(2,_e);let De=Math.floor((W+ae)/2*Pe);return De>1&&(De-=1),new RL(_e,De,Math.floor((Y+pe)/2*Pe))}(O),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new ld("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof iK||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(g){for(const Je in this.tiles){const rt=this.tiles[Je];rt.state!=="loaded"&&(rt.state="loaded",rt.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const _=qL(new RL(0,0,0),this.map.transform.projection),C=[_.projection.project(this.coordinates[0][0],this.coordinates[0][1]),_.projection.project(this.coordinates[1][0],this.coordinates[1][1]),_.projection.project(this.coordinates[2][0],this.coordinates[2][1]),_.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function(Je){const rt=Je[1].x-Je[0].x,xt=Je[1].y-Je[0].y,ut=Je[2].x-Je[1].x,St=Je[2].y-Je[1].y,Rt=Je[3].x-Je[2].x,Ft=Je[3].y-Je[2].y,bs=Je[0].x-Je[3].x,as=Je[0].y-Je[3].y,ys=rt*St-ut*xt,hs=ut*Ft-Rt*St,ms=Rt*as-bs*Ft,vn=bs*xt-rt*as;return ys>0&&hs>0&&ms>0&&vn>0||ys<0&&hs<0&&ms<0&&vn<0}(C))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const P=qL(this.tileID,this.map.transform.projection),[O,B,W,Y]=this.coordinates.map(Je=>{const rt=P.projection.project(Je[0],Je[1]);return flt(P,rt)._round()});this.perspectiveTransform=Elt(O.x,O.y,B.x,B.y,W.x,W.y,Y.x,Y.y);const ae=this._boundsArray=new ho;ae.emplaceBack(O.x,O.y,0,0),ae.emplaceBack(B.x,B.y,dr,0),ae.emplaceBack(Y.x,Y.y,0,dr),ae.emplaceBack(W.x,W.y,dr,dr),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=g.createVertexBuffer(ae,yie.members),this.boundsSegments=Ec.simpleSegment(0,0,4,2);const pe=[],ve=function(Je){return[bie(Je[0]),bie(Je[1]),bie(Je[2]),bie(Je[3])]}(this.coordinates),[_e,Pe,De,We]=function(Je){let rt=Je[0][0],xt=rt,ut=Je[0][1],St=ut;for(let Rt=1;Rtxt&&(xt=Je[Rt][0]),Je[Rt][1]St&&(St=Je[Rt][1]);return[rt,ut,xt-rt,St-ut]}(ve);{const Je=new ho,[rt,xt,ut,St]=function(Mn){let Qn=Mn[0].x,fn=Qn,Pn=Mn[0].y,Dn=Pn;for(let tr=1;trfn&&(fn=Mn[tr].x),Mn[tr].yDn&&(Dn=Mn[tr].y);return[Qn,Pn,fn-Qn,Dn-Pn]}(C),Rt=Mn=>[(Mn.x-rt)/ut,(Mn.y-xt)/St],[Ft,bs,as,ys]=C.map(Rt),hs=function(Mn,Qn,fn,Pn,Dn,tr,mr,ta){const Cr=vie(0,0,1,0,1,1,0,1);return p(Cr,Cr,m([],vie(Mn,Qn,fn,Pn,Dn,tr,mr,ta)))}(Ft[0],Ft[1],bs[0],bs[1],as[0],as[1],ys[0],ys[1]);this.elevatedGlobePerspectiveTransform=Elt(Ft[0],Ft[1],bs[0],bs[1],as[0],as[1],ys[0],ys[1]);const ms=(Mn,Qn)=>{pe.push(Mn.lng);const fn=Math.round((Mn.lng-_e)/De*dr),Pn=Math.round((Mn.lat-Pe)/We*dr),Dn=Rt(Qn),tr=Ae([],[Dn[0],Dn[1],1],hs),mr=Math.round(tr[0]/tr[2]*dr),ta=Math.round(tr[1]/tr[2]*dr);Je.emplaceBack(fn,Pn,mr,ta)},vn=C[3].x-C[0].x,Nn=C[3].y-C[0].y,Tn=C[2].x-C[1].x,Ln=C[2].y-C[1].y;for(let Mn=0;Mn<65;Mn++){const Qn=Mn/64,fn=[C[0].x+Qn*vn,C[0].y+Qn*Nn],Pn=[C[1].x+Qn*Tn,C[1].y+Qn*Ln],Dn=Pn[0]-fn[0],tr=Pn[1]-fn[1];for(let mr=0;mr<65;mr++){const ta=mr/64,Cr={x:fn[0]+Dn*ta,y:fn[1]+tr*ta};ms(_.projection.unproject(Cr.x,Cr.y),Cr)}}this.elevatedGlobeVertexBuffer=g.createVertexBuffer(Je,yie.members)}{this.maxLongitudeTriangleSize=0;let Je=[],rt=new Ru;const xt=(ut,St,Rt)=>{rt.emplaceBack(ut,St,Rt);const Ft=pe[ut],bs=pe[St],as=pe[Rt],ys=Math.min(Math.min(Ft,bs),as),hs=Math.max(Math.max(Ft,bs),as)-ys;hs>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=hs),Je.push(ys+hs/2)};for(let ut=0;ut<64;ut++)for(let St=0;St<64;St++){const Rt=65*ut+St,Ft=Rt+1,bs=Rt+65,as=bs+1;xt(Rt,bs,Ft),xt(Ft,bs,as)}[Je,rt]=function(ut,St){const Rt=Array.from({length:ut.length},(as,ys)=>ys);Rt.sort((as,ys)=>ut[as]-ut[ys]);const Ft=[],bs=new Ru;for(let as=0;as{B.segments.push({vertexOffset:0,primitiveOffset:ve,vertexLength:_.segments[0].vertexLength,primitiveLength:_e,sortKey:void 0,vaos:{}})},Y=.51*this.maxLongitudeTriangleSize;if(Math.abs(C[0]-P)<=Y){const ve=Go(C,0,C.length,P+Y);return ve===C.length||W(ve,Co(C,ve+1,C.length,P+360-Y)-ve),B}P0}}let Plt,Llt,Ilt,Rlt,Dlt,Olt,Flt;class zlt extends Wl{constructor(g,_,C,P){super(g,{layout:Plt||(Plt=new Wc({visibility:new lr(Us["layout_raster-particle"].visibility)})),paint:Llt||(Llt=new Wc({"raster-particle-array-band":new lr(Us["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new lr(Us["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new Iy(Us["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new lr(Us["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new lr(Us["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new lr(Us["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new lr(Us["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new lr(Us["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new or({type:"string",default:"default","property-type":"data-driven"})}))},_,C,P),this._updateColorRamp(),this.lastInvalidatedAt=fd.now()}_clear(){this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null),this.tileFramebuffer&&(this.tileFramebuffer.destroy(),this.tileFramebuffer=null),this.particleFramebuffer&&(this.particleFramebuffer.destroy(),this.particleFramebuffer=null)}onRemove(g){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(g){return!1}_handleSpecialPaintPropertyUpdate(g){g!=="raster-particle-color"&&g!=="raster-particle-max-speed"||(this._updateColorRamp(),this._invalidateAnimationState()),g==="raster-particle-count"&&this._invalidateAnimationState()}_updateColorRamp(){if(!this.hasColorMap())return;const g=this._transitionablePaint._values["raster-particle-color"].value.expression,_=this._transitionablePaint._values["raster-particle-max-speed"].value.expression.evaluate({zoom:0});this.colorRamp=HW({expression:g,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:_}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=fd.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class jls extends Wl{constructor(g,_){super(g,{},_,null),this.implementation=g,g.slot&&(this.slot=g.slot)}is3D(g){return this.implementation.renderingMode==="3d"}hasOffscreenPass(){return this.implementation.prerender!==void 0}isDraped(g){return this.implementation.renderToTile!==void 0}shouldRedrape(){return!!this.implementation.shouldRerenderTiles&&this.implementation.shouldRerenderTiles()}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){}onAdd(g){this.implementation.onAdd&&this.implementation.onAdd(g,g.painter.context.gl)}onRemove(g){this.implementation.onRemove&&this.implementation.onRemove(g,g.painter.context.gl)}}function IRe(k,g,_){const C=[0,0,1],P=ft([]);return Ut(P,P,_?-Un(k)+Math.PI:Un(k)),qt(P,P,-Un(g)),Fe(C,C,P),Te(C,C)}class _ie{constructor(g,_,C,P){this.message=(g?`${g}: `:"")+C,P&&(this.identifier=P),_!=null&&_.__line__&&(this.line=_.__line__)}}function RRe(k,g){const _=k.indexOf("://")===-1;try{return new URL(k,_&&g?"http://example.com":void 0),!0}catch{return!1}}class Blt{constructor(g,_){this.feature=g,this.instancedDataOffset=_,this.instancedDataCount=0,this.rotation=[0,0,0],this.scale=[1,1,1],this.translation=[0,0,0]}}class Ult{constructor(){this.maxScale=1,this.maxXYTranslationDistance=0,this.instancedDataArray=new DW,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={}}colorForInstance(g){const _=16*g,C=this.instancedDataArray.float32;let P=Math.floor(C[_+2]);const O=1.05*(C[_+2]-P);return P/=100,[C[_]%1*1.05,C[_+1]%1*1.05,O,P]}tileCoordinatesForInstance(g){const _=16*g,C=this.instancedDataArray.float32;let P=C[_+0];return P=P>dr?P-dr:P,new es(Math.trunc(P),Math.trunc(C[_+1]))}translationForInstance(g){const _=16*g,C=this.instancedDataArray.float32;return[C[_+4],C[_+5],C[_+6]]}rotationScaleForInstance(g){const _=16*g,C=this.instancedDataArray.float32;return[C[_+7],C[_+8],C[_+9],C[_+10],C[_+11],C[_+12],C[_+13],C[_+14],C[_+15]]}transformForInstance(g){const _=16*g,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 DRe{constructor(g){this.zoom=g.zoom,this.canonical=g.canonical,this.overscaledZ=this.canonical.z+Math.log2(g.overscaling),this.layers=g.layers,this.layerIds=this.layers.map(_=>_.fqid),this.projection=g.projection,this.index=g.index,this.worldview=g.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=g.styleDefinedModelURLs,this.hasAppearances=null}updateFootprints(g,_){}updateAppearances(g,_,C,P){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(g,_,C,P){this.tileToMeter=Vn(C);const O=this.layers[0]._featureFilter.needGeometry;this.lookup=new Uint8Array(this.lookupDim*this.lookupDim);const B=this.layers[0].paint.get("model-elevation-reference")==="hd-road-markup"?_.elevationFeatures:void 0;for(const{feature:W,id:Y,index:ae,sourceLayerIndex:pe}of g){const ve=Y??(W.properties&&W.properties.hasOwnProperty("id")?W.properties.id:void 0),_e=eo(W,O);if(!this.layers[0]._featureFilter.filter(new Oi(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),_e,C))continue;const Pe={id:ve,sourceLayerIndex:pe,index:ae,geometry:O?_e.geometry:Ha(W,C,P),properties:W.properties,type:W.type,patterns:{}},De=this.addFeature(Pe,Pe.geometry,_e,B,C);De&&_.featureIndex.insert(W,Pe.geometry,ae,pe,this.index,this.instancesPerModel[De].instancedDataArray.length,256)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const g=this.layers[0].modelManager,_=this.layers[0].scope;let C=0;for(const P of this.modelUris){const O=g.getModel(P,_);if(!O)continue;const B=this.instancesPerModel[P];if(B){const W=.5*be(O.aabb.max,O.aabb.min)*B.maxScale+B.maxXYTranslationDistance,Y=Math.min(dr,Math.max(W/this.tileToMeter,256));C=Math.max(Y,C)}}return C}update(g,_,C,P){for(const O in this.instancesPerModel){const B=this.instancesPerModel[O];for(const W in g)B.idToFeaturesIndex.hasOwnProperty(W)&&(this.evaluate(B.features[B.idToFeaturesIndex[W]],g[W],B,!0),this.uploaded=!1)}this.maxHeight=0}updateZoomBasedPaintProperties(){if(!this.hasZoomDependentProperties)return!1;let g=!1;for(const _ in this.instancesPerModel){const C=this.instancesPerModel[_];for(const P of C.features){const O=this.layers[0],B=P.feature,W=this.canonical,Y=O.paint.get("model-rotation").evaluate(B,{},W),ae=O.paint.get("model-scale").evaluate(B,{},W),pe=O.paint.get("model-translation").evaluate(B,{},W);$e(P.rotation,Y)&&$e(P.scale,ae)&&$e(P.translation,pe)||(this.evaluate(P,P.featureStates,C,!0),g=!0)}}return g}updateReplacement(g,_,C,P){if(_.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=_.updateTime;const O=_.getReplacementRegionsForTile(g.toUnwrapped(),!0);if(Bae(this.activeReplacements,O))return!1;this.activeReplacements=O;let B=!1;for(const W in this.instancesPerModel){const Y=this.instancesPerModel[W],ae=Y.instancedDataArray;for(const pe of Y.features){const ve=pe.instancedDataOffset,_e=pe.instancedDataCount;for(let Pe=0;Pe<_e;Pe++){const De=16*(Pe+ve);let We=ae.float32[De+0];const Je=We>dr;We=Je?We-dr:We;const rt=Math.floor(We),xt=Math.floor(ae.float32[De+1]);let ut=!1;for(const St of this.activeReplacements)if(!wit(St,C,Uae.Model,P)&&!(St.min.x>rt||rt>St.max.x||St.min.y>xt||xt>St.max.y)&&(ut=Cit(Sit(rt,xt,g.canonical,St.footprintTileId.canonical),St.footprint),ut))break;ae.float32[De]=ut?We+dr:We,B=B||ut!==Je}}}return B}isEmpty(){for(const g in this.instancesPerModel)if(this.instancesPerModel[g].instancedDataArray.length!==0)return!1;return!0}uploadPending(){return!this.uploaded}upload(g){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=g.createVertexBuffer(C.instancedDataArray,qis.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(g){for(const C in this.instancesPerModel){const P=this.instancesPerModel[C];P.instancedDataArray.length!==0&&P.instancedDataBuffer&&P.instancedDataBuffer.destroy()}const _=this.layers[0].modelManager;if(g&&_&&this.modelUris&&this.modelsRequested)for(const C of this.modelUris)_.removeModel(C,"",!0)}addFeature(g,_,C,P,O){const B=this.layers[0],W=B.layout.get("model-id"),Y=B.layout.get("model-allow-density-reduction"),ae=W.evaluate(C,{},this.canonical);if(!ae)return qr(`modelId is not evaluated for layer ${B.id} and it is not going to get rendered.`),ae;(RRe(ae,!1)||this.styleDefinedModelURLs[ae]!==void 0)&&(this.modelUris.includes(ae)||this.modelUris.push(ae)),this.instancesPerModel[ae]||(this.instancesPerModel[ae]=new Ult);const pe=this.instancesPerModel[ae],ve=pe.instancedDataArray,_e=new Blt(C,ve.length);let Pe;P&&(Pe=Fc.getElevationFeature(g,P));for(const De of _)for(const We of De){if(We.x<0||We.x>=dr||We.y<0||We.y>=dr)continue;if(this.lookupDim!==0&&Y){const rt=(this.lookupDim-1)/dr,xt=this.lookupDim*(We.y*rt|0)+We.x*rt|0;if(this.lookup){if(this.lookup[xt]!==0)continue;this.lookup[xt]=1}}this.instanceCount++;const Je=ve.length;if(ve.resize(Je+1),P){pe.instancesRoadElevation||(pe.instancesRoadElevation=[]);const rt=Pe?Pe.pointElevation(new es(We.x,We.y)):0;pe.instancesRoadElevation.push(rt)}pe.instancesEvaluatedElevation.push(0),ve.float32[16*Je]=We.x,ve.float32[16*Je+1]=We.y}return _e.instancedDataCount=pe.instancedDataArray.length-_e.instancedDataOffset,_e.instancedDataCount>0&&(g.id&&(pe.idToFeaturesIndex[g.id]=pe.features.length),pe.features.push(_e),this.evaluate(_e,{},pe,!1)),ae}getModelUris(){return this.modelUris}evaluate(g,_,C,P){const O=this.layers[0],B=g.feature,W=this.canonical,Y=g.rotation=O.paint.get("model-rotation").evaluate(B,_,W),ae=g.scale=O.paint.get("model-scale").evaluate(B,_,W),pe=g.translation=O.paint.get("model-translation").evaluate(B,_,W),ve=Object.assign({},O.paint.get("model-color").evaluate(B,_,W));ve.a=O.paint.get("model-color-mix-intensity").evaluate(B,_,W);const _e=[];this.maxVerticalOffset0?Math.sqrt(Pe):0;C.maxScale=Math.max(Math.max(C.maxScale,ae[0]),Math.max(ae[1],ae[2])),C.maxXYTranslationDistance=Math.max(C.maxXYTranslationDistance,De),this.maxScale=Math.max(Math.max(this.maxScale,ae[0]),Math.max(ae[1],ae[2])),uot(_e,Y,ae);const We=Math.round(100*ve.a)+ve.b/1.05;for(let Je=0;Je10?this.tileToMeter:Vn(W,Rt)),ut[xt+4]=pe[0],ut[xt+5]=pe[1],ut[xt+6]=pe[2]+(C.instancesRoadElevation?C.instancesRoadElevation[rt]:0)+St,ut[xt+7]=_e[0],ut[xt+8]=_e[1],ut[xt+9]=_e[2],ut[xt+10]=_e[4],ut[xt+11]=_e[5],ut[xt+12]=_e[6],ut[xt+13]=_e[8],ut[xt+14]=_e[9],ut[xt+15]=_e[10],C.instancesEvaluatedElevation[rt]=pe[2]}}}wr(DRe,"ModelBucket",{omit:["layers"]}),wr(Ult,"PerModelAttributes"),wr(Blt,"ModelFeature");class bz{constructor(g,_,C){this._demTile=g,this._dem=this._demTile.dem,this._scale=_,this._offset=C}static create(g,_,C){const P=C||g.findDEMTileFor(_);if(!P||!P.dem)return;const O=P.dem,B=P.tileID,W=1<<_.canonical.z-B.canonical.z;return new bz(P,O.dim/dr/W,[(_.canonical.x/W-B.canonical.x)*O.dim,(_.canonical.y/W-B.canonical.y)*O.dim])}tileCoordToPixel(g,_){const C=_*this._scale+this._offset[1];return new es(Math.floor(g*this._scale+this._offset[0]),Math.floor(C))}getElevationAt(g,_,C,P){const O=g*this._scale+this._offset[0],B=_*this._scale+this._offset[1],W=Math.floor(O),Y=Math.floor(B),ae=this._dem;return P=!!P,C?Es(Es(ae.get(W,Y,P),ae.get(W,Y+1,P),B-Y),Es(ae.get(W+1,Y,P),ae.get(W+1,Y+1,P),B-Y),O-W):ae.get(W,Y,P)}getElevationAtPixel(g,_,C){return this._dem.get(g,_,!!C)}getMeterToDEM(g){return(1<ae.fqid),this.stateDependentLayerIds=this.layers.filter(ae=>ae.isStateDependent()).map(ae=>ae.id),this.modelTraits|=hz.CoordinateSpaceTile,this.uploaded=!1,this.hasPattern=!1,P&&(this.modelTraits|=hz.HasMapboxMeshFeatures),O&&(this.modelTraits|=hz.HasMeshoptCompression),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:"mercator"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=B,this.worldview=Y,this.dirty=!0,this.needsUpload=!1,this.filter=null,this.nodesInfo=[];for(const ae of _)this.nodesInfo.push(new Hlt(ae)),$lt(ae,W.featureIndexArray.length,W.grid),W.featureIndexArray.emplaceBack(this.nodesInfo.length-1,0,W.bucketLayerIDs.length-1,0);this.states={},this.hasAppearances=null}updateFootprints(g,_){for(const C of this.getNodesInfo()){const P=C.node;P.footprint&&_.push({footprint:P.footprint,id:g})}}updateAppearances(g,_,C,P){return{hasLayoutChanges:!1,hasUboChanges:!1}}update(g){const _=Object.keys(g).length!==0;if(_&&!this.stateDependentLayers.length)return;const C=_?this.stateDependentLayers:this.layers;if(!ar(g,this.states))for(const P of C)this.evaluate(P,g);this.states=structuredClone(g)}populate(){console.log("populate 3D model bucket")}uploadPending(){return!this.uploaded||this.needsUpload}upload(g){if(!this.needsUpload)return;const _=this.getNodesInfo();for(const C of _){const P=C.node;this.uploaded?this.updatePbrBuffer(P):eRe(P,g,!0)}for(const C of _)eie(C.node);this.uploaded=!0,this.needsUpload=!1}updatePbrBuffer(g){let _=!1;if(!g.meshes)return _;for(const C of g.meshes)C.pbrBuffer&&(C.pbrBuffer.updateData(C.featureArray),_=!0);return _}needsReEvaluation(g,_,C){const P=g.transform.projectionOptions,O=g.style.getBrightness(),B=this.brightness!==O;if(!this.uploaded||this.dirty||P.name!==this.projection.name||wK(C.paint.get("model-color").value,B)||wK(C.paint.get("model-color-mix-intensity").value,B)||wK(C.paint.get("model-roughness").value,B)||wK(C.paint.get("model-emissive-strength").value,B)||wK(C.paint.get("model-height-based-emissive-strength-multiplier").value,B)){this.projection=P,this.brightness=O;const W=this.getNodesInfo();for(const Y of W)Y.state=null;return!0}return!1}evaluateTransform(g,_){if(g.transform.zoom===this.zoom)return;this.zoom=g.transform.zoom;const C=this.getNodesInfo(),P=this.id.canonical;for(const O of C){const B=O.feature;O.evaluatedTranslation=_.paint.get("model-translation").evaluate(B,{},P),O.evaluatedScale=_.paint.get("model-scale").evaluate(B,{},P)}}evaluate(g,_){const C=this.getNodesInfo();for(const P of C){if(!P.node.meshes)continue;const O=P.feature,B=_&&_[O.id];if(ar(B,P.state))continue;P.state=structuredClone(B);const W=P.node.meshes&&P.node.meshes[0].featureData,Y=P.evaluatedColor[2],ae=P.evaluatedRMEA[2],pe=this.id.canonical;if(P.hasTranslucentParts=!1,W){for(let ve=0;ve=Ft)continue;const Qn=ORe[Mn],fn=Math.abs(Qn);fn>ms&&(hs=Qn,ms=fn,vn=Ln,Nn=Tn)}if(ms>.1){const Tn=1-(Ft+.5*Math.abs(vn*Nn))/De;let Ln=_._dem.get(as,bs)+hs*Tn;const Mn=_._dem.get(as+vn,bs+Nn),Qn=_._dem.get(as-vn,bs-Nn,!0);(Ln-Mn)*(Ln-Qn)>0&&(Ln=(Mn+Qn)/2),ORe[ys]=_._dem.set(as,bs,Ln),$L[ys]=Ft}}}}}W&&(_._demTile.needsDEMTextureUpload=!0,_._dem._timestamp=fd.now())}setFilter(g){this.filter=g?DE(g):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(g=>this.filter.filter(new Oi(this.id.overscaledZ,{worldview:this.worldview}),g.feature,this.id.canonical)):this.nodesInfo}destroy(){const g=this.getNodesInfo();for(const _ of g)eie(_.node),tRe(_.node)}isEmpty(){return!this.nodesInfo.length}updateReplacement(g,_){if(_.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=_.updateTime;const C=_.getReplacementRegionsForTile(g.toUnwrapped());for(const P of this.getNodesInfo()){const O=P.node.footprint;P.hiddenByReplacement=!!O&&!C.find(B=>B.footprint===O)}}getHeightAtTileCoord(g,_){const C=[],P=[0,0,0],O=y([]);for(const B of this.getNodesInfo()){const W=B.node.meshes[0],Y=W.transformedAabb;if(gY.max[0]||_>Y.max[1])continue;if(B.node.hidden===!0)return{height:1/0,maxHeight:B.feature.properties.height,hidden:!1,verticalScale:B.evaluatedScale[2]};v(O,B.node.globalMatrix),P[0]=g,P[1]=_,Qe(P,P,O);const ae=(P[0]-W.aabb.min[0])/(W.aabb.max[0]-W.aabb.min[0])*FL|0,pe=Math.min(63,(P[1]-W.aabb.min[1])/(W.aabb.max[1]-W.aabb.min[1])*FL|0)*FL+Math.min(63,ae),ve=W.heightmap[pe];if(!(ve<0&&B.node.footprint))return B.hiddenByReplacement?void 0:{height:ve,maxHeight:B.feature.properties.height,hidden:!1,verticalScale:B.evaluatedScale[2]};if(B.node.footprint.grid.query(new es(g,_),new es(g,_),C),C.length>0)return{height:void 0,maxHeight:B.feature.properties.height,hidden:B.hiddenByReplacement,verticalScale:B.evaluatedScale[2]}}}}function wK(k,g){return k instanceof Ih&&!k.isLightConstant&&g}function Nls(k,g,_,C,P,O,B,W){let Y=(61440&g|(61440&g)>>4)>>8,ae=(3840&g|(3840&g)>>4)>>4,pe=240&g|(240&g)>>4;_[3]>0&&(Y=Es(Y,255*_[0],_[3]),ae=Es(ae,255*_[1],_[3]),pe=Es(pe,255*_[2],_[3]));const ve=Y<<8|ae,_e=pe<<8|Math.floor(255*C[3]),Pe=function(Ft){const bs=mt(Ft,0,2);return Math.min(Math.round(.5*bs*255),255)}(C[2])<<8|15*C[0]<<4|15*C[1],De=mt(P[0],0,1),We=mt(P[1],0,1),Je=mt(P[2],0,1),rt=mt(P[3],0,1);let xt,ut,St,Rt;if(De!==We&&B!==O&&We!==De){const Ft=B-O;ut=1/(Ft*(We-De)),St=-(O+Ft*De)/(Ft*(We-De));const bs=mt(P[4],-1,1);Rt=Math.pow(10,bs),xt=255*Je<<8|255*rt}else xt=65535,ut=0,St=1,Rt=1;if(k.emplaceBack(ve,_e,Pe,xt,ut,St,Rt),W){const Ft=W.length;W.clear();for(let bs=0;bs>16&65535,pe=O?Y>>16&65535:65535&Y,ve=(15&pe)<8?15&pe:0,_e=k.evaluatedRMEA[ve],Pe=k.evaluatedColor[ve],De=k.emissionHeightBasedParams[ve];let We;if(W&&ve===2&&C.lights&&(We=new ez,We.resize(10*C.lights.length)),Nls(B.featureArray,ae,Pe,_e,De,B.aabb.min[2],B.aabb.max[2],We),We&&W){W=!1;const Je=C.meshes[C.lightMeshIndex];Je.featureArray=We,Je.featureArray._trim()}}B.featureArray._trim(),P++}}wr(wie,"Tiled3dModelBucket",{omit:["layers"]}),wr(Hlt,"Tiled3dModelFeature");const Sls=["id","tile","layer","source","sourceLayer","state"];class VL{constructor(g,_,C,P,O){this.type="Feature",this._vectorTileFeature=g,this._z=_,this._x=C,this._y=P,this.properties=g?g.properties:{},this.id=O}clone(){const g=new VL(this._vectorTileFeature,this._z,this._x,this._y,this.id);return this.state&&(g.state=Object.assign({},this.state)),this.layer&&(g.layer=Object.assign({},this.layer)),this.source&&(g.source=this.source),this.sourceLayer&&(g.sourceLayer=this.sourceLayer),g}get geometry(){return this._geometry===void 0&&this._vectorTileFeature&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._x,this._y,this._z).geometry),this._geometry}set geometry(g){this._geometry=g}toJSON(){const g={type:"Feature",state:void 0,geometry:this.geometry,properties:this.properties};for(const _ of Sls)this[_]!==void 0&&(g[_]=this[_]);return g}}class HL extends qm{constructor(g,_,C,P){super(),this.id=g,this.type="model",this.models=[],this._options=_,this._modelsInfo=new Map,this._abortController=null}cancelModelRequests(){this._abortController&&(this._abortController.abort(),this._abortController=null)}loadGLTFFromURI(g,_){return oot(this.map._requestManager.transformRequest(g,Mu.Model).url,_)}async loadModel(g,_,C){try{const P=await this.loadGLTFFromURI(_.uri,C);if(C.aborted)return;const O=this._modelsInfo.get(g);if(!O)return;const B=nRe(P),W=O.modelSpec,Y=new hot(g,W.uri,W.position,W.orientation,B);HL.applyModelSpecification(Y,W),Y.computeBoundsAndApplyParent(),this.models.push(Y),O.model=Y}catch(P){if(P instanceof Error&&P.name==="AbortError")return;const O=P instanceof Error?P.message:"Unknown error";this.fire(new Gp(new Error(`Could not load model ${g} from ${_.uri}: ${O}`)))}}async load(){this._abortController||(this._abortController=new AbortController);const g=this._abortController.signal,_=[];for(const C in this._options.models){const P=this._options.models[C],O=this._modelsInfo.get(C);if(O&&O.model){O.modelSpec=P;const B=O.model;B.position=P.position!=null?new Ts(P.position[0],P.position[1]):new Ts(0,0),B.orientation=P.orientation!=null?P.orientation:[0,0,0],HL.applyModelSpecification(B,P),B.computeBoundsAndApplyParent(),this.models.push(B)}else O?O.modelSpec=P:(this._modelsInfo.set(C,{modelSpec:P,model:null}),_.push(this.loadModel(C,P,g)))}_.length!==0?(await Promise.allSettled(_),g.aborted||this.fire(new ld("data",{dataType:"source",sourceDataType:"metadata"}))):this.loaded()&&this.fire(new ld("data",{dataType:"source",sourceDataType:"metadata"}))}static applyModelSpecification(g,_){_.nodeOverrides&&HL.convertNodeOverrides(g,_.nodeOverrides),_.materialOverrides&&HL.convertMaterialOverrides(g,_.materialOverrides),_.nodeOverrideNames&&(g.nodeOverrideNames=[..._.nodeOverrideNames]),_.materialOverrideNames&&(g.materialOverrideNames=[..._.materialOverrideNames]),_.featureProperties&&(g.featureProperties=_.featureProperties)}static convertNodeOverrides(g,_){if(Array.isArray(_)&&_.every(C=>typeof C=="string")){g.nodeOverrideNames=[];for(const C of _)g.nodeOverrideNames.push(C)}else Object.entries(_).forEach(([C,P])=>{const O={orientation:[0,0,0]};if(P.hasOwnProperty("orientation")){const B=P.orientation;B&&(O.orientation=B)}g.nodeOverrides.set(C,O)})}static convertMaterialOverrides(g,_){if(Array.isArray(_)&&_.every(C=>typeof C=="string")){g.materialOverrideNames=[];for(const C of _)g.materialOverrideNames.push(C)}else Object.entries(_).forEach(([C,P])=>{const O={color:new Zs(1,1,1),colorMix:0,emissionStrength:0,opacity:1},B=P["model-color"];B!==void 0&&(O.color.r=B[0],O.color.g=B[1],O.color.b=B[2]);const W=P["model-color-mix-intensity"];W!==void 0&&(O.colorMix=W);const Y=P["model-emissive-strength"];Y!==void 0&&(O.emissionStrength=Y);const ae=P["model-opacity"];ae!==void 0&&(O.opacity=ae),g.materialOverrides.set(C,O)})}onAdd(g){this.map=g,this.load()}hasTransition(){return!1}loaded(){if(this._modelsInfo.size===0)return!0;for(const g of this._modelsInfo.values())if(g.model==null)return!1;return!0}getModels(){return this.models}loadTile(g,_){}serialize(){return this._options}setProperty(g,_){return!1}reload(){this.cancelModelRequests();const g=At(this.id,this.scope);this.map.style.clearSource(g),this.models=[],this._modelsInfo.clear(),this.load()}onRemove(g){this.cancelModelRequests()}setModels(g){this.models=[];const _=new Map;for(const C in g){const P=g[C],O=this._modelsInfo.get(C);O&&O.modelSpec.uri===P.uri&&_.set(C,O)}if(this._modelsInfo.size!==_.size){this.cancelModelRequests();for(const[C,P]of _)P.model||_.delete(C)}this._modelsInfo=_,this._options.models=g,this.load()}}function FRe(k,g,_,C){const P=1<Y>=Rt.vertexArrayOffset&&YSt.polygon).flat());const Je=Pe?W:null,[rt,xt]=Git(O,C,ve,pe,ae,B,Je,_e,De,O.center.lat,k.tileID.canonical),ut=k.queryGeometry;return Hit(rt,xt,ut.isPointQuery()?ut.screenBounds:ut.screenGeometry)}},building:class extends Wl{constructor(k,g,_,C){super(k,{layout:vot||(vot=new Wc({visibility:new lr(Us.layout_building.visibility),"building-facade":new or(Us.layout_building["building-facade"]),"building-facade-floors":new or(Us.layout_building["building-facade-floors"]),"building-facade-unit-width":new or(Us.layout_building["building-facade-unit-width"]),"building-facade-window":new or(Us.layout_building["building-facade-window"]),"building-roof-shape":new or(Us.layout_building["building-roof-shape"]),"building-height":new or(Us.layout_building["building-height"]),"building-base":new or(Us.layout_building["building-base"]),"building-flood-light-wall-radius":new or(Us.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new or(Us.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new or(Us.layout_building["building-flip-roof-orientation"])})),paint:bot||(bot=new Wc({"building-opacity":new lr(Us.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new lr(Us.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new lr(Us.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new lr(Us.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new lr(Us.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new lr(Us.paint_building["building-vertical-scale"]),"building-cast-shadows":new lr(Us.paint_building["building-cast-shadows"]),"building-color":new or(Us.paint_building["building-color"]),"building-emissive-strength":new or(Us.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new lr(Us.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new lr(Us.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new lr(Us.paint_building["building-front-cutoff"]),"building-flood-light-color":new lr(Us.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new lr(Us.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new lr(Us.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new or({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new or({type:"string",default:"default","property-type":"data-driven"})}))},g,_,C),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(k){return new yot(k)}cutoffRange(){return this.paint.get("building-cutoff-fade-range")}hasShadowPass(){return this.paint.get("building-cast-shadows")}hasLightBeamPass(){return!0}canCastShadows(){return!0}is3D(k){return!0}queryRadius(k){return 0}queryIntersectsFeature(k,g,_,C,P,O,B,W,Y,ae){let pe=this.layout.get("building-height").evaluate(g,_);const ve=this.layout.get("building-base").evaluate(g,_),_e=k.tile.getBucket(this).getFootprint(g);if(_e){if(_e.hiddenFlags!==0)return!1;pe=_e.height}const[Pe,De]=Git(O,C,ve,pe,new es(0,0),B,null,[0,0],1,O.center.lat,k.tileID.canonical),We=k.queryGeometry;return Hit(Pe,De,We.isPointQuery()?We.screenBounds:We.screenGeometry)}},line:class extends Wl{constructor(k,g,_,C){const P=Tot();super(k,P,g,_,C),P.layout&&(this.layout=new _p(P.layout)),this.gradientVersion=0,this.hasElevatedBuckets=!1,this.hasNonElevatedBuckets=!1}_handleSpecialPaintPropertyUpdate(k){if(k==="line-gradient"){const g=this._transitionablePaint._values["line-gradient"].value.expression;this.stepInterpolant=g._styleExpression&&g._styleExpression.expression instanceof Rj,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}widthExpression(){return this._transitionablePaint._values["line-width"].value.expression}emissiveStrengthExpression(){return this._transitionablePaint._values["line-emissive-strength"].value.expression}recalculate(k,g){super.recalculate(k,g),this.paint._values["line-floorwidth"]=(()=>{if(lK)return lK;const _=Tot();return lK=new bos(_.paint.properties["line-width"].specification),lK.useIntegerZoom=!0,lK})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,k)}createBucket(k){return new sie(k)}getProgramIds(){const k=[this.paint.get("line-pattern").constantOr(1)?"linePattern":"line"];return this.paint.get("line-blend-mode")!=="default"&&k.push("lineBlendComposite"),k}getDefaultProgramParams(k,g,_){if(k==="lineBlendComposite")return{};const C=Aot(this);return{config:new Ke(this,{zoom:g,lut:_}),defines:C,overrideFog:!1}}queryRadius(k){const g=k,_=Mot(qE("line-width",this,g),qE("line-gap-width",this,g)),C=qE("line-offset",this,g);return _/2+Math.abs(C)+Sae(this.paint.get("line-translate"))}queryIntersectsFeature(k,g,_,C,P,O){if(k.queryGeometry.isAboveHorizon)return!1;const B=Eat(k.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),O.angle,k.pixelToTileUnitsFactor),W=k.pixelToTileUnitsFactor/2*Mot(this.paint.get("line-width").evaluate(g,_),this.paint.get("line-gap-width").evaluate(g,_)),Y=this.paint.get("line-offset").evaluate(g,_);return Y&&(C=function(ae,pe){const ve=[],_e=new es(0,0);for(let Pe=0;Pe=3){for(let De=0;De{this._triggered=!1,this._callback()})}trigger(){this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout(()=>{this._triggered=!1,this._callback()},0))}remove(){this._channel=void 0,this._callback=()=>{}}}class Glt{constructor(g){this._stringToNumber={},this._numberToString=[];for(let _=0;_=0&&_e[3]>=0&&ae.insert(Y,_e[0],_e[1],_e[2],_e[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new hl(new nie(this.rawTileData)).layers,this.sourceLayerCoder=new Glt(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"]),this.vtFeatures={};for(const g in this.vtLayers)this.vtFeatures[g]=[]}return this.vtLayers}query(g,_){const{tilespaceGeometry:C,transform:P,tileTransform:O,pixelPosMatrix:B,availableImages:W,worldview:Y}=_;this.loadVTLayers(),this.serializedLayersCache.clear();const ae=_.queryRadius?_.queryRadius:0,pe=C.bufferedTilespaceBounds,ve=this.grid.query(pe.min.x,pe.min.y,pe.max.x,pe.max.y,(We,Je,rt,xt)=>YS(C.bufferedTilespaceGeometry,We-ae,Je-ae,rt+ae,xt+ae));ve.sort(Tls);let _e=null;P.elevation&&ve.length>0&&(_e=bz.create(P.elevation,this.tileID));const Pe={};let De;for(let We=0;We(xt||(xt=Ha(ut,this.tileID.canonical,O)),St.queryIntersectsFeature(C,ut,Rt,xt,this.z,P,B,_e,Ft,_.scope)))}return Pe}loadMatchingFeature(g,_,C,P,O,B){const{featureIndex:W,bucketIndex:Y,sourceLayerIndex:ae,layoutVertexArrayOffset:pe}=_,ve=this.bucketLayerIDs[Y],_e=C.layers,Pe=Object.keys(_e);if(Pe.length&&!Qr(Pe,ve))return;const De=C.sourceCache,We=this.sourceLayerCoder.decode(ae),Je=this.vtLayers[We].feature(W),rt=this.getId(Je,We);for(let xt=0;xt`${W.key}: ${W.message}`).join(", ");return void qr(`Failed to create expression for promoteId: ${B}`)}this.promoteIdExpression=O.value}C=this.promoteIdExpression.evaluate({zoom:0},g)}else C=g.properties[P];typeof C=="boolean"&&(C=Number(C))}return C}}function Klt(k,g,_,C,P){return Xs(k,(O,B)=>{const W=g instanceof _p?g.get(B):null;return W&&W.evaluate?W.evaluate(_,C,void 0,P):W})}function Tls(k,g){return g-k}function Ylt(k,g){const _={};if(!g)return _;for(const C of k){const P=C.layerIds.map(O=>g.getLayer(O)).filter(Boolean);if(P.length!==0){C.layers=P,C.stateDependentLayerIds&&(C.stateDependentLayers=C.stateDependentLayerIds.map(O=>P.filter(B=>B.id===O)[0]));for(const O of P)_[O.fqid]=C}}return _}wr(Wlt,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const Kj=32,s5=33,YE=new Uint16Array(8184);for(let k=0;k<2046;k++){let g=k+2,_=0,C=0,P=0,O=0,B=0,W=0;for(1&g?P=O=B=Kj:_=C=W=Kj;(g>>=1)>1;){const ae=_+P>>1,pe=C+O>>1;1&g?(P=_,O=C,_=B,C=W):(_=P,C=O,P=B,O=W),B=ae,W=pe}const Y=4*k;YE[Y+0]=_,YE[Y+1]=C,YE[Y+2]=P,YE[Y+3]=O}const n5=new Uint16Array(2178),ZE=new Uint8Array(1089),jie=new Uint16Array(1089);function Zlt(k){return k===0?-.03125:k===32?.03125:0}const Xlt={Other:0,Symbol:1,FillExtrusion:2},Qlt={type:2,extent:dr,loadGeometry:()=>[[new es(0,0),new es(8193,0),new es(8193,8193),new es(0,8193),new es(0,0)]]};class Mls{constructor(){this.tasks={},this.taskQueue=[],Ht(["process"],this),this.invoker=new Els(this.process),this.nextId=0}add(g,_){const C=this.nextId++,P=function({type:O,renderSourceType:B,zoom:W}){W=W||0;const Y=B===Xlt.Symbol;return O==="message"?0:O!=="maybePrepare"||Y?O!=="parseTile"||Y?O==="parseTile"&&Y?300-W:O==="maybePrepare"&&Y?400-W:500:200-W:100-W}(_);if(P===0){try{g()}finally{}return null}return this.tasks[C]={fn:g,metadata:_,priority:P,id:C},this.taskQueue.push(C),this.invoker.trigger(),{cancel:()=>{delete this.tasks[C]}}}process(){try{if(this.taskQueue=this.taskQueue.filter(C=>!!this.tasks[C]),!this.taskQueue.length)return;const g=this.pick();if(g===null)return;const _=this.tasks[g];if(delete this.tasks[g],this.taskQueue.length&&this.invoker.trigger(),!_)return;_.fn()}finally{}}pick(){let g=null,_=1/0;for(let P=0;P>16&255)/255,(k>>8&255)/255,(255&k)/255,1)}function $ls(k,g,_){k===1?(g.rgb_color=Sie(_.readVarint()),g.paint="rgb_color"):k===2?(g.linear_gradient_idx=_.readVarint(),g.paint="linear_gradient_idx"):k===3?(g.radial_gradient_idx=_.readVarint(),g.paint="radial_gradient_idx"):k===5?_.readPackedFloat(g.dasharray):k===6?g.dashoffset=_.readFloat():k===7?g.miterlimit=_.readFloat():k===8?g.opacity=_.readVarint():k===9?g.width=_.readFloat():k===10?g.linecap=_.readVarint():k===11&&(g.linejoin=_.readVarint())}function Vls(k,g,_){k===1?g.transform=kie(_,_.readVarint()+_.pos):k===2?g.spread_method=_.readVarint():k===3?g.stops.push(tct(_,_.readVarint()+_.pos)):k===4?g.x1=_.readFloat():k===5?g.y1=_.readFloat():k===6?g.x2=_.readFloat():k===7&&(g.y2=_.readFloat())}function tct(k,g){return k.readFields(Hls,{offset:0,opacity:255,rgb_color:zRe},g)}function Hls(k,g,_){k===1?g.offset=_.readFloat():k===2?g.opacity=_.readVarint():k===3&&(g.rgb_color=Sie(_.readVarint()))}function Gls(k,g,_){k===1?g.transform=kie(_,_.readVarint()+_.pos):k===2?g.spread_method=_.readVarint():k===3?g.stops.push(tct(_,_.readVarint()+_.pos)):k===4?g.cx=_.readFloat():k===5?g.cy=_.readFloat():k===6?g.r=_.readFloat():k===7?g.fx=_.readFloat():k===8?g.fy=_.readFloat():k===9&&(g.fr=_.readFloat())}function Wls(k,g,_){k===1?g.transform=kie(_,_.readVarint()+_.pos):k===2?g.clip_path_idx=_.readVarint():k===3&&g.children.push(Nie(_,_.readVarint()+_.pos))}function Kls(k,g,_){k===1?g.left=g.top=_.readFloat():k===2?g.width=g.height=_.readFloat():k===3?g.top=_.readFloat():k===4?g.height=_.readFloat():k===5?g.mask_type=_.readVarint():k===6?g.mask_idx=_.readVarint():k===7&&g.children.push(Nie(_,_.readVarint()+_.pos))}class Yls{static calculate(g={},_=[]){const C=new Map,P=new Map;if(Object.keys(g).length===0)return C;_.forEach(O=>{P.set(O.name,O.rgb_color||new Zs(0,0,0))});for(const[O,B]of Object.entries(g))P.has(O)?C.set(P.get(O).toString(),B):console.warn(`Ignoring unknown image variable "${O}"`);return C}}function _z(k,g=255,_){const C=g/255,P=k.toString(),O=_.has(P)?_.get(P).clone():k.clone();return O.a*=C,O.toString()}function jK(k,g){if(!Dc()){const _=document.createElement("canvas");return _.width=k,_.height=g,_}return new OffscreenCanvas(k,g)}let BRe,NK=null;function URe(k,g,_,C,P){for(const O of C.children)sct(k,g,_,O,P)}function sct(k,g,_,C,P){C.group?(k.save(),function(O,B,W,Y,ae){const pe=Y.mask_idx!=null?W.masks[Y.mask_idx]:null,ve=Y.clip_path_idx!=null?W.clip_paths[Y.clip_path_idx]:null;if(Y.transform&&(B=wz(Y.transform).preMultiplySelf(B)),!function(De,We,Je){return De.opacity!==255||We||Je}(Y,ve!=null,pe!=null))return void URe(O,B,W,Y,ae);const _e=jK(O.canvas.width,O.canvas.height),Pe=_e.getContext("2d");URe(Pe,B,W,Y,ae),ve&&cct(Pe,B,W,ve),pe&&dct(Pe,B,W,pe,ae),O.globalAlpha=Y.opacity/255,O.drawImage(_e,0,0)}(k,g,_,C.group,P),k.restore()):C.path&&(k.save(),function(O,B,W,Y,ae){O.setTransform(B),Y.paint_order===1?(nct(O,W,Y,ae),act(O,W,Y,ae)):(act(O,W,Y,ae),nct(O,W,Y,ae))}(k,g,_,C.path,P),k.restore())}function nct(k,g,_,C){const P=_.fill;if(!P)return;const O=P.opacity/255;switch(k.save(),k.beginPath(),uct(_,k),P.paint){case"rgb_color":k.fillStyle=_z(P.rgb_color,P.opacity,C);break;case"linear_gradient_idx":{const B=g.linear_gradients[P.linear_gradient_idx];B.transform&&k.setTransform(wz(B.transform).preMultiplySelf(k.getTransform())),k.fillStyle=ict(k,B,O,C);break}case"radial_gradient_idx":{const B=g.radial_gradients[P.radial_gradient_idx];B.transform&&k.setTransform(wz(B.transform).preMultiplySelf(k.getTransform())),k.fillStyle=oct(k,B,O,C)}}k.fill(rct(_)),k.restore()}function rct(k){return k.rule===1?"nonzero":k.rule===2?"evenodd":void 0}function act(k,g,_,C){const P=_.stroke;if(!P)return;const O=hct(_);k.lineWidth=P.width,k.miterLimit=P.miterlimit,k.setLineDash(P.dasharray),k.lineDashOffset=P.dashoffset;const B=P.opacity/255;switch(P.paint){case"rgb_color":k.strokeStyle=_z(P.rgb_color,P.opacity,C);break;case"linear_gradient_idx":k.strokeStyle=ict(k,g.linear_gradients[P.linear_gradient_idx],B,C,!0);break;case"radial_gradient_idx":k.strokeStyle=oct(k,g.radial_gradients[P.radial_gradient_idx],B,C,!0)}switch(P.linejoin){case 2:case 1:k.lineJoin="miter";break;case 3:k.lineJoin="round";break;case 4:k.lineJoin="bevel"}switch(P.linecap){case 1:k.lineCap="butt";break;case 2:k.lineCap="round";break;case 3:k.lineCap="square"}k.stroke(O)}function ict(k,g,_,C,P=!1){if(g.stops.length===1){const _e=g.stops[0];return _z(_e.rgb_color,_e.opacity*_,C)}const{x1:O,y1:B,x2:W,y2:Y}=g;let ae=new DOMPoint(O,B),pe=new DOMPoint(W,Y);if(P){const _e=wz(g.transform);ae=_e.transformPoint(ae),pe=_e.transformPoint(pe)}const ve=k.createLinearGradient(ae.x,ae.y,pe.x,pe.y);for(const _e of g.stops)ve.addColorStop(_e.offset,_z(_e.rgb_color,_e.opacity*_,C));return ve}function oct(k,g,_,C,P=!1){if(g.stops.length===1){const rt=g.stops[0];return _z(rt.rgb_color,rt.opacity*_,C)}const O=wz(g.transform),{fx:B,fy:W,fr:Y,cx:ae,cy:pe,r:ve}=g;let _e=new DOMPoint(B,W),Pe=new DOMPoint(ae,pe),De=Y,We=ve;if(P){_e=O.transformPoint(_e),Pe=O.transformPoint(Pe);const rt=(O.a+O.d)/2;De=Y*rt,We=g.r*rt}const Je=k.createRadialGradient(_e.x,_e.y,De,Pe.x,Pe.y,We);for(const rt of g.stops)Je.addColorStop(rt.offset,_z(rt.rgb_color,rt.opacity*_,C));return Je}function lct(k,g,_,C){const P=C.transform?wz(C.transform).preMultiplySelf(g):g,O=jK(k.canvas.width,k.canvas.height),B=O.getContext("2d");for(const Y of C.children)if(Y.group)lct(B,P,_,Y.group);else if(Y.path){const ae=Y.path,pe=new Path2D;pe.addPath(hct(ae),P),B.fill(pe,rct(ae))}const W=C.clip_path_idx!=null?_.clip_paths[C.clip_path_idx]:null;W&&cct(B,P,_,W),k.globalCompositeOperation="source-over",k.drawImage(O,0,0)}function cct(k,g,_,C){const P=jK(k.canvas.width,k.canvas.height);lct(P.getContext("2d"),g,_,C),k.globalCompositeOperation="destination-in",k.drawImage(P,0,0)}function dct(k,g,_,C,P){if(C.children.length===0)return;const O=C.mask_idx!=null?_.masks[C.mask_idx]:null;O&&dct(k,g,_,O,P);const B=k.canvas.width,W=k.canvas.height,Y=jK(B,W),ae=Y.getContext("2d"),pe=C.width,ve=C.height,_e=C.left,Pe=C.top,De=new Path2D,We=new Path2D;We.rect(_e,Pe,pe,ve),De.addPath(We,g),ae.clip(De);for(const xt of C.children)sct(ae,g,_,xt,P);const Je=ae.getImageData(0,0,B,W),rt=Je.data;if(C.mask_type===1)for(let xt=0;xtg[B])return null}else{const W=1/C[B];let Y=(k[B]-_[B])*W,ae=(g[B]-_[B])*W;if(Y>ae){const pe=Y;Y=ae,ae=pe}if(Y>P&&(P=Y),aeO)return null}return P}function fct(k,g,_,C,P,O,B,W,Y,ae,pe){const ve=C-k,_e=P-g,Pe=O-_,De=B-k,We=W-g,Je=Y-_,rt=pe[1]*Je-pe[2]*We,xt=pe[2]*De-pe[0]*Je,ut=pe[0]*We-pe[1]*De,St=ve*rt+_e*xt+Pe*ut;if(Math.abs(St)<1e-15)return null;const Rt=1/St,Ft=ae[0]-k,bs=ae[1]-g,as=ae[2]-_,ys=(Ft*rt+bs*xt+as*ut)*Rt;if(ys<0||ys>1)return null;const hs=bs*Pe-as*_e,ms=as*ve-Ft*Pe,vn=Ft*_e-bs*ve,Nn=(pe[0]*hs+pe[1]*ms+pe[2]*vn)*Rt;return Nn<0||ys+Nn>1?null:(De*hs+We*ms+Je*vn)*Rt}function gct(k,g,_){return(k-g)/(_-g)}function xct(k,g,_,C,P,O,B,W,Y){const ae=1<<_,pe=O-C,ve=B-P,_e=(k+1)/ae*pe+C,Pe=(g+0)/ae*ve+P,De=(g+1)/ae*ve+P;W[0]=(k+0)/ae*pe+C,W[1]=Pe,Y[0]=_e,Y[1]=De}class yct{constructor(g){if(this.maximums=[],this.minimums=[],this.leaves=[],this.childOffsets=[],this.nodeCount=0,this.dem=g,this._siblingOffset=[[0,0],[1,0],[0,1],[1,1]],!this.dem)return;const _=function(O){const B=Math.ceil(Math.log2(O.dim/8)),W=[];let Y=Math.ceil(Math.pow(2,B));const ae=1/Y,pe=(Pe,De,We,Je,rt)=>{const xt=Je?1:0,ut=(Pe+1)*We-xt,St=De*We,Rt=(De+1)*We-xt;rt[0]=Pe*We,rt[1]=St,rt[2]=ut,rt[3]=Rt};let ve=new mct(Y);const _e=[];for(let Pe=0;Pe=1;Y/=2){const Pe=W[W.length-1];ve=new mct(Y);for(let De=0;De0;){const{idx:De,t:We,nodex:Je,nodey:rt,depth:xt}=Pe.pop();if(this.leaves[De]){xct(Je,rt,xt,g,_,C,P,ve,_e);const St=1<=Mn[2])return We}continue}let ut=0;for(let St=0;St=ae[pe[as]]&&(pe.splice(as,0,St),bs=!0);bs||(pe[ut]=St),ut++}}for(let St=0;St=this.dim+1||_<-1||_>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(_+1)*this.stride+(g+1)}static pack(g,_){const C=[0,0,0,0],P=Aie.getUnpackVector(_);let O=Math.floor((g+P[3])/P[2]);return C[2]=O%256,O=Math.floor(O/256),C[1]=O%256,O=Math.floor(O/256),C[0]=O,C}getPixels(){return new eit({width:this.stride,height:this.stride},this.pixels)}backfillBorder(g,_,C){if(this.dim!==g.dim)throw new Error("dem dimension mismatch");let P=_*this.dim,O=_*this.dim+this.dim,B=C*this.dim,W=C*this.dim+this.dim;switch(_){case-1:P=O-1;break;case 1:O=P+1}switch(C){case-1:B=W-1;break;case 1:W=B+1}const Y=-_*this.dim,ae=-C*this.dim;for(let pe=B;pe=1;C--){const P=C===1?1:0,O=C===2?1:0;for(let B=0;B>>1^-(1&k[g]);return k}function ccs(k,g){switch(g){case"uint32":return k;case"uint16":for(let _=0;_>4|(61440&C)>>8|(240&P)<<4|61440&P,k[_+1]=15&C|(3840&C)>>4|(15&P)<<8|(3840&P)<<4}return k;case"uint8":for(let _=0;_>6|(192&P)>>4|(192&O)>>2|192&B,k[_+1]=(48&C)>>4|(48&P)>>2|48&O|(48&B)<<2,k[_+2]=(12&C)>>2|12&P|(12&O)<<2|(12&B)<<4,k[_+3]=3&C|(3&P)<<2|(3&O)<<4|(3&B)<<6}return k;default:throw new Error(`Invalid pixel format, "${g}"`)}}wr(Aie,"DEMData"),wr(yct,"DemMinMaxQuadTree",{omit:["dem"]});var ew=Uint8Array,kK=Uint16Array,dcs=Int32Array,bct=new ew([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]),_ct=new ew([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]),ucs=new ew([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),wct=function(k,g){for(var _=new kK(31),C=0;C<31;++C)_[C]=g+=1<>1|(21845&Wm)<<1;kct[Wm]=((65280&(jz=(61680&(jz=(52428&jz)>>2|(13107&jz)<<2))>>4|(3855&jz)<<4))>>8|(255&jz)<<8)>>1}var SK=function(k,g,_){for(var C=k.length,P=0,O=new kK(g);P>Y]=ae;return B},CK=new ew(288);for(Wm=0;Wm<144;++Wm)CK[Wm]=8;for(Wm=144;Wm<256;++Wm)CK[Wm]=9;for(Wm=256;Wm<280;++Wm)CK[Wm]=7;for(Wm=280;Wm<288;++Wm)CK[Wm]=8;var Sct=new ew(32);for(Wm=0;Wm<32;++Wm)Sct[Wm]=5;var pcs=SK(CK,9),fcs=SK(Sct,5),$Re=function(k){for(var g=k[0],_=1;_g&&(g=k[_]);return g},YN=function(k,g,_){var C=g/8|0;return(k[C]|k[C+1]<<8)>>(7&g)&_},VRe=function(k,g){var _=g/8|0;return(k[_]|k[_+1]<<8|k[_+2]<<16)>>(7&g)},gcs=function(k){return(k+7)/8|0},xcs=["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"],ZN=function(k,g,_){var C=new Error(g||xcs[k]);if(C.code=k,Error.captureStackTrace&&Error.captureStackTrace(C,ZN),!_)throw C;return C},ycs=new ew(0),vcs=typeof TextDecoder<"u"&&new TextDecoder;try{vcs.decode(ycs,{stream:!0})}catch{}const bcs={gzip_data:"gzip"};class Yj extends Error{constructor(g){super(g),this.name="MRTError"}}const _cs={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},Cct={uint32:1,uint16:2,uint8:4},wcs={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let HRe;class Eie{constructor(g=5){this.x=NaN,this.y=NaN,this.z=NaN,this.layers={},this._cacheSize=g}getLayer(g){const _=this.layers[g];if(!_)throw new Yj(`Layer '${g}' not found`);return _}getHeaderLength(g){const _=new Uint8Array(g),C=new DataView(g);if(_[0]!==13)throw new Yj("File is not a valid MRT.");return C.getUint32(1,!0)}parseHeader(g){const _=new Uint8Array(g),C=this.getHeaderLength(g);if(_.length= ${C} but got buffer of length ${_.length}`);const P=new HRe(_.subarray(0,C)).readFields(Jls,{headerLength:0,x:0,y:0,z:0,layers:[]},void 0);if(!isNaN(this.x)&&(this.x!==P.x||this.y!==P.y||this.z!==P.z))throw new Yj(`Invalid attempt to parse header ${P.z}/${P.x}/${P.y} for tile ${this.z}/${this.x}/${this.y}`);this.x=P.x,this.y=P.y,this.z=P.z;for(const O of P.layers)this.layers[O.name]=new Act(O,{cacheSize:this._cacheSize});return this}createDecodingTask(g){const _=[],C=this.getLayer(g.layerName);for(let P of g.blockIndices){const O=C.dataIndex[P],B=O.firstByte-g.firstByte,W=O.lastByte-g.firstByte;if(C._blocksInProgress.has(P))continue;const Y={layerName:C.name,firstByte:B,lastByte:W,pixelFormat:C.pixelFormat,blockIndex:P,blockShape:[O.bands.length].concat(C.bandShape),buffer:C.buffer,codec:O.codec.codec,filters:O.filters.map(ae=>ae.filter)};C._blocksInProgress.add(P),_.push(Y)}return new Ect(_,()=>{_.forEach(P=>C._blocksInProgress.delete(P.blockIndex))},(P,O)=>{if(_.forEach(B=>C._blocksInProgress.delete(B.blockIndex)),P)throw P;O.forEach(B=>{this.getLayer(B.layerName).processDecodedData(B)})})}}class Act{constructor({version:g,name:_,units:C,tileSize:P,pixelFormat:O,buffer:B,dataIndex:W},Y){if(this.version=g,this.version!==1)throw new Yj(`Cannot parse raster layer encoded with MRT version ${g}`);this.name=_,this.units=C,this.tileSize=P,this.buffer=B,this.pixelFormat=_cs[O],this.dataIndex=W,this.bandShape=[P+2*B,P+2*B,Cct[this.pixelFormat]],this._decodedBlocks=new Cie(Y?Y.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return Cct[this.pixelFormat]}get cacheSize(){return this._decodedBlocks.capacity}getBandList(){return this.dataIndex.map(({bands:g})=>g).flat()}processDecodedData(g){const _=g.blockIndex.toString();this._decodedBlocks.get(_)||this._decodedBlocks.put(_,g.data)}getBlockForBand(g){let _=0;switch(typeof g){case"string":for(const[C,P]of this.dataIndex.entries()){for(const[O,B]of P.bands.entries())if(B===g)return{bandIndex:_+O,blockIndex:C,blockBandIndex:O};_+=P.bands.length}break;case"number":for(const[C,P]of this.dataIndex.entries()){if(g>=_&&g<_+P.bands.length)return{bandIndex:g,blockIndex:C,blockBandIndex:g-_};_+=P.bands.length}break;default:throw new Yj(`Invalid band \`${JSON.stringify(g)}\`. Expected string or integer.`)}return{blockIndex:-1,blockBandIndex:-1}}getDataRange(g){let _=1/0,C=-1/0;const P=[],O=new Set;for(const B of g){const{blockIndex:W}=this.getBlockForBand(B);if(W<0)throw new Yj(`Invalid band: ${JSON.stringify(B)}`);const Y=this.dataIndex[W];P.includes(W)||P.push(W),O.add(W),_=Math.min(_,Y.firstByte),C=Math.max(C,Y.lastByte)}if(O.size>this.cacheSize)throw new Yj(`Number of blocks to decode (${O.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:_,lastByte:C,blockIndices:P}}hasBand(g){const{blockIndex:_}=this.getBlockForBand(g);return _>=0}hasDataForBand(g){const{blockIndex:_}=this.getBlockForBand(g);return _>=0&&!!this._decodedBlocks.get(_.toString())}getBandView(g){const{blockIndex:_,blockBandIndex:C}=this.getBlockForBand(g);if(_<0)throw new Yj(`Band not found: ${JSON.stringify(g)}`);const P=this._decodedBlocks.get(_.toString());if(!P)throw new Yj(`Data for band ${JSON.stringify(g)} of layer "${this.name}" not decoded.`);const O=this.dataIndex[_],B=this.bandShape.reduce((ae,pe)=>ae*pe,1),W=C*B,Y=P.subarray(W,W+B);return{data:Y,bytes:new Uint8Array(Y.buffer).subarray(Y.byteOffset,Y.byteOffset+Y.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:O.offset,scale:O.scale}}}Eie.setPbf=function(k){HRe=k};class Ect{constructor(g,_,C){this.tasks=g,this._onCancel=_,this._onComplete=C,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(g,_){this._finalized||(this._onComplete(g,_),this._finalized=!0)}}Eie.performDecoding=function(k,g){const _=new Uint8Array(k);return Promise.all(g.tasks.map(C=>{const{layerName:P,firstByte:O,lastByte:B,pixelFormat:W,blockShape:Y,blockIndex:ae,filters:pe,codec:ve}=C,_e=_.subarray(O,B+1),Pe=new Uint32Array(Y[0]*Y[1]*Y[2]);let De;if(ve!=="gzip_data")throw new Yj(`Unhandled codec: ${ve}`);return De=function(We,Je){if(!globalThis.DecompressionStream&&Je==="gzip_data")return Promise.resolve((Rt=function(as){as[0]==31&&as[1]==139&&as[2]==8||ZN(6,"invalid gzip data");var ys=as[3],hs=10;4&ys&&(hs+=2+(as[10]|as[11]<<8));for(var ms=(ys>>3&1)+(ys>>4&1);ms>0;ms-=!as[hs++]);return hs+(2&ys)}(rt=We),Rt+8>rt.length&&ZN(6,"invalid gzip data"),function(as,ys,hs,ms){var vn=as.length;if(!vn||ys.f&&!ys.l)return hs||new ew(0);var Nn=!hs,Tn=Nn||ys.i!=2,Ln=ys.i;Nn&&(hs=new ew(3*vn));var Mn=function(pu){var Ox=hs.length;if(pu>Ox){var nf=new ew(Math.max(2*Ox,pu));nf.set(hs),hs=nf}},Qn=ys.f||0,fn=ys.p||0,Pn=ys.b||0,Dn=ys.l,tr=ys.d,mr=ys.m,ta=ys.n,Cr=8*vn;do{if(!Dn){Qn=YN(as,fn,1);var Nr=YN(as,fn+1,3);if(fn+=3,!Nr){var pr=as[(jl=gcs(fn)+4)-4]|as[jl-3]<<8,Kr=jl+pr;if(Kr>vn){Ln&&ZN(0);break}Tn&&Mn(Pn+pr),hs.set(as.subarray(jl,Kr),Pn),ys.b=Pn+=pr,ys.p=fn=8*Kr,ys.f=Qn;continue}if(Nr==1)Dn=pcs,tr=fcs,mr=9,ta=5;else if(Nr==2){var da=YN(as,fn,31)+257,$a=YN(as,fn+10,15)+4,ja=da+YN(as,fn+5,31)+1;fn+=14;for(var Pi=new ew(ja),zo=new ew(19),Li=0;Li<$a;++Li)zo[ucs[Li]]=YN(as,fn+3*Li,7);fn+=3*$a;var $o=$Re(zo),to=(1<<$o)-1,mu=SK(zo,$o);for(Li=0;Li>4)<16)Pi[Li++]=jl;else{var Pc=0,ru=0;for(jl==16?(ru=3+YN(as,fn,3),fn+=2,Pc=Pi[Li-1]):jl==17?(ru=3+YN(as,fn,7),fn+=3):jl==18&&(ru=11+YN(as,fn,127),fn+=7);ru--;)Pi[Li++]=Pc}}var Np=Pi.subarray(0,da),au=Pi.subarray(da);mr=$Re(Np),ta=$Re(au),Dn=SK(Np,mr),tr=SK(au,ta)}else ZN(1);if(fn>Cr){Ln&&ZN(0);break}}Tn&&Mn(Pn+131072);for(var Du=(1<>4;if((fn+=15&Pc)>Cr){Ln&&ZN(0);break}if(Pc||ZN(2),Ng<256)hs[Pn++]=Ng;else{if(Ng==256){Ou=fn,Dn=null;break}var kp=Ng-254;Ng>264&&(kp=YN(as,fn,(1<<(rh=bct[Li=Ng-257]))-1)+Nct[Li],fn+=rh);var lo=tr[VRe(as,fn)&Rh],I0=lo>>4;if(lo||ZN(3),fn+=15&lo,au=mcs[I0],I0>3){var rh=_ct[I0];au+=VRe(as,fn)&(1<Cr){Ln&&ZN(0);break}Tn&&Mn(Pn+131072);var sf=Pn+kp;if(Pnpu.length)&&(nf=pu.length),new ew(pu.subarray(0,nf))}(hs,0,Pn):hs.subarray(0,Pn)}(rt.subarray(Rt,-8),{i:2},new ew(((ut=rt)[(St=ut.length)-4]|ut[St-3]<<8|ut[St-2]<<16|ut[St-1]<<24)>>>0),xt)));var rt,xt,ut,St,Rt;const Ft=bcs[Je];if(!Ft)throw new Error(`Unhandled codec: ${Je}`);const bs=new globalThis.DecompressionStream(Ft);return new Response(new Blob([We]).stream().pipeThrough(bs)).arrayBuffer().then(as=>new Uint8Array(as))}(_e,ve).then(We=>(function(Je,rt){Je.readFields(acs,rt)}(new HRe(We),Pe),new wcs[W](Pe.buffer))),De.then(We=>{for(let Je=pe.length-1;Je>=0;Je--)switch(pe[Je]){case"delta_filter":ocs(We,Y);break;case"zigzag_filter":lcs(We);break;case"bitshuffle_filter":ccs(We,W);break;default:throw new Yj(`Unhandled filter "${pe[Je]}"`)}return{layerName:P,blockIndex:ae,data:We}}).catch(We=>{throw We})}))},wr(Ect,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),wr(Eie,"MapboxRasterTile"),wr(Act,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const Tct=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];class GRe{static from(g){if(!(g instanceof ArrayBuffer))throw new Error("Data must be an instance of ArrayBuffer.");const[_,C]=new Uint8Array(g,0,2);if(_!==219)throw new Error("Data does not appear to be in a KDBush format.");const P=C>>4;if(P!==1)throw new Error(`Got v${P} data when expected v1.`);const O=Tct[15&C];if(!O)throw new Error("Unrecognized array type.");const[B]=new Uint16Array(g,2,1),[W]=new Uint32Array(g,4,1);return new GRe(W,B,O,g)}constructor(g,_=64,C=Float64Array,P){if(isNaN(g)||g<0)throw new Error(`Unpexpected numItems value: ${g}.`);this.numItems=+g,this.nodeSize=Math.min(Math.max(+_,2),65535),this.ArrayType=C,this.IndexArrayType=g<65536?Uint16Array:Uint32Array;const O=Tct.indexOf(this.ArrayType),B=2*g*this.ArrayType.BYTES_PER_ELEMENT,W=g*this.IndexArrayType.BYTES_PER_ELEMENT,Y=(8-W%8)%8;if(O<0)throw new Error(`Unexpected typed array class: ${C}.`);P&&P instanceof ArrayBuffer?(this.data=P,this.ids=new this.IndexArrayType(this.data,8,g),this.coords=new this.ArrayType(this.data,8+W+Y,2*g),this._pos=2*g,this._finished=!0):(this.data=new ArrayBuffer(8+B+W+Y),this.ids=new this.IndexArrayType(this.data,8,g),this.coords=new this.ArrayType(this.data,8+W+Y,2*g),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+O]),new Uint16Array(this.data,2,1)[0]=_,new Uint32Array(this.data,4,1)[0]=g)}add(g,_){const C=this._pos>>1;return this.ids[C]=C,this.coords[this._pos++]=g,this.coords[this._pos++]=_,C}finish(){const g=this._pos>>1;if(g!==this.numItems)throw new Error(`Added ${g} items when expected ${this.numItems}.`);return WRe(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(g,_,C,P){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:O,coords:B,nodeSize:W}=this,Y=[0,O.length-1,0],ae=[];for(;Y.length;){const pe=Y.pop()||0,ve=Y.pop()||0,_e=Y.pop()||0;if(ve-_e<=W){for(let Je=_e;Je<=ve;Je++){const rt=B[2*Je],xt=B[2*Je+1];rt>=g&&rt<=C&&xt>=_&&xt<=P&&ae.push(O[Je])}continue}const Pe=_e+ve>>1,De=B[2*Pe],We=B[2*Pe+1];De>=g&&De<=C&&We>=_&&We<=P&&ae.push(O[Pe]),(pe===0?g<=De:_<=We)&&(Y.push(_e),Y.push(Pe-1),Y.push(1-pe)),(pe===0?C>=De:P>=We)&&(Y.push(Pe+1),Y.push(ve),Y.push(1-pe))}return ae}within(g,_,C){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:P,coords:O,nodeSize:B}=this,W=[0,P.length-1,0],Y=[],ae=C*C;for(;W.length;){const pe=W.pop()||0,ve=W.pop()||0,_e=W.pop()||0;if(ve-_e<=B){for(let Je=_e;Je<=ve;Je++)Pct(O[2*Je],O[2*Je+1],g,_)<=ae&&Y.push(P[Je]);continue}const Pe=_e+ve>>1,De=O[2*Pe],We=O[2*Pe+1];Pct(De,We,g,_)<=ae&&Y.push(P[Pe]),(pe===0?g-C<=De:_-C<=We)&&(W.push(_e),W.push(Pe-1),W.push(1-pe)),(pe===0?g+C>=De:_+C>=We)&&(W.push(Pe+1),W.push(ve),W.push(1-pe))}return Y}}function WRe(k,g,_,C,P,O){if(P-C<=_)return;const B=C+P>>1;Mct(k,g,B,C,P,O),WRe(k,g,_,C,B-1,1-O),WRe(k,g,_,B+1,P,1-O)}function Mct(k,g,_,C,P,O){for(;P>C;){if(P-C>600){const ae=P-C+1,pe=_-C+1,ve=Math.log(ae),_e=.5*Math.exp(2*ve/3),Pe=.5*Math.sqrt(ve*_e*(ae-_e)/ae)*(pe-ae/2<0?-1:1);Mct(k,g,_,Math.max(C,Math.floor(_-pe*_e/ae+Pe)),Math.min(P,Math.floor(_+(ae-pe)*_e/ae+Pe)),O)}const B=g[2*_+O];let W=C,Y=P;for(AK(k,g,C,_),g[2*P+O]>B&&AK(k,g,C,P);WB;)Y--}g[2*C+O]===B?AK(k,g,C,Y):(Y++,AK(k,g,Y,P)),Y<=_&&(C=Y+1),_<=Y&&(P=Y-1)}}function AK(k,g,_,C){KRe(k,_,C),KRe(g,2*_,2*C),KRe(g,2*_+1,2*C+1)}function KRe(k,g,_){const C=k[g];k[g]=k[_],k[_]=C}function Pct(k,g,_,C){const P=k-_,O=g-C;return P*P+O*O}o.$=bg,o.A=class{constructor(k,g,_){this.target=k,this.parent=g,this.mapId=_,this.callbacks={},this.cancelCallbacks={},Ht(["receive"],this),this.target.addEventListener("message",this.receive,!1),this.scheduler=new Mls}send(k,g,_,C,P=!1,O){const B=Math.round(1e18*Math.random()).toString(36).substring(0,10);_&&(_.metadata=O,this.callbacks[B]=_);const W=new Set;return this.target.postMessage({id:B,type:k,hasCallback:!!_,targetMapId:C,mustQueue:P,sourceMapId:this.mapId,data:cd(g,W)},W),{cancel:()=>{_&&delete this.callbacks[B],this.target.postMessage({id:B,type:"",targetMapId:C,sourceMapId:this.mapId})}}}receive(k){const g=k.data;if(!g)return;const _=g.id;if(_&&(!g.targetMapId||this.mapId===g.targetMapId))if(g.type===""){const C=this.cancelCallbacks[_];delete this.cancelCallbacks[_],C&&C.cancel()}else if(g.mustQueue||Fa(self)){const C=this.callbacks[_],P=this.scheduler.add(()=>this.processTask(_,g),C&&C.metadata||{type:"message"});P&&(this.cancelCallbacks[_]=P)}else this.processTask(_,g)}processTask(k,g){if(delete this.cancelCallbacks[k],g.type===""){const _=this.callbacks[k];delete this.callbacks[k],_&&(g.error?_(Oc(g.error)):_(null,Oc(g.data)))}else{const _=new Set,C=g.hasCallback?(O,B)=>{this.target.postMessage({id:k,type:"",sourceMapId:this.mapId,error:O?cd(O):null,data:cd(B,_)},_)}:()=>{},P=Oc(g.data);if(this.parent[g.type])this.parent[g.type](g.sourceMapId,P,C);else if(this.parent.getWorkerSource){const O=g.type.split("."),{source:B,scope:W}=P;this.parent.getWorkerSource(g.sourceMapId,{type:O[0],source:B,scope:W,uid:0})[O[1]](P,C)}else C(new Error(`Could not find function ${g.type}`))}}remove(){this.scheduler.remove(),this.target.removeEventListener("message",this.receive,!1)}},o.B=Gp,o.C=ld,o.D=tu,o.E=qm,o.F=At,o.G=2,o.H=uK,o.I=ym,o.J=Zot,o.K=C0,o.L=R3,o.M=Px,o.N=Ny,o.O=nu,o.P=es,o.Q=ul,o.R=Mu,o.S=vm,o.T=t5,o.U=xp,o.V=_ie,o.W=WS,o.X=xd,o.Y=mh,o.Z=Pu,o._=Db,o.a=function(k){return _a.API_CDN_URL_REGEX.test(k)},o.a$=nie,o.a0=Sd,o.a1=yg,o.a2=Jg,o.a3=Bs,o.a4=D3,o.a5=class extends _ie{},o.a6=Lu,o.a7=su,o.a8=Us,o.a9=function(k){const g=k.value;return g?Jg(g)?RRe(g,!0)?[]:[new _ie(k.key,g,`invalid url "${g}"`)]:[new _ie(k.key,g,`string expected, "${Px(g)}" found`)]:[]},o.aA=Not,o.aB=function(k){let g=1/0,_=1/0,C=-1/0,P=-1/0;for(const O of k)g=Math.min(g,O.x),_=Math.min(_,O.y),C=Math.max(C,O.x),P=Math.max(P,O.y);return{min:new es(g,_),max:new es(C,P)}},o.aC=mt,o.aD=b,o.aE=tt,o.aF=Vt,o.aG=Dy,o.aH=Rn,o.aI=ea,o.aJ=function(k,g){const _={};for(let C=0;C=0?g.slice(_+1):""}catch{return""}},o.aN=class{constructor(k){this.entries={},this.scheduler=k}request(k,g,_,C){const P=this.entries[k]=this.entries[k]||{callbacks:[]};if(P.result){const[O,B]=P.result;return this.scheduler?this.scheduler.add(()=>{C(O,B)},g):C(O,B),()=>{}}return P.callbacks.push(C),P.cancel||(P.cancel=_((O,B)=>{P.result=[O,B];for(const W of P.callbacks)this.scheduler?this.scheduler.add(()=>{W(O,B)},g):W(O,B);setTimeout(()=>delete this.entries[k],3e3)})),()=>{P.result||(P.callbacks=P.callbacks.filter(O=>O!==C),P.callbacks.length||(P.cancel(),delete this.entries[k]))}}},o.aO=function(k,g,_){const C=JSON.stringify(k.request);return k.data&&(this.deduped.entries[C]={result:[null,k.data]}),this.deduped.request(C,{type:"parseTile",renderSourceType:k.renderSourceType,zoom:k.tileZoom},P=>{const O=Qh(k.request,(B,W,Y)=>{B?_u(B)?P(null,null):P(B):W&&P(null,{rawData:W,vectorTile:_?void 0:new hl(new nie(W)),responseHeaders:new Map(Y.entries())})});return()=>{O.cancel(),P(null,null)}},g)},o.aP=function(k){return k?{cacheControl:k.get("cache-control"),expires:k.get("expires")}:{cacheControl:void 0,expires:void 0}},o.aQ=function(k){bo++,bo>Hp&&(k.getActor().send("enforceCacheSizeLimit",il),bo=0)},o.aR=L0,o.aS=Mlt,o.aT=zlt,o.aU=Ts,o.aV=Tlt,o.aW=function(k,g){const _=document.createElement("video");_.muted=!0,_.onloadstart=function(){g(null,_)};for(let C=0;C{}}},o.aX=iK,o.aY=HL,o.aZ=Ht,o.a_=Eie,o.aa=LE,o.ab=Wc,o.ac=lr,o.ad=class{constructor(k){this.specification=k}possiblyEvaluate(k,g){return ha(k.expression.evaluate(g))}interpolate(k,g,_){return{x:Es(k.x,g.x,_),y:Es(k.y,g.y,_),z:Es(k.z,g.z,_),azimuthal:Es(k.azimuthal,g.azimuthal,_),polar:Es(k.polar,g.polar,_)}}},o.ae=Oi,o.af=wc,o.ag=ca,o.ah=Qe,o.ai=K,o.aj=Nt,o.ak=_p,o.al=$3,o.am=Es,o.an=dr,o.ao=bn,o.ap=Un,o.aq=Zs,o.ar=class{constructor(k){this.specification=k}possiblyEvaluate(k,g){return function([_,C]){const P=ha([1,_,C]);return{x:P.x,y:P.y,z:P.z}}(k.expression.evaluate(g))}interpolate(k,g,_){return{x:Es(k.x,g.x,_),y:Es(k.y,g.y,_),z:Es(k.z,g.z,_)}}},o.as=function(k,g,_=0,C=!0){const P=new es(_,_),O=k.sub(P),B=g.add(P),W=[O,new es(B.x,O.y),B,new es(O.x,B.y)];return C&&W.push(O.clone()),W},o.at=function(k,g){const _=[];for(let C=0;Cthis.buckets[ve].layers.some(_e=>B.has(_e.fqid))),Y=Object.keys(this.buckets).some(ve=>this.buckets[ve].layers.some(_e=>_e.hasTransition&&_e.hasTransition())),ae=this._firstPrepareComplete&&O!==this._lastAvailableImagesCount;this._hasAppearances===null&&(this._hasAppearances=this.hasAppearances(g));const pe=this._lastUpdatedBrightness!==C;this._lastAvailableImagesCount=O,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||C||this._hasAppearances||W||Y||ae)&&(!(this._hasAppearances||W||Y||ae)&&this._lastUpdatedBrightness&&C&&Math.abs(this._lastUpdatedBrightness-C)<.001||(this.updateBuckets(g,pe,void 0,ae||W||Y,B,P),this._lastUpdatedBrightness=C))}evaluateQueryRenderedFeaturePadding(){let k=0;for(const g in this.buckets){const _=this.buckets[g];_.evaluateQueryRenderedFeaturePadding&&(k=Math.max(k,_.evaluateQueryRenderedFeaturePadding()))}return k}queryRenderedFeatures(k,g,_,C,P,O,B){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const W=this.evaluateQueryRenderedFeaturePadding(),Y=function(ae,pe){const ve=M([],[.5*ae.width,.5*-ae.height,1]);return N(ve,ve,[1,-1,0]),b(ve,ve,ae.calculateProjMatrix(pe.toUnwrapped())),Float32Array.from(ve)}(P,this.tileID);return this.latestFeatureIndex.query(k,{tilespaceGeometry:g,pixelPosMatrix:Y,transform:C,availableImages:_,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:W,scope:B})}querySourceFeatures(k,g){const _=this.latestFeatureIndex;if(!_||!_.rawTileData)return;const C=_.loadVTLayers(),P=g?g.sourceLayer:"",O=C._geojsonTileLayer||C[P];if(!O)return;const B=DE(g&&g.filter),{z:W,x:Y,y:ae}=this.tileID.canonical,pe={z:W,x:Y,y:ae};for(let ve=0;ve_)C=!1;else if(g)if(this.expirationTime_.appearances&&_.appearances.length>0))return!0;return!1}updateBuckets(k,g,_,C,P,O){if(!this.latestFeatureIndex||!k.style)return;const B=O||k.style.listImages(),W=k.style.getBrightness(),Y=P||new Set;for(const ae in this.buckets){if(!k.style.hasLayer(ae))continue;const pe=this.buckets[ae],ve=pe.layers[0],_e=ve.sourceLayer||"_geojsonTileLayer",Pe=k.style.getLayerSourceCache(ve),De=pe.layers.some(Rt=>Y.has(Rt.fqid)),We=(C||De)&&pe instanceof KN?k.style.getOwnLayer(ae):void 0;let Je=_&&_[_e]||{};Pe&&!_&&(Je=Pe._state.getState(_e,void 0));const rt=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},xt=Object.keys(Je).length>0&&!g;pe.hasAppearances=pe.layers.some(Rt=>Rt.appearances&&Rt.appearances.length>0);const ut=xt?pe.stateDependentLayers:pe.layers;if(xt&&pe.stateDependentLayers.length!==0||g||De||C){const Rt=this.latestFeatureIndex.loadVTLayers()[_e];if(pe.update(Je,Rt,B,rt,ut,g,W,this.tileID.canonical),(C||De)&&!g&&pe instanceof KN&&We&&We.type==="symbol"){const Ft=pe;Ft.text&&Ft.text.uboBinder&&Ft.text.uboBinder.updateDynamicExpressions(We,Rt,this.tileID.canonical,B,Je,W),Ft.icon&&Ft.icon.uboBinder&&Ft.icon.uboBinder.updateDynamicExpressions(We,Rt,this.tileID.canonical,B,Je,W)}if(pe instanceof KN){const Ft=pe,bs=k.context;Ft.text&&Ft.text.uboBinder&&Ft.text.uboBinder.upload(bs),Ft.icon&&Ft.icon.uboBinder&&Ft.icon.uboBinder.upload(bs)}}if(xt&&pe.stateDependentLayers.length!==0||g||pe.hasAppearances){const Rt={zoom:k.transform.zoom,pitch:k.transform.pitch,brightness:k.style.getBrightness()||0,worldview:k.worldview},Ft=pe.updateAppearances(this.tileID.canonical,Je,B,Rt,k.imageManager,xt&&pe.stateDependentLayers.length!==0);if(Ft&&Ft.hasUboChanges){const bs=k.context;pe instanceof KN&&pe.text&&pe.text.uboBinder&&pe.text.uboBinder.upload(bs),pe instanceof KN&&pe.icon&&pe.icon.uboBinder&&pe.icon.uboBinder.upload(bs)}}(pe instanceof sie||pe instanceof Oae)&&k._terrain&&k._terrain.enabled&&Pe&&pe.uploadPending()&&k._terrain._clearRenderCacheForTile(Pe.id,this.tileID);const St=k&&k.style&&k.style.getOwnLayer(ae);St&&(this.queryPadding=Math.max(this.queryPadding,St.queryRadius(pe)||0))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil=0;We--){const Je=4*We,rt=YE[Je+0],xt=YE[Je+1],ut=YE[Je+2],St=YE[Je+3],Rt=rt+ut>>1,Ft=xt+St>>1,bs=Rt+Ft-xt,as=Ft+rt-Rt,ys=xt*s5+rt,hs=St*s5+ut,ms=Ft*s5+Rt,vn=Math.hypot((n5[2*ys+0]+n5[2*hs+0])/2-n5[2*ms+0],(n5[2*ys+1]+n5[2*hs+1])/2-n5[2*ms+1])>=16;ZE[ms]=ZE[ms]||(vn?1:0),We<1022&&(ZE[ms]=ZE[ms]||ZE[(xt+as>>1)*s5+(rt+bs>>1)]||ZE[(St+as>>1)*s5+(ut+bs>>1)])}const pe=new ho,ve=new Ru;let _e=0;function Pe(We,Je){const rt=Je*s5+We;return jie[rt]===0&&(pe.emplaceBack(n5[2*rt+0],n5[2*rt+1],We*dr/Kj,Je*dr/Kj),jie[rt]=++_e),jie[rt]-1}function De(We,Je,rt,xt,ut,St){const Rt=We+rt>>1,Ft=Je+xt>>1;if(Math.abs(We-ut)+Math.abs(Je-St)>1&&ZE[Ft*s5+Rt])De(ut,St,We,Je,Rt,Ft),De(rt,xt,ut,St,Rt,Ft);else{const bs=Pe(We,Je),as=Pe(rt,xt),ys=Pe(ut,St);ve.emplaceBack(bs,as,ys)}}return De(0,0,Kj,Kj,Kj,0),De(Kj,Kj,0,0,0,Kj),{vertices:pe,indices:ve}}(this.tileID.canonical,g);C=O.vertices,P=O.indices}else{C=new ho,P=new Ru;for(const{x:B,y:W}of _)C.emplaceBack(B,W,0,0);const O=oz(C.int16.subarray(0,4*C.length),void 0,4);for(let B=0;B0&&(B=v(new Float64Array(16),g.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(k,C,g,P,B,O),this._makeGlobeTileDebugTextBuffer(k,C,g,P,B,O)}_globePoint(k,g,_,C,P,O,B){let W=$W(k,g,_);if(O){const Y=1<<_.z,ae=Rn(C.center.lng),pe=Kn(C.center.lat),ve=(_.x+.5)/Y-ae;let _e=0;ve>.5?_e=-1:ve<-.5&&(_e=1);let Pe=(k/dr+_.x)/Y+_e,De=(g/dr+_.y)/Y;Pe=(Pe-ae)*C._pixelsPerMercatorPixel+ae,De=(De-pe)*C._pixelsPerMercatorPixel+pe;const We=[Pe*C.worldSize,De*C.worldSize,0];Qe(We,We,O),W=q3(W,We,B)}return Qe(W,W,P)}_makeGlobeTileDebugBorderBuffer(k,g,_,C,P,O){const B=new Qi,W=new z3,Y=new cl,ae=(ve,_e,Pe,De,We)=>{const Je=(Pe-ve)/(We-1),rt=(De-_e)/(We-1),xt=B.length;for(let ut=0;utae*ve+_e;for(let ve=0;ve1)return!1;const _=g.getSource().maxzoom,C=1<<_,P=Math.floor(k.x),O=Math.floor((k.x-P)*C),B=Math.floor(k.y*C),W=this.findDEMTileFor(new L0(_,P,_,O,B));return!(!W||!W.dem)}getAtPointOrZero(k,g=0){return this.getAtPoint(k,g)||0}getAtPoint(k,g,_=!0){if(this.isUsingMockSource())return null;g==null&&(g=null);const C=this._source();if(!C||k.y<0||k.y>1)return g;const P=C.getSource().maxzoom,O=1<{const W=this.getAtTileOffset(k,P,O,B),Y=C.upVector(k.canonical,P.x,P.y);return ce(Y,Y,W*C.upVectorScale(k.canonical,g,_).metersToTile),Y}}getForTilePoints(k,g,_,C){if(this.isUsingMockSource())return!1;const P=bz.create(this,k,C);return!!P&&(g.forEach(O=>{O[2]=this.exaggeration()*P.getElevationAt(O[0],O[1],_)}),!0)}getMinMaxForTile(k){if(this.isUsingMockSource())return null;const g=this.findDEMTileFor(k);if(!g||!g.dem)return null;const _=g.dem.tree,C=g.tileID,P=1<0&&(C+=(k[P]-0)*(k[P]-0)),g[P]<0&&(C+=(0-g[P])*(0-g[P]));return C},o.cL=function(k){return k*k*k*k*k},o.cM=hn,o.cN=45,o.cO=rz,o.cP=function(k,g,_){const C=Math.sqrt(k*k+g*g+_*_),P=C>0?Math.acos(_/C)*kn:0;let O=k!==0||g!==0?Math.atan2(-g,-k)*kn+90:0;return O<0&&(O+=360),[C,O,P]},o.cQ=Z,o.cR=ha,o.cS=Vn,o.cT=le,o.cU=Rl,o.cV=ue,o.cW=function(k){return[Math.pow(k[0],1/2.2),Math.pow(k[1],1/2.2),Math.pow(k[2],1/2.2)]},o.cX=oot,o.cY=nRe,o.cZ=hot,o.c_=RRe,o.ca=2,o.cb=7,o.cc=6,o.cd=Se,o.ce=H,o.cf=V,o.cg=0,o.ch=1,o.ci=4,o.cj=5,o.ck=iz,o.cl=Pv,o.cm=cot,o.cn=RL,o.co=Fat,o.cp=function(k,g,_,C,P,O,B,W,Y){if(Y.name==="globe")return Fat(k,g,new RL(_,C,P),!1);const ae=qL({z:_,x:C,y:P},Y);return new Rl([(O+ae.x/ae.scale)*g,g*(ae.y/ae.scale),B],[(O+ae.x2/ae.scale)*g,g*(ae.y2/ae.scale),W])},o.cq=function(k,g,_){return k[0]=Math.min(g[0],_[0]),k[1]=Math.min(g[1],_[1]),k[2]=Math.min(g[2],_[2]),k[3]=Math.min(g[3],_[3]),k},o.cr=function(k,g,_){return k[0]=Math.max(g[0],_[0]),k[1]=Math.max(g[1],_[1]),k[2]=Math.max(g[2],_[2]),k[3]=Math.max(g[3],_[3]),k},o.cs=function(k){const g=Math.round((k+45+360)%360/90)%4;return un[g]},o.ct=An,o.cu=Ye,o.cv=6,o.cw=function(k){const g=y(new Float64Array(16));b(g,k.pixelMatrix,k.globeMatrix);const _=[0,rs,0],C=[0,_s,0];return Qe(_,_,g),Qe(C,C,g),[_[0]>0&&_[0]<=k.width&&_[1]>0&&_[1]<=k.height&&!N8e(k,new Ts(k.center.lat,90)),C[0]>0&&C[0]<=k.width&&C[1]>0&&C[1]<=k.height&&!N8e(k,new Ts(k.center.lat,-90))]},o.cx=function(k,g){const{scale:_}=k.tileTransform,C=_*dr/(k.tileSize*Math.pow(2,g.zoom-k.tileID.overscaledZ+k.tileID.canonical.z));return function(P,O,B){var W=O[1],Y=O[2],ae=O[3],pe=B[0],ve=B[1];return P[0]=O[0]*pe,P[1]=W*pe,P[2]=Y*ve,P[3]=ae*ve,P}(new Float32Array(4),g.inverseAdjustmentMatrix,[C,C])},o.cy=Zae,o.cz=$,o.d=function(k){return _a.API_TILEJSON_REGEX.test(k)},o.d$=Mas,o.d0=hu,o.d1=class{static calculate(k,g,_){const C=new Set,P=new Map,O=new Set,B=new Set;for(const Y of Object.values(k))for(const[ae,pe]of Object.entries(Y.floors)){O.add(ae),pe.isDefault&&B.add(ae),pe.conflicts&&P.set(ae,pe.conflicts);const ve=ae===g,_e=pe.connections&&g&&pe.connections.has(g);(ve||_e)&&C.add(ae)}const W=Y=>{const ae=P.get(Y)||new Set;for(const pe of C)if((P.get(pe)||new Set).has(Y)||ae.has(pe))return!0;return!1};if(_)for(const Y of _)O.has(Y)&&(W(Y)||C.add(Y));for(const Y of B)C.has(Y)||W(Y)||C.add(Y);return C}},o.d2=oie,o.d3=wRe,o.d4=zi,o.d5=function(){return{API_URL:_a.API_URL,DRACO_URL:_a.DRACO_URL,MESHOPT_URL:_a.MESHOPT_URL,MESHOPT_SIMD_URL:_a.MESHOPT_SIMD_URL,BUILDING_GEN_URL:_a.BUILDING_GEN_URL}},o.d6=qS,o.d7=vy,o.d8=zd,o.d9=zn,o.dA=Aae,o.dB=Qi,o.dC=Ru,o.dD=function(k,g){return[Math.pow(k[0],2.2)*g,Math.pow(k[1],2.2)*g,Math.pow(k[2],2.2)*g]},o.dE=h,o.dF=function(k,g){var _=Math.sin(g),C=Math.cos(g);return k[0]=C,k[1]=_,k[2]=0,k[3]=-_,k[4]=C,k[5]=0,k[6]=0,k[7]=0,k[8]=1,k},o.dG=Ae,o.dH=Bat,o.dI=hi,o.dJ=Qo,o.dK=LRe,o.dL=function(k,g){const _=[0,0,0];return Qe(_,_,VW(QS(g.canonical))),Qe(_,_,k),_},o.dM=k=>({u_matrix:new w(k),u_texsize:new Gb(k),u_pixels_to_tile_units:new G(k),u_device_pixel_ratio:new bm(k),u_width_scale:new bm(k),u_floor_width_scale:new bm(k),u_image:new LL(k),u_units_to_pixels:new Gb(k),u_tile_units_to_pixels:new bm(k),u_alpha_discard_threshold:new bm(k),u_trim_offset:new Gb(k),u_trim_fade_range:new Gb(k),u_trim_gradient_mix_range:new Gb(k),u_trim_color:new rz(k),u_zbias_factor:new bm(k),u_tile_to_meter:new bm(k),u_ground_shadow_factor:new IL(k),u_pattern_transition:new bm(k)}),o.dN=k=>({u_matrix:new w(k),u_pixels_to_tile_units:new G(k),u_device_pixel_ratio:new bm(k),u_width_scale:new bm(k),u_floor_width_scale:new bm(k),u_units_to_pixels:new Gb(k),u_dash_image:new LL(k),u_gradient_image:new LL(k),u_image_height:new bm(k),u_texsize:new Gb(k),u_tile_units_to_pixels:new bm(k),u_alpha_discard_threshold:new bm(k),u_trim_offset:new Gb(k),u_trim_fade_range:new Gb(k),u_trim_gradient_mix_range:new Gb(k),u_trim_color:new rz(k),u_zbias_factor:new bm(k),u_tile_to_meter:new bm(k),u_ground_shadow_factor:new IL(k)}),o.dO=k=>({u_camera_to_center_distance:new bm(k),u_extrude_scale:new G(k),u_device_pixel_ratio:new bm(k),u_matrix:new w(k),u_inv_rot_matrix:new w(k),u_merc_center:new Gb(k),u_tile_id:new IL(k),u_zoom_transition:new bm(k),u_up_dir:new IL(k),u_emissive_strength:new bm(k)}),o.dP=MW,o.dQ=Tos,o.dR=class{constructor(k,g,_,C){this.context=k,this.format=C,this.size=_,this.texture=k.gl.createTexture();const[P,O,B]=this.size,{gl:W}=k;W.bindTexture(W.TEXTURE_3D,this.texture),k.pixelStoreUnpackFlipY.set(!1),k.pixelStoreUnpack.set(1),k.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in g&&g.data&&W.texImage3D(W.TEXTURE_3D,0,this.format,P,O,B,0,Z8e(this.format),X8e(this.format),g.data)}bind(k,g){const{context:_}=this,{gl:C}=_;C.bindTexture(C.TEXTURE_3D,this.texture),k!==this.minFilter&&(C.texParameteri(C.TEXTURE_3D,C.TEXTURE_MAG_FILTER,k),C.texParameteri(C.TEXTURE_3D,C.TEXTURE_MIN_FILTER,k),this.minFilter=k),g!==this.wrapS&&(C.texParameteri(C.TEXTURE_3D,C.TEXTURE_WRAP_S,g),C.texParameteri(C.TEXTURE_3D,C.TEXTURE_WRAP_T,g),this.wrapS=g)}destroy(){const{gl:k}=this.context;k.deleteTexture(this.texture),this.texture=null}},o.dS=Vat,o.dT=(k,g,_,C,P,O)=>{const B=k.transform,W=B.projection.name==="globe";let Y;if(O.paint.get("circle-pitch-alignment")==="map")if(W){const pe=Bat(B.zoom,g.canonical)*B._pixelsPerMercatorPixel;Y=Float32Array.from([pe,0,0,pe])}else Y=B.calculatePixelsToTileUnitsMatrix(_);else Y=new Float32Array([B.pixelsToGLUnits[0],0,0,B.pixelsToGLUnits[1]]);const ae={u_camera_to_center_distance:k.transform.getCameraToCenterDistance(B.projection),u_matrix:k.translatePosMatrix(g.projMatrix,_,O.paint.get("circle-translate"),O.paint.get("circle-translate-anchor")),u_device_pixel_ratio:fd.devicePixelRatio,u_extrude_scale:Y,u_inv_rot_matrix:Oas,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0],u_emissive_strength:O.paint.get("circle-emissive-strength")};if(W){ae.u_inv_rot_matrix=C,ae.u_merc_center=P,ae.u_tile_id=[g.canonical.x,g.canonical.y,1<{const pe=k.transform,ve=pe.pitch<15?kot(.07,.7,mt((14-pe.zoom)/5,0,1)):.07,_e=_.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:Cot(k,g,_,C),u_texsize:g.imageAtlasTexture?g.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:pe.calculatePixelsToTileUnitsMatrix(g),u_device_pixel_ratio:P,u_width_scale:O,u_floor_width_scale:B,u_image:0,u_tile_units_to_pixels:Sot(g,pe),u_units_to_pixels:[1/pe.pixelsToGLUnits[0],1/pe.pixelsToGLUnits[1]],u_alpha_discard_threshold:0,u_trim_offset:W,u_trim_fade_range:_.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:_.paint.get("line-trim-color").toPremultipliedRenderColor(_e?null:_.lut).toArray01(),u_zbias_factor:ve,u_tile_to_meter:Vn(g.tileID.canonical,0),u_ground_shadow_factor:Y,u_pattern_transition:ae}},o.dX=(k,g,_,C,P,O,B,W,Y,ae)=>{const pe=k.transform,ve=pe.calculatePixelsToTileUnitsMatrix(g),_e=_.paint.get("line-trim-color-use-theme").constantOr("default")==="none",Pe=pe.pitch<15?kot(.07,.7,mt((14-pe.zoom)/5,0,1)):.07;return{u_matrix:Cot(k,g,_,C),u_pixels_to_tile_units:ve,u_device_pixel_ratio:O,u_width_scale:B,u_floor_width_scale:W,u_units_to_pixels:[1/pe.pixelsToGLUnits[0],1/pe.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_image_height:P,u_texsize:Eot(_)&&g.lineAtlasTexture?g.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:Sot(g,k.transform),u_alpha_discard_threshold:0,u_trim_offset:Y,u_trim_fade_range:_.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:_.paint.get("line-trim-color").toPremultipliedRenderColor(_e?null:_.lut).toArray01(),u_zbias_factor:Pe,u_tile_to_meter:Vn(g.tileID.canonical,0),u_ground_shadow_factor:ae}},o.dY=ps,o.dZ=HW,o.d_=jn,o.da=function(k){const g=k.indexOf(lt);return g>=0?k.slice(0,g):k},o.db=function(k){return k.indexOf(lt)>=0},o.dc=function(k){const g=k.lastIndexOf(lt);return g>=0?k.slice(g+1):""},o.dd=function(k){const g=[],_=k.id;return _===void 0&&g.push({message:`layers.${_}: missing required property "id"`}),k.render===void 0&&g.push({message:`layers.${_}: missing required method "render"`}),k.renderingMode&&k.renderingMode!=="2d"&&k.renderingMode!=="3d"&&g.push({message:`layers.${_}: property "renderingMode" must be either "2d" or "3d"`}),g},o.de=function(k,g,_,C){return k.type==="custom"?new jls(k,g):new Als[k.type](k,g,_,C)},o.df=Rs,o.dg=DE,o.dh=Os,o.di=class extends VL{constructor(k,g){super(k._vectorTileFeature,k._z,k._x,k._y,k.id),k.state&&(this.state=Object.assign({},k.state)),this.target=g.target,this.namespace=g.namespace,g.properties&&(this.properties=g.properties),this.target&&("featuresetId"in this.target&&!this.target.importId||"layerId"in this.target)&&(this.source=k.source,this.sourceLayer=k.sourceLayer,this.layer=k.layer)}toJSON(){const k=super.toJSON();return k.target=this.target,k.namespace=this.namespace,k}},o.dj=$S,o.dk=function(k){return k({pluginStatus:uu,pluginURL:$f}),$S.on("pluginStateChange",k),k},o.dl=v8e,o.dm=class extends Hb{constructor(k){super(k),this.current=E}set(k,g,_){if(this.fetchUniformLocation(k,g)){for(let C=0;C<9;C++)if(_[C]!==this.current[C]){this.current=_,this.gl.uniformMatrix3fv(this.location,!1,_);break}}}},o.dn=Ar,o.dp=function(k,g,_){const C=$3(_.zoom),P=k.style.map._antialias,O=k.terrain&&k.terrain.exaggeration()>0;return C===0&&!P&&!O},o.dq=function(k){const g=k.pixelsPerMeter,_=g/en(1,k.center.lat),C=y(new Float64Array(16));return N(C,C,[k.point.x,k.point.y,0]),S(C,C,[_,_,g]),Float32Array.from(C)},o.dr=Eae,o.ds=function(k){const g=80.051129;k=mt(k,-80.051129,g)/g*90;const _=Math.pow(Math.abs(Math.sin(Un(k))),3);return Math.round(_*(Ss.length-1))},o.dt=function(k,g,_,C){const P=g.getNorth(),O=g.getSouth(),B=g.getWest(),W=g.getEast(),Y=1<0){const De=180/C;p(Pe,Pe,[De/ae+1,0,0,0,De/pe+1,0,-.5*De/ve,.5*De/_e,1])}return Pe[2]=Y,Pe[5]=k.x,Pe[8]=k.y,Pe},o.du=VW,o.dv=QS,o.dw=function(k,g,_){const C=y(new Float64Array(16)),P=(g/(1<0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[]}get updateTime(){return this._updateTime}getReplacementRegionsForTile(k,g=!1){const _=Nit(new es(0,0),new es(dr,dr),k),C=[];if(g&&!z8e(_,this._globalClipBounds))return C;for(const P of this._activeRegions){if(P.hiddenByOverlap||!z8e(_,P))continue;const O=vis(P.min,P.max,k);C.push({min:O.min,max:O.max,sourceId:this._sourceIds[P.priority],footprint:P.footprint,footprintTileId:P.tileId,order:P.order,clipMask:P.clipMask,clipScope:P.clipScope})}return C}setSources(k){this._setSources(k.map(g=>({getSourceId:()=>g.cache.id,getFootprints:()=>{const _=[];for(const C of g.cache.getVisibleCoordinates()){const P=g.cache.getTile(C).buckets[g.layer];P&&P.updateFootprints(C.toUnwrapped(),_)}return _},getOrder:()=>g.order,getClipMask:()=>g.clipMask,getClipScope:()=>g.clipScope})))}_addSource(k){const g=k.getFootprints();if(g.length===0)return;const _=k.getOrder(),C=k.getClipMask(),P=k.getClipScope();for(const O of g){if(!O.footprint)continue;const B=Nit(O.footprint.min,O.footprint.max,O.id);this._activeRegions.push({min:B.min,max:B.max,hiddenByOverlap:!1,priority:this._sourceIds.length,tileId:O.id,footprint:O.footprint,order:_,clipMask:C,clipScope:P})}this._sourceIds.push(k.getSourceId())}_computeReplacement(){this._activeRegions.sort((g,_)=>g.priority-_.priority||zae(g.min,_.min)||zae(g.max,_.max)||g.order-_.order||g.clipMask-_.clipMask||function(C,P){const O=(B,W)=>B+W;return C.length-P.length||C.reduce(O,"").localeCompare(P.reduce(O,""))}(g.clipScope,_.clipScope));let k=this._activeRegions.length!==this._prevRegions.length;if(!k){let g=0;for(;!k&&g!==this._activeRegions.length;){const _=this._activeRegions[g],C=this._prevRegions[g];k=_.priority!==C.priority||!jit(_,C)||_.order!==C.order||_.clipMask!==C.clipMask||!ar(_.clipScope,C.clipScope),this._activeRegions[g].hiddenByOverlap=C.hiddenByOverlap,++g}}if(k){++this._updateTime;for(const _ of this._activeRegions)_.order!==JW&&(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 g=_=>{const C=this._activeRegions;if(_>=C.length)return _;const P=C[_].priority;for(;_1){let _=0,C=g(_);for(;_!==C;){let P=_;const O=_;for(;P!==C;){const B=this._activeRegions[P];B.hiddenByOverlap=!1;for(let W=0;W=0;g--)this._addSource(k[g]);this._computeReplacement()}},o.eH=ho,o.eI=yie,o.eJ=z3,o.eK=JW,o.eL=class{constructor(k){this._createGrid(k),this._createPoles(k)}destroy(){this._poleIndexBuffer.destroy(),this._gridBuffer.destroy(),this._gridIndexBuffer.destroy(),this._poleNorthVertexBuffer.destroy(),this._poleSouthVertexBuffer.destroy();for(const k of this._poleSegments)k.destroy();for(const k of this._gridSegments)k.withSkirts.destroy(),k.withoutSkirts.destroy()}_fillGridMeshWithLods(k,g){const _=new Qi,C=new Ru,P=[],O=k+1+2,B=g[0]+1,W=g[0]+1+(1+g.length),Y=(ae,pe,ve)=>{let _e=ae===O-1?ae-2:ae===0?ae:ae-1;return _e+=ve?24575:0,[_e,pe]};for(let ae=0;ae>>=0,k=Math.imul(2747636419^k,2654435769)>>>0,k=Math.imul(k^k>>>16,2654435769)>>>0,(k=Math.imul(k^k>>>16,2654435769)>>>0)/4294967296},o.ec=Dat,o.ed=w8e,o.ee=$b,o.ef=T,o.eg=function(k,g){return k[0]=g[0],k[1]=g[1],k[2]=g[2],k[3]=g[4],k[4]=g[5],k[5]=g[6],k[6]=g[8],k[7]=g[9],k[8]=g[10],k},o.eh=O3,o.ei=AL,o.ej=function(k,g,_,C,P){return mt((k-g)/(_-g)*(P-C)+C,C,P)},o.ek=Ut,o.el=function(k,g){var _=g[0],C=g[1],P=g[2],O=g[3],B=g[4],W=g[5],Y=g[6],ae=g[7],pe=g[8],ve=pe*B-W*ae,_e=-pe*O+W*Y,Pe=ae*O-B*Y,De=_*ve+C*_e+P*Pe;return De?(k[0]=ve*(De=1/De),k[1]=(-pe*C+P*ae)*De,k[2]=(W*C-P*B)*De,k[3]=_e*De,k[4]=(pe*_-P*Y)*De,k[5]=(-W*_+P*O)*De,k[6]=Pe*De,k[7]=(-ae*_+C*Y)*De,k[8]=(B*_-C*O)*De,k):null},o.em=ga,o.en=2,o.eo=ke,o.ep=pt,o.eq=R,o.er=function(k,g){var _=new d(3);R(_,g);var C=1/_[0],P=1/_[1],O=1/_[2],B=g[0]*C,W=g[1]*P,Y=g[2]*O,ae=g[4]*C,pe=g[5]*P,ve=g[6]*O,_e=g[8]*C,Pe=g[9]*P,De=g[10]*O,We=B+pe+De,Je=0;return We>0?(Je=2*Math.sqrt(We+1),k[3]=.25*Je,k[0]=(ve-Pe)/Je,k[1]=(_e-Y)/Je,k[2]=(W-ae)/Je):B>pe&&B>De?(Je=2*Math.sqrt(1+B-pe-De),k[3]=(ve-Pe)/Je,k[0]=.25*Je,k[1]=(W+ae)/Je,k[2]=(_e+Y)/Je):pe>De?(Je=2*Math.sqrt(1+pe-B-De),k[3]=(_e-Y)/Je,k[0]=(W+ae)/Je,k[1]=.25*Je,k[2]=(ve+Pe)/Je):(Je=2*Math.sqrt(1+De-B-pe),k[3]=(W-ae)/Je,k[0]=(_e+Y)/Je,k[1]=(ve+Pe)/Je,k[2]=.25*Je),k},o.es=function(k,g){var _=2*Math.acos(g[3]),C=Math.sin(_/2);return C>c?(k[0]=g[0]/C,k[1]=g[1]/C,k[2]=g[2]/C):(k[0]=1,k[1]=0,k[2]=0),_},o.et=FRe,o.eu=Jae,o.ev=Qae,o.ew=[1,1,1],o.ex=bz,o.ey=function(k,g,_,C){var P=g[0],O=g[1],B=g[2],W=g[3];return k[0]=P+C*(_[0]-P),k[1]=O+C*(_[1]-O),k[2]=B+C*(_[2]-B),k[3]=W+C*(_[3]-W),k},o.ez=hz,o.f=gl,o.f0=qat,o.f1=function(k){const g=[0,0,0],_=y(new Float64Array(16));return b(_,k.pixelMatrix,k.globeMatrix),Qe(g,g,_),new es(g[0],g[1])},o.f2=Ly,o.f3=function(k,g,_=!1){if(uu===ph.deferred||uu===ph.loading||uu===ph.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");$f=fd.resolveURL(k),uu=ph.deferred,Gm=g,UN(),_||VS()},o.f4=Eo,o.f5=li,o.f6=ir,o.f7=function(k){const g=by();if(!g)return;const _=g.delete(Jo);k&&_.then(()=>k()).catch(k)},o.f8=wr,o.f9=$E,o.fA=vi,o.fB=function(k){let g=0;if(new Uint32Array(k,0,1)[0]!==sot){const _=new Uint32Array(k,0,7),[,,C,P,O,B]=_;g=_.byteLength+P+O+B+O,(C!==k.byteLength||g>=k.byteLength)&&qr("Invalid b3dm header information.")}return iot(k,g)},o.fC=function(k,g){const _=nRe(k);for(const C of _){for(const P of C.meshes)Zis(P);C.lights&&(C.lightMeshIndex=C.meshes.length,C.meshes.push(Xis(C.lights,g)))}return _},o.fD=wie,o.fE=Fa,o.fF=Dx,o.fG=ph,o.fH=function(k){qo(),Lh!=null&&Lh.then(g=>{g.keys().then(_=>{for(let C=0;C<_.length-k;C++)g.delete(_[C]).catch(P=>qr(P.message))}).catch(_=>qr(_.message))}).catch(g=>qr(g.message))},o.fa=2,o.fb=A0,o.fc=qL,o.fd=OW,o.fe=Glt,o.ff=Wlt,o.fg=_ot,o.fh=$i,o.fi="hd_road_elevation",o.fj=Fc,o.fk=Xs,o.fl=Oae,o.fm=V3,o.fn=bRe,o.fo=1,o.fp=KN,o.fq=function(k,g,_,C,P,O,B,W=1,Y,ae,pe,ve){k.createArrays(),k.tilePixelRatio=dr/(512*k.overscaling),k.compareText={},k.iconsNeedLinear=!1;const _e=k.layers[0].layout,Pe=k.layers[0]._unevaluatedLayout._values,De={};De.scaleFactor=W,De.textSizeScaleRange=_e.get("text-size-scale-range"),De.iconSizeScaleRange=_e.get("icon-size-scale-range");const[We,Je]=De.textSizeScaleRange,[rt,xt]=De.iconSizeScaleRange;De.textScaleFactor=mt(De.scaleFactor,We,Je),De.iconScaleFactor=mt(De.scaleFactor,rt,xt);const ut=Pe["text-size"],St=Pe["icon-size"];if(k.textSizeData.kind==="composite"){const{minZoom:hs,maxZoom:ms}=k.textSizeData;De.compositeTextSizes=[ut.possiblyEvaluate(new Oi(hs,{worldview:pe}),O),ut.possiblyEvaluate(new Oi(ms,{worldview:pe}),O)]}if(k.iconSizeData.kind==="composite"){const{minZoom:hs,maxZoom:ms}=k.iconSizeData;De.compositeIconSizes=[St.possiblyEvaluate(new Oi(hs,{worldview:pe}),O,ve),St.possiblyEvaluate(new Oi(ms,{worldview:pe}),O,ve)]}De.layoutTextSize=ut.possiblyEvaluate(new Oi(B+1,{worldview:pe}),O),De.layoutIconSize=St.possiblyEvaluate(new Oi(B+1,{worldview:pe}),O,ve),De.textMaxSize=ut.possiblyEvaluate(new Oi(18,{worldview:pe}),O);const Rt=_e.get("symbol-placement"),Ft=_e.get("text-rotation-alignment")==="map"&&Rt!=="point",bs=_e.get("text-size");let as=!1;const ys=[];for(const hs of k.features){const ms=_e.get("text-font").evaluate(hs,{},O).join(","),vn=bs.evaluate(hs,{},O)*De.textScaleFactor,Nn=De.layoutTextSize.evaluate(hs,{},O)*De.textScaleFactor,Tn=De.layoutIconSize.evaluate(hs,{},O,ve)*De.iconScaleFactor,Ln={horizontal:{},vertical:void 0},Mn=hs.text;let Qn,fn=[0,0];if(Mn){const to=Mn.toString(),mu=_e.get("text-letter-spacing").evaluate(hs,{},O)*jp,jl=_e.get("text-line-height").evaluate(hs,{},O)*jp,el=M3(to)?mu:0,Pc=_e.get("text-anchor").evaluate(hs,{},O),ru=_e.get("text-variable-anchor");if(!ru){const Ou=_e.get("text-radial-offset").evaluate(hs,{},O);if(Ou)fn=ilt(Pc,[Ou*jp,NRe]);else{const Ng=_e.get("text-offset").evaluate(hs,{},O);fn=[Ng[0]*jp,Ng[1]*jp]}}let Np=Ft?"center":_e.get("text-justify").evaluate(hs,{},O);const au=Rt==="point",Du=au?_e.get("text-max-width").evaluate(hs,{},O)*jp:1/0,Rh=Ou=>{k.allowVerticalPlacement&&qf(to)&&(Ln.vertical=mRe(Mn,g,_,P,ms,Du,jl,Pc,Ou,el,fn,L1.vertical,!0,Nn,vn,Y,De.textScaleFactor))};if(!Ft&&ru){const Ou=Np==="auto"?ru.map(kp=>kRe(kp)):[Np];let Ng=!1;for(let kp=0;kp=0||!qf(to)){const Ou=mRe(Mn,g,_,P,ms,Du,jl,Pc,Np,el,fn,L1.horizontal,!1,Nn,vn,Y,De.textScaleFactor);Ou&&(Ln.horizontal[Np]=Ou)}Rh(au?"left":Np)}}let Pn,Dn,tr,mr,ta,Cr,Nr=!1;const pr=_e.get("icon-text-fit").evaluate(hs,{},O);if(hs.icon&&hs.icon.hasPrimary()){const to=pK(hs.icon,k.iconSizeData,Pe["icon-size"],O,k.zoom,hs,Y,De.iconScaleFactor,pe,ve);Pn=to.iconPrimary,tr=to.iconSecondary;const mu=Pn.toString();if(Dn=C.get(mu),Dn&&(ta=_e.get("icon-offset").evaluate(hs,{},O),Cr=_e.get("icon-anchor").evaluate(hs,{},O),Qn=aie(P.get(mu),tr?P.get(tr.toString()):void 0,ta,Cr),Nr=Dn.sdf,k.sdfIcons===void 0?k.sdfIcons=Dn.sdf:k.sdfIcons!==Dn.sdf&&qr("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),(Dn.pixelRatio!==k.pixelRatio||_e.get("icon-rotate").constantOr(1)!==0)&&(k.iconsNeedLinear=!0)),tr){const jl=tr.toString();mr=C.get(jl)}}as=as||!(!hs.icon||!hs.icon.hasSecondary());const Kr=hie(Ln.horizontal)||Ln.vertical;k.iconsInText||(k.iconsInText=!!Kr&&Kr.iconsInText);const da=Nn*De.textScaleFactor/jp,{defaultShapedIcon:$a,verticallyShapedIcon:ja}=ols(k,Qn,_e,hs,O,Ln,da,ta,pr);pr!=="none"&&Qn&&(qot(Qn)||$ot(Qn))&&(uie(0,Dn,Pn,Qn,$a,pr,ae,C,P),uie(0,mr,tr,Qn,$a,pr,ae,C,P),ja&&(uie(0,Dn,Pn,Qn,ja,pr,ae,C,P),uie(0,mr,tr,Qn,ja,pr,ae,C,P))),Qn=$a;const{iconBBox:Pi,iconVerticalBBox:zo,textBBox:Li,textVerticalBBox:$o}=sls(k,Qn,ja,_e,hs,O,Tn,ta,De,P,Cr,Ln,Nn,fn,ve);ys.push({feature:hs,shapedTextOrientations:Ln,shapedText:Kr,shapedIcon:Qn,iconPrimary:Pn,iconSecondary:tr,iconOffset:ta,iconAnchor:Cr,verticallyShapedIcon:ja,layoutTextSize:Nn,layoutIconSize:Tn,textOffset:fn,isSDFIcon:Nr,iconTextFit:pr,iconCollisionBounds:Pi,iconVerticalCollisionBounds:zo,textCollisionBounds:Li,textVerticalCollisionBounds:$o})}return{featureData:ys,sizes:De,hasAnySecondaryIcon:as,textAlongLine:Ft,symbolPlacement:Rt}},o.fr=_Re,o.fs=vRe,o.ft=Qot,o.fu=Jot,o.fv=function(k,g,_,C,P,O,B,W,Y,ae){k.iconAtlasPositions=ae.iconPositions;const{featureData:pe,hasAnySecondaryIcon:ve,sizes:_e,textAlongLine:Pe,symbolPlacement:De}=g;for(const We of pe){const{shapedIcon:Je,verticallyShapedIcon:rt,feature:xt,shapedTextOrientations:ut,shapedText:St,layoutTextSize:Rt,textOffset:Ft,isSDFIcon:bs,iconPrimary:as,iconSecondary:ys,iconTextFit:hs,iconOffset:ms,iconCollisionBounds:vn,iconVerticalCollisionBounds:Nn,textCollisionBounds:Tn}=We;dlt(Je,ae.iconPositions,as,ys),dlt(rt,ae.iconPositions,as,ys),ils(ut,ae.iconPositions),als(as,ys,ae.iconPositions),(St||Je)&&lls(k,xt,ut,Je,rt,Y,_e,Rt,0,Ft,bs,C,P,B,W,ve,hs,ms,Pe,De,vn,Nn,Tn)}_&&k.generateCollisionDebugBuffers(O,k.collisionBoxArray,_e.textScaleFactor)},o.fw=sie,o.fx=hl,o.fy=function(k){return k<=1?1:Math.pow(2,Math.floor(Math.log2(k)))},o.fz=Aie,o.g=_a,o.h=function(k,g){return zm(Object.assign(k,{method:"GET"}),g)},o.i=function(k){return _a.API_STYLE_REGEX.test(k)&&!ds(k)},o.j=function(k){return btoa(encodeURIComponent(k).replace(/%([0-9A-F]{2})/g,(g,_)=>String.fromCharCode(+("0x"+_))))},o.k=Ex,o.l=function(k){return decodeURIComponent(atob(k).split("").map(g=>"%"+("00"+g.charCodeAt(0).toString(16)).slice(-2)).join(""))},o.m=function(k,g){return zm(Object.assign(k,{type:"json"}),g)},o.n=Bm,o.o=fd,o.p=function(k,g){return zm(Object.assign(k,{method:"POST"}),g)},o.q=rx,o.r=Is,o.s=function(k){try{const g=self[k];return g.setItem("_mapbox_test_",1),g.removeItem("_mapbox_test_"),!0}catch{return!1}},o.t=ts,o.u=function(){return function k(g){return g?(g^Math.random()*(16>>g/4)).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,k)}()},o.v=function(k){return!!k&&/^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(k)},o.w=qr,o.x=class{constructor(k){this.cache=new Map,this.textures=new Map,this.textureAccessTimes=new Map,this.textureMemoryUsed=0,this.maxTextureMemory=1024*(k&&k.maxTextureMemoryMB?k.maxTextureMemoryMB:256)*1024,this.finalizationRegistry=new FinalizationRegistry(g=>{this.cache.delete(g),this.clearExpiredTextures()})}calculateTextureMemory(k){return k.image?Math.ceil(k.image.width*k.image.height*4*(k.patternPositions.size>0?1.33:1)):0}evictTexture(k){const g=this.textures.get(k);if(g){const _=this.calculateTextureMemory(k);g.destroy(),this.textures.delete(k),this.textureAccessTimes.delete(k),this.textureMemoryUsed-=_}}evictTexturesIfNeeded(k){for(;this.textureMemoryUsed+k>this.maxTextureMemory&&this.textures.size>0;){let g=null,_=1/0;for(const[C]of this.textures.entries()){const P=this.textureAccessTimes.get(C)||0;P<_&&(_=P,g=C)}if(!g)break;this.evictTexture(g)}}findCachedAtlas(k){const g=this.cache.get(k.hash);if(g){const _=g.deref();if(_&&_.contentDescriptor&&this.isMipmapCompatible(k,_.contentDescriptor))return _}for(const[,_]of this.cache.entries()){const C=_.deref();if(C&&C.contentDescriptor){const P=k.subsetOf(C.contentDescriptor),O=this.isMipmapCompatible(k,C.contentDescriptor);if(P&&O)return C}}}getTextureForAtlas(k,g,_){this.textureAccessTimes.set(k,performance.now());let C=this.textures.get(k);if(C)return C;if(k.image){const P=this.calculateTextureMemory(k);return this.evictTexturesIfNeeded(P),C=new t5(g,k.image,_,{useMipmap:!!k.patternPositions.size}),this.textures.set(k,C),this.textureMemoryUsed+=P,C}return null}clearExpiredTextures(){for(const[k]of this.textures.entries())if(!this.isAtlasCached(k)){const g=this.textures.get(k);if(g){const _=this.calculateTextureMemory(k);g.destroy(),this.textureMemoryUsed-=_}this.textures.delete(k),this.textureAccessTimes.delete(k)}}isAtlasCached(k){if(!k.contentDescriptor)return!1;const g=this.cache.get(k.contentDescriptor.hash);return!!g&&g.deref()===k}getOrCache(k){if(!("image"in k)){const P=this.cache.get(k.sourceAtlasHash);if(P){const O=P.deref();if(O)return O}return qr("ImageAtlasReference points to GC'd atlas - atlas may have been evicted"),null}if(!k.contentDescriptor)return k;const g=k.contentDescriptor,_=g.hash,C=this.cache.get(_);if(C){const P=C.deref();if(P&&P.contentDescriptor&&this.isMipmapCompatible(g,P.contentDescriptor))return P}return this.cache.set(_,new WeakRef(k)),this.finalizationRegistry.register(k,_,k),k}isMipmapCompatible(k,g){return!k.requiresMipMaps||g.requiresMipMaps}destroyTextures(){for(const k of this.textures.values())k&&k.destroy();this.textures.clear(),this.textureAccessTimes.clear(),this.textureMemoryUsed=0}clear(){for(const k of this.textures.values())k&&k.destroy();this.cache.clear(),this.textures.clear(),this.textureAccessTimes.clear(),this.textureMemoryUsed=0}},o.y=Dc,o.z=qRe}),i(["require","./shared"],function(o,c){function d(fs){const ot=fs?fs.url.toString():void 0;return ot?performance.getEntriesByName(ot):[]}function u(fs){if(typeof fs=="number"||typeof fs=="boolean"||typeof fs=="string"||fs==null)return JSON.stringify(fs);if(Array.isArray(fs)){let mt="[";for(const Nt of fs)mt+=`${u(Nt)},`;return`${mt}]`}let ot="{";for(const mt of Object.keys(fs).sort())ot+=`${mt}:${u(fs[mt])},`;return`${ot}}`}function h(fs){let ot="";for(const mt of c.b5)ot+=`/${u(fs[mt])}`;return ot}function m(fs,ot){return function mt(Nt){return typeof Nt=="string"&&Nt===ot||(Array.isArray(Nt)?Nt.some(mt):!(!Nt||typeof Nt!="object")&&Object.values(Nt).some(mt))}(fs)}class p{constructor(ot){this.keyCache=Object.create(null),this._layers=Object.create(null),this._layerConfigs=Object.create(null),ot&&this.replace(ot)}replace(ot,mt){this._layerConfigs=Object.create(null),this._layers=Object.create(null),this.update(ot,[],mt)}update(ot,mt,Nt){this._options=Nt;for(const ts of ot)this._layerConfigs[ts.id]=ts,(this._layers[ts.id]=c.de(ts,this.scope,null,this._options)).compileFilter(Nt),this.keyCache[ts.id]&&delete this.keyCache[ts.id];for(const ts of mt)delete this.keyCache[ts],delete this._layerConfigs[ts],delete this._layers[ts];this.familiesBySource=Object.create(null);const Pt=function(ts,ls){const Is=Object.create(null);for(let Ht=0;Htthis._layers[zn.id]),Is=ls[0];if(Is.visibility==="none")continue;const ps=Is.source||"";let Ht=this.familiesBySource[ps];Ht||(Ht=this.familiesBySource[ps]=Object.create(null));const Xs=Is.sourceLayer||"_geojsonTileLayer";let Rs=Ht[Xs];Rs||(Rs=Ht[Xs]=[]),Rs.push(ls)}}}const f=1*c.fa;class x{constructor(ot){const mt={},Nt=[];for(const Is in ot){const ps=ot[Is],Ht=mt[Is]={};for(const Xs in ps.glyphs){const Rs=ps.glyphs[+Xs];if(!Rs||Rs.bitmap.width===0||Rs.bitmap.height===0)continue;const zn=Rs.metrics.localGlyph?f:1,Qr={x:0,y:0,w:Rs.bitmap.width+2*zn,h:Rs.bitmap.height+2*zn};Nt.push(Qr),Ht[Xs]=Qr}}const{w:Pt,h:ts}=c.J(Nt),ls=new c.f9({width:Pt||1,height:ts||1});for(const Is in ot){const ps=ot[Is];for(const Ht in ps.glyphs){const Xs=ps.glyphs[+Ht];if(!Xs||Xs.bitmap.width===0||Xs.bitmap.height===0)continue;const Rs=mt[Is][Ht],zn=Xs.metrics.localGlyph?f:1;c.f9.copy(Xs.bitmap,ls,{x:0,y:0},{x:Rs.x+zn,y:Rs.y+zn},Xs.bitmap)}}this.image=ls,this.positions=mt}}function y(fs,ot,mt){fs[ot]?mt&&(fs[ot].center=mt):fs[ot]={floorIds:new Set,center:mt||[0,0],floors:{}}}function v(fs,ot,mt,Nt){for(const Pt of ot)y(fs,Pt),fs[Pt].floors[mt]=Nt,fs[Pt].floorIds.add(mt)}function b(fs){return{id:fs.properties.id.toString(),center:[fs.properties.center_lon||0,fs.properties.center_lat||0]}}function N(fs,ot){const mt=fs.properties.id.toString(),Nt=!!fs.properties.is_default&&fs.properties.is_default,Pt=fs.properties.connected_floor_ids?new Set(fs.properties.connected_floor_ids.toString().split(";")):new Set,ts=fs.properties.conflicted_floor_ids?new Set(fs.properties.conflicted_floor_ids.toString().split(";")):new Set,ls=fs.properties.structure_ids?new Set(fs.properties.structure_ids.toString().split(";")):new Set,Is=fs.properties.name.toString(),ps=fs.properties.z_index,Ht=function(Xs,Rs){const zn=Xs.loadGeometry();if(!zn||zn.length===0)return;const Qr=zn.map(ma=>ma.map(qr=>c.fb(qr,Rs,Xs.extent)));return Qr.length===0?void 0:{type:"Polygon",coordinates:[Qr[0]]}}(fs,ot);return{id:mt,isDefault:Nt,connections:Pt,conflicts:ts,buildings:ls,name:Is,zIndex:ps,geometry:Ht}}function S(fs,ot){return ot.every(mt=>fs.properties&&fs.properties[mt]!=null)}function A(fs){return S(fs,["type","id","name"])&&fs.properties.type==="structure"}function T(fs){return S(fs,["type","id","name","z_index"])&&fs.properties.type==="floor"}c.f8(x,"GlyphAtlas");class L{constructor(ot){this.tileID=new c.aR(ot.tileID.overscaledZ,ot.tileID.wrap,ot.tileID.canonical.z,ot.tileID.canonical.x,ot.tileID.canonical.y),this.tileZoom=ot.tileZoom,this.uid=ot.uid,this.zoom=ot.zoom,this.lut=ot.lut,this.canonical=ot.tileID.canonical,this.pixelRatio=ot.pixelRatio,this.tileSize=ot.tileSize,this.source=ot.source,this.scope=ot.scope,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=ot.showCollisionBoxes,this.collectResourceTiming=!!ot.request&&ot.request.collectResourceTiming,this.promoteId=ot.promoteId,this.renderSourceType=ot.renderSourceType,this.tileTransform=c.fc(ot.tileID.canonical,ot.projection),this.projection=ot.projection,this.worldview=ot.worldview,this.localizableLayerIds=ot.localizableLayerIds,this.brightness=ot.brightness,this.extraShadowCaster=!!ot.extraShadowCaster,this.tessellationStep=ot.tessellationStep,this.scaleFactor=ot.scaleFactor,this.worldview=ot.worldview,this.indoor=ot.indoor}parse(ot,mt,Nt,Pt,ts,ls){this.status="parsing",this.data=ot,this.collisionBoxArray=new c.fd;const Is=new c.fe(Object.keys(ot.layers).sort()),ps=new c.ff(this.tileID,this.promoteId);ps.bucketLayerIDs=[];const Ht={},Xs=new c.fg(256,256),Rs={featureIndex:ps,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:Xs,availableImages:Nt,brightness:this.brightness,scaleFactor:this.scaleFactor,elevationFeatures:void 0,activeFloors:void 0};this.indoor&&(Rs.activeFloors=function(qr,Zr,Jr,ha){const Fa=Zr.indoorState.activeFloorsVisible;if(!Zr.sourceLayers)return Fa?Zr.indoorState.activeFloors:void 0;const Fo=function(Ja,Co){if(!Ja)return c.w("No source layers defined in indoor specification"),Co;if(Ja.size===0)return Co;const Go=Ja.difference(Co);for(const hi of Go)c.w(`Missing source layer required in indoor specification: ${hi}`);return Co.intersection(Co)}(Zr.sourceLayers,new Set(Object.keys(qr.layers))),Xo=Zr.indoorState,Vi=function(Ja,Co,Go,hi,Qo){const Ao={};for(const _a of Co){const ir=Ja.layers[_a];if(ir)for(let li=0;li=hi.maxzoom||hi.visibility==="none")continue;M(Go,this.zoom,Rs.brightness,Nt,this.worldview,Rs.activeFloors);const Qo=Ht[hi.id]=hi.createBucket({index:ps.bucketLayerIDs.length,layers:Go,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:Xo,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:Pt,worldview:this.worldview,localizable:Ja,availableImages:Nt,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO});ps.bucketLayerIDs.push(Go.map(_a=>c.F(_a.id,_a.scope)));let Ao=Qo.prepare?Qo.prepare():null;Ao!=null?(Ao=Ao.then(()=>Qo.populate(Vi,Rs,this.tileID.canonical,this.tileTransform)),zn.push(Ao)):Qo.populate(Vi,Rs,this.tileID.canonical,this.tileTransform)}}const ma=()=>{Xs.trim();const qr=!(!Rs.elevationFeatures||!Rs.elevationFeatures.some(hi=>hi.heightRange.min<0));let Zr,Jr,ha,Fa,Fo,Xo,Vi;const Ja={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},Co=()=>{if(Zr)return this.status="done",ls(Zr);if(this.extraShadowCaster)this.status="done",ls(null,{buckets:Object.values(Ht).filter(hi=>!hi.isEmpty()),featureIndex:ps,collisionBoxArray:null,hasTunnelGeometry:qr,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:Rs.brightness,glyphMap:null,iconMap:null,glyphPositions:null});else if(Jr&&ha&&Fa&&Vi){const Qo=new x(Jr),Ao=new Map;for(const[li,Eo]of ha.entries()){const{imagePosition:gl}=c.fn(li,Eo,c.fo);Ao.set(li,gl)}const _a={};for(const li in Ht){const Eo=Ht[li];Eo instanceof c.fp&&(M(Eo.layers,this.zoom,Rs.brightness,Nt,this.worldview,Rs.activeFloors),_a[li]=c.fq(Eo,Jr,Qo.positions,ha,Ao,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,Fo,this.worldview,Nt))}const ir={iconsPending:!0,patternsPending:!0};this.rasterizeIfNeeded(ts,ha,Fo,()=>{ir.iconsPending=!1,Go(_a,Qo,ir,void 0,Vi)}),this.rasterizeIfNeeded(ts,Fa,Xo,()=>{ir.patternsPending=!1,Go(_a,Qo,ir,void 0,Vi)})}},Go=(hi,Qo,Ao,_a,ir)=>{if(Ao.iconsPending||Ao.patternsPending)return;const li=ha.size>0||Fa.size>0,Eo=Object.keys(hi).length>0;if(!li&&!Eo)return this.status="done",void ls(null,{buckets:Object.values(Ht).filter(ds=>!ds.isEmpty()),featureIndex:ps,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:qr,glyphAtlasImage:Qo.image,lineAtlas:Xs,imageAtlas:null,brightness:Rs.brightness});const gl=(ds,Gr)=>{for(const ji in Ht){const ya=Ht[ji];if(ji in hi)c.fv(ya,hi[ji],this.showCollisionBoxes,Nt,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,ha,Gr);else if(ya.hasPattern&&(ya instanceof c.fw||ya instanceof c.fl||ya instanceof c.e0)){M(ya.layers,this.zoom,Rs.brightness,Nt,this.worldview,Rs.activeFloors);const Wi=Object.fromEntries(Gr.patternPositions);ya.addFeatures(Rs,this.tileID.canonical,Wi,Nt,this.tileTransform,this.brightness)}}this.status="done",ls(null,{buckets:Object.values(Ht).filter(ji=>!ji.isEmpty()),featureIndex:ps,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:qr,glyphAtlasImage:Qo.image,lineAtlas:Xs,imageAtlas:ds,brightness:Rs.brightness})};if(li){const ds=new Map,Gr=c.fr(ha,ds),ji=c.fr(Fa,ds),ya=new c.fs(Gr,ji,ir,this.lut,ds);ts.send("checkAtlasCache",{descriptor:ya,scope:this.scope},(Wi,wi)=>{let di,Dc;if(Wi&&c.w(`[Worker] Error checking atlas cache: ${Wi.message}`),wi)di=new c.ft(wi.sourceHash),Dc=wi;else{const fd=new c.fu(ha,Fa,this.lut,ir);di=fd,Dc=fd}gl(di,Dc)})}else gl(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const hi=c.fk(Rs.glyphDependencies,_a=>Object.keys(_a).map(Number));Object.keys(hi).length?ts.send("getGlyphs",{uid:this.uid,stacks:hi},(_a,ir)=>{Zr||(Zr=_a,Jr=ir,Co())},void 0,!1,Ja):Jr={},Vi=new Map;const Qo=Array.from(Rs.iconDependencies.keys()).map(_a=>c.I.parse(_a));Qo.length?ts.send("getImages",{images:Qo,source:this.source,scope:this.scope,tileID:this.tileID,type:"icons"},(_a,ir)=>{if(!Zr){Zr=_a,ha=new Map,Fo=this.updateImageMapAndGetImageTaskQueue(ha,ir.images,Rs.iconDependencies);for(const[li,Eo]of ir.versions.entries())Vi.set(li,Eo);Co()}},void 0,!1,Ja):(ha=new Map,Fo=new Map);const Ao=Array.from(Rs.patternDependencies.keys()).map(_a=>c.I.parse(_a));Ao.length?ts.send("getImages",{images:Ao,source:this.source,scope:this.scope,tileID:this.tileID,type:"patterns"},(_a,ir)=>{if(!Zr){Zr=_a,Fa=new Map,Xo=this.updateImageMapAndGetImageTaskQueue(Fa,ir.images,Rs.patternDependencies);for(const[li,Eo]of ir.versions.entries())Vi.set(li,Eo);Co()}},void 0,!1,Ja):(Fa=new Map,Xo=new Map)}if(Rs.elevationFeatures&&Rs.elevationFeatures.length>0){const hi=[];for(const Ao of Object.values(Ht))if(Ao instanceof c.fl){const _a=Ao.getUnevaluatedPortalGraph();_a&&hi.push(_a)}const Qo=c.fm.evaluate(hi);for(const Ao of Object.values(Ht))if(Ao instanceof c.fl){const _a=ot.layers[Is.decode(Ao.sourceLayerIndex)];Ao.setEvaluatedPortalGraph(Qo,_a,this.tileID.canonical,Rs.availableImages,Rs.brightness)}}Co()};zn.length>0?Promise.allSettled(zn).then(ma).catch(ls):ma()}updateParameters(ot){this.scaleFactor=ot.scaleFactor,this.showCollisionBoxes=ot.showCollisionBoxes,this.projection=ot.projection,this.brightness=ot.brightness,this.tileTransform=c.fc(ot.tileID.canonical,ot.projection),this.extraShadowCaster=ot.extraShadowCaster,this.lut=ot.lut,this.worldview=ot.worldview,this.indoor=ot.indoor}rasterizeIfNeeded(ot,mt,Nt,Pt){Array.from(mt.values()).some(ts=>ts.usvg)?this.rasterize(ot,mt,Nt,Pt):Pt()}updateImageMapAndGetImageTaskQueue(ot,mt,Nt){const Pt=new Map;for(const ts of mt.keys()){const ls=Nt.get(ts)||[];for(const Is of ls){const ps=Is.toString(),Ht=mt.get(Is.id.toString());Ht.usvg?Pt.has(ps)||(Pt.set(ps,Is),ot.set(ps,Object.assign({},Ht))):ot.set(ps,Ht)}}return Pt}rasterize(ot,mt,Nt,Pt){this.rasterizeTask=ot.send("rasterizeImages",{scope:this.scope,tasks:Nt},(ts,ls)=>{if(!ts)for(const[Is,ps]of ls.entries()){const Ht=Object.assign(mt.get(Is),{data:ps});mt.set(Is,Ht)}Pt()})}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.cancel()}}function M(fs,ot,mt,Nt,Pt,ts){const ls=new c.ae(ot,{brightness:mt,worldview:Pt,activeFloors:ts});for(const Is of fs)Is.recalculate(ls,Nt)}class I extends c.E{constructor({actor:ot,layerIndex:mt,availableImages:Nt,availableModels:Pt,isSpriteLoaded:ts,tileProvider:ls,brightness:Is,maxUniformBufferBindings:ps,maxUniformBlockSizeDwords:Ht,disableSymbolUBO:Xs}){super(),this.actor=ot,this.layerIndex=mt,this.availableImages=Nt,this.availableModels=Pt,this.loadVectorData=c.aO,this.tileProvider=ls,this.loading={},this.loaded={},this.deduped=new c.aN(ot.scheduler),this.isSpriteLoaded=ts,this.scheduler=ot.scheduler,this.brightness=Is,this.maxUniformBufferBindings=ps,this.maxUniformBlockSizeDwords=Ht,this.disableSymbolUBO=Xs}loadTileData(ot,mt){if(!this.tileProvider)return this.loadVectorData(ot,mt);const Nt=new AbortController,{z:Pt,x:ts,y:ls}=ot.tileID.canonical;return this.tileProvider.loadTile({z:Pt,x:ts,y:ls},{request:ot.request,signal:Nt.signal}).then(Is=>{if(Nt.signal.aborted)return;if(Is==null){const Ht=new Error("Tile not found");return Ht.status=404,mt(Ht)}if(Is.data===null)return mt(null,null);const ps=new Map;Is.expires&&ps.set("expires",Is.expires),Is.cacheControl&&ps.set("cache-control",Is.cacheControl),mt(null,{rawData:Is.data,responseHeaders:ps})}).catch(Is=>{Nt.signal.aborted||mt(Is instanceof Error?Is:new Error(String(Is)))}),()=>Nt.abort()}loadTile(ot,mt){const Nt=ot.uid,Pt=ot&&ot.request,ts=Pt&&Pt.collectResourceTiming,ls=this.loading[Nt]=new L(ot);ls.maxUniformBufferBindings=this.maxUniformBufferBindings,ls.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords,ls.disableSymbolUBO=this.disableSymbolUBO,ls.abort=this.loadTileData(ot,(Is,ps)=>{const Ht=!this.loading[Nt];if(delete this.loading[Nt],ls.cancelRasterize(),Ht||Is||!ps)return ls.status="done",Ht||(this.loaded[Nt]=ls),mt(Is);const Xs=ps.rawData,Rs={},zn=c.aP(ps.responseHeaders);zn&&zn.expires&&(Rs.expires=zn.expires),zn&&zn.cacheControl&&(Rs.cacheControl=zn.cacheControl),ls.vectorTile=ps.vectorTile||new c.fx(new c.a$(Xs));const Qr=()=>{ls.parse(ls.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(ma,qr)=>{if(ma||!qr)return mt(ma);const Zr={};if(ts){const Jr=d(Pt);Jr.length>0&&(Zr.resourceTiming=JSON.parse(JSON.stringify(Jr)))}mt(null,Object.assign({rawTileData:Xs.slice(0),responseHeaders:ps.responseHeaders},qr,Rs,Zr))})};this.isSpriteLoaded?Qr():this.once("isSpriteLoaded",()=>{this.scheduler?this.scheduler.add(Qr,{type:"parseTile",renderSourceType:ot.renderSourceType,zoom:ot.tileZoom}):Qr()}),this.loaded=this.loaded||{},this.loaded[Nt]=ls})}reloadTile(ot,mt){const Nt=this.loaded,Pt=ot.uid;if(Nt&&Nt[Pt]){const ts=Nt[Pt];ts.updateParameters(ot);const ls=(Is,ps)=>{const Ht=ts.reloadCallback;Ht&&(delete ts.reloadCallback,ts.parse(ts.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,Ht)),mt(Is,ps)};ts.status==="parsing"?ts.reloadCallback=ls:ts.status==="done"&&(ts.vectorTile?ts.parse(ts.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,ls):ls())}else mt(null,void 0)}abortTile(ot,mt){const Nt=ot.uid,Pt=this.loading[Nt];Pt&&(Pt.abort&&Pt.abort(),delete this.loading[Nt]),mt()}removeTile(ot,mt){const Nt=this.loaded,Pt=ot.uid;Nt&&Nt[Pt]&&delete Nt[Pt],mt()}}class R{constructor(ot){this.loading={}}loadTile(ot,mt){const Nt=ot.uid,{cancel:Pt}=c.b1(ot.request,(ts,ls,Is)=>{const ps=!this.loading[Nt];if(delete this.loading[Nt],ps||ts||!ls)return mt(ts);this.decodeTile(Nt,ls,ot.encoding).then(Ht=>{const{expires:Xs,cacheControl:Rs}=c.aP(Is);mt(null,Object.assign(Ht,{expires:Xs,cacheControl:Rs}))}).catch(Ht=>mt(Ht))});this.loading[Nt]={cancel:Pt}}async decodeTile(ot,mt,Nt){const Pt=await createImageBitmap(new Blob([new Uint8Array(mt)],{type:"image/png"})),ts=1-(Pt.width-c.fy(Pt.width))/2,ls=ts<1,Is=this.getImageData(Pt,ts);return Pt.close(),{dem:new c.fz(ot,Is,Nt,ls),borderReady:ls}}reloadTile(ot,mt){mt(null,null)}abortTile(ot,mt){const Nt=ot.uid,Pt=this.loading[Nt];Pt&&(Pt.cancel(),delete this.loading[Nt]),mt()}removeTile(ot,mt){mt()}getImageData(ot,mt){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(ot.width,ot.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d",{willReadFrequently:!0})),this.offscreenCanvas.width=ot.width,this.offscreenCanvas.height=ot.height,this.offscreenCanvasContext.drawImage(ot,0,0,ot.width,ot.height);const Nt=this.offscreenCanvasContext.getImageData(-mt,-mt,ot.width+2*mt,ot.height+2*mt);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),Nt}}c.a_.setPbf(c.a$);class z{constructor(ot){this._mrt=new c.a_(ot.partial?30:1/0),this._isHeaderLoaded=!1,this.uid=ot.uid,this.tileID=ot.tileID,this.source=ot.source}parse(ot,mt){const Nt=this._mrt;this.status="parsing",this._entireBuffer=ot;try{Nt.parseHeader(ot),this._isHeaderLoaded=!0;const Pt=[];for(const ts in Nt.layers){const ls=Nt.getLayer(ts),Is=ls.getDataRange(ls.getBandList()),ps=Nt.createDecodingTask(Is),Ht=ot.slice(Is.firstByte,Is.lastByte+1),Xs=c.a_.performDecoding(Ht,ps).then(Rs=>ps.complete(null,Rs)).catch(Rs=>ps.complete(Rs,null));Pt.push(Xs)}Promise.allSettled(Pt).then(()=>mt(null,Nt)).catch(ts=>mt(ts))}catch(Pt){mt(Pt)}}}class ${constructor({actor:ot}){this.actor=ot,this.loading={},this.loaded={}}loadTile(ot,mt){const Nt=ot.uid,Pt=ot.request,ts=this.loading[Nt]=new z(ot),{cancel:ls}=c.b1(Pt,(Is,ps,Ht)=>{const Xs=!this.loading[Nt];if(delete this.loading[Nt],Xs||Is||!ps)return ts.status="done",Xs||(this.loaded[Nt]=ts),mt(Is);ts.parse(ps,(Rs,zn)=>{if(Rs||!zn)return mt(Rs);mt(null,zn,Ht)}),this.loaded[Nt]=ts});ts.abort=ls}reloadTile(ot,mt){mt(null,void 0)}abortTile(ot,mt){const Nt=ot.uid,Pt=this.loading[Nt];Pt&&(Pt.abort&&Pt.abort(),delete this.loading[Nt]),mt()}removeTile(ot,mt){const Nt=ot.uid;this.loaded[Nt]&&delete this.loaded[Nt],mt()}decodeRasterArray(ot,mt){c.a_.performDecoding(ot.buffer,ot.task).then(Nt=>mt(null,Nt)).catch(Nt=>mt(Nt))}}const H=c.fA.prototype.toGeoJSON;class V{constructor(ot){this._feature=ot,this.extent=c.an,this.type=ot.type,this.properties=ot.tags,"id"in ot&&!isNaN(ot.id)&&(this.id=parseInt(ot.id,10))}loadGeometry(){if(this._feature.type===1){const ot=[];for(const mt of this._feature.geometry)ot.push([new c.P(mt[0],mt[1])]);return ot}{const ot=[];for(const mt of this._feature.geometry){const Nt=[];for(const Pt of mt)Nt.push(new c.P(Pt[0],Pt[1]));ot.push(Nt)}return ot}}toGeoJSON(ot,mt,Nt){return H.call(this,ot,mt,Nt)}}class K{constructor(ot,mt){this.name=ot,this.extent=c.an,this.length=mt.length,this._jsonFeatures=mt}feature(ot){return new V(this._jsonFeatures[ot])}}class Z{constructor(ot){this.layers={},this.extent=c.an;for(const mt of Object.keys(ot))this.layers[mt]=new K(mt,ot[mt])}}const Q=64/4096;class le{constructor(){this.features=new Map}clear(){this.features.clear()}load(ot=[],mt){for(const Nt of ot){const Pt=Nt.id;if(Pt==null)continue;let ts=this.features.get(Pt);ts&&this.updateCache(ts,mt),Nt.geometry?(ts=se(Nt),this.updateCache(ts,mt),this.features.set(Pt,ts)):this.features.delete(Pt),this.updateCache(ts,mt)}}updateCache(ot,mt){for(const{canonical:Nt,uid:Pt}of Object.values(mt)){const{z:ts,x:ls,y:Is}=Nt;ue(ot,Math.pow(2,ts),ls,Is)&&delete mt[Pt]}}getTile(ot,mt,Nt){const Pt=Math.pow(2,ot),ts=[];for(const ls of this.features.values())ue(ls,Pt,mt,Nt)&&ts.push(je(ls,Pt,mt,Nt));return{features:ts}}getFeatures(){return[...this.features.values()]}}function ue({minX:fs,minY:ot,maxX:mt,maxY:Nt},Pt,ts,ls){return fs<(ts+1+Q)/Pt&&ot<(ls+1+Q)/Pt&&mt>(ts-Q)/Pt&&Nt>(ls-Q)/Pt}function se(fs){const{id:ot,geometry:mt,properties:Nt}=fs;if(!mt)return;if(mt.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:Pt,coordinates:ts}=mt,ls={id:ot,type:1,geometry:[],tags:Nt,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},Is=ls.geometry;if(Pt==="Point")ne(ts,Is,ls);else if(Pt==="MultiPoint")for(const ps of ts)ne(ps,Is,ls);else if(Pt==="LineString")ls.type=2,ie(ts,Is,ls);else if(Pt==="MultiLineString")ls.type=2,ce(ts,Is,ls);else if(Pt==="Polygon")ls.type=3,ce(ts,Is,ls,!0);else{if(Pt!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");ls.type=3;for(const ps of ts)ce(ps,Is,ls,!0)}return ls}function ne([fs,ot],mt,Nt){const Pt=c.aH(fs);let ts=c.aL(ot);ts=ts<0?0:ts>1?1:ts,mt.push(Pt,ts),Nt.minX=Math.min(Nt.minX,Pt),Nt.minY=Math.min(Nt.minY,ts),Nt.maxX=Math.max(Nt.maxX,Pt),Nt.maxY=Math.max(Nt.maxY,ts)}function ie(fs,ot,mt,Nt=!1,Pt=!1){const ts=[];for(const ls of fs)ne(ls,ts,mt);ot.push(ts),Nt&&function(ls,Is){let ps=0;for(let Ht=0,Xs=ls.length,Rs=Xs-2;Ht0===Is)for(let Ht=0,Xs=ls.length;Ht=ls&&Rs>=ls||(Ht>=ls?(Xs+=Math.round(ma*((ls-Ht)/Qr)),Ht=ls):Rs>=ls&&(zn=Xs+Math.round(ma*((ls-Ht)/Qr)),Rs=ls),Xs>=ls&&zn>=ls||(Xs>=ls?(Ht+=Math.round(Qr*((ls-Xs)/ma)),Xs=ls):zn>=ls&&(Rs=Ht+Math.round(Qr*((ls-Xs)/ma)),zn=ls),Is&&Ht===Is[Is.length-1][0]&&Xs===Is[Is.length-1][1]||(Is=[[Ht,Xs]],Pt.push(Is)),Is.push([Rs,zn])))))}}function he(fs,ot,mt,Nt,Pt){const ts=(mt-Q)/ot,ls=(Nt-Q)/ot,Is=(mt+1+Q)/ot,ps=(Nt+1+Q)/ot;function Ht(zn,Qr){let ma=0;return znIs&&(ma|=2),Qrps&&(ma|=8),ma}let Xs=[];for(let zn=1;zn<=8;zn*=2){let Qr=fs[fs.length-2],ma=fs[fs.length-1],qr=!(Ht(Qr,ma)&zn);for(let Zr=0;Zr>31}function Se(fs,ot){const{geometry:mt,type:Nt}=fs;let Pt=0,ts=0;if(Nt===1){ot.writeVarint(Me(1,mt.length));for(const ls of mt){const Is=ls[0]-Pt,ps=ls[1]-ts;ot.writeVarint(Oe(Is)),ot.writeVarint(Oe(ps)),Pt+=Is,ts+=ps}}else for(const ls of mt){if(ls.length===0)continue;ot.writeVarint(Me(1,1));const Is=ls.length-(Nt===3?1:0);for(let ps=0;psfs},Fe=Math.fround||(Ne=new Float32Array(1),fs=>(Ne[0]=+fs,Ne[0]));var Ne;class $e{constructor(ot){this.options=Object.assign(Object.create(Ae),ot),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(ot){const{log:mt,minZoom:Nt,maxZoom:Pt}=this.options;mt&&console.time("total time");const ts=`prepare ${ot.length} points`;mt&&console.time(ts),this.points=ot;const ls=[];for(let ps=0;ps=Nt;ps--){const Ht=+Date.now();Is=this.trees[ps]=this._createTree(this._cluster(Is,ps)),mt&&console.log("z%d: %d clusters in %dms",ps,Is.numItems,+Date.now()-Ht)}return mt&&console.timeEnd("total time"),this}getClusters(ot,mt){let Nt=((ot[0]+180)%360+360)%360-180;const Pt=Math.max(-90,Math.min(90,ot[1]));let ts=ot[2]===180?180:((ot[2]+180)%360+360)%360-180;const ls=Math.max(-90,Math.min(90,ot[3]));if(ot[2]-ot[0]>=360)Nt=-180,ts=180;else if(Nt>ts){const Rs=this.getClusters([Nt,Pt,180,ls],mt),zn=this.getClusters([-180,Pt,ts,ls],mt);return Rs.concat(zn)}const Is=this.trees[this._limitZoom(mt)],ps=Is.range(Ze(Nt),Ue(ls),Ze(ts),Ue(Pt)),Ht=Is.data,Xs=[];for(const Rs of ps){const zn=this.stride*Rs;Xs.push(Ht[zn+5]>1?Ve(Ht,zn,this.clusterProps):this.points[Ht[zn+3]])}return Xs}getChildren(ot){const mt=this._getOriginId(ot),Nt=this._getOriginZoom(ot),Pt="No cluster with the specified id.",ts=this.trees[Nt];if(!ts)throw new Error(Pt);const ls=ts.data;if(mt*this.stride>=ls.length)throw new Error(Pt);const Is=this.options.radius/(this.options.extent*Math.pow(2,Nt-1)),ps=ts.within(ls[mt*this.stride],ls[mt*this.stride+1],Is),Ht=[];for(const Xs of ps){const Rs=Xs*this.stride;ls[Rs+4]===ot&&Ht.push(ls[Rs+5]>1?Ve(ls,Rs,this.clusterProps):this.points[ls[Rs+3]])}if(Ht.length===0)throw new Error(Pt);return Ht}getLeaves(ot,mt,Nt){const Pt=[];return this._appendLeaves(Pt,ot,mt=mt||10,Nt=Nt||0,0),Pt}getTile(ot,mt,Nt){const Pt=this.trees[this._limitZoom(ot)],ts=Math.pow(2,ot),{extent:ls,radius:Is}=this.options,ps=Is/ls,Ht=(Nt-ps)/ts,Xs=(Nt+1+ps)/ts,Rs={features:[]};return this._addTileFeatures(Pt.range((mt-ps)/ts,Ht,(mt+1+ps)/ts,Xs),Pt.data,mt,Nt,ts,Rs),mt===0&&this._addTileFeatures(Pt.range(1-ps/ts,Ht,1,Xs),Pt.data,ts,Nt,ts,Rs),mt===ts-1&&this._addTileFeatures(Pt.range(0,Ht,ps/ts,Xs),Pt.data,-1,Nt,ts,Rs),Rs.features.length?Rs:null}getClusterExpansionZoom(ot){let mt=this._getOriginZoom(ot)-1;for(;mt<=this.options.maxZoom;){const Nt=this.getChildren(ot);if(mt++,Nt.length!==1)break;ot=Nt[0].properties.cluster_id}return mt}_appendLeaves(ot,mt,Nt,Pt,ts){const ls=this.getChildren(mt);for(const Is of ls){const ps=Is.properties;if(ps&&ps.cluster?ts+ps.point_count<=Pt?ts+=ps.point_count:ts=this._appendLeaves(ot,ps.cluster_id,Nt,Pt,ts):ts1;let Xs,Rs,zn;if(Ht)Xs=qe(mt,ps,this.clusterProps),Rs=mt[ps],zn=mt[ps+1];else{const qr=this.points[mt[ps+3]];Xs=qr.properties;const[Zr,Jr]=qr.geometry.coordinates;Rs=Ze(Zr),zn=Ue(Jr)}const Qr={type:1,geometry:[[Math.round(this.options.extent*(Rs*ts-Nt)),Math.round(this.options.extent*(zn*ts-Pt))]],tags:Xs};let ma;ma=Ht||this.options.generateId?mt[ps+3]:this.points[mt[ps+3]].id,ma!==void 0&&(Qr.id=ma),ls.features.push(Qr)}}_limitZoom(ot){return Math.max(this.options.minZoom,Math.min(Math.floor(+ot),this.options.maxZoom+1))}_cluster(ot,mt){const{radius:Nt,extent:Pt,reduce:ts,minPoints:ls}=this.options,Is=Nt/(Pt*Math.pow(2,mt)),ps=ot.data,Ht=[],Xs=this.stride;for(let Rs=0;Rsmt&&(Zr+=ps[ha+5])}if(Zr>qr&&Zr>=ls){let Jr,ha=zn*qr,Fa=Qr*qr,Fo=-1;const Xo=(Rs/Xs<<5)+(mt+1)+this.points.length;for(const Vi of ma){const Ja=Vi*Xs;if(ps[Ja+2]<=mt)continue;ps[Ja+2]=mt;const Co=ps[Ja+5];ha+=ps[Ja]*Co,Fa+=ps[Ja+1]*Co,ps[Ja+4]=Xo,ts&&(Jr||(Jr=this._map(ps,Rs,!0),Fo=this.clusterProps.length,this.clusterProps.push(Jr)),ts(Jr,this._map(ps,Ja)))}ps[Rs+4]=Xo,Ht.push(ha/Zr,Fa/Zr,1/0,Xo,-1,Zr),ts&&Ht.push(Fo)}else{for(let Jr=0;Jr1)for(const Jr of ma){const ha=Jr*Xs;if(!(ps[ha+2]<=mt)){ps[ha+2]=mt;for(let Fa=0;Fa>5}_getOriginZoom(ot){return(ot-this.points.length)%32}_map(ot,mt,Nt){if(ot[mt+5]>1){const ls=this.clusterProps[ot[mt+6]];return Nt?Object.assign({},ls):ls}const Pt=this.points[ot[mt+3]].properties,ts=this.options.map(Pt);return Nt&&ts===Pt?Object.assign({},ts):ts}}function Ve(fs,ot,mt){return{type:"Feature",id:fs[ot+3],properties:qe(fs,ot,mt),geometry:{type:"Point",coordinates:[(Nt=fs[ot],360*(Nt-.5)),Ye(fs[ot+1])]}};var Nt}function qe(fs,ot,mt){const Nt=fs[ot+5],Pt=Nt>=1e4?`${Math.round(Nt/1e3)}k`:Nt>=1e3?Math.round(Nt/100)/10+"k":Nt,ts=fs[ot+6],ls=ts===-1?{}:Object.assign({},mt[ts]);return Object.assign(ls,{cluster:!0,cluster_id:fs[ot+3],point_count:Nt,point_count_abbreviated:Pt})}function Ze(fs){return fs/360+.5}function Ue(fs){const ot=Math.sin(fs*Math.PI/180),mt=.5-.25*Math.log((1+ot)/(1-ot))/Math.PI;return mt<0?0:mt>1?1:mt}function Ye(fs){const ot=(180-360*fs)*Math.PI/180;return 360*Math.atan(Math.exp(ot))/Math.PI-90}function Ge(fs,ot,mt,Nt){let Pt=Nt;const ts=ot+(mt-ot>>1);let ls,Is=mt-ot;const ps=fs[ot],Ht=fs[ot+1],Xs=fs[mt],Rs=fs[mt+1];for(let zn=ot+3;znPt)ls=zn,Pt=Qr;else if(Qr===Pt){const ma=Math.abs(zn-ts);maNt&&(ls-ot>3&&Ge(fs,ot,ls,Nt),fs[ls+2]=Pt,mt-ls>3&&Ge(fs,ls,mt,Nt))}function He(fs,ot,mt,Nt,Pt,ts){let ls=Pt-mt,Is=ts-Nt;if(ls!==0||Is!==0){const ps=((fs-mt)*ls+(ot-Nt)*Is)/(ls*ls+Is*Is);ps>1?(mt=Pt,Nt=ts):ps>0&&(mt+=ls*ps,Nt+=Is*ps)}return ls=fs-mt,Is=ot-Nt,ls*ls+Is*Is}function tt(fs,ot,mt,Nt){const Pt={id:fs??null,type:ot,geometry:mt,tags:Nt,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(ot==="Point"||ot==="MultiPoint"||ot==="LineString")pt(Pt,mt);else if(ot==="Polygon")pt(Pt,mt[0]);else if(ot==="MultiLineString")for(const ts of mt)pt(Pt,ts);else if(ot==="MultiPolygon")for(const ts of mt)pt(Pt,ts[0]);return Pt}function pt(fs,ot){for(let mt=0;mt0&&(ls+=Nt?(Pt*Xs-Ht*ts)/2:Math.sqrt(Math.pow(Ht-Pt,2)+Math.pow(Xs-ts,2))),Pt=Ht,ts=Xs}const Is=ot.length-3;ot[2]=1,Ge(ot,0,Is,mt),ot[Is+2]=1,ot.size=Math.abs(ls),ot.start=0,ot.end=ot.size}function Wt(fs,ot,mt,Nt){for(let Pt=0;Pt1?1:mt}function bt(fs,ot,mt,Nt,Pt,ts,ls,Is){if(Nt/=ot,ts>=(mt/=ot)&&ls=Nt)return null;const ps=[];for(const Ht of fs){const Xs=Ht.geometry;let Rs=Ht.type;const zn=Pt===0?Ht.minX:Ht.minY,Qr=Pt===0?Ht.maxX:Ht.maxY;if(zn>=mt&&Qr=Nt)continue;let ma=[];if(Rs==="Point"||Rs==="MultiPoint")As(Xs,ma,mt,Nt,Pt);else if(Rs==="LineString")vt(Xs,ma,mt,Nt,Pt,!1,Is.lineMetrics);else if(Rs==="MultiLineString")on(Xs,ma,mt,Nt,Pt,!1);else if(Rs==="Polygon")on(Xs,ma,mt,Nt,Pt,!0);else if(Rs==="MultiPolygon")for(const qr of Xs){const Zr=[];on(qr,Zr,mt,Nt,Pt,!0),Zr.length&&ma.push(Zr)}if(ma.length){if(Is.lineMetrics&&Rs==="LineString"){for(const qr of ma)ps.push(tt(Ht.id,Rs,qr,Ht.tags));continue}Rs!=="LineString"&&Rs!=="MultiLineString"||(ma.length===1?(Rs="LineString",ma=ma[0]):Rs="MultiLineString"),Rs!=="Point"&&Rs!=="MultiPoint"||(Rs=ma.length===3?"Point":"MultiPoint"),ps.push(tt(Ht.id,Rs,ma,Ht.tags))}}return ps.length?ps:null}function As(fs,ot,mt,Nt,Pt){for(let ts=0;ts=mt&&ls<=Nt&&Ms(ot,fs[ts],fs[ts+1],fs[ts+2])}}function vt(fs,ot,mt,Nt,Pt,ts,ls){let Is=Ws(fs);const ps=Pt===0?dn:rn;let Ht,Xs,Rs=fs.start;for(let Zr=0;Zrmt&&(Xs=ps(Is,Jr,ha,Fo,Xo,mt),ls&&(Is.start=Rs+Ht*Xs)):Vi>Nt?Ja=mt&&(Xs=ps(Is,Jr,ha,Fo,Xo,mt),Co=!0),Ja>Nt&&Vi<=Nt&&(Xs=ps(Is,Jr,ha,Fo,Xo,Nt),Co=!0),!ts&&Co&&(ls&&(Is.end=Rs+Ht*Xs),ot.push(Is),Is=Ws(fs)),ls&&(Rs+=Ht)}let zn=fs.length-3;const Qr=fs[zn],ma=fs[zn+1],qr=Pt===0?Qr:ma;qr>=mt&&qr<=Nt&&Ms(Is,Qr,ma,fs[zn+2]),zn=Is.length-3,ts&&zn>=3&&(Is[zn]!==Is[0]||Is[zn+1]!==Is[1])&&Ms(Is,Is[0],Is[1],Is[2]),Is.length&&ot.push(Is)}function Ws(fs){const ot=[];return ot.size=fs.size,ot.start=fs.start,ot.end=fs.end,ot}function on(fs,ot,mt,Nt,Pt,ts){for(const ls of fs)vt(ls,ot,mt,Nt,Pt,ts,!1)}function Ms(fs,ot,mt,Nt){fs.push(ot,mt,Nt)}function dn(fs,ot,mt,Nt,Pt,ts){const ls=(ts-ot)/(Nt-ot);return Ms(fs,ts,mt+(Pt-mt)*ls,1),ls}function rn(fs,ot,mt,Nt,Pt,ts){const ls=(ts-mt)/(Pt-mt);return Ms(fs,ot+(Nt-ot)*ls,ts,1),ls}function br(fs,ot){const mt=[];for(let Nt=0;Nt0&&ot.size<(Pt?ls:Nt))return void(mt.numPoints+=ot.length/3);const Is=[];for(let ps=0;psls)&&(mt.numSimplified++,Is.push(ot[ps],ot[ps+1])),mt.numPoints++;Pt&&function(ps,Ht){let Xs=0;for(let Rs=0,zn=ps.length,Qr=zn-2;Rs0===Ht)for(let Rs=0,zn=ps.length;Rs24)throw new Error("maxZoom should be in the 0-24 range");if(mt.promoteId&&mt.generateId)throw new Error("promoteId and generateId cannot be used together.");let Pt=function(ts,ls){const Is=[];if(ts.type==="FeatureCollection")for(let ps=0;ps1&&console.time("creation"),Qr=this.tiles[zn]=cr(ot,mt,Nt,Pt,Ht),this.tileCoords.push({z:mt,x:Nt,y:Pt}),Xs)){Xs>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",mt,Nt,Pt,Qr.numFeatures,Qr.numPoints,Qr.numSimplified),console.timeEnd("creation"));const Co=`z${mt}`;this.stats[Co]=(this.stats[Co]||0)+1,this.total++}if(Qr.source=ot,ts==null){if(mt===Ht.indexMaxZoom||Qr.numPoints<=Ht.indexMaxPoints)continue}else{if(mt===Ht.maxZoom||mt===ts)continue;if(ts!=null){const Co=ts-mt;if(Nt!==ls>>Co||Pt!==Is>>Co)continue}}if(Qr.source=null,ot.length===0)continue;Xs>1&&console.time("clipping");const ma=.5*Ht.buffer/Ht.extent,qr=.5-ma,Zr=.5+ma,Jr=1+ma;let ha=null,Fa=null,Fo=null,Xo=null,Vi=bt(ot,Rs,Nt-ma,Nt+Zr,0,Qr.minX,Qr.maxX,Ht),Ja=bt(ot,Rs,Nt+qr,Nt+Jr,0,Qr.minX,Qr.maxX,Ht);ot=null,Vi&&(ha=bt(Vi,Rs,Pt-ma,Pt+Zr,1,Qr.minY,Qr.maxY,Ht),Fa=bt(Vi,Rs,Pt+qr,Pt+Jr,1,Qr.minY,Qr.maxY,Ht),Vi=null),Ja&&(Fo=bt(Ja,Rs,Pt-ma,Pt+Zr,1,Qr.minY,Qr.maxY,Ht),Xo=bt(Ja,Rs,Pt+qr,Pt+Jr,1,Qr.minY,Qr.maxY,Ht),Ja=null),Xs>1&&console.timeEnd("clipping"),ps.push(ha||[],mt+1,2*Nt,2*Pt),ps.push(Fa||[],mt+1,2*Nt,2*Pt+1),ps.push(Fo||[],mt+1,2*Nt+1,2*Pt),ps.push(Xo||[],mt+1,2*Nt+1,2*Pt+1)}}getTile(ot,mt,Nt){ot=+ot,mt=+mt,Nt=+Nt;const Pt=this.options,{extent:ts,debug:ls}=Pt;if(ot<0||ot>24)return null;const Is=1<1&&console.log("drilling down to z%d-%d-%d",ot,mt,Nt);let Ht,Xs=ot,Rs=mt,zn=Nt;for(;!Ht&&Xs>0;)Xs--,Rs>>=1,zn>>=1,Ht=this.tiles[es(Xs,Rs,zn)];return Ht&&Ht.source?(ls>1&&(console.log("found parent tile z%d-%d-%d",Xs,Rs,zn),console.time("drilling down")),this.splitTile(Ht.source,Xs,Rs,zn,ot,mt,Nt),ls>1&&console.timeEnd("drilling down"),this.tiles[ps]?On(this.tiles[ps],ts):null):null}}function es(fs,ot,mt){return 32*((1<Ht.tags&&"3d_elevation_id"in Ht.tags&&"source"in Ht.tags&&Ht.tags.source==="elevation",ts=Nt.features.filter(Ht=>Pt(Ht));let ls={_geojsonTileLayer:Nt.features};ts.length>0&&(ls={_geojsonTileLayer:Nt.features.filter(Ht=>!Pt(Ht)),hd_road_elevation:ts});const Is=new Z(ls),ps=function(Ht){const Xs=new c.a$;for(const Rs of Object.keys(Ht))Xs.writeMessage(3,ge,{name:Rs,features:Ht[Rs]});return Xs.finish()}(ls).buffer;ot(null,{vectorTile:Is,rawData:ps})}class Hn extends I{constructor(ot){super(ot),this.loadVectorData=ar,this._dynamicIndex=new le}loadData(ot,mt){const Nt=ot&&ot.request,Pt=Nt&&Nt.collectResourceTiming;this._geoJSONIndex=null,this.loadGeoJSON(ot,(ts,ls)=>{if(ts||!ls)return mt(ts);if(typeof ls!="object")return mt(new Error(`Input data given to '${ot.source}' is not a valid GeoJSON object.`));{try{if(ot.filter){const ps=c.X(ot.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(ps.result==="error")throw new Error(ps.value.map(Ht=>`${Ht.key}: ${Ht.message}`).join(", "));ls.features=ls.features.filter(Ht=>ps.value.evaluate({zoom:0},Ht))}ot.dynamic?(ls.type==="Feature"&&(ls={type:"FeatureCollection",features:[ls]}),ot.append||(this._dynamicIndex.clear(),this.loaded={}),this._dynamicIndex.load(ls.features,this.loaded),ot.cluster&&(ls.features=this._dynamicIndex.getFeatures())):this.loaded={},this._geoJSONIndex=ot.cluster?new $e(function({superclusterOptions:ps,clusterProperties:Ht}){if(!Ht||!ps)return ps;const Xs={},Rs={},zn={accumulated:null,zoom:0},Qr={properties:null},ma=Object.keys(Ht);for(const qr of ma){const[Zr,Jr]=Ht[qr],ha=c.X(Jr),Fa=c.X(typeof Zr=="string"?[Zr,["accumulated"],["get",qr]]:Zr);Xs[qr]=ha.value,Rs[qr]=Fa.value}return ps.map=qr=>{Qr.properties=qr;const Zr={};for(const Jr of ma)Zr[Jr]=Xs[Jr].evaluate(zn,Qr);return Zr},ps.reduce=(qr,Zr)=>{Qr.properties=Zr;for(const Jr of ma)zn.accumulated=qr[Jr],qr[Jr]=Rs[Jr].evaluate(zn,Qr)},ps}(ot)).load(ls.features):ot.dynamic?this._dynamicIndex:function(ps,Ht){return new Zn(ps,Ht)}(ls,ot.geojsonVtOptions)}catch(ps){return mt(ps)}const Is={};if(Pt){const ps=d(Nt);ps&&(Is.resourceTiming={},Is.resourceTiming[ot.source]=JSON.parse(JSON.stringify(ps)))}mt(null,Is)}})}reloadTile(ot,mt){const Nt=this.loaded;return Nt&&Nt[ot.uid]?ot.partial?mt(null,void 0):super.reloadTile(ot,mt):this.loadTile(ot,mt)}loadGeoJSON(ot,mt){if(ot.request)c.m(ot.request,mt);else{if(typeof ot.data!="string")return mt(new Error(`Input data given to '${ot.source}' is not a valid GeoJSON object.`));setTimeout(()=>{try{return mt(null,JSON.parse(ot.data))}catch{return mt(new Error(`Input data given to '${ot.source}' is not a valid GeoJSON object.`))}},0)}}getClusterExpansionZoom(ot,mt){try{mt(null,this._geoJSONIndex.getClusterExpansionZoom(ot.clusterId))}catch(Nt){mt(Nt)}}getClusterChildren(ot,mt){try{mt(null,this._geoJSONIndex.getChildren(ot.clusterId))}catch(Nt){mt(Nt)}}getClusterLeaves(ot,mt){try{mt(null,this._geoJSONIndex.getLeaves(ot.clusterId,ot.limit,ot.offset))}catch(Nt){mt(Nt)}}}class kn{constructor(ot,mt,Nt){this.tileID=new c.aR(ot.tileID.overscaledZ,ot.tileID.wrap,ot.tileID.canonical.z,ot.tileID.canonical.x,ot.tileID.canonical.y),this.tileZoom=ot.tileZoom,this.uid=ot.uid,this.zoom=ot.zoom,this.canonical=ot.tileID.canonical,this.pixelRatio=ot.pixelRatio,this.tileSize=ot.tileSize,this.source=ot.source,this.overscaling=this.tileID.overscaleFactor(),this.projection=ot.projection,this.brightness=mt,this.worldview=Nt}parse(ot,mt,Nt,Pt){this.status="parsing";const ts=new c.aR(Nt.tileID.overscaledZ,Nt.tileID.wrap,Nt.tileID.canonical.z,Nt.tileID.canonical.x,Nt.tileID.canonical.y),ls=[],Is=mt.familiesBySource[Nt.source],ps=new c.ff(ts,Nt.promoteId);ps.bucketLayerIDs=[],ps.is3DTile=!0,c.fB(ot).then(Ht=>{const Xs=Ht.json.extensionsUsed&&Ht.json.extensionsUsed.includes("MAPBOX_mesh_features")||Ht.json.asset.extras&&Ht.json.asset.extras.MAPBOX_mesh_features,Rs=Ht.json.extensionsUsed&&Ht.json.extensionsUsed.includes("EXT_meshopt_compression"),zn=new c.ae(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const Qr in Is)for(const ma of Is[Qr]){const qr=ma[0];ps.bucketLayerIDs.push(ma.map(ha=>c.F(ha.id,ha.scope))),qr.recalculate(zn,[]);const Zr=c.fC(Ht,1/c.cS(Nt.tileID.canonical)),Jr=new c.fD(ma,Zr,ts,Xs,Rs,this.brightness,ps,this.worldview);Xs||(Jr.needsUpload=!0),ls.push(Jr),Jr.evaluate(qr)}this.status="done",Pt(null,{buckets:ls,featureIndex:ps,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null})}).catch(Ht=>Pt(new Error(Ht.message)))}}class Un{constructor({actor:ot,layerIndex:mt,availableImages:Nt,availableModels:Pt,brightness:ts,worldview:ls}){this.actor=ot,this.layerIndex=mt,this.availableImages=Nt,this.availableModels=Pt,this.brightness=ts,this.loading={},this.loaded={},this.worldview=ls}loadTile(ot,mt){const Nt=ot.uid,Pt=this.loading[Nt]=new kn(ot,this.brightness,this.worldview);c.b1(ot.request,(ts,ls)=>{const Is=!this.loading[Nt];return delete this.loading[Nt],Is||ts?(Pt.status="done",Is||(this.loaded[Nt]=Pt),mt(ts)):ls&&ls.byteLength!==0?void Pt.parse(ls,this.layerIndex,ot,(ps,Ht)=>{Pt.status="done",this.loaded=this.loaded||{},this.loaded[Nt]=Pt,ps||!Ht?mt(ps):mt(null,Ht)}):(Pt.status="done",this.loaded[Nt]=Pt,mt())})}reloadTile(ot,mt){const Nt=this.loaded,Pt=ot.uid;if(Nt&&Nt[Pt]){const ts=Nt[Pt];ts.projection=ot.projection,ts.brightness=ot.brightness;const ls=(Is,ps)=>{ts.reloadCallback&&(delete ts.reloadCallback,this.loadTile(ot,mt)),mt(Is,ps)};ts.status==="parsing"?ts.reloadCallback=ls:ts.status==="done"&&this.loadTile(ot,mt)}}abortTile(ot,mt){const Nt=ot.uid;this.loading[Nt]&&delete this.loading[Nt],mt()}removeTile(ot,mt){const Nt=this.loaded,Pt=ot.uid;Nt&&Nt[Pt]&&delete Nt[Pt],mt()}}const sn=new Map,un=new Map;class Ar{constructor(ot){this.self=ot,this.actor=new c.A(ot,this),this.layerIndexes={},this.availableImages={},this.availableModels={},this.isSpriteLoaded={},this.imageRasterizer=new c.z,this.rtlPluginParsingListeners=[],this.projections={},this.defaultProjection=c.c0({name:"mercator"}),this.workerSourceTypes={vector:I,geojson:Hn,"raster-dem":R,"raster-array":$,"batched-model":Un},this.workerSources={},this.self.registerWorkerSource=(mt,Nt)=>{if(this.workerSourceTypes[mt])throw new Error(`Worker source with name "${mt}" already registered.`);this.workerSourceTypes[mt]=Nt},this.self.registerRTLTextPlugin=mt=>{if(c.fF.isParsed())throw new Error("RTL text plugin already registered.");c.fF.setState({pluginStatus:c.fG.parsed,pluginURL:c.fF.getPluginURL()}),c.fF.applyArabicShaping=mt.applyArabicShaping,c.fF.processBidirectionalText=mt.processBidirectionalText,c.fF.processStyledBidirectionalText=mt.processStyledBidirectionalText;for(const Nt of this.rtlPluginParsingListeners)Nt(null,!0);this.rtlPluginParsingListeners=[]}}clearCaches(ot,mt,Nt){delete this.layerIndexes[ot],delete this.availableImages[ot],delete this.availableModels[ot],delete this.workerSources[ot],Nt()}checkIfReady(ot,mt,Nt){Nt()}setReferrer(ot,mt){this.referrer=mt}spriteLoaded(ot,mt){this.isSpriteLoaded[ot]||(this.isSpriteLoaded[ot]={});const{scope:Nt,isLoaded:Pt}=mt;if(this.isSpriteLoaded[ot][Nt]=Pt,this.workerSources[ot]&&this.workerSources[ot][Nt])for(const ts in this.workerSources[ot][Nt]){const ls=this.workerSources[ot][Nt][ts];for(const Is in ls){const ps=ls[Is];ps instanceof I&&(ps.isSpriteLoaded=Pt,ps.fire(new c.C("isSpriteLoaded")))}}}setImages(ot,mt,Nt){this.availableImages[ot]||(this.availableImages[ot]={});const{scope:Pt,images:ts}=mt;if(this.availableImages[ot][Pt]=ts,this.workerSources[ot]&&this.workerSources[ot][Pt]){for(const ls in this.workerSources[ot][Pt]){const Is=this.workerSources[ot][Pt][ls];for(const ps in Is)Is[ps].availableImages=ts}Nt()}else Nt()}setModels(ot,{scope:mt,models:Nt},Pt){if(this.availableModels[ot]||(this.availableModels[ot]={}),this.availableModels[ot][mt]=Nt,this.workerSources[ot]&&this.workerSources[ot][mt]){for(const ts in this.workerSources[ot][mt]){const ls=this.workerSources[ot][mt][ts];for(const Is in ls)ls[Is].availableModels=Nt}Pt()}else Pt()}setProjection(ot,mt){this.projections[ot]=c.c0(mt)}setBrightness(ot,mt,Nt){this.brightness=mt,Nt()}setContextParams(ot,mt,Nt){this.maxUniformBufferBindings=mt.maxBindingPoints,this.maxUniformBlockSizeDwords=mt.maxUniformBlockSizeDwords,this.disableSymbolUBO=mt.disableSymbolUBO,Nt()}setWorldview(ot,mt,Nt){this.worldview=mt,Nt()}setLayers(ot,mt,Nt){this.getLayerIndex(ot,mt.scope).replace(mt.layers,mt.options),Nt()}updateLayers(ot,mt,Nt){this.getLayerIndex(ot,mt.scope).update(mt.layers,mt.removedIds,mt.options),Nt()}loadTile(ot,mt,Nt){mt.projection=this.projections[ot]||this.defaultProjection,this.getWorkerSource(ot,mt).loadTile(mt,Nt)}decodeRasterArray(ot,mt,Nt){this.getWorkerSource(ot,mt).decodeRasterArray(mt,Nt)}reloadTile(ot,mt,Nt){mt.projection=this.projections[ot]||this.defaultProjection,this.getWorkerSource(ot,mt).reloadTile(mt,Nt)}abortTile(ot,mt,Nt){this.getWorkerSource(ot,mt).abortTile(mt,Nt)}removeTile(ot,mt,Nt){this.getWorkerSource(ot,mt).removeTile(mt,Nt)}removeSource(ot,mt,Nt){if(!(this.workerSources[ot]&&this.workerSources[ot][mt.scope]&&this.workerSources[ot][mt.scope][mt.type]&&this.workerSources[ot][mt.scope][mt.type][mt.source]))return;const Pt=this.workerSources[ot][mt.scope][mt.type][mt.source];delete this.workerSources[ot][mt.scope][mt.type][mt.source],Pt.removeSource!==void 0?Pt.removeSource(mt,Nt):Nt()}loadTileProvider(ot,mt,Nt){(async function(Pt,ts){const ls=un.get(Pt);if(ls)return ls;const Is=sn.get(Pt);if(Is!==void 0)return Is;const ps=import(ts).then(Ht=>{const Xs=Ht.default;if(typeof Xs!="function")throw new Error(`TileProvider "${Pt}" module must default-export a class`);if(typeof Xs.prototype.loadTile!="function")throw new Error(`TileProvider "${Pt}" class must have a loadTile method`);return un.set(Pt,Xs),Xs}).finally(()=>{sn.delete(Pt)});return sn.set(Pt,ps),ps})(mt.name,mt.url).then(Pt=>{const ts=new Pt(mt.options);return this.getWorkerSource(ot,{type:mt.type,source:mt.source,scope:mt.scope},ts),ts.load&&mt.request?ts.load({request:mt.request}):null}).then(Pt=>Nt(null,Pt)).catch(Pt=>Nt(Pt instanceof Error?Pt:new Error(typeof Pt=="string"?Pt:"Unknown error")))}loadWorkerSource(ot,mt,Nt){try{this.self.importScripts(mt.url),Nt()}catch(Pt){Nt(Pt)}}syncRTLPluginState(ot,mt,Nt){if(c.fF.isParsed())Nt(null,!0);else if(c.fF.isParsing())this.rtlPluginParsingListeners.push(Nt);else try{c.fF.setState(mt);const Pt=c.fF.getPluginURL();!c.fF.isLoaded()||c.fF.isParsed()||c.fF.isParsing()||Pt==null||(c.fF.setState({pluginStatus:c.fG.parsing,pluginURL:c.fF.getPluginURL()}),this.self.importScripts(Pt),c.fF.isParsed()?Nt(null,!0):this.rtlPluginParsingListeners.push(Nt))}catch(Pt){Nt(Pt)}}setConfig(ot,mt){Object.assign(c.g,mt)}getAvailableImages(ot,mt){this.availableImages[ot]||(this.availableImages[ot]={});let Nt=this.availableImages[ot][mt];return Nt||(Nt=[]),Nt}getAvailableModels(ot,mt){this.availableModels[ot]||(this.availableModels[ot]={});let Nt=this.availableModels[ot][mt];return Nt||(Nt={}),Nt}getLayerIndex(ot,mt){this.layerIndexes[ot]||(this.layerIndexes[ot]={});let Nt=this.layerIndexes[ot][mt];return Nt||(Nt=this.layerIndexes[ot][mt]=new p,Nt.scope=mt),Nt}getWorkerSource(ot,mt,Nt){const{type:Pt,source:ts,scope:ls}=mt,Is=this.workerSources;if(Is[ot]||(Is[ot]={}),Is[ot][ls]||(Is[ot][ls]={}),Is[ot][ls][Pt]||(Is[ot][ls][Pt]={}),this.isSpriteLoaded[ot]||(this.isSpriteLoaded[ot]={}),!Is[ot][ls][Pt][ts]){const ps={send:(Xs,Rs,zn,Qr,ma,qr)=>this.actor.send(Xs,Rs,zn,ot,ma,qr),scheduler:this.actor.scheduler},Ht=this.workerSourceTypes[Pt];if(!Ht)throw new Error(`Unknown worker source type "${Pt}".`);Is[ot][ls][Pt][ts]=new Ht({actor:ps,layerIndex:this.getLayerIndex(ot,ls),availableImages:this.getAvailableImages(ot,ls),availableModels:this.getAvailableModels(ot,ls),isSpriteLoaded:this.isSpriteLoaded[ot][ls],tileProvider:Nt,brightness:this.brightness,worldview:this.worldview,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO})}return Is[ot][ls][Pt][ts]}rasterizeImagesWorker(ot,mt,Nt){const Pt=new Map;for(const[ts,{image:ls,imageVariant:Is}]of mt.tasks.entries()){const ps=this.imageRasterizer.rasterize(Is,ls,mt.scope,ot);Pt.set(ts,ps)}Nt(void 0,Pt)}removeRasterizedImages(ot,mt,Nt){this.imageRasterizer.removeImagesFromCacheByIds(mt.imageIds,mt.scope,ot),Nt()}enforceCacheSizeLimit(ot,mt){c.fH(mt)}getWorkerPerformanceMetrics(ot,mt,Nt){Nt(void 0,void 0)}}return c.fE(self)&&(self.worker=new Ar(self)),Ar}),i(["./shared"],function(o){var c="3.22.0";const d={create:"create",load:"load",fullLoad:"fullLoad"},u={mark(D){performance.mark(D)},measure(D,w,E){performance.measure(D,w,E)}};function h(D){const w=D.name.split("?")[0];return o.a(w)&&w.includes("mapbox-gl.js")?"javascript":o.a(w)&&w.includes("mapbox-gl.css")?"css":o.b(w)?"fontRange":o.c(w)?"sprite":o.i(w)?"style":o.d(w)?"tilejson":"other"}var m,p={},f=function(){if(m)return p;function D(F){return!w(F)}function w(F){return typeof window>"u"||typeof document>"u"?"not a browser":function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return!1;var X,J,de=new Blob([""],{type:"text/javascript"}),ye=URL.createObjectURL(de);try{J=new Worker(ye),X=!0}catch{X=!1}return J&&J.terminate(),URL.revokeObjectURL(ye),X}()?function(){var X=document.createElement("canvas");X.width=X.height=1;var J=X.getContext("2d");if(!J)return!1;var de=J.getImageData(0,0,1,1);return de&&de.width===X.width}()?(E[G=F&&F.failIfMajorPerformanceCaveat]===void 0&&(E[G]=function(X){var J,de=function(ye){var Ce=document.createElement("canvas"),Le=Object.create(D.webGLContextAttributes);return Le.failIfMajorPerformanceCaveat=ye,Ce.getContext("webgl2",Le)}(X);if(!de)return!1;try{J=de.createShader(de.VERTEX_SHADER)}catch{return!1}return!(!J||de.isContextLost())&&(de.shaderSource(J,"void main() {}"),de.compileShader(J),de.getShaderParameter(J,de.COMPILE_STATUS)===!0)}(G)),E[G]?document.documentMode?"insufficient ECMAScript 6 support":void 0:"insufficient WebGL2 support"):"insufficient Canvas/getImageData support":"insufficient worker support";var G}m=1,p.supported=D,p.notSupportedReason=w;var E={};return D.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0},p}();function x(D,w,E){const F=document.createElement(D);return w!=null&&(F.className=w),E&&E.appendChild(F),F}function y(D,w,E){const F=document.createElementNS("http://www.w3.org/2000/svg",D);for(const G of Object.keys(w))F.setAttributeNS(null,G,String(w[G]));return E&&E.appendChild(F),F}const v=typeof document<"u"?document.documentElement&&document.documentElement.style:null,b=v&&v.userSelect!==void 0?"userSelect":"WebkitUserSelect";let N;function S(){v&&b&&(N=v[b],v[b]="none")}function A(){v&&b&&(v[b]=N)}function T(D){D.preventDefault(),D.stopPropagation(),window.removeEventListener("click",T,!0)}function L(){window.addEventListener("click",T,!0),window.setTimeout(()=>{window.removeEventListener("click",T,!0)},0)}function M(D,w){const E=D.getBoundingClientRect();return z(D,E,w)}function I(D,w){const E=D.getBoundingClientRect(),F=[];for(let G=0;Gthis._skuTokenExpiresAt}transformRequest(w,E){return this._transformRequestFn&&this._transformRequestFn(w,E)||{url:w}}normalizeStyleURL(w,E){if(!o.e(w))return w;const F=Z(w);return F.params.push(`sdk=js-${c}`),F.path=`/styles/v1${F.path}`,this._makeAPIURL(F,this._customAccessToken||E)}normalizeGlyphsURL(w,E){if(!o.e(w))return w;const F=Z(w);return F.path=`/fonts/v1${F.path}`,this._makeAPIURL(F,this._customAccessToken||E)}normalizeModelURL(w,E){if(!o.e(w))return w;const F=Z(w);return F.path=`/models/v1${F.path}`,this._makeAPIURL(F,this._customAccessToken||E)}normalizeSourceURL(w,E,F,G){if(!o.e(w))return w;const X=Z(w);return X.path=`/v4/${X.authority}.json`,X.params.push("secure"),F&&X.params.push(`language=${F}`),G&&X.params.push(`worldview=${G}`),this._makeAPIURL(X,this._customAccessToken||E)}normalizeIconsetURL(w,E){const F=Z(w);return o.e(w)?(F.path=`/styles/v1${F.path}/iconset.pbf`,this._makeAPIURL(F,this._customAccessToken||E)):Q(F)}normalizeSpriteURL(w,E,F,G){const X=Z(w);return o.e(w)?(X.path=`/styles/v1${X.path}/sprite${E}${F}`,this._makeAPIURL(X,this._customAccessToken||G)):(X.path+=`${E}${F}`,Q(X))}normalizeTileURL(w,E,F){if(this._isSkuTokenExpired()&&this._createSkuToken(),w&&!o.e(w))return w;const G=Z(w);G.path=G.path.replace(/(\.(png|jpg)\d*)(?=$)/,`${E||F&&G.authority!=="raster"&&F===512?"@2x":""}${o.k.supported?".webp":"$1"}`),G.authority==="raster"?G.path=`/${o.g.RASTER_URL_PREFIX}${G.path}`:G.authority==="rasterarrays"?G.path=`/${o.g.RASTERARRAYS_URL_PREFIX}${G.path}`:G.authority==="3dtiles"?G.path=`/${o.g.TILES3D_URL_PREFIX}${G.path}`:(G.path=G.path.replace(/^.+\/v4\//,"/"),G.path=`/${o.g.TILE_URL_VERSION}${G.path}`);const X=this._customAccessToken||function(J){for(const de of J){const ye=de.match(/^access_token=(.*)$/);if(ye)return ye[1]}return null}(G.params)||o.g.ACCESS_TOKEN;return o.g.REQUIRE_ACCESS_TOKEN&&X&&this._skuToken&&G.params.push(`sku=${this._skuToken}`),this._makeAPIURL(G,X)}canonicalizeTileURL(w,E){const F=Z(w);if(!F.path.match(/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/)||!F.path.match(/\.[\w]+$/))return w;let G="mapbox://";F.path.match(/^\/raster\/v1\//)?G+=`raster/${F.path.replace(`/${o.g.RASTER_URL_PREFIX}/`,"")}`:F.path.match(/^\/rasterarrays\/v1\//)?G+=`rasterarrays/${F.path.replace(`/${o.g.RASTERARRAYS_URL_PREFIX}/`,"")}`:G+=`tiles/${F.path.replace(`/${o.g.TILE_URL_VERSION}/`,"")}`;let X=F.params;return E&&(X=X.filter(J=>!J.match(/^access_token=/))),X.length&&(G+=`?${X.join("&")}`),G}canonicalizeTileset(w,E){const F=!!E&&o.e(E),G=[];for(const X of w.tiles||[])o.f(X)?G.push(this.canonicalizeTileURL(X,F)):G.push(X);return G}_makeAPIURL(w,E){const F="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",G=Z(o.g.API_URL);if(w.protocol=G.protocol,w.authority=G.authority,w.protocol==="http"){const X=w.params.indexOf("secure");X>=0&&w.params.splice(X,1)}if(G.path!=="/"&&(w.path=`${G.path}${w.path}`),!o.g.REQUIRE_ACCESS_TOKEN)return Q(w);if(E=E||o.g.ACCESS_TOKEN,!this._silenceAuthErrors){if(!E)throw new Error(`An API access token is required to use Mapbox GL. ${F}`);if(E[0]==="s")throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${F}`)}return w.params=w.params.filter(X=>X.indexOf("access_token")===-1),w.params.push(`access_token=${E||""}`),Q(w)}}const K=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function Z(D){const w=D.match(K);if(!w)throw new Error("Unable to parse URL object");return{protocol:w[1],authority:w[2],path:w[3]||"/",params:w[4]?w[4].split("&"):[]}}function Q(D){const w=D.params.length?`?${D.params.join("&")}`:"";return`${D.protocol}://${D.authority}${D.path}${w}`}const le="mapbox.eventData";function ue(D){if(!D)return null;const w=D.split(".");if(!w||w.length!==3)return null;try{return JSON.parse(o.l(w[1]))}catch{return null}}function se(D){return!(!o.g.EVENTS_URL||!D&&!o.g.ACCESS_TOKEN)}class ne{constructor(w){this.type=w,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=null}getStorageKey(w){const E=ue(o.g.ACCESS_TOKEN);let F="";return F=E&&E.u?o.j(E.u):o.g.ACCESS_TOKEN||"",w?`${le}.${w}:${F}`:`${le}:${F}`}fetchEventData(){const w=o.s("localStorage"),E=this.getStorageKey(),F=this.getStorageKey("uuid"),G=this.getStorageKey("uuidTimestamp");if(w)try{const X=localStorage.getItem(E);X&&(this.eventData=JSON.parse(X));const J=localStorage.getItem(F);J&&(this.anonId=J);const de=localStorage.getItem(G);de&&(this.anonIdTimestamp=Number(de));const ye=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp=1&&localStorage.setItem(E,JSON.stringify(this.eventData)),J&&localStorage.setItem(G,J.toString())}catch{o.w("Unable to write to LocalStorage")}}processRequests(w){}postEvent(w,E,F,G){if(!o.g.EVENTS_URL)return;const X=Z(o.g.EVENTS_URL);X.params.push(`access_token=${G||o.g.ACCESS_TOKEN||""}`);const J={event:this.type,created:new Date(w).toISOString()},de=E?Object.assign(J,E):J,ye={url:Q(X),headers:{"Content-Type":"text/plain"},body:JSON.stringify([de])};this.pendingRequest=o.p(ye,Ce=>{this.pendingRequest=null,F(Ce),this.saveEventData(),this.processRequests(G)})}queueRequest(w,E){this.queue.push(w),this.processRequests(E)}}class ie extends ne{constructor(w){super("metrics"),w&&(this.data=w)}postMetricsEvent(w){if(!se(w))return;this.anonId||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID();const E=Object.assign({},this.data,{sessionId:this.anonId});this.queueRequest({timestamp:Date.now(),payload:E},w)}processRequests(w){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:E,payload:F}=this.queue.shift();this.postEvent(E,F,()=>{},w)}}const ce=new class extends ne{constructor(D){super("appUserTurnstile"),this._customAccessToken=D}postTurnstileEvent(D,w){se(w)&&Array.isArray(D)&&D.some(E=>o.e(E)||o.f(E))&&this.queueRequest(Date.now(),w)}processRequests(D){if(this.pendingRequest||this.queue.length===0)return;this.anonId&&this.anonIdTimestamp&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const w=ue(o.g.ACCESS_TOKEN),E=w?w.u:o.g.ACCESS_TOKEN;let F=E!==this.eventData.tokenU;o.v(this.anonId)||(this.refreshUUID(),F=!0);const G=this.queue.shift();if(this.eventData.lastSuccess){const X=new Date(this.eventData.lastSuccess),J=new Date(G),de=(G-this.eventData.lastSuccess)/864e5;F=F||de>=1||de<-1||X.getDate()!==J.getDate()}else F=!0;F?this.postEvent(G,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:$,"enabled.telemetry":!1,userId:this.anonId},X=>{X||(this.eventData.lastSuccess=G,this.eventData.tokenU=E)},D):this.processRequests()}},je=ce.postTurnstileEvent.bind(ce),be=new class extends ne{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(D,w,E,F){this.skuToken=w,this.errorCb=F,o.g.EVENTS_URL&&(E||o.g.ACCESS_TOKEN?this.queueRequest({id:D,timestamp:Date.now()},E):this.errorCb(new Error(H)))}processRequests(D){if(this.pendingRequest||this.queue.length===0)return;const{id:w,timestamp:E}=this.queue.shift();w&&this.success[w]||(this.anonId&&this.anonIdTimestamp||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID(),this.postEvent(E,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:$,skuToken:this.skuToken,userId:this.anonId},F=>{F?this.errorCb(F):w&&(this.success[w]=!0)},D))}remove(){this.errorCb=null}},he=be.postMapLoadEvent.bind(be),ge=new class extends ne{constructor(){super("style.load"),this.eventIdPerMapInstanceMap=new Map,this.mapInstanceIdMap=new WeakMap}getMapInstanceId(D){let w=this.mapInstanceIdMap.get(D);return w||(w=o.u(),this.mapInstanceIdMap.set(D,w)),w}getEventId(D){const w=this.eventIdPerMapInstanceMap.get(D)||0;return this.eventIdPerMapInstanceMap.set(D,w+1),w}postStyleLoadEvent(D,w){const{map:E,style:F,importedStyles:G}=w;if(!se(D))return;const X=this.getMapInstanceId(E),J={mapInstanceId:X,eventId:this.getEventId(X),style:F};G.length&&(J.importedStyles=G),this.queueRequest({timestamp:Date.now(),payload:J},D)}processRequests(D){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:w,payload:E}=this.queue.shift();this.postEvent(w,E,()=>{},D)}},ke=ge.postStyleLoadEvent.bind(ge),Te=new ie({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),Me=Te.postMetricsEvent.bind(Te),Oe=new ie({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),Se=Oe.postMetricsEvent.bind(Oe),Qe=new class extends ne{constructor(){super("gljs.performance")}postPerformanceEvent(D,w){se(D)&&this.queueRequest({timestamp:Date.now(),performanceData:w},D)}processRequests(D){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:w,performanceData:E}=this.queue.shift(),F=function(G){const X=performance.getEntriesByType("resource"),J=performance.getEntriesByType("mark"),de=function(st){const dt={};if(st){for(const it in st)if(it!=="other")for(const jt of st[it]){const wt=`${it}ResolveRangeMin`,Bt=`${it}ResolveRangeMax`,Vt=`${it}RequestCount`,Ct=`${it}RequestCachedCount`;dt[wt]=Math.min(dt[wt]||1/0,jt.startTime),dt[Bt]=Math.max(dt[Bt]||-1/0,jt.responseEnd);const Ss=rs=>{dt[rs]===void 0&&(dt[rs]=0),++dt[rs]};jt.transferSize!==void 0&&jt.transferSize===0&&Ss(Ct),Ss(Vt)}}return dt}(function(st,dt){const it={};if(st)for(const jt of st){const wt=dt(jt);it[wt]===void 0&&(it[wt]=[]),it[wt].push(jt)}return it}(X,h)),ye=window.devicePixelRatio,Ce=navigator.connection||navigator.mozConnection||navigator.webkitConnection,Le=Ce?Ce.effectiveType:void 0,Xe={counters:[],metadata:[],attributes:[]},Ke=(st,dt,it)=>{it!=null&&st.push({name:dt,value:it.toString()})};for(const st in de)Ke(Xe.counters,st,de[st]);if(G.interactionRange[0]!==1/0&&G.interactionRange[1]!==-1/0&&(Ke(Xe.counters,"interactionRangeMin",G.interactionRange[0]),Ke(Xe.counters,"interactionRangeMax",G.interactionRange[1])),J)for(const st of Object.values(d)){const dt=J.find(it=>it.name===st);dt&&Ke(Xe.counters,st,dt.startTime)}return Ke(Xe.counters,"visibilityHidden",G.visibilityHidden),Ke(Xe.attributes,"style",function(st){if(st)for(const dt of st){const it=dt.name.split("?")[0];if(o.i(it)){const jt=it.split("/").slice(-2);if(jt.length===2)return`mapbox://styles/${jt[0]}/${jt[1]}`}}}(X)),Ke(Xe.attributes,"terrainEnabled",G.terrainEnabled?"true":"false"),Ke(Xe.attributes,"fogEnabled",G.fogEnabled?"true":"false"),Ke(Xe.attributes,"projection",G.projection),Ke(Xe.attributes,"zoom",G.zoom),Ke(Xe.metadata,"devicePixelRatio",ye),Ke(Xe.metadata,"connectionEffectiveType",Le),Ke(Xe.metadata,"navigatorUserAgent",navigator.userAgent),Ke(Xe.metadata,"screenWidth",window.screen.width),Ke(Xe.metadata,"screenHeight",window.screen.height),Ke(Xe.metadata,"windowWidth",window.innerWidth),Ke(Xe.metadata,"windowHeight",window.innerHeight),Ke(Xe.metadata,"mapWidth",G.width/ye),Ke(Xe.metadata,"mapHeight",G.height/ye),Ke(Xe.metadata,"webglRenderer",G.renderer),Ke(Xe.metadata,"webglVendor",G.vendor),Ke(Xe.metadata,"sdkVersion",c),Ke(Xe.metadata,"sdkIdentifier","mapbox-gl-js"),Xe}(E);for(const G of F.metadata);for(const G of F.counters);for(const G of F.attributes);this.postEvent(w,F,()=>{},D)}},Ae=Qe.postPerformanceEvent.bind(Qe),Fe=new class extends ne{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(D,w,E,F){if(!o.g.API_URL||!o.g.SESSION_PATH)return;const G=Z(o.g.API_URL+o.g.SESSION_PATH);G.params.push(`sku=${w||""}`),G.params.push(`access_token=${F||o.g.ACCESS_TOKEN||""}`);const X={url:Q(G),headers:{"Content-Type":"text/plain"}};this.pendingRequest=o.h(X,J=>{this.pendingRequest=null,E(J),this.saveEventData(),this.processRequests(F)})}getSessionAPI(D,w,E,F){this.skuToken=w,this.errorCb=F,o.g.EVENTS_URL&&o.g.SESSION_PATH&&o.g.API_URL&&(E||o.g.ACCESS_TOKEN?this.queueRequest({id:D,timestamp:Date.now()},E):this.errorCb(new Error(H)))}processRequests(D){if(this.pendingRequest||this.queue.length===0)return;const{id:w,timestamp:E}=this.queue.shift();w&&this.success[w]||this.getSession(E,this.skuToken,F=>{F?this.errorCb(F):w&&(this.success[w]=!0)},D)}remove(){this.errorCb=null}},Ne=Fe.getSessionAPI.bind(Fe),$e=new Set;function Ve(D,w){w?$e.add(D):$e.delete(D)}class qe{constructor(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps=new Set,this._updatedImages={}}isDirty(){return this._changed}setDirty(){this._changed=!0}getUpdatedSourceCaches(){return this._updatedSourceCaches}updateSourceCache(w,E){this._updatedSourceCaches[w]=E,this.setDirty()}discardSourceCacheUpdate(w){delete this._updatedSourceCaches[w]}updateLayer(w){const E=w.scope;this._updatedLayers[E]=this._updatedLayers[E]||new Set,this._updatedLayers[E].add(w.id),this.setDirty()}removeLayer(w){const E=w.scope;this._removedLayers[E]=this._removedLayers[E]||{},this._updatedLayers[E]=this._updatedLayers[E]||new Set,this._removedLayers[E][w.id]=w,this._updatedLayers[E].delete(w.id),this._updatedPaintProps.delete(w.fqid),this.setDirty()}getRemovedLayer(w){return this._removedLayers[w.scope]?this._removedLayers[w.scope][w.id]:null}discardLayerRemoval(w){this._removedLayers[w.scope]&&delete this._removedLayers[w.scope][w.id]}getLayerUpdatesByScope(){const w={};for(const E in this._updatedLayers)w[E]=w[E]||{},w[E].updatedIds=Array.from(this._updatedLayers[E].values());for(const E in this._removedLayers)w[E]=w[E]||{},w[E].removedIds=Object.keys(this._removedLayers[E]);return w}getUpdatedPaintProperties(){return this._updatedPaintProps}updatePaintProperties(w){this._updatedPaintProps.add(w.fqid),this.setDirty()}getUpdatedImages(w){return this._updatedImages[w]?Array.from(this._updatedImages[w].values()):[]}updateImage(w,E){this._updatedImages[E]=this._updatedImages[E]||new Set,this._updatedImages[E].add(o.I.toString(w)),this.setDirty()}resetUpdatedImages(w){this._updatedImages[w]&&this._updatedImages[w].clear()}reset(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps.clear(),this._updatedImages={}}}function Ze(D){const{userImage:w}=D;return!!(w&&w.render&&w.render())&&(D.data.replace(new Uint8Array(w.data.buffer)),!0)}const Ue={workerUrl:"",workerClass:null,workerParams:void 0};function Ye(D){return Ue.workerClass!=null?new Ue.workerClass:new self.Worker(Ue.workerUrl,Object.assign({name:D},Ue.workerParams))}const Ge="mapboxgl_preloaded_worker_pool";class He{constructor(w){this.active={},this.name=w}acquire(w,E=He.workerCount){if(!this.workers)for(this.workers=[];this.workers.length{E.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[Ge]}numActive(){return Object.keys(this.active).length}}He.workerCount=2;class tt{constructor(w,E,F="Worker",G=He.workerCount){this.workerPool=w,this.actors=[],this.currentActor=0,this.id=o.r();const X=this.workerPool.acquire(this.id,G);for(let J=0;J{this.ready=!0})}broadcast(w,E,F){o.t(this.actors,(G,X)=>{G.send(w,E,X)},F=F||function(){})}getActor(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]}remove(){this.actors.forEach(w=>{w.remove()}),this.actors=[],this.workerPool.release(this.id)}}let pt,ft;function qt(){return pt||(pt=new He),pt}tt.Actor=o.A;class Ut extends o.E{constructor(w){super(),this.imageProviders=new Map,this.images=new Map,this.updatedImages=new Map,this.callbackDispatchedThisFrame=new Map,this.imageVersions=new Map,this.loaded=new Map,this.requestors=[],this.patterns=new Map,this.patternsInFlight=new Set,this.atlasImage=new Map,this.atlasTexture=new Map,this.imageAtlasCache=new o.x,this.dirty=!0,this.spriteFormat=w,w!=="raster"&&o.y()&&(this.imageRasterizerDispatcher=new tt((ft||(ft=new He("ImageRasterizer")),ft),this,"Image Rasterizer Worker",1))}addScope(w){this.loaded.set(w,!1),this.imageProviders.set(w,new Map),this.images.set(w,new Map),this.updatedImages.set(w,new Set),this.callbackDispatchedThisFrame.set(w,new Set),this.imageVersions.set(w,new Map),this.patterns.set(w,new Map),this.atlasImage.set(w,new o.q({width:1,height:1}))}removeScope(w){this.loaded.delete(w),this.imageProviders.delete(w),this.images.delete(w),this.updatedImages.delete(w),this.callbackDispatchedThisFrame.delete(w),this.imageVersions.delete(w),this.patterns.delete(w),this.atlasImage.delete(w);const E=this.atlasTexture.get(w);E&&(E.destroy(),this.atlasTexture.delete(w))}addImageProvider(w,E){this.imageProviders.has(E)||this.imageProviders.set(E,new Map),this.imageProviders.get(E).set(w.id,w)}removeImageProvider(w,E){this.imageProviders.has(E)&&this.imageProviders.get(E).delete(w)}getPendingImageProviders(){const w=[];for(const E of this.imageProviders.values())for(const F of E.values())F.hasPendingRequests()&&w.push(F);return w}get imageRasterizer(){return this._imageRasterizer||(this._imageRasterizer=new o.z),this._imageRasterizer}isLoaded(){for(const w of this.loaded.keys())if(!this.loaded.get(w))return!1;return!0}setLoaded(w,E){if(this.loaded.get(E)!==w&&(this.loaded.set(E,w),w)){for(const{ids:F,callback:G}of this.requestors)this._notify(F,E,G);this.requestors=[]}}hasImage(w,E){return!!this.getImage(w,E)}getImage(w,E){return this.images.get(E).get(w.toString())}addImage(w,E,F){if(this._validate(w,F)){this.images.get(E).set(w.toString(),F);const G=this.imageVersions.get(E),X=G.get(w.toString())||0;G.set(w.toString(),X+1)}}_validate(w,E){let F=!0;return this._validateStretch(E.stretchX,E.data&&E.data.width)||(this.fire(new o.B(new Error(`Image "${w.name}" has invalid "stretchX" value`))),F=!1),this._validateStretch(E.stretchY,E.data&&E.data.height)||(this.fire(new o.B(new Error(`Image "${w.name}" has invalid "stretchY" value`))),F=!1),this._validateContent(E.content,E)||(this.fire(new o.B(new Error(`Image "${w.name}" has invalid "content" value`))),F=!1),F}_validateStretch(w,E){if(!w)return!0;let F=0;for(const G of w){if(G[0]o.I.from(E))}getImageVersions(w){const E=this.imageVersions.get(w);if(E)return E}getImages(w,E,F){const G=[],X=[],J=this.imageProviders.get(E);for(const Le of w){if(!Le.iconsetId){G.push(Le);continue}const Xe=J.get(Le.iconsetId);Xe&&(this.getImage(Le,E)?X.push(Le):Xe.addPendingRequest(Le))}if(G.length===0)return void this._notify(X,E,F);let de=!0;const ye=!!this.loaded.get(E),Ce=this.images.get(E);if(!ye)for(const Le of G)Ce.has(Le.toString())||(de=!1);ye||de?this._notify(G,E,F):this.requestors.push({ids:G,scope:E,callback:F})}rasterizeImages(w,E){const F=new Map,{tasks:G,scope:X}=w;for(const[J,de]of G.entries()){const ye=this.getImage(de.id,X);ye&&F.set(J,{image:ye,imageVariant:de})}this._rasterizeImages(X,F,E)}_rasterizeImages(w,E,F){if(o.y())this.imageRasterizerDispatcher.getActor().send("rasterizeImagesWorker",{tasks:E,scope:w},F);else{const G=new Map;for(const[X,{image:J,imageVariant:de}]of E.entries())G.set(X,this.imageRasterizer.rasterize(de,J,w,0));F(void 0,G)}}getUpdatedImages(w){return this.updatedImages.get(w)||new Set}_notify(w,E,F){const G=this.images.get(E),X=new Map;for(const J of w){if(!G.get(J.toString())){if(J.iconsetId)continue;this.fire(new o.C("styleimagemissing",{id:J.name}))}const de=G.get(J.toString());if(!de){o.w(`Image "${J.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 ye={data:de.usvg?null:de.data.clone(),pixelRatio:de.pixelRatio,sdf:de.sdf,usvg:de.usvg,stretchX:de.stretchX,stretchY:de.stretchY,content:de.content,hasRenderCallback:!!(de.userImage&&de.userImage.render)};de.usvg&&Object.assign(ye,{width:de.icon.usvg_tree.width,height:de.icon.usvg_tree.height}),X.set(o.I.toString(J),ye)}F(null,{images:X,versions:this.getImageVersions(E)})}getPixelSize(w){const{width:E,height:F}=this.atlasImage.get(w);return{width:E,height:F}}getPattern(w,E,F){const G=w.toString(),X=this.patterns.get(E),J=X.get(G),de=this.getImage(w,E);if(!de)return null;if(J){if(J.position.version===de.version)return J.position;J.position.version=de.version}else{if(de.usvg&&!de.data){const ye=this.getPatternInFlightId(G,E);if(this.patternsInFlight.has(ye))return null;this.patternsInFlight.add(ye);const Ce=new o.D(w).scaleSelf(o.o.devicePixelRatio),Le=new Map([[Ce.toString(),{image:de,imageVariant:Ce}]]);return this._rasterizeImages(E,Le,(Xe,Ke)=>this.storePatternImage(Ce,E,de,F,Ke)),null}this.storePattern(w,E,de)}return this._updatePatternAtlas(E,F),X.get(G).position}getPatternInFlightId(w,E){return o.F(w,E)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(w,E,F,G,X){const J=w.toString(),de=X?X.get(J):void 0;de&&(F.data=de,this.storePattern(w.id,E,F),this._updatePatternAtlas(E,G),this.patternsInFlight.delete(this.getPatternInFlightId(w.id.toString(),E)))}storePattern(w,E,F){const G={w:F.data.width+2*o.G,h:F.data.height+2*o.G,x:0,y:0},X=new o.H(G,F,o.G);this.patterns.get(E).set(w.toString(),{bin:G,position:X})}destroyAtlasTextures(){for(const w of this.atlasTexture.values())w&&w.destroy();this.atlasTexture.clear()}bind(w,E){const F=w.gl;let G=this.atlasTexture.get(E);G?this.dirty&&(G.update(this.atlasImage.get(E)),this.dirty=!1):(G=new o.T(w,this.atlasImage.get(E),F.RGBA8),this.atlasTexture.set(E,G)),G.bind(F.LINEAR,F.CLAMP_TO_EDGE)}_updatePatternAtlas(w,E){const F=this.patterns.get(w),G=Array.from(F.values()).map(({bin:Ce})=>Ce),{w:X,h:J}=o.J(G),de=this.atlasImage.get(w);de.resize({width:X||1,height:J||1});const ye=this.images.get(w);for(const[Ce,{bin:Le,position:Xe}]of F.entries()){let Ke=Xe.padding;const st=Le.x+Ke,dt=Le.y+Ke,it=ye.get(Ce).data,jt=it.width,wt=it.height;Ke=Ke>1?Ke-1:Ke,o.q.copy(it,de,{x:0,y:0},{x:st,y:dt},{width:jt,height:wt},E),o.q.copy(it,de,{x:0,y:wt-Ke},{x:st,y:dt-Ke},{width:jt,height:Ke},E),o.q.copy(it,de,{x:0,y:0},{x:st,y:dt+wt},{width:jt,height:Ke},E),o.q.copy(it,de,{x:jt-Ke,y:0},{x:st-Ke,y:dt},{width:Ke,height:wt},E),o.q.copy(it,de,{x:0,y:0},{x:st+jt,y:dt},{width:Ke,height:wt},E),o.q.copy(it,de,{x:jt-Ke,y:wt-Ke},{x:st-Ke,y:dt-Ke},{width:Ke,height:Ke},E),o.q.copy(it,de,{x:0,y:wt-Ke},{x:st+jt,y:dt-Ke},{width:Ke,height:Ke},E),o.q.copy(it,de,{x:0,y:0},{x:st+jt,y:dt+wt},{width:Ke,height:Ke},E),o.q.copy(it,de,{x:jt-Ke,y:0},{x:st-Ke,y:dt+wt},{width:Ke,height:Ke},E)}this.dirty=!0}beginFrame(){for(const w of this.images.keys())this.callbackDispatchedThisFrame.set(w,new Set)}dispatchRenderCallbacks(w,E){const F=this.images.get(E);for(const G of w){if(this.callbackDispatchedThisFrame.get(E).has(G.toString()))continue;this.callbackDispatchedThisFrame.get(E).add(G.toString());const X=F.get(G.toString());Ze(X)&&this.updateImage(G,E,X)}}destroy(){this.imageRasterizerDispatcher&&this.imageRasterizerDispatcher.remove()}}function Wt(D){const w=D.value,E=D.valueSpec,F=D.style,G=D.styleSpec,X=D.key,J=D.arrayElementValidator||Hn;if(!Array.isArray(w))return[new o.V(X,w,`array expected, ${o.M(w)} found`)];if(E.length&&w.length!==E.length)return[new o.V(X,w,`array length ${E.length} expected, length ${w.length} found`)];if(E["min-length"]&&w.lengthG)return[new o.V(w,E,`${E} is greater than the maximum value ${G}`)]}return[]}function zt(D){const w=D.key,E=D.value;if(!o.K(E))return[new o.V(w,E,`object expected, ${o.M(E)} found`)];const F=D.valueSpec,G=o.L(E.type);let X,J,de,ye={};const Ce=G!=="categorical"&&E.property===void 0,Le=!Ce,Xe=function(it){const jt=it.stops;return Array.isArray(jt)&&Array.isArray(jt[0])&&o.K(jt[0][0])}(E),Ke=kn({key:D.key,value:D.value,valueSpec:D.styleSpec.function,style:D.style,styleSpec:D.styleSpec,objectElementValidators:{stops:function(it){if(G==="identity")return[new o.V(it.key,it.value,'identity function may not have a "stops" property')];let jt=[];const wt=it.value;return jt=jt.concat(Wt({key:it.key,value:wt,valueSpec:it.valueSpec,style:it.style,styleSpec:it.styleSpec,arrayElementValidator:st})),Array.isArray(wt)&&wt.length===0&&jt.push(new o.V(it.key,wt,"array must have at least one stop")),jt},default:function(it){return Hn({key:it.key,value:it.value,valueSpec:F,style:it.style,styleSpec:it.styleSpec})}}});return G==="identity"&&Ce&&Ke.push(new o.V(D.key,D.value,'missing required property "property"')),G==="identity"||E.stops||Ke.push(new o.V(D.key,D.value,'missing required property "stops"')),G==="exponential"&&F.expression&&!o.O(F)&&Ke.push(new o.V(D.key,D.value,"exponential functions not supported")),D.styleSpec.$version>=8&&(Le&&!o.Q(F)?Ke.push(new o.V(D.key,D.value,"property functions not supported")):Ce&&!o.S(F)&&Ke.push(new o.V(D.key,D.value,"zoom functions not supported"))),G!=="categorical"&&!Xe||E.property!==void 0||Ke.push(new o.V(D.key,D.value,'"property" property is required')),Ke;function st(it){let jt=[];const wt=it.value,Bt=it.key;if(!Array.isArray(wt))return[new o.V(Bt,wt,`array expected, ${o.M(wt)} found`)];if(wt.length!==2)return[new o.V(Bt,wt,`array length 2 expected, length ${wt.length} found`)];if(Xe){if(!o.K(wt[0]))return[new o.V(Bt,wt,`object expected, ${o.M(wt[0])} found`)];const Vt=wt[0];if(Vt.zoom===void 0)return[new o.V(Bt,wt,"object stop key must have zoom")];if(Vt.value===void 0)return[new o.V(Bt,wt,"object stop key must have value")];const Ct=o.L(Vt.zoom);if(typeof Ct!="number")return[new o.V(Bt,Vt.zoom,"stop zoom values must be numbers")];if(de&&de>Ct)return[new o.V(Bt,Vt.zoom,"stop zoom values must appear in ascending order")];Ct!==de&&(de=Ct,J=void 0,ye={}),jt=jt.concat(kn({key:`${Bt}[0]`,value:wt[0],valueSpec:{zoom:{}},style:it.style,styleSpec:it.styleSpec,objectElementValidators:{zoom:us,value:dt}}))}else jt=jt.concat(dt({key:`${Bt}[0]`,value:wt[0],style:it.style,styleSpec:it.styleSpec},wt));return o.U(o.W(wt[1]))?jt.concat([new o.V(`${Bt}[1]`,wt[1],"expressions are not allowed in function stops.")]):jt.concat(Hn({key:`${Bt}[1]`,value:wt[1],valueSpec:F,style:it.style,styleSpec:it.styleSpec}))}function dt(it,jt){const wt=o.M(it.value),Bt=o.L(it.value),Vt=it.value!==null?it.value:jt;if(X){if(wt!==X)return[new o.V(it.key,Vt,`${wt} stop domain type must match previous stop domain type ${X}`)]}else X=wt;if(wt!=="number"&&wt!=="string"&&wt!=="boolean"&&typeof Bt!="number"&&typeof Bt!="string"&&typeof Bt!="boolean")return[new o.V(it.key,Vt,"stop domain value must be a number, string, or boolean")];if(wt!=="number"&&G!=="categorical"){let Ct=`number expected, ${wt} found`;return o.Q(F)&&G===void 0&&(Ct+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new o.V(it.key,Vt,Ct)]}return G!=="categorical"||wt!=="number"||typeof Bt=="number"&&isFinite(Bt)&&Math.floor(Bt)===Bt?G!=="categorical"&&wt==="number"&&typeof Bt=="number"&&typeof J=="number"&&J!==void 0&&Btnew o.V(`${D.key}${F.key}`,D.value,F.message));const E=w.value.expression||w.value._styleExpression.expression;if(D.expressionContext==="property"&&D.propertyKey==="text-font"&&!E.outputDefined())return[new o.V(D.key,D.value,`Invalid data expression for "${D.propertyKey}". Output values must be contained as literals within the expression.`)];if(D.expressionContext==="property"&&D.propertyType==="layout"&&!o.$(E))return[new o.V(D.key,D.value,'"feature-state" data expressions are not supported with layout properties.')];if(D.expressionContext==="filter")return As(E,D);if(D.expressionContext==="appearance")return vt(E,D);if(D.expressionContext&&D.expressionContext.indexOf("cluster")===0){if(!o.Z(E,["zoom","feature-state"]))return[new o.V(D.key,D.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if(D.expressionContext==="cluster-initial"&&!o._(E))return[new o.V(D.key,D.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function As(D,w){const E=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(w.valueSpec&&w.valueSpec.expression)for(const G of w.valueSpec.expression.parameters)E.delete(G);if(E.size===0)return[];const F=[];return D instanceof o.a0&&E.has(D.name)?[new o.V(w.key,w.value,`["${D.name}"] expression is not supported in a filter for a ${w.object.type} layer with id: ${w.object.id}`)]:(D.eachChild(G=>{F.push(...As(G,w))}),F)}function vt(D,w){const E=new Set;if(w.valueSpec&&w.valueSpec.expression)for(const G of w.valueSpec.expression.parameters)E.add(G);if(E.size===0)return[];const F=[];return D instanceof o.a0&&!E.has(D.name)?[new o.V(w.key,w.value,`["${D.name}"] is not an allowed parameter`)]:(D.eachChild(G=>{F.push(...vt(G,w))}),F)}function Ws(D){const w=D.key,E=D.value,F=D.valueSpec,G=[];return Array.isArray(F.values)?F.values.indexOf(o.L(E))===-1&&G.push(new o.V(w,E,`expected one of [${F.values.join(", ")}], ${JSON.stringify(E)} found`)):Object.keys(F.values).indexOf(o.L(E))===-1&&G.push(new o.V(w,E,`expected one of [${Object.keys(F.values).join(", ")}], ${JSON.stringify(E)} found`)),G}function on(D){return o.a4(o.W(D.value))?bt(Object.assign({},D,{expressionContext:"filter",valueSpec:D.styleSpec[`filter_${D.layerType||"fill"}`]})):Ms(D)}function Ms(D){const w=D.value,E=D.key;if(!Array.isArray(w))return[new o.V(E,w,`array expected, ${o.M(w)} found`)];if(w.length<1)return[new o.V(E,w,"filter array must have at least 1 element")];const F=D.styleSpec;let G=Ws({key:`${E}[0]`,value:w[0],valueSpec:F.filter_operator});const X=()=>{w.length>=2&&(o.a2(w[1])||G.push(new o.V(`${E}[1]`,w[1],`string expected, ${o.M(w[1])} found`)));for(let J=2;J":case">=":w.length>=2&&o.L(w[1])==="$type"&&G.push(new o.V(E,w,`"$type" cannot be use with operator "${w[0]}"`)),w.length!==3&&G.push(new o.V(E,w,`filter array for operator "${w[0]}" must have 3 elements`)),X();break;case"==":case"!=":w.length!==3&&G.push(new o.V(E,w,`filter array for operator "${w[0]}" must have 3 elements`)),X();break;case"in":case"!in":X();break;case"any":case"all":case"none":for(let J=1;J{Ce in E&&w.push(new o.V(F,E[Ce],`"${Ce}" is prohibited for ref layers`))}),G.layers.forEach(Ce=>{o.L(Ce.id)===de&&(ye=Ce)}),ye?ye.ref?w.push(new o.V(F,E.ref,"ref cannot reference another ref layer")):J=o.L(ye.type):typeof de=="string"&&w.push(new o.V(F,E.ref,`ref layer "${de}" not found`))}else if(J!=="background"&&J!=="sky"&&J!=="slot")if(E.source)if(o.a2(E.source)){const ye=G.sources&&G.sources[E.source],Ce=ye&&o.L(ye.type);ye?Ce==="vector"&&J==="raster"?w.push(new o.V(F,E.source,`layer "${E.id}" requires a raster source`)):Ce==="raster"&&J!=="raster"?w.push(new o.V(F,E.source,`layer "${E.id}" requires a vector source`)):Ce!=="vector"||E["source-layer"]?Ce==="raster-dem"&&J!=="hillshade"?w.push(new o.V(F,E.source,"raster-dem source can only be used with layer type 'hillshade'.")):Ce!=="raster-array"||["raster","raster-particle"].includes(J)?J==="line"&&E.paint&&(E.paint["line-gradient"]||E.paint["line-trim-offset"])&&Ce==="geojson"&&!ye.lineMetrics?w.push(new o.V(F,E,`layer "${E.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):J==="raster-particle"&&Ce!=="raster-array"&&w.push(new o.V(F,E.source,`layer "${E.id}" requires a 'raster-array' source.`)):w.push(new o.V(F,E.source,"raster-array source can only be used with layer type 'raster'.")):w.push(new o.V(F,E,`layer "${E.id}" must specify a "source-layer"`)):w.push(new o.V(F,E.source,`source "${E.source}" not found`))}else w.push(new o.V(`${F}.source`,E.source,'"source" must be a string'));else w.push(new o.V(F,E,'missing required property "source"'));return w=w.concat(kn({key:F,value:E,valueSpec:X.layer,style:D.style,styleSpec:D.styleSpec,objectElementValidators:{"*":()=>[],type:()=>Hn({key:`${F}.type`,value:E.type,valueSpec:X.layer.type,style:D.style,styleSpec:D.styleSpec,object:E,objectKey:"type"}),filter:ye=>on(Object.assign({layerType:J},ye)),layout:ye=>kn({layer:E,key:ye.key,value:ye.value,valueSpec:{},style:ye.style,styleSpec:ye.styleSpec,objectElementValidators:{"*":Ce=>br(Object.assign({layerType:J},Ce))}}),paint:ye=>kn({layer:E,key:ye.key,value:ye.value,valueSpec:{},style:ye.style,styleSpec:ye.styleSpec,objectElementValidators:{"*":Ce=>rn(Object.assign({layerType:J,layer:E},Ce))}}),appearances(ye){const Ce=Wt({key:ye.key,value:ye.value,valueSpec:ye.valueSpec,style:ye.style,styleSpec:ye.styleSpec,arrayElementValidator:Ke=>function(st){const{key:dt,layer:it,layerType:jt}=st,wt=o.L(st.value),Bt=o.L(wt.name),Vt=o.L(wt.condition),Ct=kn({key:dt,value:wt,valueSpec:st.styleSpec.appearance,style:st.style,styleSpec:st.styleSpec,objectElementValidators:{condition:Ss=>function(rs){const _s=[];return _s.push(...bt({key:rs.key,value:rs.object.condition,valueSpec:o.a8.appearance.condition,expressionContext:"appearance"})),_s}(Object.assign({layer:it,layerType:jt},Ss)),properties:Ss=>function(rs){const _s=[],{styleSpec:Gt,layer:ss,layerType:xs}=rs,Ks=Gt[`paint_${xs}`],Ts=Gt[`layout_${xs}`],_n=rs.object[rs.objectKey];for(const hn in _n){const Rn=hn in Ks?"paint":hn in Ts?"layout":void 0;if(!Rn){_s.push(new o.V(rs.key,hn,`unknown property "${hn}" for layer type "${xs}"`));continue}const Kn=Object.assign({},rs,{key:`${rs.key}.${hn}`,object:_n,objectKey:hn,layer:ss,layerType:xs,value:_n[hn],valueSpec:Rn==="paint"?Ks[hn]:Ts[hn]});_s.push(...dn(Kn,Rn))}return _s}(Object.assign({layer:it,layerType:jt},Ss))}});return Bt!=="hidden"&&Vt===void 0&&Ct.push(new o.V(st.key,"name",'Appearance with name different than "hidden" must have a condition')),Ct}(Object.assign({layerType:J,layer:E},Ke))}),Le=Array.isArray(ye.value)?ye.value:[],Xe=new Set;return Le.forEach((Ke,st)=>{const dt=o.L(Ke.name);if(dt)if(Xe.has(dt)){const it=o.L(E.id);Ce.push(new o.V(ye.key,dt,`Duplicated appearance name "${dt}" for layer "${it}"`))}else Xe.add(dt)}),Ce}}})),w}function On({key:D,value:w}){return o.a2(w)?[]:[new o.V(D,w,`string expected, ${o.M(w)} found`)]}const Rr={promoteId:function D({key:w,value:E}){if(o.a2(E))return On({key:w,value:E});if(Array.isArray(E)){const G=[],X=o.W(E),J=o.X(X);return J.result==="error"?(J.value.forEach(de=>{G.push(new o.V(`${w}${de.key}`,null,`${de.message}`))}),G):(o.Z(J.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"])||G.push(new o.V(`${w}`,null,"promoteId expression should be only feature dependent")),G)}if(!o.K(E))return[new o.V(w,E,`string, expression or object expected, "${o.M(E)}" found`)];const F=[];for(const G in E)F.push(...D({key:`${w}.${G}`,value:E[G]}));return F}};function cr(D){const w=D.value,E=D.key,F=D.styleSpec,G=D.style;if(!o.K(w))return[new o.V(E,w,`object expected, ${o.M(w)} found`)];if(!("type"in w))return[new o.V(E,w,'"type" is required')];const X=o.L(w.type);let J=[];switch(["vector","raster","raster-dem","raster-array"].includes(X)&&("url"in w||"tiles"in w||J.push(new o.a5(E,w,'Either "url" or "tiles" is required.'))),X){case"vector":case"raster":case"raster-dem":case"raster-array":return J=J.concat(kn({key:E,value:w,valueSpec:F[`source_${X.replace("-","_")}`],style:D.style,styleSpec:F,objectElementValidators:Rr})),J;case"geojson":if(J=kn({key:E,value:w,valueSpec:F.source_geojson,style:G,styleSpec:F,objectElementValidators:Rr}),"cluster"in w&&"clusterProperties"in w){if(!o.K(w.clusterProperties))return[new o.V(`${E}.clusterProperties`,w,`object expected, ${o.M(w)} found`)];for(const de in w.clusterProperties){const ye=w.clusterProperties[de];if(!Array.isArray(ye))return[new o.V(`${E}.clusterProperties.${de}`,ye,"array expected")];const[Ce,Le]=ye,Xe=typeof Ce=="string"?[Ce,["accumulated"],["get",de]]:Ce;J.push(...bt({key:`${E}.${de}.map`,value:Le,expressionContext:"cluster-map"})),J.push(...bt({key:`${E}.${de}.reduce`,value:Xe,expressionContext:"cluster-reduce"}))}}return J;case"video":return kn({key:E,value:w,valueSpec:F.source_video,style:G,styleSpec:F});case"image":return kn({key:E,value:w,valueSpec:F.source_image,style:G,styleSpec:F});case"canvas":return[new o.V(E,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return Ws({key:`${E}.type`,value:w.type,valueSpec:{values:Hs(F)}})}}function Hs(D){return D.source.reduce((w,E)=>{const F=D[E];return F.type.type==="enum"&&(w=w.concat(Object.keys(F.type.values||{}))),w},[])}function _r(D){const w=D.value,E=D.styleSpec,F=E.light,G=D.style;if(w===void 0)return[];if(!o.K(w))return[new o.V("light",w,`object expected, ${o.M(w)} found`)];let X=[];for(const J in w){const de=J.match(/^(.*)-transition$/),ye=J.match(/^(.*)-use-theme$/);X=X.concat(ye&&F[ye[1]]?Hn({key:J,value:w[J],valueSpec:{type:"string"},style:G,styleSpec:E}):de&&F[de[1]]&&F[de[1]].transition?Hn({key:J,value:w[J],valueSpec:E.transition,style:G,styleSpec:E}):F[J]?Hn({key:J,value:w[J],valueSpec:F[J],style:G,styleSpec:E}):[new o.V(J,w[J],`unknown property "${J}"`)])}return X}function nn(D){const w=D.value;if(!w)return[];const E=D.key;if(!o.K(w))return[new o.V(E,w,`object expected, ${o.M(w)} found`)];let F=[];const G=D.styleSpec,X=G["light-3d"],J=D.style,de=D.style.lights;for(const Le of["type","id"])if(!(Le in w))return F=F.concat([new o.V(E,w,`missing property "${Le}"`)]),F;if(!o.a2(w.type))return F=F.concat([new o.V(`${E}.type`,w.type,"string expected")]),F;if(de)for(let Le=0;Le[],array:Wt,boolean:function(D){const w=D.value,E=D.key;return o.a1(w)?[]:[new o.V(E,w,`boolean expected, ${o.M(w)} found`)]},number:us,color:function({key:D,value:w}){return o.a2(w)?o.a3.parseCSSColor(w)===null?[new o.V(D,w,`color expected, "${w}" found`)]:[]:[new o.V(D,w,`color expected, ${o.M(w)} found`)]},enum:Ws,filter:on,function:zt,layer:Gn,object:kn,source:cr,model:o.a9,light:_r,"light-3d":nn,terrain:Zn,fog:es,string:On,formatted:function(D){return On(D).length===0?[]:bt(D)},resolvedImage:function(D){return On(D).length===0?[]:bt(D)},projection:function(D){const w=D.value,E=D.styleSpec,F=E.projection,G=D.style;if(o.K(w)){let X=[];for(const J in w)X=X.concat(Hn({key:J,value:w[J],valueSpec:F[J],style:G,styleSpec:E}));return X}return o.a2(w)?[]:[new o.V("projection",w,`object or string expected, ${o.M(w)} found`)]},import:function(D){const w=D.key,{value:E,styleSpec:F}=D;if(!o.K(E))return[new o.V(w,E,"import must be an object")];const{data:G,...X}=E;Object.defineProperty(X,"__line__",{value:E.__line__,enumerable:!1});let J=kn(Object.assign({},D,{value:X,valueSpec:F.import}));return o.L(X.id)===""&&J.push(new o.V(`${D.key}.id`,X,"import id can't be an empty string")),G&&(J=J.concat(sn(G,F,{key:`${D.key}.data`}))),J},iconset:function(D){const w=D.value,E=D.key,F=D.styleSpec,G=D.style;if(!o.K(w))return[new o.V(E,w,"object expected")];if(!w.type)return[new o.V(E,w,'"type" is required')];const X=o.L(w.type);let J=[];if(J=J.concat(kn({key:E,value:w,valueSpec:F[`iconset_${X}`],style:G,styleSpec:F})),function(de,ye){return!(de!=="source"||!ye.source)}(X,w)){const de=G.sources&&G.sources[w.source],ye=de&&o.L(de.type);de?ye!=="raster-array"&&J.push(new o.V(E,w.source,`iconset cannot be used with a source of type ${String(ye)}, it only be used with a "raster-array" source type`)):J.push(new o.V(E,w.source,`source "${w.source}" not found`))}return J}};function Hn(D,w=!1){const E=D.value,F=D.valueSpec,G=D.styleSpec;if(F.expression){if(o.a6(o.L(E)))return zt(D);if(o.U(o.W(E)))return bt(D)}if(F.type&&ar[F.type]){const X=ar[F.type](D);return w===!0&&X.length>0&&Array.isArray(D.value)?bt(D):X}return kn(Object.assign({},D,{valueSpec:F.type?G[F.type]:F}))}function kn(D){const w=D.key,E=D.value,F=D.valueSpec||{},G=D.objectElementValidators||{},X=D.style,J=D.styleSpec;if(!o.K(E))return[new o.V(w,E,`object expected, ${o.M(E)} found`)];let de=[];for(const ye in E){const Ce=ye.split(".")[0];let Le;G[Ce]?Le=G[Ce]:F[Ce]?Le=Hn:G["*"]?Le=G["*"]:F["*"]&&(Le=Hn),Le?de=de.concat(Le({key:(w&&`${w}.`)+ye,value:E[ye],valueSpec:F[Ce]||F["*"],style:X,styleSpec:J,object:E,objectKey:ye},E)):de.push(new o.a5(w,E[ye],`unknown property "${ye}"`))}for(const ye in F){if(G[ye])continue;const Ce=F[ye];Ce.required&&Ce.default===void 0&&E[ye]===void 0&&de.push(new o.V(w,E,`missing required property "${ye}"`))}return de}function Un({key:D,value:w}){const E=On({key:D,value:w});if(E.length)return E;const F=w;return F.indexOf("{fontstack}")===-1&&E.push(new o.V(D,w,'"glyphs" url must include a "{fontstack}" token')),F.indexOf("{range}")===-1&&E.push(new o.V(D,w,'"glyphs" url must include a "{range}" token')),E}function sn(D,w=o.a8,E={}){return kn({key:E.key||"",value:D,valueSpec:Object.assign(w.$root,{"*":{type:"*"}}),styleSpec:w,style:D,objectElementValidators:{glyphs:Un}})}function un(D,w=o.a8){return Rs(sn(D,w))}const Ar=D=>Rs(cr(D)),fs=D=>Rs(_r(D)),ot=D=>Rs(nn(D)),mt=D=>Rs(Zn(D)),Nt=D=>Rs(es(D)),Pt=D=>Rs(function(w){const E=w.value,F=w.style,G=w.styleSpec,X=G.snow;if(E===void 0)return[];if(!o.K(E))return[new o.V("snow",E,`object expected, ${o.M(E)} found`)];let J=[];for(const de in E){const ye=de.match(/^(.*)-transition$/);J=J.concat(ye&&X[ye[1]]&&X[ye[1]].transition?Hn({key:de,value:E[de],valueSpec:G.transition,style:F,styleSpec:G}):X[de]?Hn({key:de,value:E[de],valueSpec:X[de],style:F,styleSpec:G}):[new o.a5(de,E[de],`unknown property "${de}"`)])}return J}(D)),ts=D=>Rs(function(w){const E=w.value,F=w.style,G=w.styleSpec,X=G.rain;if(E===void 0)return[];if(!o.K(E))return[new o.V("rain",E,`object expected, ${o.M(E)} found`)];let J=[];for(const de in E){const ye=de.match(/^(.*)-transition$/);J=J.concat(ye&&X[ye[1]]&&X[ye[1]].transition?Hn({key:de,value:E[de],valueSpec:G.transition,style:F,styleSpec:G}):X[de]?Hn({key:de,value:E[de],valueSpec:X[de],style:F,styleSpec:G}):[new o.a5(de,E[de],`unknown property "${de}"`)])}return J}(D)),ls=D=>Rs(Gn(D)),Is=D=>Rs(on(D)),ps=D=>Rs(rn(D)),Ht=D=>Rs(br(D)),Xs=D=>Rs(o.a9(D));function Rs(D){return D.slice().sort((w,E)=>w.line&&E.line?w.line-E.line:0)}function zn(D,w){let E=!1;if(w&&w.length)for(const F of w)F instanceof o.a5?o.w(F.message):(D.fire(new o.B(new Error(F.message))),E=!0);return E}const Qr=o.a8.light;let ma;class qr extends o.E{constructor(w,E="flat"){super(),this._transitionable=new o.aa(ma||(ma=new o.ab({anchor:new o.ac(Qr.anchor),position:new o.ad(Qr.position),color:new o.ac(Qr.color),intensity:new o.ac(Qr.intensity)}))),this.setLight(w,E),this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(w,E,F={}){this._validate(fs,w,F)||(this._transitionable.setTransitionOrValue(w),this.id=E)}updateTransitions(w){this._transitioning=this._transitionable.transitioned(w,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(w){this.properties=this._transitioning.possiblyEvaluate(w)}_validate(w,E,F){return(!F||F.validate!==!1)&&zn(this,w.call(un,Object.assign({value:E,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}const Zr=o.a8.terrain;let Jr=class extends o.E{constructor(D,w,E,F,G){super(),this.scope=E,this._transitionable=new o.aa(new o.ab({source:new o.ac(Zr.source),exaggeration:new o.ac(Zr.exaggeration)}),E,F),this._transitionable.setTransitionOrValue(D,F),this._transitioning=this._transitionable.untransitioned(),this.drapeRenderMode=w,this.worldview=G}get(){return this._transitionable.serialize()}set(D,w){this._transitionable.setTransitionOrValue(D,w)}updateTransitions(D){this._transitioning=this._transitionable.transitioned(D,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(D){this.properties=this._transitioning.possiblyEvaluate(D)}getExaggeration(D){return this._transitioning.possiblyEvaluate(new o.ae(D,{worldview:this.worldview})).get("exaggeration")}getAttenuationRange(){if(!this.isZoomDependent())return null;const D=this._transitionable._values.exaggeration;if(!D)return null;const w=D.value.expression;if(!w)return null;let E=-1,F=-1,G=1;for(const X of w.zoomStops)G=w.evaluate(new o.ae(X,{worldview:this.worldview})),G>.01?(E=X,F=-1):F=X;return G<.01&&E>0&&F>E?[E,F]:null}isZoomDependent(){const D=this._transitionable._values.exaggeration;return D!=null&&D.value!=null&&D.value.expression!=null&&D.value.expression instanceof o.af}};const ha=.05;function Fa(D,w,E,F){const G=o.aj(45,65,E),[X,J]=Fo(D,F);let de=1-Math.min(1,Math.exp((w-X)/(J-X)*-6));return de*=de*de,de=Math.min(1,1.00747*de),de*G*D.alpha}function Fo(D,w){const E=.5/Math.tan(.5*w);return[D.range[0]+E,D.range[1]+E]}function Xo(D,w,E,F,G){const X=o.ah([],[w,E,F],G.mercatorFogMatrix);return Fa(D,o.ai(X),G.pitch,G._fov)}function Vi(D,w,E,F,G,X,J){const de=[[E,F,0],[G,F,0],[G,X,0],[E,X,0]];let ye=Number.MAX_VALUE,Ce=-Number.MAX_VALUE;for(const Le of de){const Xe=o.ah([],Le,w),Ke=o.ai(Xe);ye=Math.min(ye,Ke),Ce=Math.max(Ce,Ke)}return[Fa(D,ye,J.pitch,J._fov),Fa(D,Ce,J.pitch,J._fov)]}const Ja=o.a8.fog;class Co extends o.E{constructor(w,E,F,G){super();const X=new o.ab({range:new o.ac(Ja.range),color:new o.ac(Ja.color),"color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"high-color":new o.ac(Ja["high-color"]),"high-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"space-color":new o.ac(Ja["space-color"]),"space-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new o.ac(Ja["horizon-blend"]),"star-intensity":new o.ac(Ja["star-intensity"]),"vertical-range":new o.ac(Ja["vertical-range"])});this._transitionable=new o.aa(X,F,new Map(G)),this.set(w,G),this._transitioning=this._transitionable.untransitioned(),this._transform=E,this.properties=new o.ak(X),this.scope=F}get state(){const w=this._transform,E=w.projection.name==="globe",F=o.al(w.zoom),G=this.properties.get("range"),X=[.5,3];return{range:E?[o.am(X[0],G[0],F),o.am(X[1],G[1],F)]:G,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(w,E,F={}){if(this._validate(Nt,w,F))return;const G=Object.assign({},w);for(const X of Object.keys(Ja))G[X]===void 0&&(G[X]=Ja[X].default);this._options=G,this._transitionable.setTransitionOrValue(this._options,E)}getOpacity(w){if(!this._transform.projection.supportsFog)return 0;const E=this.properties&&this.properties.get("color")||1;return(this._transform.projection.name==="globe"?1:o.aj(45,65,w))*E.a}getOpacityAtLatLng(w,E){return this._transform.projection.supportsFog?function(F,G,X){const J=o.ag.fromLngLat(G),de=X.elevation?X.elevation.getAtPointOrZero(J):0;return Xo(F,J.x,J.y,de,X)}(this.state,w,E):0}getOpacityForTile(w){if(!this._transform.projection.supportsFog)return[1,1];const E=this._transform.calculateFogTileMatrix(w.toUnwrapped());return Vi(this.state,E,0,0,o.an,o.an,this._transform)}getOpacityForBounds(w,E,F,G,X){return this._transform.projection.supportsFog?Vi(this.state,w,E,F,G,X,this._transform):[1,1]}getFovAdjustedRange(w){return this._transform.projection.supportsFog?Fo(this.state,w):[0,1]}isVisibleOnFrustum(w){if(!this._transform.projection.supportsFog)return!1;const E=[4,5,6,7];for(const F of E){const G=w.points[F];let X;if(G[2]>=0)X=G;else{const J=w.points[F-4];X=o.ao(J,G,J[2]/(J[2]-G[2]))}if(Xo(this.state,X[0],X[1],0,this._transform)>=ha)return!0}return!1}updateConfig(w){this._transitionable.setTransitionOrValue(this._options,new Map(w))}updateTransitions(w){this._transitioning=this._transitionable.transitioned(w,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(w){this.properties=this._transitioning.possiblyEvaluate(w)}_validate(w,E,F){return(!F||F.validate!==!1)&&zn(this,w.call(un,Object.assign({value:E,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}let Go,hi,Qo,Ao=class extends o.E{constructor(D,w,E,F){super();const G=Go||(Go=new o.ab({density:new o.ac(o.a8.snow.density),intensity:new o.ac(o.a8.snow.intensity),color:new o.ac(o.a8.snow.color),opacity:new o.ac(o.a8.snow.opacity),vignette:new o.ac(o.a8.snow.vignette),"vignette-color":new o.ac(o.a8.snow["vignette-color"]),"center-thinning":new o.ac(o.a8.snow["center-thinning"]),direction:new o.ac(o.a8.snow.direction),"flake-size":new o.ac(o.a8.snow["flake-size"])}));this._transitionable=new o.aa(G,E,new Map(F)),this.set(D,F),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak(G),this.scope=E}get state(){const D=this.properties.get("opacity"),w=this.properties.get("color"),E=this.properties.get("direction"),F=o.ap(E[0]),G=-Math.max(o.ap(E[1]),.01),X=[Math.cos(F)*Math.cos(G),Math.sin(F)*Math.cos(G),Math.sin(G)],J=this.properties.get("vignette"),de=this.properties.get("vignette-color");return de.a=J,{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(w.r,w.g,w.b,w.a*D),direction:X,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:de}}get(){return this._transitionable.serialize()}set(D,w,E={}){if(this._validate(Pt,D,E))return;const F=Object.assign({},D),G=o.a8.snow;for(const X of Object.keys(G))F[X]===void 0&&(F[X]=G[X].default);this._options=F,this._transitionable.setTransitionOrValue(this._options,w)}updateConfig(D){this._transitionable.setTransitionOrValue(this._options,new Map(D))}updateTransitions(D){this._transitioning=this._transitionable.transitioned(D,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(D){this.properties=this._transitioning.possiblyEvaluate(D)}_validate(D,w,E){return(!E||E.validate!==!1)&&zn(this,D.call(un,Object.assign({value:w,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}},_a=class extends o.E{constructor(D,w,E,F){super();const G=hi||(hi=new o.ab({density:new o.ac(o.a8.rain.density),intensity:new o.ac(o.a8.rain.intensity),color:new o.ac(o.a8.rain.color),opacity:new o.ac(o.a8.rain.opacity),vignette:new o.ac(o.a8.rain.vignette),"vignette-color":new o.ac(o.a8.rain["vignette-color"]),"center-thinning":new o.ac(o.a8.rain["center-thinning"]),direction:new o.ac(o.a8.rain.direction),"droplet-size":new o.ac(o.a8.rain["droplet-size"]),"distortion-strength":new o.ac(o.a8.rain["distortion-strength"])}));this._transitionable=new o.aa(G,E,new Map(F)),this.set(D,F),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak(G),this.scope=E}get state(){const D=this.properties.get("opacity"),w=this.properties.get("color"),E=this.properties.get("direction"),F=o.ap(E[0]),G=-Math.max(o.ap(E[1]),.01),X=[Math.cos(F)*Math.cos(G),Math.sin(F)*Math.cos(G),Math.sin(G)],J=this.properties.get("vignette-color");return J.a=this.properties.get("vignette"),{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(w.r,w.g,w.b,w.a*D),direction:X,centerThinning:this.properties.get("center-thinning"),dropletSize:this.properties.get("droplet-size"),distortionStrength:this.properties.get("distortion-strength"),vignetteColor:J}}get(){return this._transitionable.serialize()}set(D,w,E={}){if(this._validate(ts,D,E))return;const F=Object.assign({},D),G=o.a8.rain;for(const X of Object.keys(G))F[X]===void 0&&(F[X]=G[X].default);this._options=F,this._transitionable.setTransitionOrValue(this._options,w)}updateConfig(D){this._transitionable.setTransitionOrValue(this._options,new Map(D))}updateTransitions(D){this._transitioning=this._transitionable.transitioned(D,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(D){this.properties=this._transitioning.possiblyEvaluate(D)}_validate(D,w,E){return(!E||E.validate!==!1)&&zn(this,D.call(un,Object.assign({value:w,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}};class ir extends o.E{constructor(w,E,F,G){super(),this.scope=F,this._options=w,this.properties=new o.ak(E),this._transitionable=new o.aa(E,F,new Map(G)),this._transitionable.setTransitionOrValue(w.properties),this._transitioning=this._transitionable.untransitioned()}updateConfig(w){this._transitionable.setTransitionOrValue(this._options.properties,new Map(w))}updateTransitions(w){this._transitioning=this._transitionable.transitioned(w,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(w){this.properties=this._transitioning.possiblyEvaluate(w)}get(){return this._options.properties=this._transitionable.serialize(),this._options}set(w,E){this._options=w,this._transitionable.setTransitionOrValue(w.properties,E)}shadowsEnabled(){return!!this.properties&&this.properties.get("cast-shadows")===!0}}const li=()=>Qo||(Qo=new o.ab({color:new o.ac(o.a8.properties_light_ambient.color),"color-use-theme":new o.ac({type:"string",default:"default","property-type":"data-constant"}),intensity:new o.ac(o.a8.properties_light_ambient.intensity)}));let Eo;const gl=()=>Eo||(Eo=new o.ab({direction:new o.ar(o.a8.properties_light_directional.direction),color:new o.ac(o.a8.properties_light_directional.color),"color-use-theme":new o.ac({type:"string",default:"default","property-type":"data-constant"}),intensity:new o.ac(o.a8.properties_light_directional.intensity),"cast-shadows":new o.ac(o.a8.properties_light_directional["cast-shadows"]),"shadow-quality":new o.ac(o.a8.properties_light_directional["shadow-quality"]),"shadow-intensity":new o.ac(o.a8.properties_light_directional["shadow-intensity"]),"shadow-draw-before-layer":new o.ac(o.a8.properties_light_directional["shadow-draw-before-layer"])}));class ds{constructor(w,E,F){this.screenBounds=w,this.cameraPoint=F.getCameraPoint(),this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=E,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,F)}static createFromScreenPoints(w,E){let F,G;if(w instanceof o.P||typeof w[0]=="number"){const X=o.P.convert(w);F=[X],G=E.isPointAboveHorizon(X)}else{const X=o.P.convert(w[0]),J=o.P.convert(w[1]),de=X.add(J)._div(2);F=[X,J],G=o.as(X,J).every(ye=>E.isPointAboveHorizon(ye))&&E.isPointAboveHorizon(de)}return new ds(F,G,E)}isPointQuery(){return this.screenBounds.length===1}bufferedScreenGeometry(w){return o.as(this.screenBounds[0],this.screenBounds.length===1?this.screenBounds[0]:this.screenBounds[1],w)}bufferedCameraGeometry(w){const E=this.screenBounds[0],F=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],G=o.as(E,F,0,!1);return this.cameraPoint.y>F.y&&(this.cameraPoint.x>E.x&&this.cameraPoint.x=F.x?G[2]=this.cameraPoint:this.cameraPoint.x<=E.x&&(G[3]=this.cameraPoint)),o.at(G,w)}bufferedCameraGeometryGlobe(w){const E=this.screenBounds[0],F=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],G=o.as(E,F,w),X=this.cameraPoint.clone(),J=+(X.x>E.x)+ +(X.x>F.x);switch(3*(+(X.y>E.y)+ +(X.y>F.y))+J){case 0:G[0]=X,G[4]=X.clone();break;case 1:G.splice(1,0,X);break;case 2:G[1]=X;break;case 3:G.splice(4,0,X);break;case 5:G.splice(2,0,X);break;case 6:G[3]=X;break;case 7:G.splice(3,0,X);break;case 8:G[2]=X}return G}containsTile(w,E,F,G=0){const X=Math.max(w.queryPadding,w.evaluateQueryRenderedFeaturePadding())/E._pixelsPerMercatorPixel+1,J=F?this._bufferedCameraMercator(X,E):this._bufferedScreenMercator(X,E);let de=w.tileID.wrap+(J.unwrapped?G:0);const ye=J.polygon.map(jt=>o.au(w.tileTransform,jt,de));if(!o.av(ye,0,0,o.an,o.an))return;de=w.tileID.wrap+(this.screenGeometryMercator.unwrapped?G:0);const Ce=this.screenGeometryMercator.polygon.map(jt=>o.aw(w.tileTransform,jt,de)),Le=Ce.map(jt=>new o.P(jt[0],jt[1])),Xe=E.getFreeCameraOptions().position||new o.ag(0,0,0),Ke=o.aw(w.tileTransform,Xe,de),st=Ce.map(jt=>{const wt=o.ax(jt,jt,Ke);return o.ay(wt,wt),new o.az(Ke,wt)}),dt=o.aA(w,1,E.zoom)*E._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:Le,tilespaceRays:st,bufferedTilespaceGeometry:ye,bufferedTilespaceBounds:(it=o.aB(ye),it.min.x=o.aC(it.min.x,0,o.an),it.min.y=o.aC(it.min.y,0,o.an),it.max.x=o.aC(it.max.x,0,o.an),it.max.y=o.aC(it.max.y,0,o.an),it),tile:w,tileID:w.tileID,pixelToTileUnitsFactor:dt};var it}_bufferedScreenMercator(w,E){const F=ya(w);if(this._screenRaycastCache[F])return this._screenRaycastCache[F];{let G;return G=E.projection.name==="globe"?this._projectAndResample(this.bufferedScreenGeometry(w),E):{polygon:this.bufferedScreenGeometry(w).map(X=>E.pointCoordinate3D(X)),unwrapped:!0},this._screenRaycastCache[F]=G,G}}_bufferedCameraMercator(w,E){const F=ya(w);if(this._cameraRaycastCache[F])return this._cameraRaycastCache[F];{let G;return G=E.projection.name==="globe"?this._projectAndResample(this.bufferedCameraGeometryGlobe(w),E):{polygon:this.bufferedCameraGeometry(w).map(X=>E.pointCoordinate3D(X)),unwrapped:!0},this._cameraRaycastCache[F]=G,G}}_projectAndResample(w,E){const F=function(X,J){const de=o.aD([],J.pixelMatrix,J.globeMatrix),ye=[0,-o.aF,0,1],Ce=[0,o.aF,0,1],Le=[0,0,0,1];o.aE(ye,ye,de),o.aE(Ce,Ce,de),o.aE(Le,Le,de);const Xe=new o.P(ye[0]/ye[3],ye[1]/ye[3]),Ke=new o.P(Ce[0]/Ce[3],Ce[1]/Ce[3]),st=o.aG(X,Xe)&&ye[3]1?Gr(X.slice(0,jt),J):[],Vt=jtnew o.P(ji(_s.x),_s.y)),Vt=Vt.map(_s=>new o.P(ji(_s.x),_s.y));const Ct=[...Bt];Ct.length===0&&Ct.push(Vt[Vt.length-1]);const Ss=o.am(Ct[Ct.length-1].y,(Vt.length===0?Bt[0]:Vt[0]).y,wt);let rs;return rs=st?[new o.P(0,Ss),new o.P(0,0),new o.P(1,0),new o.P(1,Ss)]:[new o.P(1,Ss),new o.P(1,1),new o.P(0,1),new o.P(0,Ss)],Ct.push(...rs),Vt.length===0?Ct.push(Bt[0]):Ct.push(...Vt),{polygon:Ct.map(_s=>new o.ag(_s.x,_s.y)),unwrapped:!1}}(w,E);if(F)return F;const G=function(X,J){let de=!1,ye=-1/0,Ce=0;for(let Xe=0;Xeye&&(ye=X[Xe].x,Ce=Xe);for(let Xe=0;Xe.5&&(st.x{Xe.x-=1}),{polygon:X,unwrapped:de}}(Gr(w,E).map(X=>new o.P(ji(X.x),X.y)),E);return{polygon:G.polygon.map(X=>new o.ag(X.x,X.y)),unwrapped:G.unwrapped}}}function Gr(D,w){return o.aI(D,E=>{const F=w.pointCoordinate3D(E);E.x=F.x,E.y=F.y},1/256)}function ji(D){return D<0?1+D%1:D%1}function ya(D){return 100*D|0}function Wi(D,w,E){try{w=function(G){if(!G.variants)return G;if(!Array.isArray(G.variants))throw new Error("variants must be an array");for(const X of G.variants){if(X==null||typeof X!="object"||X.constructor!==Object)throw new Error("variant must be an object");if(!Array.isArray(X.capabilities))throw new Error("capabilities must be an array");if(X.capabilities.length===1&&X.capabilities[0]==="meshopt")return Object.assign(G,X)}return G}(w)}catch(G){return new Error("Failed to process TileJSON variants",{cause:G})}const F=o.aJ(Object.assign({},w,D),["tilejson","tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds","extra_bounds","scheme","tileSize","encoding","vector_layers","raster_layers","worldview_options","worldview_default","worldview"]);return D.url&&w.tiles&&D.tiles&&(F.tiles=w.tiles),F.tiles=E.canonicalizeTileset(F,D.url),F}function wi(D,w,E,F,G){const X=function(de,ye){if(de)return G(de);if(ye){D.url&&ye.tiles&&D.tiles&&delete D.tiles;const Ce=Wi(D,ye,w);if(Ce instanceof Error)return G(Ce);G(null,Ce)}},J=function(de,ye,Ce){if(!de)return null;if(!ye&&!Ce)return de;Ce=Ce||de.worldview_default;const Le=Object.values(de.language||{});if(Le.length===0)return null;const Xe=Object.values(de.worldview||{});if(Xe.length===0)return null;const Ke=Le.every(dt=>dt===ye),st=Xe.every(dt=>dt===Ce);return Ke&&st?de:ye in(de.language_options||{})||Ce in(de.worldview_options||{})?null:de.language_options&&de.worldview_options?de:null}(D.data,E,F);return J?o.o.frame(()=>X(null,J)):D.url?o.m(w.transformRequest(w.normalizeSourceURL(D.url,null,E,F),o.R.Source),X):o.o.frame(()=>{const{data:de,...ye}=D;X(null,ye)})}function di(D,w){const E=Math.pow(2,w.z),F=Math.floor(o.aH(D.getWest())*E),G=Math.floor(o.aL(D.getNorth())*E),X=Math.ceil(o.aH(D.getEast())*E),J=Math.ceil(o.aL(D.getSouth())*E);return w.x>=F&&w.x=G&&w.ythis.maxzoom||w.z{this._tileJSONRequest=null,this._loaded=!0,J?(E&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${E}`),F&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${F}`),this.fire(new o.B(J))):de&&(this._setTileJSON(de),je(de.tiles,this.map._requestManager._customAccessToken),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),w&&w(J)};this.provider=this._options.provider;const X=function(J){if("provider"in J&&!J.provider)return null;let de=J.provider;if(!de&&"url"in J&&J.url&&(de=o.aM(J.url)),!de)return null;const ye=o.g.TILE_PROVIDER_URLS[de];if(!ye)return null;let Ce;try{Ce=new URL(ye,o.g.API_URL).href}catch{return o.w(`TileProvider "${de}" has an invalid URL: "${ye}"`),null}return{name:de,url:Ce}}(this._options);if(this.provider&&!X)return this._loaded=!0,this.fire(new o.B(new Error(`TileProvider "${this.provider}" is not registered`))),void(w&&w());this._tileJSONRequest=X?this._loadWithProvider(X,G):wi(this._options,this.map._requestManager,E,F,G)}_loadWithProvider(w,E){this.provider=w.name;const F=new AbortController,G=this._options.url&&!this._options.tiles?this.map._requestManager.transformRequest(this._options.url,o.R.Source):void 0,X=G?Object.assign({},this._options,{url:G.url}):this._options;return this.dispatcher.broadcast("loadTileProvider",{name:w.name,url:w.url,source:this.id,scope:this.scope,type:this.type,options:X,request:G},(J,de)=>{if(F.signal.aborted)return;if(J)return void E(J);const ye=de?de.find(Ce=>Ce!=null):null;if(ye){const Ce=Wi(this._options,ye,this.map._requestManager);Ce instanceof Error?E(Ce):E(null,Ce)}else E(null,{tiles:this._options.tiles})}),{cancel:()=>{F.abort()}}}_setTileJSON(w){if(Object.assign(this,w),this.hasWorldviews=!!w.worldview_options,w.worldview_default&&(this.worldviewDefault=w.worldview_default),w.vector_layers){this.vectorLayers=w.vector_layers,this.vectorLayerIds=[],this.localizableLayerIds=new Set;for(const E of w.vector_layers)this.vectorLayerIds.push(E.id),w.worldview&&w.worldview[E.source]&&this.localizableLayerIds.add(E.id)}this.tileBounds=Dc.fromTileJSON(w)}loaded(){return this._loaded}hasTile(w){return!this.tileBounds||this.tileBounds.contains(w.canonical)}onAdd(w){this.map=w,this.load()}reload(){this.cancelTileJSONRequest();const w=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(w))}setTiles(w){return this._options.tiles=w,this.reload(),this}setUrl(w){return this.url=w,this._options.url=w,this.reload(),this}onRemove(w){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}loadTile(w,E){const F=w.tileID.canonical.url(this.tiles,this.scheme),G=this.map._requestManager.normalizeTileURL(F),X=this.map._requestManager.transformRequest(G,o.R.Tile),J=this.map.style?this.map.style.getLut(this.scope):null,de=J?{image:J.image.clone()}:null,ye={request:X,data:void 0,uid:w.uid,tileID:w.tileID,tileZoom:w.tileZoom,zoom:w.tileID.overscaledZ,maxZoom:this.maxzoom,lut:de,tileSize:this.tileSize*w.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,renderSourceType:w.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:w.isExtraShadowCaster,tessellationStep:this.map._tessellationStep,scaleFactor:this.map.getScaleFactor(),worldview:this.map.getWorldview()||this.worldviewDefault,indoor:this.map.getIndoorTileOptions(this.id,this.scope)};if(this.hasWorldviews&&o.e(F)&&(ye.localizableLayerIds=this.localizableLayerIds),ye.request.collectResourceTiming=this._collectResourceTiming,w.actor&&w.state!=="expired")w.state==="loading"?w.reloadCallback=E:w.request=w.actor.send("reloadTile",ye,Ce.bind(this));else if(w.actor=this._tileWorkers[G]=this._tileWorkers[G]||this.dispatcher.getActor(),this.dispatcher.ready||this.provider)w.request=w.actor.send("loadTile",ye,Ce.bind(this),void 0,!0);else{const Le=o.aO.call({deduped:this._deduped},ye,(Xe,Ke)=>{if(Xe||!Ke)Ce.call(this,Xe);else{const st=o.aP(Ke.responseHeaders);ye.data={rawData:Ke.rawData.slice(0),expires:st.expires,cacheControl:st.cacheControl},w.actor&&w.actor.send("loadTile",ye,Ce.bind(this),void 0,!0)}},!0);w.request={cancel:Le}}function Ce(Le,Xe){return delete w.request,w.aborted?E(null):Le?E(Le):(Xe&&Xe.resourceTiming&&(w.resourceTiming=Xe.resourceTiming),this.map._refreshExpiredTiles&&Xe&&w.setExpiryData(Xe),w.loadVectorData(Xe,this.map.painter),o.aQ(this.dispatcher),E(null,Xe),void(w.reloadCallback&&(this.loadTile(w,w.reloadCallback),w.reloadCallback=null)))}}abortTile(w){w.request&&(w.request.cancel(),delete w.request),w.actor&&w.actor.send("abortTile",{uid:w.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(w,E){w.actor&&w.actor.send("removeTile",{uid:w.uid,type:this.type,source:this.id,scope:this.scope}),w.destroy()}hasTransition(){return!1}afterUpdate(){this._tileWorkers={}}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}class Vp extends o.E{constructor(w,E,F,G){super(),this.id=w,this.dispatcher=F,this.setEventedParent(G),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=Object.assign({type:"raster"},E),Object.assign(this,o.aJ(E,["url","scheme","tileSize"]))}load(w){this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"}));const E=this.map.getWorldview();this._tileJSONRequest=wi(this._options,this.map._requestManager,null,E,(F,G)=>{this._tileJSONRequest=null,this._loaded=!0,F?this.fire(new o.B(F)):G&&(Object.assign(this,G),G.raster_layers&&(this.rasterLayers=G.raster_layers,this.rasterLayerIds=this.rasterLayers.map(X=>X.id)),this.tileBounds=Dc.fromTileJSON(G),je(G.tiles),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),w&&w(F)})}loaded(){return this._loaded}onAdd(w){this.map=w,this.load()}reload(){this.cancelTileJSONRequest();const w=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(w))}setTiles(w){return this._options.tiles=w,this.reload(),this}setUrl(w){return this.url=w,this._options.url=w,this.reload(),this}onRemove(w){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}hasTile(w){return!this.tileBounds||this.tileBounds.contains(w.canonical)}loadTile(w,E){const F=o.o.devicePixelRatio>=2,G=this.map._requestManager.normalizeTileURL(w.tileID.canonical.url(this.tiles,this.scheme),F,this.tileSize);w.request=o.n(this.map._requestManager.transformRequest(G,o.R.Tile),(X,J,de)=>{if(delete w.request,w.aborted)return w.state="unloaded",E(null);if(X)return w.state="errored",E(X);if(!J)return E(null);const ye=o.aP(de);this.map._refreshExpiredTiles&&w.setExpiryData(ye),w.setTexture(J,this.map.painter),w.state="loaded",o.aQ(this.dispatcher),E(null)})}abortTile(w,E){w.request&&(w.request.cancel(),delete w.request),E&&E()}unloadTile(w,E){w.texture&&w.texture instanceof o.T?(w.destroy(!1),w.texture&&w.texture instanceof o.T&&this.map.painter.saveTileTexture(w.texture)):w.destroy(),E&&E()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}function vy([D,w],E,F,{scaled:G=!0}={}){const{tileSize:X,buffer:J}=F,{x:de,y:ye,z:Ce}=E;if(!isFinite(de)||!isFinite(ye)||!isFinite(Ce))throw new Error("Invalid MRT header");const Le=2**Ce,Xe=Le*o.aH(D),Ke=Le*o.aL(w);return function([st,dt],it,{scaled:jt=!0}={}){if(!it)throw new Error("bandView is undefined");const{data:wt,tileSize:Bt,buffer:Vt,offset:Ct,scale:Ss,dimension:rs}=it;if(st<-Vt||st>Bt+Vt||dt<-Vt||dt>Bt+Vt)throw new Error(`Point (${st}, ${dt}) out of bounds for tileSize=${Bt}, buffer=${Vt}`);const _s=(dt+Vt)*(Bt+2*Vt)+(st+Vt);if(new Uint32Array(wt.buffer)[_s]===4294967295)return null;let Gt=[];Gt=jt?[]:new it.data.constructor(rs);for(let ss=0;ss{if(delete w.request,w.aborted)return w.state="unloaded",E(null);if(de)return de.name==="AbortError"?void 0:(w.state="errored",E(de));if(this.map._refreshExpiredTiles&&ye){const Le=o.aP(Ce);w.setExpiryData(Le)}if(this.partial&&w.state!=="expired")w.state="empty";else if(!this.partial){if(!ye)return E(null);w.state="loaded",w._isHeaderLoaded=!0,w._mrt=ye}E(null)};w.request=this.partial?w.fetchHeader(void 0,J.bind(this)):w.actor.send("loadTile",X,J.bind(this),void 0,!0)}abortTile(w){w.request&&(w.request.cancel(),delete w.request),w.actor&&w.actor.send("abortTile",{uid:w.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(w,E){const F=w.texturePerLayer;if(w.flushAllQueues(),F.size){w.destroy(!1);for(const G of F.values())this.map.painter.saveTileTexture(G)}else w.destroy()}prepareTile(w,E,F,G){w._isHeaderLoaded&&(w.state!=="empty"&&(w.state="reloading"),w.fetchBandForRender(E,F,G,(X,J)=>{X?(w.state="errored",this.fire(new o.B(X))):J&&(w._isHeaderLoaded=!0,w.setTexturePerLayer(F,J,this.map.painter),w.state="loaded"),this.triggerRepaint(w)}))}getInitialBand(w){if(!this.rasterLayers)return 0;const E=this.rasterLayers.find(({id:X})=>X===w),F=E&&E.fields,G=F&&F.bands&&F.bands;return G?G[0]:0}getTextureDescriptor(w,E,F){if(!w)return;const G=E.sourceLayer||this.rasterLayerIds&&this.rasterLayerIds[0];if(!G)return;let X=null;E instanceof o.aS?X=E.paint.get("raster-array-band"):E instanceof o.aT&&(X=E.paint.get("raster-particle-array-band"));const J=X||this.getInitialBand(G);if(J==null)return;if(!w.textureDescriptorPerLayer.get(E.id))return void this.prepareTile(w,G,E.id,J);if(w.updateNeeded(E.id,J)&&!F)return;const de=w.textureDescriptorPerLayer.get(E.id);return Object.assign({},de,{texture:w.texturePerLayer.get(E.id)})}getImages(w,E){const F=new Map;for(const G of w)for(const X of E){const[J,de]=X.split("/"),ye=G.getLayer(J);if(!ye||!ye.hasBand(de)||!ye.hasDataForBand(de))continue;const{bytes:Ce,tileSize:Le,buffer:Xe}=ye.getBandView(de),Ke=Le+2*Xe,st={data:new o.q({width:Ke,height:Ke},Ce),pixelRatio:2,sdf:!1,usvg:!1,version:0};F.set(X,st)}return F}queryRasterArrayValueByBandId(w,E,F){const G=E._mrt;return new Promise(X=>{const J={},de=new Set;for(const[ye,Ce]of Object.entries(G.layers)){if(F.layerName&&ye!==F.layerName)continue;const Le={};J[ye]=Le;for(const{bands:Xe}of Ce.dataIndex)for(const Ke of Xe)F.bands&&!F.bands.includes(Ke)||(de.add(o.F(ye,Ke)),E.fetchBand(ye,null,Ke,st=>{o.o.frame(()=>{Le[Ke]=st?null:vy([w.lng,w.lat],G,Ce.getBandView(Ke)),de.delete(o.F(ye,Ke)),de.size===0&&X(J)})},!1))}de.size===0&&X(J)})}_loadTileForQuery(w,E){if(this._loadTileLoaded[w.uid])return void E(null,w._mrt);if(this._loadTilePending[w.uid])return void this._loadTilePending[w.uid].push(E);this._loadTilePending[w.uid]=[E];const F=this.map._requestManager.normalizeTileURL(w.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),G=this.map._requestManager.transformRequest(F,o.R.Tile);w.actor.send("loadTile",{request:G,uid:w.uid,tileID:w.tileID,type:this.type,source:this.id,scope:this.scope,partial:!1},(X,J,de)=>{if(X)return this._loadTilePending[w.uid].forEach(ye=>ye(X,null)),void delete this._loadTilePending[w.uid];if(!J)return this._loadTilePending[w.uid].forEach(ye=>ye(null,null)),void delete this._loadTilePending[w.uid];if(this.map._refreshExpiredTiles&&J){const ye=o.aP(de);w.setExpiryData(ye)}w._mrt=J,w._isHeaderLoaded=!0,w.state="loaded",this._loadTilePending[w.uid].forEach(ye=>ye(null,J)),this._loadTileLoaded[w.uid]=!0,delete this._loadTilePending[w.uid]},void 0,!0)}queryRasterArrayValueByAllBands(w,E,F){return new Promise((G,X)=>{this._loadTileForQuery(E,(J,de)=>{J?X(J):G(de?this.queryRasterArrayValueByBandId(w,E,F):null)})})}queryRasterArrayValue(w,E){const F=o.aU.convert(w),G=this.findLoadedParent(F);return G&&G._mrt?E.bands||!this.partial?this.queryRasterArrayValueByBandId(F,G,E):this.queryRasterArrayValueByAllBands(F,G,E):Promise.resolve(null)}findLoadedParent(w){const E=o.ag.fromLngLat(w,this.map.transform.tileSize),F=this.maxzoom+1,G=1<0&&(de[new o.aR(D.overscaledZ,G,w.z,F,w.y-1).key]={backfilled:!1},de[new o.aR(D.overscaledZ,D.wrap,w.z,w.x,w.y-1).key]={backfilled:!1},de[new o.aR(D.overscaledZ,J,w.z,X,w.y-1).key]={backfilled:!1}),w.y+1{if(this._loaded=!0,this._pendingLoad=null,F)this.fire(new o.B(F));else{const X={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&G&&G.resourceTiming&&G.resourceTiming[this.id]&&(X.resourceTiming=G.resourceTiming[this.id]),D&&(this._partialReload=!0),this.fire(new o.C("data",X)),this._partialReload=!1,this._metadataFired=!0}this._coalesce&&(this._updateWorkerData(D),this._coalesce=!1)})}loaded(){return this._loaded}reload(){const D=o.F(this.id,this.scope);this.map.style.clearSource(D),this._updateWorkerData()}loadTile(D,w){const E=D.actor?"reloadTile":"loadTile";D.actor=this.actor;const F=this.map.style?this.map.style.getLut(this.scope):null,G=F?{image:F.image.clone()}:null,X=this._partialReload,J={type:this.type,uid:D.uid,tileID:D.tileID,tileZoom:D.tileZoom,zoom:D.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,lut:G,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:D.isExtraShadowCaster,scaleFactor:this.map.getScaleFactor(),partial:X,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};D.request=this.actor.send(E,J,(de,ye)=>X&&!ye?(D.state="loaded",w(null)):(delete D.request,D.destroy(!1),D.aborted?w(null):de?w(de):(D.loadVectorData(ye,this.map.painter,E==="reloadTile"),w(null))),void 0,E==="loadTile")}abortTile(D){D.request&&(D.request.cancel(),delete D.request),D.aborted=!0}unloadTile(D,w){this.actor.send("removeTile",{uid:D.uid,type:this.type,source:this.id,scope:this.scope}),D.destroy()}onRemove(D){this._pendingLoad&&this._pendingLoad.cancel()}serialize(){return Object.assign({},this._options,{type:this.type,data:this._data})}hasTransition(){return!1}},video:class extends o.aV{constructor(D,w,E,F){super(D,w,E,F),this.roundZoom=!0,this.type="video",this.options=w}load(){this._loaded=!1;const D=this.options;this.urls=[];for(const w of D.urls)this.urls.push(this.map._requestManager.transformRequest(w,o.R.Source).url);o.aW(this.urls,(w,E)=>{this._loaded=!0,w?this.fire(new o.B(w)):E&&(this.video=E,this.video.loop=!0,this.video.setAttribute("playsinline",""),this.video.addEventListener("playing",()=>{this.map.triggerRepaint()}),this.map&&this.video.play(),this._finishLoading())})}pause(){this.video&&this.video.pause()}play(){this.video&&this.video.play()}seek(D){if(this.video){const w=this.video.seekable;Dw.end(0)?this.fire(new o.B(new o.V(`sources.${this.id}`,null,`Playback for this video can be set only between the ${w.start(0)} and ${w.end(0)}-second mark.`))):this.video.currentTime=D}}getVideo(){return this.video}onAdd(D){this.map||(this.map=D,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 D=this.map.painter.context,w=D.gl;this.texture?this.video.paused||(this.texture.bind(w.LINEAR,w.CLAMP_TO_EDGE),w.texSubImage2D(w.TEXTURE_2D,0,0,0,w.RGBA,w.UNSIGNED_BYTE,this.video)):(this.texture=new o.T(D,this.video,w.RGBA8),this.texture.bind(w.LINEAR,w.CLAMP_TO_EDGE),this.width=this.video.videoWidth,this.height=this.video.videoHeight),this._prepareData(D)}serialize(){return{type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}},image:o.aV,model:o.aY,"batched-model":class extends o.E{constructor(D,w,E,F){super(),this.type="batched-model",this.id=D,this.tileSize=512,this._options=w,this.tiles=this._options.tiles,this.maxzoom=w.maxzoom||19,this.minzoom=w.minzoom||0,this.roundZoom=!0,this.usedInConflation=!0,this.dispatcher=E,this.reparseOverscaled=!1,this.scheme="xyz",this._loaded=!1,this.setEventedParent(F)}onAdd(D){this.map=D,this.load()}reload(){this.cancelTileJSONRequest();const D=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(D))}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}load(D){this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"}));const w=Array.isArray(this.map._language)?this.map._language.join():this.map._language,E=this.map.getWorldview();this._tileJSONRequest=wi(this._options,this.map._requestManager,w,E,(F,G)=>{this._tileJSONRequest=null,this._loaded=!0,F?(w&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${w}`),E&&E.length!==2&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${E}`),this.fire(new o.B(F))):G&&(Object.assign(this,G),G.bounds&&(this.tileBounds=new Dc(G.bounds,this.minzoom,this.maxzoom)),je(G.tiles,this.map._requestManager._customAccessToken),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),D&&D(F)})}hasTransition(){return!1}hasTile(D){return!this.tileBounds||this.tileBounds.contains(D.canonical)}loaded(){return this._loaded}loadTile(D,w){const E=this.map._requestManager.normalizeTileURL(D.tileID.canonical.url(this.tiles,this.scheme)),F={request:this.map._requestManager.transformRequest(E,o.R.Tile),data:void 0,uid:D.uid,tileID:D.tileID,tileZoom:D.tileZoom,zoom:D.tileID.overscaledZ,tileSize:this.tileSize*D.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,showCollisionBoxes:this.map.showCollisionBoxes,renderSourceType:D.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,pixelRatio:o.o.devicePixelRatio,promoteId:this.promoteId};if(D.actor&&D.state!=="expired")if(D.state==="loading")D.reloadCallback=w;else{if(D.buckets){const X=Object.values(D.buckets);for(const J of X)J.dirty=!0;return void(D.state="loaded")}D.request=D.actor.send("reloadTile",F,G.bind(this))}else D.actor=this.dispatcher.getActor(),D.request=D.actor.send("loadTile",F,G.bind(this),void 0,!0);function G(X,J){return D.aborted?w(null):X&&X.status!==404?w(X):(this.map._refreshExpiredTiles&&J&&D.setExpiryData(J),D.loadModelData(J,this.map.painter),D.state="loaded",void w(null))}}serialize(){return Object.assign({},this._options)}},canvas:class extends o.aV{constructor(D,w,E,F){super(D,w,E,F),w.coordinates?Array.isArray(w.coordinates)&&w.coordinates.length===4&&!w.coordinates.some(G=>!Array.isArray(G)||G.length!==2||G.some(X=>typeof X!="number"))||this.fire(new o.B(new o.V(`sources.${D}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new o.B(new o.V(`sources.${D}`,null,'missing required property "coordinates"'))),w.animate&&typeof w.animate!="boolean"&&this.fire(new o.B(new o.V(`sources.${D}`,null,'optional "animate" property must be a boolean value'))),w.canvas?typeof w.canvas=="string"||w.canvas instanceof HTMLCanvasElement||this.fire(new o.B(new o.V(`sources.${D}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new o.B(new o.V(`sources.${D}`,null,'missing required property "canvas"'))),this.options=w,this.animate=w.animate===void 0||w.animate}load(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new o.B(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint()},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1)},this._finishLoading())}getCanvas(){return this.canvas}onAdd(D){this.map=D,this.load(),this.canvas&&this.animate&&this.play()}onRemove(D){this.pause()}prepare(){let D=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,D=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,D=!0),this._hasInvalidDimensions()||Object.keys(this.tiles).length===0)return;const w=this.map.painter.context;this.texture?!D&&!this._playing||this.texture instanceof o.aX||this.texture.update(this.canvas,{premultiply:!0}):this.texture=new o.T(w,this.canvas,w.gl.RGBA8,{premultiply:!0}),this._prepareData(w)}serialize(){return{type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const D of[this.canvas.width,this.canvas.height])if(isNaN(D)||D<=0)return!0;return!1}},custom:class extends o.E{constructor(D,w,E,F){super(),this.id=D,this.type="custom",this._dataType="raster",this._dispatcher=E,this._implementation=w,this.setEventedParent(F),this.scheme="xyz",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this._loaded=!1,this.roundZoom=!0,this._implementation||this.fire(new o.B(new Error(`Missing implementation for ${this.id} custom source`))),this._implementation.loadTile||this.fire(new o.B(new Error(`Missing loadTile implementation for ${this.id} custom source`))),this._implementation.bounds&&(this.tileBounds=new Dc(this._implementation.bounds,this.minzoom,this.maxzoom));const G=w;G.update=this._update.bind(this),G.clearTiles=this._clearTiles.bind(this),G.coveringTiles=this._coveringTiles.bind(this),Object.assign(this,o.aJ(w,["dataType","scheme","minzoom","maxzoom","tileSize","attribution","minTileCacheSize","maxTileCacheSize"]))}serialize(){return o.aJ(this,["type","scheme","minzoom","maxzoom","tileSize","attribution"])}load(){this._loaded=!0,this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))}loaded(){return this._loaded}onAdd(D){this.map=D,this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"})),this._implementation.onAdd&&this._implementation.onAdd(D),this.load()}onRemove(D){this._implementation.onRemove&&this._implementation.onRemove(D)}hasTile(D){if(this._implementation.hasTile){const{x:w,y:E,z:F}=D.canonical;return this._implementation.hasTile({x:w,y:E,z:F})}return!this.tileBounds||this.tileBounds.contains(D.canonical)}loadTile(D,w){const{x:E,y:F,z:G}=D.tileID.canonical,X=new AbortController,J=Promise.resolve(this._implementation.loadTile({x:E,y:F,z:G},{signal:X.signal})).then((function(de){return delete D.request,D.aborted?(D.state="unloaded",w(null)):de===void 0?(D.state="errored",w(null)):de===null?(this.loadTileData(D,{width:this.tileSize,height:this.tileSize,data:null}),D.state="loaded",w(null)):function(ye){return ye instanceof ImageData||ye instanceof HTMLCanvasElement||ye instanceof ImageBitmap||ye instanceof HTMLImageElement}(de)?(this.loadTileData(D,de),D.state="loaded",void w(null)):(D.state="errored",w(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`)))}).bind(this)).catch(de=>{de.name!=="AbortError"&&(D.state="errored",w(de))});J.cancel=()=>X.abort(),D.request=J}loadTileData(D,w){D.setTexture(w,this.map.painter)}unloadTile(D,w){if(D.texture&&D.texture instanceof o.T?(D.destroy(!1),D.texture&&D.texture instanceof o.T&&this.map.painter.saveTileTexture(D.texture)):D.destroy(),this._implementation.unloadTile){const{x:E,y:F,z:G}=D.tileID.canonical;this._implementation.unloadTile({x:E,y:F,z:G})}w&&w()}abortTile(D,w){D.request&&D.request.cancel&&(D.request.cancel(),delete D.request),w&&w()}hasTransition(){return!1}_coveringTiles(){return this.map.transform.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,roundZoom:this.roundZoom}).map(D=>({x:D.canonical.x,y:D.canonical.y,z:D.canonical.z}))}_clearTiles(){const D=o.F(this.id,this.scope);this.map.style.clearSource(D)}_update(){this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))}}},Hp=function(D,w,E,F){const G=new il[w.type](D,w,E,F);if(G.id!==D)throw new Error(`Expected Source id to be ${D} instead of ${G.id}`);return o.aZ(["load","abort","unload","serialize","prepare"],G),G};function fg(D,w,E=""){return`${E}:${w.id||""}:${w.layer.id}:${function(F){if("layerId"in F)return`layer:${F.layerId}`;{const{featuresetId:G,importId:X}=F;return`featureset:${G}${X?`:import:${X}`:""}`}}(D.target)}`}function Lh(D,w,E,F=""){if(D.uniqueFeatureID){const G=fg(D,w,F);if(E.has(G))return!0;E.add(G)}return!1}function by(D,w,E,F,G=!1,X=void 0){const J=w.sourceCache.transform,de=w.sourceCache.tilesIn(D,w.has3DLayers,G);de.sort(Ex);const ye=[];for(const Ce of de){const Le=Ce.tile.queryRenderedFeatures(w,Ce,E,F,J,G,X);Object.keys(Le).length&&ye.push({wrappedTileID:Ce.tile.tileID.wrapped().key,queryResults:Le})}for(const Ce in w.layers){const Le=w.layers[Ce];if(Le.styleLayer){const Xe=Le.styleLayer.queryRenderedFeatures(D,w.sourceCache,F);Object.keys(Xe).length&&ye.push({wrappedTileID:0,queryResults:Xe})}}return ye.length===0?{}:function(Ce){const Le={},Xe={};for(const Ke of Ce){const st=Ke.queryResults,dt=Ke.wrappedTileID,it=Xe[dt]=Xe[dt]||{};for(const jt in st){const wt=st[jt],Bt=it[jt]=it[jt]||{},Vt=Le[jt]=Le[jt]||[];for(const Ct of wt)Bt[Ct.featureIndex]||(Bt[Ct.featureIndex]=!0,Vt.push(Ct))}}return Le}(ye)}function qo(D,w,E,F,G,X){const J={},de=F.queryRenderedSymbols(D),ye=[];for(const Ce of Object.keys(de).map(Number))ye.push(G[Ce]);ye.sort(Ex);for(const Ce of ye){const Le=Ce.featureIndex.lookupSymbolFeatures(de[Ce.bucketInstanceId],Ce.bucketIndex,Ce.sourceLayerIndex,w,E,X);for(const Xe in Le){const Ke=J[Xe]=J[Xe]||[],st=Le[Xe];st.sort((dt,it)=>{const jt=Ce.featureSortOrder;if(jt){const wt=jt.indexOf(dt.featureIndex);return jt.indexOf(it.featureIndex)-wt}return it.featureIndex-dt.featureIndex});for(const dt of st)Ke.push(dt)}}return J}function bo(D,w){const E=D.getRenderableIds().map(X=>D.getTileByID(X)),F=[],G={};for(let X=0;X{if(X)E(X);else try{const ye=F.getHeaderLength(J);if(ye>w)return void(this.request=this.fetchHeader(ye,E));F.parseHeader(J),this._isHeaderLoaded=!0;let Ce=0;for(const Le of Object.values(F.layers))Ce=Math.max(Ce,Le.dataIndex[Le.dataIndex.length-1].lastByte);J.byteLength>=Ce&&(this.entireBuffer=J),E(null,this.entireBuffer||J,de)}catch(ye){E(ye)}}),this.request}fetchBandForRender(w,E,F,G){this.fetchBand(w,E,F,X=>{if(X)return void G(X);this.updateTextureDescriptor(w,E,F);const J=this.textureDescriptorPerLayer.get(E);G(null,J?J.img:null)})}fetchBand(w,E,F,G,X=!0){const J=this._mrt;if(!this._isHeaderLoaded||!J)return void G(new Error("Tile header is not ready"));const de=this.actor;if(!de)return void G(new Error("Can't fetch tile band without an actor"));let ye;const Ce=o.F(String(F),o.F(this.tileID.key,w));let Le=this._taskQueue.get(Ce);Le?Le.add(G):(Le=new Set,Le.add(G),this._taskQueue.set(Ce,Le));const Xe=(it,jt)=>{ye.complete(it,jt),it?G(it):(Le.forEach(wt=>wt(null,jt)),this._taskQueue.delete(Ce))},Ke=(it,jt)=>{if(it)return G(it);const wt=de.send("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:jt,task:ye},Xe,void 0,!0);if(E!==null){const Bt=this._workQueuePerLayer.get(E)||[];Bt.push(()=>{wt&&wt.cancel(),ye.cancel()}),this._workQueuePerLayer.has(E)||this._workQueuePerLayer.set(E,Bt)}};let st;try{st=J.getLayer(w)}catch(it){if(this.state==="reloading")return;throw it}if(!st)return void G(new Error(`Unknown sourceLayer "${w}"`));if(st.hasDataForBand(F))return Le.forEach(it=>it(null,null)),void this._taskQueue.delete(Ce);const dt=st.getDataRange([F]);if(ye=J.createDecodingTask(dt),!ye||ye.tasks.length)if(E!==null&&this.flushQueues(E),this.entireBuffer)Ke(null,this.entireBuffer.slice(dt.firstByte,dt.lastByte+1));else{const it=Object.assign({},this.requestParams,{headers:{Range:`bytes=${dt.firstByte}-${dt.lastByte}`}}),jt=o.b1(it,Ke);if(E!==null){const wt=this._fetchQueuePerLayer.get(E)||[];wt.push(()=>{jt.cancel(),ye.cancel()}),this._fetchQueuePerLayer.has(E)||this._fetchQueuePerLayer.set(E,wt)}}}updateNeeded(w,E){return(!this.textureDescriptorPerLayer.get(w)||this.textureDescriptorPerLayer.get(w).band!==E||this.refreshedUponExpiration)&&this.state!=="errored"}updateTextureDescriptor(w,E,F){if(!this._mrt)return;const G=this._mrt.getLayer(w);if(!G||!G.hasBand(F)||!G.hasDataForBand(F))return;const{bytes:X,tileSize:J,buffer:de,offset:ye,scale:Ce}=G.getBandView(F),Le=J+2*de,Xe=new o.q({width:Le,height:Le},X),Ke=this.texturePerLayer.get(E);Ke&&Ke instanceof o.T&&Ke.update(Xe,{premultiply:!1}),this.textureDescriptorPerLayer.set(E,{layer:w,band:F,img:Xe,buffer:de,offset:ye,tileSize:J,format:G.pixelFormat,mix:[Ce,256*Ce,65536*Ce,16777216*Ce]})}destroy(w=!1){if(super.destroy(w),delete this._mrt,!w)for(const E of this.texturePerLayer.values())E&&E instanceof o.T&&E.destroy();this.texturePerLayer.clear(),this.textureDescriptorPerLayer.clear(),this.fbo&&(this.fbo.destroy(),delete this.fbo),delete this.request,delete this.requestParams,this._isHeaderLoaded=!1}}class up{constructor(w,E){this.max=w,this.onRemove=E,this.reset()}reset(){for(const w in this.data)for(const E of this.data[w])E.timeout&&clearTimeout(E.timeout),this.onRemove(E.value);return this.data={},this.order=[],this}add(w,E,F){const G=w.wrapped().key;this.data[G]===void 0&&(this.data[G]=[]);const X={value:E,timeout:void 0};if(F!==void 0&&(X.timeout=setTimeout(()=>{this.remove(w,X)},F)),this.data[G].push(X),this.order.push(G),this.order.length>this.max){const J=this._getAndRemoveByKey(this.order[0]);J&&this.onRemove(J)}return this}has(w){return w.wrapped().key in this.data}getAndRemove(w){return this.has(w)?this._getAndRemoveByKey(w.wrapped().key):null}_getAndRemoveByKey(w){const E=this.data[w].shift();return E.timeout&&clearTimeout(E.timeout),this.data[w].length===0&&delete this.data[w],this.order.splice(this.order.indexOf(w),1),E.value}getByKey(w){const E=this.data[w];return E?E[0].value:null}get(w){return this.has(w)?this.data[w.wrapped().key][0].value:null}remove(w,E){if(!this.has(w))return this;const F=w.wrapped().key,G=E===void 0?0:this.data[F].indexOf(E),X=this.data[F][G];return this.data[F].splice(G,1),X.timeout&&clearTimeout(X.timeout),this.data[F].length===0&&delete this.data[F],this.onRemove(X.value),this.order.splice(this.order.indexOf(F),1),this}setMaxSize(w){for(this.max=w;this.order.length>this.max;){const E=this._getAndRemoveByKey(this.order[0]);E&&this.onRemove(E)}return this}filter(w){const E=[];for(const F in this.data)for(const G of this.data[F])w(G.value)||E.push(G);for(const F of E)this.remove(F.value.tileID,F)}}class gg{constructor(){this.state={},this.stateChanges={},this.deletedStates={}}updateState(w,E,F){const G=String(E);if(this.stateChanges[w]=this.stateChanges[w]||{},this.stateChanges[w][G]=this.stateChanges[w][G]||{},Object.assign(this.stateChanges[w][G],F),this.deletedStates[w]===null){this.deletedStates[w]={};for(const X in this.state[w])X!==G&&(this.deletedStates[w][X]=null)}else if(this.deletedStates[w]&&this.deletedStates[w][G]===null){this.deletedStates[w][G]={};for(const X in this.state[w][G])F[X]||(this.deletedStates[w][G][X]=null)}else for(const X in F)this.deletedStates[w]&&this.deletedStates[w][G]&&this.deletedStates[w][G][X]===null&&delete this.deletedStates[w][G][X]}removeFeatureState(w,E,F){if(this.deletedStates[w]===null)return;const G=String(E);if(this.deletedStates[w]=this.deletedStates[w]||{},F&&E!==void 0)this.deletedStates[w][G]!==null&&(this.deletedStates[w][G]=this.deletedStates[w][G]||{},this.deletedStates[w][G][F]=null);else if(E!==void 0)if(this.stateChanges[w]&&this.stateChanges[w][G])for(F in this.deletedStates[w][G]={},this.stateChanges[w][G])this.deletedStates[w][G][F]=null;else this.deletedStates[w][G]=null;else this.deletedStates[w]=null}getState(w,E){const F=this.state[w]||{},G=this.stateChanges[w]||{},X=this.deletedStates[w];if(X===null)return{};if(E!==void 0){const de=String(E),ye=Object.assign({},F[de],G[de]);if(X){const Ce=X[E];if(Ce===null)return{};for(const Le in Ce)delete ye[Le]}return ye}const J=Object.assign({},F,G);if(X)for(const de in X)delete J[de];return J}initializeTileState(w,E){w.refreshFeatureState(E)}coalesceChanges(w,E){const F={};for(const G in this.stateChanges){this.state[G]=this.state[G]||{};const X={};for(const J in this.stateChanges[G])this.state[G][J]||(this.state[G][J]={}),Object.assign(this.state[G][J],this.stateChanges[G][J]),X[J]=this.state[G][J];F[G]=X}for(const G in this.deletedStates){this.state[G]=this.state[G]||{};const X={};if(this.deletedStates[G]===null)for(const J in this.state[G])X[J]={},this.state[G][J]={};else for(const J in this.deletedStates[G]){if(this.deletedStates[G][J]===null)this.state[G][J]={};else if(this.state[G][J])for(const de of Object.keys(this.deletedStates[G][J]))delete this.state[G][J][de];X[J]=this.state[G][J]}F[G]=F[G]||{},Object.assign(F[G],X)}if(this.stateChanges={},this.deletedStates={},Object.keys(F).length!==0)for(const G in w)w[G].refreshFeatureState(E,F)}}class Vl extends o.E{constructor(w,E,F){super(),this.id=w,this._renderSourceType=F,this._maxzoomOverride=null,E.on("data",G=>{G.dataType==="source"&&G.sourceDataType==="metadata"&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&G.dataType==="source"&&G.sourceDataType==="content"&&(this.reload(),this.transform&&this.update(this.transform))}),E.on("error",()=>{this._sourceErrored=!0}),this._source=E,this._tiles={},this._cache=new up(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._minTileCacheSize=E.minTileCacheSize,this._maxTileCacheSize=E.maxTileCacheSize,this._loadedParentTiles={},this.castsShadows=!1,this.tileCoverLift=0,this._coveredTiles={},this._shadowCasterTiles={},this._state=new gg,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(w){this.map=w,this._minTileCacheSize=this._minTileCacheSize===void 0&&w?w._minTileCacheSize:this._minTileCacheSize,this._maxTileCacheSize=this._maxTileCacheSize===void 0&&w?w._maxTileCacheSize:this._maxTileCacheSize}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded||!this._source.loaded())return!1;for(const w in this._tiles)if(!this._tiles[w].loaded())return!1;return!0}getSource(){return this._source}pause(){this._paused=!0}resume(){if(!this._paused)return;const w=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,w&&this.reload(),this.transform&&this.update(this.transform)}setMaxzoomOverride(w){this._maxzoomOverride=w}_loadTile(w,E){return w.renderSourceType=this._renderSourceType,w.isExtraShadowCaster=this._shadowCasterTiles[w.tileID.key],this._source.loadTile(w,E)}_unloadTile(w){if(this._source.unloadTile)return this._source.unloadTile(w)}_abortTile(w){if(this._source.abortTile)return this._source.abortTile(w)}serialize(){return this._source.serialize()}prepare(w){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const E in this._tiles){const F=this._tiles[E];F.upload(w,this.map?this.map.painter:void 0),F.prepare(this.map.style.imageManager,this.map?this.map.painter:null,this._source.scope)}}getIds(){return Object.values(this._tiles).map(w=>w.tileID).sort(hp).map(w=>w.key)}getRenderableIds(w,E){const F=[];for(const G in this._tiles)this._isIdRenderable(+G,w,E)&&F.push(this._tiles[G]);return w?F.sort((G,X)=>{const J=G.tileID,de=X.tileID,ye=new o.P(J.canonical.x,J.canonical.y)._rotate(this.transform.angle),Ce=new o.P(de.canonical.x,de.canonical.y)._rotate(this.transform.angle);return J.overscaledZ-de.overscaledZ||Ce.y-ye.y||Ce.x-ye.x}).map(G=>G.tileID.key):F.map(G=>G.tileID).sort(hp).map(G=>G.key)}hasRenderableParent(w){const E=this.findLoadedParent(w,0);return!!E&&this._isIdRenderable(E.tileID.key)}_isIdRenderable(w,E,F){return this._tiles[w]&&this._tiles[w].hasData()&&!this._coveredTiles[w]&&(E||!this._tiles[w].holdingForFade())&&(F||!this._shadowCasterTiles[w])}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const w in this._tiles)this._tiles[w].state!=="errored"&&this._reloadTile(+w,"reloading")}}_reloadTile(w,E){const F=this._tiles[w];F&&(F.state!=="loading"&&(F.state=E),this._loadTile(F,this._tileLoaded.bind(this,F,w,E)))}_tileLoaded(w,E,F,G,X){if(G){if(w.state="errored",o.b2(G)){if(this._source.fire(new o.C("data",{dataType:"source",sourceDataType:"error",sourceId:this._source.id,tile:w})),!(w.tileID.key in this._loadedParentTiles))return;if(this._source.type==="raster-dem"&&this.usedForTerrain&&this.map.painter.terrain){const de=this.map.painter.terrain;this.update(this.transform,de.getScaledDemTileSize(),!0),de.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new o.B(G,{tile:w}));return}w.timeAdded=o.o.now(),F==="expired"&&(w.refreshedUponExpiration=!0),this._setTileReloadTimer(E,w),this._source.type==="raster-dem"&&w.dem&&this._backfillDEM(w),this._state.initializeTileState(w,this.map?this.map.painter:null);let J=new Map;X&&X.responseHeaders&&(J=X.responseHeaders),this._source.fire(new o.C("data",{dataType:"source",tile:w,coord:w.tileID,sourceCacheId:this.id,responseHeaders:J}))}_hasTunnelGeometry(){for(const w in this._tiles){const E=this._tiles[w];if(E&&E.hasTunnelGeometry)return!0}return!1}_backfillDEM(w){const E=this.getRenderableIds();for(let G=0;G1||(Math.abs(J)>1&&(Math.abs(J+ye)===1?J+=ye:Math.abs(J-ye)===1&&(J-=ye)),X.dem&&G.dem&&(G.dem.backfillBorder(X.dem,J,de),G.neighboringTiles&&G.neighboringTiles[Ce]&&(G.neighboringTiles[Ce].backfilled=!0)))}}getTile(w){return this.getTileByID(w.key)}getTileByID(w){return this._tiles[w]}_retainLoadedChildren(w,E,F,G){for(const X in this._tiles){let J=this._tiles[X];if(G[X]||!J.hasData()||J.tileID.overscaledZ<=E||J.tileID.overscaledZ>F)continue;let de=J.tileID;for(;J&&J.tileID.overscaledZ>E+1;){const Ce=J.tileID.scaledTo(J.tileID.overscaledZ-1);J=this._tiles[Ce.key],J&&J.hasData()&&(de=Ce)}let ye=de;for(;ye.overscaledZ>E;)if(ye=ye.scaledTo(ye.overscaledZ-1),w[ye.key]){G[de.key]=de;break}}}findLoadedParent(w,E){if(w.key in this._loadedParentTiles){const F=this._loadedParentTiles[w.key];return F&&F.tileID.overscaledZ>=E?F:null}for(let F=w.overscaledZ-1;F>=E;F--){const G=w.scaledTo(F),X=this._getLoadedTile(G);if(X)return X}}_getLoadedTile(w){const E=this._tiles[w.key];return E&&E.hasData()?E:this._cache.getByKey(this._source.reparseOverscaled?w.wrapped().key:w.canonical.key)}updateCacheSize(w,E){E=E||this._source.tileSize;const F=Math.ceil(w.width/E)+1,G=Math.ceil(w.height/E)+1,X=Math.floor(F*G*5),J=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,X):X,de=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,J):J;this._cache.setMaxSize(de)}handleWrapJump(w){const E=Math.round((w-(this._prevLng===void 0?w:this._prevLng))/360);if(this._prevLng=w,E){const F={};for(const G in this._tiles){const X=this._tiles[G];X.tileID=X.tileID.unwrapTo(X.tileID.wrap+E),F[X.tileID.key]=X}this._tiles=F;for(const G in this._timers)clearTimeout(this._timers[G]),delete this._timers[G];for(const G in this._tiles)this._setTileReloadTimer(+G,this._tiles[G])}}update(w,E,F,G,X){if(this.transform=w,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage||this.usedForTerrain&&!F)return;this.updateCacheSize(w,E),this.transform.projection.name!=="globe"&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles={},this._coveredTiles={};const J=this._source.type==="batched-model";let de,ye=this._source.maxzoom;this._maxzoomOverride!==null&&(ye=Math.min(ye,this._maxzoomOverride));const Ce=this.map&&this.map.painter?this.map.painter._terrain:null;if(Ce&&Ce.sourceCache===this&&Ce.attenuationRange()){const st=Ce.attenuationRange()[0],dt=Math.floor(st)-Math.log2(Ce.getDemUpscale());ye>dt&&(ye=dt)}const Le=this._maxzoomOverride===null&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain){if(this._source.tileID)de=w.getVisibleUnwrappedCoordinates(this._source.tileID).map(st=>new o.aR(st.canonical.z,st.wrap,st.canonical.z,st.canonical.x,st.canonical.y));else if(this.tileCoverLift!==0){const st=w.clone();st.tileCoverLift=this.tileCoverLift,de=st.coveringTiles({tileSize:E||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:ye,roundZoom:this._source.roundZoom&&!F,reparseOverscaled:Le,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:J}),this._source.minzoom<=1&&w.projection.name==="globe"&&(de.push(new o.aR(1,0,1,0,0)),de.push(new o.aR(1,0,1,1,0)),de.push(new o.aR(1,0,1,0,1)),de.push(new o.aR(1,0,1,1,1)))}else if(de=w.coveringTiles({tileSize:E||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:ye,roundZoom:this._source.roundZoom&&!F,reparseOverscaled:Le,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:J}),this._source.hasTile){const st=this._source.hasTile.bind(this._source);de=de.filter(dt=>st(dt))}}else de=[];if(de.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!this._supportsFading){const st=w.coveringZoomLevel({tileSize:E||this._source.tileSize,roundZoom:this._source.roundZoom&&!F}),dt=Math.min(st,ye);if(J){const it=w.extendTileCover(de,dt);for(const jt of it)de.push(jt)}else if(X){const it=this.transform.getFrustum(dt),jt=w.extendTileCoverToNearPlane(de,it,dt);for(const wt of jt)de.push(wt);if(dt>=18&&this._hasTunnelGeometry()){const wt=w.extendTileCoverForTunnels(de,it,dt,20);for(const Bt of wt)de.push(Bt)}}else if(this.castsShadows&&G){const it=w.extendTileCover(de,dt,G,16);for(const jt of it)this._shadowCasterTiles[jt.key]=!0,de.push(jt)}}const Xe=this._updateRetainedTiles(de);if(this._supportsFading&&de.length!==0){const st={},dt={},it=o.o.now(),jt=Object.keys(Xe);for(const Bt of jt){const Vt=Xe[Bt],Ct=this._tiles[Bt];if(!Ct||Ct.fadeEndTime!==void 0&&Ct.fadeEndTime<=it)continue;const Ss=this.findLoadedParent(Vt,Math.max(Vt.overscaledZ-Vl.maxOverzooming,this._source.minzoom));Ss&&(this._addTile(Ss.tileID),st[Ss.tileID.key]=Ss.tileID),dt[Bt]=Vt}const wt=de[de.length-1].overscaledZ;for(const Bt in this._tiles){const Vt=this._tiles[Bt];if(Xe[Bt]||!Vt.hasData())continue;let Ct=Vt.tileID;for(;Ct.overscaledZ>wt;){Ct=Ct.scaledTo(Ct.overscaledZ-1);const Ss=this._tiles[Ct.key];if(Ss&&Ss.hasData()&&dt[Ct.key]){Xe[Bt]=Vt.tileID;break}}}for(const Bt in st)Xe[Bt]||(this._coveredTiles[Bt]=!0,Xe[Bt]=st[Bt])}for(const st in Xe)this._tiles[st].clearFadeHold();const Ke=o.b3(this._tiles,Xe);for(const st of Ke){const dt=this._tiles[st];dt.hasSymbolBuckets&&!dt.holdingForFade()?dt.setHoldDuration(this.map._fadeDuration):dt.hasSymbolBuckets&&!dt.symbolFadeFinished()||this._removeTile(+st)}this._updateLoadedParentTileCache(),this._renderSourceType===o.b4.Symbol&&this._source.afterUpdate&&this._source.afterUpdate()}releaseSymbolFadeTiles(){for(const w in this._tiles)this._tiles[w].holdingForFade()&&this._removeTile(+w)}_updateRetainedTiles(w){const E={};if(w.length===0)return E;const F={},G=w.reduce((Ce,Le)=>Math.min(Ce,Le.overscaledZ),1/0),X=w[0].overscaledZ,J=Math.max(X-Vl.maxOverzooming,this._source.minzoom),de=Math.max(X+Vl.maxUnderzooming,this._source.minzoom),ye={};for(const Ce of w){const Le=this._addTile(Ce);E[Ce.key]=Ce,Le.hasData()||G=this._source.maxzoom){const Ke=Ce.children(this._source.maxzoom)[0],st=this.getTile(Ke);if(st&&st.hasData()){E[Ke.key]=Ke;continue}}else{const Ke=Ce.children(this._source.maxzoom);if(E[Ke[0].key]&&E[Ke[1].key]&&E[Ke[2].key]&&E[Ke[3].key])continue}let Xe=Le.wasRequested();for(let Ke=Ce.overscaledZ-1;Ke>=J;--Ke){const st=Ce.scaledTo(Ke);if(F[st.key]||(F[st.key]=!0,Le=this.getTile(st),!Le&&Xe&&(Le=this._addTile(st)),Le&&(E[st.key]=st,Xe=Le.wasRequested(),Le.hasData())))break}}return E}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const w in this._tiles){const E=[];let F,G=this._tiles[w].tileID;for(;G.overscaledZ>0;){if(G.key in this._loadedParentTiles){F=this._loadedParentTiles[G.key];break}E.push(G.key);const X=G.scaledTo(G.overscaledZ-1);if(F=this._getLoadedTile(X),F)break;G=X}for(const X of E)this._loadedParentTiles[X]=F}}_addTile(w){let E=this._tiles[w.key];if(E)return E.isExtraShadowCaster!==!0||this._shadowCasterTiles[w.key]||this._reloadTile(w.key,"reloading"),E;E=this._cache.getAndRemove(w),E&&(this._setTileReloadTimer(w.key,E),E.tileID=w,this._state.initializeTileState(E,this.map?this.map.painter:null),this._cacheTimers[w.key]&&(clearTimeout(this._cacheTimers[w.key]),delete this._cacheTimers[w.key],this._setTileReloadTimer(w.key,E)));const F=!!E;if(!F){const G=this.map?this.map.painter:null,X=this._source.tileSize*w.overscaleFactor();E=this._source.type==="raster-array"?new dp(w,X,this.transform.tileZoom,G,this._isRaster):new o.b0(w,X,this.transform.tileZoom,G,this._isRaster,this._source.worldview),this._loadTile(E,this._tileLoaded.bind(this,E,w.key,E.state))}return E.uses++,this._tiles[w.key]=E,F||this._source.fire(new o.C("dataloading",{tile:E,coord:E.tileID,dataType:"source"})),E}_setTileReloadTimer(w,E){w in this._timers&&(clearTimeout(this._timers[w]),delete this._timers[w]);const F=E.getExpiryTimeout();F&&(this._timers[w]=setTimeout(()=>{this._reloadTile(w,"expired"),delete this._timers[w]},F))}_removeTile(w){const E=this._tiles[w];E&&(E.uses--,delete this._tiles[w],this._timers[w]&&(clearTimeout(this._timers[w]),delete this._timers[w]),E.uses>0||(E.hasData()&&E.state!=="reloading"||E.state==="empty"?this._cache.add(E.tileID,E,E.getExpiryTimeout()):(E.aborted=!0,this._abortTile(E),this._unloadTile(E))))}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const w in this._tiles)this._removeTile(+w);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(w,E,F){const G=[],X=this.transform;if(!X)return G;const J=X.projection.name==="globe",de=o.aH(X.center.lng);for(const ye in this._tiles){const Ce=this._tiles[ye];if(F&&Ce.clearQueryDebugViz(),Ce.holdingForFade())continue;let Le;if(J){const Xe=Ce.tileID.canonical;if(Xe.z===0){const Ke=[Math.abs(o.aC(de,...Jd(Xe,-1))-de),Math.abs(o.aC(de,...Jd(Xe,1))-de)];Le=[0,2*Ke.indexOf(Math.min(...Ke))-1]}else{const Ke=[Math.abs(o.aC(de,...Jd(Xe,-1))-de),Math.abs(o.aC(de,...Jd(Xe,0))-de),Math.abs(o.aC(de,...Jd(Xe,1))-de)];Le=[Ke.indexOf(Math.min(...Ke))-1]}}else Le=[0];for(const Xe of Le){const Ke=w.containsTile(Ce,X,E,Xe);Ke&&G.push(Ke)}}return G}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(w){return this._getRenderableCoordinates(w)}_getRenderableCoordinates(w,E){const F=this.getRenderableIds(w,E).map(X=>this._tiles[X].tileID),G=this.transform.projection.name==="globe";for(const X of F)X.projMatrix=this.transform.calculateProjMatrix(X.toUnwrapped()),X.expandedProjMatrix=G?this.transform.calculateProjMatrix(X.toUnwrapped(),!1,!0):X.projMatrix;return F}sortCoordinatesByDistance(w){const E=w.slice(),F=this.transform._camera.position,G=this.transform._camera.forward(),X={};for(const J of E){const de=1/(1<X[J.key]-X[de.key]),E}hasTransition(){if(this._source.hasTransition())return!0;if(this._supportsFading){const w=o.o.now();for(const E in this._tiles){const F=this._tiles[E];if(F.fadeEndTime!==void 0&&F.fadeEndTime>=w)return!0}}return!1}setFeatureState(w,E,F){this._state.updateState(w=w||"_geojsonTileLayer",E,F)}removeFeatureState(w,E,F){this._state.removeFeatureState(w=w||"_geojsonTileLayer",E,F)}getFeatureState(w,E){return this._state.getState(w=w||"_geojsonTileLayer",E)}setDependencies(w,E,F){const G=this._tiles[w];G&&G.setDependencies(E,F)}reloadTilesForDependencies(w,E){for(const F in this._tiles)this._tiles[F].hasDependency(w,E)&&this._reloadTile(+F,"reloading");this._cache.filter(F=>!F.hasDependency(w,E))}_preloadTiles(w,E){if(!this._sourceLoaded){const ye=()=>{this._sourceLoaded&&(this._source.off("data",ye),this._preloadTiles(w,E))};return void this._source.on("data",ye)}const F=new Map,G=Array.isArray(w)?w:[w],X=this.map.painter.terrain,J=this.usedForTerrain&&X?X.getScaledDemTileSize():this._source.tileSize;for(const ye of G){const Ce=ye.coveringTiles({tileSize:J,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom&&!this.usedForTerrain,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain});for(const Le of Ce)F.set(Le.key,Le);this.usedForTerrain&&ye.updateElevation(!1)}const de=Array.from(F.values());o.t(de,(ye,Ce)=>{const Le=new o.b0(ye,this._source.tileSize*ye.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster,this._source.worldview);this._loadTile(Le,Xe=>{this._source.type==="raster-dem"&&Le.dem&&this._backfillDEM(Le),Ce(Xe,Le)})},E)}}function hp(D,w){const E=Math.abs(2*D.wrap)-+(D.wrap<0),F=Math.abs(2*w.wrap)-+(w.wrap<0);return D.overscaledZ-w.overscaledZ||F-E||w.canonical.y-D.canonical.y||w.canonical.x-D.canonical.x}function Jd(D,w){const E=1<0:F.type==="building"?G=!F.isHidden(w)&&F.paint.get("building-opacity")>0:F.type==="model"&&(G=!F.isHidden(w)&&F.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!G&&E.visible,E.visible=G}}updateZOffset(w,E){this.currentBuildingBuckets=[];for(const G of this.layers){const X=G.layer,J=this.style.getLayerSourceCache(X);let de=1;X.type==="fill-extrusion"?de=G.visible?X.paint.get("fill-extrusion-vertical-scale"):0:X.type==="building"&&(de=G.visible?X.paint.get("building-vertical-scale"):0);let ye=J?J.getTile(E):null;if(!ye&&J)for(const Ce in J._tiles){const Le=J._tiles[Ce];if(E.canonical.isChildOf(Le.tileID.canonical)){ye=Le;break}}this.currentBuildingBuckets.push({bucket:ye?ye.getBucket(X):null,tileID:ye?ye.tileID:E,verticalScale:de})}w.hasAnyZOffset=!1;let F=!1;for(let G=0;G{F in w&&(E[F]=w[F])}),E}function _u(D){D=D.slice();const w=Object.create(null);for(const E of D)w[E.id]=E;for(let E=0;E0?(G-J)/de:0;return this.points[X].mult(1-ye).add(this.points[E].mult(ye))}}class Qg{constructor(w,E,F){const G=this.boxCells=[],X=this.circleCells=[];this.xCellCount=Math.ceil(w/F),this.yCellCount=Math.ceil(E/F);for(let J=0;Jthis.width||G<0||E>this.height)return!X&&[];const de=[];if(w<=0&&E<=0&&this.width<=F&&this.height<=G){if(X)return!0;for(let ye=0;ye0:de}_queryCircle(w,E,F,G,X){const J=w-F,de=w+F,ye=E-F,Ce=E+F;if(de<0||J>this.width||Ce<0||ye>this.height)return!G&&[];const Le=[];return this._forEachCell(J,ye,de,Ce,this._queryCellCircle,Le,{hitTest:G,circle:{x:w,y:E,radius:F},seenUids:{box:{},circle:{}}},X),G?Le.length>0:Le}query(w,E,F,G,X){return this._query(w,E,F,G,!1,X)}hitTest(w,E,F,G,X){return this._query(w,E,F,G,!0,X)}hitTestCircle(w,E,F,G){return this._queryCircle(w,E,F,!0,G)}_queryCell(w,E,F,G,X,J,de,ye){const Ce=de.seenUids,Le=this.boxCells[X];if(Le!==null){const Ke=this.bboxes;for(const st of Le)if(!Ce.box[st]){Ce.box[st]=!0;const dt=4*st;if(w<=Ke[dt+2]&&E<=Ke[dt+3]&&F>=Ke[dt+0]&&G>=Ke[dt+1]&&(!ye||ye(this.boxKeys[st]))){if(de.hitTest)return J.push(!0),!0;J.push({key:this.boxKeys[st],x1:Ke[dt],y1:Ke[dt+1],x2:Ke[dt+2],y2:Ke[dt+3]})}}}const Xe=this.circleCells[X];if(Xe!==null){const Ke=this.circles;for(const st of Xe)if(!Ce.circle[st]){Ce.circle[st]=!0;const dt=3*st;if(this._circleAndRectCollide(Ke[dt],Ke[dt+1],Ke[dt+2],w,E,F,G)&&(!ye||ye(this.circleKeys[st]))){if(de.hitTest)return J.push(!0),!0;{const it=Ke[dt],jt=Ke[dt+1],wt=Ke[dt+2];J.push({key:this.circleKeys[st],x1:it-wt,y1:jt-wt,x2:it+wt,y2:jt+wt})}}}}}_queryCellCircle(w,E,F,G,X,J,de,ye){const Ce=de.circle,Le=de.seenUids,Xe=this.boxCells[X];if(Xe!==null){const st=this.bboxes;for(const dt of Xe)if(!Le.box[dt]){Le.box[dt]=!0;const it=4*dt;if(this._circleAndRectCollide(Ce.x,Ce.y,Ce.radius,st[it+0],st[it+1],st[it+2],st[it+3])&&(!ye||ye(this.boxKeys[dt])))return J.push(!0),!0}}const Ke=this.circleCells[X];if(Ke!==null){const st=this.circles;for(const dt of Ke)if(!Le.circle[dt]){Le.circle[dt]=!0;const it=3*dt;if(this._circlesCollide(st[it],st[it+1],st[it+2],Ce.x,Ce.y,Ce.radius)&&(!ye||ye(this.circleKeys[dt])))return J.push(!0),!0}}}_forEachCell(w,E,F,G,X,J,de,ye){const Ce=this._convertToXCellCoord(w),Le=this._convertToYCellCoord(E),Xe=this._convertToXCellCoord(F),Ke=this._convertToYCellCoord(G);for(let st=Ce;st<=Xe;st++)for(let dt=Le;dt<=Ke;dt++)if(X.call(this,w,E,F,G,this.xCellCount*dt+st,J,de,ye))return}_convertToXCellCoord(w){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(w*this.xScale)))}_convertToYCellCoord(w){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(w*this.yScale)))}_circlesCollide(w,E,F,G,X,J){const de=G-w,ye=X-E,Ce=F+J;return Ce*Ce>de*de+ye*ye}_circleAndRectCollide(w,E,F,G,X,J,de){const ye=(J-G)/2,Ce=Math.abs(w-(G+ye));if(Ce>ye+F)return!1;const Le=(de-X)/2,Xe=Math.abs(E-(X+Le));if(Xe>Le+F)return!1;if(Ce<=ye||Xe<=Le)return!0;const Ke=Ce-ye,st=Xe-Le;return Ke*Ke+st*st<=F*F}}const _y=Math.tan(85*Math.PI/180);function zd(D,w,E,F,G,X,J){const de=o.bb();if(E)if(X.name==="globe"){const ye=o.bc(G,w);o.aD(de,de,ye)}else{const ye=o.bd([],J);de[0]=ye[0],de[1]=ye[1],de[4]=ye[2],de[5]=ye[3],F||o.ba(de,de,G.angle)}else o.aD(de,G.labelPlaneMatrix,D);return de}function ld(D,w,E,F,G,X,J){const de=zd(D,w,E,F,G,X,J);return X.name==="globe"&&E||(de[2]=de[6]=de[10]=de[14]=0),de}function Gp(D,w,E,F,G,X,J){if(E){if(X.name==="globe"){const de=zd(D,w,E,F,G,X,J);return o.b7(de,de),o.aD(de,D,de),de}{const de=o.b8(D),ye=o.b9([]);return ye[0]=J[0],ye[1]=J[1],ye[4]=J[2],ye[5]=J[3],o.aD(de,de,ye),F||o.ba(de,de,-G.angle),de}}return G.glCoordMatrix}function eu(D,w,E,F){const G=[D,w,E,1];E?o.aE(G,G,F):Es(G,G,F);const X=G[3];return G[0]/=X,G[1]/=X,G[2]/=X,G}function Wp(D,w){return Math.min(.5+D/w*.5,1.5)}function qm(D,w){const E=D[0]/D[3],F=D[1]/D[3];return E>=-w[0]&&E<=w[0]&&F>=-w[1]&&F<=w[1]}function ym(D,w,E,F,G,X,J,de,ye,Ce,Le=1){const Xe=E.transform,Ke=F?D.textSizeData:D.iconSizeData,st=o.bj(Ke,E.transform.zoom,Le),dt=Xe.projection.name==="globe",it=[256/E.width*2+1,256/E.height*2+1],jt=F?D.text.dynamicLayoutVertexArray:D.icon.dynamicLayoutVertexArray;jt.clear();let wt=null;dt&&(wt=F?D.text.globeExtVertexArray:D.icon.globeExtVertexArray);const Bt=D.lineVertexArray,Vt=F?D.text.placedSymbolArray:D.icon.placedSymbolArray,Ct=E.transform.width/E.transform.height;let Ss,rs=!1;for(let _s=0;_sMath.abs(E)?{useVertical:!0}:D===o.bk.vertical?F>0?{needsFlipping:!0}:null:w!==0&&function(G,X){return G===0||Math.abs(X/G)>_y}(E,F)?w===1?{needsFlipping:!0}:null:E<0?{needsFlipping:!0}:null}function Bs(D,w,E,F,G,X,J,de,ye,Ce,Le,Xe,Ke,st,dt,it,jt,wt,Bt,Vt){const Ct=w/24,Ss=D.lineOffsetX*Ct,rs=D.lineOffsetY*Ct,{lineStartIndex:_s,glyphStartIndex:Gt,numGlyphs:ss,segment:xs,writingMode:Ks,flipState:Ts}=D,_n=_s+D.lineLength,hn=Rn=>{if(Le){const[yn,jn,An]=Rn.up,jr=Ce.length;o.bm(Le,jr+0,yn,jn,An),o.bm(Le,jr+1,yn,jn,An),o.bm(Le,jr+2,yn,jn,An),o.bm(Le,jr+3,yn,jn,An)}const[Kn,en,Ls]=Rn.point;o.bn(Ce,Kn,en,Ls,Rn.angle)};if(ss>1){const Rn=at(Ct,de,Ss,rs,E,Xe,Ke,D,ye,X,st,it,!1,jt,wt,Bt,Vt);if(!Rn)return{notEnoughRoom:!0};if(F&&!E){let[Kn,en,Ls]=Rn.first.point,[yn,jn,An]=Rn.last.point;[Kn,en]=eu(Kn,en,Ls,J),[yn,jn]=eu(yn,jn,An,J);const jr=Yt(Ks,Ts,(yn-Kn)*dt,jn-en);if(D.flipState=jr&&jr.needsFlipping?1:2,jr)return jr}hn(Rn.first);for(let Kn=Gt+1;Kn0?yn:Sn(Ke,Ls,Kn,1,G,void 0,jt,wt.canonical),An=Yt(Ks,Ts,(jn[0]-Kn[0])*dt,jn[1]-Kn[1]);if(D.flipState=An&&An.needsFlipping?1:2,An)return An}const Rn=Dr(Ct*de.getoffsetX(Gt),Ss,rs,E,Xe,Ke,xs,_s,_n,ye,X,st,it,!1,!1,jt,wt,Bt,Vt);if(!Rn)return{notEnoughRoom:!0};hn(Rn)}return{}}function Zs(D,w,E,F,G){const{x:X,y:J,z:de}=F.projectTilePoint(D.x,D.y,w);if(!G)return eu(X,J,de,E);const[ye,Ce,Le]=G.getElevation(D,G.elevation,G.elevationFeature);return eu(X+ye,J+Ce,de+Le,E)}function Sn(D,w,E,F,G,X,J,de){const ye=Zs(D.sub(w)._unit()._add(D),de,G,J,X);return o.ax(ye,E,ye),o.ay(ye,ye),o.bg(ye,E,ye,F)}function Dr(D,w,E,F,G,X,J,de,ye,Ce,Le,Xe,Ke,st,dt,it,jt,wt,Bt){const Vt=F?D-w:D+w;let Ct=Vt>0?1:-1,Ss=0;F&&(Ct*=-1,Ss=Math.PI),Ct<0&&(Ss+=Math.PI);let rs=de+J+(Ct>0?0:1)|0,_s=G,Gt=G,ss=0,xs=0;const Ks=Math.abs(Vt),Ts=[],_n=[];let hn=X,Rn=hn,Kn=o.be([]);const en=()=>Sn(Rn,hn,Gt,Ks-ss+1,Le,Ke,it,jt.canonical);for(;ss+xs<=Ks;){if(rs+=Ct,rs=ye)return null;if(Gt=_s,Rn=hn,Ts.push(Gt),st&&_n.push(Rn),hn=new o.P(Ce.getx(rs),Ce.gety(rs)),_s=Xe[rs],!_s){const Na=Zs(hn,jt.canonical,Le,it,Ke);_s=Na[3]>0?Xe[rs]=Na:en()}ss+=xs;const Vn=o.ax([],_s,Gt),ca=o.bf(Gt,_s);if(E&&ca>0&&xs>0&&o.bi(Kn,Vn)/(xs*ca)0,Vt),_s=Ce*rs.perspectiveRatio,Gt=(F.x1*E+de.x-F.padding)*_s+rs.point.x,ss=(F.y1*E+de.y-F.padding)*_s+rs.point.y,xs=(F.x2*E+de.x+F.padding)*_s+rs.point.x,Ks=(F.y2*E+de.y+F.padding)*_s+rs.point.y,Ts=rs.perspectiveRatio<=.55||rs.occluded;return!this.isInsideGrid(Gt,ss,xs,Ks)||!ye&&this.grid.hitTest(Gt,ss,xs,Ks,Xe)||Ts?{box:[],offscreen:!1,occluded:rs.occluded}:{box:[Gt,ss,xs,Ks],offscreen:this.isOffscreen(Gt,ss,xs,Ks),occluded:!1}}placeCollisionCircles(w,E,F,G,X,J,de,ye,Ce,Le,Xe,Ke,st,dt,it,jt){const wt=[],Bt=this.transform.elevation,Vt=w.getProjection(),Ct=w.elevationType==="road",Ss=!!Bt||Ct,rs=o.bu.getAtTileOffsetFunc(jt,this.transform.center.lat,this.transform.worldSize,Vt),_s=new o.P(F.tileAnchorX,F.tileAnchorY),Gt=new o.P(F.tileAnchorX,F.tileAnchorY);let{x:ss,y:xs,z:Ks}=Vt.projectTilePoint(Gt.x,Gt.y,jt.canonical),Ts=null;if(Ss){const ca=Ct?w.getElevationFeatureForText(G):null;Ts={getElevation:rs,elevation:Bt,elevationFeature:ca};const[Na,ea,ia]=rs(_s,Bt,ca);ss+=Na,xs+=ea,Ks+=ia}const _n=Vt.name==="globe",hn=this.projectAndGetPerspectiveRatio(ye,ss,xs,Ks,jt,_n||!!Bt||this.transform.pitch>0,Vt),{perspectiveRatio:Rn}=hn,Kn=(Ke?de/Rn:de*Rn)/o.by,en=eu(ss,xs,Ks,Ce),Ls=F.lineOffsetX*Kn,yn=F.lineOffsetY*Kn,jn=o.ap(w.layers[0].layout.get("text-max-angle")),An=Math.cos(jn),jr=hn.signedDistanceFromCamera>0?at(Kn,J,Ls,yn,Ct&&F.flipState===1,en,Gt,F,X,Ce,{},Ss&&!Ke?Ts:null,Ke&&Ss,Vt,jt,Ke,An):null;let ur=!1,hr=!1,Vn=!0;if(jr&&!hn.occluded){const ca=.5*dt*Rn+it,Na=new o.P(-100,-100),ea=new o.P(this.screenRightBoundary,this.screenBottomBoundary),ia=new Tx,{first:ii,last:Ni}=jr,yi=ii.path.length;let Ji=[];for(let vi=yi-1;vi>=1;vi--)Ji.push(ii.path[vi]);for(let vi=1;vi(Ss&&!_n&&(oc=rs(Edvi[3]<=0)&&(Ji=[]));let eo=[];if(Ji.length>0){let vi=1/0,Wo=-1/0,oc=1/0,Ed=-1/0;for(const Tc of Ji)vi=Math.min(vi,Tc[0]),oc=Math.min(oc,Tc[1]),Wo=Math.max(Wo,Tc[0]),Ed=Math.max(Ed,Tc[1]);Wo>=Na.x&&vi<=ea.x&&Ed>=Na.y&&oc<=ea.y&&(eo=[Ji.map(Tc=>new o.P(Tc[0],Tc[1]))],(viea.x||ocea.y)&&(eo=o.bv(eo,Na.x,Na.y,ea.x,ea.y)))}for(const vi of eo){ia.reset(vi,.25*ca);let Wo=0;Wo=ia.length<=.5*ca?1:Math.ceil(ia.paddedLength/Ha)+1;for(let oc=0;oc0?(o.aE(ye,ye,w),this.fogState&&X&&de.name!=="globe"&&(Ce=function(Ke,st,dt,it,jt,wt){const Bt=wt.calculateFogTileMatrix(jt),Vt=[st,dt,it];return o.ah(Vt,Vt,Bt),Fa(Ke,o.ai(Vt),wt.pitch,wt._fov)}(this.fogState,E,F,G,X.toUnwrapped(),this.transform)>.9)):Es(ye,ye,w);const Le=ye[3];return{point:new o.P((ye[0]/Le+1)/2*this.transform.width+bn,(-ye[1]/Le+1)/2*this.transform.height+bn),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(de)/Le*.5,1.5),signedDistanceFromCamera:Le,occluded:J&&ye[2]>Le||Ce}}isOffscreen(w,E,F,G){return F=this.screenRightBoundary||Gthis.screenBottomBoundary}isInsideGrid(w,E,F,G){return F>=0&&w=0&&EF.collisionGroupID===E}}return this.collisionGroups[w]}}function ol(D,w,E,F,G){const{horizontalAlign:X,verticalAlign:J}=o.bF(D),de=-(X-.5)*w,ye=-(J-.5)*E,Ce=o.bG(D,F);return new o.P(de+Ce[0]*G,ye+Ce[1]*G)}function vc(D,w,E,F,G){const X=new o.P(D,w);return E&&X._rotate(F?G:-G),X}class ao{constructor(w,E,F,G,X,J){this.transform=w.clone(),this.projection=w.projection.name,this.collisionIndex=new Br(this.transform,X),this.buildingIndex=J,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=E,this.retainedQueryData={},this.collisionGroups=new mi(F),this.collisionCircleArrays={},this.prevPlacement=G,G&&(G.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(w,E,F,G,X=1){const J=F.getBucket(E),de=F.latestFeatureIndex;if(!J||!de||E.fqid!==J.layerIds[0])return;const ye=J.layers[0].layout,Ce=J.layers[0].paint,Le=F.collisionBoxArray,Xe=Math.pow(2,this.transform.zoom-F.tileID.overscaledZ),Ke=F.tileSize/o.an,st=F.tileID.toUnwrapped();this.transform.setProjection(J.projection);const dt=(it=F.tileID,jt=J.getProjection(),wt=this.transform,jt.name===this.projection?wt.calculateProjMatrix(it.toUnwrapped()):N0(wt,jt,it));var it,jt,wt;const Bt=ye.get("text-pitch-alignment")==="map",Vt=ye.get("text-rotation-alignment")==="map";E.compileFilter(E.options);const Ct=E.dynamicFilter(),Ss=E.dynamicFilterNeedsFeature(),rs=E.dynamicFilterNeedsGeometry(),_s=this.transform.calculatePixelsToTileUnitsMatrix(F),Gt=ld(dt,F.tileID.canonical,Bt,Vt,this.transform,J.getProjection(),_s);let ss=null;const xs=J.getProjection().createInversionMatrix(this.transform,F.tileID.canonical);if(Bt){const yn=Gp(dt,F.tileID.canonical,Bt,Vt,this.transform,J.getProjection(),_s);ss=o.aD([],this.transform.labelPlaneMatrix,yn)}let Ks=null;Ct&&F.latestFeatureIndex&&(Ks={unwrappedTileID:st,dynamicFilter:Ct,dynamicFilterNeedsFeature:Ss,needGeometry:rs}),this.retainedQueryData[J.bucketInstanceId]=new Va(J.bucketInstanceId,de,J.sourceLayerIndex,J.index,F.tileID);const[Ts,_n]=J.layers[0].layout.get("text-size-scale-range"),hn=o.aC(X,Ts,_n),[Rn,Kn]=ye.get("icon-size-scale-range"),en=o.aC(X,Rn,Kn),Ls={bucket:J,layout:ye,paint:Ce,posMatrix:dt,invMatrix:xs,mercatorCenter:[o.aH(this.transform.center.lng),o.aL(this.transform.center.lat)],textLabelPlaneMatrix:Gt,labelToScreenMatrix:ss,clippingData:Ks,scale:Xe,textPixelRatio:Ke,holdingForFade:F.holdingForFade(),collisionBoxArray:Le,partiallyEvaluatedTextSize:o.bj(J.textSizeData,this.transform.zoom,hn),partiallyEvaluatedIconSize:o.bj(J.iconSizeData,this.transform.zoom,en),collisionGroup:this.collisionGroups.get(J.sourceID),latestFeatureIndex:F.latestFeatureIndex};if(G)for(const yn of J.sortKeyRanges){const{sortKey:jn,symbolInstanceStart:An,symbolInstanceEnd:jr}=yn;w.push({sortKey:jn,symbolInstanceStart:An,symbolInstanceEnd:jr,parameters:Ls})}else w.push({symbolInstanceStart:0,symbolInstanceEnd:J.symbolInstances.length,parameters:Ls})}attemptAnchorPlacement(w,E,F,G,X,J,de,ye,Ce,Le,Xe,Ke,st,dt,it,jt,wt,Bt,Vt,Ct,Ss){const{textOffset0:rs,textOffset1:_s,crossTileID:Gt}=it,ss=[rs,_s],xs=ol(w,J,de,ss,ye),Ks=this.collisionIndex.placeCollisionBox(wt,ye,E,F,G,X,vc(xs.x,xs.y,Ce,Le,this.transform.angle),dt,Xe,Ke,st.predicate);if(Vt){const Ts=wt.getSymbolInstanceIconSize(Ss,this.transform.zoom,it.placedIconSymbolIndex);if(this.collisionIndex.placeCollisionBox(wt,Ts,Vt,F,G,X,vc(xs.x,xs.y,Ce,Le,this.transform.angle),dt,Xe,Ke,st.predicate).box.length===0)return}if(Ks.box.length>0){let Ts;return this.prevPlacement&&this.prevPlacement.variableOffsets[Gt]&&this.prevPlacement.placements[Gt]&&this.prevPlacement.placements[Gt].text&&(Ts=this.prevPlacement.variableOffsets[Gt].anchor),this.variableOffsets[Gt]={textOffset:ss,width:J,height:de,anchor:w,textScale:ye,prevAnchor:Ts},this.markUsedJustification(wt,w,it,Bt),wt.allowVerticalPlacement&&(this.markUsedOrientation(wt,Bt,it),this.placedOrientations[Gt]=Bt),{shift:xs,placedGlyphBoxes:Ks}}}placeLayerBucketPart(w,E,F,G,X=1){const{bucket:J,layout:de,paint:ye,posMatrix:Ce,textLabelPlaneMatrix:Le,labelToScreenMatrix:Xe,clippingData:Ke,textPixelRatio:st,mercatorCenter:dt,invMatrix:it,holdingForFade:jt,collisionBoxArray:wt,partiallyEvaluatedTextSize:Bt,partiallyEvaluatedIconSize:Vt,collisionGroup:Ct,latestFeatureIndex:Ss}=w.parameters,rs=de.get("text-optional"),_s=de.get("icon-optional"),Gt=de.get("text-allow-overlap"),ss=de.get("icon-allow-overlap"),xs=de.get("text-rotation-alignment")==="map",Ks=de.get("icon-rotation-alignment")==="map",Ts=de.get("text-pitch-alignment")==="map",_n=ye.get("symbol-z-offset"),hn=de.get("symbol-elevation-reference")==="sea",Rn=de.get("symbol-placement"),[Kn,en]=de.get("text-size-scale-range"),[Ls,yn]=de.get("icon-size-scale-range"),jn=o.aC(X,Kn,en),An=o.aC(X,Ls,yn),jr=de.get("text-variable-anchor"),ur=xs&&Rn!=="point",hr=Ks&&Rn!=="point",Vn=jr&&J.hasTextData(),ca=J.hasIconTextFit()&&Vn&&J.hasIconData();this.transform.setProjection(J.projection);const Na=Vn||ur,ea=hr||ca;let ia=Gt&&(ss||!J.hasIconData()||_s),ii=ss&&(Gt||!J.hasTextData()||rs);const Ni=!_n.isConstant();!J.collisionArrays&&wt&&J.deserializeCollisionBoxes(wt),F&&G&&J.updateCollisionDebugBuffers(this.transform.zoom,wt,jn,An);const yi=(Ha,eo,vi)=>{const{crossTileID:Wo,numVerticalGlyphVertices:oc}=Ha;let Ed=null;if(Ke&&Ke.dynamicFilterNeedsFeature||Ni){const Fc=this.retainedQueryData[J.bucketInstanceId],Kc=Ss.loadFeature({featureIndex:Ha.featureIndex,bucketIndex:Fc.bucketIndex,sourceLayerIndex:Fc.sourceLayerIndex,layoutVertexArrayOffset:0}),Kl=Kc.properties?Kc.properties.worldview:null;if(J.localizable&&J.worldview&&typeof Kl=="string")if(Kl==="all")Kc.properties.$localized=!0;else{if(!Kl.split(",").includes(J.worldview))return;Kc.properties.$localized=!0,Kc.properties.worldview=J.worldview}Ed=Ke&&Ke.needGeometry?o.bD(Kc,!0):Kc}if(Ke&&!(0,Ke.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:J.worldview},Ed,this.retainedQueryData[J.bucketInstanceId].tileID.canonical,new o.P(Ha.tileAnchorX,Ha.tileAnchorY),this.transform.calculateDistanceTileData(Ke.unwrappedTileID)))return this.placements[Wo]=new Ra(!1,!1,!1,!0),void E.add(Wo);const Tc=_n.evaluate(Ed,{});if((Ha.zOffset||0)+(Tc||0)>0&&this.frontCutoffStart>0){const Fc=2*this.frontCutoffStart-1,Kc=[Ha.tileAnchorX,Ha.tileAnchorY,0,1],Kl=o.aE(o.bE(),Kc,Ce);if(Kl[1]/Kl[3]{Fc.tileID=this.retainedQueryData[J.bucketInstanceId].tileID;const Kc=this.transform.elevation;Fc.elevation=hn?Tc:Tc+o.bu.getAtTileOffset(Fc.tileID,new o.P(Fc.tileAnchorX,Fc.tileAnchorY),Kc,_m),Fc.elevation+=Ha.zOffset},Pv=vi.textBox;if(Pv){ef(Pv);const Fc=Kl=>{let nh=o.bk.horizontal;if(J.allowVerticalPlacement&&!Kl&&this.prevPlacement){const nx=this.prevPlacement.placedOrientations[Wo];nx&&(this.placedOrientations[Wo]=nx,nh=nx,this.markUsedOrientation(J,nh,Ha))}return nh},Kc=(Kl,nh)=>{if(J.allowVerticalPlacement&&oc>0&&vi.verticalTextBox){for(const nx of J.writingModes)if(nx===o.bk.vertical?(Ti=nh(),yd=Ti):Ti=Kl(),Ti&&Ti.box&&Ti.box.length)break}else Ti=Kl()};if(jr){let Kl=jr;if(this.prevPlacement&&this.prevPlacement.variableOffsets[Wo]){const hu=this.prevPlacement.variableOffsets[Wo];Kl.indexOf(hu.anchor)>0&&(Kl=Kl.filter(Lv=>Lv!==hu.anchor),Kl.unshift(hu.anchor))}const nh=(hu,Lv,KS)=>{const B3=J.getSymbolInstanceTextSize(Bt,Ha,this.transform.zoom,eo),U3=(hu.x2-hu.x1)*B3+2*hu.padding,BE=(hu.y2-hu.y1)*B3+2*hu.padding,HN=Ha.hasIconTextFit&&!ss?Lv:null;HN&&ef(HN);let Wj={box:[],offscreen:!1,occluded:!1};const UE=Gt?2*Kl.length:Kl.length;for(let Dy=0;Dy=Kl.length,Ha,eo,J,KS,HN,Bt,Vt);if(YS&&(Wj=YS.placedGlyphBoxes,Wj&&Wj.box&&Wj.box.length)){hl=!0,ml=YS.shift;break}}return Wj};Kc(()=>nh(Pv,vi.iconBox,o.bk.horizontal),()=>{const hu=vi.verticalTextBox;return hu&&ef(hu),J.allowVerticalPlacement&&!(Ti&&Ti.box&&Ti.box.length)&&oc>0&&hu?nh(hu,vi.verticalIconBox,o.bk.vertical):{box:null,offscreen:null,occluded:null}}),Ti&&(hl=Ti.box,$i=Ti.offscreen,Mc=Ti.occluded);const nx=Fc(!(!Ti||!Ti.box));if(!hl&&this.prevPlacement){const hu=this.prevPlacement.variableOffsets[Wo];hu&&(this.variableOffsets[Wo]=hu,this.markUsedJustification(J,hu.anchor,Ha,nx))}}else{const Kl=(nh,nx)=>{const hu=J.getSymbolInstanceTextSize(Bt,Ha,this.transform.zoom,eo),Lv=this.collisionIndex.placeCollisionBox(J,hu,nh,dt,it,Na,new o.P(0,0),Gt,st,Ce,Ct.predicate);return Lv&&Lv.box&&Lv.box.length&&(this.markUsedOrientation(J,nx,Ha),this.placedOrientations[Wo]=nx),Lv};Kc(()=>Kl(Pv,o.bk.horizontal),()=>{const nh=vi.verticalTextBox;return J.allowVerticalPlacement&&oc>0&&nh?(ef(nh),Kl(nh,o.bk.vertical)):{box:null,offscreen:null,occluded:null}}),Fc(!!(Ti&&Ti.box&&Ti.box.length))}}if(lc=Ti,hl=lc&&lc.box&&lc.box.length>0,$i=lc&&lc.offscreen,Mc=lc&&lc.occluded,Ha.useRuntimeCollisionCircles){const Fc=Ha.centerJustifiedTextSymbolIndex>=0?Ha.centerJustifiedTextSymbolIndex:Ha.verticalPlacedTextSymbolIndex,Kc=J.text.placedSymbolArray.get(Fc),Kl=o.bl(J.textSizeData,Bt,Kc),nh=de.get("text-padding");gh=this.collisionIndex.placeCollisionCircles(J,Gt,Kc,Fc,J.lineVertexArray,J.glyphOffsetArray,Kl,Ce,Le,Xe,F,Ts,Ct.predicate,Ha.collisionCircleDiameter*Kl/o.by,nh,this.retainedQueryData[J.bucketInstanceId].tileID),hl=Gt||gh.circles.length>0&&!gh.collisionDetected,$i=$i&&gh.offscreen,Mc=gh.occluded}if(vi.iconFeatureIndex&&(jg=vi.iconFeatureIndex),vi.iconBox){const Fc=Kc=>{ef(Kc);const Kl=Ha.hasIconTextFit&&ml?vc(ml.x,ml.y,xs,Ts,this.transform.angle):new o.P(0,0),nh=J.getSymbolInstanceIconSize(Vt,this.transform.zoom,Ha.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(J,nh,Kc,dt,it,ea,Kl,ss,st,Ce,Ct.predicate)};yd&&yd.box&&yd.box.length&&vi.verticalIconBox?(po=Fc(vi.verticalIconBox),qi=po.box.length>0):(po=Fc(vi.iconBox),qi=po.box.length>0),$i=$i&&po.offscreen,$d=po.occluded}const Rl=rs||Ha.numHorizontalGlyphVertices===0&&oc===0,E1=_s||Ha.numIconVertices===0;if(Rl||E1?E1?Rl||(qi=qi&&hl):hl=qi&&hl:qi=hl=qi&&hl,hl&&lc&&lc.box&&this.collisionIndex.insertCollisionBox(lc.box,de.get("text-ignore-placement"),J.bucketInstanceId,yd&&yd.box&&am?am:jc,Ct.ID),qi&&po&&this.collisionIndex.insertCollisionBox(po.box,de.get("icon-ignore-placement"),J.bucketInstanceId,jg,Ct.ID),gh&&(hl&&this.collisionIndex.insertCollisionCircles(gh.circles,de.get("text-ignore-placement"),J.bucketInstanceId,jc,Ct.ID),F)){const Fc=J.bucketInstanceId;let Kc=this.collisionCircleArrays[Fc];Kc===void 0&&(Kc=this.collisionCircleArrays[Fc]=new nr);for(let Kl=0;Kl=0;--eo){const vi=Ha[eo];yi(J.symbolInstances.get(vi),vi,J.collisionArrays[vi])}J.hasAnyZOffset&&o.w(`${J.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`)}else if(J.hasAnyZOffset){const Ha=J.getSortedIndexesByZOffset();for(let eo=0;eo=0&&(w.text.placedSymbolArray.get(X).crossTileID=Xe>=0&&X!==Xe?0:Ce),J>=0&&(w.text.placedSymbolArray.get(J).crossTileID=Xe>=0&&J!==Xe?0:Ce),de>=0&&(w.text.placedSymbolArray.get(de).crossTileID=Xe>=0&&de!==Xe?0:Ce),ye>=0&&(w.text.placedSymbolArray.get(ye).crossTileID=Xe>=0&&ye!==Xe?0:Ce)}markUsedOrientation(w,E,F){const G=E===o.bk.horizontal||E===o.bk.horizontalOnly?E:0,X=E===o.bk.vertical?E:0,{leftJustifiedTextSymbolIndex:J,centerJustifiedTextSymbolIndex:de,rightJustifiedTextSymbolIndex:ye,verticalPlacedTextSymbolIndex:Ce}=F,Le=w.text.placedSymbolArray;J>=0&&(Le.get(J).placedOrientation=G),de>=0&&(Le.get(de).placedOrientation=G),ye>=0&&(Le.get(ye).placedOrientation=G),Ce>=0&&(Le.get(Ce).placedOrientation=X)}commit(w){this.commitTime=w,this.zoomAtLastRecencyCheck=this.transform.zoom;const E=this.prevPlacement;let F=!1;this.prevZoomAdjustment=E?E.zoomAdjustment(this.transform.zoom):0;const G=E?E.symbolFadeChange(w):1,X=E?E.opacities:{},J=E?E.variableOffsets:{},de=E?E.placedOrientations:{};for(const ye in this.placements){const Ce=this.placements[ye],Le=X[ye];Le?(this.opacities[ye]=new Ma(Le,G,Ce.text,Ce.icon,null,Ce.clipped),F=F||Ce.text!==Le.text.placed||Ce.icon!==Le.icon.placed):(this.opacities[ye]=new Ma(null,G,Ce.text,Ce.icon,Ce.skipFade,Ce.clipped),F=F||Ce.text||Ce.icon)}for(const ye in X){const Ce=X[ye];if(!this.opacities[ye]){const Le=new Ma(Ce,G,!1,!1);Le.isHidden()||(this.opacities[ye]=Le,F=F||Ce.text.placed||Ce.icon.placed)}}for(const ye in J)this.variableOffsets[ye]||!this.opacities[ye]||this.opacities[ye].isHidden()||(this.variableOffsets[ye]=J[ye]);for(const ye in de)this.placedOrientations[ye]||!this.opacities[ye]||this.opacities[ye].isHidden()||(this.placedOrientations[ye]=de[ye]);F?this.lastPlacementChangeTime=w:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=E?E.lastPlacementChangeTime:w)}updateLayerOpacities(w,E,F,G){G&&(this.lastReplacementSourceUpdateTime=G.updateTime);const X=new Set;for(const J of E){const de=J.getBucket(w);de&&J.latestFeatureIndex&&w.fqid===de.layerIds[0]&&(this.updateBucketOpacities(de,X,J,J.collisionBoxArray,F,G,J.tileID,w.scope),de.elevationType==="offset"&&this.buildingIndex&&this.buildingIndex.updateZOffset(de,J.tileID),de.elevationType==="road"&&de.updateRoadElevation(J.tileID.canonical),de.updateZOffset())}}updateBucketOpacities(w,E,F,G,X,J,de,ye){w.hasTextData()&&w.text.opacityVertexArray.clear(),w.hasIconData()&&w.icon.opacityVertexArray.clear(),w.hasIconCollisionBoxData()&&w.iconCollisionBox.collisionVertexArray.clear(),w.hasTextCollisionBoxData()&&w.textCollisionBox.collisionVertexArray.clear();const Ce=w.layers[0].layout,Le=w.layers[0].paint,Xe=!!w.layers[0].dynamicFilter(),Ke=new Ma(null,0,!1,!1,!0),st=Ce.get("text-allow-overlap"),dt=Ce.get("icon-allow-overlap"),it=Ce.get("text-variable-anchor"),jt=Ce.get("text-rotation-alignment")==="map",wt=Ce.get("text-pitch-alignment")==="map",Bt=Le.get("symbol-z-offset"),Vt=Ce.get("symbol-elevation-reference")==="sea",Ct=!Bt.isConstant(),Ss=new Ma(null,0,st&&(dt||!w.hasIconData()||Ce.get("icon-optional")),dt&&(st||!w.hasTextData()||Ce.get("text-optional")),!0);!w.collisionArrays&&G&&(w.hasIconCollisionBoxData()||w.hasTextCollisionBoxData())&&w.deserializeCollisionBoxes(G);const rs=(Gt,ss,xs)=>{for(let Ks=0;Ks0||Ks>0,jr=_n>0,ur=this.placedOrientations[Ts],hr=ur===o.bk.vertical,Vn=ur===o.bk.horizontal||ur===o.bk.horizontalOnly;!An&&!jr||jn.isHidden()||_s++;let ca=!1;if((An||jr)&&J)for(const Na of w.activeReplacements){if(o.bz(Na,X,o.bA.Symbol,ye)||Na.min.x>hn||hn>Na.max.x||Na.min.y>Rn||Rn>Na.max.y)continue;const ea=o.bB(hn,Rn,de.canonical,Na.footprintTileId.canonical);if(ca=o.bC(ea,Na.footprint),ca)break}if(ca&&this.collisionIndex.markSymbolAsClipped(w.bucketInstanceId,ss.featureIndex),An){const Na=ca?Kp:wu(jn.text);rs(w.text,xs,hr?Kp:Na),rs(w.text,Ks,Vn?Kp:Na);const ea=jn.text.isHidden(),{leftJustifiedTextSymbolIndex:ia,centerJustifiedTextSymbolIndex:ii,rightJustifiedTextSymbolIndex:Ni,verticalPlacedTextSymbolIndex:yi}=ss,Ji=w.text.placedSymbolArray,Ha=ea||hr?1:0;ia>=0&&(Ji.get(ia).hidden=Ha),ii>=0&&(Ji.get(ii).hidden=Ha),Ni>=0&&(Ji.get(Ni).hidden=Ha),yi>=0&&(Ji.get(yi).hidden=ea||Vn?1:0);const eo=this.variableOffsets[Ts];eo&&this.markUsedJustification(w,eo.anchor,ss,ur);const vi=this.placedOrientations[Ts];vi&&(this.markUsedJustification(w,"left",ss,vi),this.markUsedOrientation(w,vi,ss))}if(jr){const Na=ca?Kp:wu(jn.icon),{placedIconSymbolIndex:ea,verticalPlacedIconSymbolIndex:ia}=ss,ii=w.icon.placedSymbolArray,Ni=jn.icon.isHidden()?1:0;ea>=0&&(rs(w.icon,_n,hr?Kp:Na),ii.get(ea).hidden=Ni),ia>=0&&(rs(w.icon,ss.numVerticalIconVertices,Vn?Kp:Na),ii.get(ia).hidden=Ni)}if(w.hasIconCollisionBoxData()||w.hasTextCollisionBoxData()){const Na=w.collisionArrays[Gt];if(Na){let ea=new o.P(0,0),ia=!0;if(Na.textBox||Na.verticalTextBox){if(it){const Ni=this.variableOffsets[Ts];Ni?(ea=ol(Ni.anchor,Ni.width,Ni.height,Ni.textOffset,Ni.textScale),jt&&ea._rotate(wt?this.transform.angle:-this.transform.angle)):ia=!1}Xe&&(ia=!jn.clipped),Na.textBox&&$m(w.textCollisionBox.collisionVertexArray,jn.text.placed,!ia||hr,Ls,Vt,ea.x,ea.y),Na.verticalTextBox&&$m(w.textCollisionBox.collisionVertexArray,jn.text.placed,!ia||Vn,Ls,Vt,ea.x,ea.y)}const ii=ia&&!!(!Vn&&Na.verticalIconBox);Na.iconBox&&$m(w.iconCollisionBox.collisionVertexArray,jn.icon.placed,ii,Ls,Vt,ss.hasIconTextFit?ea.x:0,ss.hasIconTextFit?ea.y:0),Na.verticalIconBox&&$m(w.iconCollisionBox.collisionVertexArray,jn.icon.placed,!ii,Ls,Vt,ss.hasIconTextFit?ea.x:0,ss.hasIconTextFit?ea.y:0)}}}if(w.fullyClipped=_s===0,w.sortFeatures(this.transform.angle),this.retainedQueryData[w.bucketInstanceId]&&(this.retainedQueryData[w.bucketInstanceId].featureSortOrder=w.featureSortOrder),w.hasTextData()&&w.text.opacityVertexBuffer&&w.text.opacityVertexBuffer.updateData(w.text.opacityVertexArray),w.hasIconData()&&w.icon.opacityVertexBuffer&&w.icon.opacityVertexBuffer.updateData(w.icon.opacityVertexArray),w.hasIconCollisionBoxData()&&w.iconCollisionBox.collisionVertexBuffer&&w.iconCollisionBox.collisionVertexBuffer.updateData(w.iconCollisionBox.collisionVertexArray),w.hasTextCollisionBoxData()&&w.textCollisionBox.collisionVertexBuffer&&w.textCollisionBox.collisionVertexBuffer.updateData(w.textCollisionBox.collisionVertexArray),w.bucketInstanceId in this.collisionCircleArrays){const Gt=this.collisionCircleArrays[w.bucketInstanceId];w.placementInvProjMatrix=Gt.invProjMatrix,w.placementViewportMatrix=Gt.viewportMatrix,w.collisionCircleArray=Gt.circles,delete this.collisionCircleArrays[w.bucketInstanceId]}}symbolFadeChange(w){return this.fadeDuration===0?1:(w-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(w){return Math.max(0,(this.transform.zoom-w)/1.5)}hasTransitions(w){return w-this.lastPlacementChangeTimew}isStale(){return this.stale}setStale(){this.stale=!0}}function $m(D,w,E,F,G,X,J){D.emplaceBack(w?1:0,E?1:0,X||0,J||0,F,G?1:0),D.emplaceBack(w?1:0,E?1:0,X||0,J||0,F,G?1:0),D.emplaceBack(w?1:0,E?1:0,X||0,J||0,F,G?1:0),D.emplaceBack(w?1:0,E?1:0,X||0,J||0,F,G?1:0)}const k0=Math.pow(2,25),S0=Math.pow(2,24),Xu=Math.pow(2,17),Ac=Math.pow(2,16),Ab=Math.pow(2,9),Mx=Math.pow(2,8),wy=Math.pow(2,1);function wu(D){if(D.opacity===0&&!D.placed)return 0;if(D.opacity===1&&D.placed)return 4294967295;const w=D.placed?1:0,E=Math.floor(127*D.opacity);return E*k0+w*S0+E*Xu+w*Ac+E*Ab+w*Mx+E*wy+w}const Kp=0;class jy{constructor(w){this._sortAcrossTiles=w.layout.get("symbol-z-order")!=="viewport-y"&&w.layout.get("symbol-sort-key").constantOr(1)!==void 0,this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs=new Set,this._bucketParts=[]}continuePlacement(w,E,F,G,X,J){const de=this._bucketParts;for(;this._currentTileIndexye.sortKey-Ce.sortKey));this._currentPartIndex{const ye=o.o.now()-J;return!this.isFullPlacementRequested()&&this._fadeDuration!==0&&ye>2};for(;this._currentPlacementIndex>=0;){const ye=E[w[this._currentPlacementIndex]],Ce=this.placement.collisionIndex.transform.zoom;if(ye.type==="symbol"&&ye.visibility!=="none"&&(!ye.minzoom||ye.minzoom<=Ce)&&(!ye.maxzoom||ye.maxzoom>Ce)){const Le=ye,Xe=Le.layout.get("symbol-z-elevate"),Ke=Le.layout.get("symbol-sort-key").constantOr(1)!==void 0,st=Le.layout.get("symbol-z-order"),dt=st==="viewport-y"||st==="auto"&&!(st!=="viewport-y"&&Ke),it=Le.layout.get("text-allow-overlap")||Le.layout.get("icon-allow-overlap")||Le.layout.get("text-ignore-placement")||Le.layout.get("icon-ignore-placement"),jt=dt&&it,wt=this._inProgressLayer=this._inProgressLayer||new jy(Le),Bt=o.F(ye.source,ye.scope);if(wt.continuePlacement(Xe||jt?G[Bt]:F[Bt],this.placement,this._showCollisionBoxes,ye,de,X))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(w){return this.placement.commit(w),this.placement}}const Bd=512/o.an/2;class tu{constructor(w,E,F){this.tileID=w,this.bucketInstanceId=F,this.index=new o.bI(E.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const G=w.canonical.x*o.an,X=w.canonical.y*o.an;for(let J=0;Jjt-wt);for(const jt of it){const wt=this.crossTileIDs[jt];if(this.keys[jt]===Le&&!F.has(wt)){F.add(wt),Ce.crossTileID=wt;break}}}}}class uh{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class fp{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(w){const E=Math.round((w-this.lng)/360);if(E!==0)for(const F in this.indexes){const G=this.indexes[F],X={};for(const J in G){const de=G[J];de.tileID=de.tileID.unwrapTo(de.tileID.wrap+E),X[de.tileID.key]=de}this.indexes[F]=X}this.lng=w}addBucket(w,E,F){if(this.indexes[w.overscaledZ]&&this.indexes[w.overscaledZ][w.key]){if(this.indexes[w.overscaledZ][w.key].bucketInstanceId===E.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(w.overscaledZ,this.indexes[w.overscaledZ][w.key])}for(let X=0;Xw.overscaledZ)for(const de in J){const ye=J[de];ye.tileID.isChildOf(w)&&ye.findMatches(E.symbolInstances,w,G)}else{const de=J[w.scaledTo(Number(X)).key];de&&de.findMatches(E.symbolInstances,w,G)}}for(let X=0;X{E[F]=!0});for(const F in this.layerIndexes)E[F]||delete this.layerIndexes[F]}}const Hl=771;class Ia{constructor(w,E,F,G){this.blendFunction=w,this.blendColor=E.toNonPremultipliedRenderColor(null),this.mask=F,this.blendEquation=G}}Ia.Replace=[1,0,1,0],Ia.disabled=new Ia(Ia.Replace,o.aq.transparent,[!1,!1,!1,!1]),Ia.unblended=new Ia(Ia.Replace,o.aq.transparent,[!0,!0,!0,!0]),Ia.alphaBlended=new Ia([1,Hl,1,Hl],o.aq.transparent,[!0,!0,!0,!0]),Ia.alphaBlendedNonPremultiplied=new Ia([770,Hl,770,Hl],o.aq.transparent,[!0,!0,!0,!0]),Ia.multiply=new Ia([774,0,774,0],o.aq.transparent,[!0,!0,!0,!0]),Ia.multiplyAccumulateAlpha=new Ia([774,0,1,Hl],o.aq.transparent,[!0,!0,!0,!0]),Ia.additive=new Ia([1,1,1,1],o.aq.transparent,[!0,!0,!0,!0]);class Hr{constructor(w,E,F){this.func=w,this.mask=E,this.range=F}}Hr.ReadOnly=!1,Hr.ReadWrite=!0,Hr.disabled=new Hr(519,Hr.ReadOnly,[0,1]);const bc=7680;class Da{constructor(w,E,F,G,X,J){this.test=w,this.ref=E,this.mask=F,this.fail=G,this.depthFail=X,this.pass=J}}Da.disabled=new Da({func:519,mask:0},0,0,bc,bc,bc);const gp=1029,Ud=2305;class fa{constructor(w,E,F){this.enable=w,this.mode=E,this.frontFace=F}}function Px(D,w){const E=o.bO(D,3);o.bR(D,w),o.bW(D,3,E)}function C0(D,w){const E=o.bL([]);return o.bM(E,E,-w),o.bN(E,E,-D),E}function Jg(D,w){const E=[D[0],D[1],0],F=[w[0],w[1],0];if(o.ai(E)>=1e-15){const J=o.ay([],E);o.bJ(F,J,o.bi(F,J)),w[0]=F[0],w[1]=F[1]}const G=o.bh([],w,D);if(o.bK(G)<1e-15)return null;const X=Math.atan2(-G[1],G[0]);return C0(Math.atan2(Math.sqrt(D[0]*D[0]+D[1]*D[1]),-D[2]),X)}fa.disabled=new fa(!1,gp,Ud),fa.backCCW=new fa(!0,gp,Ud),fa.backCW=new fa(!0,gp,2304),fa.frontCW=new fa(!0,1028,2304),fa.frontCCW=new fa(!0,1028,Ud);class Ny{constructor(w,E){this.position=w,this.orientation=E}get position(){return this._position}set position(w){if(w){const E=w instanceof o.ag?w:new o.ag(w[0],w[1],w[2]);this._renderWorldCopies&&(E.x=o.bs(E.x,0,1)),this._position=E}else this._position=null}lookAtPoint(w,E,F){if(this.orientation=null,!this.position)return;const G=this.position,X=F||(this._elevation?this._elevation.getAtPointOrZero(o.ag.fromLngLat(w)):0),J=o.ag.fromLngLat(w,X),de=[J.x-G.x,J.y-G.y,J.z-G.z];E||(E=[0,0,1]),E[2]=Math.abs(E[2]),this.orientation=Jg(de,E)}setPitchBearing(w,E){this.orientation=C0(o.ap(w),o.ap(-E))}}class yg{constructor(w,E){this._transform=o.b9([]),this.orientation=E,this.position=w}get mercatorPosition(){const w=this.position;return new o.ag(w[0],w[1],w[2])}get position(){const w=o.bO(this._transform,3);return[w[0],w[1],w[2]]}set position(w){var E;w&&o.bW(this._transform,3,[(E=w)[0],E[1],E[2],1])}get orientation(){return this._orientation}set orientation(w){this._orientation=w||o.bL([]),w&&Px(this._transform,this._orientation)}getPitchBearing(){const w=this.forward(),E=this.right();return{bearing:Math.atan2(-E[1],E[0]),pitch:Math.atan2(Math.sqrt(w[0]*w[0]+w[1]*w[1]),-w[2])}}setPitchBearing(w,E){this._orientation=C0(w,E),Px(this._transform,this._orientation)}forward(){const w=o.bO(this._transform,2);return[-w[0],-w[1],-w[2]]}up(){const w=o.bO(this._transform,1);return[-w[0],-w[1],-w[2]]}right(){const w=o.bO(this._transform,0);return[w[0],w[1],w[2]]}getCameraToWorld(w,E){const F=new Float64Array(16);return o.b7(F,this.getWorldToCamera(w,E)),F}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(w,E,F){const G=this.position;o.bJ(G,G,-w);const X=new Float64Array(16);return o.bP(X,[F,F,F]),o.bx(X,X,G),X[10]*=E,X}getWorldToCamera(w,E){const F=new Float64Array(16),G=new Float64Array(4),X=this.position;return o.bQ(G,this._orientation),o.bJ(X,X,-w),o.bR(F,G),o.bx(F,F,X),F[1]*=-1,F[5]*=-1,F[9]*=-1,F[13]*=-1,F[8]*=E,F[9]*=E,F[10]*=E,F[11]*=E,F}getCameraToClipPerspective(w,E,F,G){const X=new Float64Array(16);return o.bS(X,w,E,F,G),X}getCameraToClipOrthographic(w,E,F,G,X,J){const de=new Float64Array(16);return o.bT(de,w,E,F,G,X,J),de}getDistanceToElevation(w,E=!1){const F=w===0?0:o.bU(w,E?o.bV(this.position[1]):this.position[1]),G=this.forward();return(F-this.position[2])/G[2]}clone(){return new yg([...this.position],[...this.orientation])}}const gd=(D,w)=>({u_matrix:D,u_ground_shadow_factor:w});class Yp{constructor(w=0,E=0,F=0,G=0){if(isNaN(w)||w<0||isNaN(E)||E<0||isNaN(F)||F<0||isNaN(G)||G<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=w,this.bottom=E,this.left=F,this.right=G}interpolate(w,E,F){return E.top!=null&&w.top!=null&&(this.top=o.am(w.top,E.top,F)),E.bottom!=null&&w.bottom!=null&&(this.bottom=o.am(w.bottom,E.bottom,F)),E.left!=null&&w.left!=null&&(this.left=o.am(w.left,E.left,F)),E.right!=null&&w.right!=null&&(this.right=o.am(w.right,E.right,F)),this}getCenter(w,E){const F=o.aC((this.left+w-this.right)/2,0,w),G=o.aC((this.top+E-this.bottom)/2,0,E);return new o.P(F,G)}equals(w){return this.top===w.top&&this.bottom===w.bottom&&this.left===w.left&&this.right===w.right}clone(){return new Yp(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const em=15;class Qu{constructor(w,E,F,G,X,J,de){this.tileSize=512,this._renderWorldCopies=X===void 0||X,this._minZoom=w||0,this._maxZoom=E||22,this._minPitch=F??0,this._maxPitch=G??60,this.setProjection(J),this.setMaxBounds(de),this.width=0,this.height=0,this._center=new o.aU(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._nearZ=0,this._farZ=0,this._nearClipOffset=0,this._unmodified=!0,this._edgeInsets=new Yp,this._projMatrixCache={},this._alignedProjMatrixCache={},this._fogTileMatrixCache={},this._expandedProjMatrixCache={},this._distanceTileDataCache={},this._camera=new yg,this._centerAltitude=0,this._averageElevation=0,this.cameraElevationReference="ground",this._pixelsPerMercatorPixel=1,this.globeRadius=0,this.globeCenterInViewSpace=[0,0,0],this._tileCoverLift=0,this.freezeTileCoverage=!1,this._horizonShift=.1,this._orthographicProjectionAtLowPitch=!1,this._allowWorldUnderZoom=!1}clone(){const w=new Qu(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies,this.getProjection(),this.maxBounds);return w._elevation=this._elevation,w._centerAltitude=this._centerAltitude,w._centerAltitudeValidForExaggeration=this._centerAltitudeValidForExaggeration,w.tileSize=this.tileSize,w.mercatorFromTransition=this.mercatorFromTransition,w.width=this.width,w.height=this.height,w.cameraElevationReference=this.cameraElevationReference,w._center=this._center,w._setZoom(this.zoom),w._seaLevelZoom=this._seaLevelZoom,w.angle=this.angle,w._fov=this._fov,w._pitch=this._pitch,w._nearZ=this._nearZ,w._farZ=this._farZ,w._nearClipOffset=this._nearClipOffset,w._averageElevation=this._averageElevation,w._orthographicProjectionAtLowPitch=this._orthographicProjectionAtLowPitch,w._unmodified=this._unmodified,w._edgeInsets=this._edgeInsets.clone(),w._camera=this._camera.clone(),w._calcMatrices(),w.freezeTileCoverage=this.freezeTileCoverage,w.frustumCorners=this.frustumCorners,w._allowWorldUnderZoom=this._allowWorldUnderZoom,w}get isOrthographic(){return this.projection.name!=="globe"&&this._orthographicProjectionAtLowPitch&&this.pitch0&&this.elevation.exaggeration()>0&&this._centerAltitudeValidForExaggeration;if(!this._elevation||w===Number.NEGATIVE_INFINITY&&(!E||!this._centerAltitude))return this._centerAltitude=0,this._seaLevelZoom=null,void(this._centerAltitudeValidForExaggeration=void 0);const F=this._elevation;E||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&F.exaggeration()&&this._centerAltitudeValidForExaggeration!==F.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*F.exaggeration(),this._centerAltitudeValidForExaggeration=F.exaggeration()):(this._centerAltitude=w||0,this._centerAltitudeValidForExaggeration=F.exaggeration()),this._updateSeaLevelZoom()}_updateSeaLevelZoom(){if(this._centerAltitudeValidForExaggeration===void 0)return;const w=Math.max(0,(this.pixelsPerMeter*this._centerAltitude+this.cameraToCenterDistance)/this.worldSize);this._seaLevelZoom=this._zoomFromMercatorZ(w)}sampleAverageElevation(){if(!this._elevation)return 0;const w=this._elevation,E=[[.5,.2],[.3,.5],[.5,.5],[.7,.5],[.5,.8]],F=this.horizonLineFromTop();let G=0,X=0;for(let J=0;J{const jt=o.ck(Ke,Xe,st,dt,it);ye.has(jt)||(X.push(new o.aR(Xe,Ke,st,dt,it)),ye.add(jt))};for(let Xe=0;XeKe.canonical.z)continue;const st=Ke.canonical,dt=Ke.overscaledZ,it=Ke.wrap,jt=1<0,Vt=st.y+10,Ss=Ke.wrap-(Bt?0:1),rs=Ke.wrap+(wt?0:1),_s=Bt?st.x-1:jt-1,Gt=wt?st.x+1:0;if(J)F[0]<0?(Ce(dt,rs,st.z,Gt,st.y),F[1]<0&&Vt&&(Ce(dt,it,st.z,st.x,st.y+1),Ce(dt,rs,st.z,Gt,st.y+1)),F[1]>0&&Ct&&(Ce(dt,it,st.z,st.x,st.y-1),Ce(dt,rs,st.z,Gt,st.y-1))):F[0]>0?(Ce(dt,Ss,st.z,_s,st.y),F[1]<0&&Vt&&(Ce(dt,it,st.z,st.x,st.y+1),Ce(dt,Ss,st.z,_s,st.y+1)),F[1]>0&&Ct&&(Ce(dt,it,st.z,st.x,st.y-1),Ce(dt,Ss,st.z,_s,st.y-1))):F[1]<0&&Vt?Ce(dt,it,st.z,st.x,st.y+1):Ct&&Ce(dt,it,st.z,st.x,st.y-1);else{const ss=Ke.visibleQuadrants;1&ss&&(Ce(dt,Ss,st.z,_s,st.y),Ct&&(Ce(dt,it,st.z,st.x,st.y-1),Ce(dt,Ss,st.z,_s,st.y-1))),2&ss&&(Ce(dt,rs,st.z,Gt,st.y),Ct&&(Ce(dt,it,st.z,st.x,st.y-1),Ce(dt,rs,st.z,Gt,st.y-1))),4&ss&&(Ce(dt,Ss,st.z,_s,st.y),Vt&&(Ce(dt,it,st.z,st.x,st.y+1),Ce(dt,Ss,st.z,_s,st.y+1))),8&ss&&(Ce(dt,rs,st.z,Gt,st.y),Vt&&(Ce(dt,it,st.z,st.x,st.y+1),Ce(dt,rs,st.z,Gt,st.y+1)))}}const Le=[];for(const Xe of X)X.some(Ke=>Xe.isChildOf(Ke))||Le.push(Xe);if(X=Le.filter(Xe=>!w.some(Ke=>!!(Xe.overscaledZ{const wt=jt.canonical.x+.5-st[0],Bt=jt.canonical.y+.5-st[1];return wt*wt+Bt*Bt{const _s=o.ck(Vt,Bt,Ct,Ss,rs);X.has(_s)||(G.push(new o.aR(Bt,Vt,Ct,Ss,rs)),X.add(_s))},de=w.reduce((Bt,Vt)=>Math.max(Bt,Vt.overscaledZ),F),ye=1<{const Ct=Math.floor(Bt[0]),Ss=Math.floor(Bt[1]),rs=(Bt[0]-Ct)*o.an,_s=(Bt[1]-Ss)*o.an,Gt=Math.floor(Vt[0]),ss=Math.floor(Vt[1]),xs=(Vt[0]-Gt)*o.an,Ks=(Vt[1]-ss)*o.an;for(let Ts=-1;Ts<=1;Ts++){const _n=Ct+Ts;if(!(_n<0||_n>=ye)){Le.x=rs-Ts*o.an,Xe.x=xs-(_n-Gt)*o.an;for(let hn=-1;hn<=1;hn++){const Rn=Ss+hn;Le.y=_s-hn*o.an,Xe.y=Ks-(Rn-ss)*o.an,o.cI(Le,Xe,Ce)&&J(de,0,F,_n,Rn)}}}},st=E.points,dt=st[o.c9],it=st[o.ca],jt=this._projectToGround(dt,st[o.cb]),wt=this._projectToGround(it,st[o.cc]);return Ke(dt,jt),Ke(it,wt),G}_projectToGround(w,E){return o.cd(o.ce(),w,E,w[2]/(w[2]-E[2]))}_projectToZ(w,E,F){const G=w[2]-E[2];return Math.abs(G)<1e-6?o.cf(w):o.cd(o.ce(),w,E,(w[2]-F)/G)}extendTileCoverForTunnels(w,E,F,G){if(F<18)return[];const X=E.points,J=X[o.cg],de=X[o.ch],ye=X[o.ci],Ce=X[o.cj];if(ye[2]>=0&&Ce[2]>=0||J[2]<=0||de[2]<=0)return[];const Le=ye[2]<0?this._projectToZ(J,ye,0):ye,Xe=Ce[2]<0?this._projectToZ(de,Ce,0):Ce,Ke=-G,st=ye[2]3&&(it.length=3),it}_findExtensionTilesInQuad(w,E,F,G){const X=[],J=new Set;for(const Gt of w)J.add(Gt.key);const de=w.reduce((Gt,ss)=>Math.max(Gt,ss.overscaledZ),E),ye=1<{const xs=Gt.canonical.x+.5-rs,Ks=Gt.canonical.y+.5-_s,Ts=ss.canonical.x+.5-rs,_n=ss.canonical.y+.5-_s;return xs*xs+Ks*Ks-(Ts*Ts+_n*_n)||Gt.canonical.x-ss.canonical.x||Gt.canonical.y-ss.canonical.y}),X}coveringTiles(w){let E=this.coveringZoomLevel(w);const F=E,G=this.elevation&&this.elevation.exaggeration(),X=G&&!w.isTerrainDEM,J=this.projection.name==="mercator";if(w.minzoom!==void 0&&Ew.maxzoom&&(E=w.maxzoom);const de=this.locationCoordinate(this.center),ye=this.center.lat,Ce=1<{const jn=new o.ag(Ls.x+25e-6,Ls.y,Ls.z),An=new o.ag(Ls.x,Ls.y+25e-6,Ls.z),jr=Ls.toLngLat(),ur=jn.toLngLat(),hr=An.toLngLat(),Vn=this.locationCoordinate(jr),ca=this.locationCoordinate(ur),Na=this.locationCoordinate(hr),ea=Math.hypot(ca.x-Vn.x,ca.y-Vn.y),ia=Math.hypot(Na.x-Vn.x,Na.y-Vn.y);return Math.sqrt(ea*ia)*_s/25e-6},ss=Ls=>{const yn=Ss,jn=rs;return{aabb:o.cp(this,Ce,0,0,0,Ls,jn,yn,this.projection),zoom:0,x:0,y:0,minZ:jn,maxZ:yn,wrap:Ls,fullyVisible:!1}},xs=[];let Ks=[];const Ts=E,_n=w.reparseOverscaled?F:E,hn=(jt-this._centerAltitude)*it,Rn=Ls=>{if(!this._elevation||!Ls.tileID||!J)return;const yn=this._elevation.getMinMaxForTile(Ls.tileID),jn=Ls.aabb;yn?(jn.min[2]=yn.min,jn.max[2]=yn.max,jn.center[2]=(jn.min[2]+jn.max[2])/2):(Ls.shouldSplit=en(Ls),Ls.shouldSplit||(jn.min[2]=jn.max[2]=jn.center[2]=this._centerAltitude))},Kn=(Ls,yn)=>{if(.707*yn{if(Ls.zoom=.9)return!0}else if(X&&(An=Ls.aabb.distanceZ(wt)*it),this.projection.isReprojectedInTileSpace&&F<=5){const ia=Math.pow(2,Ls.zoom),ii=Gt(new o.ag((Ls.x+.5)/ia,(Ls.y+.5)/ia));jr=ii>.85?1:ii}if(!J&&!Xe){const ia=Math.sqrt(yn*yn+jn*jn+An*An);let ii=(1<0;){const Ls=xs.pop(),yn=Ls.x,jn=Ls.y;let An=Ls.fullyVisible;const jr=()=>this.projection.name==="globe"&&(Ls.y===0||Ls.y===(1<ur)continue;let hr=0;if(!An){let ea=Bt?Ls.aabb.intersectsPrecise(st):Ls.aabb.intersectsPreciseFlat(st);if(ea===0&&jr()){const ia=new o.cn(Ls.zoom,yn,jn);ea=o.co(this,Ce,ia,!0).intersectsPrecise(st)}if(ea===0)continue;if(w.calculateQuadrantVisibility)if(st.containsPoint(Ls.aabb.center))hr=15;else for(let ia=0;ia<4;ia++)Ls.aabb.quadrant(ia).intersects(st)!==0&&(hr|=1<>1),ca={aabb:J?Ls.aabb.quadrant(ur):o.cp(this,Ce,Ls.zoom+1,hr,Vn,Ls.wrap,Ls.minZ,Ls.maxZ,this.projection),zoom:Ls.zoom+1,x:hr,y:Vn,wrap:Ls.wrap,fullyVisible:An,tileID:void 0,shouldSplit:void 0,minZ:Ls.minZ,maxZ:Ls.maxZ};X&&!Xe&&(ca.tileID=new o.aR(Ls.zoom+1===Ts?_n:Ls.zoom+1,Ls.wrap,Ls.zoom+1,hr,Vn),Rn(ca)),xs.push(ca)}}if(this.fogCullDistSq){const Ls=this.fogCullDistSq,yn=this.horizonLineFromTop();Ks=Ks.filter(jn=>{const An=[0,0,0,1],jr=[o.an,o.an,0,1],ur=this.calculateFogTileMatrix(jn.tileID.toUnwrapped());o.aE(An,An,ur),o.aE(jr,jr,ur);const hr=o.cq([],An,jr),Vn=o.cr([],An,jr),ca=o.cK(hr,Vn);if(ca===0)return!0;let Na=!1;const ea=this._elevation;if(ea&&ca>Ls&&yn!==0){const ia=this.calculateProjMatrix(jn.tileID.toUnwrapped());let ii;w.isTerrainDEM||(ii=ea.getMinMaxForTile(jn.tileID)),ii||(ii={min:rs,max:Ss});const Ni=o.cs(this.rotation),yi=[Ni[0]*o.an,Ni[1]*o.an,ii.max];o.ah(yi,yi,ia),Na=(1-yi[1])*this.height*.5Ls.distanceSq-yn.distanceSq).map(Ls=>Ls.tileID)}resize(w,E){this.width=w,this.height=E,this.pixelsToGLUnits=[2/w,-2/E],this._constrain(),this._calcMatrices()}get unmodified(){return this._unmodified}zoomScale(w){return Math.pow(2,w)}scaleZoom(w){return Math.log2(w)}project(w){const E=o.aC(w.lat,-o.ct,o.ct),F=this.projection.project(w.lng,E);return new o.P(F.x*this.worldSize,F.y*this.worldSize)}unproject(w){return this.projection.unproject(w.x/this.worldSize,w.y/this.worldSize)}get point(){return this.project(this.center)}get pointMerc(){return this.point._div(this.worldSize)}get pixelsPerMeterRatio(){return this.pixelsPerMeter/o.bU(1,this.center.lat)/this.worldSize}setLocationAtPoint(w,E){let F,G;const X=this.centerPoint;if(this.projection.name==="globe"){const de=this.worldSize;F=(E.x-X.x)/de,G=(E.y-X.y)/de}else{const de=this.pointCoordinate(E),ye=this.pointCoordinate(X);F=de.x-ye.x,G=de.y-ye.y}const J=this.locationCoordinate(w);this.setLocation(new o.ag(J.x-F,J.y-G))}setLocation(w){this.center=this.coordinateLocation(w),this.projection.wrap&&(this.center=this.center.wrap())}locationPoint(w,E){return this.projection.locationPoint(this,w,E)}locationPoint3D(w,E){return this.projection.locationPoint(this,w,E,!0)}pointLocation(w){return this.coordinateLocation(this.pointCoordinate(w))}pointLocation3D(w,E){return this.coordinateLocation(this.pointCoordinate3D(w,E))}locationCoordinate(w,E){const F=E?o.bU(E,w.lat):void 0,G=this.projection.project(w.lng,w.lat);return new o.ag(G.x,G.y,F)}coordinateLocation(w){return this.projection.unproject(w.x,w.y)}pointRayIntersection(w,E){const F=E??this._centerAltitude,G=[w.x,w.y,0,1],X=[w.x,w.y,1,1];o.aE(G,G,this.pixelMatrixInverse),o.aE(X,X,this.pixelMatrixInverse);const J=X[3];o.cu(G,G,1/G[3]),o.cu(X,X,1/J);const de=G[2],ye=X[2];return{p0:G,p1:X,t:de===ye?0:(F-de)/(ye-de)}}screenPointToMercatorRay(w){const E=[w.x,w.y,0,1],F=[w.x,w.y,1,1];return o.aE(E,E,this.pixelMatrixInverse),o.aE(F,F,this.pixelMatrixInverse),o.cu(E,E,1/E[3]),o.cu(F,F,1/F[3]),E[2]=o.bU(E[2],this._center.lat)*this.worldSize,F[2]=o.bU(F[2],this._center.lat)*this.worldSize,o.cu(E,E,1/this.worldSize),o.cu(F,F,1/this.worldSize),new o.az([E[0],E[1],E[2]],o.ay([],o.ax([],F,E)))}rayIntersectionCoordinate(w){const{p0:E,p1:F,t:G}=w,X=o.bU(E[2],this._center.lat),J=o.bU(F[2],this._center.lat);return new o.ag(o.am(E[0],F[0],G)/this.worldSize,o.am(E[1],F[1],G)/this.worldSize,o.am(X,J,G))}pointCoordinate(w,E=this._centerAltitude){return this.projection.pointCoordinate(this,w.x,w.y,E)}pointCoordinate3D(w,E){if(!this.elevation)return this.pointCoordinate(w,E);let F=this.projection.pointCoordinate3D(this,w.x,w.y);if(F)return new o.ag(F[0],F[1],F[2]);let G=0,X=this.horizonLineFromTop();if(w.y>X)return this.pointCoordinate(w,E);const J=.02*X,de=w.clone();for(let ye=0;ye<10&&X-G>J;ye++){de.y=o.am(G,X,.66);const Ce=this.projection.pointCoordinate3D(this,de.x,de.y);Ce?(X=de.y,F=Ce):G=de.y}return F?new o.ag(F[0],F[1],F[2]):this.pointCoordinate(w)}isPointAboveHorizon(w){return this.projection.isPointAboveHorizon(this,w)}isPointOnSurface(w){if(w.y<0||w.y>this.height||w.x<0||w.x>this.width)return!1;if(this.elevation||this.zoom>=o.cv)return!this.isPointAboveHorizon(w);const E=this.pointCoordinate(w);return E.y>=0&&E.y<=1}_coordinatePoint(w,E){const F=E&&this.elevation?this.elevation.getAtPointOrZero(w,this._centerAltitude):this._centerAltitude,G=[w.x*this.worldSize,w.y*this.worldSize,F+w.toAltitude(),1];return o.aE(G,G,this.pixelMatrix),G[3]>0?new o.P(G[0]/G[3],G[1]/G[3]):new o.P(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:w,left:E}=this._edgeInsets,F=this.height-this._edgeInsets.bottom,G=this.width-this._edgeInsets.right,X=this.pointLocation3D(new o.P(E,w)),J=this.pointLocation3D(new o.P(G,w)),de=this.pointLocation3D(new o.P(G,F)),ye=this.pointLocation3D(new o.P(E,F));let Ce=Math.min(X.lng,J.lng,de.lng,ye.lng),Le=Math.max(X.lng,J.lng,de.lng,ye.lng),Xe=Math.min(X.lat,J.lat,de.lat,ye.lat),Ke=Math.max(X.lat,J.lat,de.lat,ye.lat);const st=Math.pow(2,-this.zoom)/16*270,dt=this.projection.name==="globe"?1:4,it=(jt,wt,Bt,Vt,Ct)=>{const Ss=(jt+Bt)/2,rs=(wt+Vt)/2,_s=new o.P(Ss,rs),{lng:Gt,lat:ss}=this.pointLocation3D(_s),xs=Math.max(0,Ce-Gt,Xe-ss,Gt-Le,ss-Ke);Ce=Math.min(Ce,Gt),Le=Math.max(Le,Gt),Xe=Math.min(Xe,ss),Ke=Math.max(Ke,ss),(Ctst)&&(it(jt,wt,Ss,rs,Ct+1),it(Ss,rs,Bt,Vt,Ct+1))};if(it(E,w,G,w,1),it(G,w,G,F,1),it(G,F,E,F,1),it(E,F,E,w,1),this.projection.name==="globe"){const[jt,wt]=o.cw(this);jt?(Ke=90,Le=180,Ce=-180):wt&&(Xe=-90,Le=180,Ce=-180)}return new o.aK(new o.aU(Ce,Xe),new o.aU(Le,Ke))}_getBoundsRectangular(w,E){const{top:F,left:G}=this._edgeInsets,X=this.height-this._edgeInsets.bottom,J=this.width-this._edgeInsets.right,de=new o.P(G,F),ye=new o.P(J,F),Ce=new o.P(J,X),Le=new o.P(G,X);let Xe=this.pointCoordinate(de,w),Ke=this.pointCoordinate(ye,w);const st=this.pointCoordinate(Ce,E),dt=this.pointCoordinate(Le,E),it=(jt,wt)=>(wt.y-jt.y)/(wt.x-jt.x);return Xe.y>1&&Ke.y>=0?Xe=new o.ag((1-dt.y)/it(dt,Xe)+dt.x,1):Xe.y<0&&Ke.y<=1&&(Xe=new o.ag(-dt.y/it(dt,Xe)+dt.x,0)),Ke.y>1&&Xe.y>=0?Ke=new o.ag((1-st.y)/it(st,Ke)+st.x,1):Ke.y<0&&Xe.y<=1&&(Ke=new o.ag(-st.y/it(st,Ke)+st.x,0)),new o.aK().extend(this.coordinateLocation(Xe)).extend(this.coordinateLocation(Ke)).extend(this.coordinateLocation(dt)).extend(this.coordinateLocation(st))}_getBoundsRectangularTerrain(){const w=this.elevation;if(!w.visibleDemTiles.length||w.isUsingMockSource())return this._getBoundsRectangular(0,0);const E=w.visibleDemTiles.reduce((F,G)=>{if(G.dem){const X=G.dem.tree;F.min=Math.min(F.min,X.minimums[0]),F.max=Math.max(F.max,X.maximums[0])}return F},{min:Number.MAX_VALUE,max:0});return this._getBoundsRectangular(E.min*w.exaggeration(),E.max*w.exaggeration())}getBounds(){return this.projection.name==="mercator"||this.projection.name==="equirectangular"?this._terrainEnabled()?this._getBoundsRectangularTerrain():this._getBoundsRectangular(0,0):this._getBoundsNonRectangular()}horizonLineFromTop(w=!0){const E=this.height/2/Math.tan(this._fov/2)/Math.tan(Math.max(this._pitch,.1))-this.centerOffset.y,F=this.height/2-E*(1-this._horizonShift);return w?Math.max(0,F):F}getMaxBounds(){return this.maxBounds}setMaxBounds(w){this.maxBounds=w,this.minLat=-o.ct,this.maxLat=o.ct,this.minLng=-180,this.maxLng=180,w&&(this.minLat=w.getSouth(),this.maxLat=w.getNorth(),this.minLng=w.getWest(),this.maxLng=w.getEast(),this.maxLngXe&&(de=Xe-Ce),Xe-Lest&&(J=st-ye),st-Ke{for(let en=0;en<16;en++)_n[en]=o.am(hn[en],Rn[en],Kn)})(de,de,ye,o.cL(this.pitch>=em?1:this.pitch/em))}else de=ye;const Ce=o.cz([],ye,J);let Le=o.cz([],de,J);if(this.projection.isReprojectedInTileSpace){const ss=this.locationCoordinate(this.center),xs=o.b9([]);o.bx(xs,xs,[ss.x*this.worldSize,ss.y*this.worldSize,0]),o.aD(xs,xs,o.cA(this)),o.bx(xs,xs,[-ss.x*this.worldSize,-ss.y*this.worldSize,0]),o.aD(Le,Le,xs),o.aD(Ce,Ce,xs),this.inverseAdjustmentMatrix=o.cB(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(this.mercatorMatrix=o.cC([],Le,[this.worldSize,this.worldSize,this.worldSize/X,1]),this.projMatrix=Le,this.invProjMatrix=o.b7(new Float64Array(16),this.projMatrix),E){const ss=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);ss[8]=2*-w.x/this.width,ss[9]=2*w.y/this.height,this.expandedFarZProjMatrix=o.cz([],ss,J)}else this.expandedFarZProjMatrix=this.projMatrix;const Xe=o.b7([],de);this.frustumCorners=o.cD.fromInvProjectionMatrix(Xe,this.horizonLineFromTop(),this.height),this.cameraFrustum=o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,0,!E);const Ke=new Float32Array(16);o.b9(Ke),o.cC(Ke,Ke,[1,-1,1]),o.cE(Ke,Ke,this._pitch),o.ba(Ke,Ke,this.angle);const st=o.bS(new Float32Array(16),this._fov,this.width/this.height,this._nearZ,this._farZ);this.starsProjMatrix=o.b8(st);const dt=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;st[8]=2*-w.x/this.width,st[9]=2*(w.y+dt)/this.height,this.skyboxMatrix=o.aD(Ke,st,Ke);const it=this.point,jt=it.x,wt=it.y,Bt=this.width%2/2,Vt=this.height%2/2,Ct=Math.cos(this.angle),Ss=Math.sin(this.angle),rs=jt-Math.round(jt)+Ct*Bt+Ss*Vt,_s=wt-Math.round(wt)+Ct*Vt+Ss*Bt,Gt=new Float64Array(Le);if(o.bx(Gt,Gt,[rs>.5?rs-1:rs,_s>.5?_s-1:_s,0]),this.alignedProjMatrix=Gt,Le=o.bb(),o.cC(Le,Le,[this.width/2,-this.height/2,1]),o.bx(Le,Le,[1,-1,0]),this.labelPlaneMatrix=Le,Le=o.bb(),o.cC(Le,Le,[1,-1,1]),o.bx(Le,Le,[-1,-1,0]),o.cC(Le,Le,[2/this.width,2/this.height,1]),this.glCoordMatrix=Le,this.pixelMatrix=o.aD(new Float64Array(16),this.labelPlaneMatrix,Ce),this._calcFogMatrices(),this._distanceTileDataCache={},Le=o.b7(new Float64Array(16),this.pixelMatrix),!Le)throw new Error("failed to invert matrix");if(this.pixelMatrixInverse=Le,this.projection.name==="globe"||this.mercatorFromTransition){this.globeMatrix=o.cF(this);const ss=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=o.ah(ss,ss,J),this.globeRadius=this.worldSize/2/Math.PI-1}else this.globeMatrix=Le;this._projMatrixCache={},this._alignedProjMatrixCache={},this._pixelsToTileUnitsCache={},this._expandedProjMatrixCache={}}_calcFogMatrices(){this._fogTileMatrixCache={};const w=this.cameraWorldSizeForFog,E=this.cameraPixelsPerMeter,F=this._camera.position,G=1/this.height/this._pixelsPerMercatorPixel,X=[w,w,E];o.bJ(X,X,G),o.bJ(F,F,-1),o.cG(F,F,X);const J=o.bb();o.bx(J,J,F),o.cC(J,J,X),this.mercatorFogMatrix=J,this.worldToFogMatrix=this._camera.getWorldToCameraPosition(w,E,G)}_computeCameraPosition(w){const E=(w=w||this.pixelsPerMeter)/this.pixelsPerMeter,F=this._camera.forward(),G=this.point,X=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*E-w/this.worldSize*this._centerAltitude;return[G.x/this.worldSize-F[0]*X,G.y/this.worldSize-F[1]*X,w/this.worldSize*this._centerAltitude-F[2]*X]}_updateCameraState(){this.height&&(this._camera.setPitchBearing(this._pitch,this.angle),this._camera.position=this._computeCameraPosition())}_translateCameraConstrained(w){const E=this._maxCameraBoundsDistance()*Math.cos(this._pitch),F=this._camera.position[2],G=w[2];let X=1;this.projection.wrap&&(this.center=this.center.wrap()),G>0&&(X=Math.min((E-F)/G,1)),this._camera.position=o.bg([],this._camera.position,w,X),this._updateStateFromCamera()}_updateStateFromCamera(){const w=this._camera.position,E=this._camera.forward(),{pitch:F,bearing:G}=this._camera.getPitchBearing(),X=o.bU(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,J=this._mercatorZfromZoom(this._maxZoom)*Math.cos(o.ap(this._maxPitch)),de=Math.max((w[2]-X)/Math.cos(F),J),ye=this._zoomFromMercatorZ(de);o.bg(w,w,E,de),this._pitch=o.aC(F,o.ap(this.minPitch),o.ap(this.maxPitch)),this.angle=o.bs(G,-Math.PI,Math.PI),this._setZoom(o.aC(ye,this._minZoom,this._maxZoom)),this._updateSeaLevelZoom(),this._center=this.coordinateLocation(new o.ag(w[0],w[1],w[2])),this._unmodified=!1,this._constrain(),this._calcMatrices()}_worldSizeFromZoom(w){return Math.pow(2,w)*this.tileSize}_mercatorZfromZoom(w){return this.cameraToCenterDistance/this._worldSizeFromZoom(w)}_minimumHeightOverTerrain(){const w=Math.min(this._seaLevelZoom!=null?this._seaLevelZoom:this._zoom,this._maxZoom)+4;return this._mercatorZfromZoom(w)}_zoomFromMercatorZ(w){return this.scaleZoom(this.cameraToCenterDistance/(Math.max(0,w)*this.tileSize))}zoomFromMercatorZAdjusted(w){let E=0,F=o.cv,G=0,X=1/0;for(;F-E>1e-6&&F>E;){const J=E+.5*(F-E),de=this.tileSize*Math.pow(2,J),ye=this.getCameraToCenterDistance(this.projection,J,de),Ce=this.scaleZoom(ye/(Math.max(0,w)*this.tileSize)),Le=Math.abs(J-Ce);LeCe||Ke.y>1)return!0}return!1}isHorizonVisible(){return this.pitch+o.cH(this.fovAboveCenter)>88||this.anyCornerOffEdge(new o.P(0,0),new o.P(this.width,this.height))}zoomDeltaToMovement(w,E){const F=o.ai(o.ax([],this._camera.position,w)),G=this._zoomFromMercatorZ(F)+E;return F-this._mercatorZfromZoom(G)}getCameraPoint(){if(this.projection.name==="globe"){const w=function([E,F,G],X){const J=[E,F,G,1];o.aE(J,J,X);const de=J[3]=Math.max(J[3],1e-6);return J[0]/=de,J[1]/=de,J[2]/=de,J}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new o.P(w[0],w[1])}{const w=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new o.P(0,w))}}getCameraToCenterDistance(w,E=this.zoom,F=this.worldSize){const G=o.cy(w,E,this.width,this.height,1024),X=w.pixelSpaceConversion(this.center.lat,F,G);let J=.5/Math.tan(.5*this._fov)*this.height*X;return this.isOrthographic&&(J=o.am(1,J,o.cL(this.pitch>=em?1:this.pitch/em))),J}getWorldToCameraMatrix(){const w=this._camera.getWorldToCamera(this.worldSize,this.projection.zAxisUnit==="meters"?this.pixelsPerMeter:1);return this.projection.name==="globe"&&o.aD(w,w,this.globeMatrix),w}getFrustum(w){return o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,w,this.projection.zAxisUnit==="meters")}}const Sd=(D,w)=>{if(w>0&&D.terrain&&o.w("Cutoff is currently disabled on terrain"),w<=0||D.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const E=D.transform,F=E.pitch,G=E.isLODDisabled(!1)?60:30;if(F0,uniformValues:{u_cutoff_params:[E._nearZ,E._farZ,(Le-E._nearZ)/X,(Le-Ke-E._nearZ)/X]}}},Zp=2048;class v1{constructor(w,E){this.aabb=w,this.lastCascade=E}}class b1{add(w,E){const F=this.receivers[w.key];F!==void 0?(F.aabb.min[0]=Math.min(F.aabb.min[0],E.min[0]),F.aabb.min[1]=Math.min(F.aabb.min[1],E.min[1]),F.aabb.min[2]=Math.min(F.aabb.min[2],E.min[2]),F.aabb.max[0]=Math.max(F.aabb.max[0],E.max[0]),F.aabb.max[1]=Math.max(F.aabb.max[1],E.max[1]),F.aabb.max[2]=Math.max(F.aabb.max[2],E.max[2])):this.receivers[w.key]=new v1(E,null)}clear(){this.receivers={}}get(w){return this.receivers[w.key]}computeRequiredCascades(w,E,F){const G=o.cU.fromPoints(w.points);let X=0;for(const J in this.receivers){const de=this.receivers[J];if(!de||!G.intersectsAabb(de.aabb))continue;de.aabb.min=G.closestPoint(de.aabb.min),de.aabb.max=G.closestPoint(de.aabb.max);const ye=de.aabb.getCorners();for(let Ce=0;Ce1||Ke[1]<-1||Ke[1]>1){Le=!1;break}}if(de.lastCascade=Ce,X=Math.max(X,Ce),Le)break}}return X+1}}class Xc{constructor(w){this.painter=w,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new b1,this._depthMode=new Hr(w.context.gl.LEQUAL,Hr.ReadWrite,[0,1]),this._uniformValues={u_light_matrix_0:new Float32Array(16),u_light_matrix_1:new Float32Array(16),u_shadow_intensity:0,u_fade_range:[0,0],u_shadow_normal_offset:[1,1,1],u_shadow_texel_size:1,u_shadow_map_resolution:1,u_shadow_direction:[0,0,1],u_shadow_bias:[36e-5,.0012,.012],u_shadowmap_0:0,u_shadowmap_1:0},this._forceDisable=!1,this.useNormalOffset=!1}destroy(){for(const w of this._cascades)w.texture.destroy(),w.framebuffer.destroy();this._cascades=[]}updateShadowParameters(w,E){const F=this.painter;if(this._enabled=!1,this._drawShadowAfterLayer=-1,this._receivers.clear(),!E||!E.properties)return;const G=E.properties.get("shadow-intensity"),X=E.properties.get("shadow-draw-before-layer");if(!E.shadowsEnabled()||G<=0)return;let J=-1,de=0;for(const wt of F.style.order){const Bt=F.style._mergedLayers[wt];Bt.hasShadowPass()&&!Bt.isHidden(w.zoom)&&(J=de),!X||X!==wt&&X!==Bt.slot||(this._drawShadowAfterLayer=de>0?de-1:0),de+=1}if(this._enabled=J>=0,!this.enabled)return;this._drawShadowAfterLayer<0&&(this._drawShadowAfterLayer=J);const ye=F.context,Ce=Zp,Le=Zp;if(this._cascades.length===0||Zp!==this._cascades[0].texture.size[0]){this._cascades=[];for(let wt=0;wt<2;++wt){const Bt=ye.gl,Vt=ye.createFramebuffer(Ce,Le,0,"texture"),Ct=new o.T(ye,{width:Ce,height:Le,data:null},Bt.DEPTH_COMPONENT16);Vt.depthAttachment.set(Ct.texture),this._cascades.push({framebuffer:Vt,texture:Ct,matrix:[],far:0,boundingSphereRadius:0,frustum:new o.cl,scale:0})}}this.shadowDirection=ky(E);let Xe=0;if(w.elevation){const wt=w.elevation,Bt=[1e4,-1e4];wt.visibleDemTiles.filter(Vt=>Vt.dem).forEach(Vt=>{const Ct=Vt.dem.tree;Bt[0]=Math.min(Bt[0],Ct.minimums[0]),Bt[1]=Math.max(Bt[1],Ct.maximums[0])}),Bt[0]!==1e4&&(Xe=(Bt[1]-Bt[0])*wt.exaggeration())}const Ke=1.5*w.cameraToCenterDistance,st=3*Ke,dt=new Float64Array(16);for(let wt=0;wt=0)return{};const X=function(ye,Ce,Le){const Xe=Le/(1<0&&(o.cT(X[1],X[1],[G[0]*J,0,0]),o.cT(X[2],X[2],[G[0]*J,0,0])),G[1]<0?(o.cT(X[0],X[0],[0,G[1]*J,0]),o.cT(X[1],X[1],[0,G[1]*J,0])):G[1]>0&&(o.cT(X[2],X[2],[0,G[1]*J,0]),o.cT(X[3],X[3],[0,G[1]*J,0]));const de={};return de.vertices=X,de.planes=[Lx(X[1],X[0],X[4]),Lx(X[2],X[1],X[5]),Lx(X[3],X[2],X[6]),Lx(X[0],X[3],X[7])],de}addShadowReceiver(w,E,F){this._receivers.add(w,o.cU.fromTileIdAndHeight(w,E,F))}getMaxCascadeForTile(w){const E=this._receivers.get(w);return E&&E.lastCascade?E.lastCascade:0}}function Lx(D,w,E){const F=o.ax([],E,w),G=o.ax([],D,w),X=o.bh([],F,G),J=o.ai(X);return J===0?[0,0,1,0]:(o.bJ(X,X,1/J),[X[0],X[1],X[2],-o.bi(X,w)])}function ky(D){const w=D.properties.get("direction"),E=o.cP(w.x,w.y,w.z);E[2]=o.aC(E[2],0,75);const F=o.cR([E[0],E[1],E[2]]);return o.cQ(F.x,F.y,F.z)}function tm(D,w,E){const F=w.properties.get("color-use-theme")==="none",G=w.properties.get("color"),X=w.properties.get("intensity"),J=w.properties.get("direction"),de=[J.x,J.y,J.z],ye=E.properties.get("color-use-theme")==="none",Ce=E.properties.get("color"),Le=E.properties.get("intensity"),Xe=Math.max(o.bi([0,0,1],de),0),Ke=[0,0,0];o.bJ(Ke,Ce.toPremultipliedRenderColor(ye?null:D.getLut(w.scope)).toArray01Linear().slice(0,3),Le);const st=[0,0,0];return o.bJ(st,G.toPremultipliedRenderColor(F?null:D.getLut(E.scope)).toArray01Linear().slice(0,3),Xe*X),o.cW([Ke[0]>0?Ke[0]/(Ke[0]+st[0]):0,Ke[1]>0?Ke[1]/(Ke[1]+st[1]):0,Ke[2]>0?Ke[2]/(Ke[2]+st[2]):0])}function vg(D,w,E,F,G,X){const J=D.zoom,de=D.scale,ye=D.worldSize,Ce=1/ye,Le=D.aspect,Xe=Math.sqrt(1+Le*Le)*Math.tan(.5*D.fovX),Ke=Xe*Xe,st=F-E,dt=F+E;let it,jt;Ke>st/dt?(it=F,jt=F*Xe):(it=.5*dt*(1+Ke),jt=.5*Math.sqrt(st*st+2*(F*F+E*E)*Ke+dt*dt*Ke*Ke));const wt=D.projection.pixelsPerMeter(D.center.lat,ye),Bt=D._camera.getCameraToWorldMercator(),Vt=[0,0,-it*Ce];o.ah(Vt,Vt,Bt);let Ct=jt*Ce;const Ss=function(An){return An[0]/=de,An[1]/=de,An[2]=o.bU(An[2],D._center.lat),An},rs=D._edgeInsets;if(!(rs.left===0&&rs.top===0&&rs.right===0&&rs.bottom===0||rs.left===rs.right&&rs.top===rs.bottom)){const An=D._camera.getWorldToCamera(D.worldSize,D.projection.zAxisUnit==="meters"?wt:1),jr=D._camera.getCameraToClipPerspective(D._fov,D.width/D.height,E,F);jr[8]=2*-D.centerOffset.x/D.width,jr[9]=2*D.centerOffset.y/D.height;const ur=new Float64Array(16);o.cz(ur,jr,An);const hr=new Float64Array(16);o.b7(hr,ur);const Vn=o.cl.fromInvProjectionMatrix(hr,ye,J,!0);for(const ca of Vn.points){const Na=Ss(ca);Ct=Math.max(Ct,o.bK(o.cV([],Vt,Na)))}}Ct*=G/(G-1);const _s=Math.acos(w[2]),Gt=Math.atan2(-w[0],-w[1]),ss=new yg;ss.position=Vt,ss.setPitchBearing(_s,Gt);const xs=ss.getWorldToCamera(ye,wt),Ks=Ct*ye,Ts=Math.min(D._mercatorZfromZoom(17)*ye*-2,-2*Ks),_n=ss.getCameraToClipOrthographic(-Ks,Ks,-Ks,Ks,Ts,(Ks+X*wt)/w[2]),hn=new Float64Array(16);o.aD(hn,_n,xs);const Rn=o.cQ(Math.floor(1e6*Vt[0])/1e6*ye,Math.floor(1e6*Vt[1])/1e6*ye,0),Kn=.5*G,en=[0,0,0];o.ah(en,Rn,hn),o.bJ(en,en,Kn);const Ls=[Math.floor(en[0]),Math.floor(en[1]),Math.floor(en[2])],yn=[0,0,0];o.ax(yn,en,Ls),o.bJ(yn,yn,-1/Kn);const jn=new Float64Array(16);return o.b9(jn),o.bx(jn,jn,yn),o.aD(hn,jn,hn),[hn,Ks]}class Eb extends o.E{constructor(w){super(),this.requestManager=w,this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}loadModel(w,E){return o.cX(this.requestManager.transformRequest(E,o.R.Model).url).then(F=>{const G=o.cY(F),X=new o.cZ(w,E,void 0,void 0,G);return X.computeBoundsAndApplyParent(),X}).catch(F=>{if(F&&F.status===404)return null;this.fire(new o.B(new Error(`Could not load model ${w} from ${E}: ${F.message}`)))})}load(w,E,F={forceReload:!1}){this.models[E]||(this.models[E]={});const G=Object.keys(w),X=[],J=[];for(const de of G){const ye=w[de];this.hasURLBeenRequested(ye)&&!F.forceReload||(this.modelByURL[ye]={modelId:de,scope:E},X.push(this.loadModel(de,ye)),J.push(de)),this.models[E][de]||(this.models[E][de]={model:null,numReferences:1})}this.numModelsLoading[E]=(this.numModelsLoading[E]||0)+J.length,Promise.allSettled(X).then(de=>{for(let ye=0;ye{this.fire(new o.B(new Error(`Could not load models: ${de.message}`)))})}isLoaded(){for(const w in this.numModelsLoading)if(this.numModelsLoading[w]>0)return!1;return!0}hasModel(w,E,F={exactIdMatch:!1}){return!!(F.exactIdMatch?this.getModel(w,E):this.getModelByURL(this.modelUris[E][w]))}getModel(w,E){return this.models[E]||(this.models[E]={}),this.models[E][w]?this.models[E][w].model:void 0}getModelByURL(w){if(!w)return null;const E=this.modelByURL[w];return E?this.models[E.scope][E.modelId].model:null}hasModelBeenAdded(w,E){return this.models[E]&&this.models[E][w]!==void 0}getModelURIs(w){return this.modelUris[w]||{}}addModel(w,E,F){this.models[F]||(this.models[F]={}),this.modelUris[F]||(this.modelUris[F]={});const G=this.requestManager.normalizeModelURL(E);if((this.hasModel(w,F,{exactIdMatch:!0})||this.hasModelBeenAdded(w,F))&&this.modelUris[F][w]===G)this.models[F][w].numReferences++;else if(this.hasURLBeenRequested(G)){const{scope:X,modelId:J}=this.modelByURL[G];this.models[X][J].numReferences++}else this.modelUris[F][w]=G,this.load({[w]:this.modelUris[F][w]},F)}addModelURLs(w,E){this.models[E]||(this.models[E]={}),this.modelUris[E]||(this.modelUris[E]={});const F=this.modelUris[E];for(const G in w)F[G]=this.requestManager.normalizeModelURL(w[G])}reloadModels(w){this.load(this.modelUris[w],w,{forceReload:!0})}addModelsFromBucket(w,E){this.models[E]||(this.models[E]={}),this.modelUris[E]||(this.modelUris[E]={});const F={};for(const G of w)this.hasModel(G,E,{exactIdMatch:!0})||this.hasURLBeenRequested(G)?this.models[E][G].numReferences++:this.modelUris[E][G]&&!this.hasURLBeenRequested(G)?F[G]=this.modelUris[E][G]:!this.hasURLBeenRequested(G)&&o.c_(G,!1)&&(this.modelUris[E][G]=this.requestManager.normalizeModelURL(G),F[G]=this.modelUris[E][G]);this.load(F,E)}hasURLBeenRequested(w){return this.modelByURL[w]!==void 0}removeModel(w,E,F=!1,G=!1){if(this.models[E]&&this.models[E][w]&&(this.models[E][w].numReferences--,this.models[E][w].numReferences===0||G)){const X=this.modelUris[E][w];F||delete this.modelUris[E][w],delete this.modelByURL[X];const J=this.models[E][w].model;if(!J)return;delete this.models[E][w],J.destroy()}}destroy(){for(const w of Object.keys(this.models))for(const E of Object.keys(this.models[w])){const F=this.models[w][E].model;delete this.models[w][E],F&&F.destroy()}this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}listModels(w){return this.models[w]||(this.models[w]={}),Object.keys(this.models[w])}upload(w,E){this.models[E]||(this.models[E]={});for(const F in this.models[E])this.models[E][F].model&&this.models[E][F].model.upload(w.context)}}const Ju=o.a8.colorTheme,_c=new o.ab({data:new o.ac(Ju.data)});function xl(D){if(!D.metadata||!D.metadata.content_area)return;const w=o.o.devicePixelRatio,{left:E,top:F,width:G,height:X}=D.metadata.content_area,J=E*w,de=F*w;return[J,de,J+G*w,de+X*w]}function ll(D){if(D)return D.map(([w,E])=>[w*o.o.devicePixelRatio,E*o.o.devicePixelRatio])}class ju{constructor(w,E,F){this.id=w,this.scope=E,this.sourceCache=F,this.pendingRequests=new Set,this.missingRequests=new Set}addPendingRequest(w){this.missingRequests.has(w.name)||this.pendingRequests.has(w.name)||this.pendingRequests.add(w.name)}hasPendingRequests(){return this.pendingRequests.size>0}resolvePendingRequests(){const w=new Map;if(!this.sourceCache.loaded())return w;const E=this.sourceCache.getVisibleCoordinates();if(E.length===0)return w;const F=this.sourceCache.getSource();if(!(F instanceof Jo))return w;const G=E.map(J=>this.sourceCache.getTile(J)),X=F.getImages(G,Array.from(this.pendingRequests));for(const[J,de]of X)w.set(o.I.from({name:J,iconsetId:this.id}),de),this.pendingRequests.delete(J);for(const J of this.pendingRequests)this.missingRequests.add(J);return this.pendingRequests.clear(),w}}class Cd{constructor(){this._previousClosestBuildingId=null,this._hysteresisRatio=.8,this._indoorMinimumZoom=16}findClosestBuilding(w,E,F,G,X){if(Fye*this._hysteresisRatio&&(J=this._previousClosestBuildingId):Ce&&!J&&(J=this._previousClosestBuildingId),this._previousClosestBuildingId=J,J}_calculateDistance(w,E){if(!E.center)return Number.MAX_VALUE;const F=w.lat-E.center[1],G=w.lng-E.center[0];return F*F+G*G}_isBuildingVisible(w,E,F){if(!F)return!1;for(const G of w.floorIds){const X=w.floors[G];if(!X.geometry)continue;const J=X.geometry;if(J.type==="Polygon"){const de=this._convertRingToPoints(J.coordinates[0]);if(o.bw(de,F))return!0}else if(J.type==="MultiPolygon"){const de=this._convertMultiPolygonToPoints(J.coordinates);if(o.d0(F,de))return!0}}return!1}_convertRingToPoints(w){return w.map(E=>new o.P(E[0],E[1]))}_convertMultiPolygonToPoints(w){return w.map(E=>E.length===0?[]:E[0].map(F=>new o.P(F[0],F[1])))}}class Ix extends o.E{constructor(w){super(),this._style=w,this._buildings={},this._activeFloors=new Set,this._closestBuildingId=null,this._indoorState={selectedFloorId:null,activeFloorsVisible:!0,activeFloors:this._activeFloors},this._buildingDetectionStrategy=new Cd,this._initialLoadDone=!1,o.aZ(["_updateUI"],this),this._style.on("style.load",()=>{this._style.isIndoorEnabled()&&(this._style.map.on("load",()=>{this._initialLoadDone=!0,this._indoorState&&this._indoorState.needsUpdate&&(this._indoorState.needsUpdate=!1,this._style.updateIndoorDependentLayers()),this._updateUI()}),this._style.map.on("move",this._updateUI),this._style.map.on("idle",this._updateUI))})}destroy(){this._buildings={},this._activeFloors=new Set,this._indoorState=null}selectFloor(w){w===this._selectedFloorId&&this._indoorState&&this._indoorState.activeFloorsVisible||(this._selectedFloorId=w,this._recalculateActiveFloors())}setActiveFloorsVisibility(w){this._updateActiveFloors(w),this._updateIndoorSelector()}setIndoorData(w){let E=!1;for(const[F,G]of Object.entries(w.buildings))if(this._buildings[F])for(const X of G.floorIds)this._buildings[F].floorIds.add(X),this._buildings[F].floors[X]?this._mergeFloors(this._buildings[F].floors[X],G.floors[X]):(this._buildings[F].floors[X]=G.floors[X],E=!0);else this._buildings[F]=G,E=!0;E&&this._recalculateActiveFloors()}getIndoorTileOptions(w,E){return this._indoorState?{sourceLayers:this._style.getIndoorSourceLayers(w,E),indoorState:this._indoorState}:null}getControlState(){const w=this._buildings,E=this._closestBuildingId,F=E&&w?w[E]:void 0;if(!F)return{selectedFloorId:null,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:[]};let G=null;for(const J of F.floorIds)if(this._activeFloors&&this._activeFloors.has(J)){G=J;break}const X=Array.from(F.floorIds).map(J=>({id:J,name:F.floors[J].name,zIndex:F.floors[J].zIndex})).sort((J,de)=>de.zIndex-J.zIndex).filter((J,de,ye)=>de===0||J.zIndex!==ye[de-1].zIndex);return{selectedFloorId:G,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:X}}_updateUI(){this._initialLoadDone=!0;const w=this._style.map.transform,E=this._buildingDetectionStrategy.findClosestBuilding(this._buildings,w.center,w.zoom,w.getBounds(),this._makeViewportPolygon());if(E!==this._closestBuildingId){const F=this._closestBuildingId;this._closestBuildingId=E,this._onBuildingTransition(F,E),this._updateIndoorSelector()}}_onBuildingTransition(w,E){if(!this._indoorState)return;!E&&w?(this._indoorState.activeFloors=new Set,this._indoorState.activeFloorsVisible=!1,this._style.updateIndoorDependentLayers()):!!E&&!w&&(this._recalculateActiveFloors(),this._updateActiveFloors(!0))}_updateIndoorSelector(){this.fire(new o.C("selector-update",this.getControlState()))}_updateActiveFloors(w){this._indoorState={selectedFloorId:this._selectedFloorId,activeFloorsVisible:w,activeFloors:this._activeFloors},this._initialLoadDone?this._style.updateIndoorDependentLayers():this._indoorState.needsUpdate=!0}_recalculateActiveFloors(){if(!this._buildings)return;const w=o.d1.calculate(this._buildings,this._selectedFloorId,this._activeFloors);(function(E,F){if(E===F)return!0;if(!E||!F||E.size!==F.size)return!1;for(const G of E)if(!F.has(G))return!1;return!0})(w,this._activeFloors)||(this._activeFloors=w,this._updateActiveFloors(!!this._indoorState&&this._indoorState.activeFloorsVisible),this._updateIndoorSelector())}_mergeFloors(w,E){E.geometry&&(w.geometry?(w.geometry.type==="Polygon"&&(w.geometry={type:"MultiPolygon",coordinates:[w.geometry.coordinates]}),E.geometry.type==="Polygon"?w.geometry.coordinates.push(E.geometry.coordinates):E.geometry.type==="MultiPolygon"&&w.geometry.coordinates.push(...E.geometry.coordinates)):w.geometry=E.geometry)}_makeViewportPolygon(){const w=this._style.map.transform,E=w.width,F=w.height;return[w.pointLocation(new o.P(0,0)),w.pointLocation(new o.P(E,0)),w.pointLocation(new o.P(E,F)),w.pointLocation(new o.P(0,F))].map(G=>new o.P(G.lng,G.lat))}}const Sy=(D,w)=>zn(D,w&&w.filter(E=>E.identifier!=="source.canvas")),sm=o.aJ(zi,["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"]),$_=o.aJ(zi,["setCenter","setZoom","setBearing","setPitch"]),Tj=new Set(["background","sky","slot","custom"]),V_={version:8,layers:[],sources:{}},Rx={duration:300,delay:0};class eh extends o.E{constructor(w,E={}){if(super(),this.map=w,this.scope=E.scope||"",this.globalId=null,this.fragments=[],this.importDepth=E.importDepth||0,this.importsCache=E.importsCache||new Map,this.resolvedImports=E.resolvedImports||new Set,this.transition=Object.assign({},Rx),this._buildingIndex=new Mu(this),this.crossTileSymbolIndex=new xg,this._mergedOrder=[],this._drapedFirstOrder=[],this._mergedLayers={},this._mergedIndoor={},this._mergedSourceCaches={},this._mergedOtherSourceCaches={},this._mergedSymbolSourceCaches={},this._mergedFillExtrusionSourceCaches={},this._clipLayerPresent=!1,this._hasAppearances=!1,this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this._importedAsBasemap=!1,this._changes=E.styleChanges||new qe,this._hasDataDrivenEmissive=!1,this.indoorManager=new Ix(this),this.dispatcher=E.dispatcher?E.dispatcher:new tt(qt(),this),this.map.painter&&this.map.painter.context){const G=this.map.painter.context.maxUniformBufferBindings,X=Math.floor(this.map.painter.context.maxUniformBlockSize/4);this.dispatcher.broadcast("setContextParams",{maxBindingPoints:G,maxUniformBlockSizeDwords:X,disableSymbolUBO:this.map.painter.context.disableSymbolUBO})}E.imageManager?this.imageManager=E.imageManager:(this.imageManager=new Ut(this.map._spriteFormat),this.imageManager.setEventedParent(this)),this.imageManager.addScope(this.scope),this.glyphManager=E.glyphManager?E.glyphManager:new o.d2(w._requestManager,E.localFontFamily?o.d3.all:E.localIdeographFontFamily?o.d3.ideographs:o.d3.none,E.localFontFamily||E.localIdeographFontFamily,E.useServerFontComposition),E.modelManager?this.modelManager=E.modelManager:(this.modelManager=new Eb(w._requestManager),this.modelManager.setEventedParent(this)),this._layers={},this._sourceCaches={},this._otherSourceCaches={},this._symbolSourceCaches={},this._fillExtrusionSourceCaches={},this._loaded=!1,this._precompileDone=!1,this._shouldPrecompile=!1,this._availableImages=[],this._availableModels={},this._order=[],this._markersNeedUpdate=!1,this.options=E.configOptions?E.configOptions:new Map,this._configDependentLayers=E.configDependentLayers?E.configDependentLayers:new Set,this._indoorDependentLayers=E.indoorDependentLayers?E.indoorDependentLayers:new Set,this._config=E.config,this._styleColorTheme={lut:null,lutLoading:!1,lutLoadingCorrelationID:0,colorTheme:null,colorThemeOverride:E.colorThemeOverride},this._styleColorThemeForScope={},this._initialConfig=E.initialConfig,this.dispatcher.broadcast("setReferrer",o.d4()),this.dispatcher.broadcast("setConfig",o.d5());const F=this;this._rtlTextPluginCallback=eh.registerForPluginStateChange(G=>{F.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:G.pluginStatus,pluginURL:G.pluginURL},(X,J)=>{if(o.d6(X),J&&J.every(de=>de))for(const de in F._sourceCaches){const ye=F._sourceCaches[de],Ce=ye.getSource().type;Ce!=="vector"&&Ce!=="geojson"||ye.reload()}})}),this.on("data",G=>{if(G.dataType!=="source"||G.sourceDataType!=="metadata")return;const X=this.getOwnSource(G.sourceId);if(X&&X.vectorLayerIds)for(const J in this._layers){const de=this._layers[J];de.source===X.id&&this._validateLayer(de)}})}load(w){return w?(typeof w=="string"?this.loadURL(w):this.loadJSON(w),this):this}_getGlobalId(w){if(!w)return null;if(typeof w=="string"){if(o.e(w))return w;const E=o.d7(w);if(!E.startsWith("http"))try{return new URL(E,location.href).toString()}catch{return E}return E}return`json://${o.d8(JSON.stringify(w))}`}_diffStyle(w,E,F){this.globalId=this._getGlobalId(w);const G=(X,J)=>{try{J(null,this.setState(X,F))}catch(de){J(de,!1)}};if(typeof w=="string"){const X=this.map._requestManager.normalizeStyleURL(w),J=this.map._requestManager.transformRequest(X,o.R.Style);o.m(J,(de,ye)=>{de?this.fire(new o.B(de)):ye&&G(ye,E)})}else typeof w=="object"&&G(w,E)}loadURL(w,E={}){this.fire(new o.C("dataloading",{dataType:"style"}));const F=typeof E.validate=="boolean"?E.validate:!o.e(w);this.globalId=this._getGlobalId(w),w=this.map._requestManager.normalizeStyleURL(w,E.accessToken),this.resolvedImports.add(w);const G=this.importsCache.get(w);if(G)return this._load(G,F);const X=this.map._requestManager.transformRequest(w,o.R.Style);this._request=o.m(X,(J,de)=>{if(this._request=null,J)this.fire(new o.B(J));else if(de)return this.importsCache.set(w,de),this._load(de,F)})}loadJSON(w,E={}){this.fire(new o.C("dataloading",{dataType:"style"})),this.globalId=this._getGlobalId(w),this._request=o.o.frame(()=>{this._request=null,this._load(w,E.validate!==!1)})}loadEmpty(){this.fire(new o.C("dataloading",{dataType:"style"})),this._load(V_,!1)}_loadImports(w,E,F){if(this.importDepth>=4)return o.w("Style doesn't support nesting deeper than 5"),Promise.resolve();const G=[];for(const X of w){const J=this._createFragmentStyle(X),de=new Promise(Le=>{J.once("style.import.load",Le),J.once("error",Le)}).then(()=>{this.mergeAll(),this.fire(new o.C("data",{dataType:"style"}))});if(G.push(de),this.resolvedImports.has(X.url)){J.loadEmpty();continue}const ye=X.data||this.importsCache.get(X.url);ye?(X.data?(J.fire(new o.C("dataloading",{dataType:"style"})),J.globalId=J._getGlobalId(ye),queueMicrotask(()=>J._load(ye,E))):J.loadJSON(ye,{validate:E}),this._isInternalStyle(ye)&&(J.globalId=null)):X.url?J.loadURL(X.url,{validate:E}):J.loadEmpty();const Ce={style:J,id:X.id,config:X.config};if(F){const Le=this.fragments.findIndex(({id:Xe})=>Xe===F);this.fragments=this.fragments.slice(0,Le).concat(Ce).concat(this.fragments.slice(Le))}else this.fragments.push(Ce)}return Promise.allSettled(G)}getImportGlobalIds(w=this,E=new Set){for(const F of w.fragments)F.style.globalId&&E.add(F.style.globalId),this.getImportGlobalIds(F.style,E);return[...E.values()]}_createFragmentStyle(w){const E=this.scope?o.F(w.id,this.scope):w.id;let F;const G=this._initialConfig&&this._initialConfig[E];(w.config||G)&&(F=Object.assign({},w.config,G));const X=new eh(this.map,{scope:E,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:F,configOptions:this.options,colorThemeOverride:w["color-theme"],configDependentLayers:this._configDependentLayers,indoorDependentLayers:this._indoorDependentLayers});return X.setEventedParent(this.map,{style:X}),X}_reloadImports(){this.mergeAll(),this._updateMapProjection(),this.updateConfigDependencies(),this._updateLayers(this._indoorDependentLayers),this.map._triggerCameraUpdate(this.camera),this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),this._shouldPrecompile=this.map._precompilePrograms&&this.isRootStyle()}_isInternalStyle(w){return this.isRootStyle()&&(w.fragment||!!w.schema&&w.fragment!==!1)}_load(w,E){if(this._isInternalStyle(w)){const X=Object.assign({},V_,{imports:[{id:"basemap",data:w,url:""}]},w.center?{center:w.center}:{},w.bearing?{bearing:w.bearing}:{},w.pitch?{pitch:w.pitch}:{},w.zoom?{zoom:w.zoom}:{},w.light?{light:w.light}:{});return this._importedAsBasemap=!0,void this._load(X,E)}if(this.updateConfig(this._config,w.schema),E&&Sy(this,un(w)))return;this._loaded=!0;for(const X in w.sources)this.addSource(X,w.sources[X],{validate:!1,isInitialLoad:!0});this.stylesheet=o.d9(w);const F=()=>{if(w.iconsets)for(const ye in w.iconsets)this.addIconset(ye,w.iconsets[ye]);w.sprite?this._loadIconset(w.sprite):(this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0})),!this.glyphManager.url&&w.glyphs&&this.glyphManager.setURL(w.glyphs);const X=_u(this.stylesheet.layers);if(this._order=X.map(ye=>ye.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 ye=this.stylesheet.lights[0];this.light=new qr(ye.properties,ye.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new qr(this.stylesheet.light)),this._layers={};for(const ye of X){const Ce=o.de(ye,this.scope,this._styleColorTheme.lut,this.options);Ce.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(Ce.fqid),Ce.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(Ce.fqid),this._hasAppearances=this._hasAppearances||Ce.getAppearances().length!==0,Ce.setEventedParent(this,{layer:{id:Ce.id}}),this._layers[Ce.id]=Ce;const Le=this.getOwnLayerSourceCache(Ce),Xe=!!this.directionalLight&&this.directionalLight.shadowsEnabled();Le&&Ce.canCastShadows()&&Xe&&(Le.castsShadows=!0)}if(this.glyphManager.url){const ye=new Set;for(const Ce in this._layers){const Le=this._layers[Ce];if(Le.type==="symbol"&&Le.layout){const Xe=Le.layout.get("text-font");Xe&&Xe.value&&Xe.value.kind==="constant"&&ye.add(Xe.value.value.join(","))}}for(const Ce of ye)this.glyphManager.prefetchRange(Ce,0)}this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const J=this.stylesheet.terrain;J&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||this._createTerrain(J,1)),this.stylesheet.fog&&this._createFog(this.stylesheet.fog),this.stylesheet.snow&&this._createSnow(this.stylesheet.snow),this.stylesheet.rain&&this._createRain(this.stylesheet.rain),this.stylesheet.transition&&this.setTransition(this.stylesheet.transition),this.fire(new o.C("data",{dataType:"style"}));const de=this.isRootStyle();w.imports?this._loadImports(w.imports,E).then(()=>{this._reloadImports(),this.fire(new o.C(de?"style.load":"style.import.load"))}).catch(ye=>{this.fire(new o.B(new Error("Failed to load imports",ye))),this.fire(new o.C(de?"style.load":"style.import.load"))}):(this._reloadImports(),this.fire(new o.C(de?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const G=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(G){const X=this._evaluateColorThemeData(G);this._loadColorTheme(X).then(()=>{F()}).catch(J=>{o.w(`Couldn't load color theme from the stylesheet: ${J}`),F()})}else this._styleColorTheme.lut=null,F()}isRootStyle(){return this.importDepth===0}hasAppearances(){return this._hasAppearances||this.fragments.some(w=>w.style.hasAppearances())}mergeAll(){let w,E,F,G,X,J,de,ye,Ce,Le;const Xe={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(Ke=>{if(Ke.stylesheet){if(Ke.light!=null&&(w=Ke.light),Ke.stylesheet.lights)for(const st of Ke.stylesheet.lights)st.type==="ambient"&&Ke.ambientLight!=null&&(E=Ke.ambientLight),st.type==="directional"&&Ke.directionalLight!=null&&(F=Ke.directionalLight);G=this._prioritizeTerrain(G,Ke.terrain,Ke.stylesheet.terrain),Ke.stylesheet.fog&&Ke.fog!=null&&(X=Ke.fog),Ke.stylesheet.snow&&Ke.snow!=null&&(J=Ke.snow),Ke.stylesheet.rain&&Ke.rain!=null&&(de=Ke.rain),Ke.stylesheet.camera!=null&&(Le=Ke.stylesheet.camera),Ke.stylesheet.projection!=null&&(ye=Ke.stylesheet.projection),Ke.stylesheet.transition!=null&&(Ce=Ke.stylesheet.transition),Xe[Ke.scope]=Ke._styleColorTheme}}),this.light=w,this.ambientLight=E,this.directionalLight=F,this.fog=X,this.snow=J,this.rain=de,this._styleColorThemeForScope=Xe,G===null?delete this.terrain:this.terrain=G,this.camera=Le||{"camera-projection":"perspective"},this.projection=ye||{name:"mercator"},this.transition=Object.assign({},Rx,Ce),this.mergeSources(),this.mergeLayers(),this.mergeIndoor()}forEachFragmentStyle(w){const E=F=>{for(const G of F.fragments)E(G.style);w(F)};E(this)}_prioritizeTerrain(w,E,F){const G=w&&w.drapeRenderMode===0;return F===null?E&&E.drapeRenderMode===0?E:G?w:null:E!=null&&(!w||G||E&&E.drapeRenderMode===1)?E:w}mergeTerrain(){let w;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(E=>{w=this._prioritizeTerrain(w,E.terrain,E.stylesheet.terrain)}),w===null?delete this.terrain:this.terrain=w}mergeProjection(){let w;this.forEachFragmentStyle(E=>{E.stylesheet.projection!=null&&(w=E.stylesheet.projection)}),this.projection=w||{name:"mercator"}}mergeSources(){const w={},E={},F={},G={};this.forEachFragmentStyle(X=>{for(const J in X._sourceCaches){const de=o.F(J,X.scope);w[de]=X._sourceCaches[J]}for(const J in X._otherSourceCaches){const de=o.F(J,X.scope);E[de]=X._otherSourceCaches[J]}for(const J in X._symbolSourceCaches){const de=o.F(J,X.scope);F[de]=X._symbolSourceCaches[J]}for(const J in X._fillExtrusionSourceCaches){const de=o.F(J,X.scope);G[de]=X._fillExtrusionSourceCaches[J]}}),this._mergedSourceCaches=w,this._mergedOtherSourceCaches=E,this._mergedSymbolSourceCaches=F,this._mergedFillExtrusionSourceCaches=G}mergeIndoor(){this.forEachFragmentStyle(w=>{if(w.stylesheet&&w.stylesheet.indoor)for(const E of Object.values(w.stylesheet.indoor)){const F=E,G=o.F(F.sourceId,w.scope);this._mergedIndoor[G]=new Set(F.sourceLayers||[])}})}mergeLayers(){const w={},E=[],F={};this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(J=>{for(const de of J._order){const ye=J._layers[de];if(ye.type==="slot"){const Ce=o.da(de);if(w[Ce])continue;w[Ce]=[]}ye.slot&&w[ye.slot]?w[ye.slot].push(ye):E.push(ye)}}),this._mergedOrder=[];let G=-1;const X=(J=[])=>{for(const de of J)if(de.type==="slot"){const ye=o.da(de.id);w[ye]&&X(w[ye]),this._mergedSlots.push(ye)}else{const ye=o.F(de.id,de.scope);this._mergedOrder.push(ye),F[ye]=de,de.is3D(!!this.terrain)&&(this._has3DLayers=!0,G=this._mergedOrder.length-1),de.type==="circle"&&(this._hasCircleLayers=!0),de.type==="symbol"&&(this._hasSymbolLayers=!0),de.type==="clip"&&(this._clipLayerPresent=!0)}};if(X(E),this._has3DLayers){const J={};for(let de=0;deJ[de]-J[ye])}this._mergedLayers=F,this.updateDrapeFirstLayers(),this._buildingIndex.processLayersChanged(),this._updateDataDrivenEmissiveStrength()}terrainSetForDrapingOnly(){return!!this.terrain&&this.terrain.drapeRenderMode===0}getCamera(){return this.stylesheet.camera}setCamera(w){return this.stylesheet.camera=Object.assign({},this.stylesheet.camera,w),this.camera=this.stylesheet.camera,this}_evaluateColorThemeData(w){return w.data?function(E,F,G){const X=Object.assign({},F);for(const de of Object.keys(Ju))X[de]===void 0&&(X[de]=Ju[de].default);const J=new o.aa(_c,E,new Map(G));return J.setTransitionOrValue(X,G),J.untransitioned().possiblyEvaluate(new o.ae(0,{worldview:void 0}))}(this.scope,w,this.options).get("data"):null}_loadColorTheme(w){this._styleColorTheme.lutLoading=!0,this._styleColorTheme.lutLoadingCorrelationID+=1;const E=this._styleColorTheme.lutLoadingCorrelationID;return new Promise((F,G)=>{const X="data:image/png;base64,";if(!w||w.length===0)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void F();let J=w;J.startsWith(X)||(J=X+J);const de=o.I.from("mapbox-reserved-lut"),ye=new Image;ye.src=J,ye.onerror=()=>{this._styleColorTheme.lutLoading=!1,G(new Error("Failed to load image data"))},ye.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==E)return void F();this._styleColorTheme.lutLoading=!1;const{width:Ce,height:Le,data:Xe}=o.o.getImageData(ye);if(Le>32)return void G(new Error("The height of the image must be less than or equal to 32 pixels."));if(Ce!==Le*Le)return void G(new Error("The width of the image must be equal to the height squared."));this.getImage(de)&&this.removeImage(de),this.addImage(de,{data:new o.q({width:Ce,height:Le},Xe),pixelRatio:1,sdf:!1,usvg:!1,version:0});const Ke=this.imageManager.getImage(de,this.scope);Ke?(this._styleColorTheme.lut={image:Ke.data,data:w},F()):G(new Error("Missing LUT image."))}})}getLut(w){const E=this._styleColorThemeForScope[w];return E?E.lut:null}setProjection(w){w?this.stylesheet.projection=w:delete this.stylesheet.projection,this.mergeProjection(),this._updateMapProjection()}applyProjectionUpdate(){this._loaded&&(this.dispatcher.broadcast("setProjection",this.map.transform.projectionOptions),this.map.transform.projection.requiresDraping?(this.getTerrain()||this.stylesheet.terrain)&&!this.disableElevatedTerrain||this.setTerrainForDraping():this.terrainSetForDrapingOnly()&&this.setTerrain(null,0))}_updateMapProjection(){this.isRootStyle()&&(this.map._useExplicitProjection?this.applyProjectionUpdate():this.map._prioritizeAndUpdateProjection(null,this.projection))}_loadSprite(w){this._spriteRequest=function(E,F,G){let X,J,de;const ye=o.o.devicePixelRatio>1?"@2x":"";let Ce=o.m(F.transformRequest(F.normalizeSpriteURL(E,ye,".json"),o.R.SpriteJSON),(Ke,st)=>{Ce=null,de||(de=Ke,X=st,Xe())}),Le=o.n(F.transformRequest(F.normalizeSpriteURL(E,ye,".png"),o.R.SpriteImage),(Ke,st)=>{Le=null,de||(de=Ke,J=st,Xe())});function Xe(){if(de)G(de);else if(X&&J){const Ke=o.o.getImageData(J),st={};for(const dt in X){const{width:it,height:jt,x:wt,y:Bt,sdf:Vt,pixelRatio:Ct,stretchX:Ss,stretchY:rs,content:_s}=X[dt],Gt=new o.q({width:it,height:jt});o.q.copy(Ke,Gt,{x:wt,y:Bt},{x:0,y:0},{width:it,height:jt},null),st[dt]={data:Gt,pixelRatio:Ct!==void 0?Ct:1,sdf:Vt!==void 0&&Vt,stretchX:Ss,stretchY:rs,content:_s,usvg:!1,version:0}}G(null,st)}}return{cancel(){Ce&&(Ce.cancel(),Ce=null),Le&&(Le.cancel(),Le=null)}}}(w,this.map._requestManager,(E,F)=>{if(this._spriteRequest=null,E)this.fire(new o.B(E));else if(F){const G=new Map;for(const X in F)G.set(o.I.from(X),F[X]);this.addImages(G)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new o.C("data",{dataType:"style"}))})}addIconset(w,E){if(E.type==="sprite")return void this._loadSprite(E.url);const F=this.getOwnSourceCache(E.source);if(!F)return void this.fire(new o.B(new Error(`Source "${E.source}" as specified by iconset "${w}" does not exist and cannot be used as an iconset source`)));const G=F.getSource();if(G.type!=="raster-array")return void this.fire(new o.B(new Error(`Source "${E.source}" as specified by iconset "${w}" is not a "raster-array" source and cannot be used as an iconset source`)));G.partial=!1;const X=new ju(w,this.scope,F);this.imageManager.addImageProvider(X,this.scope)}removeIconset(w){this.imageManager.removeImageProvider(w,this.scope)}_loadIconset(w){if(!o.e(w)&&this.map._spriteFormat!=="icon_set"||this.map._spriteFormat==="raster")return void this._loadSprite(w);const E=this.map._spriteFormat==="auto";var F,G;this._spriteRequest=(G=(X,J)=>{if(this._spriteRequest=null,X)E?this._loadSprite(w):this.fire(new o.B(X));else if(J){const de=new Map;for(const ye in J)de.set(o.I.from(ye),J[ye]);this.addImages(de)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new o.C("data",{dataType:"style"}))},o.b1((F=this.map._requestManager).transformRequest(F.normalizeIconsetURL(w),o.R.Iconset),(X,J)=>{if(X)return void G(X);const de={},ye=o.c$(new o.a$(J));for(const Ce of ye.icons){const Le={version:1,pixelRatio:o.o.devicePixelRatio,content:xl(Ce),stretchX:Ce.metadata?ll(Ce.metadata.stretch_x_areas):void 0,stretchY:Ce.metadata?ll(Ce.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:Ce};de[Ce.name]=Le}G(null,de)}))}_validateLayer(w){const E=this.getOwnSource(w.source);if(!E)return;const F=w.sourceLayer;F&&(E.type==="geojson"||E.vectorLayerIds&&E.vectorLayerIds.indexOf(F)===-1)&&this.fire(new o.B(new Error(`Source layer "${F}" does not exist on source "${E.id}" as specified by style layer "${w.id}"`)))}loaded(){if(!this._loaded||Object.keys(this._changes.getUpdatedSourceCaches()).length)return!1;for(const w in this._sourceCaches)if(!this._sourceCaches[w].loaded())return!1;if(!this.imageManager.isLoaded()||this.imageManager.hasPatternsInFlight()||!this.modelManager.isLoaded()||this._styleColorTheme.lutLoading)return!1;for(const{style:w}of this.fragments)if(!w.loaded())return!1;return!0}_serializeImports(){if(this.stylesheet.imports)return this.stylesheet.imports.map((w,E)=>{const F=this.fragments[E];return F&&F.style&&(w.data=F.style.serialize()),w})}_serializeSources(){const w={};for(const E in this._sourceCaches){const F=this._sourceCaches[E].getSource();w[F.id]||(w[F.id]=F.serialize())}return w}_serializeLayers(w){const E=[];for(const F of w){const G=this._layers[F];G&&G.type!=="custom"&&E.push(G.serialize())}return E}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 w in this._sourceCaches)if(this._sourceCaches[w].hasTransition())return!0;for(const w in this._layers)if(this._layers[w].hasTransition())return!0;return!1}_updateDataDrivenEmissiveStrength(){for(const w in this._mergedLayers){const E=this._mergedLayers[w];if(E._transitionablePaint&&E._transitionablePaint._values){const F=E._transitionablePaint._values["line-emissive-strength"];if(F&&F.value&&F.value.isDataDriven())return void(this._hasDataDrivenEmissive=!0)}}this._hasDataDrivenEmissive=!1}hasDataDrivenEmissiveStrength(){return this._hasDataDrivenEmissive}get order(){return this.terrain?this._drapedFirstOrder:this._mergedOrder}_getOrder(w){return w?this.order:this._mergedOrder}isLayerDraped(w){return!!this.terrain&&w.isDraped(this.getLayerSourceCache(w))}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading")}_checkLayer(w){const E=this.getOwnLayer(w);if(E)return E;this.fire(new o.B(new Error(`The layer '${w}' does not exist in the map's style.`)))}_checkSource(w){const E=this.getOwnSource(w);if(E)return E;this.fire(new o.B(new Error(`The source '${w}' does not exist in the map's style.`)))}precompilePrograms(w,E){const F=this.map.painter;if(F)for(let G=w.minzoom||0;G<(w.maxzoom||25.5);G++){const X=w.getProgramIds();if(X)for(const J of X){const de=w.getDefaultProgramParams(J,E.zoom,this._styleColorTheme.lut);de&&(F.style=this,this.fog&&(F._fogVisible=!0,de.overrideFog=!0,F.getOrCreateProgram(J,de)),F._fogVisible=!1,de.overrideFog=!1,F.getOrCreateProgram(J,de),(this.stylesheet.terrain||this.stylesheet.projection&&this.stylesheet.projection.name==="globe")&&(de.overrideRtt=!0,F.getOrCreateProgram(J,de)))}}}update(w){if(!this._loaded)return;this.ambientLight&&this.ambientLight.recalculate(w),this.directionalLight&&this.directionalLight.recalculate(w);const E=this.calculateLightsBrightness();w.brightness=E||0,E!==this._brightness&&(this._brightness=E,this.dispatcher.broadcast("setBrightness",E)),w.worldview!==this._worldview&&(this._worldview=w.worldview,this.dispatcher.broadcast("setWorldview",this._worldview));const F=this._changes.isDirty();let G=!1;if(this._changes.isDirty()){const ye=this._changes.getLayerUpdatesByScope();for(const Ce in ye){const{updatedIds:Le,removedIds:Xe}=ye[Ce];(Le||Xe)&&(this._updateWorkerLayers(Ce,Le,Xe),G=!0)}this.updateSourceCaches(),this._updateTilesForChangedImages(),this.updateLayers(w),this.light&&this.light.updateTransitions(w),this.ambientLight&&this.ambientLight.updateTransitions(w),this.directionalLight&&this.directionalLight.updateTransitions(w),this.fog&&this.fog.updateTransitions(w),this.snow&&this.snow.updateTransitions(w),this.rain&&this.rain.updateTransitions(w),this._changes.reset()}const X={};for(const ye in this._mergedSourceCaches){const Ce=this._mergedSourceCaches[ye];X[ye]=Ce.used,Ce.used=!1,Ce.tileCoverLift=0}const J={};for(const ye of this._mergedOrder){const Ce=this._mergedLayers[ye];if((Ce.visibility!=="none"||Ce.hasTransition())&&Ce.recalculate(w,this._availableImages),!Ce.isHidden(w.zoom)){const Le=this.getLayerSourceCache(Ce);Le&&(Le.used=!0,Le.tileCoverLift=Math.max(Le.tileCoverLift,Ce.tileCoverLift()))}if(Ce.type==="fill-extrusion"){const Le=o.F(Ce.source,Ce.scope);if(Le in this._mergedFillExtrusionSourceCaches){const Xe=Ce.layout&&Ce.layout.get("source-max-zoom");if(Xe!=null){const Ke=J[Le];J[Le]=Ke==null?Xe:Math.min(Ke,Xe)}}}!this._precompileDone&&this._shouldPrecompile&&("requestIdleCallback"in window?requestIdleCallback(()=>{this.precompilePrograms(Ce,w)}):this.precompilePrograms(Ce,w))}this._shouldPrecompile&&(this._precompileDone=!0);for(const ye in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[ye].setMaxzoomOverride(J[ye]!=null?J[ye]:null);this.terrain&&G&&this.mergeLayers();const de=this.imageManager.getPendingImageProviders();for(const ye of de)ye.sourceCache.used=!0;for(const ye in X){const Ce=this._mergedSourceCaches[ye];X[ye]!==Ce.used&&Ce.getSource().fire(new o.C("data",{sourceDataType:"visibility",dataType:"source",sourceId:Ce.getSource().id}))}this.light&&this.light.recalculate(w),this.terrain&&this.terrain.recalculate(w),this.fog&&this.fog.recalculate(w),this.snow&&this.snow.recalculate(w),this.rain&&this.rain.recalculate(w),this.z=w.zoom,this._markersNeedUpdate&&(this._updateMarkersOpacity(),this._markersNeedUpdate=!1),this.imageManager.clearUpdatedImages(this.scope),F&&this.fire(new o.C("data",{dataType:"style"}))}updateImageProviders(){const w=this.imageManager.getPendingImageProviders();for(const E of w){const F=E.resolvePendingRequests(),G=this.getFragmentStyle(E.scope);G&&G.addImages(F)}}_updateTilesForChangedImages(){const w={};for(const E in this._mergedSourceCaches){const F=this._mergedSourceCaches[E].getSource().scope;w[F]=w[F]||this._changes.getUpdatedImages(F),w[F].length!==0&&this._mergedSourceCaches[E].reloadTilesForDependencies(["icons","patterns"],w[F])}for(const E in w)this._changes.resetUpdatedImages(E)}_updateWorkerLayers(w,E,F){const G=this.getFragmentStyle(w);G&&this.dispatcher.broadcast("updateLayers",{layers:E?G._serializeLayers(E):[],scope:w,removedIds:F||[],options:G.options})}setState(w,E){if(this._checkLoaded(),Sy(this,un(w)))return!1;(w=o.d9(w)).layers=_u(w.layers);const F=function(J,de){if(!J)return[{command:zi.setStyle,args:[de]}];let ye=[];try{if(!o.b6(J.version,de.version))return[{command:zi.setStyle,args:[de]}];if(o.b6(J.center,de.center)||ye.push({command:zi.setCenter,args:[de.center]}),o.b6(J.zoom,de.zoom)||ye.push({command:zi.setZoom,args:[de.zoom]}),o.b6(J.bearing,de.bearing)||ye.push({command:zi.setBearing,args:[de.bearing]}),o.b6(J.pitch,de.pitch)||ye.push({command:zi.setPitch,args:[de.pitch]}),o.b6(J.sprite,de.sprite)||ye.push({command:zi.setSprite,args:[de.sprite]}),o.b6(J.glyphs,de.glyphs)||ye.push({command:zi.setGlyphs,args:[de.glyphs]}),o.b6(J.imports,de.imports)||function(st=[],dt=[],it){dt=dt||[];const jt=(st=st||[]).map(Bm),wt=dt.map(Bm),Bt=st.reduce(j0,{}),Vt=dt.reduce(j0,{}),Ct=jt.slice();let Ss,rs,_s,Gt;for(Ss=0,rs=0;Ss{st.source&&Ce[st.source]?ye.push({command:zi.removeLayer,args:[st.id]}):Xe.push(st)});let Ke=J.terrain;Ke&&Ce[Ke.source]&&(ye.push({command:zi.setTerrain,args:[void 0]}),Ke=void 0),ye=ye.concat(Le),o.b6(Ke,de.terrain)||ye.push({command:zi.setTerrain,args:[de.terrain]}),function(st,dt,it){dt=dt||[];const jt=(st=st||[]).map(Bm),wt=dt.map(Bm),Bt=st.reduce(j0,{}),Vt=dt.reduce(j0,{}),Ct=jt.slice(),Ss=Object.create(null);let rs,_s,Gt,ss,xs,Ks,Ts;for(rs=0,_s=0;rs!(J.command in $_));if(F.length===0)return!1;const G=F.filter(J=>!(J.command in sm));if(G.length>0)throw new Error(`Unimplemented: ${G.map(J=>J.command).join(", ")}.`);const X=[];return F.forEach(J=>{X.push(this[J.command](...J.args))}),E&&Promise.all(X).then(E).catch(E),this.stylesheet=w,this.mergeAll(),this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),!0}_updateWorkerImages(){this._availableImages=this.imageManager.listImages(this.scope),this.dispatcher.broadcast("setImages",{scope:this.scope,images:this._availableImages})}_updateWorkerModels(){this._availableModels=this.modelManager.getModelURIs(this.scope),this.dispatcher.broadcast("setModels",{scope:this.scope,models:this._availableModels})}addImages(w){if(w.size===0)return this;for(const[E,F]of w.entries()){if(this.getImage(E))return this.fire(new o.B(new Error(`An image with the name "${E.name}" already exists.`)));this.imageManager.addImage(E,this.scope,F),this._changes.updateImage(E,this.scope)}return this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this}addImage(w,E){return this.getImage(w)?this.fire(new o.B(new Error(`An image with the name "${w.name}" already exists.`))):(this.imageManager.addImage(w,this.scope,E),this._changes.updateImage(w,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this)}updateImage(w,E,F=!1){this.imageManager.updateImage(w,this.scope,E),F&&(this._changes.updateImage(w,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})))}getImage(w){return this.imageManager.getImage(w,this.scope)}removeImage(w){return this.getImage(w)?(this.imageManager.removeImage(w,this.scope),this._changes.updateImage(w,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this):this.fire(new o.B(new Error("No image with this name exists.")))}listImages(){return this._checkLoaded(),this._availableImages.slice()}getActualScope(){return this._importedAsBasemap?"basemap":this.scope}addModelURLs(w){return this.modelManager.addModelURLs(w,this.getActualScope()),this._updateWorkerModels(),this.fire(new o.C("data",{dataType:"style"})),this}addModel(w,E,F={}){return this._checkLoaded(),this._validate(Xs,`models.${w}`,E,null,F)||(this.modelManager.addModel(w,E,this.getActualScope()),this.fire(new o.C("data",{dataType:"style"}))),this}hasModel(w){return this.modelManager.hasModel(w,this.getActualScope())}removeModel(w){return this.hasModel(w)?(this.modelManager.removeModel(w,this.getActualScope(),!1,!0),this.fire(new o.C("data",{dataType:"style"})),this):this.fire(new o.B(new Error("No model with this ID exists.")))}listModels(){return this._checkLoaded(),this.modelManager.listModels(this.getActualScope())}addSource(w,E,F={}){if(this._checkLoaded(),this.getOwnSource(w)!==void 0)throw new Error(`There is already a source with ID "${w}".`);if(!E.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(E).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(E.type)>=0&&this._validate(Ar,`sources.${w}`,E,null,F))return;this.map&&this.map._collectResourceTiming&&(E.collectResourceTiming=!0);const G=Hp(w,E,this.dispatcher,this);G.scope=this.scope,G.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded(G.id),source:G.serialize(),sourceId:G.id}));const X=J=>{const de=(J===o.b4.Symbol?"symbol:":J===o.b4.FillExtrusion?"fill-extrusion:":"other:")+G.id,ye=o.F(de,this.scope),Ce=this._sourceCaches[de]=new Vl(ye,G,J);J===o.b4.Symbol?this._symbolSourceCaches[G.id]=Ce:J===o.b4.FillExtrusion?this._fillExtrusionSourceCaches[G.id]=Ce:this._otherSourceCaches[G.id]=Ce,Ce.onAdd(this.map)};X(o.b4.Other),E.type!=="vector"&&E.type!=="geojson"||(X(o.b4.Symbol),E.type==="vector"&&X(o.b4.FillExtrusion)),G.onAdd&&G.onAdd(this.map),F.isInitialLoad||(this.mergeSources(),this._changes.setDirty())}removeSource(w){this._checkLoaded();const E=this.getOwnSource(w);if(!E)throw new Error("There is no source with this ID");for(const G in this._layers)if(this._layers[G].source===w)return this.fire(new o.B(new Error(`Source "${w}" cannot be removed while layer "${G}" is using it.`)));if(this.terrain&&this.terrain.scope===this.scope&&this.terrain.get().source===w)return this.fire(new o.B(new Error(`Source "${w}" cannot be removed while terrain is using it.`)));if(this.stylesheet.iconsets){const G=Object.entries(this.stylesheet.iconsets).find(([X,J])=>J.type==="source"&&J.source===w);if(G)return this.fire(new o.B(new Error(`Source "${w}" cannot be removed while iconset "${G[0]}" is using it.`)))}const F=this.getOwnSourceCaches(w);for(const G of F){const X=o.da(G.id);delete this._sourceCaches[X],this._changes.discardSourceCacheUpdate(G.id),G.fire(new o.C("data",{sourceDataType:"metadata",dataType:"source",sourceId:G.getSource().id})),G.setEventedParent(null),G.clearTiles()}return delete this._otherSourceCaches[w],delete this._symbolSourceCaches[w],delete this._fillExtrusionSourceCaches[w],this.mergeSources(),E.setEventedParent(null),E.onRemove&&E.onRemove(this.map),this._changes.setDirty(),this}setGeoJSONSourceData(w,E){this._checkLoaded(),this.getOwnSource(w).setData(E),this._changes.setDirty()}getOwnSource(w){const E=this.getOwnSourceCache(w);return E&&E.getSource()}getOwnSources(){const w=[];for(const E in this._otherSourceCaches){const F=this.getOwnSourceCache(E);F&&w.push(F.getSource())}return w}areTilesLoaded(){const w=this._mergedSourceCaches;for(const E in w){const F=w[E]._tiles;for(const G in F){const X=F[G];if(X.state!=="loaded"&&X.state!=="errored")return!1}}return!0}setLights(w){if(this._checkLoaded(),!w)return delete this.ambientLight,void delete this.directionalLight;const E=this._getTransitionParameters();for(const X of w){if(this._validate(ot,"lights",X))return;switch(X.type){case"ambient":if(this.ambientLight){const J=this.ambientLight;J.set(X),J.updateTransitions(E)}else this.ambientLight=new ir(X,li(),this.scope,this.options);break;case"directional":if(this.directionalLight){const J=this.directionalLight;J.set(X),J.updateTransitions(E)}else this.directionalLight=new ir(X,gl(),this.scope,this.options)}}const F=Object.assign(E,{worldview:this.map.getWorldview()}),G=new o.ae(this.z||0,F);this.ambientLight&&this.ambientLight.recalculate(G),this.directionalLight&&this.directionalLight.recalculate(G),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("setBrightness",this._brightness)}calculateLightsBrightness(){const w=this.directionalLight,E=this.ambientLight;if(!w||!E)return;const F=Ke=>.2126*(Ke[0]<=.03928?Ke[0]/12.92:Math.pow((Ke[0]+.055)/1.055,2.4))+.7152*(Ke[1]<=.03928?Ke[1]/12.92:Math.pow((Ke[1]+.055)/1.055,2.4))+.0722*(Ke[2]<=.03928?Ke[2]/12.92:Math.pow((Ke[2]+.055)/1.055,2.4)),G=w.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),X=w.properties.get("intensity"),J=w.properties.get("direction"),de=1-o.cP(J.x,J.y,J.z)[2]/90,ye=F(G)*X*de,Ce=E.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),Le=E.properties.get("intensity"),Xe=F(Ce)*Le;return Number(((ye+Xe)/2).toFixed(6))}getBrightness(){return this._brightness}getLights(){if(!this.enable3dLights())return null;const w=[];return this.directionalLight&&w.push(this.directionalLight.get()),this.ambientLight&&w.push(this.ambientLight.get()),w}enable3dLights(){return!!this.ambientLight&&!!this.directionalLight}getFragmentStyle(w){if(w==null||w===""&&this.isRootStyle())return this;if(o.db(w)){const E=o.dc(w),F=this.fragments.find(({id:X})=>X===E);if(!F)return;const G=o.da(w);return F.style.getFragmentStyle(G)}{const E=this.fragments.find(({id:F})=>F===w);return E?E.style:void 0}}setFeaturesetSelectors(w){if(!w)return;const E=(F,G="")=>`${F}::${G}`;this._featuresetSelectors={};for(const F in w){const G={},X=this._featuresetSelectors[F]=[];for(const J of w[F].selectors){if(J.featureNamespace){const ye=this.getOwnLayer(J.layer);if(!ye){o.w(`Layer is undefined for selector: ${J.layer}`);continue}const Ce=E(ye.source,ye.sourceLayer);if(Ce in G&&G[Ce]!==J.featureNamespace){o.w(`"featureNamespace ${J.featureNamespace} of featureset ${F}'s selector is not associated to the same source, skip this selector`);continue}G[Ce]=J.featureNamespace}let de;if(J.properties)for(const ye in J.properties){const Ce=o.X(J.properties[ye]);Ce.result==="success"&&(de=de||{},de[ye]=Ce.value)}X.push({layerId:J.layer,namespace:J.featureNamespace,properties:de,uniqueFeatureID:J._uniqueFeatureID})}}}getFeaturesetDescriptors(w){const E=this.getFragmentStyle(w);if(!E||!E.stylesheet.featuresets)return[];const F=[];for(const G in E.stylesheet.featuresets)F.push({featuresetId:G,importId:E.scope?E.scope:void 0});return F}getFeaturesetLayers(w,E){const F=this.getFragmentStyle(E),G=F.stylesheet.featuresets;if(!G||!G[w])return this.fire(new o.B(new Error(`The featureset '${w}' does not exist in the map's style and cannot be queried.`))),[];const X=[];for(const J of G[w].selectors){const de=F.getOwnLayer(J.layer);de&&X.push(de)}return X}getConfigProperty(w,E){const F=this.getFragmentStyle(w);if(!F)return null;const G=o.F(E,F.scope),X=F.options.get(G),J=X?X.value||X.default:null;return J?J.serialize():null}isIndoorEnabled(){return Object.keys(this._mergedIndoor).length>0}getIndoorSourceLayers(w,E){const F=o.F(w,E);return this._mergedIndoor[F]}setIndoorData(w,E){this.indoorManager.setIndoorData(E)}updateIndoorDependentLayers(){this._updateLayers(this._indoorDependentLayers),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(w,E,F){const G=this.getFragmentStyle(w);if(!G)return;const X=G.stylesheet.schema;if(!X||!X[E])return;const J=o.X(F);if(J.result!=="success")return void Sy(this,J.value);const de=J.value.expression,ye=o.F(E,G.scope),Ce=G.options.get(ye);if(!Ce)return;let Le;const{minValue:Xe,maxValue:Ke,stepValue:st,type:dt,values:it}=X[E],jt=o.X(X[E].default);jt.result==="success"&&(Le=jt.value.expression),Le?(this.options.set(ye,Object.assign({},Ce,{value:de,default:Le,minValue:Xe,maxValue:Ke,stepValue:st,type:dt,values:it})),this.updateConfigDependencies(E)):this.fire(new o.B(new Error(`No schema defined for the config option "${E}" in the "${w}" fragment.`)))}getConfig(w){const E=this.getFragmentStyle(w);if(!E)return null;const F=E.stylesheet.schema;if(!F)return null;const G={};for(const X in F){const J=o.F(X,E.scope),de=E.options.get(J),ye=de?de.value||de.default:null;G[X]=ye?ye.serialize():null}return G}setConfig(w,E){const F=this.getFragmentStyle(w);F&&(F.updateConfig(E,F.stylesheet.schema),this.updateConfigDependencies())}getSchema(w){const E=this.getFragmentStyle(w);return E?E.stylesheet.schema:null}setSchema(w,E){const F=this.getFragmentStyle(w);F&&(F.stylesheet.schema=E,F.updateConfig(F._config,E),this.updateConfigDependencies())}updateConfig(w,E){if(this._config=w,w||E)if(E)for(const F in E){let G,X;const J=o.X(E[F].default);if(J.result==="success"&&(G=J.value.expression),w&&w[F]!==void 0){const Ke=o.X(w[F]);Ke.result==="success"&&(X=Ke.value.expression)}const{minValue:de,maxValue:ye,stepValue:Ce,type:Le,values:Xe}=E[F];if(G){const Ke=o.F(F,this.scope);this.options.set(Ke,{default:G,value:X,minValue:de,maxValue:ye,stepValue:Ce,type:Le,values:Xe})}else this.fire(new o.B(new Error(`No schema defined for config option "${F}".`)))}else this.fire(new o.B(new Error("Attempting to set config for a style without schema.")))}_updateLayers(w,E=()=>!0){for(const F of w){const G=this.getLayer(F);G&&E(G)&&(G.possiblyEvaluateVisibility(),this._updateLayer(G),this._changes.setDirty())}}updateConfigDependencies(w){this._updateLayers(this._configDependentLayers,E=>!w||E.expressionDependencies.configDependencies.has(w)),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(E=>{const F=E._styleColorTheme.colorThemeOverride?E._styleColorTheme.colorThemeOverride:E._styleColorTheme.colorTheme;if(F){const G=E._evaluateColorThemeData(F);(!E._styleColorTheme.lut&&G!==""||E._styleColorTheme.lut&&G!==E._styleColorTheme.lut.data)&&E.setColorTheme(F)}}),this._changes.setDirty()}addLayer(w,E,F={}){this._checkLoaded();const G=w.id;if(this._layers[G])return void this.fire(new o.B(new Error(`Layer with id "${G}" already exists on this map`)));let X;if(w.type==="custom"){if(Sy(this,o.dd(w)))return;X=o.de(w,this.scope,this._styleColorTheme.lut,this.options)}else{if(typeof w.source=="object"&&(this.addSource(G,w.source),w=o.d9(w),w=Object.assign(w,{source:G})),this._validate(ls,`layers.${G}`,w,{arrayIndex:-1},F))return;X=o.de(w,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(X),X.setEventedParent(this,{layer:{id:G}})}const J=o.F(X.source,X.scope);X.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(J),X.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(J);let de=this._order.length;if(E){const Xe=this._order.indexOf(E);if(Xe===-1)return void this.fire(new o.B(new Error(`Layer with id "${E}" does not exist on this map.`)));X.slot&&X.slot!==this._layers[E].slot?o.w(`Layer with id "${E}" has a different slot. Layers can only be rearranged within the same slot.`):de=Xe}this._order.splice(de,0,G),this._handleLayerOrderChange(),this._layers[G]=X;const ye=this.getOwnLayerSourceCache(X),Ce=!!this.directionalLight&&this.directionalLight.shadowsEnabled();ye&&X.canCastShadows()&&Ce&&(ye.castsShadows=!0);const Le=this._changes.getRemovedLayer(X);if(Le&&X.source&&ye&&X.type!=="custom"){this._changes.discardLayerRemoval(X);const Xe=o.F(X.source,X.scope);Le.type!==X.type?this._changes.updateSourceCache(Xe,"clear"):(this._changes.updateSourceCache(Xe,"reload"),ye.pause())}this._updateLayer(X),X.onAdd&&X.onAdd(this.map),X.scope=this.scope,this.mergeLayers()}moveLayer(w,E){this._checkLoaded();const F=this._checkLayer(w);if(!F||w===E)return;const G=this._order.indexOf(w);this._order.splice(G,1);let X=this._order.length;if(E){const J=this._order.indexOf(E);if(J===-1)return void this.fire(new o.B(new Error(`Layer with id "${E}" does not exist on this map.`)));F.slot&&F.slot!==this._layers[E].slot?o.w(`Layer with id "${E}" has a different slot. Layers can only be rearranged within the same slot.`):X=J}this._order.splice(X,0,w),this._changes.setDirty(),this._handleLayerOrderChange(),this.mergeLayers()}removeLayer(w){this._checkLoaded();const E=this._checkLayer(w);if(!E)return;E.setEventedParent(null);const F=this._order.indexOf(w);this._order.splice(F,1),delete this._layers[w],this._changes.setDirty(),this._handleLayerOrderChange(),this._configDependentLayers.delete(E.fqid),this._indoorDependentLayers.delete(E.fqid),this._changes.removeLayer(E);const G=this.getOwnLayerSourceCache(E);if(G&&G.castsShadows){let X=!1;for(const J in this._layers)if(this._layers[J].source===E.source&&this._layers[J].canCastShadows()){X=!0;break}G.castsShadows=X}E.onRemove&&E.onRemove(this.map),this.mergeLayers()}getOwnLayer(w){return this._layers[w]}hasLayer(w){return w in this._mergedLayers}hasLayerType(w){for(const E in this._layers)if(this._layers[E].type===w)return!0;return!1}setLayerZoomRange(w,E,F){this._checkLoaded();const G=this._checkLayer(w);G&&(G.minzoom===E&&G.maxzoom===F||(E!=null&&(G.minzoom=E),F!=null&&(G.maxzoom=F),this._updateLayer(G)))}getSlots(){return this._checkLoaded(),this._mergedSlots}setSlot(w,E){this._checkLoaded();const F=this._checkLayer(w);F&&F.slot!==E&&(F.slot=E,this._updateLayer(F))}setFilter(w,E,F={}){this._checkLoaded();const G=this._checkLayer(w);if(G&&!o.b6(G.filter,E))return E==null?(G.filter=void 0,void this._updateLayer(G)):void(this._validate(Is,`layers.${G.id}.filter`,E,{layerType:G.type},F)||(G.filter=o.d9(E),this._updateLayer(G)))}getFilter(w){const E=this._checkLayer(w);if(E)return o.d9(E.filter)}setLayoutProperty(w,E,F,G={}){this._checkLoaded();const X=this._checkLayer(w);if(X&&!o.b6(X.getLayoutProperty(E),F)){if(F!=null&&(!G||G.validate!==!1)&&Sy(X,Ht.call(un,{key:`layers.${w}.layout.${E}`,layerType:X.type,objectKey:E,value:F,styleSpec:o.a8,style:{glyphs:!0,sprite:!0}})))return;X.setLayoutProperty(E,F),X.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(X.fqid),X.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(X.fqid),this._updateLayer(X)}}setLayerProperty(w,E,F,G={}){this._checkLoaded();const X=this._checkLayer(w);X&&(E==="appearances"?(X.setAppearances(F),this._updateLayer(X)):X.isPaintProperty(E)?this.setPaintProperty(w,E,F,G):this.setLayoutProperty(w,E,F,G))}getLayoutProperty(w,E){const F=this._checkLayer(w);if(F)return F.getLayoutProperty(E)}setPaintProperty(w,E,F,G={}){this._checkLoaded();const X=this._checkLayer(w);if(!X||o.b6(X.getPaintProperty(E),F)||F!=null&&(!G||G.validate!==!1)&&Sy(X,ps.call(un,{key:`layers.${w}.paint.${E}`,layerType:X.type,objectKey:E,value:F,styleSpec:o.a8})))return;const J=X.setPaintProperty(E,F);X.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(X.fqid),X.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(X.fqid),J&&this._updateLayer(X),this._changes.updatePaintProperties(X)}getPaintProperty(w,E){const F=this._checkLayer(w);if(F)return F.getPaintProperty(E)}setFeatureState(w,E){if(this._checkLoaded(),"target"in w){if("featuresetId"in w.target){const{featuresetId:ye,importId:Ce}=w.target,Le=this.getFragmentStyle(Ce),Xe=Le.getFeaturesetLayers(ye);for(const{source:Ke,sourceLayer:st}of Xe)Le.setFeatureState({id:w.id,source:Ke,sourceLayer:st},E)}else if("layerId"in w.target){const{layerId:ye}=w.target,Ce=this.getLayer(ye);this.setFeatureState({id:w.id,source:Ce.source,sourceLayer:Ce.sourceLayer},E)}return}const F=w.source,G=w.sourceLayer,X=this._checkSource(F);if(!X)return;const J=X.type;if(J==="geojson"&&G)return void this.fire(new o.B(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if(J==="vector"&&!G)return void this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")));w.id===void 0&&this.fire(new o.B(new Error("The feature id parameter must be provided.")));const de=this.getOwnSourceCaches(F);for(const ye of de)ye.setFeatureState(G,w.id,E)}removeFeatureState(w,E){if(this._checkLoaded(),"target"in w){if("featuresetId"in w.target){const{featuresetId:ye,importId:Ce}=w.target,Le=this.getFragmentStyle(Ce),Xe=Le.getFeaturesetLayers(ye);for(const{source:Ke,sourceLayer:st}of Xe)Le.removeFeatureState({id:w.id,source:Ke,sourceLayer:st},E)}else if("layerId"in w.target){const{layerId:ye}=w.target,Ce=this.getLayer(ye);this.removeFeatureState({id:w.id,source:Ce.source,sourceLayer:Ce.sourceLayer},E)}return}const F=w.source,G=this._checkSource(F);if(!G)return;const X=G.type,J=X==="vector"?w.sourceLayer:void 0;if(X==="vector"&&!J)return void this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")));if(E&&typeof w.id!="string"&&typeof w.id!="number")return void this.fire(new o.B(new Error("A feature id is required to remove its specific state property.")));const de=this.getOwnSourceCaches(F);for(const ye of de)ye.removeFeatureState(J,w.id,E)}getFeatureState(w){if(this._checkLoaded(),"target"in w){let X;if("featuresetId"in w.target){const{featuresetId:J,importId:de}=w.target,ye=this.getFragmentStyle(de),Ce=ye.getFeaturesetLayers(J);for(const{source:Le,sourceLayer:Xe}of Ce){const Ke=ye.getFeatureState({id:w.id,source:Le,sourceLayer:Xe});if(Ke&&!X)X=Ke;else if(!o.b6(X,Ke))return void this.fire(new o.B(new Error("The same feature id exists in multiple sources in the featureset, but their feature states are not consistent through the sources.")))}}else if("layerId"in w.target){const{layerId:J}=w.target,de=this.getLayer(J);X=this.getFeatureState({id:w.id,source:de.source,sourceLayer:de.sourceLayer})}return X}const E=w.source,F=w.sourceLayer,G=this._checkSource(E);if(G){if(G.type!=="vector"||F)return w.id===void 0&&this.fire(new o.B(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(E)[0].getFeatureState(F,w.id);this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")))}}setTransition(w){return this.stylesheet.transition=Object.assign({},this.stylesheet.transition,w),this.transition=this.stylesheet.transition,this}getTransition(){return Object.assign({},this.stylesheet.transition)}setWorldview(w){w!==this._worldview&&(this._worldview=w,this.dispatcher.broadcast("setWorldview",this._worldview),this.reloadSources())}serialize(){this._checkLoaded();const w=this.getTerrain(),E=w&&this.terrain&&this.terrain.scope===this.scope?w:this.stylesheet.terrain;return o.df({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,fragment:this.stylesheet.fragment,iconsets:this.stylesheet.iconsets,featuresets:this.stylesheet.featuresets,imports:this._serializeImports(),schema:this.stylesheet.schema,camera:this.stylesheet.camera,light:this.stylesheet.light,lights:this.stylesheet.lights,terrain:E,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)},F=>F!==void 0)}_updateFilteredLayers(w){for(const E of Object.values(this._mergedLayers))w(E)&&this._updateLayer(E)}_updateLayer(w){this._changes.updateLayer(w);const E=this.getLayerSourceCache(w),F=o.F(w.source,w.scope),G=this._changes.getUpdatedSourceCaches();w.source&&!G[F]&&E&&E.getSource().type!=="raster"&&(this._changes.updateSourceCache(F,"reload"),E.pause()),w.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(w){const E=de=>this._mergedLayers[de].is3D(!!this.terrain),F=this.order,G={},X=[];for(let de=F.length-1;de>=0;de--){const ye=F[de];if(E(ye)){G[ye]=de;for(const Ce of w){const Le=Ce[ye];if(Le)for(const Xe of Le)X.push(Xe)}}}X.sort((de,ye)=>ye.intersectionZ-de.intersectionZ);const J=[];for(let de=F.length-1;de>=0;de--){const ye=F[de];if(E(ye))for(let Ce=X.length-1;Ce>=0;Ce--){const Le=X[Ce].feature;if(Le.layer&&G[Le.layer.id]{if(Tj.has(Le.type))return;const Xe=this.getOwnLayerSourceCache(Le),Ke=X[Xe.id]=X[Xe.id]||{sourceCache:Xe,layers:{},has3DLayers:!1};Le.is3D(!!this.terrain)&&(Ke.has3DLayers=!0),Ke.layers[Le.fqid]=Ke.layers[Le.fqid]||{styleLayer:Le,targets:[]},Ke.layers[Le.fqid].targets.push({filter:G})};if(E&&E.layers){if(!Array.isArray(E.layers))return this.fire(new o.B(new Error("parameters.layers must be an Array."))),[];for(const Le of E.layers){const Xe=this._layers[Le];if(!Xe)return this.fire(new o.B(new Error(`The layer '${Le}' does not exist in the map's style and cannot be queried for features.`))),[];J(Xe)}}else for(const Le in this._layers)J(this._layers[Le]);const de=this._queryRenderedFeatures(w,X,F),ye=this._flattenAndSortRenderedFeatures(de),Ce=[];for(const Le of ye)o.dh(Le.layer.id)===this.scope&&Ce.push(Le);return Ce}queryRenderedFeatureset(w,E,F){let G;E&&!Array.isArray(E)&&E.filter&&(this._validate(Is,"queryRenderedFeatures.filter",E.filter,null,E),G=o.dg(E.filter));const X="mock",J=[];if(E&&E.target)J.push(Object.assign({},E,{targetId:X,filter:G}));else{const Le=this.getFeaturesetDescriptors();for(const Xe of Le)J.push({targetId:X,filter:G,target:Xe});for(const{style:Xe}of this.fragments){const Ke=Xe.getFeaturesetDescriptors();for(const st of Ke)J.push({targetId:X,filter:G,target:st})}}const de=this.queryRenderedTargets(w,J,F),ye=[],Ce=new Set;for(const Le of de)for(const Xe of Le.variants[X])Lh(Xe,Le,Ce)||ye.push(new o.di(Le,Xe));return ye}queryRenderedTargets(w,E,F){const G={},X=(de,ye,Ce,Le)=>{const Xe=G[ye.id]=G[ye.id]||{sourceCache:ye,layers:{},has3DLayers:!1};if(Xe.layers[de.fqid]=Xe.layers[de.fqid]||{styleLayer:de,targets:[]},de.is3D(!!this.terrain)&&(Xe.has3DLayers=!0),!Le)return Ce.uniqueFeatureID=!1,void Xe.layers[de.fqid].targets.push(Ce);Xe.layers[de.fqid].targets.push(Object.assign({},Ce,{namespace:Le.namespace,properties:Le.properties,uniqueFeatureID:Le.uniqueFeatureID}))};for(const de of E)if("featuresetId"in de.target){const{featuresetId:ye,importId:Ce}=de.target,Le=this.getFragmentStyle(Ce);if(!Le||!Le._featuresetSelectors)continue;const Xe=Le._featuresetSelectors[ye];if(!Xe){this.fire(new o.B(new Error(`The featureset '${ye}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const Ke of Xe){const st=Le.getOwnLayer(Ke.layerId);st&&!Tj.has(st.type)&&X(st,Le.getOwnLayerSourceCache(st),de,Ke)}}else if("layerId"in de.target){const{layerId:ye}=de.target,Ce=this.getLayer(ye);if(!Ce||Tj.has(Ce.type))continue;X(Ce,this.getLayerSourceCache(Ce),de)}const J=this._queryRenderedFeatures(w,G,F);return this._flattenAndSortRenderedFeatures(J)}_queryRenderedFeatures(w,E,F){const G=[],X=!!this.map._showQueryGeometry,J=ds.createFromScreenPoints(w,F);for(const de in E){const ye=by(J,E[de],this._availableImages,F,X,this.getActualScope());Object.keys(ye).length&&G.push(ye)}if(this.placement)for(const de in E){if(E[de].sourceCache._renderSourceType!==o.b4.Symbol)continue;const ye=qo(J.screenGeometry,E[de],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(ye).length&&G.push(ye)}return G}querySourceFeatures(w,E){const F=E&&E.filter;F&&this._validate(Is,"querySourceFeatures.filter",F,null,E);let G=[];const X=this.getOwnSourceCaches(w);for(const J of X)G=G.concat(bo(J,E));return G}addSourceType(w,E,F){return eh.getSourceType(w)?F(new Error(`A source type called "${w}" already exists.`)):(eh.setSourceType(w,E),E.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:w,url:E.workerSourceURL},F):F(null,null))}getFlatLight(){return this.light.getLight()}setFlatLight(w,E,F={}){this._checkLoaded();const G=this.light.getLight();let X=!1;for(const de in w)if(!o.b6(w[de],G[de])){X=!0;break}if(!X)return;const J=this._getTransitionParameters();this.light.setLight(w,E,F),this.light.updateTransitions(J)}getTerrain(){return this.terrain&&this.terrain.drapeRenderMode===1?this.terrain.get():null}setTerrainForDraping(){this.setTerrain({source:"",exaggeration:0},0)}checkCanvasFingerprintNoise(){this.disableElevatedTerrain===void 0&&(this.disableElevatedTerrain=o.o.hasCanvasFingerprintNoise(),this.disableElevatedTerrain&&o.w("Terrain and hillshade are disabled because of Canvas2D limitations when fingerprinting protection is enabled (e.g. in private browsing mode)."))}setTerrain(w,E=1){if(this._checkLoaded(),!w)return this.terrainSetForDrapingOnly()||(delete this.terrain,this.map.transform.projection.requiresDraping&&this.setTerrainForDraping()),E===0&&delete this.terrain,w===null?this.stylesheet.terrain=null:delete this.stylesheet.terrain,this._force3DLayerUpdate(),void(this._markersNeedUpdate=!0);this.checkCanvasFingerprintNoise();let F=w;const G=!("source"in w)||w.source==null;if(E===1){if(this.disableElevatedTerrain)return;if("source"in F&&typeof F.source=="object"){const de="terrain-dem-src";this.addSource(de,F.source),F=o.d9(F),F=Object.assign(F,{source:de})}const X=Object.assign({},F),J={};if(this.terrain&&G){X.source=this.terrain.get().source;const de=this.terrain?this.getFragmentStyle(this.terrain.scope):null;de&&(J.style=de.serialize())}if(this._validate(mt,"terrain",X,J))return}if(!this.terrain||this.terrain.scope!==this.scope&&!G||this.terrain&&E!==this.terrain.drapeRenderMode){if(!F)return;this._createTerrain(F,E),this.fire(new o.C("data",{dataType:"style"}))}else{const X=this.terrain,J=X.get();for(const de of Object.keys(o.a8.terrain))!F.hasOwnProperty(de)&&o.a8.terrain[de].default&&(F[de]=o.a8.terrain[de].default);for(const de in w)if(!o.b6(w[de],J[de])){X.set(w,this.options),this.stylesheet.terrain=w;const ye=this._getTransitionParameters({duration:0});X.updateTransitions(ye),this.fire(new o.C("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(w){const E=this.fog=new Co(w,this.map.transform,this.scope,this.options);this.stylesheet.fog=E.get();const F=this._getTransitionParameters({duration:0});E.updateTransitions(F)}_createSnow(w){const E=this.snow=new Ao(w,this.map.transform,this.scope,this.options);this.stylesheet.snow=E.get();const F=this._getTransitionParameters({duration:0});E.updateTransitions(F)}_createRain(w){const E=this.rain=new _a(w,this.map.transform,this.scope,this.options);this.stylesheet.rain=E.get();const F=this._getTransitionParameters({duration:0});E.updateTransitions(F)}_updateMarkersOpacity(){this.map._markers.length!==0&&this.map._requestDomTask(()=>{for(const w of this.map._markers)w._evaluateOpacity()})}getFog(){return this.fog?this.fog.get():null}setFog(w){if(this._checkLoaded(),!w)return delete this.fog,delete this.stylesheet.fog,void(this._markersNeedUpdate=!0);if(this.fog){const E=this.fog;if(!o.b6(E.get(),w)){E.set(w,this.options),this.stylesheet.fog=E.get();const F=this._getTransitionParameters({duration:0});E.updateTransitions(F)}}else this._createFog(w);this._markersNeedUpdate=!0}getSnow(){return this.snow?this.snow.get():null}setSnow(w){if(this._checkLoaded(),!w)return delete this.snow,void delete this.stylesheet.snow;if(this.snow){const E=this.snow;if(!o.b6(E.get(),w)){E.set(w,this.options),this.stylesheet.snow=E.get();const F=this._getTransitionParameters({duration:0});E.updateTransitions(F)}}else this._createSnow(w);this._markersNeedUpdate=!0}getRain(){return this.rain?this.rain.get():null}setRain(w){if(this._checkLoaded(),!w)return delete this.rain,void delete this.stylesheet.rain;if(this.rain){const E=this.rain;if(!o.b6(E.get(),w)){E.set(w,this.options),this.stylesheet.rain=E.get();const F=this._getTransitionParameters({duration:0});E.updateTransitions(F)}}else this._createRain(w);this._markersNeedUpdate=!0}_reloadColorTheme(){const w=()=>{for(const G in this._layers)this._layers[G].lut=this._styleColorTheme.lut;for(const G in this._sourceCaches)this._sourceCaches[G].clearTiles()},E=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!E)return this._styleColorTheme.lut=null,void w();const F=this._evaluateColorThemeData(E);this._loadColorTheme(F).then(()=>{this.fire(new o.C("colorthemeset")),w()}).catch(G=>{o.w(`Couldn't set color theme: ${G}`)})}setColorTheme(w){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=w,this._reloadColorTheme()}setImportColorTheme(w,E){const F=this.getFragmentStyle(w);F&&(F._styleColorTheme.colorThemeOverride=E,F._reloadColorTheme())}_getTransitionParameters(w){return{now:o.o.now(),transition:Object.assign(this.transition,w)}}updateDrapeFirstLayers(){if(!this.terrain)return;const w=[],E=[];for(const F of this._mergedOrder)this.isLayerDraped(this._mergedLayers[F])?w.push(F):E.push(F);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...w),this._drapedFirstOrder.push(...E)}_createTerrain(w,E){const F=this.terrain=new Jr(w,E,this.scope,this.options,this.map.getWorldview());E===1&&(this.stylesheet.terrain=w),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const G=this._getTransitionParameters({duration:0});F.updateTransitions(G)}_force3DLayerUpdate(){for(const w in this._layers){const E=this._layers[w];E.type==="fill-extrusion"&&this._updateLayer(E)}}_forceSymbolLayerUpdate(){for(const w in this._layers){const E=this._layers[w];E.type==="symbol"&&this._updateLayer(E)}}_validate(w,E,F,G,X={}){if(X&&X.validate===!1)return!1;const J=Object.assign({},this.serialize());return Sy(this,w.call(un,Object.assign({key:E,style:J,value:F,styleSpec:o.a8},G)))}_remove(){this._request&&(this._request.cancel(),this._request=null),this._spriteRequest&&(this._spriteRequest.cancel(),this._spriteRequest=null),o.dj.off("pluginStateChange",this._rtlTextPluginCallback);for(const w in this._mergedLayers)this._mergedLayers[w].setEventedParent(null);for(const w in this._mergedSourceCaches)this._mergedSourceCaches[w].clearTiles(),this._mergedSourceCaches[w].setEventedParent(null);this.imageManager.removeScope(this.scope),this.imageManager.imageAtlasCache.clear(),this.setEventedParent(null),delete this.fog,delete this.snow,delete this.rain,delete this.terrain,delete this.ambientLight,delete this.directionalLight,this.indoorManager.destroy(),this.isRootStyle()&&(this.imageManager.setEventedParent(null),this.imageManager.destroy(),this.modelManager.setEventedParent(null),this.modelManager.destroy(),this.dispatcher.remove())}clearSource(w){const E=this.getSourceCaches(w);for(const F of E)F.clearTiles()}clearSources(){for(const w in this._mergedSourceCaches)this._mergedSourceCaches[w].clearTiles()}clearLayers(){for(const w in this._mergedLayers){const E=this._mergedLayers[w];E._clear&&E._clear()}}reloadSource(w){const E=this.getSourceCaches(w);for(const F of E)F.resume(),F.reload()}reloadSources(){for(const w of this.getSources())w.reload&&w.reload()}reloadModels(){this.modelManager.reloadModels(""),this.forEachFragmentStyle(w=>{w.modelManager.reloadModels(w.scope)})}updateSources(w){let E;this.directionalLight&&(E=ky(this.directionalLight));const F=new Set,G=new Set,X=new Set;for(const J in this._mergedLayers){const de=this._mergedLayers[J];de.type==="building"?F.add(de.source):de.type==="raster"&&de.paint&&de.paint.get("raster-elevation-reference")==="ground"&&X.add(de.source),de.hasElevation()&&!G.has(de.source)&&G.add(de.source)}for(const J in this._mergedSourceCaches){const de=this._mergedSourceCaches[J],ye=G.has(de._source.id);de._isRasterElevatedOverTerrain=X.has(de._source.id),F.has(de._source.id)&&(de._source.reparseOverscaled=!1),de.update(w,void 0,void 0,E,ye)}}_generateCollisionBoxes(){for(const w in this._sourceCaches){const E=this._sourceCaches[w];E.resume(),E.reload()}}_handleLayerOrderChange(){this._requestFullLabelPlacement(),this.fire(new o.C("neworder"))}_requestFullLabelPlacement(){this.pauseablePlacement||(this.pauseablePlacement=new Sv),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(w,E,F,G,X){this.pauseablePlacement||(this.pauseablePlacement=new Sv);let J=!1,de=!1;const ye={},Ce={};for(const it of this._mergedOrder){const jt=this._mergedLayers[it];if(jt.type!=="symbol")continue;const wt=o.F(jt.source,jt.scope);let Bt=ye[wt];if(!Bt){const Ct=this.getLayerSourceCache(jt);if(!Ct)continue;const Ss=Ct.getRenderableIds(!0).map(rs=>Ct.getTileByID(rs));Ce[wt]=Ss.slice(),Bt=ye[wt]=Ss.sort((rs,_s)=>_s.tileID.overscaledZ-rs.tileID.overscaledZ||(rs.tileID.isLessThan(_s.tileID)?-1:1))}const Vt=this.crossTileSymbolIndex.addLayer(jt,Bt,w.center.lng,w.projection);J=J||Vt}this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder);const Le=!!(this.placement&&!w.equals(this.placement.transform)),Xe=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!X||this.placement.lastReplacementSourceUpdateTime!==X.updateTime)),Ke=Le||Xe||J,st=(Ke||this.pauseablePlacement.isStale())&&F===0,dt=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(o.o.now(),w.zoom)&&F!==0;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||st||dt)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(w,this._mergedOrder,E,F,G,this.placement,this.fog&&w.projection.supportsFog?this.fog.state:null,this._buildingIndex),this.map.painter)){const it=this.map.painter.maxFrontCutoffRawStart;if(it>0){const jt=180*w.pitch/Math.PI;if(jt>=15){const wt=Math.min(1,Math.max(0,(jt-15)/5)),Bt=wt*wt*(3-2*wt);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-Bt)+it*Bt}}}if(this.pauseablePlacement.isDone()?Ke&&F!==0&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(this._mergedOrder,this._mergedLayers,ye,Ce,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(o.o.now()),de=!0),J&&this.pauseablePlacement.setStale()),de||J){this._buildingIndex.onNewFrame(w.zoom);for(let it=0;itX===w.id)!==-1)return void this.fire(new o.B(new Error(`Import with id '${w.id}' already exists in the map's style.`)));if(!E)return F.push(w),this._loadImports([w],!0);const G=F.findIndex(({id:X})=>X===E);return G===-1&&this.fire(new o.B(new Error(`Import with id "${E}" does not exist on this map.`))),this.stylesheet.imports=F.slice(0,G).concat(w).concat(F.slice(G)),this._loadImports([w],!0,E)}updateImport(w,E){this._checkLoaded();const F=this.stylesheet.imports||[],G=this.getImportIndex(w);return G===-1?this:typeof E=="string"?(this.setImportUrl(w,E),this):(E.url&&E.url!==F[G].url&&this.setImportUrl(w,E.url),o.b6(E.config,F[G].config)||this.setImportConfig(w,E.config,E.data.schema),o.b6(E.data,F[G].data)||this.setImportData(w,E.data),this)}moveImport(w,E){this._checkLoaded();let F=this.stylesheet.imports||[];const G=this.getImportIndex(w);if(G===-1)return this;const X=this.getImportIndex(E);if(X===-1)return this;const J=F[G],de=this.fragments[G];return F=F.filter(({id:ye})=>ye!==w),this.fragments=this.fragments.filter(({id:ye})=>ye!==w),this.stylesheet.imports=F.slice(0,X).concat(J).concat(F.slice(X)),this.fragments=this.fragments.slice(0,X).concat(de).concat(this.fragments.slice(X)),this.mergeLayers(),this}setImportUrl(w,E){this._checkLoaded();const F=this.stylesheet.imports||[],G=this.getImportIndex(w);if(G===-1)return this;F[G].url=E;const X=this.fragments[G];return X.style=this._createFragmentStyle(F[G]),X.style.on("style.import.load",()=>this.mergeAll()),X.style.loadURL(E),this}setImportData(w,E){this._checkLoaded();const F=this.getImportIndex(w),G=this.stylesheet.imports||[];return F===-1?this:E?(this.fragments[F].style.setState(E),this._reloadImports(),this):(delete G[F].data,this.setImportUrl(w,G[F].url))}setImportConfig(w,E,F){this._checkLoaded();const G=this.getImportIndex(w),X=this.stylesheet.imports||[];if(G===-1)return this;E?X[G].config=E:delete X[G].config;const J=this.fragments[G];F&&J.style.stylesheet&&(J.style.stylesheet.schema=F);const de=J.style.stylesheet&&J.style.stylesheet.schema;return J.config=E,J.style.updateConfig(E,de),this.updateConfigDependencies(),this}removeImport(w){this._checkLoaded();const E=this.stylesheet.imports||[],F=this.getImportIndex(w);F!==-1&&(E.splice(F,1),this.fragments[F].style._remove(),this.fragments.splice(F,1),this._reloadImports())}getImportIndex(w){const E=(this.stylesheet.imports||[]).findIndex(F=>F.id===w);return E===-1&&this.fire(new o.B(new Error(`Import '${w}' does not exist in the map's style and cannot be updated.`))),E}getLayer(w){return this._mergedLayers[w]}getSources(){const w=[];for(const E in this._mergedOtherSourceCaches){const F=this._mergedOtherSourceCaches[E];F&&w.push(F.getSource())}return w}getSource(w,E){const F=this.getSourceCache(w,E);return F&&F.getSource()}getLayerSource(w){const E=this.getLayerSourceCache(w);return E&&E.getSource()}getSourceCache(w,E){const F=o.F(w,E);return this._mergedOtherSourceCaches[F]}getLayerSourceCache(w){const E=o.F(w.source,w.scope);return w.type==="symbol"?this._mergedSymbolSourceCaches[E]:w.type==="fill-extrusion"&&this._mergedFillExtrusionSourceCaches[E]||this._mergedOtherSourceCaches[E]}getSourceCaches(w){if(w==null)return Object.values(this._mergedSourceCaches);const E=[];return this._mergedOtherSourceCaches[w]&&E.push(this._mergedOtherSourceCaches[w]),this._mergedSymbolSourceCaches[w]&&E.push(this._mergedSymbolSourceCaches[w]),this._mergedFillExtrusionSourceCaches[w]&&E.push(this._mergedFillExtrusionSourceCaches[w]),E}updateSourceCaches(){const w=this._changes.getUpdatedSourceCaches();for(const E in w){const F=w[E];F==="reload"?this.reloadSource(E):F==="clear"&&this.clearSource(E)}}updateLayers(w){const E=this._changes.getUpdatedPaintProperties();for(const F of E){const G=this.getLayer(F);G&&G.updateTransitions(w)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(w){this.stylesheet.glyphs=w,this.glyphManager.setURL(w)}getImages(w,E,F){this.imageManager.getImages(E.images,E.scope,F),this._updateTilesForChangedImages();const G=J=>{if(J){const de=E.images.map(ye=>o.I.toString(ye));J.setDependencies(E.tileID.key,E.type,de)}},X=o.F(E.source,E.scope);G(this._mergedOtherSourceCaches[X]),G(this._mergedSymbolSourceCaches[X]),E.images.some(J=>J.iconsetId)&&this.fire(new o.C("data",{dataType:"style"}))}rasterizeImages(w,E,F){this.imageManager.rasterizeImages(E,F)}checkAtlasCache(w,E,F){const G=this.imageManager.imageAtlasCache.findCachedAtlas(E.descriptor);F(null,G&&G.contentDescriptor?{iconPositions:G.iconPositions,patternPositions:G.patternPositions,sourceHash:G.contentDescriptor.hash}:null)}getGlyphs(w,E,F){this.glyphManager.getGlyphs(E.stacks,F)}getOwnSourceCache(w){return this._otherSourceCaches[w]}getOwnLayerSourceCache(w){return w.type==="symbol"?this._symbolSourceCaches[w.source]:w.type==="fill-extrusion"&&this._fillExtrusionSourceCaches[w.source]||this._otherSourceCaches[w.source]}getOwnSourceCaches(w){const E=[];return this._otherSourceCaches[w]&&E.push(this._otherSourceCaches[w]),this._symbolSourceCaches[w]&&E.push(this._symbolSourceCaches[w]),this._fillExtrusionSourceCaches[w]&&E.push(this._fillExtrusionSourceCaches[w]),E}_isSourceCacheLoaded(w){const E=this.getOwnSourceCaches(w);return E.length===0?(this.fire(new o.B(new Error(`There is no source with ID '${w}'`))),!1):E.every(F=>F.loaded())}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}isLayerClipped(w,E){if(!this._clipLayerPresent&&w.type!=="fill-extrusion"&&w.type!=="building")return!1;const F=w.type==="fill-extrusion"&&(w.sourceLayer==="building"||w.sourceLayer==="procedural_buildings"),G=w.type==="building";if(w.is3D(!!this.terrain)){if(F||G||E&&E.type==="batched-model"||w.type==="model")return!0}else if(w.type==="symbol")return!0;return!1}_clearWorkerCaches(){this.dispatcher.broadcast("clearCaches")}getBOMObject(){}destroy(){this._clearWorkerCaches(),this.imageManager.imageAtlasCache.clear(),this.fragments.forEach(w=>{w.style._remove()}),this.terrainSetForDrapingOnly()&&(delete this.terrain,delete this.stylesheet.terrain)}}eh.getSourceType=function(D){return il[D]},eh.setSourceType=function(D,w){il[D]=w},eh.registerForPluginStateChange=o.dk;var Cy=` #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`,Mj=` #ifdef DUAL_SOURCE_BLENDING layout(location=0,index=0) out vec4 glFragColor;layout(location=0,index=1) out vec4 glFragColorSrc1; #elif defined(FLOAT_RENDER_TARGET) layout(location=0) out highp vec4 glFragColor; #else layout(location=0) out vec4 glFragColor; #endif #ifdef USE_MRT1 layout(location=1) out vec4 out_Target1; #endif highp float unpack_depth(highp vec4 rgba_depth) {const highp vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(rgba_depth,bit_shift)*2.0-1.0;}highp vec4 pack_depth(highp float ndc_z) {highp float depth=ndc_z*0.5+0.5;const highp vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const highp vec4 bit_mask =vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);highp vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;} #ifdef INDICATOR_CUTOUT uniform vec3 u_indicator_cutout_centers;uniform vec4 u_indicator_cutout_params; #endif const float DITHER_THRESHOLDS[16]=float[16]( 1.0/17.0, 9.0/17.0, 3.0/17.0,11.0/17.0,13.0/17.0, 5.0/17.0,15.0/17.0, 7.0/17.0,4.0/17.0,12.0/17.0, 2.0/17.0,10.0/17.0,16.0/17.0, 8.0/17.0,14.0/17.0, 6.0/17.0 );vec4 applyCutout(vec4 color,float height) { #ifdef INDICATOR_CUTOUT float verticalFadeRange=u_indicator_cutout_centers.z*0.25;float holeMinOpacity=mix(1.0,u_indicator_cutout_params.x,smoothstep(u_indicator_cutout_centers.z,u_indicator_cutout_centers.z+verticalFadeRange,height));float holeRadius=max(u_indicator_cutout_params.y,0.0);float holeAspectRatio=u_indicator_cutout_params.z;float fadeStart=u_indicator_cutout_params.w;float distA=distance(vec2(gl_FragCoord.x,gl_FragCoord.y*holeAspectRatio),vec2(u_indicator_cutout_centers[0],u_indicator_cutout_centers[1]*holeAspectRatio));return color*min(smoothstep(fadeStart,holeRadius,distA)+holeMinOpacity,1.0); #else return color; #endif }float cutoutGroundRoofOpacity(vec4 groundRoof) { #ifdef INDICATOR_CUTOUT float fadeStartX=u_indicator_cutout_params.w;float holeRadius=u_indicator_cutout_params.y;float holeMinOpacity=mix(u_indicator_cutout_params.x,1.0,smoothstep(u_indicator_cutout_params.z,u_indicator_cutout_centers.z,groundRoof.y));float distX=abs(u_indicator_cutout_centers.x-groundRoof.x);float roofOpacity=mix(holeMinOpacity,1.0,smoothstep(fadeStartX,holeRadius,u_indicator_cutout_centers.y-groundRoof.w));float groundOpacity=min(smoothstep(fadeStartX,holeRadius,distX)+holeMinOpacity,1.0);return max(roofOpacity,groundOpacity); #else return 1.0; #endif } #ifdef DEBUG_WIREFRAME #define HANDLE_WIREFRAME_DEBUG \\ glFragColor=vec4(0.7,0.0,0.0,0.7); \\ gl_FragDepth=gl_FragCoord.z-0.0001; #else #define HANDLE_WIREFRAME_DEBUG #endif #ifdef RENDER_CUTOFF uniform highp vec4 u_cutoff_params;in float v_cutoff_opacity; #endif vec4 textureLodCustom(sampler2D image,highp vec2 pos,highp vec2 lod_coord) {highp vec2 size=vec2(textureSize(image,0));highp vec2 dx=dFdx(lod_coord.xy*size);highp vec2 dy=dFdy(lod_coord.xy*size);highp float delta_max_sqr=max(dot(dx,dx),dot(dy,dy));highp float lod=0.5*log2(delta_max_sqr);return textureLod(image,pos,lod);}vec4 applyLUT(highp sampler3D lut,vec4 col) {vec3 size=vec3(textureSize(lut,0));vec3 uvw=(col.rbg*float(size-1.0)+0.5)/size;return vec4(texture(lut,uvw).rgb*col.a,col.a);}vec3 applyLUT(highp sampler3D lut,vec3 col) {return applyLUT(lut,vec4(col,1.0)).rgb;}`,Ay=` #define EXTENT 8192.0 #define RAD_TO_DEG 180.0/PI #define DEG_TO_RAD PI/180.0 #define GLOBE_RADIUS EXTENT/PI/2.0 float wrap(float n,float min,float max) {float d=max-min;float w=mod(mod(n-min,d)+d,d)+min;return (w==min) ? max : w;} #ifdef PROJECTION_GLOBE_VIEW vec3 mercator_tile_position(mat4 matrix,vec2 tile_anchor,vec3 tile_id,vec2 mercator_center) { #ifndef PROJECTED_POS_ON_VIEWPORT float tiles=tile_id.z;vec2 mercator=(tile_anchor/EXTENT+tile_id.xy)/tiles;mercator-=mercator_center;mercator.x=wrap(mercator.x,-0.5,0.5);vec4 mercator_tile=vec4(mercator.xy*EXTENT,EXTENT/(2.0*PI),1.0);mercator_tile=matrix*mercator_tile;return mercator_tile.xyz; #else return vec3(0.0); #endif }vec3 mix_globe_mercator(vec3 globe,vec3 mercator,float t) {return mix(globe,mercator,t);}mat3 globe_mercator_surface_vectors(vec3 pos_normal,vec3 up_dir,float zoom_transition) {vec3 normal=zoom_transition==0.0 ? pos_normal : normalize(mix(pos_normal,up_dir,zoom_transition));vec3 xAxis=normalize(vec3(normal.z,0.0,-normal.x));vec3 yAxis=normalize(cross(normal,xAxis));return mat3(xAxis,yAxis,normal);} #endif vec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec4 decode_color(const vec2 encodedColor) {return vec4( unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0 );}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const vec2 units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (units_to_pixels*pos+offset)/pattern_size;}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {return get_pattern_pos(pixel_coord_upper,pixel_coord_lower,pattern_size,vec2(tile_units_to_pixels),pos);}float mercatorXfromLng(float lng) {return (180.0+lng)/360.0;}float mercatorYfromLat(float lat) {return (180.0-(RAD_TO_DEG*log(tan(PI/4.0+lat/2.0*DEG_TO_RAD))))/360.0;}vec3 latLngToECEF(vec2 latLng) {latLng=DEG_TO_RAD*latLng;float cosLat=cos(latLng[0]);float sinLat=sin(latLng[0]);float cosLng=cos(latLng[1]);float sinLng=sin(latLng[1]);float sx=cosLat*sinLng*GLOBE_RADIUS;float sy=-sinLat*GLOBE_RADIUS;float sz=cosLat*cosLng*GLOBE_RADIUS;return vec3(sx,sy,sz);} #ifdef RENDER_CUTOFF uniform vec4 u_cutoff_params;out float v_cutoff_opacity; #endif const vec4 AWAY=vec4(-1000.0,-1000.0,-1000.0,1);const float skirtOffset=24575.0;vec3 decomposeToPosAndSkirt(ivec2 posWithComposedSkirt) {float skirt=float(float(posWithComposedSkirt.x) >=skirtOffset);vec2 pos=vec2(posWithComposedSkirt)-vec2(skirt*skirtOffset,0.0);return vec3(pos,skirt);} #ifndef HAS_SHADER_STORAGE_BLOCK_material_buffer #define GET_ATTRIBUTE_float(attrib,matInfo,attrib_id) attrib #define GET_ATTRIBUTE_vec4(attrib,matInfo,attrib_id) attrib #define GET_ATTRIBUTE_vec2(attrib,matInfo,attrib_id) attrib #define DECLARE_MATERIAL_TABLE_INFO #endif`,H_="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;}",LN=` #define ELEVATION_SCALE 7.0 #define ELEVATION_OFFSET 450.0 #ifdef PROJECTION_GLOBE_VIEW uniform vec3 u_tile_tl_up;uniform vec3 u_tile_tr_up;uniform vec3 u_tile_br_up;uniform vec3 u_tile_bl_up;uniform float u_tile_up_scale;vec3 elevationVector(vec2 pos) {vec2 uv=pos/EXTENT;vec3 up=normalize(mix( mix(u_tile_tl_up,u_tile_tr_up,uv.xxx),mix(u_tile_bl_up,u_tile_br_up,uv.xxx),uv.yyy));return up*u_tile_up_scale;} #else vec3 elevationVector(vec2 pos) { return vec3(0,0,1); } #endif #ifdef TERRAIN uniform highp sampler2D u_dem;uniform highp sampler2D u_dem_prev;uniform vec2 u_dem_tl;uniform vec2 u_dem_tl_prev;uniform float u_dem_scale;uniform float u_dem_scale_prev;uniform float u_dem_size;uniform float u_dem_lerp;uniform float u_exaggeration;uniform float u_meter_to_dem;uniform mat4 u_label_plane_matrix_inv;vec4 tileUvToDemSample(vec2 uv,float dem_size,float dem_scale,vec2 dem_tl) {vec2 pos=dem_size*(uv*dem_scale+dem_tl)+1.0;vec2 f=fract(pos);return vec4((pos-f+0.5)/(dem_size+2.0),f);}float currentElevation(vec2 apos) { #ifdef TERRAIN_DEM_FLOAT_FORMAT vec2 pos=(u_dem_size*(apos/8192.0*u_dem_scale+u_dem_tl)+1.5)/(u_dem_size+2.0);return u_exaggeration*texture(u_dem,pos).r; #else float dd=1.0/(u_dem_size+2.0);vec4 r=tileUvToDemSample(apos/8192.0,u_dem_size,u_dem_scale,u_dem_tl);vec2 pos=r.xy;vec2 f=r.zw;float tl=texture(u_dem,pos).r;float tr=texture(u_dem,pos+vec2(dd,0)).r;float bl=texture(u_dem,pos+vec2(0,dd)).r;float br=texture(u_dem,pos+vec2(dd,dd)).r;return u_exaggeration*mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y); #endif }float prevElevation(vec2 apos) { #ifdef TERRAIN_DEM_FLOAT_FORMAT vec2 pos=(u_dem_size*(apos/8192.0*u_dem_scale_prev+u_dem_tl_prev)+1.5)/(u_dem_size+2.0);return u_exaggeration*texture(u_dem_prev,pos).r; #else float dd=1.0/(u_dem_size+2.0);vec4 r=tileUvToDemSample(apos/8192.0,u_dem_size,u_dem_scale_prev,u_dem_tl_prev);vec2 pos=r.xy;vec2 f=r.zw;float tl=texture(u_dem_prev,pos).r;float tr=texture(u_dem_prev,pos+vec2(dd,0)).r;float bl=texture(u_dem_prev,pos+vec2(0,dd)).r;float br=texture(u_dem_prev,pos+vec2(dd,dd)).r;return u_exaggeration*mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y); #endif } #ifdef TERRAIN_VERTEX_MORPHING float elevation(vec2 apos) { #ifdef ZERO_EXAGGERATION return 0.0; #endif float nextElevation=currentElevation(apos);float prevElevation=prevElevation(apos);return mix(prevElevation,nextElevation,u_dem_lerp);} #else float elevation(vec2 apos) { #ifdef ZERO_EXAGGERATION return 0.0; #endif return currentElevation(apos);} #endif vec4 fourSample(vec2 pos,vec2 off) {float tl=texture(u_dem,pos).r;float tr=texture(u_dem,pos+vec2(off.x,0.0)).r;float bl=texture(u_dem,pos+vec2(0.0,off.y)).r;float br=texture(u_dem,pos+off).r;return vec4(tl,tr,bl,br);}float flatElevation(vec2 pack) {vec2 apos=floor(pack/8.0);vec2 span=10.0*(pack-apos*8.0);vec2 uvTex=(apos-vec2(1.0,1.0))/8190.0;float size=u_dem_size+2.0;float dd=1.0/size;vec2 pos=u_dem_size*(uvTex*u_dem_scale+u_dem_tl)+1.0;vec2 f=fract(pos);pos=(pos-f+0.5)*dd;vec4 h=fourSample(pos,vec2(dd));float z=mix(mix(h.x,h.y,f.x),mix(h.z,h.w,f.x),f.y);vec2 w=floor(0.5*(span*u_meter_to_dem-1.0));vec2 d=dd*w;h=fourSample(pos-d,2.0*d+vec2(dd));vec4 diff=abs(h.xzxy-h.ywzw);vec2 slope=min(vec2(0.25),u_meter_to_dem*0.5*(diff.xz+diff.yw)/(2.0*w+vec2(1.0)));vec2 fix=slope*span;float base=z+max(fix.x,fix.y);return u_exaggeration*base;}float elevationFromUint16(float word) {return u_exaggeration*(word/ELEVATION_SCALE-ELEVATION_OFFSET);} #else float elevation(vec2 pos) { return 0.0; } #endif #ifdef DEPTH_OCCLUSION uniform highp sampler2D u_depth;uniform highp vec2 u_depth_size_inv;uniform highp vec2 u_depth_range_unpack;uniform highp float u_occluder_half_size;uniform highp float u_occlusion_depth_offset; #ifdef DEPTH_D24 float unpack_depth(float depth) {return depth*u_depth_range_unpack.x+u_depth_range_unpack.y;}vec4 unpack_depth4(vec4 depth) {return depth*u_depth_range_unpack.x+vec4(u_depth_range_unpack.y);} #else highp float unpack_depth_rgba(vec4 rgba_depth) {const highp vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(rgba_depth,bit_shift)*2.0-1.0;} #endif bool isOccluded(vec4 frag) {vec3 coord=frag.xyz/frag.w; #ifdef CLIP_ZERO_TO_ONE coord.z=-1.0+2.0*coord.z; #endif #ifdef DEPTH_D24 float depth=unpack_depth(texture(u_depth,(coord.xy+1.0)*0.5).r); #else float depth=unpack_depth_rgba(texture(u_depth,(coord.xy+1.0)*0.5)); #endif return coord.z+u_occlusion_depth_offset > depth;}highp vec4 getCornerDepths(vec2 coord) {highp vec3 df=vec3(u_occluder_half_size*u_depth_size_inv,0.0);highp vec2 uv=0.5*coord.xy+0.5; #ifdef DEPTH_D24 highp vec4 depth=vec4( texture(u_depth,uv-df.xz).r,texture(u_depth,uv+df.xz).r,texture(u_depth,uv-df.zy).r,texture(u_depth,uv+df.zy).r );depth=unpack_depth4(depth); #else highp vec4 depth=vec4( unpack_depth_rgba(texture(u_depth,uv-df.xz)),unpack_depth_rgba(texture(u_depth,uv+df.xz)),unpack_depth_rgba(texture(u_depth,uv-df.zy)),unpack_depth_rgba(texture(u_depth,uv+df.zy)) ); #endif return depth;}highp float occlusionFadeMultiSample(vec4 frag) {highp vec3 coord=frag.xyz/frag.w;highp vec2 uv=0.5*coord.xy+0.5; #ifdef CLIP_ZERO_TO_ONE coord.z=-1.0+2.0*coord.z; #endif int NX=3;int NY=4;highp vec2 df=u_occluder_half_size*u_depth_size_inv;highp vec2 oneStep=2.0*u_occluder_half_size*u_depth_size_inv/vec2(NX-1,NY-1);highp float res=0.0;for (int y=0; y < NY;++y) {for (int x=0; x < NX;++x) { #ifdef DEPTH_D24 highp float depth=unpack_depth(texture(u_depth,uv-df+vec2(float(x)*oneStep.x,float(y)*oneStep.y)).r); #else highp float depth=unpack_depth_rgba(texture(u_depth,uv-df+vec2(float(x)*oneStep.x,float(y)*oneStep.y))); #endif res+=1.0-clamp(300.0*(coord.z+u_occlusion_depth_offset-depth),0.0,1.0);}}res=clamp(2.0*res/float(NX*NY)-0.5,0.0,1.0);return res;}highp float occlusionFade(vec4 frag) {highp vec3 coord=frag.xyz/frag.w; #ifdef CLIP_ZERO_TO_ONE coord.z=-1.0+2.0*coord.z; #endif highp vec4 depth=getCornerDepths(coord.xy);return dot(vec4(0.25),vec4(1.0)-clamp(300.0*(vec4(coord.z+u_occlusion_depth_offset)-depth),0.0,1.0));} #else bool isOccluded(vec4 frag) { return false; }highp float occlusionFade(vec4 frag) { return 1.0; }highp float occlusionFadeMultiSample(vec4 frag) { return 1.0; } #endif`,IN=`#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`,Tb=`#ifdef FOG uniform mediump vec4 u_fog_color;uniform mediump vec2 u_fog_range;uniform mediump float u_fog_horizon_blend;uniform mediump vec2 u_fog_vertical_limit;uniform mediump float u_fog_temporal_offset;in vec3 v_fog_pos;uniform highp vec3 u_frustum_tl;uniform highp vec3 u_frustum_tr;uniform highp vec3 u_frustum_br;uniform highp vec3 u_frustum_bl;uniform highp vec3 u_globe_pos;uniform highp float u_globe_radius;uniform highp vec2 u_viewport;uniform float u_globe_transition;uniform int u_is_globe;float fog_range(float depth) {return (depth-u_fog_range[0])/(u_fog_range[1]-u_fog_range[0]);}float fog_horizon_blending(vec3 camera_dir) {float t=max(0.0,camera_dir.z/u_fog_horizon_blend);return u_fog_color.a*exp(-3.0*t*t);}float fog_opacity(float t) {const float decay=6.0;float falloff=1.0-min(1.0,exp(-decay*t));falloff*=falloff*falloff;return u_fog_color.a*min(1.0,1.00747*falloff);}float globe_glow_progress() {highp vec2 uv=gl_FragCoord.xy/u_viewport; #ifdef FLIP_Y uv.y=1.0-uv.y; #endif highp vec3 ray_dir=mix( mix(u_frustum_tl,u_frustum_tr,uv.x),mix(u_frustum_bl,u_frustum_br,uv.x),1.0-uv.y);highp vec3 dir=normalize(ray_dir);highp vec3 closest_point=dot(u_globe_pos,dir)*dir;highp float sdf=length(closest_point-u_globe_pos)/u_globe_radius;return sdf+PI*0.5;}float fog_opacity(vec3 pos) {float depth=length(pos);return fog_opacity(fog_range(depth));}vec3 fog_apply(vec3 color,vec3 pos,float opacity_limit) {float depth=length(pos);float opacity;if (u_is_globe==1) {float glow_progress=globe_glow_progress();float t=mix(glow_progress,depth,u_globe_transition);opacity=fog_opacity(fog_range(t));} else {opacity=fog_opacity(fog_range(depth));opacity*=fog_horizon_blending(pos/depth);}return mix(color,u_fog_color.rgb,min(opacity,opacity_limit));}vec3 fog_apply(vec3 color,vec3 pos) {return fog_apply(color,pos,1.0);}vec4 fog_apply_from_vert(vec4 color,float fog_opac) {float alpha=EPSILON+color.a;color.rgb=mix(color.rgb/alpha,u_fog_color.rgb,fog_opac)*alpha;return color;}vec3 fog_apply_sky_gradient(vec3 camera_ray,vec3 sky_color) {float horizon_blend=fog_horizon_blending(normalize(camera_ray));return mix(sky_color,u_fog_color.rgb,horizon_blend);}vec4 fog_apply_premultiplied(vec4 color,vec3 pos) {float alpha=EPSILON+color.a;color.rgb=fog_apply(color.rgb/alpha,pos)*alpha;return color;}vec4 fog_apply_premultiplied(vec4 color,vec3 pos,float heightMeters) {float verticalProgress=(u_fog_vertical_limit.x > 0.0 || u_fog_vertical_limit.y > 0.0) ? smoothstep(u_fog_vertical_limit.x,u_fog_vertical_limit.y,heightMeters) : 0.0;float opacityLimit=1.0-smoothstep(0.9,1.0,fog_opacity(pos));return mix(fog_apply_premultiplied(color,pos),color,min(verticalProgress,opacityLimit));}vec3 fog_dither(vec3 color) {return color;}vec4 fog_dither(vec4 color) {return vec4(fog_dither(color.rgb),color.a);} #endif`,Mb=`#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`,RN=`#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;}`,G_=`#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`,Xp=`#ifdef RENDER_SHADOWS precision highp sampler2DShadow;uniform sampler2DShadow u_shadowmap_0;uniform sampler2DShadow u_shadowmap_1;uniform float u_shadow_intensity;uniform float u_shadow_map_resolution;uniform float u_shadow_texel_size;uniform highp vec3 u_shadow_normal_offset;uniform vec2 u_fade_range;uniform mediump vec3 u_shadow_direction;uniform highp vec3 u_shadow_bias;float shadow_sample(sampler2DShadow shadowmap,highp vec3 pos,highp float bias) { #ifdef CLIP_ZERO_TO_ONE highp vec3 coord=vec3(pos.xy*0.5+0.5,pos.z-bias); #else highp vec3 coord=vec3(pos.xy*0.5+0.5,pos.z*0.5+0.5-bias); #endif return texture(shadowmap,coord);}float shadow_occlusion(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth,highp float bias) {light_view_pos0.xyz/=light_view_pos0.w; #ifdef SHADOWS_SINGLE_CASCADE vec2 abs_bounds=abs(light_view_pos0.xy);if (abs_bounds.x >=1.0 || abs_bounds.y >=1.0) {return 0.0;}return shadow_sample(u_shadowmap_0,light_view_pos0.xyz,bias); #else light_view_pos1.xyz/=light_view_pos1.w;vec4 abs_bounds=abs(vec4(light_view_pos0.xy,light_view_pos1.xy));if (abs_bounds.x < 1.0 && abs_bounds.y < 1.0) {return shadow_sample(u_shadowmap_0,light_view_pos0.xyz,bias);}if (abs_bounds.z >=1.0 || abs_bounds.w >=1.0) {return 0.0;}float occlusion1=shadow_sample(u_shadowmap_1,light_view_pos1.xyz,bias);return clamp(mix(occlusion1,0.0,smoothstep(u_fade_range.x,u_fade_range.y,view_depth)),0.0,1.0); #endif }highp float calculate_shadow_bias(float NDotL) { #ifdef NORMAL_OFFSET return 0.5*u_shadow_bias.x; #else return 0.5*(u_shadow_bias.x+clamp(u_shadow_bias.y*tan(acos(NDotL)),0.0,u_shadow_bias.z)); #endif }float shadowed_light_factor_normal(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float NDotL=dot(N,u_shadow_direction);float bias=calculate_shadow_bias(NDotL);float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}float shadowed_light_factor_normal_opacity(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth,float shadow_opacity) {float NDotL=dot(N,u_shadow_direction);float bias=calculate_shadow_bias(NDotL);float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias)*shadow_opacity;return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}float shadowed_light_factor_normal_unbiased(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float NDotL=dot(N,u_shadow_direction);float bias=0.0;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}highp vec2 compute_receiver_plane_depth_bias(highp vec3 pos_dx,highp vec3 pos_dy) {highp vec2 biasUV=vec2( pos_dy.y*pos_dx.z-pos_dx.y*pos_dy.z,pos_dx.x*pos_dy.z-pos_dy.x*pos_dx.z);biasUV*=1.0/((pos_dx.x*pos_dy.y)-(pos_dx.y*pos_dy.x));return biasUV;}float shadowed_light_factor_plane_bias(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {highp vec3 light_view_pos0_xyz=light_view_pos0.xyz/light_view_pos0.w*0.5+0.5;highp vec3 light_view_pos0_ddx=dFdx(light_view_pos0_xyz);highp vec3 light_view_pos0_ddy=dFdy(light_view_pos0_xyz);highp vec2 plane_depth_bias=compute_receiver_plane_depth_bias(light_view_pos0_ddx,light_view_pos0_ddy);highp float bias=dot(vec2(u_shadow_texel_size,u_shadow_texel_size),plane_depth_bias)+0.0001;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return 1.0-(u_shadow_intensity*occlusion);}float shadowed_light_factor(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float bias=0.0;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return 1.0-(u_shadow_intensity*occlusion);}float shadow_occlusion(float ndotl,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float bias=calculate_shadow_bias(ndotl);return shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);} #endif`;const nm=/#include\s+"([^"]+)"/g,dr=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,Pb=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,Lb=new Set(["ifdef","ifndef","elif","if","defined"]),_1=new Set;A0(Cy,_1),A0(Ay,_1),A0(Mj,_1);const Rf={"_prelude_fog.vertex.glsl":IN,"_prelude_terrain.vertex.glsl":LN,"_prelude_shadow.vertex.glsl":G_,"_prelude_material_table.vertex.glsl":`#ifdef HAS_SHADER_STORAGE_BLOCK_material_buffer #define MATERIAL_TABLE_DEBUG 0 uniform int u_material_offset;uniform int u_vertex_offset;layout(std140,binding=0)readonly buffer material_buffer{uvec4 material_data[];};struct MaterialInfo{uint dataOffset; #if MATERIAL_TABLE_DEBUG vec4 colorDebug; #endif };uint read_buf_no_offset(uint iDword) {return material_data[iDword/4u][iDword % 4u];}uint read_buf(uint iDword) {iDword+=uint(u_material_offset/4);return read_buf_no_offset(iDword);}float read_buf_float(uint iDword){return uintBitsToFloat(read_buf(iDword));}uint read_buf_uint8(uint iDword,uint iUint8){uint dwordOffset=iDword+(iUint8/4u);uint byteOffset=iUint8 & 3u;uint bitOffset=8u*byteOffset;uint mask=0xffu << bitOffset;uint dwordVal=read_buf(dwordOffset);return (dwordVal & mask) >> bitOffset;}uint read_buf_uint16(uint iDword,uint iUint16){uint dwordOffset=iDword+(iUint16 >> 1u);uint bitOffset=(iUint16 & 1u)*16u;uint mask=0xffffu << bitOffset;uint dwordVal=read_buf(dwordOffset);return (dwordVal & mask) >> bitOffset;}uint nrDwordsForVertexIdEntries(uint nrMaterialLookupEntries) {return nrMaterialLookupEntries;}uint nrDwordsForMaterialIdEntries(uint nrMaterialLookupEntries) {return (nrMaterialLookupEntries*2u+3u)/4u;}uint findRangeBinarySearch(uint vertexId,uint numRanges,uint dwordOffset) {uint left=0u;uint right=numRanges-1u;for (uint i=0u; i < 16u; i++) { if (left > right) {break;}uint mid=(left+right)/2u;uint start=read_buf(dwordOffset+mid);uint nextStart=(mid+1u < numRanges) ? read_buf(dwordOffset+mid+1u) : 0xffffffffu;if (vertexId >=start && vertexId < nextStart) {return mid;} else if (vertexId < start) {if (mid==0u) {break;}right=mid-1u;} else {left=mid+1u;}}return 0u; }uint readVertexId(uint dwordOffset,uint iMaterialLookupEntry) {return read_buf(dwordOffset+iMaterialLookupEntry);}uint findRange(uint vertexId,uint numRanges,uint dwordOffset) {uint iRange;if(numRanges <=64u){uint vertexBegin;for(iRange=0u; iRange < numRanges;++iRange) {vertexBegin=readVertexId(dwordOffset,iRange);if(vertexBegin > vertexId) {break;}}iRange=iRange==0u? 0u : iRange-1u;} else { iRange=findRangeBinarySearch(vertexId,numRanges,dwordOffset);}return iRange;}MaterialInfo read_material_info(uint vertex_id) {MaterialInfo info; #if MATERIAL_TABLE_DEBUG const vec4 red=vec4(1.0,0.0,0.0,1.0);const vec4 orange=vec4(1.0,0.5,0.0,1.0);const vec4 yellow=vec4(1.0,1.0,0.0,1.0);const vec4 green=vec4(0.0,1.0,0.0,1.0);const vec4 indigo=vec4(0.294,0.0,0.510,1.0);const vec4 blue=vec4(0.0,0.0,1.0,1.0);const vec4 purple=vec4(0.5,0.0,0.5,1.0);const vec4 pink=vec4(1.0,0.0,1.0,1.0);info.colorDebug=green; #endif uint offset=0u; #if MATERIAL_TABLE_DEBUG bool keepFinding=true;uint magic=read_buf(offset);if(magic !=0xCAFEBABEu) {info.colorDebug=red;keepFinding=false;return info;} #endif offset++; #if MATERIAL_TABLE_DEBUG uint nrMaterials=read_buf(offset);uint nrVertices=read_buf(offset+1u);if(keepFinding && vertex_id >=nrVertices) {info.colorDebug=red;keepFinding=false;} #endif offset+=2u;uint nrMaterialLookupEntries=read_buf(offset++);uint perMaterialEntrySizeDwords=read_buf(offset++); #if MATERIAL_TABLE_DEBUG if(keepFinding && perMaterialEntrySizeDwords !=1u) {info.colorDebug=red;keepFinding=false;} #endif uint iMaterialLookup=findRange(vertex_id,nrMaterialLookupEntries,offset); #if MATERIAL_TABLE_DEBUG if(keepFinding) {uint vertexBeginCheck=readVertexId(offset,iMaterialLookup);if(vertexBeginCheck > vertex_id) {info.colorDebug=red;keepFinding=false;}if(iMaterialLookup < nrMaterialLookupEntries-1u) {uint vertexEndCheck=readVertexId(offset,iMaterialLookup+1u);if(vertexEndCheck <=vertex_id) {info.colorDebug=red;keepFinding=false;}}} #endif offset+=nrDwordsForVertexIdEntries(nrMaterialLookupEntries);uint materialId=iMaterialLookup; #if MATERIAL_TABLE_DEBUG if(keepFinding) {if(materialId >=nrMaterialLookupEntries) {info.colorDebug=red;}} #endif info.dataOffset=offset+materialId*perMaterialEntrySizeDwords;return info;}uint get_data_location(const MaterialInfo matInfo,uint attribOffsetBytes) {uint attribFieldOffsetDwords=attribOffsetBytes/4u;return matInfo.dataOffset+attribFieldOffsetDwords;}vec4 read_material_vec4(const MaterialInfo matInfo,uint attribOffsetBytes){uint loc=get_data_location(matInfo,attribOffsetBytes);return vec4(read_buf_float(loc),read_buf_float(loc+1u),read_buf_float(loc+2u),read_buf_float(loc+3u));}vec2 read_material_vec2(const MaterialInfo matInfo,uint attribOffsetBytes){uint loc=get_data_location(matInfo,attribOffsetBytes);return vec2(read_buf_float(loc),read_buf_float(loc+1u));}float read_material_float(const MaterialInfo matInfo,uint attribOffsetBytes){uint loc=get_data_location(matInfo,attribOffsetBytes);return read_buf_float(loc);} #define GET_ATTRIBUTE_float(attrib,matInfo,attrib_offset) read_material_float(matInfo,attrib_offset) #define GET_ATTRIBUTE_vec4(attrib,matInfo,attrib_offset) read_material_vec4(matInfo,attrib_offset) #define GET_ATTRIBUTE_vec2(attrib,matInfo,attrib_offset) read_material_vec2(matInfo,attrib_offset) #define DECLARE_MATERIAL_TABLE_INFO MaterialInfo materialInfo=read_material_info(uint(gl_VertexID)); #define DECLARE_MATERIAL_TABLE_INFO_DEBUG(dbgColor) MaterialInfo materialInfo=read_material_info(uint(gl_VertexID)); dbgColor=materialInfo.colorDebug; #endif`,"_prelude_fog.fragment.glsl":Tb,"_prelude_shadow.fragment.glsl":Xp,"_prelude_lighting.glsl":` #ifdef LIGHTING_3D_MODE uniform mediump vec3 u_lighting_ambient_color;uniform mediump vec3 u_lighting_directional_dir;uniform mediump vec3 u_lighting_directional_color;uniform mediump vec3 u_ground_radiance;float calculate_ambient_directional_factor(vec3 normal) {float NdotL=dot(normal,u_lighting_directional_dir);const float factor_reduction_max=0.3;float dir_luminance=dot(u_lighting_directional_color,vec3(0.2126,0.7152,0.0722));float directional_factor_min=1.0-factor_reduction_max*min(dir_luminance,1.0);float ambient_directional_factor=mix(directional_factor_min,1.0,min((NdotL+1.0),1.0));const float vertical_factor_min=0.92;float vertical_factor=mix(vertical_factor_min,1.0,normal.z*0.5+0.5);return vertical_factor*ambient_directional_factor;}vec3 linearProduct(vec3 srgbIn,vec3 k) {return srgbIn*pow(k,vec3(1./2.2));}vec3 apply_lighting(vec3 color,vec3 normal,float dir_factor) {float ambient_directional_factor=calculate_ambient_directional_factor(normal);vec3 ambient_contrib=ambient_directional_factor*u_lighting_ambient_color;vec3 directional_contrib=u_lighting_directional_color*dir_factor;return linearProduct(color,ambient_contrib+directional_contrib);}vec4 apply_lighting(vec4 color,vec3 normal,float dir_factor) {return vec4(apply_lighting(color.rgb,normal,dir_factor),color.a);}vec3 apply_lighting(vec3 color,vec3 normal) {float dir_factor=max(dot(normal,u_lighting_directional_dir),0.0);return apply_lighting(color.rgb,normal,dir_factor);}vec4 apply_lighting(vec4 color,vec3 normal) {float dir_factor=max(dot(normal,u_lighting_directional_dir),0.0);return vec4(apply_lighting(color.rgb,normal,dir_factor),color.a);}vec3 apply_lighting_ground(vec3 color) {return color*u_ground_radiance;}vec4 apply_lighting_ground(vec4 color) {return vec4(apply_lighting_ground(color.rgb),color.a);}float calculate_NdotL(vec3 normal) {const float ext=0.70710678118;return (clamp(dot(normal,u_lighting_directional_dir),-ext,1.0)+ext)/(1.0+ext);}vec4 apply_lighting_with_emission_ground(vec4 color,float emissive_strength) {return mix(apply_lighting_ground(color),color,emissive_strength);}vec3 compute_flood_lighting(vec3 flood_light_color,float fully_occluded_factor,float occlusion,vec3 ground_shadow_factor) {vec3 fully_occluded_color=flood_light_color*mix(ground_shadow_factor,vec3(1.0),fully_occluded_factor);float occlusion_ramp=smoothstep(0.0,0.2,1.0-occlusion);return mix(fully_occluded_color,flood_light_color,occlusion_ramp);}vec3 compute_emissive_draped(vec3 unlit_color,float fully_occluded_factor,float occlusion,vec3 ground_shadow_factor) {vec3 fully_occluded_color=unlit_color*mix(ground_shadow_factor,vec3(1.0),fully_occluded_factor);return mix(fully_occluded_color,unlit_color,1.0-occlusion);} #endif`,"_prelude_raster_array.glsl":Mb,"_prelude_raster_particle.glsl":RN},Cv={};_o("",LN),_o(Tb,IN),_o(Xp,G_),_o(Mb,""),_o(RN,"");const Ey=_o(Mj,Ay),W_=Cy,w1=[` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,"precision mediump float;",W_,Ey.fragmentSource].join(` `),DN=["precision highp float;",W_,Ey.vertexSource].join(` `);var Pj={background:_o(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform vec4 u_color;uniform float u_opacity;uniform mediump float u_emissive_strength; #ifdef LIGHTING_3D_MODE in vec4 v_color; #endif void main() {vec4 out_color; #ifdef FEATURE_CUTOUT vec2 uv=gl_FragCoord.xy*u_inv_viewport_size.xy; #ifdef FLIP_Y uv.y=1.0-uv.y; #endif float factorTex=min(texture(u_cutout_factor_image,uv).r,1.0);float cutoutFactor=(1.0-u_feature_cutout_params.x)*factorTex;out_color=u_color*(1.0-cutoutFactor); #else #ifdef LIGHTING_3D_MODE out_color=v_color; #else out_color=u_color; #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif #endif glFragColor=out_color*u_opacity; #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_lighting.glsl" in ivec2 a_pos;uniform mat4 u_matrix;uniform mediump float u_emissive_strength; #ifdef LIGHTING_3D_MODE uniform mediump vec4 u_color;out vec4 v_color; #endif void main() {gl_Position=u_matrix*vec4(a_pos,0,1); #ifndef FEATURE_CUTOUT #ifdef LIGHTING_3D_MODE v_color=apply_lighting_with_emission_ground(u_color,u_emissive_strength); #endif #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif #endif }`),backgroundPattern:_o(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform vec2 u_pattern_tl;uniform vec2 u_pattern_br;uniform vec2 u_texsize;uniform float u_opacity;uniform float u_emissive_strength;uniform sampler2D u_image;in highp vec2 v_pos;void main() {highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(u_pattern_tl/u_texsize,u_pattern_br/u_texsize,imagecoord);vec4 out_color=textureLodCustom(u_image,pos,v_pos); #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*u_opacity; #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;uniform vec2 u_pattern_size;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec2 u_pattern_units_to_pixels;in ivec2 a_pos;out highp vec2 v_pos;void main() {vec2 pos=vec2(a_pos);gl_Position=u_matrix*vec4(pos,0,1);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_pattern_size,u_pattern_units_to_pixels,pos); #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),building:_o(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" const float window_depth=0.5;const float ao_radius=0.2;in vec4 v_color;in highp vec3 v_normal;in highp vec3 v_pos; #ifdef RENDER_FRONT_CUTOFF in float v_front_cutoff_opacity; #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT in vec4 v_ground_roof; #endif #endif #ifdef BUILDING_FAUX_FACADE in lowp float v_faux_facade;in highp float v_faux_facade_ed;in highp vec2 v_faux_facade_window;in highp vec2 v_faux_facade_floor;in highp vec2 v_faux_facade_range;in highp float v_aspect;in highp vec3 v_tbn_0;in highp vec3 v_tbn_1;in highp vec3 v_tbn_2;in highp vec4 v_faux_color_emissive;uniform float u_faux_facade_ao_intensity; #endif #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1; #endif #ifdef FLOOD_LIGHT in highp float v_flood_radius;in float v_has_flood_light; #endif uniform lowp float u_opacity;uniform vec3 u_camera_pos;uniform highp float u_tile_to_meter;uniform float u_facade_emissive_chance;uniform vec3 u_flood_light_color;uniform float u_flood_light_intensity;vec3 linearTosRGB(in vec3 color) {return pow(color,vec3(1./2.2));} #ifdef BUILDING_FAUX_FACADE highp float hash12(in highp vec2 p) {highp vec3 p3 =fract(vec3(p.xyx)*0.1031);p3+=dot(p3,p3.yzx+33.33);return fract((p3.x+p3.y)*p3.z);}float min3(in vec3 v) {return min(min(v.x,v.y),v.z);}highp vec2 get_uv_mask_id(in highp vec2 q,out highp float mask,out highp vec2 id) {highp vec2 p=q;mask=step(v_faux_facade_range.x,p.y)*step(p.y,v_faux_facade_range.y);p.y=p.y-v_faux_facade_range.x;highp vec2 uv=modf(p/v_faux_facade_floor,id);highp vec4 d=(v_faux_facade_floor.xyxy+vec4(-v_faux_facade_window,v_faux_facade_window))*0.5;highp vec4 edge=d/v_faux_facade_floor.xyxy;highp vec2 m=step(edge.xy,uv)*step(uv,edge.zw);mask*=m.x*m.y;uv-=vec2(0.5);uv*=vec2(0.5)/(vec2(0.5)-edge.xy);uv+=vec2(0.5);return uv;}highp float ray_unit_box(in highp vec3 ray_o,in highp vec3 ray_d,in highp vec3 bmin,in highp vec3 bmax) {highp vec3 planes=mix(bmin,bmax,step(0.0,ray_d));highp vec3 t=(planes-ray_o)/ray_d;return min3(t);}float get_emissive(in vec2 id) {if (u_facade_emissive_chance > 0.0) {return (step(hash12(id),u_facade_emissive_chance)+0.05)*v_faux_color_emissive.a;}return 0.0;}vec3 get_shade_info(in highp vec3 v,in highp vec3 v_normalized,in vec3 color,in vec2 id,in mat3 tbn,inout vec3 out_normal,inout float out_emissive) {vec3 out_color=color;highp vec3 abs_v=abs(v_normalized);bool x_major=abs_v.x >=abs_v.y && abs_v.x >=abs_v.z;bool y_major=abs_v.y >=abs_v.x && abs_v.y >=abs_v.z;bool z_major=abs_v.z >=abs_v.x && abs_v.z >=abs_v.y; #if 0 if (x_major) {out_color=v.x > 0.0 ? vec3(1.0,0.0,0.0) : vec3(0.0,1.0,1.0);} else if (y_major) {out_color=v.y > 0.0 ? vec3(0.0,1.0,0.0) : vec3(1.0,0.0,1.0);} else if (z_major) {out_color=v.z > 0.0 ? vec3(0.0,0.0,1.0) : vec3(1.0,1.0,0.0);}out_emissive=1.0; #else if (x_major) {out_normal=-sign(v.x)*tbn[0];} else if (y_major) {out_normal=vec3(0.0,0.0,-sign(v.y));} else if (z_major) {out_color=v_faux_color_emissive.rgb;out_emissive=v.z <=0.0 ? get_emissive(id) : out_emissive;}float ao=1.0;if (u_faux_facade_ao_intensity > 0.0) {vec4 ao_range=v_faux_facade_window.xxyy*0.5-vec4(0,ao_radius,0,ao_radius);vec2 ao_range_z=vec2(window_depth*0.5)-vec2(0.0,ao_radius);if (x_major || y_major) {ao*=smoothstep(-ao_range_z.x,-ao_range_z.y,v.z);} else if (z_major) {ao*=smoothstep(-ao_range.x,-ao_range.y,v.x)*(1.0-smoothstep(ao_range.y,ao_range.x,v.x));ao*=smoothstep(-ao_range.z,-ao_range.w,v.y)*(1.0-smoothstep(ao_range.w,ao_range.z,v.y));}ao=mix(1.0,min(1.0,ao+0.25),u_faux_facade_ao_intensity);}out_color*=ao; #endif return out_color;} #endif vec3 apply_lighting_linear(in vec3 color,in vec3 normal,in float dir_factor) {float ambient_directional_factor=calculate_ambient_directional_factor(normal);vec3 ambient_contrib=ambient_directional_factor*u_lighting_ambient_color;vec3 directional_contrib=u_lighting_directional_color*dir_factor;return color*(ambient_contrib+directional_contrib);}void main() {vec3 normal=normalize(v_normal);vec3 base_color=v_color.rgb;float emissive=v_color.a; #ifdef BUILDING_FAUX_FACADE if (v_faux_facade > 0.0) {highp mat3 tbn=mat3(v_tbn_0,v_tbn_1,v_tbn_2);highp vec3 v=vec3(v_pos.xy,v_pos.z/u_tile_to_meter)-u_camera_pos;highp vec3 view_tangent=transpose(tbn)*v;highp vec2 q=vec2(v_faux_facade_ed,v_pos.z);float mask=0.0;vec2 id=vec2(0.0);highp vec2 uv=get_uv_mask_id(q,mask,id);uv*=v_faux_facade_window;highp vec3 bmin=vec3(0.0,0.0,-window_depth);highp vec3 bmax=bmin+vec3(v_faux_facade_window,window_depth);highp vec3 ray_o=vec3(uv,0.0);highp vec3 ray_d=normalize(view_tangent);highp float t_min=ray_unit_box(ray_o,ray_d,bmin,bmax);highp vec3 hit=ray_o+t_min*ray_d;highp vec3 r=vec3(v_faux_facade_window,-window_depth);hit-=r*0.5;highp vec3 normalized=hit/r;vec3 out_normal=normal;float out_emissive=emissive;vec3 room_color=get_shade_info(hit,normalized,base_color,id,tbn,out_normal,out_emissive);base_color=mix(base_color,room_color,mask);normal=mix(normal,out_normal,mask);emissive=mix(emissive,out_emissive,mask);} #endif vec4 color=vec4(base_color,1.0);vec3 xy_flipped_normal=vec3(-normal.xy,normal.z);float shadowed_lighting_factor=0.0; #ifdef RENDER_SHADOWS #ifdef RENDER_CUTOFF shadowed_lighting_factor=shadowed_light_factor_normal_opacity(xy_flipped_normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,v_cutoff_opacity);if (v_cutoff_opacity==0.0) {discard;} #else shadowed_lighting_factor=shadowed_light_factor_normal(xy_flipped_normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w); #endif #else shadowed_lighting_factor=max(0.0,dot(xy_flipped_normal,u_lighting_directional_dir)); #endif color.rgb=apply_lighting_linear(color.rgb,xy_flipped_normal,shadowed_lighting_factor);color.rgb=linearTosRGB(color.rgb); #ifdef FLOOD_LIGHT float flood_radiance=(1.0-min(v_pos.z/v_flood_radius,1.0))*u_flood_light_intensity*v_has_flood_light;color.rgb=mix(color.rgb,u_flood_light_color,flood_radiance); #endif color.rgb=mix(color.rgb,linearTosRGB(base_color.rgb),emissive); #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos,v_pos.z)); #endif color*=u_opacity; #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT {float ditherOpacity=cutoutGroundRoofOpacity(v_ground_roof);if (ditherOpacity < 1.0) {int index=(int(gl_FragCoord.x) % 4)*4+(int(gl_FragCoord.y) % 4);if (ditherOpacity < DITHER_THRESHOLDS[index]) {discard;}}} #else color=applyCutout(color,v_pos.z); #endif #endif #ifdef RENDER_FRONT_CUTOFF if (v_front_cutoff_opacity < 1.0) {int index=(int(gl_FragCoord.x) % 4)*4+(int(gl_FragCoord.y) % 4);if (v_front_cutoff_opacity < DITHER_THRESHOLDS[index]) {discard;}} #endif #ifdef FEATURE_CUTOUT color=apply_feature_cutout(color,gl_FragCoord,get_cutout_factors(gl_FragCoord).x); #endif glFragColor=color; #ifdef DEBUG_SHOW_NORMALS color.rgb=xy_flipped_normal*0.5+vec3(0.5,0.5,0.5);color.a=1.0;glFragColor=color; #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in vec3 a_pos_3f;in ivec4 a_normal_3;in ivec4 a_centroid_3; #ifdef FLOOD_LIGHT in int a_flood_light_wall_radius_1i16; #endif #ifdef BUILDING_FAUX_FACADE in uvec4 a_faux_facade_data;in uvec2 a_faux_facade_vertical_range; #endif uniform mat4 u_matrix;uniform mat4 u_normal_matrix;uniform highp float u_tile_to_meter; #ifdef RENDER_FRONT_CUTOFF uniform vec3 u_front_cutoff_params;out float v_front_cutoff_opacity; #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT out vec4 v_ground_roof; #endif #endif out vec4 v_color;out vec3 v_normal;out highp vec3 v_pos; #ifdef BUILDING_FAUX_FACADE out lowp float v_faux_facade;out highp float v_faux_facade_ed;out highp vec2 v_faux_facade_window;out highp vec2 v_faux_facade_floor;out highp vec2 v_faux_facade_range;out highp float v_aspect;out highp vec3 v_tbn_0;out highp vec3 v_tbn_1;out highp vec3 v_tbn_2;out highp vec4 v_faux_color_emissive; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1; #endif #ifdef FLOOD_LIGHT out highp float v_flood_radius;out float v_has_flood_light; #endif const float MAX_UINT_16=65535.0;const float MAX_INT_16=32767.0;const float MAX_UINT_8=255.0;const float TWO_POW_8=256.0;const float FLOOD_LIGHT_MAX_RADIUS_METER=2048.0;vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));} #ifdef BUILDING_FAUX_FACADE mat3 get_tbn(in vec3 normal) {const vec3 bitangent=vec3(0.0,0.0,1.0);vec3 tangent=normalize(vec3(normal.y,-normal.x,0.0));return mat3(tangent,bitangent,normal);} #endif #pragma mapbox: define-attribute-vertex-shader-only highp uvec2 part_color_emissive #pragma mapbox: define-attribute-vertex-shader-only highp uvec2 faux_facade_color_emissive void main() { #pragma mapbox: initialize-attribute-custom highp uvec2 part_color_emissive #pragma mapbox: initialize-attribute-custom highp uvec2 faux_facade_color_emissive #ifdef FLOOD_LIGHT v_flood_radius=(float(a_flood_light_wall_radius_1i16)/MAX_INT_16*FLOOD_LIGHT_MAX_RADIUS_METER);v_has_flood_light=step(0.0,v_flood_radius); #endif vec4 color_emissive=decode_color(vec2(part_color_emissive));v_color=vec4(sRGBToLinear(color_emissive.rgb),color_emissive.a);vec3 a_normal_3f=vec3(a_normal_3)/MAX_INT_16;v_normal=vec3(u_normal_matrix*vec4(a_normal_3f,0.0));float hidden=0.0;float depth_offset=0.0;vec2 centroid_xy=vec2(a_centroid_3.xy >> 2);vec2 spanBits=vec2(a_centroid_3.xy & 3); #ifdef BUILDING_FAUX_FACADE vec4 faux_facade_data=vec4(a_faux_facade_data);v_faux_facade=faux_facade_data.x;if (v_faux_facade > 0.0) {v_faux_facade_ed=faux_facade_data.x *u_tile_to_meter;float window_x_perc=floor(faux_facade_data.y/TWO_POW_8);float window_y_perc=faux_facade_data.y-TWO_POW_8*window_x_perc;vec2 window_perc=vec2(window_x_perc,window_y_perc)/MAX_UINT_8;v_faux_facade_floor=(faux_facade_data.zw/MAX_UINT_16*EXTENT)*u_tile_to_meter;v_faux_facade_window=window_perc*v_faux_facade_floor;v_faux_facade_range=(vec2(a_faux_facade_vertical_range)/MAX_UINT_16*EXTENT)*u_tile_to_meter;v_aspect=v_faux_facade_window.x/v_faux_facade_window.y;mat3 tbn=get_tbn(normalize(v_normal));v_tbn_0=tbn[0];v_tbn_1=tbn[1];v_tbn_2=tbn[2];v_faux_color_emissive=decode_color(vec2(faux_facade_color_emissive));v_faux_color_emissive.rgb=sRGBToLinear(v_faux_color_emissive.rgb);depth_offset=min(1000.0,float(a_centroid_3.z))*0.0000002;} #endif v_pos=a_pos_3f; #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) float halfSpanX=spanBits.x*10.0/u_tile_to_meter;float halfSpanY=spanBits.y*10.0/u_tile_to_meter;vec2 screenUpInTile=vec2(u_matrix[0][1],u_matrix[1][1]);vec2 spanOffset=vec2(halfSpanX,halfSpanY)*sign(screenUpInTile);vec2 cutoff_highestCorner=centroid_xy+spanOffset;vec2 cutoff_lowestCorner=centroid_xy-spanOffset; #endif #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) vec4 ground=u_matrix*vec4(centroid_xy,0.0,1.0); #endif #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,ground.z);hidden=float(v_cutoff_opacity==0.0);v_pos.z*=v_cutoff_opacity; #endif #ifdef RENDER_SHADOWS vec3 shadow_pos=v_pos; #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset_model(v_normal);shadow_pos+=offset*shadow_normal_offset_multiplier0(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shadow_pos,1.0);v_pos_light_view_1=u_light_matrix_1*vec4(shadow_pos,1.0); #endif #ifdef FOG v_fog_pos=fog_position(v_pos); #endif #ifdef RENDER_FRONT_CUTOFF v_front_cutoff_opacity=1.0;{hidden=max(hidden,float(ground.w <=0.0));float ndc_y=ground.y/max(ground.w,0.001);float threshold=u_front_cutoff_params.x*2.0-1.0;float range_ndc=u_front_cutoff_params.y*2.0;hidden=max(hidden,float(ndc_y < threshold-range_ndc));float t=clamp((ndc_y-(threshold-range_ndc))/max(range_ndc,0.001),0.0,1.0);v_front_cutoff_opacity=mix(u_front_cutoff_params.z,1.0,t);} #endif gl_Position=mix(u_matrix*vec4(v_pos,1),AWAY,hidden);gl_Position.z-=depth_offset*gl_Position.w; #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT vec4 ic_ground=u_matrix*vec4(v_pos.xy,0.0,1.0);vec4 ic_roof=u_matrix*vec4(v_pos.xy,v_pos.z,1.0);v_ground_roof=vec4(ic_ground.xy/ic_ground.w,ic_roof.xy/ic_roof.w); #endif #endif }`),buildingBloom:_o(`in vec4 v_color_emissive; #pragma mapbox: define-attribute highp vec4 bloom_attenuation #pragma mapbox: initialize-attribute highp vec4 bloom_attenuation float saturate(float val) {return clamp(val,0.0,1.0);}void main() {float emission=v_color_emissive.a;float opacity=1.0; #ifdef HAS_ATTRIBUTE_a_bloom_attenuation float distance=length(vec2(1.3*max(0.0,abs(bloom_attenuation.x)-bloom_attenuation.z),bloom_attenuation.y));distance+= mix(0.5,0.0,clamp(emission-1.0,0.0,1.0));opacity*=saturate(1.0-distance*distance); #endif #ifdef RENDER_CUTOFF opacity*=v_cutoff_opacity; #endif glFragColor=vec4(v_color_emissive.rgb,1.0)*opacity;}`,`in vec3 a_pos_3f; #pragma mapbox: define-attribute-vertex-shader-only highp uvec2 part_color_emissive #pragma mapbox: define-attribute highp vec4 bloom_attenuation out vec4 v_color_emissive;uniform mat4 u_matrix;vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}void main() { #pragma mapbox: initialize-attribute-custom highp uvec2 part_color_emissive #pragma mapbox: initialize-attribute highp vec4 bloom_attenuation #ifdef HAS_ATTRIBUTE_a_part_color_emissive vec4 color_emissive=decode_color(vec2(part_color_emissive));float part_emissive=color_emissive.a*5.0;v_color_emissive=vec4(sRGBToLinear(color_emissive.rgb),part_emissive); #else v_color_emissive=vec4(1.0); #endif gl_Position=u_matrix*vec4(a_pos_3f,1.0); #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z); #endif }`),buildingDepth:_o("void main() {}","in vec3 a_pos_3f;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);}"),circle:_o(`#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:_o("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:_o(`#include "_prelude_fog.fragment.glsl" uniform highp float u_intensity;in vec2 v_extrude; #pragma mapbox: define highp float weight #define GAUSS_COEF 0.3989422804014327 void main() { #pragma mapbox: initialize highp float weight float d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);glFragColor=vec4(val,1.0,1.0,1.0); #ifdef FOG if (u_is_globe==0) {glFragColor.r*=pow(1.0-fog_opacity(v_fog_pos),2.0);} #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_terrain.vertex.glsl" #include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;in ivec2 a_pos; #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir; #endif out vec2 v_extrude; #pragma mapbox: define highp float weight #pragma mapbox: define mediump float radius const highp float ZERO=1.0/255.0/16.0; #define GAUSS_COEF 0.3989422804014327 void main() { #pragma mapbox: initialize highp float weight #pragma mapbox: initialize mediump float radius vec2 unscaled_extrude=vec2(mod(vec2(a_pos),2.0)*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 tilePos=floor(vec2(a_pos)*0.5);vec3 pos; #ifdef PROJECTION_GLOBE_VIEW vec3 pos_normal_3=vec3(a_pos_normal_3)/16384.0;mat3 surface_vectors=globe_mercator_surface_vectors(pos_normal_3,u_up_dir,u_zoom_transition);vec3 surface_extrusion=extrude.x*surface_vectors[0]+extrude.y*surface_vectors[1];vec3 globe_elevation=elevationVector(tilePos)*elevation(tilePos);vec3 globe_pos=vec3(a_pos_3)+surface_extrusion+globe_elevation;vec3 mercator_elevation=u_up_dir*u_tile_up_scale*elevation(tilePos);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,tilePos,u_tile_id,u_merc_center)+surface_extrusion+mercator_elevation;pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition); #else pos=vec3(tilePos+extrude,elevation(tilePos)); #endif gl_Position=u_matrix*vec4(pos,1); #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),heatmapTexture:_o(`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:_o("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:_o("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:_o("uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);glFragColor=mix(u_color,overlay_color,overlay_color.a);}",`#include "_prelude_terrain.vertex.glsl" in ivec2 a_pos; #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3; #endif out vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {vec2 pos=vec2(a_pos);float h=elevation(pos);v_uv=pos/8192.0; #ifdef PROJECTION_GLOBE_VIEW gl_Position=u_matrix*vec4(vec3(a_pos_3)+elevationVector(pos)*h,1); #else gl_Position=u_matrix*vec4(pos*u_overlay_scale,h,1); #endif }`),elevatedStructuresDepth:_o("void main() {}","in ivec2 a_pos;in float a_height;uniform mat4 u_matrix;uniform float u_depth_bias;void main() {gl_Position=u_matrix*vec4(a_pos,a_height,1);gl_Position.z=gl_Position.z+u_depth_bias;}"),elevatedStructuresDepthReconstruct:_o(`#ifdef DEPTH_RECONSTRUCTION in float v_height; #endif void main() { #ifdef DEPTH_RECONSTRUCTION if (v_height >=0.0) discard; #else #ifdef FEATURE_CUTOUT apply_feature_cutout(vec4(0.0,0.0,0.0,1.0),gl_FragCoord,get_cutout_factors(gl_FragCoord).x); #endif #endif glFragColor=vec4(1.0,0.0,0.0,1.0);}`,`in ivec2 a_pos;in float a_height;uniform mat4 u_matrix;uniform vec3 u_camera_pos;uniform highp float u_depth_bias;uniform lowp float u_height_scale;uniform lowp float u_reset_depth; #ifdef DEPTH_RECONSTRUCTION out float v_height; #endif void main() {vec3 vpos=vec3(a_pos,a_height*u_height_scale); #ifdef DEPTH_RECONSTRUCTION if (u_camera_pos.z > vpos.z) {vpos-=(u_camera_pos-vpos)*(vpos.z/(u_camera_pos.z-vpos.z));}v_height=a_height; #endif gl_Position=u_matrix*vec4(vpos,1);gl_Position.z=u_reset_depth==1.0 ? gl_Position.w : gl_Position.z+u_depth_bias;}`),elevatedStructures:_o(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" in vec3 v_normal;in float v_height; #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in float v_depth; #endif vec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}vec3 compute_view_dependent_emissive_color(float ndotl,float emissive_strength,vec3 color) {color=sRGBToLinear(color);color=color*(ndotl+(1.0-min(ndotl*57.29,1.0))*emissive_strength);color=linearTosRGB(color.rgb);return color;}uniform float u_emissive_strength; #pragma mapbox: define highp vec4 structure_color void main() { #pragma mapbox: initialize highp vec4 structure_color vec3 color=structure_color.xyz;vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #ifdef LIGHTING_3D_MODE vec3 normal=normalize(v_normal);vec3 transformed_normal=vec3(-normal.xy,normal.z);float ndotl=calculate_NdotL(transformed_normal);float emissive_strength=u_emissive_strength;emissive_strength=0.0;vec3 emissive_color=compute_view_dependent_emissive_color(ndotl,emissive_strength,color.xyz); #ifdef RENDER_SHADOWS float light=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);color.rgb=apply_lighting(color.rgb,transformed_normal,light); #else color=apply_lighting(color,transformed_normal); #endif color=mix(color,emissive_color,emissive_strength);if (v_height < 0.0) {float penetration=max(v_height+7.5,0.0);float occlusion=1.0-1.0/PI*acos(1.0-penetration/4.0);color=color*(1.0-pow(occlusion,2.0)*0.3);} #endif #ifdef FOG color=fog_apply(color,v_fog_pos); #endif vec4 out_color=vec4(color,1.0); #ifdef INDICATOR_CUTOUT out_color=applyCutout(out_color,v_height); #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif glFragColor=out_color;HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in ivec2 a_pos;in float a_height;in ivec4 a_pos_normal_3;uniform mat4 u_matrix;out vec3 v_normal;out float v_height; #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out float v_depth; #endif #pragma mapbox: define highp vec4 structure_color void main() { #pragma mapbox: initialize highp vec4 structure_color v_normal=vec3(a_pos_normal_3)/16384.0;v_height=a_height;vec3 pos=vec3(vec2(a_pos),a_height);gl_Position=u_matrix*vec4(pos,1); #ifdef RENDER_SHADOWS vec3 shd_pos0=pos;vec3 shd_pos1=pos; #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(-v_normal.xy,v_normal.z));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif }`),fill:_o(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float opacity uniform float u_emissive_strength; #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif #ifdef INDICATOR_CUTOUT in highp float v_z_offset; #endif void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float opacity vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif vec4 out_color=color; #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif out_color*=opacity; #ifdef INDICATOR_CUTOUT if (v_z_offset >=0.0) {out_color=applyCutout(out_color,v_z_offset);} #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif glFragColor=out_color; #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in ivec2 a_pos; #ifdef ELEVATED_ROADS in float a_road_z_offset;out highp float v_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif #ifdef INDICATOR_CUTOUT out highp float v_z_offset; #endif uniform mat4 u_matrix; #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float opacity #pragma mapbox: define highp float z_offset void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize highp float z_offset #ifdef ELEVATED_ROADS z_offset+=a_road_z_offset;v_road_z_offset=z_offset; #endif float hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden); #ifdef RENDER_SHADOWS vec3 shd_pos0=vec3(a_pos,z_offset);vec3 shd_pos1=vec3(a_pos,z_offset); #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif #ifdef INDICATOR_CUTOUT v_z_offset=z_offset; #endif }`),fillOutline:_o(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" in highp vec2 v_pos;uniform float u_emissive_strength; #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #pragma mapbox: define highp vec4 outline_color #pragma mapbox: define lowp float opacity void main() { #pragma mapbox: initialize highp vec4 outline_color #pragma mapbox: initialize lowp float opacity float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);vec4 out_color=outline_color;vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif glFragColor=out_color*(alpha*opacity); #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in ivec2 a_pos; #ifdef ELEVATED_ROADS in float a_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif uniform mat4 u_matrix;uniform vec2 u_world;out highp vec2 v_pos; #pragma mapbox: define highp vec4 outline_color #pragma mapbox: define lowp float opacity #pragma mapbox: define highp float z_offset void main() { #pragma mapbox: initialize highp vec4 outline_color #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize highp float z_offset #ifdef ELEVATED_ROADS z_offset+=a_road_z_offset; #endif float hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden); #ifdef FLIP_Y v_pos=(vec2(gl_Position.x,-gl_Position.y)/gl_Position.w+1.0)/2.0*u_world; #else v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world; #endif #ifdef RENDER_SHADOWS vec3 shd_pos0=vec3(a_pos,z_offset);vec3 shd_pos1=vec3(a_pos,z_offset); #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif }`),fillOutlinePattern:_o(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" uniform vec2 u_texsize;uniform sampler2D u_image; #ifdef FILL_PATTERN_TRANSITION uniform float u_pattern_transition; #endif uniform float u_emissive_strength; #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif in highp vec2 v_pos;in highp vec2 v_pos_world; #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);float dist=length(v_pos_world-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);vec4 out_color=textureLodCustom(u_image,pos,lod_pos); #ifdef APPLY_LUT_ON_GPU out_color=applyLUT(u_lutTexture,out_color); #endif #ifdef FILL_PATTERN_TRANSITION vec2 pattern_b_tl=pattern_b.xy;vec2 pattern_b_br=pattern_b.zw;highp vec2 pos_b=mix(pattern_b_tl/u_texsize,pattern_b_br/u_texsize,imagecoord);vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);out_color=out_color*(1.0-u_pattern_transition)+color_b*u_pattern_transition; #endif vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*(alpha*opacity); #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" uniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;in ivec2 a_pos; #ifdef ELEVATED_ROADS in float a_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif out highp vec2 v_pos;out highp vec2 v_pos_world; #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define lowp float pixel_ratio #pragma mapbox: define highp float z_offset void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize lowp float pixel_ratio #pragma mapbox: initialize highp float z_offset vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw); #ifdef ELEVATED_ROADS z_offset+=a_road_z_offset; #endif float hidden=float(opacity==0.0);vec2 pos=vec2(a_pos);gl_Position=mix(u_matrix*vec4(pos,z_offset,1),AWAY,hidden);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,pos); #ifdef FLIP_Y v_pos_world=(vec2(gl_Position.x,-gl_Position.y)/gl_Position.w+1.0)/2.0*u_world; #else v_pos_world=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world; #endif #ifdef RENDER_SHADOWS vec3 shd_pos0=vec3(pos,z_offset);vec3 shd_pos1=vec3(pos,z_offset); #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),fillPattern:_o(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" uniform vec2 u_texsize;uniform sampler2D u_image; #ifdef FILL_PATTERN_TRANSITION uniform float u_pattern_transition; #endif in highp vec2 v_pos;uniform float u_emissive_strength; #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);vec4 out_color=textureLodCustom(u_image,pos,lod_pos); #ifdef APPLY_LUT_ON_GPU out_color=applyLUT(u_lutTexture,out_color); #endif #ifdef FILL_PATTERN_TRANSITION vec2 pattern_b_tl=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(pattern_b.zw);highp vec2 pos_b=mix(pattern_b_tl/u_texsize,pattern_b_br/u_texsize,imagecoord);vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);out_color=out_color*(1.0-u_pattern_transition)+color_b*u_pattern_transition; #endif vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y); #ifdef ELEVATED_ROADS out_color.rgb*=mix(v_road_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light); #else out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*opacity; #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;in ivec2 a_pos; #ifdef ELEVATED_ROADS in float a_road_z_offset;out highp float v_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif out highp vec2 v_pos; #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define lowp float pixel_ratio #pragma mapbox: define highp float z_offset void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump uvec4 pattern #pragma mapbox: initialize lowp float pixel_ratio #pragma mapbox: initialize highp float z_offset #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio; #ifdef ELEVATED_ROADS z_offset+=a_road_z_offset;v_road_z_offset=z_offset; #endif float hidden=float(opacity==0.0);vec2 pos=vec2(a_pos);gl_Position=mix(u_matrix*vec4(pos,z_offset,1),AWAY,hidden);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,pos); #ifdef RENDER_SHADOWS vec3 shd_pos0=vec3(pos,z_offset);vec3 shd_pos1=vec3(pos,z_offset); #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),lineBlendComposite:_o(`uniform sampler2D u_image;uniform float u_opacity;uniform int u_blend_mode;in vec2 v_pos; #define ADDITIVE 1 void main() {vec4 color=texture(u_image,v_pos);if (u_blend_mode==ADDITIVE) {if (color.a <=0.0) {discard;}float density=color.a;vec3 avgColor=color.rgb/max(density,0.001);float t=density/(1.0+density);glFragColor=vec4(avgColor*t*u_opacity,t*u_opacity);} else {vec3 multiplyFactor=color.rgb*u_opacity+(1.0-u_opacity);glFragColor=vec4(multiplyFactor,1.0);} #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(0.0); #endif HANDLE_WIREFRAME_DEBUG;}`,"in ivec2 a_pos;out vec2 v_pos;void main() {gl_Position=vec4(a_pos,0,1);v_pos=vec2(a_pos)*0.5+0.5;}"),fillExtrusion:_o(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" in vec4 v_color;in vec4 v_flat; #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1; #endif uniform lowp float u_opacity; #ifdef RENDER_FRONT_CUTOFF in float v_front_cutoff_opacity; #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT in vec4 v_ground_roof; #endif #endif #ifdef FAUX_AO uniform lowp vec2 u_ao;in vec2 v_ao; #endif #if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE) in vec4 v_roof_color; #endif #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) in highp vec3 v_normal; #endif uniform vec3 u_flood_light_color;uniform highp float u_vertical_scale;uniform float u_flood_light_intensity;uniform vec3 u_ground_shadow_factor; #if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT) in float v_flood_radius;in float v_has_floodlight; #endif in float v_height; #pragma mapbox: define highp float emissive_strength void main() { #pragma mapbox: initialize highp float emissive_strength #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) vec3 normal=normalize(v_normal); #endif float z;vec4 color=v_color; #ifdef ZERO_ROOF_RADIUS z=float(normal.z > 0.00001); #ifdef LIGHTING_3D_MODE normal=mix(normal,vec3(0.0,0.0,1.0),z); #else color=mix(v_color,v_roof_color,z); #endif #endif float h=max(0.0,v_height);float ao_shade=1.0; #ifdef FAUX_AO float intensity=u_ao[0];float h_floors=h/(u_ao[1]*u_vertical_scale);float y_shade=1.0-0.9*intensity*min(v_ao.y,1.0);ao_shade=(1.0-0.08*intensity)*(y_shade+(1.0-y_shade)*(1.0-pow(1.0-min(h_floors/16.0,1.0),16.0)))+0.08*intensity*min(h_floors/160.0,1.0);float concave=v_ao.x*v_ao.x; #ifdef ZERO_ROOF_RADIUS concave*=(1.0-z); #endif float x_shade=mix(1.0,mix(0.6,0.75,min(h_floors/30.0,1.0)),intensity)+0.1*intensity*min(h,1.0);ao_shade*=mix(1.0,x_shade*x_shade*x_shade,concave); #ifdef LIGHTING_3D_MODE #ifdef FLOOD_LIGHT color.rgb*=mix(ao_shade,1.0,v_has_floodlight); #else color.rgb*=ao_shade; #endif #else color.rgb*=ao_shade; #endif #endif #ifdef LIGHTING_3D_MODE float flood_radiance=0.0; #ifdef FLOOD_LIGHT flood_radiance=(1.0-min(h/v_flood_radius,1.0))*u_flood_light_intensity*v_has_floodlight; #endif #ifdef RENDER_SHADOWS #ifdef FLOOD_LIGHT float ndotl_unclamped=dot(normal,u_shadow_direction);float ndotl=max(0.0,ndotl_unclamped);float occlusion=ndotl_unclamped < 0.0 ? 1.0 : shadow_occlusion(ndotl,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);vec3 litColor=apply_lighting(color.rgb,normal,(1.0-u_shadow_intensity*occlusion)*ndotl);vec3 floodLitColor=compute_flood_lighting(u_flood_light_color*u_opacity,1.0-u_shadow_intensity,occlusion,u_ground_shadow_factor);color.rgb=mix(litColor,floodLitColor,flood_radiance); #else float shadowed_lighting_factor; #ifdef RENDER_CUTOFF shadowed_lighting_factor=shadowed_light_factor_normal_opacity(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,v_cutoff_opacity);if (v_cutoff_opacity==0.0) {discard;} #else shadowed_lighting_factor=shadowed_light_factor_normal(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w); #endif color.rgb=apply_lighting(color.rgb,normal,shadowed_lighting_factor); #endif #else color.rgb=apply_lighting(color.rgb,normal); #ifdef FLOOD_LIGHT color.rgb=mix(color.rgb,u_flood_light_color*u_opacity,flood_radiance); #endif #endif color.rgb=mix(color.rgb,v_flat.rgb,emissive_strength);color*=u_opacity; #endif #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos,h)); #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT {float ditherOpacity=cutoutGroundRoofOpacity(v_ground_roof);if (ditherOpacity < 1.0) {int index=(int(gl_FragCoord.x) % 4)*4+(int(gl_FragCoord.y) % 4);if (ditherOpacity < DITHER_THRESHOLDS[index]) {discard;}}} #else color=applyCutout(color,h); #endif #endif #ifdef RENDER_FRONT_CUTOFF if (v_front_cutoff_opacity < 1.0) {int index=(int(gl_FragCoord.x) % 4)*4+(int(gl_FragCoord.y) % 4);if (v_front_cutoff_opacity < DITHER_THRESHOLDS[index]) {discard;}} #endif #ifdef FEATURE_CUTOUT color=apply_feature_cutout(color,gl_FragCoord,get_cutout_factors(gl_FragCoord).x); #endif glFragColor=color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #include "_prelude_lighting.glsl" #include "_prelude_material_table.vertex.glsl" uniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform float u_edge_radius;uniform float u_width_scale;in ivec4 a_pos_normal_ed; #if defined(HAS_CENTROID) || defined(TERRAIN) in uvec2 a_centroid_pos; #endif #ifdef RENDER_WALL_MODE in ivec4 a_join_normal_inside; #endif #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;uniform float u_height_lift; #endif #ifdef TERRAIN uniform int u_height_type;uniform int u_base_type; #endif uniform highp float u_vertical_scale; #ifdef RENDER_FRONT_CUTOFF uniform vec3 u_front_cutoff_params;out float v_front_cutoff_opacity; #endif out vec4 v_color;out vec4 v_flat; #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1; #endif #if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE) out vec4 v_roof_color; #endif #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) out highp vec3 v_normal; #endif #ifdef FAUX_AO uniform lowp vec2 u_ao;out vec2 v_ao; #endif #if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT) out float v_flood_radius;out float v_has_floodlight; #endif out float v_height; #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT out vec4 v_ground_roof; #endif #endif vec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));} #pragma mapbox: define highp float base #pragma mapbox: define highp float height #pragma mapbox: define highp vec4 color #pragma mapbox: define highp float flood_light_wall_radius #pragma mapbox: define highp float line_width #pragma mapbox: define highp float emissive_strength void main() {DECLARE_MATERIAL_TABLE_INFO #pragma mapbox: initialize highp float base #pragma mapbox: initialize highp float height #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize highp float flood_light_wall_radius #pragma mapbox: initialize highp float line_width #pragma mapbox: initialize highp float emissive_strength base*=u_vertical_scale;height*=u_vertical_scale;vec4 top_up_ny_start=vec4(a_pos_normal_ed & 1);vec4 pos_nx=vec4(a_pos_normal_ed >> 1);float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny_start.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny_start.z-1.0)*(1.0-abs(x_normal)),0.0)); #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) v_normal=normal; #endif base=max(0.0,base);float attr_height=height;height=max(0.0,top_up_ny_start.y==0.0 && top_up_ny_start.x==1.0 ? height-u_edge_radius : height);float t=top_up_ny_start.x;vec2 centroid_pos=vec2(0.0); #if defined(HAS_CENTROID) || defined(TERRAIN) centroid_pos=vec2(a_centroid_pos); #endif float ele=0.0;float h=0.0;float c_ele=0.0;vec3 pos; #ifdef TERRAIN bool is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;ele=elevation(pos_nx.xy);bool is_elevation_encoded=centroid_pos.y==0.0 || (centroid_pos.y > 0.0 && (int(centroid_pos.y) & 7)==7);c_ele=is_flat_height || is_flat_base ? (is_elevation_encoded ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);h=t > 0.0 ? max(h_base,h_height) : h_base; #else h=t > 0.0 ? height : base; #endif pos=vec3(pos_nx.xy,h); #ifdef PROJECTION_GLOBE_VIEW float lift=float((t+base) > 0.0)*u_height_lift;h+=lift;vec3 globe_normal=normalize(mix(vec3(a_pos_normal_3)/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=vec3(a_pos_3)+globe_normal*(u_tile_up_scale*h);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,pos.xy,u_tile_id,u_merc_center)+u_up_dir*u_tile_up_scale*pos.z;pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition); #endif float cutoff=1.0;vec3 scaled_pos=pos; #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) vec2 centroid_decoded=pos.xy;bool isBorderCentroid=false;if (centroid_pos.x > 0.0 && centroid_pos.y > 0.0) {int iy=int(centroid_pos.y);int spanYbits=iy & 7;if (spanYbits==7) {isBorderCentroid=true;int borderID=(iy >> 3) & 3;float coordAlongBorder=float(iy >> 5)*4.0;if (borderID==0) centroid_decoded=vec2(0.0,coordAlongBorder);else if (borderID==1) centroid_decoded=vec2(EXTENT,coordAlongBorder);else if (borderID==2) centroid_decoded=vec2(coordAlongBorder,0.0);else centroid_decoded=vec2(coordAlongBorder,EXTENT);} else {centroid_decoded=floor(centroid_pos/8.0);}} #endif #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) vec4 ground=u_matrix*vec4(centroid_decoded,ele,1.0); #endif #ifdef RENDER_CUTOFF #ifdef CLIP_ZERO_TO_ONE cutoff=cutoff_opacity(u_cutoff_params,ground.z*2.0-ground.w); #else cutoff=cutoff_opacity(u_cutoff_params,ground.z); #endif if (centroid_pos.y !=0.0 && centroid_pos.x !=0.0) {vec3 centroid_random=vec3(centroid_pos.xy,centroid_pos.x+centroid_pos.y+1.0);vec3 ground_pos=centroid_random/8.0;vec3 g=floor(ground_pos);vec3 mod_=centroid_random-g*8.0;float seed=min(1.0,0.1*(min(3.5,max(mod_.x+mod_.y,0.2*attr_height))*0.35+mod_.z));if (cutoff < 0.8-seed) {cutoff=0.0;}}float cutoff_scale=cutoff;v_cutoff_opacity=cutoff;scaled_pos.z=mix(c_ele,h,cutoff_scale); #endif float hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (cutoff==0.0 && centroid_pos.x !=0.0) || (color.a==0.0)); #ifdef RENDER_FRONT_CUTOFF v_front_cutoff_opacity=1.0;if (centroid_pos.x > 0.0 && centroid_pos.y > 0.0) {hidden=max(hidden,float(ground.w <=0.0));float ndc_y=ground.y/max(ground.w,0.001);float threshold=u_front_cutoff_params.x*2.0-1.0;float range_ndc=u_front_cutoff_params.y*2.0;if (!isBorderCentroid) {hidden=max(hidden,float(ndc_y < threshold-range_ndc));}float t=clamp((ndc_y-(threshold-range_ndc))/max(range_ndc,0.001),0.0,1.0);v_front_cutoff_opacity=mix(u_front_cutoff_params.z,1.0,t);} #endif #ifdef RENDER_WALL_MODE vec3 join_normal_inside=vec3(a_join_normal_inside);vec2 wall_offset=u_width_scale*line_width*(join_normal_inside.xy/EXTENT);scaled_pos.xy+=(1.0-join_normal_inside.z)*wall_offset*0.5;scaled_pos.xy-=join_normal_inside.z*wall_offset*0.5; #endif gl_Position=mix(u_matrix*vec4(scaled_pos,1),AWAY,hidden);h=h-ele;v_height=h; #ifdef RENDER_SHADOWS vec3 shd_pos0=pos;vec3 shd_pos1=pos; #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(normal);shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1); #endif float NdotL=0.0;float colorvalue=0.0; #ifndef LIGHTING_3D_MODE colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;NdotL=clamp(dot(normal,u_lightpos),0.0,1.0);NdotL=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),NdotL);if (normal.y !=0.0) {float r=0.84;r=mix(0.7,0.98,1.0-u_lightintensity);NdotL*=( (1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),r,1.0)));} #endif #ifdef FAUX_AO float concave=pos_nx.w-floor(pos_nx.w*0.5)*2.0;float start=top_up_ny_start.w;float y_ground=1.0-clamp(t+base,0.0,1.0);float top_height=height; #ifdef TERRAIN top_height=mix(max(c_ele+height,ele+base+2.0),ele+height,float(centroid_pos.x==0.0))-ele;y_ground+=y_ground*5.0/max(3.0,top_height); #endif v_ao=vec2(mix(concave,-concave,start),y_ground);NdotL*=(1.0+0.05*(1.0-top_up_ny_start.y)*u_ao[0]); #ifdef PROJECTION_GLOBE_VIEW top_height+=u_height_lift; #endif gl_Position.z-=(0.0000006*(min(top_height,500.)+2.0*min(base,500.0)+60.0*concave+3.0*start))*gl_Position.w; #endif #ifdef LIGHTING_3D_MODE #ifdef FLOOD_LIGHT float is_wall=1.0-float(t > 0.0 && top_up_ny_start.y > 0.0);v_has_floodlight=float(flood_light_wall_radius > 0.0 && is_wall > 0.0);v_flood_radius=flood_light_wall_radius*u_vertical_scale; #endif v_color=vec4(color.rgb,1.0);float ndotl=calculate_NdotL(normal);v_flat.rgb=sRGBToLinear(color.rgb);v_flat.rgb=v_flat.rgb*(ndotl+(1.0-min(ndotl*57.29,1.0))*emissive_strength);v_flat=vec4(linearTosRGB(v_flat.rgb),1.0); #else v_color=vec4(0.0,0.0,0.0,1.0);v_color.rgb+=clamp(color.rgb*NdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_color*=u_opacity; #endif #if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE) float roofNdotL=clamp(u_lightpos.z,0.0,1.0);roofNdotL=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),roofNdotL);v_roof_color=vec4(0.0,0.0,0.0,1.0);v_roof_color.rgb+=clamp(color.rgb*roofNdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_roof_color*=u_opacity; #endif #ifdef FOG v_fog_pos=fog_position(pos); #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT vec4 pos_ground=u_matrix*vec4(pos.xy,ele,1.0);vec4 pos_roof=u_matrix*vec4(pos.xy,ele+height,1.0);v_ground_roof=vec4(pos_ground.xy/pos_ground.w,pos_roof.xy/pos_roof.w); #endif #endif }`),fillExtrusionDepth:_o("void main() {}",`#include "_prelude_terrain.vertex.glsl" #include "_prelude_material_table.vertex.glsl" uniform mat4 u_matrix;uniform float u_edge_radius;uniform float u_width_scale;uniform float u_vertical_scale; #ifdef TERRAIN uniform int u_height_type;uniform int u_base_type; #endif in ivec4 a_pos_normal_ed; #if defined(HAS_CENTROID) || defined(TERRAIN) in uvec2 a_centroid_pos; #endif #ifdef RENDER_WALL_MODE in ivec4 a_join_normal_inside; #endif #pragma mapbox: define highp float base #pragma mapbox: define highp float height #pragma mapbox: define highp float line_width #pragma mapbox: define highp vec4 color void main() {DECLARE_MATERIAL_TABLE_INFO #pragma mapbox: initialize highp float base #pragma mapbox: initialize highp float height #pragma mapbox: initialize highp float line_width #pragma mapbox: initialize highp vec4 color base*=u_vertical_scale;height*=u_vertical_scale;vec3 top_up_ny=vec3(a_pos_normal_ed.xyz & 1);vec3 pos_nx=vec3(a_pos_normal_ed.xyz >> 1);base=max(0.0,base);height=max(0.0,top_up_ny.y==0.0 && top_up_ny.x==1.0 ? height-u_edge_radius : height);float t=top_up_ny.x;vec2 centroid_pos=vec2(0.0); #if defined(HAS_CENTROID) || defined(TERRAIN) centroid_pos=vec2(a_centroid_pos); #endif vec3 pos; #ifdef TERRAIN bool is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;float ele=elevation(pos_nx.xy);bool is_elevation_encoded=centroid_pos.y==0.0 || (centroid_pos.y > 0.0 && int(centroid_pos.y)-(int(centroid_pos.y)/8)*8==7);float c_ele=is_flat_height || is_flat_base ? (is_elevation_encoded ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);float h=t > 0.0 ? max(h_base,h_height) : h_base;pos=vec3(pos_nx.xy,h); #else pos=vec3(pos_nx.xy,t > 0.0 ? height : base); #endif #ifdef RENDER_WALL_MODE vec3 join_normal_inside=vec3(a_join_normal_inside);vec2 wall_offset=u_width_scale*line_width*(join_normal_inside.xy/EXTENT);pos.xy+=(1.0-join_normal_inside.z)*wall_offset*0.5;pos.xy-=join_normal_inside.z*wall_offset*0.5; #endif float hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (color.a==0.0));gl_Position=mix(u_matrix*vec4(pos,1),AWAY,hidden);}`),fillExtrusionPattern:_o(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform vec2 u_texsize;uniform sampler2D u_image; #ifdef FILL_EXTRUSION_PATTERN_TRANSITION uniform float u_pattern_transition; #endif #ifdef FAUX_AO uniform lowp vec2 u_ao;in vec3 v_ao; #endif #ifdef LIGHTING_3D_MODE in vec3 v_normal; #endif #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif in highp vec2 v_pos;in vec4 v_lighting;uniform lowp float u_opacity; #pragma mapbox: define highp float base #pragma mapbox: define highp float height #pragma mapbox: define mediump uvec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define highp float pixel_ratio void main() { #pragma mapbox: initialize highp float base #pragma mapbox: initialize highp float height #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize highp float pixel_ratio vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);vec4 out_color=textureLodCustom(u_image,pos,lod_pos); #ifdef APPLY_LUT_ON_GPU out_color=applyLUT(u_lutTexture,out_color); #endif #ifdef FILL_EXTRUSION_PATTERN_TRANSITION vec2 pattern_b_tl=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(pattern_b.zw);highp vec2 pos_b=mix(pattern_b_tl/u_texsize,pattern_b_br/u_texsize,imagecoord);vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);out_color=out_color*(1.0-u_pattern_transition)+color_b*u_pattern_transition; #endif #ifdef LIGHTING_3D_MODE out_color=apply_lighting(out_color,normalize(v_normal))*u_opacity; #else out_color=out_color*v_lighting; #endif #ifdef FAUX_AO float intensity=u_ao[0];float h=max(0.0,v_ao.z);float h_floors=h/u_ao[1];float y_shade=1.0-0.9*intensity*min(v_ao.y,1.0);float shade=(1.0-0.08*intensity)*(y_shade+(1.0-y_shade)*(1.0-pow(1.0-min(h_floors/16.0,1.0),16.0)))+0.08*intensity*min(h_floors/160.0,1.0);float concave=v_ao.x*v_ao.x;float x_shade=mix(1.0,mix(0.6,0.75,min(h_floors/30.0,1.0)),intensity)+0.1*intensity*min(h,1.0);shade*=mix(1.0,x_shade*x_shade*x_shade,concave);out_color.rgb=out_color.rgb*shade; #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif #ifdef INDICATOR_CUTOUT out_color=applyCutout(out_color,height); #endif glFragColor=out_color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #include "_prelude_lighting.glsl" #include "_prelude_material_table.vertex.glsl" uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform float u_tile_units_to_pixels;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform float u_width_scale;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;in ivec4 a_pos_normal_ed; #if defined(HAS_CENTROID) || defined(TERRAIN) in uvec2 a_centroid_pos; #endif #ifdef RENDER_WALL_MODE in ivec4 a_join_normal_inside; #endif #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;uniform float u_height_lift; #endif #ifdef TERRAIN uniform int u_height_type;uniform int u_base_type; #endif out highp vec2 v_pos;out vec4 v_lighting; #ifdef FAUX_AO uniform lowp vec2 u_ao;out vec3 v_ao; #endif #ifdef LIGHTING_3D_MODE out vec3 v_normal; #endif #pragma mapbox: define highp float base #pragma mapbox: define highp float height #pragma mapbox: define highp vec4 color #pragma mapbox: define mediump uvec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define highp float pixel_ratio #pragma mapbox: define highp float line_width void main() {DECLARE_MATERIAL_TABLE_INFO #pragma mapbox: initialize highp float base #pragma mapbox: initialize highp float height #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize highp float pixel_ratio #pragma mapbox: initialize highp float line_width vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);vec4 top_up_ny_start=vec4(a_pos_normal_ed & 1);vec4 pos_nx=vec4(a_pos_normal_ed >> 1);float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny_start.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny_start.z-1.0)*(1.0-abs(x_normal)),0.0));float edgedistance=float(a_pos_normal_ed.w);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;base=max(0.0,base);height=max(0.0,height);float t=top_up_ny_start.x;float z=t > 0.0 ? height : base;vec2 centroid_pos=vec2(0.0); #if defined(HAS_CENTROID) || defined(TERRAIN) centroid_pos=vec2(a_centroid_pos); #endif float ele=0.0;float h=z;vec3 p;float c_ele; #ifdef TERRAIN bool is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;ele=elevation(pos_nx.xy);bool is_elevation_encoded=centroid_pos.y==0.0 || (centroid_pos.y > 0.0 && int(centroid_pos.y)-(int(centroid_pos.y)/8)*8==7);c_ele=is_flat_height || is_flat_base ? (is_elevation_encoded ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);h=t > 0.0 ? max(h_base,h_height) : h_base;p=vec3(pos_nx.xy,h); #else p=vec3(pos_nx.xy,z); #endif #ifdef PROJECTION_GLOBE_VIEW float lift=float((t+base) > 0.0)*u_height_lift;h+=lift;vec3 globe_normal=normalize(mix(vec3(a_pos_normal_3)/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=vec3(a_pos_3)+globe_normal*(u_tile_up_scale*(p.z+lift));vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,p.xy,u_tile_id,u_merc_center)+u_up_dir*u_tile_up_scale*p.z;p=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition); #endif #ifdef RENDER_WALL_MODE vec3 join_normal_inside=vec3(a_join_normal_inside);vec2 wall_offset=u_width_scale*line_width*(join_normal_inside.xy/EXTENT);p.xy+=(1.0-join_normal_inside.z)*wall_offset*0.5;p.xy-=join_normal_inside.z*wall_offset*0.5; #endif float hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (color.a==0.0));gl_Position=mix(u_matrix*vec4(p,1),AWAY,hidden);vec2 pos=normal.z==1.0 ? pos_nx.xy : vec2(edgedistance,z*u_height_factor);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float NdotL=0.0; #ifdef LIGHTING_3D_MODE NdotL=calculate_NdotL(normal); #else NdotL=clamp(dot(normal,u_lightpos),0.0,1.0);NdotL=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),NdotL); #endif if (normal.y !=0.0) {float r=0.84; #ifndef LIGHTING_3D_MODE r=mix(0.7,0.98,1.0-u_lightintensity); #endif NdotL*=( (1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),r,1.0)));} #ifdef FAUX_AO float concave=pos_nx.w-floor(pos_nx.w*0.5)*2.0;float start=top_up_ny_start.w;float y_ground=1.0-clamp(t+base,0.0,1.0);float top_height=height; #ifdef TERRAIN top_height=mix(max(c_ele+height,ele+base+2.0),ele+height,float(centroid_pos.x==0.0))-ele;y_ground+=y_ground*5.0/max(3.0,top_height); #endif v_ao=vec3(mix(concave,-concave,start),y_ground,h-ele);NdotL*=(1.0+0.05*(1.0-top_up_ny_start.y)*u_ao[0]); #ifdef PROJECTION_GLOBE_VIEW top_height+=u_height_lift; #endif gl_Position.z-=(0.0000006*(min(top_height,500.)+2.0*min(base,500.0)+60.0*concave+3.0*start))*gl_Position.w; #endif #ifdef LIGHTING_3D_MODE v_normal=normal; #else v_lighting.rgb+=clamp(NdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity; #endif #ifdef FOG v_fog_pos=fog_position(p); #endif }`),groundShadow:_o(`#include "_prelude_shadow.fragment.glsl" precision highp float;uniform vec3 u_ground_shadow_factor;in vec4 v_pos_light_view_0;in vec4 v_pos_light_view_1; #ifdef FOG in float v_fog_opacity; #endif void main() {float light=shadowed_light_factor_plane_bias(v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);vec3 shadow=mix(u_ground_shadow_factor,vec3(1.0),light); #ifdef RENDER_CUTOFF shadow=mix(vec3(1.0),shadow,cutoff_opacity(u_cutoff_params,1.0/gl_FragCoord.w)); #endif #ifdef FOG shadow=mix(shadow,vec3(1.0),v_fog_opacity); #endif #ifdef INDICATOR_CUTOUT shadow=mix(shadow,vec3(1.0),1.0-applyCutout(vec4(1.0),0.0).r); #endif #ifdef FEATURE_CUTOUT shadow=mix(shadow,vec3(1.0),get_cutout_factors(gl_FragCoord).y); #endif glFragColor=vec4(shadow,1.0);}`,`#include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;in ivec2 a_pos;out vec4 v_pos_light_view_0;out vec4 v_pos_light_view_1; #ifdef FOG out float v_fog_opacity; #endif void main() {gl_Position=u_matrix*vec4(a_pos,0.0,1.0);v_pos_light_view_0=u_light_matrix_0*vec4(a_pos,0.0,1.0);v_pos_light_view_1=u_light_matrix_1*vec4(a_pos,0.0,1.0); #ifdef FOG v_fog_pos=fog_position(vec2(a_pos));v_fog_opacity=fog(v_fog_pos); #endif }`),fillExtrusionGroundEffect:_o(`uniform highp float u_ao_pass;uniform highp float u_opacity;uniform highp float u_flood_light_intensity;uniform highp vec3 u_flood_light_color;uniform highp float u_attenuation;uniform sampler2D u_fb;uniform float u_fb_size; #ifdef SDF_SUBPASS in highp vec2 v_pos;in highp vec4 v_line_segment;in highp float v_flood_light_radius_tile;in highp vec2 v_ao;float line_df(highp vec2 a,highp vec2 b,highp vec2 p) {highp vec2 ba=b-a;highp vec2 pa=p-a;highp float r=clamp(dot(pa,ba)/dot(ba,ba),0.0,1.0);return length(pa-r*ba);} #ifdef FOG in highp float v_fog; #endif #endif void main() { #ifdef CLEAR_SUBPASS vec4 color=vec4(1.0); #ifdef CLEAR_FROM_TEXTURE color=texture(u_fb,gl_FragCoord.xy/vec2(u_fb_size)); #endif glFragColor=color; #else #ifdef SDF_SUBPASS highp float d=line_df(v_line_segment.xy,v_line_segment.zw,v_pos);highp float effect_radius=mix(v_flood_light_radius_tile,v_ao.y,u_ao_pass);d/=effect_radius;d=min(d,1.0);d=1.0-pow(1.0-d,u_attenuation);highp float effect_intensity=mix(u_flood_light_intensity,v_ao.x,u_ao_pass);highp float fog=1.0; #ifdef FOG fog=v_fog; #endif #ifdef RENDER_CUTOFF fog*=v_cutoff_opacity; #endif glFragColor=vec4(vec3(0.0),mix(1.0,d,effect_intensity*u_opacity*fog)); #else #ifdef USE_MRT1 out_Target1=vec4(1.0-texture(u_fb,gl_FragCoord.xy/vec2(u_fb_size)).a,0.0,0.0,0.0); #else vec4 color=mix(vec4(u_flood_light_color,1.0),vec4(vec3(0.0),1.0),u_ao_pass); #ifdef OVERDRAW_INSPECTOR color=vec4(1.0); #endif glFragColor=color; #endif #endif HANDLE_WIREFRAME_DEBUG; #endif }`,`#include "_prelude_fog.vertex.glsl" in highp ivec4 a_pos_end;in highp int a_angular_offset_factor;in highp uint a_hidden_by_landmark; #ifdef SDF_SUBPASS out highp vec2 v_pos;out highp vec4 v_line_segment;out highp float v_flood_light_radius_tile;out highp vec2 v_ao; #ifdef FOG out highp float v_fog; #endif #endif uniform highp float u_flood_light_intensity;uniform highp mat4 u_matrix;uniform highp float u_ao_pass;uniform highp float u_meter_to_tile;uniform highp float u_edge_radius;uniform highp float u_dynamic_offset;uniform highp vec2 u_ao; #pragma mapbox: define highp float flood_light_ground_radius const float TANGENT_CUTOFF=4.0;const float NORM=32767.0;void main() { #pragma mapbox: initialize highp float flood_light_ground_radius vec4 pos_end=vec4(a_pos_end);vec2 p=pos_end.xy;vec2 q=floor(pos_end.zw*0.5);vec2 start_bottom=pos_end.zw-q*2.0;float fl_ground_radius=abs(flood_light_ground_radius);float direction=flood_light_ground_radius < 0.0 ?-1.0 : 1.0;float flood_radius_tile=fl_ground_radius*u_meter_to_tile;vec2 v=normalize(q-p);float ao_radius=u_ao.y/3.5;float effect_radius=mix(flood_radius_tile,ao_radius,u_ao_pass)+u_edge_radius;float angular_offset_factor=float(a_angular_offset_factor)/NORM*TANGENT_CUTOFF;float angular_offset=direction*angular_offset_factor*effect_radius;float top=1.0-start_bottom.y;float side=(0.5-start_bottom.x)*2.0;vec2 extrusion_parallel=v*side*mix(u_dynamic_offset,angular_offset,top);vec2 perp=vec2(v.y,-v.x);vec2 extrusion_perp=direction*perp*effect_radius*top;vec3 pos=vec3(mix(q,p,start_bottom.x),0.0);pos.xy+=extrusion_parallel+extrusion_perp; #ifdef SDF_SUBPASS v_pos=pos.xy;v_line_segment=vec4(p,q)+perp.xyxy*u_edge_radius;v_flood_light_radius_tile=flood_radius_tile;v_ao=vec2(u_ao.x,ao_radius); #ifdef FOG v_fog_pos=fog_position(pos);v_fog=1.0-fog(v_fog_pos); #endif #endif float hidden_by_landmark=0.0; #ifdef HAS_CENTROID hidden_by_landmark=float(a_hidden_by_landmark); #endif float isFloodlit=float(fl_ground_radius > 0.0 && u_flood_light_intensity > 0.0);float hidden=mix(1.0-isFloodlit,isFloodlit,u_ao_pass);hidden+=hidden_by_landmark;gl_Position=mix(u_matrix*vec4(pos,1.0),AWAY,float(hidden > 0.0)); #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z); #endif }`),hillshadePrepare:_o(`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:_o(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;uniform float u_emissive_strength;void main() {vec4 pixel=texture(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);glFragColor=accent_color*(1.0-shade_color.a)+shade_color; #ifdef LIGHTING_3D_MODE glFragColor=apply_lighting_with_emission_ground(glFragColor,u_emissive_strength); #endif #ifdef FOG glFragColor=fog_dither(fog_apply_premultiplied(glFragColor,v_fog_pos)); #endif #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;in ivec2 a_pos;in uvec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=vec2(a_texture_pos)/8192.0; #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif }`),line:_o(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" uniform lowp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform highp float u_floor_width_scale;uniform float u_alpha_discard_threshold;uniform highp vec2 u_trim_offset;uniform highp vec2 u_trim_fade_range;uniform highp vec2 u_trim_gradient_mix_range;uniform lowp vec4 u_trim_color;uniform bool u_emissive_in_shadows;in vec4 v_width2_dilute;in vec2 v_normal;in float v_gamma_scale;in highp vec3 v_uv; #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif #ifdef VARIABLE_LINE_WIDTH in float stub_side; #endif #ifdef RENDER_LINE_DASH uniform sampler2D u_dash_image;in vec2 v_tex; #endif #ifdef RENDER_LINE_GRADIENT uniform sampler2D u_gradient_image; #endif #ifdef INDICATOR_CUTOUT in highp float v_z_offset; #endif #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif float luminance(vec3 c) {return (c.r+c.r+c.b+c.g+c.g+c.g)*0.1667;} #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float floorwidth #pragma mapbox: define mediump uvec4 dash #pragma mapbox: define lowp float blur #pragma mapbox: define lowp float opacity #pragma mapbox: define mediump float side_z_offset #pragma mapbox: define lowp float border_width #pragma mapbox: define lowp vec4 border_color #pragma mapbox: define lowp float emissive_strength float linearstep(float edge0,float edge1,float x) {return clamp((x-edge0)/(edge1-edge0),0.0,1.0);}void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float floorwidth #pragma mapbox: initialize mediump uvec4 dash #pragma mapbox: initialize lowp float blur #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump float side_z_offset #pragma mapbox: initialize lowp float border_width #pragma mapbox: initialize lowp vec4 border_color #pragma mapbox: initialize lowp float emissive_strength float dist=length(v_normal)*v_width2_dilute.x; #ifdef VARIABLE_LINE_WIDTH blur=mix(blur,0.0,stub_side); #endif float diluted_opacity=opacity*v_width2_dilute.z;float blur2=(u_width_scale*blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2_dilute.y-blur2),v_width2_dilute.x-dist)/blur2,0.0,1.0); #ifdef VARIABLE_LINE_WIDTH alpha=mix(alpha,1.0,stub_side); #endif alpha=side_z_offset > 0.0 ? 1.0-alpha : alpha; #ifdef RENDER_LINE_DASH float sdfdist=texture(u_dash_image,v_tex).r;float sdfgamma=1.0/(2.0*u_device_pixel_ratio)/(float(dash.z)+float(dash.w)/65535.0);float scaled_floorwidth=(floorwidth*u_floor_width_scale);alpha*=linearstep(0.5-sdfgamma/scaled_floorwidth,0.5+sdfgamma/scaled_floorwidth,sdfdist); #endif highp vec4 out_color; #ifdef RENDER_LINE_GRADIENT out_color=texture(u_gradient_image,v_uv.xy); #else out_color=color; #endif float trim_alpha=1.0; #ifdef RENDER_LINE_TRIM_OFFSET highp float trim_start=u_trim_offset[0];highp float trim_end=u_trim_offset[1];highp float line_progress=v_uv[2];if (trim_end > trim_start) {highp float start_transition=max(0.0,min(1.0,(line_progress-trim_start)/max(u_trim_fade_range[0],1.0e-9)));highp float end_transition=max(0.0,min(1.0,(trim_end-line_progress)/max(u_trim_fade_range[1],1.0e-9)));highp float transition_factor=min(start_transition,end_transition);highp float gradient_trim_color_mix_factor=0.0; #ifdef RENDER_LINE_GRADIENT gradient_trim_color_mix_factor=smoothstep(u_trim_gradient_mix_range.x,u_trim_gradient_mix_range.y,line_progress); #endif highp vec4 trim_color=mix(u_trim_color,out_color,gradient_trim_color_mix_factor);out_color=mix(u_trim_gradient_mix_range.x < 1.0 ? color : out_color,trim_color,transition_factor);trim_alpha=1.0-transition_factor;} #endif if (u_alpha_discard_threshold !=0.0) {if (alpha < u_alpha_discard_threshold) {discard;}} #ifdef RENDER_LINE_BORDER #ifndef VARIABLE_LINE_WIDTH float edgeBlur=((border_width*u_width_scale)+1.0/u_device_pixel_ratio);float alpha2=clamp(min(dist-(v_width2_dilute.y-edgeBlur),v_width2_dilute.x-dist)/edgeBlur,0.0,1.0);if (alpha2 < 1.) {float smoothAlpha=smoothstep(0.6,1.0,alpha2);if (border_color.a==0.0) {float Y=(out_color.a > 0.01) ? luminance(out_color.rgb/out_color.a) : 1.;float adjustment=(Y > 0.) ? 0.5/Y : 0.45;if (out_color.a > 0.25 && Y < 0.25) {vec3 borderColor=(Y > 0.) ? out_color.rgb : vec3(1,1,1)*out_color.a;out_color.rgb=out_color.rgb+borderColor*(adjustment*(1.0-smoothAlpha));} else {out_color.rgb*=(0.6 +0.4*smoothAlpha);}} else {out_color=mix(border_color*trim_alpha,out_color,smoothAlpha);}out_color*=v_width2_dilute.w;} #endif #endif vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);light=u_emissive_in_shadows ? mix(light,1.0,emissive_strength) : light; #ifdef ELEVATED_ROADS out_color.rgb*=mix(v_road_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light); #else out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif out_color*=(alpha*diluted_opacity); #ifdef LINE_BLEND_MULTIPLY glFragColor=vec4(out_color.rgb+(1.0-out_color.a),1.0);HANDLE_WIREFRAME_DEBUG;return; #endif #ifdef INDICATOR_CUTOUT out_color=applyCutout(out_color,v_z_offset); #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif glFragColor=out_color; #ifdef DUAL_SOURCE_BLENDING glFragColorSrc1=vec4(vec3(0.0),emissive_strength); #else #ifdef USE_MRT1 out_Target1=vec4(emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #define EXTRUDE_SCALE 0.015873016 in ivec2 a_pos_normal;in uvec4 a_data; #if defined(ELEVATED) || defined(ELEVATED_ROADS) || defined(VARIABLE_LINE_WIDTH) in vec3 a_z_offset_width; #endif #ifdef ELEVATION_GROUND_SCALE in float a_elevation_ground_scale; #endif #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) || defined(RENDER_LINE_CURVE) in highp vec3 a_packed; #endif #ifdef RENDER_LINE_DASH in float a_linesofar; #endif uniform mat4 u_matrix;uniform mat2 u_pixels_to_tile_units;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;uniform float u_width_scale;uniform highp float u_floor_width_scale; #ifdef RENDER_LINE_CURVE uniform mat3 u_curve_points_x;uniform mat3 u_curve_points_y;uniform mat3 u_curve_points_z;uniform float u_curve_point_count; #endif #ifdef ELEVATED uniform lowp float u_zbias_factor;uniform lowp float u_tile_to_meter;float sample_elevation(vec2 apos) { #ifdef ELEVATION_REFERENCE_SEA return 0.0; #else return elevation(apos); #endif } #endif out vec2 v_normal;out vec4 v_width2_dilute;out float v_gamma_scale;out highp vec3 v_uv; #ifdef ELEVATED_ROADS out highp float v_road_z_offset; #endif #ifdef VARIABLE_LINE_WIDTH out float stub_side; #endif #ifdef RENDER_LINE_DASH uniform vec2 u_texsize;uniform float u_tile_units_to_pixels;out vec2 v_tex; #endif #ifdef RENDER_LINE_GRADIENT uniform float u_image_height; #endif #ifdef INDICATOR_CUTOUT out highp float v_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float floorwidth #pragma mapbox: define mediump uvec4 dash #pragma mapbox: define lowp float blur #pragma mapbox: define lowp float opacity #pragma mapbox: define mediump float gapwidth #pragma mapbox: define lowp float offset #pragma mapbox: define mediump float width #pragma mapbox: define mediump float side_z_offset #pragma mapbox: define lowp float border_width #pragma mapbox: define lowp vec4 border_color #pragma mapbox: define lowp float emissive_strength #ifdef RENDER_LINE_CURVE vec3 getCurvePoint(int index) {int row=index/3;int col=index-row*3;float x=u_curve_points_x[row][col];float y=u_curve_points_y[row][col];float z=u_curve_points_z[row][col];return vec3(x,y,z);}vec3 catmullRom(vec3 p0,vec3 p1,vec3 p2,vec3 p3,float t) {float t2=t*t;float t3=t2*t;return 0.5*( 2.0*p1+(-p0+p2)*t+(2.0*p0-5.0*p1+4.0*p2-p3)*t2+(-p0+3.0*p1-3.0*p2+p3)*t3 );}vec2 catmullRomTangent(vec2 p0,vec2 p1,vec2 p2,vec2 p3,float t) {float t2=t*t;return 0.5*( (-p0+p2)+(2.0*p0-5.0*p1+4.0*p2-p3)*2.0*t+(-p0+3.0*p1-3.0*p2+p3)*3.0*t2 );}struct CurveResult {vec3 point;vec2 tangent;};CurveResult calculateCurve(float line_progress) {float curve_progress=line_progress*(u_curve_point_count-1.0);float curve_progress_local=fract(curve_progress);float curve_segment=floor(curve_progress);int seg=int(curve_segment);vec3 p1=getCurvePoint(seg);vec3 p2=getCurvePoint(seg+1);float is_first_seg=step(curve_segment,0.5);vec3 p0_extrapolated=p1-(p2-p1);vec3 p0_fetched=getCurvePoint(max(seg-1,0));vec3 p0=mix(p0_fetched,p0_extrapolated,is_first_seg);int last_seg=int(u_curve_point_count)-2;float is_last_seg=step(float(last_seg)-0.5,curve_segment);vec3 p3_extrapolated=p2+(p2-p1);vec3 p3_fetched=getCurvePoint(min(seg+2,int(u_curve_point_count)-1));vec3 p3=mix(p3_fetched,p3_extrapolated,is_last_seg);vec3 point=catmullRom(p0,p1,p2,p3,curve_progress_local);vec2 tangent=catmullRomTangent(p0.xy,p1.xy,p2.xy,p3.xy,curve_progress_local)*(u_curve_point_count-1.0);CurveResult result;result.point=point;result.tangent=tangent;return result;} #endif void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float floorwidth #pragma mapbox: initialize mediump uvec4 dash #pragma mapbox: initialize lowp float blur #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump float gapwidth #pragma mapbox: initialize lowp float offset #pragma mapbox: initialize mediump float width #pragma mapbox: initialize mediump float side_z_offset #pragma mapbox: initialize lowp float border_width #pragma mapbox: initialize lowp vec4 border_color #pragma mapbox: initialize lowp float emissive_strength float a_z_offset; #if defined(ELEVATED) || defined(ELEVATED_ROADS) a_z_offset=a_z_offset_width.x; #endif highp float line_progress=0.0; #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) || defined(RENDER_LINE_CURVE) line_progress=a_packed[2]; #endif float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(a_data.xy)-128.0;float a_direction=float(a_data.z & 3u)-1.0;vec2 pos_normal=vec2(a_pos_normal);vec2 pos=floor(pos_normal*0.5);mediump vec2 normal=pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;offset=-1.0*offset*u_width_scale;bool left=normal.y==1.0; #ifdef RENDER_LINE_CURVE CurveResult curve=calculateCurve(line_progress);pos=curve.point.xy*8192.0;a_extrude=length(a_extrude)*normalize(curve.tangent);a_extrude=left ? vec2(-a_extrude.y,a_extrude.x) : vec2(a_extrude.y,-a_extrude.x);a_z_offset+=curve.point.z; #endif gapwidth=gapwidth/2.0;float halfwidth;float dilute_scale=1.0;float dilute_border_scale=1.0; #ifdef VARIABLE_LINE_WIDTH float left_width=a_z_offset_width.y;float right_width=a_z_offset_width.z;halfwidth=(u_width_scale*(left ? left_width : right_width))/2.0;if (side_z_offset !=0.0) {float left_f=step(1.0,normal.y);float is_negative=step(side_z_offset,0.0);float apply=mix(1.0-left_f,left_f,is_negative);a_extrude*=apply;a_z_offset+=abs(side_z_offset)*apply;v_normal*=left_f;}offset=border_width > 0.0 ? (left_width+right_width)*u_width_scale*0.5 : offset;halfwidth=border_width > 0.0 ? border_width*u_width_scale*0.5 : halfwidth;bool zero_right_width=border_width==0.0 && right_width==0.0;stub_side=zero_right_width ?-normal.y : 0.0;v_normal=!left && zero_right_width ? vec2(0.0) : v_normal;ANTIALIASING=!left && zero_right_width ? 0.0 : ANTIALIASING; #else halfwidth=(u_width_scale*width)/2.0; #endif float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*EXTRUDE_SCALE;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*EXTRUDE_SCALE*normal.y*mat2(t,-u,u,t);float hidden=float(opacity==0.0);vec2 extrude=dist*u_pixels_to_tile_units;vec4 projected_extrude=u_matrix*vec4(extrude,0.0,0.0);vec2 projected_extrude_xy=projected_extrude.xy; #ifdef ELEVATED_ROADS v_road_z_offset=a_z_offset;gl_Position=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,a_z_offset,1.0); #else #ifdef ELEVATED vec2 offsetTile=offset2*u_pixels_to_tile_units;vec2 offset_pos=pos+offsetTile;float ele=0.0;float scaled_z_offset=a_z_offset; #ifdef ELEVATION_GROUND_SCALE scaled_z_offset=a_z_offset*mix(1.0,u_exaggeration,a_elevation_ground_scale); #endif #ifdef CROSS_SLOPE_VERTICAL float top=pos_normal.y-2.0*floor(pos_normal.y*0.5);float line_height=2.0*u_tile_to_meter*outset*top*u_pixels_to_tile_units[1][1]+scaled_z_offset;ele=sample_elevation(offset_pos)+line_height;projected_extrude=vec4(0); #else #ifdef CROSS_SLOPE_HORIZONTAL float ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,max(ele1,ele2));ele=ele_max+scaled_z_offset; #else float ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,0.5*(ele1+ele2));ele=ele_max-ele0+ele1+scaled_z_offset; #endif #endif gl_Position=u_matrix*vec4(offset_pos,ele,1.0)+projected_extrude;float z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor*u_exaggeration);gl_Position.z-=(gl_Position.w*zbias);gl_Position=mix(gl_Position,AWAY,hidden); #else gl_Position=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,0.0,1.0); #endif #endif #ifndef ELEVATED #ifndef VARIABLE_LINE_WIDTH #ifndef RENDER_TO_TEXTURE float base_w=gl_Position.w;vec2 screen_width=abs(projected_extrude.xy/base_w*u_units_to_pixels);float max_extrude_component=max(screen_width.x,screen_width.y);if (width >=1.0 && base_w > 0.0 && max_extrude_component > 0.0001) {float min_pixel=1.05;if (max_extrude_component < min_pixel) {vec2 abs_pos=abs(gl_Position.xy);float is_out=max(abs_pos.x,abs_pos.y)/base_w;dilute_scale=mix(max_extrude_component/min_pixel,1.0,smoothstep(2.5,4.5,is_out));projected_extrude/=dilute_scale;}else { #ifdef RENDER_LINE_BORDER float border_ratio=(border_width*u_width_scale+ANTIALIASING)/outset;screen_width*=border_ratio;float max_border_component=max(screen_width.x,screen_width.y);dilute_border_scale=min(1.0,max_border_component/min_pixel); #endif }} #endif #endif #ifdef ELEVATED_ROADS gl_Position=gl_Position+projected_extrude; #else gl_Position=mix(gl_Position+projected_extrude,AWAY,hidden); #endif #endif #ifdef ELEVATED_ROADS #ifdef RENDER_SHADOWS vec3 shd_pos=vec3(pos+(offset2+dist)*u_pixels_to_tile_units,a_z_offset);vec3 shd_pos0=shd_pos;vec3 shd_pos1=shd_pos; #ifdef NORMAL_OFFSET vec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #endif #ifndef RENDER_TO_TEXTURE float epsilon=0.0001;float extrude_length_without_perspective=max(length(dist),epsilon);float extrude_length_with_perspective=max(length(projected_extrude_xy/gl_Position.w*u_units_to_pixels),epsilon);v_gamma_scale=mix(extrude_length_without_perspective/extrude_length_with_perspective,1.0,step(0.01,blur)); #else v_gamma_scale=1.0; #endif #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) highp float a_uv_x=a_packed[0];float a_split_index=a_packed[1]; #ifdef RENDER_LINE_GRADIENT highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec3(a_uv_x,a_split_index*texel_height-half_texel_height,line_progress); #else v_uv=vec3(a_uv_x,0.0,line_progress); #endif #endif #ifdef RENDER_LINE_DASH vec4 dashf=vec4(dash);float totalLength=dashf.z+dashf.w/65535.0;float scale=totalLength==0.0 ? 0.0 : u_tile_units_to_pixels/totalLength;v_tex=vec2(a_linesofar*scale/(floorwidth*u_floor_width_scale),(-normal.y*dashf.y+dashf.x+0.5)/u_texsize.y); #endif v_width2_dilute=vec4(outset,inset,dilute_scale,dilute_border_scale); #ifdef FOG v_fog_pos=fog_position(pos); #endif #ifdef INDICATOR_CUTOUT v_z_offset=a_z_offset; #endif }`),linePattern:_o(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" uniform highp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform highp float u_alpha_discard_threshold;uniform highp vec2 u_texsize;uniform highp float u_tile_units_to_pixels;uniform highp vec2 u_trim_offset;uniform highp vec2 u_trim_fade_range;uniform lowp vec4 u_trim_color;uniform sampler2D u_image; #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #ifdef LINE_PATTERN_TRANSITION uniform float u_pattern_transition; #endif in vec2 v_normal;in vec2 v_width2;in highp float v_linesofar;in float v_gamma_scale;in float v_width; #ifdef RENDER_LINE_TRIM_OFFSET in highp vec3 v_uv; #endif #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif #ifdef LINE_JOIN_NONE in vec2 v_pattern_data; #endif #ifdef INDICATOR_CUTOUT in highp float v_z_offset; #endif #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #pragma mapbox: define mediump uvec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define mediump float pixel_ratio #pragma mapbox: define mediump float blur #pragma mapbox: define mediump float opacity #pragma mapbox: define lowp float emissive_strength void main() { #pragma mapbox: initialize mediump uvec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize mediump float pixel_ratio #pragma mapbox: initialize mediump float blur #pragma mapbox: initialize mediump float opacity #pragma mapbox: initialize lowp float emissive_strength vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;highp float pattern_size=display_size.x/u_tile_units_to_pixels;float aspect=display_size.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(u_width_scale*blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);highp float pattern_x=v_linesofar/pattern_size*aspect;highp float x=mod(pattern_x,1.0);highp float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;highp vec2 pos=mix(pattern_tl*texel_size-texel_size,pattern_br*texel_size+texel_size,vec2(x,y));highp vec2 lod_pos=mix(pattern_tl*texel_size-texel_size,pattern_br*texel_size+texel_size,vec2(pattern_x,y));vec4 color=textureLodCustom(u_image,pos,lod_pos); #ifdef APPLY_LUT_ON_GPU color=applyLUT(u_lutTexture,color); #endif #ifdef LINE_PATTERN_TRANSITION vec2 pattern_b_tl=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(pattern_b.zw);highp vec2 pos_b=mix(pattern_b_tl*texel_size-texel_size,pattern_b_br*texel_size+texel_size,vec2(x,y));vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);color=color*(1.0-u_pattern_transition)+color_b*u_pattern_transition; #endif #ifdef RENDER_LINE_TRIM_OFFSET highp float trim_start=u_trim_offset[0];highp float trim_end=u_trim_offset[1];highp float line_progress=v_uv[2];if (trim_end > trim_start) {highp float start_transition=max(0.0,min(1.0,(line_progress-trim_start)/max(u_trim_fade_range[0],1.0e-9)));highp float end_transition=max(0.0,min(1.0,(trim_end-line_progress)/max(u_trim_fade_range[1],1.0e-9)));highp float transition_factor=min(start_transition,end_transition);color=mix(color,color.a*u_trim_color,transition_factor);} #endif #ifdef LINE_JOIN_NONE highp float pattern_len=pattern_size/aspect;highp float segment_phase=pattern_len-mod(v_linesofar-v_pattern_data.x+pattern_len,pattern_len);highp float visible_start=segment_phase-step(pattern_len*0.5,segment_phase)*pattern_len;highp float visible_end=floor((v_pattern_data.y-segment_phase)/pattern_len)*pattern_len+segment_phase;visible_end+=step(pattern_len*0.5,v_pattern_data.y-visible_end)*pattern_len;if (v_pattern_data.x < visible_start || v_pattern_data.x >=visible_end) {color=vec4(0.0);} #endif #ifdef LIGHTING_3D_MODE color=apply_lighting_with_emission_ground(color,emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth); #ifdef ELEVATED_ROADS color.rgb*=mix(v_road_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light); #else color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #endif #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos)); #endif color*=(alpha*opacity);if (u_alpha_discard_threshold !=0.0) {if (color.a < u_alpha_discard_threshold) {discard;}} #ifdef INDICATOR_CUTOUT color=applyCutout(color,v_z_offset); #endif glFragColor=color; #ifdef DUAL_SOURCE_BLENDING glFragColorSrc1=vec4(vec3(0.0),emissive_strength); #else #ifdef USE_MRT1 out_Target1=vec4(emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #define scale 0.015873016 in ivec2 a_pos_normal;in uvec4 a_data; #if defined(ELEVATED) || defined(ELEVATED_ROADS) in vec3 a_z_offset_width; #endif #ifdef ELEVATION_GROUND_SCALE in float a_elevation_ground_scale; #endif #ifdef RENDER_LINE_TRIM_OFFSET in highp vec3 a_packed; #endif in highp float a_linesofar; #ifdef LINE_JOIN_NONE in highp vec3 a_pattern_data;out vec2 v_pattern_data; #endif #ifdef INDICATOR_CUTOUT out highp float v_z_offset; #endif uniform mat4 u_matrix;uniform float u_tile_units_to_pixels;uniform vec2 u_units_to_pixels;uniform mat2 u_pixels_to_tile_units;uniform float u_device_pixel_ratio;uniform float u_width_scale;uniform float u_floor_width_scale; #ifdef ELEVATED uniform lowp float u_zbias_factor;uniform lowp float u_tile_to_meter;float sample_elevation(vec2 apos) { #ifdef ELEVATION_REFERENCE_SEA return 0.0; #else return elevation(apos); #endif } #endif out vec2 v_normal;out vec2 v_width2;out highp float v_linesofar;out float v_gamma_scale;out float v_width; #ifdef RENDER_LINE_TRIM_OFFSET out highp vec3 v_uv; #endif #ifdef ELEVATED_ROADS out highp float v_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif #pragma mapbox: define mediump float blur #pragma mapbox: define mediump float opacity #pragma mapbox: define mediump float offset #pragma mapbox: define mediump float gapwidth #pragma mapbox: define mediump float width #pragma mapbox: define mediump float floorwidth #pragma mapbox: define mediump uvec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define mediump float pixel_ratio #pragma mapbox: define lowp float emissive_strength void main() { #pragma mapbox: initialize mediump float blur #pragma mapbox: initialize mediump float opacity #pragma mapbox: initialize mediump float offset #pragma mapbox: initialize mediump float gapwidth #pragma mapbox: initialize mediump float width #pragma mapbox: initialize mediump float floorwidth #pragma mapbox: initialize mediump uvec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize mediump float pixel_ratio #pragma mapbox: initialize lowp float emissive_strength float a_z_offset; #if defined(ELEVATED) || defined(ELEVATED_ROADS) a_z_offset=a_z_offset_width.x; #endif float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(a_data.xy)-128.0;float a_direction=float(a_data.z & 3u)-1.0;vec2 pos_normal=vec2(a_pos_normal);vec2 pos=floor(pos_normal*0.5);vec2 normal=pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=(u_width_scale*width)/2.0;offset=-1.0*offset*u_width_scale;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);vec2 dist=outset*a_extrude*scale;float u=0.5*a_direction;float t=1.0-abs(u);vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float hidden=float(opacity==0.0);vec2 extrude=dist*u_pixels_to_tile_units;vec4 projected_extrude=u_matrix*vec4(extrude,0.0,0.0);vec2 projected_extrude_xy=projected_extrude.xy; #ifdef ELEVATED_ROADS v_road_z_offset=a_z_offset;gl_Position=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,a_z_offset,1.0)+projected_extrude; #else #ifdef ELEVATED vec2 offsetTile=offset2*u_pixels_to_tile_units;vec2 offset_pos=pos+offsetTile;float ele=0.0;float scaled_z_offset=a_z_offset; #ifdef ELEVATION_GROUND_SCALE scaled_z_offset=a_z_offset*mix(1.0,u_exaggeration,a_elevation_ground_scale); #endif #ifdef CROSS_SLOPE_VERTICAL float top=pos_normal.y-2.0*floor(pos_normal.y*0.5);float line_height=2.0*u_tile_to_meter*outset*top*u_pixels_to_tile_units[1][1]+scaled_z_offset;ele=sample_elevation(offset_pos)+line_height;projected_extrude=vec4(0); #else #ifdef CROSS_SLOPE_HORIZONTAL float ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,max(ele1,ele2));ele=ele_max+scaled_z_offset; #else float ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,0.5*(ele1+ele2));ele=ele_max-ele0+ele1+scaled_z_offset; #endif #endif gl_Position=u_matrix*vec4(offset_pos,ele,1.0)+projected_extrude;float z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor*u_exaggeration);gl_Position.z-=(gl_Position.w*zbias);gl_Position=mix(gl_Position,AWAY,hidden); #else gl_Position=mix(u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,0.0,1.0)+projected_extrude,AWAY,hidden); #endif #endif #ifdef ELEVATED_ROADS #ifdef RENDER_SHADOWS vec3 shd_pos=vec3(pos+(offset2+dist)*u_pixels_to_tile_units,a_z_offset);vec3 shd_pos0=shd_pos;vec3 shd_pos1=shd_pos; #ifdef NORMAL_OFFSET vec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #endif #ifndef RENDER_TO_TEXTURE float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude_xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=mix(extrude_length_without_perspective/extrude_length_with_perspective,1.0,step(0.01,blur)); #else v_gamma_scale=1.0; #endif #ifdef RENDER_LINE_TRIM_OFFSET highp float a_uv_x=a_packed[0];highp float line_progress=a_packed[2];v_uv=vec3(a_uv_x,0.0,line_progress); #endif v_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=(floorwidth*u_floor_width_scale); #ifdef LINE_JOIN_NONE v_width=(floorwidth*u_floor_width_scale)+ANTIALIASING;mediump float pixels_to_tile_units=1.0/u_tile_units_to_pixels;mediump float pixel_ratio_inverse=1.0/pixel_ratio;mediump float aspect=v_width/(float(pattern.w-pattern.y)*pixel_ratio_inverse);highp float subt_multiple=float(pattern.z-pattern.x)*pixel_ratio_inverse*pixels_to_tile_units*aspect*32.0;highp float subt=floor(a_pattern_data.z/subt_multiple)*subt_multiple;float offset_sign=(fract(a_pattern_data.x)-0.5)*4.0;float line_progress_offset=offset_sign*v_width*0.5*pixels_to_tile_units;v_linesofar=(a_pattern_data.z-subt)+a_linesofar+line_progress_offset;v_pattern_data=vec2(a_pattern_data.x+line_progress_offset,a_pattern_data.y); #endif #ifdef FOG v_fog_pos=fog_position(pos); #endif #ifdef INDICATOR_CUTOUT v_z_offset=a_z_offset; #endif }`),raster:_o(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_raster_array.glsl" uniform float u_fade_t;uniform float u_opacity;uniform highp float u_raster_elevation;uniform highp float u_zoom_transition;in vec2 v_pos0;in vec2 v_pos1;in float v_depth; #ifdef PROJECTION_GLOBE_VIEW in float v_split_fade; #endif uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;uniform float u_emissive_strength; #ifndef RASTER_ARRAY uniform highp sampler2D u_image0;uniform sampler2D u_image1; #endif #ifdef RASTER_COLOR uniform sampler2D u_color_ramp;uniform highp vec4 u_colorization_mix;uniform highp float u_colorization_offset;uniform vec2 u_texture_res; #endif void main() {vec4 color0,color1,color;vec2 value; #ifdef RASTER_COLOR #ifdef RASTER_ARRAY #ifdef RASTER_ARRAY_LINEAR value=mix( raTexture2D_image0_linear(v_pos0,u_texture_res,u_colorization_mix,u_colorization_offset),raTexture2D_image1_linear(v_pos1,u_texture_res,u_colorization_mix,u_colorization_offset),u_fade_t ); #else value=mix( raTexture2D_image0_nearest(v_pos0,u_texture_res,u_colorization_mix,u_colorization_offset),raTexture2D_image1_nearest(v_pos1,u_texture_res,u_colorization_mix,u_colorization_offset),u_fade_t ); #endif if (value.y > 0.0) value.x/=value.y; #else color=mix(texture(u_image0,v_pos0),texture(u_image1,v_pos1),u_fade_t);value=vec2(u_colorization_offset+dot(color.rgb,u_colorization_mix.rgb),color.a); #endif color=texture(u_color_ramp,vec2(value.x,0.5));if (color.a > 0.0) color.rgb/=color.a;color.a*=value.y; #else color0=texture(u_image0,v_pos0);color1=texture(u_image1,v_pos1);if (color0.a > 0.0) color0.rgb/=color0.a;if (color1.a > 0.0) color1.rgb/=color1.a;color=mix(color0,color1,u_fade_t); #endif color.a*=u_opacity; #ifdef GLOBE_POLES color.a*=1.0-smoothstep(0.0,0.05,u_zoom_transition); #endif vec3 rgb=color.rgb;rgb=vec3( dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);vec3 out_color=mix(u_high_vec,u_low_vec,rgb); #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(vec4(out_color,1.0),u_emissive_strength).rgb; #endif #ifdef FOG highp float fog_limit_high_meters=1000000.0;highp float fog_limit_low_meters=600000.0;float fog_limit=1.0-smoothstep(fog_limit_low_meters,fog_limit_high_meters,u_raster_elevation);out_color=fog_dither(fog_apply(out_color,v_fog_pos,fog_limit)); #endif glFragColor=vec4(out_color*color.a,color.a); #ifdef PROJECTION_GLOBE_VIEW glFragColor*=mix(1.0,1.0-smoothstep(0.0,0.05,u_zoom_transition),smoothstep(0.8,0.9,v_split_fade)); #endif #ifdef RENDER_CUTOFF glFragColor=glFragColor*cutoff_opacity(u_cutoff_params,v_depth); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" uniform mat4 u_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform mat3 u_grid_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform vec2 u_perspective_transform;uniform vec2 u_texture_offset;uniform float u_raster_elevation;uniform float u_zoom_transition;uniform vec2 u_merc_center; #ifdef ELEVATED uniform lowp float u_zbias_factor; #endif #define GLOBE_UPSCALE GLOBE_RADIUS/6371008.8 #ifdef GLOBE_POLES in vec3 a_globe_pos;in vec2 a_uv; #else in ivec2 a_pos;in uvec2 a_texture_pos; #endif out vec2 v_pos0;out vec2 v_pos1;out float v_depth; #ifdef PROJECTION_GLOBE_VIEW out float v_split_fade; #endif void main() {vec2 uv; #ifdef GLOBE_POLES vec3 globe_pos=a_globe_pos;uv=a_uv;float ele=u_raster_elevation; #ifdef ELEVATION_REFERENCE_GROUND ele+=elevation(uv*EXTENT); #endif globe_pos+=normalize(globe_pos)*ele*GLOBE_UPSCALE;gl_Position=u_matrix*u_globe_matrix*vec4(globe_pos,1.0); #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(a_globe_pos,1.0)).xyz); #endif #else vec4 world_pos; #ifdef PROJECTION_GLOBE_VIEW vec2 texture_pos=vec2(a_texture_pos);uv=texture_pos/8192.0;vec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);float mercatorY=mercatorYfromLat(latLng[0]);float mercatorX=mercatorXfromLng(latLng[1]); float tiles=u_grid_matrix[0][2];if (tiles > 0.0) {float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];float uvY=mercatorY*tiles-idy;float uvX=mercatorX*tiles-idx;uv=vec2(uvX,uvY);}float ele=u_raster_elevation; #ifdef ELEVATION_REFERENCE_GROUND ele+=elevation(uv*EXTENT)-decomposed_pos_and_skirt.z; #endif vec4 merc_world_pos=vec4(0.0); v_split_fade=0.0;if (u_zoom_transition > 0.0) {vec2 merc_pos=vec2(mercatorX,mercatorY);merc_world_pos=vec4(merc_pos,ele,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;float opposite_merc_center=mod(u_merc_center.x+0.5,1.0);float dist_from_poles=(abs(mercatorY-0.5)*2.0);float range=0.1;v_split_fade=abs(opposite_merc_center-mercatorX);v_split_fade=clamp(1.0-v_split_fade,0.0,1.0);v_split_fade=max(smoothstep(1.0-range,1.0,dist_from_poles),max(smoothstep(1.0-range,1.0,v_split_fade),smoothstep(1.0-range,1.0,1.0-v_split_fade)));}vec3 globe_pos=latLngToECEF(latLng.xy);globe_pos+=normalize(globe_pos)*ele*GLOBE_UPSCALE;vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);world_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition),1.0); #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz); #endif #else float ele=0.0;vec2 decodedPos=vec2(a_pos); #ifdef ELEVATION_REFERENCE_GROUND vec3 decomposedPosAndSkirt=decomposeToPosAndSkirt(a_pos);float skirt=decomposedPosAndSkirt.z;decodedPos=decomposedPosAndSkirt.xy;uv=decodedPos/8192.0;ele=elevation(decodedPos)-skirt; #else uv=vec2(a_texture_pos)/8192.0; #endif world_pos=vec4(decodedPos,(u_raster_elevation+ele),1.0); #ifdef FOG v_fog_pos=fog_position(decodedPos); #endif #endif float w=1.0+dot(uv*EXTENT,u_perspective_transform);gl_Position=u_matrix*world_pos*w; #endif v_pos0=uv;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;v_pos0=u_texture_offset.x+u_texture_offset.y*v_pos0;v_pos1=u_texture_offset.x+u_texture_offset.y*v_pos1; #ifdef ELEVATED float z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor);gl_Position.z-=(gl_Position.w*zbias); #endif #ifdef RENDER_CUTOFF v_depth=gl_Position.z; #endif }`),rasterParticle:_o(`#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("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("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(`#include "_prelude_raster_particle.glsl" uniform sampler2D u_particle_texture;uniform mediump float u_particle_texture_side_len;uniform mediump float u_speed_factor;uniform highp float u_reset_rate;uniform highp float u_rand_seed;in highp vec2 v_tex_coord;vec2 linearstep(vec2 edge0,vec2 edge1,vec2 x) {return clamp((x-edge0)/(edge1-edge0),vec2(0),vec2(1));}const highp vec3 rand_constants=vec3(12.9898,78.233,4375.85453);highp float rand(const highp vec2 co) {highp float t=dot(rand_constants.xy,co);return fract(sin(t)*(rand_constants.z+t));}void main() {ivec2 pixel_coord=ivec2(v_tex_coord*u_particle_texture_side_len);highp vec4 pixel=texelFetch(u_particle_texture,pixel_coord,0);highp vec2 pos=unpack_pos_from_rgba(pixel);highp vec2 velocity=lookup_velocity(clamp(pos,0.0,1.0));highp vec2 dp=velocity==INVALID_VELOCITY ? vec2(0) : velocity*u_speed_factor;pos=pos+dp;highp vec2 seed=(pos+v_tex_coord)*u_rand_seed;highp vec2 random_pos=vec2(rand(seed+1.3),rand(seed+2.1));highp vec2 persist_rate=pow( linearstep(vec2(-u_particle_pos_offset),vec2(0),pos)*linearstep(vec2(1.0+u_particle_pos_offset),vec2(1),pos),vec2(4) );highp vec2 per_frame_persist=pow(persist_rate,abs(dp)/u_particle_pos_offset);highp float drop_rate=1.0-per_frame_persist.x*per_frame_persist.y;drop_rate=any(greaterThanEqual(abs(pos-0.5),vec2(0.5+u_particle_pos_offset))) ? 1.0 : drop_rate;highp float drop=step(1.0-drop_rate-u_reset_rate,rand(seed));highp vec2 next_pos=mix(pos,random_pos,drop);glFragColor=pack_pos_to_rgba(next_pos);}`,"in ivec2 a_pos;out vec2 v_tex_coord;void main() {v_tex_coord=0.5*vec2(a_pos+ivec2(1));gl_Position=vec4(a_pos,0.0,1.0);}"),symbol:_o(`#include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #define SDF_PX 8.0 #define SDF 1.0 #define ICON 0.0 uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;uniform bool u_is_halo;uniform lowp float u_scale_factor; #ifdef ICON_TRANSITION uniform float u_icon_transition; #endif #ifdef COLOR_ADJUSTMENT uniform mat4 u_color_adj_mat; #endif #ifdef INDICATOR_CUTOUT in highp float v_z_offset; #else #ifdef RENDER_SHADOWS in highp float v_z_offset; #endif #endif in vec2 v_tex_a; #ifdef ICON_TRANSITION in vec2 v_tex_b; #endif in float v_draw_halo;in vec3 v_gamma_scale_size_fade_opacity; #ifdef RENDER_TEXT_AND_SYMBOL in float is_sdf;in vec2 v_tex_a_icon; #endif #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #ifdef USE_PAINT_PROPERTIES_UBO in lowp float v_opacity; #ifdef RENDER_SDF in lowp vec4 v_fill_np_color;in lowp vec4 v_halo_np_color;in lowp float v_halo_width;in lowp float v_halo_blur; #endif #ifdef LIGHTING_3D_MODE in lowp float v_emissive_strength; #endif #else #pragma mapbox: define highp vec4 fill_color #pragma mapbox: define highp vec4 halo_color #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp float halo_width #pragma mapbox: define lowp float halo_blur #pragma mapbox: define lowp float emissive_strength #endif void main() { #ifdef USE_PAINT_PROPERTIES_UBO lowp float opacity=v_opacity;lowp vec4 fill_color=vec4(0.0);lowp vec4 halo_color=vec4(0.0);lowp float halo_width=0.0;lowp float halo_blur=0.0; #ifdef RENDER_SDF fill_color=vec4(v_fill_np_color.rgb*v_fill_np_color.a,v_fill_np_color.a);halo_color=vec4(v_halo_np_color.rgb*v_halo_np_color.a,v_halo_np_color.a);halo_width=v_halo_width;halo_blur=v_halo_blur; #endif lowp float emissive_strength=0.0; #ifdef LIGHTING_3D_MODE emissive_strength=v_emissive_strength; #endif #else #pragma mapbox: initialize highp vec4 fill_color #pragma mapbox: initialize highp vec4 halo_color #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize lowp float halo_width #pragma mapbox: initialize lowp float halo_blur #pragma mapbox: initialize lowp float emissive_strength #endif vec4 out_color;float fade_opacity=v_gamma_scale_size_fade_opacity[2]; #ifdef RENDER_TEXT_AND_SYMBOL if (is_sdf==ICON) {vec2 tex_icon=v_tex_a_icon;lowp float alpha=opacity*fade_opacity;glFragColor=texture(u_texture_icon,tex_icon)*alpha; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif return;} #endif vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #ifdef RENDER_SDF float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_gamma_scale_size_fade_opacity.x;float size=v_gamma_scale_size_fade_opacity.y;float fontScale=u_is_text ? size/24.0 : size;out_color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;bool draw_halo=v_draw_halo > 0.0;if (draw_halo) {out_color=halo_color;gamma=(halo_blur*u_scale_factor*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width*u_scale_factor/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,v_tex_a).r;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);out_color*=alpha; #else #ifdef ICON_TRANSITION vec4 a=texture(u_texture,v_tex_a)*(1.0-u_icon_transition);vec4 b=texture(u_texture,v_tex_b)*u_icon_transition;out_color=(a+b); #else out_color=texture(u_texture,v_tex_a); #endif #ifdef APPLY_LUT_ON_GPU out_color=applyLUT(u_lutTexture,out_color); #endif #ifdef COLOR_ADJUSTMENT out_color=u_color_adj_mat*out_color; #endif #endif out_color*=opacity*fade_opacity; #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y); #ifdef TERRAIN out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #else out_color.rgb*=mix(v_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light); #endif #endif #endif #ifdef INDICATOR_CUTOUT out_color=applyCutout(out_color,v_z_offset); #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif glFragColor=out_color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_terrain.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #define USING_APPEARANCE 1.0 in ivec4 a_pos_offset;in uvec4 a_tex_size;in ivec4 a_pixeloffset;in vec4 a_projected_pos;in uint a_fade_opacity; #ifdef Z_OFFSET in float a_auto_z_offset; #endif #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_globe_anchor;in vec3 a_globe_normal; #endif #ifdef ICON_TRANSITION in uvec2 a_texb; #endif #ifdef OCCLUSION_QUERIES in float a_occlusion_query_opacity; #endif #ifdef ELEVATED_ROADS in vec3 a_x_axis;in vec3 a_y_axis;uniform float u_normal_scale; #endif #ifdef INDICATOR_CUTOUT out highp float v_z_offset; #else #ifdef RENDER_SHADOWS out highp float v_z_offset; #endif #endif uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_elevation_from_sea;uniform bool u_pitch_with_map;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec3 u_up_vector;uniform vec2 u_texsize_icon;uniform bool u_is_halo; #ifdef PROJECTION_GLOBE_VIEW uniform vec3 u_tile_id;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_camera_forward;uniform float u_zoom_transition;uniform vec3 u_ecef_origin;uniform mat4 u_tile_matrix; #endif out vec2 v_tex_a; #ifdef ICON_TRANSITION out vec2 v_tex_b; #endif out float v_draw_halo;out vec3 v_gamma_scale_size_fade_opacity; #ifdef RENDER_TEXT_AND_SYMBOL out float is_sdf;out vec2 v_tex_a_icon; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif #ifdef USE_PAINT_PROPERTIES_UBO #ifndef MAX_UBO_SIZE_VEC4 #define MAX_UBO_SIZE_VEC4 1024u #endif #define SPP_HEADER_SIZE_VEC4 3u #define DWORDS_PER_VEC4 4u struct SymbolPaintProperties {vec4 fill_np_color;vec4 halo_np_color;float opacity;float halo_width;float halo_blur;float emissive_strength;float occlusion_opacity;float z_offset;vec2 translate;};struct PropertyType {bool isDataDriven;bool isZoomDependent;uint offsetDwords;};struct SymbolPropertyHeader {uint dataDrivenBlockSizeVec4;PropertyType fill_np_color;PropertyType halo_np_color;PropertyType opacity;PropertyType halo_width;PropertyType halo_blur;PropertyType emissive_strength;PropertyType occlusion_opacity;PropertyType z_offset;PropertyType translate;};uniform float u_zoom;uniform lowp vec4 u_spp_fill_np_color;uniform lowp vec4 u_spp_halo_np_color;uniform lowp float u_spp_opacity;uniform lowp float u_spp_halo_width;uniform lowp float u_spp_halo_blur;uniform lowp float u_spp_emissive_strength;uniform lowp float u_spp_occlusion_opacity;uniform lowp float u_spp_z_offset;uniform lowp vec2 u_spp_translate_rotation;in float a_feature_index;layout(std140) uniform SymbolPaintPropertiesHeaderUniform {uvec4 header[SPP_HEADER_SIZE_VEC4];} u_spp_header;layout(std140) uniform SymbolPaintPropertiesUniform {vec4 properties[MAX_UBO_SIZE_VEC4];} u_spp_properties;layout(std140) uniform SymbolPaintPropertiesIndexUniform {uvec4 block_indices[MAX_UBO_SIZE_VEC4];} u_spp_index;out lowp float v_opacity; #ifdef RENDER_SDF out lowp vec4 v_fill_np_color;out lowp vec4 v_halo_np_color;out lowp float v_halo_width;out lowp float v_halo_blur; #endif #ifdef LIGHTING_3D_MODE out lowp float v_emissive_strength; #endif PropertyType getPropertyType(uint propertyIndex,uint dataDrivenMask,uint zoomDependentMask,uint offsetDwords) {PropertyType type;type.isDataDriven=(dataDrivenMask & (1u << propertyIndex)) !=0u;type.isZoomDependent=(zoomDependentMask & (1u << propertyIndex)) !=0u;type.offsetDwords=offsetDwords;return type;}SymbolPropertyHeader readSymbolPropertiesHeader() {SymbolPropertyHeader header;uint dataDrivenMask=u_spp_header.header[0][0];uint zoomDependentMask=u_spp_header.header[0][1];header.dataDrivenBlockSizeVec4=u_spp_header.header[0][2];header.fill_np_color =getPropertyType(0u,dataDrivenMask,zoomDependentMask,u_spp_header.header[0][3]);header.halo_np_color =getPropertyType(1u,dataDrivenMask,zoomDependentMask,u_spp_header.header[1][0]);header.opacity =getPropertyType(2u,dataDrivenMask,zoomDependentMask,u_spp_header.header[1][1]);header.halo_width =getPropertyType(3u,dataDrivenMask,zoomDependentMask,u_spp_header.header[1][2]);header.halo_blur =getPropertyType(4u,dataDrivenMask,zoomDependentMask,u_spp_header.header[1][3]);header.emissive_strength =getPropertyType(5u,dataDrivenMask,zoomDependentMask,u_spp_header.header[2][0]);header.occlusion_opacity =getPropertyType(6u,dataDrivenMask,zoomDependentMask,u_spp_header.header[2][1]);header.z_offset =getPropertyType(7u,dataDrivenMask,zoomDependentMask,u_spp_header.header[2][2]);header.translate =getPropertyType(8u,dataDrivenMask,zoomDependentMask,u_spp_header.header[2][3]);return header;}uint uvec4At(uvec4 v,uint index) {return (index==0u) ? v.x : (index==1u) ? v.y : (index==2u) ? v.z : v.w;}float vec4At(vec4 v,uint index) {return (index==0u) ? v.x : (index==1u) ? v.y : (index==2u) ? v.z : v.w;}vec4 readVec4(uint baseOffsetVec4,uint propertyOffsetDwords) {return u_spp_properties.properties[baseOffsetVec4+propertyOffsetDwords/DWORDS_PER_VEC4];}float readFloat(vec4 slot,uint propertyOffsetDwords) {return slot[propertyOffsetDwords % DWORDS_PER_VEC4];}uint readUint(uvec4 slot,uint offset) {return slot[offset % DWORDS_PER_VEC4];}vec2 readVec2(vec4 slot,uint propertyOffsetDwords) {float x=vec4At(slot,propertyOffsetDwords % DWORDS_PER_VEC4);float y=vec4At(slot,propertyOffsetDwords % DWORDS_PER_VEC4+1u);return vec2(x,y);}uint getDataDrivenBlockOffsetVec4(uint dataDrivenBlockSizeVec4) {uint featureIndex=uint(a_feature_index);uvec4 slot=u_spp_index.block_indices[featureIndex/DWORDS_PER_VEC4];uint blockIndex=uvec4At(slot,featureIndex % DWORDS_PER_VEC4);return blockIndex*dataDrivenBlockSizeVec4;}vec4 readColorProperty(PropertyType propertyType,uint dataDrivenBlockSizeVec4) {uint blockOffsetVec4=getDataDrivenBlockOffsetVec4(dataDrivenBlockSizeVec4);vec4 color=readVec4(blockOffsetVec4,propertyType.offsetDwords);if (propertyType.isZoomDependent) {color=unpack_mix_color(color,u_zoom);} else {vec2 packedColor=readVec2(color,propertyType.offsetDwords);color=decode_color(packedColor);}return color;}vec2 readVec2Property(PropertyType propertyType,uint dataDrivenBlockSizeVec4) {uint blockOffsetVec4=getDataDrivenBlockOffsetVec4(dataDrivenBlockSizeVec4);vec4 slot=readVec4(blockOffsetVec4,propertyType.offsetDwords);if (propertyType.isZoomDependent) {vec2 minVal=slot.xy;vec2 maxVal=slot.zw;return mix(minVal,maxVal,u_zoom);}return readVec2(slot,propertyType.offsetDwords);}float readFloatProperty(PropertyType propertyType,uint dataDrivenBlockSizeVec4) {uint blockOffsetVec4=getDataDrivenBlockOffsetVec4(dataDrivenBlockSizeVec4);vec4 slot=readVec4(blockOffsetVec4,propertyType.offsetDwords);float value;if (propertyType.isZoomDependent) {vec2 packedValues=readVec2(slot,propertyType.offsetDwords);value=unpack_mix_vec2(packedValues,u_zoom);} else {value=readFloat(slot,propertyType.offsetDwords);}return value;}SymbolPaintProperties readSymbolPaintProperties() {SymbolPropertyHeader header=readSymbolPropertiesHeader();uint sizeVec4=header.dataDrivenBlockSizeVec4;SymbolPaintProperties props;props.fill_np_color =header.fill_np_color.isDataDriven ? readColorProperty(header.fill_np_color,sizeVec4) : u_spp_fill_np_color;props.halo_np_color =header.halo_np_color.isDataDriven ? readColorProperty(header.halo_np_color,sizeVec4) : u_spp_halo_np_color;props.opacity =header.opacity.isDataDriven ? readFloatProperty(header.opacity,sizeVec4) : u_spp_opacity;props.halo_width =header.halo_width.isDataDriven ? readFloatProperty(header.halo_width,sizeVec4) : u_spp_halo_width;props.halo_blur =header.halo_blur.isDataDriven ? readFloatProperty(header.halo_blur,sizeVec4) : u_spp_halo_blur;props.emissive_strength =header.emissive_strength.isDataDriven ? readFloatProperty(header.emissive_strength,sizeVec4) : u_spp_emissive_strength;props.occlusion_opacity =header.occlusion_opacity.isDataDriven ? readFloatProperty(header.occlusion_opacity,sizeVec4) : u_spp_occlusion_opacity;props.z_offset =header.z_offset.isDataDriven ? readFloatProperty(header.z_offset,sizeVec4) : u_spp_z_offset;props.translate =header.translate.isDataDriven ? readVec2Property(header.translate,sizeVec4) : vec2(0.0);return props;} #else #pragma mapbox: define highp vec4 fill_color #pragma mapbox: define highp vec4 halo_color #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp float halo_width #pragma mapbox: define lowp float halo_blur #pragma mapbox: define lowp float emissive_strength #pragma mapbox: define lowp float occlusion_opacity #pragma mapbox: define lowp float z_offset #endif vec2 unpack_opacity(uint packedOpacity) {return vec2(float(packedOpacity/2u)/127.0,float(packedOpacity & 1u));}void main() { #ifdef USE_PAINT_PROPERTIES_UBO SymbolPaintProperties paint_properties=readSymbolPaintProperties();lowp float opacity=paint_properties.opacity;v_opacity=opacity; #ifdef RENDER_SDF v_fill_np_color=paint_properties.fill_np_color;v_halo_np_color=paint_properties.halo_np_color;v_halo_width=paint_properties.halo_width;v_halo_blur=paint_properties.halo_blur; #endif #ifdef LIGHTING_3D_MODE v_emissive_strength=paint_properties.emissive_strength; #endif lowp float occlusion_opacity=paint_properties.occlusion_opacity;lowp float z_offset=paint_properties.z_offset; #else #pragma mapbox: initialize highp vec4 fill_color #pragma mapbox: initialize highp vec4 halo_color #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize lowp float halo_width #pragma mapbox: initialize lowp float halo_blur #pragma mapbox: initialize lowp float emissive_strength #pragma mapbox: initialize lowp float occlusion_opacity #pragma mapbox: initialize lowp float z_offset #endif vec2 a_pos=vec2(a_pos_offset.xy);vec2 a_offset=vec2(a_pos_offset.zw);vec2 a_tex=vec2(a_tex_size.xy);vec2 a_size=vec2(a_tex_size.zw);float a_size_min=floor(a_size[0]*0.5);float a_size_max= floor(a_size[1]*0.5);float a_apperance=a_size[1]-2.0*a_size_max;vec2 a_pxoffset=vec2(a_pixeloffset.xy);vec2 a_min_font_scale=vec2(a_pixeloffset.zw)/256.0;highp float segment_angle=-a_projected_pos[3];float size;if (a_apperance==USING_APPEARANCE) {size=a_size_max/128.0;} else if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size_max,u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 tile_anchor=a_pos;float e=u_elevation_from_sea ? z_offset : z_offset+elevation(tile_anchor); #ifdef Z_OFFSET e+=a_auto_z_offset; #endif vec3 h=elevationVector(tile_anchor)*e;float globe_occlusion_fade;vec3 world_pos;vec3 mercator_pos;vec3 world_pos_globe; #ifdef PROJECTION_GLOBE_VIEW mercator_pos=mercator_tile_position(u_inv_rot_matrix,tile_anchor,u_tile_id,u_merc_center);world_pos_globe=vec3(a_globe_anchor)+h;world_pos=mix_globe_mercator(world_pos_globe,mercator_pos,u_zoom_transition);vec4 ecef_point=u_tile_matrix*vec4(world_pos,1.0);vec3 origin_to_point=ecef_point.xyz-u_ecef_origin;globe_occlusion_fade=dot(origin_to_point,u_camera_forward) >=0.0 ? 0.0 : 1.0; #else world_pos=vec3(tile_anchor,0)+h;globe_occlusion_fade=1.0; #endif vec4 projected_point=u_matrix*vec4(world_pos,1);highp float camera_to_anchor_distance=projected_point.w;highp float distance_ratio=u_pitch_with_map ? camera_to_anchor_distance/u_camera_to_center_distance : u_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp( 0.5+0.5*distance_ratio,0.0,1.5);size*=perspective_ratio;float font_scale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetprojected_point;vec2 a; #ifdef PROJECTION_GLOBE_VIEW vec3 displacement=vec3(a_globe_normal.z,0,-a_globe_normal.x);offsetprojected_point=u_matrix*vec4(vec3(a_globe_anchor)+displacement,1);vec4 projected_point_globe=u_matrix*vec4(world_pos_globe,1);a=projected_point_globe.xy/projected_point_globe.w; #else offsetprojected_point=u_matrix*vec4(tile_anchor+vec2(1,0),0,1);a=projected_point.xy/projected_point.w; #endif vec2 b=offsetprojected_point.xy/offsetprojected_point.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}vec4 projected_pos; #ifdef PROJECTION_GLOBE_VIEW #ifdef PROJECTED_POS_ON_VIEWPORT projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xyz+h,1.0); #else vec3 proj_pos=mix_globe_mercator(a_projected_pos.xyz,mercator_pos,u_zoom_transition)+h;projected_pos=u_label_plane_matrix*vec4(proj_pos,1.0); #endif #else projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,h.z,1.0); #endif highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);float z=0.0;vec2 offset=rotation_matrix*(a_offset/32.0*max(a_min_font_scale,font_scale)+a_pxoffset/16.0); #ifdef TERRAIN #ifdef PITCH_WITH_MAP_TERRAIN vec4 tile_pos=u_label_plane_matrix_inv*vec4(a_projected_pos.xy+offset,0.0,1.0);z=elevation(tile_pos.xy); #endif #endif #ifdef Z_OFFSET z+=u_pitch_with_map ? a_auto_z_offset+z_offset : 0.0; #else z+=u_pitch_with_map ? z_offset : 0.0; #endif float occlusion_fade=globe_occlusion_fade;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float out_fade_opacity=max(0.0,min(occlusion_fade,fade_opacity[0]+fade_change)); #ifdef DEPTH_OCCLUSION float depth_occlusion=occlusionFadeMultiSample(projected_point);float depth_occlusion_multplier=mix(occlusion_opacity,1.0,depth_occlusion);out_fade_opacity*=depth_occlusion_multplier; #endif #ifdef OCCLUSION_QUERIES float occludedFadeMultiplier=mix(occlusion_opacity,1.0,a_occlusion_query_opacity);out_fade_opacity*=occludedFadeMultiplier; #endif #ifdef Z_TEST_OCCLUSION out_fade_opacity*=occlusion_opacity; #endif float alpha=opacity*out_fade_opacity;float hidden=float(alpha==0.0 || projected_point.w <=0.0 || occlusion_fade==0.0);vec3 pos; #ifdef PROJECTION_GLOBE_VIEW vec3 xAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,u_up_vector)) : vec3(1,0,0);vec3 yAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,xAxis)) : vec3(0,1,0);pos=projected_pos.xyz/projected_pos.w+xAxis*offset.x+yAxis*offset.y; #else #ifdef ELEVATED_ROADS vec3 xAxis=vec3(a_x_axis.xy,a_x_axis.z*u_normal_scale);vec3 yAxis=vec3(a_y_axis.xy,a_y_axis.z*u_normal_scale);pos=projected_pos.xyz/projected_pos.w+xAxis*offset.x+yAxis*offset.y; #else pos=vec3(projected_pos.xy/projected_pos.w+offset,z); #endif #endif gl_Position=mix(u_coord_matrix*vec4(pos,1.0),AWAY,hidden); #ifdef USE_PAINT_PROPERTIES_UBO {vec2 tr=paint_properties.translate;vec2 rotated_tr=vec2( u_spp_translate_rotation.x*tr.x-u_spp_translate_rotation.y*tr.y,u_spp_translate_rotation.y*tr.x+u_spp_translate_rotation.x*tr.y );gl_Position.xy+=(u_coord_matrix*vec4(rotated_tr,0.0,0.0)).xy;} #endif float gamma_scale=gl_Position.w;v_draw_halo=(u_is_halo && float(gl_InstanceID)==0.0) ? 1.0 : 0.0;v_gamma_scale_size_fade_opacity=vec3(gamma_scale,size,out_fade_opacity);v_tex_a=a_tex/u_texsize; #ifdef RENDER_TEXT_AND_SYMBOL is_sdf=a_size[0]-2.0*a_size_min;v_tex_a_icon=a_tex/u_texsize_icon; #endif #ifdef ICON_TRANSITION v_tex_b=vec2(a_texb)/u_texsize; #endif #ifdef RENDER_SHADOWS vec4 shd_pos=u_inv_matrix*vec4(pos,1.0);vec3 shd_pos0=shd_pos.xyz;vec3 shd_pos1=shd_pos.xyz; #ifdef NORMAL_OFFSET vec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef INDICATOR_CUTOUT v_z_offset=e; #else #ifdef RENDER_SHADOWS v_z_offset=e; #endif #endif }`),terrainRaster:_o(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" uniform sampler2D u_image0; #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS uniform sampler2D u_image1;uniform float u_emissive_texture_available; #endif in vec2 v_pos0; #ifdef FOG in float v_fog_opacity; #endif #ifdef RENDER_SHADOWS in vec4 v_pos_light_view_0;in vec4 v_pos_light_view_1; #endif uniform vec3 u_ground_shadow_factor;void main() {vec4 image_color=texture(u_image0,v_pos0);vec4 color; #ifdef LIGHTING_3D_MODE const vec3 normal=vec3(0.0,0.0,1.0); #ifdef RENDER_SHADOWS float cutoffOpacity=1.0; #ifdef RENDER_CUTOFF cutoffOpacity=cutoff_opacity(u_cutoff_params,1.0/gl_FragCoord.w); #endif #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS float emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : image_color.a;vec3 unlit_base=image_color.rgb*(1.0-emissive_strength);vec3 emissive_base=image_color.rgb*emissive_strength;float ndotl=u_shadow_direction.z;float occlusion=ndotl < 0.0 ? 1.0 : shadow_occlusion(v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,0.0);ndotl=max(0.0,ndotl);vec3 lit=apply_lighting(unlit_base,normal,mix(1.0,(1.0-(u_shadow_intensity*occlusion))*ndotl,cutoffOpacity));vec3 emissive=compute_emissive_draped(emissive_base,1.0-u_shadow_intensity,occlusion,u_ground_shadow_factor);color.rgb=lit+emissive;color.a=1.0; #else float lighting_factor=shadowed_light_factor_normal_unbiased(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);color=apply_lighting(image_color,normal,mix(1.0,lighting_factor,cutoffOpacity)); #endif #else float lighting_factor=u_lighting_directional_dir.z;color=apply_lighting(image_color,normal,lighting_factor); #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS float emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : image_color.a;color.rgb=mix(color.rgb,image_color.rgb,emissive_strength);color.a=1.0; #endif #endif #else color=image_color; #endif #ifdef FOG #ifdef ZERO_EXAGGERATION color=fog_dither(fog_apply_premultiplied(color,v_fog_pos)); #else color=fog_dither(fog_apply_from_vert(color,v_fog_opacity)); #endif #endif glFragColor=color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" uniform mat4 u_matrix;uniform float u_skirt_height;in ivec2 a_pos;out vec2 v_pos0; #ifdef FOG out float v_fog_opacity; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out vec4 v_pos_light_view_0;out vec4 v_pos_light_view_1; #endif void main() {vec3 decomposedPosAndSkirt=decomposeToPosAndSkirt(a_pos);float skirt=decomposedPosAndSkirt.z;vec2 decodedPos=decomposedPosAndSkirt.xy;float elevation=elevation(decodedPos)-skirt*u_skirt_height;v_pos0=decodedPos/8192.0;gl_Position=u_matrix*vec4(decodedPos,elevation,1.0); #ifdef FOG #ifdef ZERO_EXAGGERATION v_fog_pos=fog_position(decodedPos); #else v_fog_opacity=fog(fog_position(vec3(decodedPos,elevation))); #endif #endif #ifdef RENDER_SHADOWS vec3 pos=vec3(decodedPos,elevation);v_pos_light_view_0=u_light_matrix_0*vec4(pos,1.);v_pos_light_view_1=u_light_matrix_1*vec4(pos,1.); #endif }`),terrainDepth:_o("precision highp float;in float v_depth;void main() {glFragColor=pack_depth(v_depth);}",`#include "_prelude_terrain.vertex.glsl" uniform mat4 u_matrix;in ivec2 a_pos;out float v_depth;void main() {float elevation=elevation(vec2(a_pos));gl_Position=u_matrix*vec4(a_pos,elevation,1.0);v_depth=gl_Position.z/gl_Position.w;}`),skybox:_o(`#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 }`,H_),skyboxGradient:_o(`#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 }`,H_),skyboxCapture:_o(` in highp vec3 v_position;uniform highp float u_sun_intensity;uniform highp float u_luminance;uniform lowp vec3 u_sun_direction;uniform highp vec4 u_color_tint_r;uniform highp vec4 u_color_tint_m;precision highp float; #define BETA_R vec3(5.5e-6,13.0e-6,22.4e-6) #define BETA_M vec3(21e-6,21e-6,21e-6) #define MIE_G 0.76 #define DENSITY_HEIGHT_SCALE_R 8000.0 #define DENSITY_HEIGHT_SCALE_M 1200.0 #define PLANET_RADIUS 6360e3 #define ATMOSPHERE_RADIUS 6420e3 #define SAMPLE_STEPS 10 #define DENSITY_STEPS 4 float ray_sphere_exit(vec3 orig,vec3 dir,float radius) {float a=dot(dir,dir);float b=2.0*dot(dir,orig);float c=dot(orig,orig)-radius*radius;float d=sqrt(b*b-4.0*a*c);return (-b+d)/(2.0*a);}vec3 extinction(vec2 density) {return exp(-vec3(BETA_R*u_color_tint_r.a*density.x+BETA_M*u_color_tint_m.a*density.y));}vec2 local_density(vec3 point) {float height=max(length(point)-PLANET_RADIUS,0.0);float exp_r=exp(-height/DENSITY_HEIGHT_SCALE_R);float exp_m=exp(-height/DENSITY_HEIGHT_SCALE_M);return vec2(exp_r,exp_m);}float phase_ray(float cos_angle) {return (3.0/(16.0*PI))*(1.0+cos_angle*cos_angle);}float phase_mie(float cos_angle) {return (3.0/(8.0*PI))*((1.0-MIE_G*MIE_G)*(1.0+cos_angle*cos_angle))/((2.0+MIE_G*MIE_G)*pow(1.0+MIE_G*MIE_G-2.0*MIE_G*cos_angle,1.5));}vec2 density_to_atmosphere(vec3 point,vec3 light_dir) {float ray_len=ray_sphere_exit(point,light_dir,ATMOSPHERE_RADIUS);float step_len=ray_len/float(DENSITY_STEPS);vec2 density_point_to_atmosphere=vec2(0.0);for (int i=0; i < DENSITY_STEPS;++i) {vec3 point_on_ray=point+light_dir*((float(i)+0.5)*step_len);density_point_to_atmosphere+=local_density(point_on_ray)*step_len;;}return density_point_to_atmosphere;}vec3 atmosphere(vec3 ray_dir,vec3 sun_direction,float sun_intensity) {vec2 density_orig_to_point=vec2(0.0);vec3 scatter_r=vec3(0.0);vec3 scatter_m=vec3(0.0);vec3 origin=vec3(0.0,PLANET_RADIUS,0.0);float ray_len=ray_sphere_exit(origin,ray_dir,ATMOSPHERE_RADIUS);float step_len=ray_len/float(SAMPLE_STEPS);for (int i=0; i < SAMPLE_STEPS;++i) {vec3 point_on_ray=origin+ray_dir*((float(i)+0.5)*step_len);vec2 density=local_density(point_on_ray)*step_len;density_orig_to_point+=density;vec2 density_point_to_atmosphere=density_to_atmosphere(point_on_ray,sun_direction);vec2 density_orig_to_atmosphere=density_orig_to_point+density_point_to_atmosphere;vec3 extinction=extinction(density_orig_to_atmosphere);scatter_r+=density.x*extinction;scatter_m+=density.y*extinction;}float cos_angle=dot(ray_dir,sun_direction);float phase_r=phase_ray(cos_angle);float phase_m=phase_mie(cos_angle);vec3 beta_r=BETA_R*u_color_tint_r.rgb*u_color_tint_r.a;vec3 beta_m=BETA_M*u_color_tint_m.rgb*u_color_tint_m.a;return (scatter_r*phase_r*beta_r+scatter_m*phase_m*beta_m)*sun_intensity;}const float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;vec3 uncharted2_tonemap(vec3 x) {return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;}void main() {vec3 ray_direction=v_position;ray_direction.y=pow(ray_direction.y,5.0);const float y_bias=0.015;ray_direction.y+=y_bias;vec3 color=atmosphere(normalize(ray_direction),u_sun_direction,u_sun_intensity);float white_scale=1.0748724675633854;color=uncharted2_tonemap((log2(2.0/pow(u_luminance,4.0)))*color)*white_scale;glFragColor=vec4(color,1.0);}`,"in highp vec3 a_pos_3f;uniform mat3 u_matrix_3f;out highp vec3 v_position;float map(float value,float start,float end,float new_start,float new_end) {return ((value-start)*(new_end-new_start))/(end-start)+new_start;}void main() {vec4 pos=vec4(u_matrix_3f*a_pos_3f,1.0);v_position=pos.xyz;v_position.y*=-1.0;v_position.y=map(v_position.y,-1.0,1.0,0.0,1.0);gl_Position=vec4(a_pos_3f.xy,0.0,1.0);}"),globeRaster:_o(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform sampler2D u_image0; #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS uniform sampler2D u_image1;uniform float u_emissive_texture_available; #endif uniform float u_far_z_cutoff;in vec2 v_pos0; #ifndef FOG uniform highp vec3 u_frustum_tl;uniform highp vec3 u_frustum_tr;uniform highp vec3 u_frustum_br;uniform highp vec3 u_frustum_bl;uniform highp vec3 u_globe_pos;uniform highp float u_globe_radius;uniform vec2 u_viewport; #endif void main() {vec4 color; #ifdef CUSTOM_ANTIALIASING highp vec2 uv=gl_FragCoord.xy/u_viewport; #ifdef FLIP_Y uv.y=1.0-uv.y; #endif highp vec3 ray_dir=mix( mix(u_frustum_tl,u_frustum_tr,uv.x),mix(u_frustum_bl,u_frustum_br,uv.x),1.0-uv.y);highp vec3 dir=normalize(ray_dir);highp vec3 closest_point=dot(u_globe_pos,dir)*dir;highp float norm_dist_from_center=1.0-length(closest_point-u_globe_pos)/u_globe_radius;const float antialias_pixel=2.0;highp float antialias_factor=antialias_pixel*fwidth(norm_dist_from_center);highp float antialias=smoothstep(0.0,antialias_factor,norm_dist_from_center);vec4 raster=texture(u_image0,v_pos0); #ifdef LIGHTING_3D_MODE #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS float emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : raster.a;raster=apply_lighting_with_emission_ground(raster,emissive_strength);color=vec4(clamp(raster.rgb,vec3(0),vec3(1))*antialias,antialias); #else raster=apply_lighting_ground(raster);color=vec4(raster.rgb*antialias,raster.a*antialias); #endif #else color=vec4(raster.rgb*antialias,raster.a*antialias); #endif #else color=texture(u_image0,v_pos0); #ifdef LIGHTING_3D_MODE #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS float emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : color.a;color=apply_lighting_with_emission_ground(color,emissive_strength);color.a=1.0; #else color=apply_lighting_ground(color); #endif #endif #endif #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos)); #endif color*=1.0-step(u_far_z_cutoff,1.0/gl_FragCoord.w);glFragColor=color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" uniform mat4 u_proj_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform float u_zoom_transition;uniform vec2 u_merc_center;uniform mat3 u_grid_matrix;uniform float u_skirt_height; #ifdef GLOBE_POLES in vec3 a_globe_pos;in vec2 a_uv; #else in ivec2 a_pos; #endif out vec2 v_pos0;void main() { #ifdef GLOBE_POLES vec3 globe_pos=a_globe_pos;vec2 uv=a_uv; #else float tiles=u_grid_matrix[0][2];float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];vec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);float mercatorY=mercatorYfromLat(latLng[0]);float uvY=mercatorY*tiles-idy;float mercatorX=mercatorXfromLng(latLng[1]);float uvX=mercatorX*tiles-idx;vec3 globe_pos=latLngToECEF(latLng.xy);vec2 merc_pos=vec2(mercatorX,mercatorY);vec2 uv=vec2(uvX,uvY); #endif v_pos0=uv;vec2 tile_pos=uv*EXTENT;vec3 globe_derived_up_vector=normalize(globe_pos)*u_tile_up_scale; #ifdef GLOBE_POLES vec3 up_vector=globe_derived_up_vector; #else vec3 up_vector=elevationVector(tile_pos); #endif float height=elevation(tile_pos);globe_pos+=up_vector*height; #ifndef GLOBE_POLES globe_pos-=globe_derived_up_vector*u_skirt_height*decomposed_pos_and_skirt.z; #endif #ifdef GLOBE_POLES vec4 interpolated_pos=u_globe_matrix*vec4(globe_pos,1.0); #else vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);vec4 merc_world_pos=vec4(0.0);if (u_zoom_transition > 0.0) {merc_world_pos=vec4(merc_pos,height-u_skirt_height*decomposed_pos_and_skirt.z,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;}vec4 interpolated_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition),1.0); #endif gl_Position=u_proj_matrix*interpolated_pos; #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz); #endif }`),globeAtmosphere:_o(`#include "_prelude_fog.fragment.glsl" uniform float u_transition;uniform highp float u_fadeout_range;uniform highp float u_temporal_offset;uniform vec4 u_atmosphere_fog_color;uniform vec4 u_high_color;uniform vec4 u_space_color;uniform float u_horizon_angle;in highp vec3 v_ray_dir;in highp vec3 v_horizon_dir;void main() {highp vec3 dir=normalize(v_ray_dir);float globe_pos_dot_dir; #ifdef PROJECTION_GLOBE_VIEW globe_pos_dot_dir=dot(u_globe_pos,dir);highp vec3 closest_point_forward=abs(globe_pos_dot_dir)*dir;float norm_dist_from_center=length(closest_point_forward-u_globe_pos)/u_globe_radius;if (norm_dist_from_center < 0.98) { #ifdef ALPHA_PASS glFragColor=vec4(0,0,0,0);return; #else #ifdef NATIVE glFragColor=vec4(1,1,1,1); #else glFragColor=vec4(0,0,0,1); #endif return; #endif } #endif highp vec3 horizon_dir=normalize(v_horizon_dir);float horizon_angle_mercator=dir.y < horizon_dir.y ? 0.0 : max(acos(clamp(dot(dir,horizon_dir),-1.0,1.0)),0.0);float horizon_angle; #ifdef PROJECTION_GLOBE_VIEW highp vec3 closest_point=globe_pos_dot_dir*dir;highp float closest_point_to_center=length(closest_point-u_globe_pos);highp float theta=asin(clamp(closest_point_to_center/length(u_globe_pos),-1.0,1.0));horizon_angle=globe_pos_dot_dir < 0.0 ? PI-theta-u_horizon_angle : theta-u_horizon_angle;float angle_t=pow(u_transition,10.0);horizon_angle=mix(horizon_angle,horizon_angle_mercator,angle_t); #else horizon_angle=horizon_angle_mercator; #endif horizon_angle/=PI;float t=exp(-horizon_angle/u_fadeout_range);float alpha_0=u_atmosphere_fog_color.a;float alpha_1=u_high_color.a;float alpha_2=u_space_color.a;vec3 color_stop_0=u_atmosphere_fog_color.rgb;vec3 color_stop_1=u_high_color.rgb;vec3 color_stop_2=u_space_color.rgb; #ifdef ALPHA_PASS float a0=mix(alpha_2,1.0,alpha_1);float a1=mix(a0,1.0,alpha_0);float a2=mix(a0,a1,t);float a =mix(alpha_2,a2,t);glFragColor=vec4(1.0,1.0,1.0,a); #else vec3 c0=mix(color_stop_2,color_stop_1,alpha_1);vec3 c1=mix(c0,color_stop_0,alpha_0);vec3 c2=mix(c0,c1,t);vec3 c=c2;glFragColor=vec4(c*t,t); #endif }`,`in vec3 a_pos;in vec2 a_uv;uniform vec3 u_frustum_tl;uniform vec3 u_frustum_tr;uniform vec3 u_frustum_br;uniform vec3 u_frustum_bl;uniform float u_horizon;out highp vec3 v_ray_dir;out highp vec3 v_horizon_dir;void main() {v_ray_dir=mix( mix(u_frustum_tl,u_frustum_tr,a_uv.x),mix(u_frustum_bl,u_frustum_br,a_uv.x),a_uv.y);v_horizon_dir=mix( mix(u_frustum_tl,u_frustum_bl,u_horizon),mix(u_frustum_tr,u_frustum_br,u_horizon),a_uv.x);gl_Position=vec4(a_pos,1.0);}`),model:_o(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" uniform float u_opacity; #ifdef DITHERED_DISCARD uniform float u_dithered_discard_threshold; #endif uniform vec3 u_lightcolor;uniform vec3 u_lightpos;uniform float u_lightintensity;uniform vec4 u_baseColorFactor;uniform vec4 u_emissiveFactor;uniform float u_metallicFactor;uniform float u_roughnessFactor;uniform float u_emissive_strength;in highp vec4 v_position_height;in lowp vec4 v_color_mix; #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in float v_depth_shadows; #endif #ifdef OCCLUSION_TEXTURE_TRANSFORM uniform vec4 u_occlusionTextureTransform; #endif #pragma mapbox: define-attribute highp vec3 normal_3f #pragma mapbox: define-attribute highp vec3 color_3f #pragma mapbox: define-attribute highp vec4 color_4f #pragma mapbox: define-attribute highp vec2 uv_2f #pragma mapbox: initialize-attribute highp vec3 normal_3f #pragma mapbox: initialize-attribute highp vec3 color_3f #pragma mapbox: initialize-attribute highp vec4 color_4f #pragma mapbox: initialize-attribute highp vec2 uv_2f #ifdef HAS_ATTRIBUTE_a_pbr in lowp vec4 v_roughness_metallic_emissive_alpha;in mediump vec4 v_height_based_emission_params; #endif #ifdef HAS_TEXTURE_u_baseColorTexture uniform sampler2D u_baseColorTexture;uniform bool u_baseTextureIsAlpha;uniform bool u_alphaMask;uniform float u_alphaCutoff; #endif #ifdef HAS_TEXTURE_u_metallicRoughnessTexture uniform sampler2D u_metallicRoughnessTexture; #endif #ifdef HAS_TEXTURE_u_occlusionTexture uniform sampler2D u_occlusionTexture;uniform float u_aoIntensity; #endif #ifdef HAS_TEXTURE_u_normalTexture uniform sampler2D u_normalTexture; #endif #ifdef HAS_TEXTURE_u_emissionTexture uniform sampler2D u_emissionTexture; #endif #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #ifdef TERRAIN_FRAGMENT_OCCLUSION in highp float v_depth;uniform highp sampler2D u_depthTexture;uniform highp vec2 u_inv_depth_size;uniform highp vec2 u_depth_range_unpack; #ifdef DEPTH_D24 highp float unpack_depth(highp float depth) {return depth*u_depth_range_unpack.x+u_depth_range_unpack.y;} #else highp float unpack_depth_rgba(highp vec4 rgba_depth) {const highp vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(rgba_depth,bit_shift)*2.0-1.0;} #endif bool isOccluded() {highp vec2 coord=gl_FragCoord.xy*u_inv_depth_size; #ifdef FLIP_Y coord.y=1.0-coord.y; #endif #ifdef DEPTH_D24 highp float depth=unpack_depth(texture(u_depthTexture,coord).r); #else highp float depth=unpack_depth_rgba(texture(u_depthTexture,coord)); #endif return v_depth > depth+0.0005;} #endif #define saturate(_x) clamp(_x,0.,1.) vec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}float calculate_NdotL(vec3 normal,vec3 lightDir) {const float ext=0.70710678118;return (clamp(dot(normal,lightDir),-ext,1.0)+ext)/(1.0+ext);}vec3 getDiffuseShadedColor(vec3 albedo,vec3 normal,vec3 lightDir,vec3 lightColor) { #ifdef LIGHTING_3D_MODE vec3 transformed_normal=vec3(-normal.xy,normal.z);float lighting_factor; #ifdef RENDER_SHADOWS lighting_factor=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth_shadows); #else lighting_factor=saturate(dot(transformed_normal,u_lighting_directional_dir)); #endif return apply_lighting(albedo,transformed_normal,lighting_factor); #else vec3 n=normal;float colorvalue=((albedo.x*0.2126)+(albedo.y*0.7152))+(albedo.z*0.0722);vec3 c=vec3(0.03,0.03,0.03);float directional=clamp(dot(n,vec3(lightDir)),0.0,1.0);directional=mix(1.0-u_lightintensity,max((1.0-colorvalue)+u_lightintensity,1.0),directional);vec3 c3=c+clamp((albedo*directional)*lightColor,mix(vec3(0.0),vec3(0.3),vec3(1.0)-lightColor),vec3(1.0));return c3; #endif }vec4 getBaseColor() {vec4 albedo=u_baseColorFactor; #ifdef HAS_ATTRIBUTE_a_color_3f albedo*=vec4(color_3f,1.0); #endif #ifdef HAS_ATTRIBUTE_a_pbr #else #ifdef HAS_ATTRIBUTE_a_color_4f albedo*=color_4f; #endif #endif #if defined (HAS_TEXTURE_u_baseColorTexture) && defined (HAS_ATTRIBUTE_a_uv_2f) vec4 texColor=texture(u_baseColorTexture,uv_2f);if(u_alphaMask) {if (texColor.w < u_alphaCutoff) {discard;}} #ifdef UNPREMULT_TEXTURE_IN_SHADER if(texColor.w > 0.0) {texColor.rgb/=texColor.w;}texColor.w=1.0; #endif if(u_baseTextureIsAlpha) {if (texColor.r < 0.5) {discard;}} else {texColor.rgb=sRGBToLinear(texColor.rgb);albedo*=texColor;} #endif vec4 color=vec4(mix(albedo.rgb,v_color_mix.rgb,v_color_mix.a),albedo.a); #ifdef APPLY_LUT_ON_GPU color=applyLUT(u_lutTexture,color); #endif return color;}highp mat3 cotangentFrame(highp vec3 N,highp vec3 p,highp vec2 uv ) { #ifdef HAS_TEXTURE_u_normalTexture highp vec3 dp1=vec3(dFdx(p.x),dFdx(p.y),dFdx(p.z));highp vec3 dp2=vec3(dFdy(p.x),dFdy(p.y),dFdy(p.z));highp vec2 duv1=vec2(dFdx(uv.x),dFdx(uv.y));highp vec2 duv2=vec2(dFdy(uv.x),dFdy(uv.y));highp vec3 dp2perp=cross( dp2,N );highp vec3 dp1perp=cross( N,dp1 );highp vec3 T=dp2perp*duv1.x+dp1perp*duv2.x;highp vec3 B=dp2perp*duv1.y+dp1perp*duv2.y; #ifdef FLIP_Y T=-T;B=-B; #endif highp float lengthT=dot(T,T);highp float lengthB=dot(B,B);highp float maxLength=max(lengthT,lengthB);highp float invmax=inversesqrt( maxLength );highp mat3 res=mat3( T*invmax,B*invmax,N );return res; #else return mat3(1.0); #endif }highp vec3 getNormal(){highp vec3 n; #ifdef HAS_ATTRIBUTE_a_normal_3f n=normalize(normal_3f); #else highp vec3 fdx=vec3(dFdx(v_position_height.x),dFdx(v_position_height.y),dFdx(v_position_height.z));highp vec3 fdy=vec3(dFdy(v_position_height.x),dFdy(v_position_height.y),dFdy(v_position_height.z)); #ifdef FLIP_Y n=normalize(cross(fdx,fdy)); #else n=normalize(cross(fdx,fdy))*-1.0; #endif #endif #if defined(HAS_TEXTURE_u_normalTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) vec3 nMap=texture( u_normalTexture,uv_2f).xyz;nMap=normalize(2.0*nMap-vec3(1.0));highp vec3 v=normalize(-v_position_height.xyz);highp mat3 TBN=cotangentFrame(n,v,uv_2f);n=normalize(TBN*nMap); #endif return n;}struct Material {float perceptualRoughness;float alphaRoughness;float metallic;vec3 f90;vec4 baseColor;vec3 diffuseColor;vec3 specularColor;highp vec3 normal;};Material getPBRMaterial() {Material mat;mat.baseColor=getBaseColor();mat.perceptualRoughness=u_roughnessFactor;mat.metallic=u_metallicFactor; #ifdef HAS_ATTRIBUTE_a_pbr mat.perceptualRoughness=v_roughness_metallic_emissive_alpha.x;mat.metallic=v_roughness_metallic_emissive_alpha.y;mat.baseColor.w*=v_roughness_metallic_emissive_alpha.w; #endif #if defined(HAS_TEXTURE_u_metallicRoughnessTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) vec4 mrSample=texture(u_metallicRoughnessTexture,uv_2f);mat.perceptualRoughness*=mrSample.g;mat.metallic*=mrSample.b; #endif const float c_minRoughness=0.04;mat.perceptualRoughness=clamp(mat.perceptualRoughness,c_minRoughness,1.0);mat.metallic=saturate(mat.metallic);mat.alphaRoughness=mat.perceptualRoughness*mat.perceptualRoughness;const vec3 f0=vec3(0.04);mat.diffuseColor=mat.baseColor.rgb*(vec3(1.0)-f0);mat.diffuseColor*=1.0-mat.metallic;mat.specularColor=mix(f0,mat.baseColor.rgb,mat.metallic);highp float reflectance=max(max(mat.specularColor.r,mat.specularColor.g),mat.specularColor.b);highp float reflectance90=saturate(reflectance*25.0);mat.f90=vec3(reflectance90);mat.normal=getNormal();return mat;}float V_GGX(float NdotL,float NdotV,float roughness) {float a2=roughness*roughness;float GGXV=NdotL*sqrt(NdotV*NdotV*(1.0-a2)+a2);float GGXL=NdotV*sqrt(NdotL*NdotL*(1.0-a2)+a2);return 0.5/(GGXV+GGXL);}float V_GGXFast(float NdotL,float NdotV,float roughness) {float a=roughness;float GGXV=NdotL*(NdotV*(1.0-a)+a);float GGXL=NdotV*(NdotL*(1.0-a)+a);return 0.5/(GGXV+GGXL);}vec3 F_Schlick(vec3 specularColor,vec3 f90,float VdotH) {return specularColor+(f90-specularColor)*pow(clamp(1.0-VdotH,0.0,1.0),5.0);}vec3 F_SchlickFast(vec3 specularColor,float VdotH) {float x=1.0-VdotH;float x4=x*x*x*x;return specularColor+(1.0-specularColor)*x4*x;}float D_GGX(highp float NdotH,float alphaRoughness) {highp float a4=alphaRoughness*alphaRoughness;highp float f=(NdotH*a4-NdotH)*NdotH+1.0;return a4/(PI*f*f);}vec3 diffuseBurley(Material mat,float LdotH,float NdotL,float NdotV) {float f90=2.0*LdotH*LdotH*mat.alphaRoughness-0.5;return (mat.diffuseColor/PI)*(1.0+f90*pow((1.0-NdotL),5.0))*(1.0+f90*pow((1.0-NdotV),5.0));}vec3 diffuseLambertian(Material mat) { #ifdef LIGHTING_3D_MODE return mat.diffuseColor; #else return mat.diffuseColor/PI; #endif }vec3 EnvBRDFApprox(vec3 specularColor,float roughness,highp float NdotV) {vec4 c0=vec4(-1,-0.0275,-0.572,0.022);vec4 c1=vec4(1,0.0425,1.04,-0.04);highp vec4 r=roughness*c0+c1;highp float a004=min(r.x*r.x,exp2(-9.28*NdotV))*r.x+r.y;vec2 AB=vec2(-1.04,1.04)*a004+r.zw;return specularColor*AB.x+AB.y;}vec3 computeIndirectLightContribution(Material mat,float NdotV,vec3 normal) {vec3 env_light=vec3(0.65,0.65,0.65); #ifdef LIGHTING_3D_MODE float ambient_factor=calculate_ambient_directional_factor(normal);env_light=u_lighting_ambient_color*ambient_factor; #endif vec3 envBRDF=EnvBRDFApprox(mat.specularColor,mat.perceptualRoughness,NdotV);vec3 indirectSpecular= envBRDF*env_light;vec3 indirectDiffuse=mat.diffuseColor*env_light;return indirectSpecular+indirectDiffuse;}vec3 computeLightContribution(Material mat,vec3 lightPosition,vec3 lightColor) {highp vec3 n=mat.normal;highp vec3 v=normalize(-v_position_height.xyz);highp vec3 l=normalize(lightPosition);highp vec3 h=normalize(v+l);float NdotV=clamp(abs(dot(n,v)),0.001,1.0);float NdotL=saturate(dot(n,l));highp float NdotH=saturate(dot(n,h));float VdotH=saturate(dot(v,h));vec3 f=F_SchlickFast(mat.specularColor,VdotH);float g=V_GGXFast(NdotL,NdotV,mat.alphaRoughness);float d=D_GGX(NdotH,mat.alphaRoughness);vec3 diffuseTerm=(1.0-f)*diffuseLambertian(mat);vec3 specularTerm=f*g*d;vec3 transformed_normal=vec3(-n.xy,n.z);float lighting_factor; #ifdef RENDER_SHADOWS lighting_factor=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth_shadows); #else lighting_factor=NdotL; #endif vec3 directLightColor=(specularTerm+diffuseTerm)*lighting_factor*lightColor;vec3 indirectLightColor=computeIndirectLightContribution(mat,NdotV,transformed_normal);vec3 color=(saturate(directLightColor)+indirectLightColor);float intensityFactor=1.0; #if !defined(LIGHTING_3D_MODE) const vec3 luminosityFactor=vec3(0.2126,0.7152,0.0722);float luminance=dot(diffuseTerm,luminosityFactor);intensityFactor=mix((1.0-u_lightintensity),max((1.0-luminance+u_lightintensity),1.0),NdotL); #endif color*=intensityFactor;return color;}void main() { #ifdef TERRAIN_FRAGMENT_OCCLUSION if (isOccluded()) {discard;} #endif vec3 lightDir=u_lightpos;vec3 lightColor=u_lightcolor; #ifdef LIGHTING_3D_MODE lightDir=u_lighting_directional_dir;lightDir.xy=-lightDir.xy;lightColor=u_lighting_directional_color; #endif vec4 finalColor; #ifdef DIFFUSE_SHADED vec3 N=getNormal();vec3 baseColor=getBaseColor().rgb;vec3 diffuse=getDiffuseShadedColor(baseColor,N,lightDir,lightColor); #ifdef HAS_TEXTURE_u_occlusionTexture float ao=(texture(u_occlusionTexture,uv_2f).r-1.0)*u_aoIntensity+1.0;diffuse*=ao; #endif finalColor=vec4(mix(diffuse,baseColor,u_emissive_strength),1.0)*u_opacity; #else Material mat=getPBRMaterial();vec3 color=computeLightContribution(mat,lightDir,lightColor);float ao=1.0; #if defined (HAS_TEXTURE_u_occlusionTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) #ifdef OCCLUSION_TEXTURE_TRANSFORM vec2 uv=uv_2f.xy*u_occlusionTextureTransform.zw+u_occlusionTextureTransform.xy; #else vec2 uv=uv_2f; #endif ao=(texture(u_occlusionTexture,uv).x-1.0)*u_aoIntensity+1.0;color*=ao; #endif vec4 emissive=u_emissiveFactor; #if defined(HAS_TEXTURE_u_emissionTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) emissive.rgb*=sRGBToLinear(texture(u_emissionTexture,uv_2f).rgb); #endif #ifdef APPLY_LUT_ON_GPU float emissiveFactorLength=max(length(u_emissiveFactor.rgb),0.001);emissive.rgb=sRGBToLinear(applyLUT(u_lutTexture,linearTosRGB(emissive.rgb/emissiveFactorLength).rbg))*emissiveFactorLength; #endif color+=emissive.rgb;float opacity=mat.baseColor.w*u_opacity; #ifdef HAS_ATTRIBUTE_a_pbr float resEmission=v_roughness_metallic_emissive_alpha.z;resEmission*=v_height_based_emission_params.z+v_height_based_emission_params.w*pow(clamp(v_height_based_emission_params.x,0.0,1.0),v_height_based_emission_params.y);vec3 color_mix=v_color_mix.rgb; #ifdef APPLY_LUT_ON_GPU color_mix=applyLUT(u_lutTexture,color_mix); #endif color=mix(color,color_mix,min(1.0,resEmission)); #ifdef HAS_ATTRIBUTE_a_color_4f float distance=length(vec2(1.3*max(0.0,abs(color_4f.x)-color_4f.z),color_4f.y));distance+= mix(0.5,0.0,clamp(resEmission-1.0,0.0,1.0));opacity*=v_roughness_metallic_emissive_alpha.w*saturate(1.0-distance*distance); #endif #endif vec3 unlitColor=mat.baseColor.rgb*ao+emissive.rgb;color=mix(color,unlitColor,u_emissive_strength);color=linearTosRGB(color);color*=opacity;finalColor=vec4(color,opacity); #endif #ifdef DITHERED_DISCARD if (abs(u_dithered_discard_threshold) < 1.0) {float ditherValue=fract(52.9829189*fract(0.06711056*gl_FragCoord.x+0.00583715*gl_FragCoord.y));float compareValue=mix(1.0-ditherValue,ditherValue,step(0.0,u_dithered_discard_threshold));if (abs(u_dithered_discard_threshold) < compareValue) {discard;}} #endif #ifdef FOG finalColor=fog_dither(fog_apply_premultiplied(finalColor,v_fog_pos,v_position_height.w)); #endif #ifdef RENDER_CUTOFF finalColor*=v_cutoff_opacity; #endif #ifdef INDICATOR_CUTOUT finalColor=applyCutout(finalColor,v_position_height.w); #endif #ifdef FEATURE_CUTOUT finalColor=apply_feature_cutout(finalColor,gl_FragCoord,get_cutout_factors(gl_FragCoord).x); #endif glFragColor=finalColor; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in vec3 a_pos_3f; #pragma mapbox: define-attribute highp vec3 normal_3f #pragma mapbox: define-attribute highp vec2 uv_2f #pragma mapbox: define-attribute highp vec3 color_3f #pragma mapbox: define-attribute highp vec4 color_4f #pragma mapbox: define-attribute-vertex-shader-only highp uvec4 pbr #pragma mapbox: define-attribute-vertex-shader-only highp vec3 heightBasedEmissiveStrength uniform mat4 u_matrix;uniform mat4 u_node_matrix;uniform mat4 u_lighting_matrix;uniform vec3 u_camera_pos;uniform vec4 u_color_mix; #ifdef INSTANCED_ARRAYS in vec4 a_normal_matrix0;in vec4 a_normal_matrix1;in vec4 a_normal_matrix2;in vec4 a_normal_matrix3; #else uniform highp mat4 u_normal_matrix; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out float v_depth_shadows; #endif out vec4 v_position_height;out lowp vec4 v_color_mix; #ifdef TERRAIN_FRAGMENT_OCCLUSION out highp float v_depth; #endif #ifdef HAS_ATTRIBUTE_a_pbr out lowp vec4 v_roughness_metallic_emissive_alpha;out mediump vec4 v_height_based_emission_params; #endif vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}void main() { #pragma mapbox: initialize-attribute highp vec3 normal_3f #pragma mapbox: initialize-attribute highp vec2 uv_2f #pragma mapbox: initialize-attribute highp vec3 color_3f #pragma mapbox: initialize-attribute highp vec4 color_4f #pragma mapbox: initialize-attribute-custom highp uvec4 pbr #pragma mapbox: initialize-attribute-custom highp vec3 heightBasedEmissiveStrength highp mat4 normal_matrix; #ifdef INSTANCED_ARRAYS normal_matrix=mat4(a_normal_matrix0,a_normal_matrix1,a_normal_matrix2,a_normal_matrix3); #else normal_matrix=u_normal_matrix; #endif vec3 local_pos;mat3 rs; #ifdef MODEL_POSITION_ON_GPU vec3 pos_color=normal_matrix[0].xyz;vec4 translate=normal_matrix[1];vec3 pos_a=floor(pos_color);vec3 rgb=1.05*(pos_color-pos_a);float hidden=float(pos_a.x > EXTENT);float color_mix=pos_a.z/100.0;v_color_mix=vec4(sRGBToLinear(rgb),color_mix);float meter_to_tile=normal_matrix[0].w;vec4 pos=vec4(pos_a.xy,translate.z,1.0);rs[0].x=normal_matrix[1].w;rs[0].yz=normal_matrix[2].xy;rs[1].xy=normal_matrix[2].zw;rs[1].z=normal_matrix[3].x;rs[2].xyz=normal_matrix[3].yzw;vec4 pos_node=u_lighting_matrix*vec4(a_pos_3f,1.0);vec3 rotated_pos_node=rs*pos_node.xyz;vec3 pos_model_tile=(rotated_pos_node+vec3(translate.xy,0.0))*vec3(meter_to_tile,meter_to_tile,1.0);pos.xyz+=pos_model_tile;local_pos=pos.xyz;gl_Position=mix(u_matrix*pos,AWAY,hidden);pos.z*=meter_to_tile;v_position_height.xyz=pos.xyz-u_camera_pos; #else local_pos=a_pos_3f;gl_Position=u_matrix*vec4(a_pos_3f,1);v_position_height.xyz=vec3(u_lighting_matrix*vec4(a_pos_3f,1));v_color_mix=vec4(sRGBToLinear(u_color_mix.rgb),u_color_mix.a); #endif v_position_height.w=a_pos_3f.z; #ifdef HAS_ATTRIBUTE_a_pbr vec4 albedo_c=decode_color(vec2(pbr.xy));vec2 e_r_m=unpack_float(float(pbr.z));vec2 r_m= unpack_float(e_r_m.y*16.0);r_m.r=r_m.r*16.0;v_color_mix=vec4(albedo_c.rgb,1.0);v_roughness_metallic_emissive_alpha=vec4(vec3(r_m,e_r_m.x)/255.0,albedo_c.a);v_roughness_metallic_emissive_alpha.z*=2.0;float heightBasedRelativeIntepolation=a_pos_3f.z*heightBasedEmissiveStrength.x+heightBasedEmissiveStrength.y;v_height_based_emission_params.x=heightBasedRelativeIntepolation;v_height_based_emission_params.y=heightBasedEmissiveStrength.z;vec2 emissionMultiplierValues=unpack_float(float(pbr.w))/256.0;v_height_based_emission_params.z=emissionMultiplierValues.x;v_height_based_emission_params.w=emissionMultiplierValues.y-emissionMultiplierValues.x; #endif #ifdef FOG v_fog_pos=fog_position(local_pos); #endif #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z); #endif #ifdef TERRAIN_FRAGMENT_OCCLUSION v_depth=gl_Position.z/gl_Position.w; #ifdef CLIP_ZERO_TO_ONE v_depth=-1.0+2.0*v_depth; #endif #endif #ifdef HAS_ATTRIBUTE_a_normal_3f #ifdef MODEL_POSITION_ON_GPU float x_squared_scale=dot(rs[0],rs[0]);float y_squared_scale=dot(rs[1],rs[1]);float z_squared_scale=dot(rs[2],rs[2]);vec3 squared_scale=vec3(x_squared_scale,y_squared_scale,z_squared_scale);normal_3f=rs*((u_lighting_matrix*vec4(normal_3f,0.0)).xyz/squared_scale);normal_3f=normalize(normal_3f); #else normal_3f=vec3(normal_matrix*vec4(normal_3f,0)); #endif #endif #ifdef HAS_ATTRIBUTE_a_pbr #ifdef HAS_ATTRIBUTE_a_color_4f v_roughness_metallic_emissive_alpha.w=clamp(color_4f.a*v_roughness_metallic_emissive_alpha.w*(v_roughness_metallic_emissive_alpha.z-1.0),0.0,1.0); #endif #endif #ifdef RENDER_SHADOWS vec4 shadow_pos=u_node_matrix*vec4(local_pos,1.0); #ifdef NORMAL_OFFSET #ifdef HAS_ATTRIBUTE_a_normal_3f #ifdef MODEL_POSITION_ON_GPU vec3 offset=shadow_normal_offset(vec3(-normal_3f.xy,normal_3f.z));shadow_pos.xyz+=offset*shadow_normal_offset_multiplier0(); #else vec3 offset=shadow_normal_offset_model(normal_3f);shadow_pos.xyz+=offset*shadow_normal_offset_multiplier0(); #endif #endif #endif v_pos_light_view_0=u_light_matrix_0*shadow_pos;v_pos_light_view_1=u_light_matrix_1*shadow_pos;v_depth_shadows=gl_Position.w; #endif }`),modelDepth:_o("void main() {}",`in vec3 a_pos_3f;uniform mat4 u_matrix; #ifdef MODEL_POSITION_ON_GPU #ifdef INSTANCED_ARRAYS in vec4 a_normal_matrix0;in vec4 a_normal_matrix1;in vec4 a_normal_matrix2;in vec4 a_normal_matrix3; #else uniform highp mat4 u_instance; #endif uniform highp mat4 u_node_matrix; #endif void main() { #ifdef MODEL_POSITION_ON_GPU highp mat4 instance; #ifdef INSTANCED_ARRAYS instance=mat4(a_normal_matrix0,a_normal_matrix1,a_normal_matrix2,a_normal_matrix3); #else instance=u_instance; #endif vec3 pos_color=instance[0].xyz;vec4 translate=instance[1];vec3 pos_a=floor(pos_color);float hidden=float(pos_a.x > EXTENT);float meter_to_tile=instance[0].w;vec4 pos=vec4(pos_a.xy,translate.z,1.0);mat3 rs;rs[0].x=instance[1].w;rs[0].yz=instance[2].xy;rs[1].xy=instance[2].zw;rs[1].z=instance[3].x;rs[2].xyz=instance[3].yzw;vec4 pos_node=u_node_matrix*vec4(a_pos_3f,1.0);vec3 rotated_pos_node=rs*pos_node.xyz;vec3 pos_model_tile=(rotated_pos_node+vec3(translate.xy,0.0))*vec3(meter_to_tile,meter_to_tile,1.0);pos.xyz+=pos_model_tile;gl_Position=mix(u_matrix*pos,AWAY,hidden); #else gl_Position=u_matrix*vec4(a_pos_3f,1); #endif }`),stars:_o(`in highp vec2 v_uv;in mediump float v_intensity;float shapeCircle(in vec2 uv) {float beginFade=0.6;float lengthFromCenter=length(v_uv);return 1.0-clamp((lengthFromCenter-beginFade)/(1.0-beginFade),0.0,1.0);}void main() {float alpha=shapeCircle(v_uv);vec3 color=vec3(1.0,1.0,1.0);alpha*=v_intensity;glFragColor=vec4(color*alpha,alpha);HANDLE_WIREFRAME_DEBUG;}`,` in vec3 a_pos_3f;in vec2 a_uv;in float a_size_scale;in float a_opacity;uniform mat4 u_matrix;uniform vec3 u_up;uniform vec3 u_right;uniform float u_intensity_multiplier;out highp vec2 v_uv;out mediump float v_intensity;void main() {v_uv=a_uv;v_intensity=a_opacity*u_intensity_multiplier;vec3 pos=a_pos_3f;pos+=a_uv.x*u_right*a_size_scale;pos+=a_uv.y*u_up*a_size_scale;gl_Position=u_matrix*vec4(pos,1.0);}`),snowParticle:_o("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("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("uniform vec3 u_vignetteShape;uniform vec4 u_vignetteColor;in vec2 st;void main() {float screenDist=length(st);float alpha=clamp((screenDist-u_vignetteShape.x)/u_vignetteShape.y,0.0,1.0);alpha=pow(alpha,u_vignetteShape.z)*u_vignetteColor.a;vec3 color=u_vignetteColor.rgb;glFragColor=vec4(color*alpha,alpha) ;}","in vec2 a_pos_2f;out vec2 st;void main() {st=a_pos_2f;gl_Position=vec4(a_pos_2f,0,1);}"),occlusion:_o("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 A0(D,w){const E=D.split(` `);for(let F of E){if(F=F.trimStart(),F[0]!=="#"||!F.includes("if")||F.startsWith("#endif"))continue;const G=F.match(Pb);if(G)for(const X of G)Lb.has(X)||w.add(X)}}function k3(D){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(D)}function _o(D,w){const E=new Set,F=[],G=[];D=D.replace(nm,(J,de)=>(G.push(de),"")),w=w.replace(nm,(J,de)=>(F.push(de),""));let X=new Set(_1);A0(D,X),A0(w,X);for(const J of[...F,...G])Cv[J]||(Cv[J]=new Set,A0(Rf[J],Cv[J])),X=new Set([...X,...Cv[J]]);return{fragmentSource:D=D.replace(dr,(J,de,ye,Ce,Le)=>(E.add(Le),de==="define"?` #ifndef HAS_UNIFORM_u_${Le} ${k3(Ce)?"flat ":""}in ${ye} ${Ce} ${Le}; #else uniform ${ye} ${Ce} u_${Le}; #endif `:de==="initialize"?` #ifdef HAS_UNIFORM_u_${Le} ${ye} ${Ce} ${Le} = u_${Le}; #endif `:de==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Le} in ${ye} ${Ce} ${Le}; #endif `:de==="initialize-attribute"?"":void 0)),vertexSource:w=w.replace(dr,(J,de,ye,Ce,Le)=>{const Xe=`MATERIAL_ATTRIBUTE_OFFSET_${Le}`,Ke=Ce==="float"?"vec2":Ce,st=`GET_ATTRIBUTE_${Ke}(a_${Le}, materialInfo, ${Xe})`,dt=Le.match(/color/)?"color":Ke;return de==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${Le} in ${ye} ${Ce} a_${Le}; #endif `:E.has(Le)?de==="define"?` #ifndef HAS_UNIFORM_u_${Le} uniform lowp float u_${Le}_t; #if !defined(${Xe}) in ${ye} ${Ke} a_${Le}; #endif ${k3(Ce)?"flat ":""}out ${ye} ${Ce} ${Le}; #else uniform ${ye} ${Ce} u_${Le}; #endif `:de==="initialize"?dt==="vec4"||dt==="uvec4"?` #ifndef HAS_UNIFORM_u_${Le} ${Le} = a_${Le}; #else ${ye} ${Ce} ${Le} = u_${Le}; #endif `:` #if !defined(HAS_UNIFORM_u_${Le}) #ifdef ${Xe} ${Le} = unpack_mix_${dt}(${st}, u_${Le}_t); #else ${Le} = unpack_mix_${dt}(a_${Le}, u_${Le}_t); #endif #else ${ye} ${Ce} ${Le} = u_${Le}; #endif `:de==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Le} in ${ye} ${Ce} a_${Le}; out ${ye} ${Ce} ${Le}; #endif `:de==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Le} ${Le} = a_${Le}; #endif `:void 0:de==="define"?` #ifndef HAS_UNIFORM_u_${Le} uniform lowp float u_${Le}_t; #if !defined(${Xe}) in ${ye} ${Ke} a_${Le}; #endif #else uniform ${ye} ${Ce} u_${Le}; #endif `:de==="define-instanced"?dt==="mat4"?` #ifdef INSTANCED_ARRAYS in vec4 a_${Le}0; in vec4 a_${Le}1; in vec4 a_${Le}2; in vec4 a_${Le}3; #else uniform ${ye} ${Ce} u_${Le}; #endif `:` #ifdef INSTANCED_ARRAYS in ${ye} ${Ke} a_${Le}; #else uniform ${ye} ${Ce} u_${Le}; #endif `:de==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${Le} ${ye} ${Ce} ${Le} = a_${Le}; #endif `:dt==="vec4"||dt==="uvec4"?` #ifndef HAS_UNIFORM_u_${Le} #ifdef ${Xe} ${ye} ${Ce} ${Le} = ${st}; #else ${ye} ${Ce} ${Le} = a_${Le}; #endif #else ${ye} ${Ce} ${Le} = u_${Le}; #endif `:` #ifndef HAS_UNIFORM_u_${Le} #ifdef ${Xe} ${ye} ${Ce} ${Le} = unpack_mix_${dt}(${st}, u_${Le}_t); #else ${ye} ${Ce} ${Le} = unpack_mix_${dt}(a_${Le}, u_${Le}_t); #endif #else ${ye} ${Ce} ${Le} = u_${Le}; #endif `}),usedDefines:X,vertexIncludes:F,fragmentIncludes:G}}class IS{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(w,E,F,G,X,J,de,ye){this.context=w;let Ce=this.boundPaintVertexBuffers.length!==G.length;for(let Xe=0;!Ce&&Xe{const Ss=Vt.paint.get("hillshade-shadow-color"),rs=Vt.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",_s=Vt.paint.get("hillshade-highlight-color"),Gt=Vt.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",ss=Vt.paint.get("hillshade-accent-color"),xs=Vt.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",Ks=Vt.paint.get("hillshade-emissive-strength");let Ts=o.ap(Vt.paint.get("hillshade-illumination-direction"));if(Vt.paint.get("hillshade-illumination-anchor")==="viewport")Ts-=wt.transform.angle;else if(wt.style&&wt.style.enable3dLights()&&wt.style.directionalLight){const hn=wt.style.directionalLight.properties.get("direction"),Rn=o.cP(hn.x,hn.y,hn.z);Ts=o.ap(Rn[1])}const _n=!wt.options.moving;return{u_matrix:Ct||wt.transform.calculateProjMatrix(Bt.tileID.toUnwrapped(),_n),u_image:0,u_latrange:S3(0,Bt.tileID),u_light:[Vt.paint.get("hillshade-exaggeration"),Ts],u_shadow:Ss.toPremultipliedRenderColor(rs?null:Vt.lut),u_highlight:_s.toPremultipliedRenderColor(Gt?null:Vt.lut),u_emissive_strength:Ks,u_accent:ss.toPremultipliedRenderColor(xs?null:Vt.lut)}})(D,E,F,D.terrain?w.projMatrix:null);D.uploadCommonUniforms(de,Ke,w.toUnwrapped());const{tileBoundsBuffer:dt,tileBoundsIndexBuffer:it,tileBoundsSegments:jt}=D.getTileBoundsBuffers(E);Ke.draw(D,ye.TRIANGLES,G,X,J,fa.disabled,st,F.id,dt,it,jt)}function C3(D,w,E){if(!w.needsDEMTextureUpload)return;const F=D.context,G=F.gl;F.pixelStoreUnpackPremultiplyAlpha.set(!1),w.demTexture=w.demTexture||D.getTileTexture(E.stride);const X=E.getPixels();w.demTexture?w.demTexture.update(X,{premultiply:!1}):w.demTexture=new o.T(F,X,G.R32F,{premultiply:!1}),w.needsDEMTextureUpload=!1}function ME(D,w,E){const F=D.context,G=F.gl;if(!w.dem)return;const X=w.dem;if(F.activeTexture.set(G.TEXTURE1),C3(D,w,X),!w.demTexture)return;w.demTexture.bind(G.NEAREST,G.CLAMP_TO_EDGE);const J=X.dim;F.activeTexture.set(G.TEXTURE0);let de=w.hillshadeFBO;if(!de){const Ke=new o.T(F,{width:J,height:J,data:null},G.RGBA8);Ke.bind(G.LINEAR,G.CLAMP_TO_EDGE),de=w.hillshadeFBO=F.createFramebuffer(J,J,1,"renderbuffer"),de.colorAttachment0.set(Ke.texture)}F.bindFramebuffer.set(de.framebuffer),F.viewport.set([0,0,J,J]);const{tileBoundsBuffer:ye,tileBoundsIndexBuffer:Ce,tileBoundsSegments:Le}=D.getMercatorTileBoundsBuffers(),Xe=[];D.linearFloatFilteringSupported()&&Xe.push("TERRAIN_DEM_FLOAT_FORMAT"),D.terrain&&D.terrain.renderingToTexture&&D.emissiveMode==="mrt-fallback"&&Xe.push("USE_MRT1"),D.getOrCreateProgram("hillshadePrepare",{defines:Xe}).draw(D,G.TRIANGLES,Hr.disabled,Da.disabled,Ia.unblended,fa.disabled,((Ke,st)=>{const dt=st.stride,it=o.bb();return o.bT(it,0,o.an,-o.an,0,0,1),o.bx(it,it,[0,-o.an,0]),{u_matrix:it,u_image:1,u_dimension:[dt,dt],u_zoom:Ke.overscaledZ}})(w.tileID,X),E.id,ye,Ce,Le),w.needsHillshadePrepare=!1}class Qc{constructor(w){this.gl=w.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1}get(){return this.current}set(w){}getDefault(){return this.default}setDefault(){this.set(this.default)}}class K_ extends Qc{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(w){const E=this.current;(w.r!==E.r||w.g!==E.g||w.b!==E.b||w.a!==E.a||this.dirty)&&(this.gl.clearColor(w.r,w.g,w.b,w.a),this.current=w,this.dirty=!1)}}class A3 extends Qc{getDefault(){return 1}set(w){(w!==this.current||this.dirty)&&(this.gl.clearDepth(w),this.current=w,this.dirty=!1)}}class Ib extends Qc{getDefault(){return 0}set(w){(w!==this.current||this.dirty)&&(this.gl.clearStencil(w),this.current=w,this.dirty=!1)}}class yL extends Qc{getDefault(){return[!0,!0,!0,!0]}set(w){const E=this.current;(w[0]!==E[0]||w[1]!==E[1]||w[2]!==E[2]||w[3]!==E[3]||this.dirty)&&(this.gl.colorMask(w[0],w[1],w[2],w[3]),this.current=w,this.dirty=!1)}}class E0 extends Qc{getDefault(){return!0}set(w){(w!==this.current||this.dirty)&&(this.gl.depthMask(w),this.current=w,this.dirty=!1)}}class Lj extends Qc{getDefault(){return 255}set(w){(w!==this.current||this.dirty)&&(this.gl.stencilMask(w),this.current=w,this.dirty=!1)}}class Y_ extends Qc{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(w){const E=this.current;(w.func!==E.func||w.ref!==E.ref||w.mask!==E.mask||this.dirty)&&(this.gl.stencilFunc(w.func,w.ref,w.mask),this.current=w,this.dirty=!1)}}class RS extends Qc{getDefault(){const w=this.gl;return[w.KEEP,w.KEEP,w.KEEP]}set(w){const E=this.current;(w[0]!==E[0]||w[1]!==E[1]||w[2]!==E[2]||this.dirty)&&(this.gl.stencilOp(w[0],w[1],w[2]),this.current=w,this.dirty=!1)}}class Rb extends Qc{getDefault(){return!1}set(w){if(w===this.current&&!this.dirty)return;const E=this.gl;w?E.enable(E.STENCIL_TEST):E.disable(E.STENCIL_TEST),this.current=w,this.dirty=!1}}class Db extends Qc{getDefault(){return[0,1]}set(w){const E=this.current;(w[0]!==E[0]||w[1]!==E[1]||this.dirty)&&(this.gl.depthRange(w[0],w[1]),this.current=w,this.dirty=!1)}}class bg extends Qc{getDefault(){return!1}set(w){if(w===this.current&&!this.dirty)return;const E=this.gl;w?E.enable(E.DEPTH_TEST):E.disable(E.DEPTH_TEST),this.current=w,this.dirty=!1}}class Pu extends Qc{getDefault(){return this.gl.LESS}set(w){(w!==this.current||this.dirty)&&(this.gl.depthFunc(w),this.current=w,this.dirty=!1)}}class T0 extends Qc{getDefault(){return!1}set(w){if(w===this.current&&!this.dirty)return;const E=this.gl;w?E.enable(E.BLEND):E.disable(E.BLEND),this.current=w,this.dirty=!1}}class ON extends Qc{getDefault(){const w=this.gl;return[w.ONE,w.ZERO,w.ONE,w.ZERO]}set(w){const E=this.current;(w[0]!==E[0]||w[1]!==E[1]||w[2]!==E[2]||w[3]!==E[3]||this.dirty)&&(this.gl.blendFuncSeparate(w[0],w[1],w[2],w[3]),this.current=w,this.dirty=!1)}}class E3 extends Qc{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(w){const E=this.current;(w.r!==E.r||w.g!==E.g||w.b!==E.b||w.a!==E.a||this.dirty)&&(this.gl.blendColor(w.r,w.g,w.b,w.a),this.current=w,this.dirty=!1)}}class ex extends Qc{getDefault(){return this.gl.FUNC_ADD}set(w){(w!==this.current||this.dirty)&&(this.gl.blendEquationSeparate(w,w),this.current=w,this.dirty=!1)}}class Df extends Qc{getDefault(){return!1}set(w){if(w===this.current&&!this.dirty)return;const E=this.gl;w?E.enable(E.CULL_FACE):E.disable(E.CULL_FACE),this.current=w,this.dirty=!1}}class FN extends Qc{getDefault(){return this.gl.BACK}set(w){(w!==this.current||this.dirty)&&(this.gl.cullFace(w),this.current=w,this.dirty=!1)}}class DS extends Qc{getDefault(){return this.gl.CCW}set(w){(w!==this.current||this.dirty)&&(this.gl.frontFace(w),this.current=w,this.dirty=!1)}}let Ij=class extends Qc{getDefault(){return null}set(D){(D!==this.current||this.dirty)&&(this.gl.useProgram(D),this.current=D,this.dirty=!1)}};class Rj extends Qc{getDefault(){return this.gl.TEXTURE0}set(w){(w!==this.current||this.dirty)&&(this.gl.activeTexture(w),this.current=w,this.dirty=!1)}}class Of extends Qc{getDefault(){const w=this.gl;return[0,0,w.drawingBufferWidth,w.drawingBufferHeight]}set(w){const E=this.current;(w[0]!==E[0]||w[1]!==E[1]||w[2]!==E[2]||w[3]!==E[3]||this.dirty)&&(this.gl.viewport(w[0],w[1],w[2],w[3]),this.current=w,this.dirty=!1)}}class Qp extends Qc{getDefault(){return null}set(w){if(w===this.current&&!this.dirty)return;const E=this.gl;E.bindFramebuffer(E.FRAMEBUFFER,w),this.current=w,this.dirty=!1}}class T3 extends Qc{getDefault(){return null}set(w){if(w===this.current&&!this.dirty)return;const E=this.gl;E.bindRenderbuffer(E.RENDERBUFFER,w),this.current=w,this.dirty=!1}}class Av extends Qc{getDefault(){return null}set(w){if(w===this.current&&!this.dirty)return;const E=this.gl;E.bindTexture(E.TEXTURE_2D,w),this.current=w,this.dirty=!1}}class Dj extends Qc{getDefault(){return null}set(w){if(w===this.current&&!this.dirty)return;const E=this.gl;E.bindBuffer(E.ARRAY_BUFFER,w),this.current=w,this.dirty=!1}}class Oj extends Qc{getDefault(){return null}set(w){const E=this.gl;E.bindBuffer(E.ELEMENT_ARRAY_BUFFER,w),this.current=w,this.dirty=!1}}class OS extends Qc{getDefault(){return null}set(w){this.gl&&(w!==this.current||this.dirty)&&(this.gl.bindVertexArray(w),this.current=w,this.dirty=!1)}}class FS extends Qc{getDefault(){return 4}set(w){if(w===this.current&&!this.dirty)return;const E=this.gl;E.pixelStorei(E.UNPACK_ALIGNMENT,w),this.current=w,this.dirty=!1}}class zS extends Qc{getDefault(){return!1}set(w){if(w===this.current&&!this.dirty)return;const E=this.gl;E.pixelStorei(E.UNPACK_PREMULTIPLY_ALPHA_WEBGL,w),this.current=w,this.dirty=!1}}class Fj extends Qc{getDefault(){return!1}set(w){if(w===this.current&&!this.dirty)return;const E=this.gl;E.pixelStorei(E.UNPACK_FLIP_Y_WEBGL,w),this.current=w,this.dirty=!1}}class zj extends Qc{constructor(w,E){super(w),this.context=w,this.parent=E}getDefault(){return null}}class Z_ extends zj{constructor(w,E,F=0){super(w,E),this.attachmentPoint=w.gl.COLOR_ATTACHMENT0+F}setDirty(){this.dirty=!0}set(w){if(w===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const E=this.gl;E.framebufferTexture2D(E.FRAMEBUFFER,this.attachmentPoint,E.TEXTURE_2D,w,0),this.current=w,this.dirty=!1}}class zN extends zj{attachment(){return this.gl.DEPTH_ATTACHMENT}set(w){if(w===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const E=this.gl;E.framebufferRenderbuffer(E.FRAMEBUFFER,this.attachment(),E.RENDERBUFFER,w),this.current=w,this.dirty=!1}}class BS extends zj{attachment(){return this.gl.DEPTH_ATTACHMENT}set(w){if(w===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const E=this.gl;E.framebufferTexture2D(E.FRAMEBUFFER,this.attachment(),E.TEXTURE_2D,w,0),this.current=w,this.dirty=!1}}class PE extends zN{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const X_=(D,w,E,F)=>({u_matrix:D,u_image0:0,u_image1:1,u_skirt_height:w,u_ground_shadow_factor:E,u_emissive_texture_available:F}),Ev=(D,w,E,F,G,X,J,de,ye,Ce,Le,Xe,Ke,st,dt,it,jt)=>({u_proj_matrix:Float32Array.from(D),u_globe_matrix:w,u_normalize_matrix:Float32Array.from(F),u_merc_matrix:E,u_zoom_transition:G,u_merc_center:X,u_image0:0,u_image1:1,u_frustum_tl:J,u_frustum_tr:de,u_frustum_br:ye,u_frustum_bl:Ce,u_globe_pos:Le,u_globe_radius:Xe,u_viewport:Ke,u_grid_matrix:jt?Float32Array.from(jt):new Float32Array(9),u_skirt_height:st,u_far_z_cutoff:dt,u_emissive_texture_available:it});function Bj(D,w){return D!=null&&w!=null&&!(!D.hasData()||!w.hasData())&&D.demTexture!=null&&w.demTexture!=null&&D.tileID.key!==w.tileID.key}const Vm=new class{constructor(){this.operations={}}newMorphing(D,w,E,F,G){if(D in this.operations){const X=this.operations[D];X.to.tileID.key!==E.tileID.key&&(X.queued=E)}else this.operations[D]={startTime:F,phase:0,duration:G,from:w,to:E,queued:null}}getMorphValuesForProxy(D){if(!(D in this.operations))return null;const w=this.operations[D];return{from:w.from,to:w.to,phase:w.phase}}update(D){for(const w in this.operations){const E=this.operations[w];for(E.phase=(D-E.startTime)/E.duration;E.phase>=1||!this._validOp(E);)if(!this._nextOp(E,D)){delete this.operations[w];break}}}_nextOp(D,w){return!!D.queued&&(D.from=D.to,D.to=D.queued,D.queued=null,D.phase=0,D.startTime=w,!0)}_validOp(D){return D.from.hasData()&&D.to.hasData()}},Uj={0:null,1:"TERRAIN_VERTEX_MORPHING"};function Q_(D,w,E){if(w===0)return 0;const F=w<1&&E===514?.25/w:1;return 6*Math.pow(1.5,22-D)*Math.max(w,1)*F}function Ee(D,w){const E=1<({u_matrix:D});function _t(D,w,E,F,G){if(G>0){const X=o.o.now(),J=(X-D.timeAdded)/G,de=w?(X-w.timeAdded)/G:-1,ye=E.getSource(),Ce=F.coveringZoomLevel({tileSize:ye.tileSize,roundZoom:ye.roundZoom}),Le=!w||Math.abs(w.tileID.overscaledZ-Ce)>Math.abs(D.tileID.overscaledZ-Ce),Xe=Le&&D.refreshedUponExpiration?1:o.aC(Le?J:1-de,0,1);return w?{opacity:1,mix:1-Xe,isFading:J<1}:{opacity:Xe,mix:0,isFading:J<1}}return{opacity:1,mix:0,isFading:!1}}class Jt extends Vl{constructor(w){const E={type:"raster-dem",maxzoom:Math.ceil(w.transform.maxZoom)},F=Hp("mock-dem",E,w.style.dispatcher,w.style);super("mock-dem",F,null),F.setEventedParent(this),this._sourceLoaded=!0}_loadTile(w,E){w.state="loaded",E(null)}}class cs extends Vl{constructor(w){const E=Hp("proxy",{type:"geojson",maxzoom:Math.ceil(w.transform.maxZoom)},w.style.dispatcher,w.style);super("proxy",E,null),E.setEventedParent(this),this.map=this.getSource().map=w,this.used=this._sourceLoaded=!0,this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}update(w,E,F){if(w.freezeTileCoverage)return;this.transform=w;const G=w.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}).reduce((X,J)=>{if(X[J.key]="",!this._tiles[J.key]){const de=new o.b0(J,this._source.tileSize*J.overscaleFactor(),w.tileZoom,void 0,void 0,this._source.worldview);de.state="loaded",this._tiles[J.key]=de}return X},{});for(const X in this._tiles)X in G||(this.freeFBO(X),this._tiles[X].unloadVectorData(),delete this._tiles[X])}freeFBO(w){const E=this.proxyCachedFBO[w];if(E!==void 0){const F=Object.values(E);this.renderCachePool.push(...F),delete this.proxyCachedFBO[w]}}deallocRenderCache(){this.renderCache.forEach(w=>w.fb.destroy()),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}}class gs extends o.aR{constructor(w,E,F){super(w.overscaledZ,w.wrap,w.canonical.z,w.canonical.x,w.canonical.y),this.proxyTileKey=E,this.projMatrix=F}}class Cs extends o.bu{constructor(w,E){super(),this._debugParams={sortTilesHiZFirst:!0,disableRenderCache:!1},this.painter=w,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[F,G,X]=function(){const ye=new o.dB,Ce=new o.dC,Le=131;ye.reserve(17161),Ce.reserve(33800);const Xe=o.an/128,Ke=o.an+Xe/2,st=Ke+Xe;for(let it=-Xe;itKe||it<0||it>Ke?24575:0,Bt=o.aC(Math.round(jt),0,o.an),Vt=o.aC(Math.round(it),0,o.an);ye.emplaceBack(Bt+wt,Vt)}const dt=(it,jt)=>{const wt=jt*Le+it;Ce.emplaceBack(wt+1,wt,wt+Le),Ce.emplaceBack(wt+Le,wt+Le+1,wt+1)};for(let it=1;it<129;it++)for(let jt=1;jt<129;jt++)dt(jt,it);return[0,129].forEach(it=>{for(let jt=0;jt<130;jt++)dt(jt,it),dt(it,jt)}),[ye,Ce,32768]}(),J=w.context;this.gridBuffer=J.createVertexBuffer(F,o.dx.members),this.gridIndexBuffer=J.createIndexBuffer(G),this.gridSegments=o.dy.simpleSegment(0,0,F.length,G.length),this.gridNoSkirtSegments=o.dy.simpleSegment(0,0,F.length,X),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new cs(E.map),this.orthoMatrix=o.bb(),o.bT(this.orthoMatrix,this.painter.transform.projection.name==="globe"?.015:0,o.an,0,o.an,0,1);const de=J.gl;this._overlapStencilMode=new Da({func:de.GEQUAL,mask:255},0,255,de.KEEP,de.KEEP,de.REPLACE),this._previousZoom=w.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=E,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new Jt(E.map),this._pendingGroundEffectLayers=[],this._emissiveTexture=!1}set style(w){w.on("data",this._onStyleDataEvent.bind(this)),this._style=w,this._style.map.on("moveend",()=>{this._clearLineLayersFromRenderCache()})}update(w,E,F){if(w&&w.terrain){this._style!==w&&(this.style=w,this._evaluationZoom=void 0);const G=w.terrain.properties,X=w.terrain.drapeRenderMode===0,J=w.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=o.o.now();const de=w.terrain&&w.terrain.scope,ye=G.get("source"),Ce=X?this._mockSourceCache:w.getSourceCache(ye,de);if(!Ce)return void o.w(`Couldn't find terrain source "${ye}".`);if(this.sourceCache=Ce,this._attenuationRange=w.terrain.getAttenuationRange(),this._exaggeration=J?this.calculateExaggeration(E):G.get("exaggeration"),!E.projection.requiresDraping&&J&&this._exaggeration===0)return void this._disable();this.enabled=!0;const Le=()=>{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 Xe=this.getScaledDemTileSize();this.sourceCache.update(E,Xe,!0),this.resetTileLookupCache(this.sourceCache.id)};this.sourceCache.usedForTerrain||(this.resetTileLookupCache(this.sourceCache.id),this.sourceCache.usedForTerrain=!0,Le(),this._initializing=!0),Le(),E.updateElevation(!0,F),this.resetTileLookupCache(this.proxySourceCache.id),this.proxySourceCache.update(E),this._emptyDEMTextureDirty=!0,this._previousZoom=E.zoom}else this._disable()}calculateExaggeration(w){if(this._attenuationRange&&w.zoom>=Math.ceil(this._attenuationRange[1]))return this._style.terrain.getExaggeration(w.zoom);const E=this._previousCameraAltitude,F=w.getFreeCameraOptions().position.z/w.pixelsPerMeter*w.worldSize;this._previousCameraAltitude=F;const G=E!=null?F-E:Number.MAX_VALUE;if(Math.abs(G)<2)return this._exaggeration;const X=w.zoom,J=this._style.terrain;if(!this._previousUpdateTimestamp)return J.getExaggeration(X);let de=X-this._previousZoom;const ye=this._previousUpdateTimestamp;let Ce=X;this._evaluationZoom!=null&&(Ce=this._evaluationZoom,Math.abs(X-Ce)>.5&&(de=.5*(X-Ce+de)),de*G<0&&(Ce+=de)),this._evaluationZoom=Ce;const Le=J.getExaggeration(Ce),Xe=Le===J.getExaggeration(Math.max(0,Ce-.1));if(Xe&&Math.abs(Le-this._exaggeration)<.01)return Le;let Ke=Math.min(.1,.00375*(this._updateTimestamp-ye));return(Xe||Le<.1||Math.abs(de)<1e-4)&&(Ke=Math.min(.2,4*Ke)),o.am(this._exaggeration,Le,Ke)}resetTileLookupCache(w){this._findCoveringTileCache[w]={}}attenuationRange(){return this._attenuationRange}getDemUpscale(){return this.proxySourceCache.getSource().tileSize/128}getScaledDemTileSize(){return this.sourceCache.getSource().tileSize/128*this.proxySourceCache.getSource().tileSize}_onStyleDataEvent(w){w.dataType==="source"&&w.coord?this._clearRenderCacheForTile(w.sourceCacheId,w.coord):w.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 w in this._style._mergedSourceCaches)this._style._mergedSourceCaches[w].usedForTerrain=!1}destroy(){this._disable(),this._emptyDEMTexture&&this._emptyDEMTexture.destroy(),this.pool.forEach(w=>w.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 w=2*this.proxySourceCache.getSource().tileSize;return[w,w]}set useVertexMorphing(w){this._useVertexMorphing=w}updateTileBinding(w){if(!this.enabled)return;this.prevTerrainTileForTile=this.terrainTileForTile;const E=this.proxySourceCache,F=this.painter.transform;this._initializing&&(this._initializing=F._centerAltitude===0&&this.getAtPointOrZero(o.ag.fromLngLat(F.center),-1)===-1,this._emptyDEMTextureDirty=!this._initializing);const G=this.proxyCoords=E.getIds().map(ye=>{const Ce=E.getTileByID(ye).tileID;return Ce.projMatrix=F.calculateProjMatrix(Ce.toUnwrapped()),Ce});(function(ye,Ce){const Le=Ce.transform.pointCoordinate(Ce.transform.getCameraPoint()),Xe=new o.P(Le.x,Le.y);ye.sort((Ke,st)=>{if(st.overscaledZ-Ke.overscaledZ)return st.overscaledZ-Ke.overscaledZ;const dt=new o.P(Ke.canonical.x+(1<{this.proxyToSource[ye.key]={}}),this.terrainTileForTile={};const J=this._style._mergedSourceCaches;for(const ye in J){const Ce=J[ye];if(!Ce.used||(Ce!==this.sourceCache&&this.resetTileLookupCache(Ce.id),this._setupProxiedCoordsForOrtho(Ce,w[ye],X),Ce.usedForTerrain))continue;const Le=w[ye];(Ce.getSource().reparseOverscaled||Ce._isRasterElevatedOverTerrain)&&this._assignTerrainTiles(Le)}this.proxiedCoords[E.id]=G.map(ye=>new gs(ye,ye.key,this.orthoMatrix)),this._assignTerrainTiles(G),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(X),this.renderingToTexture=!1;const de={};this._visibleDemTiles=[];for(const ye of this.proxyCoords){const Ce=this.terrainTileForTile[ye.key];if(!Ce)continue;const Le=Ce.tileID.key;Le in de||(this._visibleDemTiles.push(Ce),de[Le]=Le)}}_assignTerrainTiles(w){this._initializing||w.forEach(E=>{if(this.terrainTileForTile[E.key])return;const F=this._findTileCoveringTileID(E,this.sourceCache);F&&(this.terrainTileForTile[E.key]=F)})}_prepareDEMTextures(){const w=this.painter.context,E=w.gl;for(const F in this.terrainTileForTile){const G=this.terrainTileForTile[F],X=G.dem;!X||G.demTexture&&!G.needsDEMTextureUpload||(w.activeTexture.set(E.TEXTURE1),C3(this.painter,G,X))}}_prepareDemTileUniforms(w,E,F,G){if(!E||E.demTexture==null)return!1;const X=w.tileID.canonical,J=Math.pow(2,E.tileID.canonical.z-X.z),de=G||"";return F[`u_dem_tl${de}`]=[X.x*J%1,X.y*J%1],F[`u_dem_scale${de}`]=J,!0}get emptyDEMTexture(){return!this._emptyDEMTextureDirty&&this._emptyDEMTexture?this._emptyDEMTexture:this._updateEmptyDEMTexture()}_getLoadedAreaMinimum(){if(!this.enabled)return 0;let w=0;const E=this._visibleDemTiles.reduce((F,G)=>{if(!G.dem)return F;const X=G.dem.tree.minimums[0];return X>0&&w++,F+X},0);return w?E/w:0}_updateEmptyDEMTexture(){const w=this.painter.context,E=w.gl;w.activeTexture.set(E.TEXTURE2);const F=this._getLoadedAreaMinimum(),G=new o.dz({width:1,height:1},new Float32Array([F]));this._emptyDEMTextureDirty=!1;let X=this._emptyDEMTexture;return X?X.update(G,{premultiply:!1}):X=this._emptyDEMTexture=new o.T(w,G,E.R32F,{premultiply:!1}),X}setupElevationDraw(w,E,F){const G=this.painter.context,X=G.gl,J={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};J.u_exaggeration=this.exaggeration();let de=null,ye=null,Ce=1;if(F&&F.morphing&&this._useVertexMorphing){const st=F.morphing.srcDemTile,dt=F.morphing.dstDemTile;Ce=F.morphing.phase,st&&dt&&(this._prepareDemTileUniforms(w,st,J,"_prev")&&(ye=st),this._prepareDemTileUniforms(w,dt,J)&&(de=dt))}const Le=st=>st&&st.demTexture&&this.painter.linearFloatFilteringSupported()?X.LINEAR:X.NEAREST;let Xe=null;var Ke;if(this.enabled?ye&&de?(Xe=de.demTexture,G.activeTexture.set(X.TEXTURE4),ye.demTexture.bind(Le(ye),X.CLAMP_TO_EDGE),J.u_dem_lerp=Ce):(de=this.terrainTileForTile[w.tileID.key],Xe=this._prepareDemTileUniforms(w,de,J)?de.demTexture:this.emptyDEMTexture):Xe=this.emptyDEMTexture,G.activeTexture.set(X.TEXTURE2),Xe&&(J.u_dem_size=(Ke=Xe).size[0]===1?1:Ke.size[0]-2,Xe.bind(Le(de),X.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(F&&F.useDepthForOcclusion,E,J),F&&F.useMeterToDem&&de){const st=(1<{if(wt===hn)return;const Rn=[Uj[hn],"PROJECTION_GLOBE_VIEW"];Vt&&Rn.push("CUSTOM_ANTIALIASING");const Kn=Ce.isTileAffectedByFog(_n);jt=Ce.getOrCreateProgram("globeRaster",{defines:Rn,overrideFog:Kn}),wt=hn},Ss=Ce.colorModeForRenderPass(),rs=new Hr(it.LEQUAL,Hr.ReadWrite,Ce.depthRangeFor3D);Vm.update(st);const _s=o.dq(Bt),Gt=[o.aH(Bt.center.lng),o.aL(Bt.center.lat)],ss=Ce.globeSharedBuffers,xs=[Bt.width*o.o.devicePixelRatio,Bt.height*o.o.devicePixelRatio],Ks=Float32Array.from(Bt.globeMatrix),Ts={useDenormalizedUpVectorScale:!0};{const _n=Ce.transform,hn=Q_(_n.zoom,Le.exaggeration(),Le.sourceCache._source.tileSize);wt=-1;const Rn=it.TRIANGLES;for(const Kn of Ke){const en=Xe.getTile(Kn),Ls=Da.disabled,yn=Le.prevTerrainTileForTile[Kn.key],jn=Le.terrainTileForTile[Kn.key];Bj(yn,jn)&&Vm.newMorphing(Kn.key,yn,jn,st,250),ze(Ce,en.emissiveTexture),dt.activeTexture.set(it.TEXTURE0),en.texture&&en.texture.bind(it.LINEAR,it.CLAMP_TO_EDGE);const An=Vm.getMorphValuesForProxy(Kn.key),jr=An?1:0;An&&Object.assign(Ts,{morphing:{srcDemTile:An.from,dstDemTile:An.to,phase:o.dn(An.phase)}});const ur=o.dr(Kn.canonical),hr=o.ds(ur.getCenter().lat),Vn=o.dt(Kn.canonical,ur,hr,_n.worldSize/_n._pixelsPerMercatorPixel),ca=o.du(o.dv(Kn.canonical)),Na=Ce.emissiveMode==="mrt-fallback"?1:0,ea=Ev(_n.expandedFarZProjMatrix,Ks,_s,ca,o.al(_n.zoom),Gt,_n.frustumCorners.TL,_n.frustumCorners.TR,_n.frustumCorners.BR,_n.frustumCorners.BL,_n.globeCenterInViewSpace,_n.globeRadius,xs,hn,_n._farZ,Na,Vn);if(Ct(Kn,jr),jt&&(Le.setupElevationDraw(en,jt,Ts),Ce.uploadCommonUniforms(dt,jt,Kn.toUnwrapped()),ss)){const[ia,ii,Ni]=ss.getGridBuffers(hr,hn!==0);jt.draw(Ce,Rn,rs,Ls,Ss,fa.backCCW,ea,"globe_raster",ia,ii,Ni)}}}if(ss&&(Ce.renderDefaultNorthPole||Ce.renderDefaultSouthPole)){const _n=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];Vt&&_n.push("CUSTOM_ANTIALIASING"),jt=Ce.getOrCreateProgram("globeRaster",{defines:_n});for(const hn of Ke){const{x:Rn,y:Kn,z:en}=hn.canonical,Ls=Kn===0,yn=Kn===(1<ia.draw(Ce,it.TRIANGLES,rs,Da.disabled,Ss,fa.disabled,Ev(Bt.expandedFarZProjMatrix,Vn,Vn,ca,0,Gt,Bt.frustumCorners.TL,Bt.frustumCorners.TR,Bt.frustumCorners.BR,Bt.frustumCorners.BL,Bt.globeCenterInViewSpace,Bt.globeRadius,xs,0,Bt._farZ,Na),"globe_pole_raster",ii,jr,ur);Le.setupElevationDraw(hr,jt,Ts),Ce.uploadCommonUniforms(dt,jt,hn.toUnwrapped()),Ls&&Ce.renderDefaultNorthPole&&ea(jt,jn),yn&&Ce.renderDefaultSouthPole&&(Vn=o.cC(o.bb(),Vn,[1,-1,1]),ea(jt,An))}}}})(G,X,J,de,ye);else{const Ce=G.context,Le=Ce.gl;let Xe,Ke;const st=G.shadowRenderer,dt=Sd(G,G.longestCutoffRange),it=Ss=>{if(Ke===Ss)return;const rs=[];rs.push(Uj[Ss]),dt.shouldRenderCutoff&&rs.push("RENDER_CUTOFF"),st&&(rs.push("RENDER_SHADOWS"),st.useNormalOffset&&rs.push("NORMAL_OFFSET")),Xe=G.getOrCreateProgram("terrainRaster",{defines:rs}),Ke=Ss},jt=G.colorModeForRenderPass(),wt=new Hr(Le.LEQUAL,Hr.ReadWrite,G.depthRangeFor3D);Vm.update(ye);const Bt=G.transform,Vt=Q_(Bt.zoom,X.exaggeration(),X.sourceCache._source.tileSize);let Ct=[0,0,0];if(st){const Ss=G.style.directionalLight,rs=G.style.ambientLight;Ss&&rs&&(Ct=tm(G.style,Ss,rs))}{Ke=-1;const Ss=Le.TRIANGLES,[rs,_s]=[X.gridIndexBuffer,X.gridSegments];for(const Gt of de){const ss=J.getTile(Gt),xs=Da.disabled,Ks=X.prevTerrainTileForTile[Gt.key],Ts=X.terrainTileForTile[Gt.key];Bj(Ks,Ts)&&Vm.newMorphing(Gt.key,Ks,Ts,ye,250),ze(G,ss.emissiveTexture),Ce.activeTexture.set(Le.TEXTURE0),ss.texture&&ss.texture.bind(Le.LINEAR,Le.CLAMP_TO_EDGE);const _n=Vm.getMorphValuesForProxy(Gt.key),hn=_n?1:0;let Rn;_n&&(Rn={morphing:{srcDemTile:_n.from,dstDemTile:_n.to,phase:o.dn(_n.phase)}});const Kn=G.emissiveMode==="mrt-fallback"?1:0,en=X_(Gt.projMatrix,Ee(Gt.canonical,Bt.renderWorldCopies)?Vt/10:Vt,Ct,Kn);if(it(hn),!Xe)continue;X.setupElevationDraw(ss,Xe,Rn);const Ls=Gt.toUnwrapped();st&&st.setupShadows(Ls,Xe),G.uploadCommonUniforms(Ce,Xe,Ls,null,dt),Xe.draw(G,Ss,wt,xs,jt,fa.backCCW,en,"terrain_raster",X.gridBuffer,rs,_s)}}}}(E,this,this.proxySourceCache,w,this._updateTimestamp),this.renderingToTexture=!0,E.gpuTimingDeferredRenderEnd(),w.splice(0,w.length))}renderBatch(w){if(this._drapedRenderBatches.length===0)return w+1;this.renderingToTexture=!0;const E=this.painter,F=this.painter.context,G=this.proxySourceCache,X=this.proxiedCoords[G.id],J=this._drapedRenderBatches.shift(),de=E.style.order,ye=[];this._updateFBOs(E.emissiveMode==="mrt-fallback");let Ce=0;for(const Le of X){const Xe=G.getTileByID(Le.proxyTileKey),Ke=G.proxyCachedFBO[Le.key]?G.proxyCachedFBO[Le.key][w]:void 0,st=Ke!==void 0?G.renderCache[Ke]:this.pool[Ce++],dt=Ke!==void 0;if(Xe.texture=st.tex,Xe.emissiveTexture=st.emissiveTex,dt&&!st.dirty){ye.push(Xe.tileID);continue}F.bindFramebuffer.set(st.fb.framebuffer);const it=F.gl;let jt;it.drawBuffers(E.emissiveMode==="mrt-fallback"?[it.COLOR_ATTACHMENT0,it.COLOR_ATTACHMENT1]:[it.COLOR_ATTACHMENT0]),this.renderedToTile=!1,st.dirty&&(F.clear({color:o.aq.transparent,stencil:0}),st.dirty=!1);for(let wt=J.start;wt<=J.end;++wt){const Bt=E.style._mergedLayers[de[wt]];if(Bt.isHidden(E.transform.zoom))continue;const Vt=E.style.getLayerSourceCache(Bt),Ct=Vt?this.proxyToSource[Le.key][Vt.id]:[Le];if(!Ct)continue;const Ss=Ct;F.viewport.set([0,0,st.fb.width,st.fb.height]),jt!==(Vt?Vt.id:null)&&(this._setupStencil(st,Ct,Bt,Vt),jt=Vt?Vt.id:null),E.renderLayer(E,Vt,Bt,Ss)}if(it.drawBuffers([it.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const wt of this._pendingGroundEffectLayers){const Bt=E.style._mergedLayers[de[wt]];if(Bt.isHidden(E.transform.zoom))continue;const Vt=E.style.getLayerSourceCache(Bt),Ct=Vt?this.proxyToSource[Le.key][Vt.id]:[Le];if(!Ct)continue;const Ss=Ct;F.viewport.set([0,0,st.fb.width,st.fb.height]),jt!==(Vt?Vt.id:null)&&(this._setupStencil(st,Ct,Bt,Vt),jt=Vt?Vt.id:null),E.renderLayer(E,Vt,Bt,Ss)}this.renderedToTile?(st.dirty=!0,ye.push(Xe.tileID)):dt||--Ce,Ce===5&&(Ce=0,this.renderToBackBuffer(ye))}return this.renderToBackBuffer(ye),this.renderingToTexture=!1,F.bindFramebuffer.set(null),F.viewport.set([0,0,E.width,E.height]),J.end+1}postRender(){}isLayerOrderingCorrect(w){const E=w.order.length;let F=-1,G=E;for(let X=0;XF}getMinElevationBelowMSL(){let w=0;return this._visibleDemTiles.filter(E=>E.dem).forEach(E=>{w=Math.min(w,E.dem.tree.minimums[0])}),w===0?w:(w-30)*this._exaggeration}raycast(w,E,F){if(!this._visibleDemTiles)return null;const G=this._visibleDemTiles.filter(X=>X.dem).map(X=>{const J=X.tileID,de=1<(X.t!==null?X.t:Number.MAX_VALUE)-(J.t!==null?J.t:Number.MAX_VALUE));for(const X of G){if(X.t==null)return null;const J=X.tile.dem.tree.raycast(X.minx,X.miny,X.maxx,X.maxy,w,E,F);if(J!=null)return J}return null}_createFBO(){const w=this.painter.context,E=w.gl,F=this.drapeBufferSize;w.activeTexture.set(E.TEXTURE0);const G=new o.T(w,{width:F[0],height:F[1],data:null},E.RGBA8);G.bind(E.LINEAR,E.CLAMP_TO_EDGE);const X=w.createFramebuffer(F[0],F[1],1,null);let J;return X.colorAttachment0.set(G.texture),this._emissiveTexture&&(J=new o.T(w,{width:F[0],height:F[1],data:null},E.R8),J.bind(E.LINEAR,E.CLAMP_TO_EDGE),X.createColorAttachment(w,1),X.colorAttachment1.set(J.texture)),X.depthAttachment=new PE(w,X.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=w.createRenderbuffer(w.gl.DEPTH_STENCIL,F[0],F[1]),this._stencilRef=0,X.depthAttachment.set(this._sharedDepthStencil),w.clear({stencil:0})):X.depthAttachment.set(this._sharedDepthStencil),w.extTextureFilterAnisotropic&&E.texParameterf(E.TEXTURE_2D,w.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,w.extTextureFilterAnisotropicMax),{fb:X,tex:G,emissiveTex:J,dirty:!1}}_updateFBOs(w){if(this._emissiveTexture!==w){for(const E of this.pool)this._updateFBO(E,w);for(const E of this.proxySourceCache.renderCache)this._updateFBO(E,w);this._emissiveTexture=w}}_updateFBO(w,E){const F=w.fb,G=this.painter.context,X=G.gl,J=this.drapeBufferSize;if(E){const de=new o.T(G,{width:J[0],height:J[1],data:null},X.R8);de.bind(X.LINEAR,X.CLAMP_TO_EDGE),w.emissiveTex=de,F.createColorAttachment(G,1),F.colorAttachment1.set(de.texture)}else w.emissiveTex=void 0,F.removeColorAttachment(G,1);w.dirty=!0}_initFBOPool(){for(;this.pool.length{const E=this._style._mergedLayers[w],F=E.isHidden(this.painter.transform.zoom);return E.type==="hillshade"||E.type==="custom"?!F&&E.shouldRedrape():!F&&E.hasTransition()})}_clearLineLayersFromRenderCache(){let w=!1;for(const F of this._style.getSources())if(F instanceof fd){w=!0;break}if(!w)return;const E={};for(let F=0;Fye>de.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=F}_setupRenderCache(w){const E=this.proxySourceCache;if(this._shouldDisableRenderCache()||this.invalidateRenderCache){if(this.invalidateRenderCache=!1,E.renderCache.length>E.renderCachePool.length){const J=Object.values(E.proxyCachedFBO);E.proxyCachedFBO={};for(let de=0;de=0;J--){const de=F[J];if(E.getTileByID(de.key),E.proxyCachedFBO[de.key]!==void 0){const ye=w[de.key],Ce=this.proxyToSource[de.key];let Le=0;for(const Xe in Ce){const Ke=Ce[Xe],st=ye[Xe];if(!st||st.length!==Ke.length||Ke.some((dt,it)=>dt!==st[it]||G[Xe]&&G[Xe].hasOwnProperty(dt.key))){Le=-1;break}++Le}for(const Xe in E.proxyCachedFBO[de.key])E.renderCache[E.proxyCachedFBO[de.key][Xe]].dirty=Le<0||Le!==Object.values(ye).length}}const X=[...this._drapedRenderBatches];X.sort((J,de)=>de.end-de.start-(J.end-J.start));for(const J of X)for(const de of F){if(E.proxyCachedFBO[de.key])continue;let ye=E.renderCachePool.pop();ye===void 0&&E.renderCache.length<50&&(ye=E.renderCache.length,E.renderCache.push(this._createFBO())),ye!==void 0&&(E.proxyCachedFBO[de.key]={},E.proxyCachedFBO[de.key][J.start]=ye,E.renderCache[ye].dirty=!0)}this._tilesDirty={}}_setupStencil(w,E,F,G){if(!G||!this._sourceTilesOverlap[G.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const X=this.painter.context,J=X.gl;if(E.length<=1)return void(this._overlapStencilType=!1);let de;if(F.isTileClipped())de=E.length,this._overlapStencilMode.test={func:J.EQUAL,mask:255},this._overlapStencilType="Clip";else{if(!(E[0].overscaledZ>E[E.length-1].overscaledZ))return void(this._overlapStencilType=!1);de=1,this._overlapStencilMode.test={func:J.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+de>255&&(X.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=de,this._overlapStencilMode.ref=this._stencilRef,F.isTileClipped()&&this._renderTileClippingMasks(E,this._overlapStencilMode.ref)}clipOrMaskOverlapStencilType(){return this._overlapStencilType==="Clip"||this._overlapStencilType==="Mask"}stencilModeForRTTOverlap(w){return this.renderingToTexture&&this._overlapStencilType?(this._overlapStencilType==="Clip"&&(this._overlapStencilMode.ref=this.painter._tileClippingMaskIDs[w.key]),this._overlapStencilMode):Da.disabled}_renderTileClippingMasks(w,E){const F=this.painter,G=this.painter.context,X=G.gl;F._tileClippingMaskIDs={},G.setColorMode(Ia.disabled),G.setDepthMode(Hr.disabled);const J=F.getOrCreateProgram("clippingMask");for(const de of w){const ye=F._tileClippingMaskIDs[de.key]=--E;J.draw(F,X.TRIANGLES,Hr.disabled,new Da({func:X.ALWAYS,mask:0},ye,255,X.KEEP,X.KEEP,X.REPLACE),Ia.disabled,fa.disabled,ht(de.projMatrix),"$clipping",F.tileExtentBuffer,F.quadTriangleIndexBuffer,F.tileExtentSegments)}}pointCoordinate(w){const E=this.painter.transform;if(w.x<0||w.x>E.width||w.y<0||w.y>E.height)return null;const F=[w.x,w.y,1,1];o.aE(F,F,E.pixelMatrixInverse),o.cu(F,F,1/F[3]),F[0]/=E.worldSize,F[1]/=E.worldSize;const G=E._camera.position,X=o.bU(1,E.center.lat),J=[G[0],G[1],G[2]/X,0],de=o.cV([],F.slice(0,3),J);o.ay(de,de);const ye=this.raycast(J,de,this._exaggeration);return ye!==null&&ye?(o.bg(J,J,de,ye),J[3]=J[2],J[2]*=X,J):null}_setupProxiedCoordsForOrtho(w,E,F){if(w.getSource()instanceof o.aV)return this._setupProxiedCoordsForImageSource(w,E,F);this._findCoveringTileCache[w.id]=this._findCoveringTileCache[w.id]||{};const G=this.proxiedCoords[w.id]=[],X=this.proxyCoords;for(let ye=0;yeLe.overscaledZ-Ce.overscaledZ)}_setupProxiedCoordsForImageSource(w,E,F){if(!w.getSource().loaded())return;const G=this.proxiedCoords[w.id]=[],X=this.proxyCoords,J=w.getSource(),de=J.tileID;if(!de)return;const ye=new o.P(de.x,de.y)._div(1<(Xe.min.x=Math.min(Xe.min.x,Ke.x-ye.x),Xe.min.y=Math.min(Xe.min.y,Ke.y-ye.y),Xe.max.x=Math.max(Xe.max.x,Ke.x-ye.x),Xe.max.y=Math.max(Xe.max.y,Ke.y-ye.y),Xe),{min:new o.P(Number.MAX_VALUE,Number.MAX_VALUE),max:new o.P(-Number.MAX_VALUE,-Number.MAX_VALUE)}),Le=(Xe,Ke)=>{const st=Xe.wrap+Xe.canonical.x/(1<jt+Ce.max.x||dt+itwt+Ce.max.y};for(let Xe=0;XeJ.key===E.tileID.key);if(X)return X}if(E.tileID.key!==w.key){const X=w.canonical.z-E.tileID.canonical.z;let J,de,ye;G=o.bb();const Ce=E.tileID.wrap-w.wrap<0?(J=o.an>>X,de=J*((E.tileID.canonical.x<=Xe){const Ke=w.canonical.z-Xe;E.getSource().reparseOverscaled?(de=Math.max(w.canonical.z+2,E.transform.tileZoom),J=new o.aR(de,w.wrap,Xe,w.canonical.x>>Ke,w.canonical.y>>Ke)):Ke!==0&&(de=Xe,J=new o.aR(de,w.wrap,Xe,w.canonical.x>>Ke,w.canonical.y>>Ke))}J.key!==w.key&&(Ce.push(J.key),F=E.getTile(J))}const Le=Xe=>{Ce.forEach(Ke=>{G[Ke]=Xe}),Ce.length=0};for(de-=1;de>=ye&&(!F||!F.hasData());de--){F&&Le(F.tileID.key);const Xe=J.calculateScaledKey(de);if(F=E.getTileByID(Xe),F&&F.hasData())break;const Ke=G[Xe];if(Ke===null)break;Ke===void 0?Ce.push(Xe):F=E.getTileByID(Ke)}return Le(F?F.tileID.key:null),F&&F.hasData()?F:null}findDEMTileFor(w){return this.enabled?this._findTileCoveringTileID(w,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0}_clearRenderCacheForTile(w,E){let F=this._tilesDirty[w];F||(F=this._tilesDirty[w]={}),F[E.key]=!0}}function Ps(D,w,E){const F=function(de,ye,Ce){const Le=o.bi(ye,de),Xe=o.bi(Ce,[.2126,.7152,.0722]),Ke=(dt,it,jt)=>(1-jt)*dt+jt*it,st=Ke(1-.3*Math.min(Xe,1),1,Math.min(Le+1,1));return Ke(.92,1,Math.asin(o.aC(ye[2],-1,1))/Math.PI+.5)*st}(D,[0,0,1],w),G=[0,0,0];o.bJ(G,E.slice(0,3),F);const X=[0,0,0];o.bJ(X,w.slice(0,3),D[2]);const J=[0,0,0];return o.cT(J,G,X),o.cW(J)}const Qs=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],En=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];class Xn{static cacheKey(w,E,F,G){const X=[E];G&&X.push(G.cacheKey);for(const J of F)(typeof J=="string"&&J.includes(" ")||w.usedDefines.has(J))&&X.push(J);return X.join("/")}constructor(w,E,F,G,X,J){const de=w.gl;this.program=de.createProgram(),this.configuration=G,this.name=E,this.fixedDefines=[...J];const ye=`#version 300 es ${(G?G.defines():[]).concat(J.map(it=>`#define ${it}`)).join(` `)}`,Ce=[ye,w1];for(const it of F.fragmentIncludes)Ce.push(Rf[it]);Ce.push(F.fragmentSource);const Le=Ce.join(` `),Xe=[ye,DN];for(const it of F.vertexIncludes)Xe.push(Rf[it]);this.forceManualRenderingForInstanceIDShaders=w.forceManualRenderingForInstanceIDShaders&&F.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&Xe.push("uniform int u_instanceID;"),Xe.push(F.vertexSource);let Ke=Xe.join(` `);this.forceManualRenderingForInstanceIDShaders&&(Ke=Ke.replaceAll("gl_InstanceID","u_instanceID"));const st=de.createShader(de.FRAGMENT_SHADER);if(de.isContextLost())return void(this.failedToCreate=!0);de.shaderSource(st,Le),de.compileShader(st),de.attachShader(this.program,st);const dt=de.createShader(de.VERTEX_SHADER);de.isContextLost()?this.failedToCreate=!0:(de.shaderSource(dt,Ke),de.compileShader(dt),de.attachShader(this.program,dt),this.attributes={},de.linkProgram(this.program),de.deleteShader(dt),de.deleteShader(st),this.fixedUniforms=X(w),this.fixedUniformsEntries=Object.entries(this.fixedUniforms),this.binderUniforms=G?G.getUniforms(w):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(it=>({u_instanceID:new o.bX(it)}))(w)),(J.includes("TERRAIN")||J.includes("ELEVATED")||E.includes("symbol")||E.includes("circle"))&&(this.terrainUniforms=(it=>({u_dem:new o.bX(it),u_dem_prev:new o.bX(it),u_dem_tl:new o.b_(it),u_dem_scale:new o.bZ(it),u_dem_tl_prev:new o.b_(it),u_dem_scale_prev:new o.bZ(it),u_dem_size:new o.bZ(it),u_dem_lerp:new o.bZ(it),u_exaggeration:new o.bZ(it),u_depth:new o.bX(it),u_depth_size_inv:new o.b_(it),u_depth_range_unpack:new o.b_(it),u_occluder_half_size:new o.bZ(it),u_occlusion_depth_offset:new o.bZ(it),u_meter_to_dem:new o.bZ(it),u_label_plane_matrix_inv:new o.b$(it)}))(w)),J.includes("GLOBE")&&(this.globeUniforms=(it=>({u_tile_tl_up:new o.bY(it),u_tile_tr_up:new o.bY(it),u_tile_br_up:new o.bY(it),u_tile_bl_up:new o.bY(it),u_tile_up_scale:new o.bZ(it)}))(w)),J.includes("FOG")&&(this.fogUniforms=(it=>({u_fog_matrix:new o.b$(it),u_fog_range:new o.b_(it),u_fog_color:new o.cO(it),u_fog_horizon_blend:new o.bZ(it),u_fog_vertical_limit:new o.b_(it),u_fog_temporal_offset:new o.bZ(it),u_frustum_tl:new o.bY(it),u_frustum_tr:new o.bY(it),u_frustum_br:new o.bY(it),u_frustum_bl:new o.bY(it),u_globe_pos:new o.bY(it),u_globe_radius:new o.bZ(it),u_globe_transition:new o.bZ(it),u_is_globe:new o.bX(it),u_viewport:new o.b_(it)}))(w)),J.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=(it=>({u_cutoff_params:new o.cO(it)}))(w)),J.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=(it=>({u_lighting_ambient_color:new o.bY(it),u_lighting_directional_dir:new o.bY(it),u_lighting_directional_color:new o.bY(it),u_ground_radiance:new o.bY(it)}))(w)),J.includes("RENDER_SHADOWS")&&(this.shadowUniforms=(it=>({u_light_matrix_0:new o.b$(it),u_light_matrix_1:new o.b$(it),u_fade_range:new o.b_(it),u_shadow_normal_offset:new o.bY(it),u_shadow_intensity:new o.bZ(it),u_shadow_texel_size:new o.bZ(it),u_shadow_map_resolution:new o.bZ(it),u_shadow_direction:new o.bY(it),u_shadow_bias:new o.bY(it),u_shadowmap_0:new o.bX(it),u_shadowmap_1:new o.bX(it)}))(w)))}getAttributeLocation(w,E){let F=this.attributes[E];return F===void 0&&(F=this.attributes[E]=w.getAttribLocation(this.program,E)),F}setTerrainUniformValues(w,E){if(!this.terrainUniforms)return;const F=this.terrainUniforms;if(!this.failedToCreate){w.program.set(this.program);for(const G in E)F[G]&&F[G].set(this.program,G,E[G])}}setGlobeUniformValues(w,E){if(!this.globeUniforms)return;const F=this.globeUniforms;if(!this.failedToCreate){w.program.set(this.program);for(const G in E)F[G]&&F[G].set(this.program,G,E[G])}}setFogUniformValues(w,E){if(!this.fogUniforms)return;const F=this.fogUniforms;if(!this.failedToCreate){w.program.set(this.program);for(const G in E)F[G].set(this.program,G,E[G])}}setCutoffUniformValues(w,E){if(!this.cutoffUniforms)return;const F=this.cutoffUniforms;if(!this.failedToCreate){w.program.set(this.program);for(const G in E)F[G].set(this.program,G,E[G])}}setLightsUniformValues(w,E){if(!this.lightsUniforms)return;const F=this.lightsUniforms;if(!this.failedToCreate){w.program.set(this.program);for(const G in E)F[G].set(this.program,G,E[G])}}setShadowUniformValues(w,E){if(this.failedToCreate||!this.shadowUniforms)return;const F=this.shadowUniforms;w.program.set(this.program);for(const G in E)F[G].set(this.program,G,E[G])}_drawDebugWireframe(w,E,F,G,X,J,de,ye,Ce,Le){const Xe=w.options.wireframe;if(Xe.terrain===!1&&Xe.layers2D===!1&&Xe.layers3D===!1)return;const Ke=w.context;if(!(!(!Xe.terrain||this.name!=="terrainRaster"&&this.name!=="globeRaster")||!(!Xe.layers2D||w._terrain&&w._terrain.renderingToTexture||!Qs.includes(this.name))||!(!Xe.layers3D||!En.includes(this.name))))return;const st=Ke.gl,dt=w.wireframeDebugCache.getLinesFromTrianglesBuffer(w.frameCounter,X,Ke);if(!dt)return;const it=[...this.fixedDefines,"DEBUG_WIREFRAME"],jt=w.getOrCreateProgram(this.name,{config:this.configuration,defines:it});Ke.program.set(jt.program);const wt=(Ct,Ss,rs)=>{if(Ss[Ct]&&rs[Ct])for(const _s in Ss[Ct])rs[Ct][_s]&&rs[Ct][_s].set(rs.program,_s,Ss[Ct][_s].current)};Ce&&Ce.setUniforms(jt.program,Ke,jt.binderUniforms,de,{zoom:ye}),wt("fixedUniforms",this,jt),wt("terrainUniforms",this,jt),wt("globeUniforms",this,jt),wt("fogUniforms",this,jt),wt("lightsUniforms",this,jt),wt("shadowUniforms",this,jt),dt.bind(),Ke.setColorMode(new Ia([st.ONE,st.ONE_MINUS_SRC_ALPHA,st.ZERO,st.ONE],o.aq.transparent,[!0,!0,!0,!1])),Ke.setDepthMode(new Hr(E.func===st.LESS?st.LEQUAL:E.func,Hr.ReadOnly,E.range)),Ke.setStencilMode(Da.disabled);const Bt=3*J.primitiveLength*2,Vt=3*J.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const Ct=Le||1;for(let Ss=0;Ss1?st.drawElementsInstanced(st.LINES,Bt,st.UNSIGNED_SHORT,Vt,Le):st.drawElements(st.LINES,Bt,st.UNSIGNED_SHORT,Vt);X.bind(),Ke.program.set(this.program),Ke.setDepthMode(E),Ke.setStencilMode(F),Ke.setColorMode(G)}checkUniforms(w,E,F){if(this.fixedDefines.includes(E)){for(const G of Object.keys(F))if(!F[G].initialized)throw new Error(`Program '${this.name}', from draw '${w}': uniform ${G} not set but required by ${E} being defined`)}}draw(w,E,F,G,X,J,de,ye,Ce,Le,Xe,Ke,st,dt,it,jt){const wt=w.context,Bt=wt.gl;if(this.failedToCreate)return;wt.program.set(this.program),wt.setDepthMode(F),wt.setStencilMode(G),wt.setColorMode(X),wt.setCullFace(J);for(const[Gt,ss]of this.fixedUniformsEntries)ss.set(this.program,Gt,de[Gt]);dt&&dt.setUniforms(this.program,wt,this.binderUniforms,Ke,{zoom:st});const Vt={[Bt.POINTS]:1,[Bt.LINES]:2,[Bt.TRIANGLES]:3,[Bt.LINE_STRIP]:1}[E];this.checkUniforms(ye,"RENDER_SHADOWS",this.shadowUniforms);const Ct=it||[],Ss=dt?dt.getPaintVertexBuffers():[],rs=E===Bt.TRIANGLES&&Le,_s=jt&&jt>0?1:void 0;for(const Gt of Xe.get()){const ss=Gt.vaos||(Gt.vaos={});if((ss[ye]||(ss[ye]=new IS)).bind(wt,this,Ce,Ss,Le,Gt.vertexOffset,Ct,_s),this.forceManualRenderingForInstanceIDShaders){const xs=jt||1;for(let Ks=0;Ks1?Bt.drawElementsInstanced(E,Gt.primitiveLength*Vt,Bt.UNSIGNED_SHORT,Gt.primitiveOffset*Vt*2,jt):Le?Bt.drawElements(E,Gt.primitiveLength*Vt,Bt.UNSIGNED_SHORT,Gt.primitiveOffset*Vt*2):Bt.drawArrays(E,Gt.vertexOffset,Gt.vertexLength);rs&&this._drawDebugWireframe(w,F,G,X,Le,Gt,Ke,st,dt,jt)}}}function Js(D,w,E=0){const F=Math.pow(2,w.tileID.overscaledZ),G=w.tileSize*Math.pow(2,D.transform.tileZoom)/F,X=G*(w.tileID.canonical.x+w.tileID.wrap*F),J=G*w.tileID.canonical.y;return{u_image:0,u_texsize:w.imageAtlasTexture?w.imageAtlasTexture.size:[0,0],u_tile_units_to_pixels:1/o.aA(w,1,D.transform.tileZoom),u_pixel_coord_upper:[X>>16,J>>16],u_pixel_coord_lower:[65535&X,65535&J],u_pattern_transition:E}}const Fn={terrain:0,flat:1},rr=o.bb(),Tr=(D,w,E,F,G,X,J,de,ye,Ce,Le,Xe,Ke,st,dt,it,jt,wt,Bt=[0,0,1])=>{const Vt=w.style.light,Ct=Vt.properties.get("position"),Ss=[Ct.x,Ct.y,Ct.z],rs=o.dE();Vt.properties.get("anchor")==="viewport"&&(o.dF(rs,-w.transform.angle),o.dG(Ss,Ss,rs));const _s=Vt.properties.get("color").toPremultipliedRenderColor(null),Gt=w.transform,ss={u_matrix:D,u_lightpos:Ss,u_lightintensity:Vt.properties.get("intensity"),u_lightcolor:[_s.r,_s.g,_s.b],u_vertical_gradient:+E,u_opacity:F,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:rr,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:Fn[Ce],u_base_type:Fn[Le],u_ao:G,u_edge_radius:X,u_width_scale:J,u_flood_light_color:dt,u_vertical_scale:it,u_flood_light_intensity:jt,u_ground_shadow_factor:wt,u_front_cutoff_params:Bt};return Gt.projection.name==="globe"&&(ss.u_tile_id=[de.canonical.x,de.canonical.y,1<({u_matrix:D,u_edge_radius:w,u_width_scale:E,u_vertical_scale:F,u_height_type:Fn[G],u_base_type:Fn[X]}),qn=(D,w,E,F,G,X,J,de,ye,Ce,Le,Xe,Ke,st,dt,it,jt,wt)=>{const Bt=Tr(D,w,E,F,G,X,J,de,Ce,Le,Xe,Ke,st,dt,it,jt,1,[0,0,0]),Vt={u_height_factor:-Math.pow(2,de.overscaledZ)/ye.tileSize/8};return Object.assign(Bt,Js(w,ye,wt),Vt)},Vr=(D,w,E)=>({u_matrix:D,u_emissive_strength:w,u_ground_shadow_factor:E}),wa=(D,w,E,F,G,X=0)=>Object.assign(Vr(D,w,G),Js(E,F,X)),ga=(D,w,E,F)=>({u_matrix:D,u_world:E,u_emissive_strength:w,u_ground_shadow_factor:F}),Xi=(D,w,E,F,G,X,J=0)=>Object.assign(wa(D,w,E,F,X,J),{u_world:G}),Mi=(D,w)=>({u_matrix:D,u_depth_bias:w}),yl=(D,w)=>({u_matrix:D,u_ground_shadow_factor:w}),Ui=(D,w,E,F,G)=>({u_matrix:D,u_camera_pos:[w[0],w[1],w[2]],u_depth_bias:E,u_height_scale:F,u_reset_depth:G}),ic=(D,w,E)=>({u_image:D,u_opacity:w,u_blend_mode:E}),cu=(D,w,E,F,G,X,J,de,ye,Ce=[0,0,1])=>({u_matrix:D,u_normal_matrix:w,u_opacity:E,u_faux_facade_ao_intensity:F,u_camera_pos:G,u_tile_to_meter:X,u_facade_emissive_chance:J,u_flood_light_color:de,u_flood_light_intensity:ye,u_front_cutoff_params:Ce}),vl=D=>({u_matrix:D}),Hi=D=>({u_matrix:D}),ci=(D,w,E,F,G,X,J,de)=>{const ye=o.an/X.tileSize;return{u_matrix:D,u_inv_rot_matrix:w,u_camera_to_center_distance:E.getCameraToCenterDistance(de),u_extrude_scale:[E.pixelsToGLUnits[0]/ye,E.pixelsToGLUnits[1]/ye],u_zoom_transition:F,u_tile_id:J,u_merc_center:G}},wl=(D,w,E,F)=>({u_matrix:D,u_inv_matrix:w,u_camera_to_center_distance:E.getCameraToCenterDistance(F),u_viewport_size:[E.width,E.height]}),vo=(D,w,E=1)=>({u_matrix:D,u_color:w,u_overlay:0,u_overlay_scale:E}),ul=o.bb(),su=(D,w,E,F,G,X,J)=>{const de=D.transform,ye=de.projection.name==="globe",Ce=ye?o.dH(de.zoom,w.canonical)*de._pixelsPerMercatorPixel:o.aA(E,1,X),Le={u_matrix:w.projMatrix,u_extrude_scale:Ce,u_intensity:J,u_inv_rot_matrix:ul,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(ye){Le.u_inv_rot_matrix=F,Le.u_merc_center=G,Le.u_tile_id=[w.canonical.x,w.canonical.y,1<({u_matrix:w,u_normalize_matrix:E,u_globe_matrix:F,u_merc_matrix:G,u_grid_matrix:X,u_tl_parent:J,u_scale_parent:Le,u_fade_t:Xe.mix,u_opacity:Xe.opacity*Ke.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:Ke.paint.get("raster-brightness-min"),u_brightness_high:Ke.paint.get("raster-brightness-max"),u_saturation_factor:o.dJ(Ke.paint.get("raster-saturation")),u_contrast_factor:o.dI(Ke.paint.get("raster-contrast")),u_spin_weights:Ff(Ke.paint.get("raster-hue-rotate")),u_perspective_transform:st,u_raster_elevation:dt,u_zoom_transition:de,u_merc_center:ye,u_cutoff_params:Ce,u_colorization_mix:vm(o.dK,jt,Bt),u_colorization_offset:nu(o.dK,wt,Bt),u_color_ramp:it,u_texture_offset:[Ct/(Vt+2*Ct),Vt/(Vt+2*Ct)],u_texture_res:[Vt+2*Ct,Vt+2*Ct],u_emissive_strength:Ss,u_zbias_factor:Lu(D)});function Ff(D){D*=Math.PI/180;const w=Math.sin(D),E=Math.cos(D);return[(2*E+1)/3,(-Math.sqrt(3)*w-E+1)/3,(Math.sqrt(3)*w-E+1)/3]}const qd=.05,Vc=(D,w,E,F,G,X,J,de,ye,Ce,Le,Xe)=>({u_matrix:D,u_normalize_matrix:w,u_globe_matrix:E,u_merc_matrix:F,u_grid_matrix:G,u_tl_parent:X,u_scale_parent:Ce,u_fade_t:Le.mix,u_opacity:Le.opacity,u_image0:0,u_image1:1,u_raster_elevation:Xe,u_zoom_transition:J,u_merc_center:de,u_cutoff_params:ye}),Ad=(D,w,E,F,G,X,J,de,ye,Ce)=>({u_particle_texture:D,u_particle_texture_side_len:w,u_tile_offset:E,u_velocity:F,u_color_ramp:X,u_velocity_res:G,u_max_speed:J,u_uv_offset:de,u_data_scale:[255*ye[0],255*ye[1]],u_data_offset:Ce,u_particle_pos_scale:1.1,u_particle_pos_offset:[qd,qd]}),th=(D,w,E,F,G,X,J,de,ye,Ce)=>({u_particle_texture:D,u_particle_texture_side_len:w,u_velocity:E,u_velocity_res:F,u_max_speed:G,u_speed_factor:X,u_reset_rate:J,u_rand_seed:Math.random(),u_uv_offset:de,u_data_scale:[255*ye[0],255*ye[1]],u_data_offset:Ce,u_particle_pos_scale:1.1,u_particle_pos_offset:[qd,qd]}),Jc=o.bb(),hh=(D,w,E,F,G,X,J,de,ye,Ce,Le,Xe,Ke,st,dt,it,jt,wt,Bt,Vt,Ct,Ss,rs,_s)=>{const Gt=G.transform,ss={u_is_size_zoom_constant:+(D==="constant"||D==="source"),u_is_size_feature_constant:+(D==="constant"||D==="camera"),u_size_t:w?w.uSizeT:0,u_size:w?w.uSize:0,u_camera_to_center_distance:Gt.getCameraToCenterDistance(Bt),u_rotate_symbol:+E,u_aspect_ratio:Gt.width/Gt.height,u_fade_change:G.options.fadeDuration?G.symbolFadeChange:1,u_matrix:X,u_label_plane_matrix:J,u_coord_matrix:de,u_is_text:+Ce,u_elevation_from_sea:ye?1:0,u_pitch_with_map:+F,u_texsize:Le,u_texsize_icon:Xe,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:Jc,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:Jc,u_up_vector:[0,-1,0],u_color_adj_mat:Ss,u_icon_transition:rs||0,u_gamma_scale:F?G.transform.getCameraToCenterDistance(Bt)*Math.cos(G.terrain?0:G.transform._pitch):1,u_device_pixel_ratio:o.o.devicePixelRatio,u_is_halo:1,u_scale_factor:_s||1,u_ground_shadow_factor:Vt,u_inv_matrix:o.b7(o.bb(),J),u_normal_scale:Ct,u_lutTexture:10,u_zoom:Gt.zoom-Math.floor(Gt.zoom),u_spp_fill_np_color:[0,0,0,1],u_spp_halo_np_color:[0,0,0,0],u_spp_opacity:1,u_spp_halo_width:0,u_spp_halo_blur:0,u_spp_emissive_strength:0,u_spp_occlusion_opacity:1,u_spp_z_offset:0,u_spp_translate_rotation:[1,0]};return Bt.name==="globe"&&(ss.u_tile_id=[st.canonical.x,st.canonical.y,1<({u_matrix:D,u_emissive_strength:w,u_opacity:E,u_color:F}),xd=(D,w,E,F,G,X,J,de,ye)=>Object.assign(function(Ce,Le,Xe,Ke,st,dt){const{width:it,height:jt}=Ke.imageManager.getPixelSize(Le),wt=Math.pow(2,dt.tileID.overscaledZ),Bt=dt.tileSize*Math.pow(2,Ke.transform.tileZoom)/wt,Vt=Bt*(dt.tileID.canonical.x+dt.tileID.wrap*wt),Ct=Bt*dt.tileID.canonical.y;return{u_image:0,u_pattern_tl:Xe.tl,u_pattern_br:Xe.br,u_texsize:[it,jt],u_pattern_size:Xe.displaySize,u_pattern_units_to_pixels:st?[Ke.transform.width,-1*Ke.transform.height]:[1/o.aA(dt,1,Ke.transform.tileZoom),1/o.aA(dt,1,Ke.transform.tileZoom)],u_pixel_coord_upper:[Vt>>16,Ct>>16],u_pixel_coord_lower:[65535&Vt,65535&Ct]}}(0,X,J,F,de,ye),{u_matrix:D,u_emissive_strength:w,u_opacity:E}),Ih=new Float32Array(o.b9([])),wc=(D,w,E,F,G,X,J,de,ye,Ce,Le,Xe,Ke,st=[0,0,0],dt,it,jt)=>{const wt=G.style.light,Bt=wt.properties.get("position"),Vt=[-Bt.x,-Bt.y,Bt.z],Ct=o.dE();wt.properties.get("anchor")==="viewport"&&(o.dF(Ct,-G.transform.angle),o.dG(Vt,Vt,Ct));const Ss=Le.alphaMode==="MASK",rs=wt.properties.get("color").toNonPremultipliedRenderColor(null),_s=Ke.paint.get("model-ambient-occlusion-intensity"),Gt=Ke.paint.get("model-color").constantOr(o.aq.white).toNonPremultipliedRenderColor(null);return Gt.a=Ke.paint.get("model-color-mix-intensity").constantOr(0),jt&&(Gt.r=jt[0],Gt.g=jt[1],Gt.b=jt[2],Gt.a=jt[3]),it&&(Gt.r=it.color.r,Gt.g=it.color.g,Gt.b=it.color.b,Gt.a=it.colorMix,Xe=it.emissionStrength,X*=it.opacity),{u_matrix:D,u_lighting_matrix:w,u_normal_matrix:E,u_node_matrix:F||Ih,u_lightpos:Vt,u_lightintensity:wt.properties.get("intensity"),u_lightcolor:[rs.r,rs.g,rs.b],u_camera_pos:st,u_opacity:X,u_baseTextureIsAlpha:0,u_alphaMask:+Ss,u_alphaCutoff:Le.alphaCutoff,u_baseColorFactor:J.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:de.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:ye,u_roughnessFactor:Ce,u_baseColorTexture:5,u_metallicRoughnessTexture:6,u_normalTexture:7,u_occlusionTexture:8,u_emissionTexture:9,u_lutTexture:10,u_color_mix:Gt.toArray01(),u_aoIntensity:_s,u_emissive_strength:Xe,u_occlusionTextureTransform:dt||[0,0,0,0]}},mh=(D,w=Ih,E=Ih)=>({u_matrix:D,u_instance:w,u_node_matrix:E}),yp={fillExtrusion:D=>({u_matrix:new o.b$(D),u_lightpos:new o.bY(D),u_lightintensity:new o.bZ(D),u_lightcolor:new o.bY(D),u_vertical_gradient:new o.bZ(D),u_opacity:new o.bZ(D),u_edge_radius:new o.bZ(D),u_width_scale:new o.bZ(D),u_ao:new o.b_(D),u_height_type:new o.bX(D),u_base_type:new o.bX(D),u_tile_id:new o.bY(D),u_zoom_transition:new o.bZ(D),u_inv_rot_matrix:new o.b$(D),u_merc_center:new o.b_(D),u_up_dir:new o.bY(D),u_height_lift:new o.bZ(D),u_flood_light_color:new o.bY(D),u_vertical_scale:new o.bZ(D),u_flood_light_intensity:new o.bZ(D),u_ground_shadow_factor:new o.bY(D),u_front_cutoff_params:new o.bY(D)}),fillExtrusionDepth:D=>({u_matrix:new o.b$(D),u_edge_radius:new o.bZ(D),u_width_scale:new o.bZ(D),u_vertical_scale:new o.bZ(D),u_height_type:new o.bX(D),u_base_type:new o.bX(D)}),fillExtrusionPattern:D=>({u_matrix:new o.b$(D),u_lightpos:new o.bY(D),u_lightintensity:new o.bZ(D),u_lightcolor:new o.bY(D),u_vertical_gradient:new o.bZ(D),u_height_factor:new o.bZ(D),u_edge_radius:new o.bZ(D),u_width_scale:new o.bZ(D),u_ao:new o.b_(D),u_height_type:new o.bX(D),u_base_type:new o.bX(D),u_tile_id:new o.bY(D),u_zoom_transition:new o.bZ(D),u_inv_rot_matrix:new o.b$(D),u_merc_center:new o.b_(D),u_up_dir:new o.bY(D),u_height_lift:new o.bZ(D),u_image:new o.bX(D),u_texsize:new o.b_(D),u_pixel_coord_upper:new o.b_(D),u_pixel_coord_lower:new o.b_(D),u_tile_units_to_pixels:new o.bZ(D),u_opacity:new o.bZ(D),u_pattern_transition:new o.bZ(D)}),fillExtrusionGroundEffect:D=>({u_matrix:new o.b$(D),u_opacity:new o.bZ(D),u_ao_pass:new o.bZ(D),u_meter_to_tile:new o.bZ(D),u_ao:new o.b_(D),u_flood_light_intensity:new o.bZ(D),u_flood_light_color:new o.bY(D),u_attenuation:new o.bZ(D),u_edge_radius:new o.bZ(D),u_fb:new o.bX(D),u_fb_size:new o.bZ(D),u_dynamic_offset:new o.bZ(D)}),fill:D=>({u_matrix:new o.b$(D),u_emissive_strength:new o.bZ(D),u_ground_shadow_factor:new o.bY(D)}),fillPattern:D=>({u_matrix:new o.b$(D),u_emissive_strength:new o.bZ(D),u_image:new o.bX(D),u_texsize:new o.b_(D),u_pixel_coord_upper:new o.b_(D),u_pixel_coord_lower:new o.b_(D),u_tile_units_to_pixels:new o.bZ(D),u_ground_shadow_factor:new o.bY(D),u_pattern_transition:new o.bZ(D)}),fillOutline:D=>({u_matrix:new o.b$(D),u_emissive_strength:new o.bZ(D),u_world:new o.b_(D),u_ground_shadow_factor:new o.bY(D)}),fillOutlinePattern:D=>({u_matrix:new o.b$(D),u_emissive_strength:new o.bZ(D),u_world:new o.b_(D),u_image:new o.bX(D),u_texsize:new o.b_(D),u_pixel_coord_upper:new o.b_(D),u_pixel_coord_lower:new o.b_(D),u_tile_units_to_pixels:new o.bZ(D),u_ground_shadow_factor:new o.bY(D),u_pattern_transition:new o.bZ(D)}),lineBlendComposite:D=>({u_image:new o.bX(D),u_opacity:new o.bZ(D),u_blend_mode:new o.bX(D)}),building:D=>({u_matrix:new o.b$(D),u_normal_matrix:new o.b$(D),u_opacity:new o.bZ(D),u_faux_facade_ao_intensity:new o.bZ(D),u_camera_pos:new o.bY(D),u_tile_to_meter:new o.bZ(D),u_facade_emissive_chance:new o.bZ(D),u_flood_light_color:new o.bY(D),u_flood_light_intensity:new o.bZ(D),u_front_cutoff_params:new o.bY(D)}),buildingBloom:D=>({u_matrix:new o.b$(D)}),buildingDepth:D=>({u_matrix:new o.b$(D)}),elevatedStructuresDepth:D=>({u_matrix:new o.b$(D),u_depth_bias:new o.bZ(D)}),elevatedStructures:D=>({u_matrix:new o.b$(D),u_ground_shadow_factor:new o.bY(D)}),elevatedStructuresDepthReconstruct:D=>({u_matrix:new o.b$(D),u_camera_pos:new o.bY(D),u_depth_bias:new o.bZ(D),u_height_scale:new o.bZ(D),u_reset_depth:new o.bZ(D)}),circle:o.dO,collisionBox:D=>({u_matrix:new o.b$(D),u_inv_rot_matrix:new o.b$(D),u_camera_to_center_distance:new o.bZ(D),u_extrude_scale:new o.b_(D),u_zoom_transition:new o.bZ(D),u_merc_center:new o.b_(D),u_tile_id:new o.bY(D)}),collisionCircle:D=>({u_matrix:new o.b$(D),u_inv_matrix:new o.b$(D),u_camera_to_center_distance:new o.bZ(D),u_viewport_size:new o.b_(D)}),debug:D=>({u_color:new o.dl(D),u_matrix:new o.b$(D),u_overlay:new o.bX(D),u_overlay_scale:new o.bZ(D)}),clippingMask:D=>({u_matrix:new o.b$(D)}),heatmap:D=>({u_extrude_scale:new o.bZ(D),u_intensity:new o.bZ(D),u_matrix:new o.b$(D),u_inv_rot_matrix:new o.b$(D),u_merc_center:new o.b_(D),u_tile_id:new o.bY(D),u_zoom_transition:new o.bZ(D),u_up_dir:new o.bY(D)}),heatmapTexture:D=>({u_image:new o.bX(D),u_color_ramp:new o.bX(D),u_opacity:new o.bZ(D)}),hillshade:D=>({u_matrix:new o.b$(D),u_image:new o.bX(D),u_latrange:new o.b_(D),u_light:new o.b_(D),u_shadow:new o.dl(D),u_highlight:new o.dl(D),u_emissive_strength:new o.bZ(D),u_accent:new o.dl(D)}),hillshadePrepare:D=>({u_matrix:new o.b$(D),u_image:new o.bX(D),u_dimension:new o.b_(D),u_zoom:new o.bZ(D)}),line:o.dN,linePattern:o.dM,raster:D=>({u_matrix:new o.b$(D),u_normalize_matrix:new o.b$(D),u_globe_matrix:new o.b$(D),u_merc_matrix:new o.b$(D),u_grid_matrix:new o.dm(D),u_tl_parent:new o.b_(D),u_scale_parent:new o.bZ(D),u_fade_t:new o.bZ(D),u_opacity:new o.bZ(D),u_image0:new o.bX(D),u_image1:new o.bX(D),u_brightness_low:new o.bZ(D),u_brightness_high:new o.bZ(D),u_saturation_factor:new o.bZ(D),u_contrast_factor:new o.bZ(D),u_spin_weights:new o.bY(D),u_perspective_transform:new o.b_(D),u_raster_elevation:new o.bZ(D),u_zoom_transition:new o.bZ(D),u_merc_center:new o.b_(D),u_cutoff_params:new o.cO(D),u_colorization_mix:new o.cO(D),u_colorization_offset:new o.bZ(D),u_color_ramp:new o.bX(D),u_texture_offset:new o.b_(D),u_texture_res:new o.b_(D),u_emissive_strength:new o.bZ(D),u_zbias_factor:new o.bZ(D)}),rasterParticle:D=>({u_matrix:new o.b$(D),u_normalize_matrix:new o.b$(D),u_globe_matrix:new o.b$(D),u_merc_matrix:new o.b$(D),u_grid_matrix:new o.dm(D),u_tl_parent:new o.b_(D),u_scale_parent:new o.bZ(D),u_fade_t:new o.bZ(D),u_opacity:new o.bZ(D),u_image0:new o.bX(D),u_image1:new o.bX(D),u_raster_elevation:new o.bZ(D),u_zoom_transition:new o.bZ(D),u_merc_center:new o.b_(D),u_cutoff_params:new o.cO(D)}),rasterParticleTexture:D=>({u_texture:new o.bX(D),u_opacity:new o.bZ(D)}),rasterParticleDraw:D=>({u_particle_texture:new o.bX(D),u_particle_texture_side_len:new o.bZ(D),u_tile_offset:new o.b_(D),u_velocity:new o.bX(D),u_color_ramp:new o.bX(D),u_velocity_res:new o.b_(D),u_max_speed:new o.bZ(D),u_uv_offset:new o.b_(D),u_data_scale:new o.b_(D),u_data_offset:new o.bZ(D),u_particle_pos_scale:new o.bZ(D),u_particle_pos_offset:new o.b_(D)}),rasterParticleUpdate:D=>({u_particle_texture:new o.bX(D),u_particle_texture_side_len:new o.bZ(D),u_velocity:new o.bX(D),u_velocity_res:new o.b_(D),u_max_speed:new o.bZ(D),u_speed_factor:new o.bZ(D),u_reset_rate:new o.bZ(D),u_rand_seed:new o.bZ(D),u_uv_offset:new o.b_(D),u_data_scale:new o.b_(D),u_data_offset:new o.bZ(D),u_particle_pos_scale:new o.bZ(D),u_particle_pos_offset:new o.b_(D)}),symbol:D=>({u_is_size_zoom_constant:new o.bX(D),u_is_size_feature_constant:new o.bX(D),u_size_t:new o.bZ(D),u_size:new o.bZ(D),u_camera_to_center_distance:new o.bZ(D),u_rotate_symbol:new o.bX(D),u_aspect_ratio:new o.bZ(D),u_fade_change:new o.bZ(D),u_matrix:new o.b$(D),u_label_plane_matrix:new o.b$(D),u_coord_matrix:new o.b$(D),u_is_text:new o.bX(D),u_elevation_from_sea:new o.bX(D),u_pitch_with_map:new o.bX(D),u_texsize:new o.b_(D),u_texsize_icon:new o.b_(D),u_texture:new o.bX(D),u_texture_icon:new o.bX(D),u_gamma_scale:new o.bZ(D),u_device_pixel_ratio:new o.bZ(D),u_tile_id:new o.bY(D),u_zoom_transition:new o.bZ(D),u_inv_rot_matrix:new o.b$(D),u_merc_center:new o.b_(D),u_camera_forward:new o.bY(D),u_tile_matrix:new o.b$(D),u_up_vector:new o.bY(D),u_ecef_origin:new o.bY(D),u_is_halo:new o.bX(D),u_icon_transition:new o.bZ(D),u_color_adj_mat:new o.b$(D),u_scale_factor:new o.bZ(D),u_ground_shadow_factor:new o.bY(D),u_inv_matrix:new o.b$(D),u_normal_scale:new o.bZ(D),u_lutTexture:new o.bX(D),u_zoom:new o.bZ(D),u_spp_fill_np_color:new o.cO(D),u_spp_halo_np_color:new o.cO(D),u_spp_opacity:new o.bZ(D),u_spp_halo_width:new o.bZ(D),u_spp_halo_blur:new o.bZ(D),u_spp_emissive_strength:new o.bZ(D),u_spp_occlusion_opacity:new o.bZ(D),u_spp_z_offset:new o.bZ(D),u_spp_translate_rotation:new o.b_(D)}),background:D=>({u_matrix:new o.b$(D),u_emissive_strength:new o.bZ(D),u_opacity:new o.bZ(D),u_color:new o.dl(D)}),backgroundPattern:D=>({u_matrix:new o.b$(D),u_emissive_strength:new o.bZ(D),u_opacity:new o.bZ(D),u_image:new o.bX(D),u_pattern_tl:new o.b_(D),u_pattern_br:new o.b_(D),u_texsize:new o.b_(D),u_pattern_size:new o.b_(D),u_pixel_coord_upper:new o.b_(D),u_pixel_coord_lower:new o.b_(D),u_pattern_units_to_pixels:new o.b_(D)}),terrainRaster:D=>({u_matrix:new o.b$(D),u_image0:new o.bX(D),u_image1:new o.bX(D),u_skirt_height:new o.bZ(D),u_ground_shadow_factor:new o.bY(D),u_emissive_texture_available:new o.bZ(D)}),skybox:D=>({u_matrix:new o.b$(D),u_sun_direction:new o.bY(D),u_cubemap:new o.bX(D),u_opacity:new o.bZ(D),u_temporal_offset:new o.bZ(D)}),skyboxGradient:D=>({u_matrix:new o.b$(D),u_color_ramp:new o.bX(D),u_center_direction:new o.bY(D),u_radius:new o.bZ(D),u_opacity:new o.bZ(D),u_temporal_offset:new o.bZ(D)}),skyboxCapture:D=>({u_matrix_3f:new o.dm(D),u_sun_direction:new o.bY(D),u_sun_intensity:new o.bZ(D),u_color_tint_r:new o.cO(D),u_color_tint_m:new o.cO(D),u_luminance:new o.bZ(D)}),globeRaster:D=>({u_proj_matrix:new o.b$(D),u_globe_matrix:new o.b$(D),u_normalize_matrix:new o.b$(D),u_merc_matrix:new o.b$(D),u_zoom_transition:new o.bZ(D),u_merc_center:new o.b_(D),u_image0:new o.bX(D),u_image1:new o.bX(D),u_grid_matrix:new o.dm(D),u_skirt_height:new o.bZ(D),u_far_z_cutoff:new o.bZ(D),u_frustum_tl:new o.bY(D),u_frustum_tr:new o.bY(D),u_frustum_br:new o.bY(D),u_frustum_bl:new o.bY(D),u_globe_pos:new o.bY(D),u_globe_radius:new o.bZ(D),u_viewport:new o.b_(D),u_emissive_texture_available:new o.bZ(D)}),globeAtmosphere:D=>({u_frustum_tl:new o.bY(D),u_frustum_tr:new o.bY(D),u_frustum_br:new o.bY(D),u_frustum_bl:new o.bY(D),u_horizon:new o.bZ(D),u_transition:new o.bZ(D),u_fadeout_range:new o.bZ(D),u_atmosphere_fog_color:new o.cO(D),u_high_color:new o.cO(D),u_space_color:new o.cO(D),u_temporal_offset:new o.bZ(D),u_horizon_angle:new o.bZ(D)}),model:D=>({u_matrix:new o.b$(D),u_lighting_matrix:new o.b$(D),u_normal_matrix:new o.b$(D),u_node_matrix:new o.b$(D),u_lightpos:new o.bY(D),u_lightintensity:new o.bZ(D),u_lightcolor:new o.bY(D),u_camera_pos:new o.bY(D),u_opacity:new o.bZ(D),u_baseColorFactor:new o.cO(D),u_emissiveFactor:new o.cO(D),u_metallicFactor:new o.bZ(D),u_roughnessFactor:new o.bZ(D),u_baseTextureIsAlpha:new o.bX(D),u_alphaMask:new o.bX(D),u_alphaCutoff:new o.bZ(D),u_baseColorTexture:new o.bX(D),u_metallicRoughnessTexture:new o.bX(D),u_normalTexture:new o.bX(D),u_occlusionTexture:new o.bX(D),u_emissionTexture:new o.bX(D),u_lutTexture:new o.bX(D),u_color_mix:new o.cO(D),u_aoIntensity:new o.bZ(D),u_emissive_strength:new o.bZ(D),u_occlusionTextureTransform:new o.cO(D)}),modelDepth:D=>({u_matrix:new o.b$(D),u_instance:new o.b$(D),u_node_matrix:new o.b$(D)}),groundShadow:D=>({u_matrix:new o.b$(D),u_ground_shadow_factor:new o.bY(D)}),stars:D=>({u_matrix:new o.b$(D),u_up:new o.bY(D),u_right:new o.bY(D),u_intensity_multiplier:new o.bZ(D)}),snowParticle:D=>({u_modelview:new o.b$(D),u_projection:new o.b$(D),u_time:new o.bZ(D),u_cam_pos:new o.bY(D),u_velocityConeAperture:new o.bZ(D),u_velocity:new o.bZ(D),u_horizontalOscillationRadius:new o.bZ(D),u_horizontalOscillationRate:new o.bZ(D),u_boxSize:new o.bZ(D),u_billboardSize:new o.bZ(D),u_simpleShapeParameters:new o.b_(D),u_screenSize:new o.b_(D),u_thinningCenterPos:new o.b_(D),u_thinningShape:new o.bY(D),u_thinningAffectedRatio:new o.bZ(D),u_thinningParticleOffset:new o.bZ(D),u_particleColor:new o.cO(D),u_direction:new o.bY(D)}),rainParticle:D=>({u_modelview:new o.b$(D),u_projection:new o.b$(D),u_time:new o.bZ(D),u_cam_pos:new o.bY(D),u_texScreen:new o.bX(D),u_velocityConeAperture:new o.bZ(D),u_velocity:new o.bZ(D),u_boxSize:new o.bZ(D),u_rainDropletSize:new o.b_(D),u_distortionStrength:new o.bZ(D),u_rainDirection:new o.bY(D),u_color:new o.cO(D),u_screenSize:new o.b_(D),u_thinningCenterPos:new o.b_(D),u_thinningShape:new o.bY(D),u_thinningAffectedRatio:new o.bZ(D),u_thinningParticleOffset:new o.bZ(D),u_shapeDirectionalPower:new o.bZ(D),u_shapeNormalPower:new o.bZ(D),u_mode:new o.bZ(D)}),vignette:D=>({u_vignetteShape:new o.bY(D),u_vignetteColor:new o.cO(D)}),occlusion:D=>({u_matrix:new o.b$(D),u_anchorPos:new o.bY(D),u_screenSizePx:new o.b_(D),u_occluderSizePx:new o.b_(D),u_color:new o.cO(D)})};class du{constructor(w,E,F,G){this.id=du.uniqueIdxCounter,du.uniqueIdxCounter++,this.context=w;const X=w.gl;this.buffer=X.createBuffer(),this.dynamicDraw=!!F,this.context.unbindVAO(),w.bindElementBuffer.set(this.buffer),X.bufferData(X.ELEMENT_ARRAY_BUFFER,E.arrayBuffer,this.dynamicDraw?X.DYNAMIC_DRAW:X.STATIC_DRAW),this.dynamicDraw||G||E.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(w){this.id=du.uniqueIdxCounter,du.uniqueIdxCounter++;const E=this.context.gl;this.context.unbindVAO(),this.bind(),E.bufferSubData(E.ELEMENT_ARRAY_BUFFER,0,w.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}du.uniqueIdxCounter=0;const zf={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class Bf{constructor(w,E,F,G,X,J){this.length=E.length,this.attributes=F,this.itemSize=E.bytesPerElement,this.dynamicDraw=G,this.instanceCount=J,this.context=w;const de=w.gl;this.buffer=de.createBuffer(),w.bindVertexBuffer.set(this.buffer),de.bufferData(de.ARRAY_BUFFER,E.arrayBuffer,this.dynamicDraw?de.DYNAMIC_DRAW:de.STATIC_DRAW),this.dynamicDraw||X||E.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(w){const E=this.context.gl;this.bind(),E.bufferSubData(E.ARRAY_BUFFER,0,w.arrayBuffer)}enableAttributes(w,E){for(const F of this.attributes){const G=E.getAttributeLocation(w,F.name);G!==-1&&w.enableVertexAttribArray(G)}}setVertexAttribPointers(w,E,F){for(const G of this.attributes){const X=E.getAttributeLocation(w,G.name);if(X!==-1){const J=G.offset+this.itemSize*(F||0);G.type==="Float32"?w.vertexAttribPointer(X,G.components,w.FLOAT,!1,this.itemSize,J):w.vertexAttribIPointer(X,G.components,w[zf[G.type]],this.itemSize,J)}}}setVertexAttribDivisor(w,E,F){for(let G=0;G0&&w.vertexAttribDivisor(X,F)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class vp{constructor(w,E,F,G,X){this.context=w,this.width=E,this.height=F;const J=this.framebuffer=w.gl.createFramebuffer();G>0&&(this.colorAttachment0=new Z_(w,J,0)),G>1&&(this.colorAttachment1=new Z_(w,J,1)),X&&(this.depthAttachmentType=X,this.depthAttachment=X==="renderbuffer"?new zN(w,J):new BS(w,J))}static createWithTexture(w,E,F,G,X){const J=w.gl;if(w.activeTexture.set(J.TEXTURE1),w.viewport.set([0,0,F,G]),E&&E.width===F&&E.height===G)return J.bindTexture(J.TEXTURE_2D,E.colorAttachment0.get()),w.bindFramebuffer.set(E.framebuffer),E;E&&E.destroy();const de=new o.T(w,{width:F,height:G,data:null},w.extRenderToTextureHalfFloat?w.gl.RGBA16F:w.gl.RGBA8);de.bind(J.LINEAR,J.CLAMP_TO_EDGE);const ye=w.createFramebuffer(F,G,1,null);if(ye.colorAttachment0.set(de.texture),X){const Ce=w.createRenderbuffer(J.DEPTH24_STENCIL8,F,G);w.bindFramebuffer.set(ye.framebuffer),J.framebufferRenderbuffer(J.FRAMEBUFFER,J.DEPTH_STENCIL_ATTACHMENT,J.RENDERBUFFER,Ce),ye._stencilRbo=Ce}return ye}createColorAttachment(w,E){E===0?this.colorAttachment0=new Z_(w,this.framebuffer,0):E===1&&(this.colorAttachment1=new Z_(w,this.framebuffer,1))}removeColorAttachment(w,E){const F=this.context.gl;let G;E===0?(G=this.colorAttachment0.get(),this.colorAttachment0=void 0):E===1&&(G=this.colorAttachment1.get(),this.colorAttachment1=void 0),G&&F.deleteTexture(G)}destroy(){const w=this.context.gl;if(this.colorAttachment0){const E=this.colorAttachment0.get();E&&w.deleteTexture(E)}if(this.colorAttachment1){const E=this.colorAttachment1.get();E&&w.deleteTexture(E)}if(this.depthAttachment&&this.depthAttachmentType)if(this.depthAttachmentType==="renderbuffer"){const E=this.depthAttachment.get();E&&w.deleteRenderbuffer(E)}else{const E=this.depthAttachment.get();E&&w.deleteTexture(E)}this._stencilRbo&&(w.deleteRenderbuffer(this._stencilRbo),this._stencilRbo=null),w.deleteFramebuffer(this.framebuffer)}}class rm{constructor(w,E){this.gl=w,this.clearColor=new K_(this),this.clearDepth=new A3(this),this.clearStencil=new Ib(this),this.colorMask=new yL(this),this.depthMask=new E0(this),this.stencilMask=new Lj(this),this.stencilFunc=new Y_(this),this.stencilOp=new RS(this),this.stencilTest=new Rb(this),this.depthRange=new Db(this),this.depthTest=new bg(this),this.depthFunc=new Pu(this),this.blend=new T0(this),this.blendFunc=new ON(this),this.blendColor=new E3(this),this.blendEquation=new ex(this),this.cullFace=new Df(this),this.cullFaceSide=new FN(this),this.frontFace=new DS(this),this.program=new Ij(this),this.activeTexture=new Rj(this),this.viewport=new Of(this),this.bindFramebuffer=new Qp(this),this.bindRenderbuffer=new T3(this),this.bindTexture=new Av(this),this.bindVertexBuffer=new Dj(this),this.bindElementBuffer=new Oj(this),this.bindVertexArrayOES=new OS(this),this.pixelStoreUnpack=new FS(this),this.pixelStoreUnpackPremultiplyAlpha=new zS(this),this.pixelStoreUnpackFlipY=new Fj(this),this.options=E?Object.assign({},E):{},this.options.extTextureFilterAnisotropicForceOff||(this.extTextureFilterAnisotropic=w.getExtension("EXT_texture_filter_anisotropic")||w.getExtension("MOZ_EXT_texture_filter_anisotropic")||w.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=w.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT))),this.extDebugRendererInfo=w.getExtension("WEBGL_debug_renderer_info"),this.extDebugRendererInfo&&(this.renderer=w.getParameter(this.extDebugRendererInfo.UNMASKED_RENDERER_WEBGL),this.vendor=w.getParameter(this.extDebugRendererInfo.UNMASKED_VENDOR_WEBGL)),this.forceManualRenderingForInstanceIDShaders=E&&!!E.forceManualRenderingForInstanceIDShaders||this.renderer&&this.renderer.indexOf("PowerVR")!==-1,this.disableSymbolUBO=E&&!!E.forceDisableSymbolUBO,this.options.extTextureFloatLinearForceOff||(this.extTextureFloatLinear=w.getExtension("OES_texture_float_linear")),this.extRenderToTextureHalfFloat=w.getExtension("EXT_color_buffer_half_float"),this.extTimerQuery=w.getExtension("EXT_disjoint_timer_query_webgl2"),this.maxTextureSize=w.getParameter(w.MAX_TEXTURE_SIZE),this.maxUniformBlockSize=Math.min(w.getParameter(w.MAX_UNIFORM_BLOCK_SIZE),32768),this.maxUniformBufferBindings=w.getParameter(w.MAX_UNIFORM_BUFFER_BINDINGS),this.extBlendFuncExtended=w.getExtension("WEBGL_blend_func_extended")}setDefault(){this.unbindVAO(),this.clearColor.setDefault(),this.clearDepth.setDefault(),this.clearStencil.setDefault(),this.colorMask.setDefault(),this.depthMask.setDefault(),this.stencilMask.setDefault(),this.stencilFunc.setDefault(),this.stencilOp.setDefault(),this.stencilTest.setDefault(),this.depthRange.setDefault(),this.depthTest.setDefault(),this.depthFunc.setDefault(),this.blend.setDefault(),this.blendFunc.setDefault(),this.blendColor.setDefault(),this.blendEquation.setDefault(),this.cullFace.setDefault(),this.cullFaceSide.setDefault(),this.frontFace.setDefault(),this.program.setDefault(),this.activeTexture.setDefault(),this.bindFramebuffer.setDefault(),this.pixelStoreUnpack.setDefault(),this.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.pixelStoreUnpackFlipY.setDefault()}setDirty(){this.clearColor.dirty=!0,this.clearDepth.dirty=!0,this.clearStencil.dirty=!0,this.colorMask.dirty=!0,this.depthMask.dirty=!0,this.stencilMask.dirty=!0,this.stencilFunc.dirty=!0,this.stencilOp.dirty=!0,this.stencilTest.dirty=!0,this.depthRange.dirty=!0,this.depthTest.dirty=!0,this.depthFunc.dirty=!0,this.blend.dirty=!0,this.blendFunc.dirty=!0,this.blendColor.dirty=!0,this.blendEquation.dirty=!0,this.cullFace.dirty=!0,this.cullFaceSide.dirty=!0,this.frontFace.dirty=!0,this.program.dirty=!0,this.activeTexture.dirty=!0,this.viewport.dirty=!0,this.bindFramebuffer.dirty=!0,this.bindRenderbuffer.dirty=!0,this.bindTexture.dirty=!0,this.bindVertexBuffer.dirty=!0,this.bindElementBuffer.dirty=!0,this.bindVertexArrayOES.dirty=!0,this.pixelStoreUnpack.dirty=!0,this.pixelStoreUnpackPremultiplyAlpha.dirty=!0,this.pixelStoreUnpackFlipY.dirty=!0}createIndexBuffer(w,E,F){return new du(this,w,E,F)}createVertexBuffer(w,E,F,G,X){return new Bf(this,w,E,F,G,X)}createRenderbuffer(w,E,F){const G=this.gl,X=G.createRenderbuffer();return this.bindRenderbuffer.set(X),G.renderbufferStorage(G.RENDERBUFFER,w,E,F),this.bindRenderbuffer.set(null),X}createFramebuffer(w,E,F,G){return new vp(this,w,E,F,G)}clear({color:w,depth:E,stencil:F,colorMask:G}){const X=this.gl;let J=0;w&&(J|=X.COLOR_BUFFER_BIT,this.clearColor.set(w.toNonPremultipliedRenderColor(null)),this.colorMask.set(G||[!0,!0,!0,!0])),E!==void 0&&(J|=X.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(E),this.depthMask.set(!0)),F!==void 0&&(J|=X.STENCIL_BUFFER_BIT,this.clearStencil.set(F),this.stencilMask.set(255)),X.clear(J)}setCullFace(w){w.enable===!1?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(w.mode),this.frontFace.set(w.frontFace))}setDepthMode(w){w.func!==this.gl.ALWAYS||w.mask?(this.depthTest.set(!0),this.depthFunc.set(w.func),this.depthMask.set(w.mask),this.depthRange.set(w.range)):this.depthTest.set(!1)}setStencilMode(w){w.test.func!==this.gl.ALWAYS||w.mask?(this.stencilTest.set(!0),this.stencilMask.set(w.mask),this.stencilOp.set([w.fail,w.depthFail,w.pass]),this.stencilFunc.set({func:w.test.func,ref:w.ref,mask:w.test.mask})):this.stencilTest.set(!1)}setColorMode(w){o.b6(w.blendFunction,Ia.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(w.blendFunction),this.blendColor.set(w.blendColor),w.blendEquation?this.blendEquation.set(w.blendEquation):this.blendEquation.setDefault()),this.colorMask.set(w.mask)}unbindVAO(){this.bindVertexArrayOES.set(null)}}let Hc;function wr(D,w,E,F,G,X,J){const de=D.context,ye=de.gl,Ce=D.transform,Le=[o.aH(Ce.center.lng),o.aL(Ce.center.lat)],Xe=E.layout.get("symbol-placement"),Ke=E.layout.get("text-variable-anchor"),st=E.layout.get("icon-rotation-alignment")==="map",dt=E.layout.get("text-rotation-alignment")==="map",it=Xe!=="point",jt=[];let wt=0,Bt=0;for(let Gt=0;Gt0){const Na=o.bb(),ea=ur;o.cz(Na,Ks.placementInvProjMatrix,Ce.glCoordMatrix),o.cz(Na,Na,Ks.placementViewportMatrix),jt.push({circleArray:Vn,circleOffset:Bt,transform:ea,invTransform:Na,projection:Ks.getProjection()}),wt+=Vn.length/4,Bt=wt}if(!hr)continue;D.terrain&&D.terrain.setupElevationDraw(xs,jr);const ca=jn?[ss.canonical.x,ss.canonical.y,1<=0&&(st[Vt.associatedIconIndex]={x:Ts,y:_n,z:hn,angle:yn})}else kt(rs,Xe)}if(Ce){Ke.clear();const Bt=D.icon.placedSymbolArray;for(let Vt=0;Vt{let Ti=[0,0,0];if(ml){const yd=D.style.directionalLight,lc=D.style.ambientLight;yd&&lc&&(Ti=tm(D.style,yd,lc))}return Ti},eo=ml=>{if(D.context.disableSymbolUBO)return;ml.push("USE_PAINT_PROPERTIES_UBO");const Ti=Math.floor(D.context.maxUniformBlockSize/4),yd=Math.floor(Ti/4);ml.push(`MAX_UBO_SIZE_VEC4 ${yd}u`)},vi=ml=>{ss.depthOcclusionForSymbolsAndCircles&&(E.hasOcclusionOpacityProperties||D.terrain)&&(ml.push("DEPTH_D24"),ml.push("DEPTH_OCCLUSION"))},Wo=ml=>{E.lut&&!rs&&(E.lut.texture||(E.lut.texture=new o.dR(D.context,E.lut.image,[E.lut.image.height,E.lut.image.height,E.lut.image.height],_s.gl.RGBA8)),_s.activeTexture.set(_s.gl.TEXTURE0+10),E.lut.texture&&E.lut.texture.bind(_s.gl.LINEAR,_s.gl.CLAMP_TO_EDGE),ml.push("APPLY_LUT_ON_GPU"))},oc=()=>{const ml=xs&&E.layout.get("symbol-placement")!=="point",Ti=[];vi(Ti),Wo(Ti);const yd=ml||Ni,lc=Vn.elevationType==="road",gh=D.shadowRenderer,po=lc&&Ts&&!!gh&&gh.enabled,jc=Ha(po),am=lc&&Ts&&!D.terrain?en:Kn,jg=E.paint.get("icon-image-cross-fade");D.terrainRenderModeElevated()&&Ts&&Ti.push("PITCH_WITH_MAP_TERRAIN"),ca&&(Ti.push("PROJECTION_GLOBE_VIEW"),yd&&Ti.push("PROJECTED_POS_ON_VIEWPORT")),jg>0&&Vn.hasAnySecondaryIcon&&Ti.push("ICON_TRANSITION"),!Vn.icon.zOffsetVertexBuffer||lc&&D.terrain||Ti.push("Z_OFFSET"),wt===0&&Bt===0&&Vt===0&&Ct===1||Ti.push("COLOR_ADJUSTMENT"),Vn.sdfIcons&&Ti.push("RENDER_SDF"),po&&Ti.push("RENDER_SHADOWS","NORMAL_OFFSET"),lc&&Ts&&!D.terrain&&Vn.icon.orientationVertexBuffer&&Ti.push("ELEVATED_ROADS"),eo(Ti);const _m=_s.disableSymbolUBO?Vn.icon.programConfigurations.get(E.id):null,ef=D.getOrCreateProgram("symbol",{config:_m,defines:Ti}),Pv=hr.imageAtlasTexture?hr.imageAtlasTexture.size:[0,0],Rl=Vn.iconSizeData,E1=o.bj(Rl,ss.zoom),T1=Ts||!ss.isOrthographic,Fc=zd(ea,hr.tileID.canonical,Ts,xs,ss,Vn.getProjection(),ia),Kc=Gp(ea,hr.tileID.canonical,Ts,xs,ss,Vn.getProjection(),ia),Kl=Vn.icon.uboBinder&&Vn.icon.uboBinder.cachedHeader&&256&Vn.icon.uboBinder.cachedHeader.dataDrivenMask?[0,0]:de,nh=D.translatePosMatrix(Kc,hr,Kl,Ce,!0),nx=D.translatePosMatrix(ea,hr,Kl,Ce),hu=yd?To:Fc,Lv=xs&&!Ts&&!ml;let KS=jr;!jn&&!ss.mercatorFromTransition||xs||(KS=cd(ss));const B3=ca?KS:jr,U3=E.getColorAdjustmentMatrix(wt,Bt,Vt,Ct),BE=hh(Rl.kind,E1,Lv,Ts,D,nx,hu,nh,Ss,!1,Pv,[0,0],0,ur,Na,Ls,yi,B3,Vn.getProjection(),jc,Ji,U3,jg,null),HN=hr.imageAtlasTexture?hr.imageAtlasTexture:null,Wj=E.layout.get("icon-size").constantOr(0)!==1||Vn.iconsNeedLinear,UE=Vn.sdfIcons||D.options.rotating||D.options.zooming||Wj||T1?Gt.LINEAR:Gt.NEAREST,Dy=Vn.sdfIcons&&E.paint.get("icon-halo-width").constantOr(1)!==0,YS=D.terrain&&Ts&&ml?o.b7(o.bb(),Fc):To;if(ml&&Vn.icon){const ZS=o.bu.getAtTileOffsetFunc(ur,ss.center.lat,ss.worldSize,Vn.getProjection()),XS=ld(ea,hr.tileID.canonical,Ts,xs,ss,Vn.getProjection(),ia),az=E.layout.get("icon-size-scale-range"),qE=o.aC(D.scaleFactor,az[0],az[1]);ym(Vn,ea,D,!1,XS,Kc,Ts,it,ZS,ur,qE)}return{program:ef,buffers:Vn.icon,uniformValues:BE,atlasTexture:HN,atlasTextureIcon:null,atlasInterpolation:UE,atlasInterpolationIcon:null,isSDF:Vn.sdfIcons,hasHalo:Dy,depthMode:am,tile:hr,renderWithShadows:po,labelPlaneMatrixInv:YS}},Ed=()=>{const ml=Ks&&E.layout.get("symbol-placement")!=="point",Ti=[],yd=ml||yn||Ni,lc=Vn.elevationType==="road",gh=D.shadowRenderer,po=lc&&_n&&!!gh&&gh.enabled,jc=Ha(po),am=lc&&_n&&!D.terrain?en:Kn;D.terrainRenderModeElevated()&&_n&&Ti.push("PITCH_WITH_MAP_TERRAIN"),ca&&(Ti.push("PROJECTION_GLOBE_VIEW"),yd&&Ti.push("PROJECTED_POS_ON_VIEWPORT")),!Vn.text.zOffsetVertexBuffer||lc&&D.terrain||Ti.push("Z_OFFSET"),Vn.iconsInText&&Ti.push("RENDER_TEXT_AND_SYMBOL"),Ti.push("RENDER_SDF"),po&&Ti.push("RENDER_SHADOWS","NORMAL_OFFSET"),lc&&_n&&!D.terrain&&Vn.text.orientationVertexBuffer&&Ti.push("ELEVATED_ROADS"),vi(Ti),eo(Ti);const jg=_s.disableSymbolUBO?Vn.text.programConfigurations.get(E.id):null,_m=D.getOrCreateProgram("symbol",{config:jg,defines:Ti});let ef,Pv=[0,0],Rl=null;const E1=Vn.textSizeData;Vn.iconsInText&&(Pv=hr.imageAtlasTexture?hr.imageAtlasTexture.size:[0,0],Rl=hr.imageAtlasTexture?hr.imageAtlasTexture:null,ef=_n||!ss.isOrthographic||D.options.rotating||D.options.zooming||E1.kind==="composite"||E1.kind==="camera"?Gt.LINEAR:Gt.NEAREST);const T1=hr.glyphAtlasTexture?hr.glyphAtlasTexture.size:[0,0],Fc=E.layout.get("text-size-scale-range"),Kc=o.aC(D.scaleFactor,Fc[0],Fc[1]),Kl=o.bj(E1,ss.zoom,Kc),nh=zd(ea,hr.tileID.canonical,_n,Ks,ss,Vn.getProjection(),ia),nx=Gp(ea,hr.tileID.canonical,_n,Ks,ss,Vn.getProjection(),ia),hu=Vn.text.uboBinder&&Vn.text.uboBinder.cachedHeader&&256&Vn.text.uboBinder.cachedHeader.dataDrivenMask?[0,0]:ye,Lv=D.translatePosMatrix(nx,hr,hu,Le,!0),KS=D.translatePosMatrix(ea,hr,hu,Le),B3=yd?To:nh,U3=Ks&&!_n&&!ml;let BE=jr;!jn&&!ss.mercatorFromTransition||Ks||(BE=cd(ss));const HN=hh(E1.kind,Kl,U3,_n,D,KS,B3,Lv,Ss,!0,T1,Pv,0,ur,Na,Ls,yi,ca?BE:jr,Vn.getProjection(),jc,Ji,null,null,Kc),Wj=hr.glyphAtlasTexture?hr.glyphAtlasTexture:null,UE=Gt.LINEAR,Dy=E.paint.get("text-halo-width").constantOr(1)!==0,YS=D.terrain&&_n&&ml?o.b7(o.bb(),nh):To;if(ml&&Vn.text){const ZS=o.bu.getAtTileOffsetFunc(ur,ss.center.lat,ss.worldSize,Vn.getProjection()),XS=ld(ea,hr.tileID.canonical,_n,Ks,ss,Vn.getProjection(),ia);ym(Vn,ea,D,!0,XS,nx,_n,jt,ZS,ur,Kc)}return{program:_m,buffers:Vn.text,uniformValues:HN,atlasTexture:Wj,atlasTextureIcon:Rl,atlasInterpolation:UE,atlasInterpolationIcon:ef,isSDF:!0,hasHalo:Dy,depthMode:am,tile:hr,renderWithShadows:po,labelPlaneMatrixInv:YS}},Tc=Vn.icon.segments.get().length,hl=Vn.text.segments.get().length,qi=Tc&&!J.onlyText?oc():null,$i=hl&&!J.onlyIcons?Ed():null,Mc=E.paint.get("icon-opacity").constantOr(1),$d=E.paint.get("text-opacity").constantOr(1);if(hn&&Vn.canOverlap){Rn=!0;const ml=Mc&&!J.onlyText?Vn.icon.segments.get():[],Ti=$d&&!J.onlyIcons?Vn.text.segments.get():[];for(const yd of ml)An.push({segments:new o.dy([yd]),sortKey:yd.sortKey,state:qi});for(const yd of Ti)An.push({segments:new o.dy([yd]),sortKey:yd.sortKey,state:$i})}else J.onlyText||An.push({segments:Mc?Vn.icon.segments:new o.dy([]),sortKey:0,state:qi}),J.onlyIcons||An.push({segments:$d?Vn.text.segments:new o.dy([]),sortKey:0,state:$i})}Rn&&An.sort((ur,hr)=>ur.sortKey-hr.sortKey);for(const ur of An){const hr=ur.state;if(hr)if(D.terrain?D.terrain.setupElevationDraw(hr.tile,hr.program,{useDepthForOcclusion:ss.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:hr.labelPlaneMatrixInv}):D.setupDepthForOcclusion(ss.depthOcclusionForSymbolsAndCircles,hr.program),_s.activeTexture.set(Gt.TEXTURE0),hr.atlasTexture&&hr.atlasTexture.bind(hr.atlasInterpolation,Gt.CLAMP_TO_EDGE,!0),hr.atlasTextureIcon&&(_s.activeTexture.set(Gt.TEXTURE1),hr.atlasTextureIcon&&hr.atlasTextureIcon.bind(hr.atlasInterpolationIcon,Gt.CLAMP_TO_EDGE,!0)),hr.renderWithShadows&&D.shadowRenderer.setupShadows(hr.tile.tileID.toUnwrapped(),hr.program,"vector-tile"),D.uploadCommonLightUniforms(D.context,hr.program),hr.hasHalo){const Vn=hr.uniformValues;Vn.u_is_halo=1,Ty(hr.buffers,ur.segments,E,D,hr.program,hr.depthMode,G,X,Vn,2),Vn.u_is_halo=0}else{if(hr.isSDF){const Vn=hr.uniformValues;hr.hasHalo&&(Vn.u_is_halo=1,Ty(hr.buffers,ur.segments,E,D,hr.program,hr.depthMode,G,X,Vn,1)),Vn.u_is_halo=0}Ty(hr.buffers,ur.segments,E,D,hr.program,hr.depthMode,G,X,hr.uniformValues,1)}}}function Ty(D,w,E,F,G,X,J,de,ye,Ce){const Le=F.context,Xe=Le.gl,Ke=[D.dynamicLayoutVertexBuffer,D.opacityVertexBuffer,D.iconTransitioningVertexBuffer,D.globeExtVertexBuffer,D.zOffsetVertexBuffer,D.orientationVertexBuffer];D.featureIdBuffer&&Ke.push(D.featureIdBuffer);const st=D.uboBinder?null:D.programConfigurations.get(E.id);if(D.uboBinder){D.uboBinder.layer=E;const jt=F.transform.zoom,wt=F.style.getBrightness?F.style.getBrightness():null,Bt=D.uboBinder.getConstantUniformValues(jt,wt);ye.u_spp_fill_np_color=Bt.fill_np_color,ye.u_spp_halo_np_color=Bt.halo_np_color,ye.u_spp_opacity=Bt.opacity,ye.u_spp_halo_width=Bt.halo_width,ye.u_spp_halo_blur=Bt.halo_blur,ye.u_spp_emissive_strength=Bt.emissive_strength,ye.u_spp_occlusion_opacity=Bt.occlusion_opacity,ye.u_spp_z_offset=Bt.z_offset;const Vt=E.paint.get(D.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),Ct=D.uboBinder.cachedHeader&&256&D.uboBinder.cachedHeader.dataDrivenMask&&Vt==="map"?F.transform.angle:0;ye.u_spp_translate_rotation=[Math.cos(Ct),Math.sin(Ct)]}const{batchIndices:dt,batchSegments:it}=D.getBatchGrouping(w);for(const jt of dt){const wt=it.get(jt);D.uboBinder&&D.uboBinder.bind(Le,G.program,jt),G.draw(F,Xe.TRIANGLES,X,J,de,fa.disabled,ye,E.id,D.layoutVertexBuffer,D.indexBuffer,wt,E.paint,F.transform.zoom,st,Ke,Ce)}}function Iu(D,w,E,F,G,X){const J=E.paint.get("line-width"),de=E.paint.get("line-emissive-strength").isConstant(),ye=E.paint.get("line-emissive-strength").constantOr(0),Ce=E.paint.get("line-occlusion-opacity"),Le=E.layout.get("line-elevation-reference"),Xe=E.layout.get("line-width-unit")==="meters",Ke=Le==="sea",st=!(!D.terrain||!D.terrain.enabled),dt=D.context,it=dt.gl;if(E.hasElevatedBuckets&&D.transform.projection.name==="globe")return;const jt=E.layout.get("line-cross-slope"),wt=jt!==void 0,Bt=jt<1,Vt=G||D.colorModeForDrapableLayerRenderPass(de?ye:null),Ct=D.terrain&&D.terrain.renderingToTexture||X,Ss=Ct?1:o.o.devicePixelRatio,rs=E.paint.get("line-dasharray"),_s=rs.constantOr(1),Gt=E.layout.get("line-cap"),ss=rs.constantOr(null),xs=Gt.constantOr(null),Ks=E.paint.get("line-pattern"),Ts=Ks.constantOr(1),_n=E.paint.get("line-pattern-cross-fade"),hn=Ks.constantOr(null),Rn=E.paint.get("line-opacity").constantOr(1);let Kn=!Ts&&Rn!==1||D.depthOcclusion&&Ce>0&&Ce<1;const en=E.paint.get("line-gradient"),Ls=Ts?"linePattern":"line",yn=o.dU(E);let jn;if(Ct&&D.terrain&&D.terrain.clipOrMaskOverlapStencilType()&&(Kn=!1),Ce!==0&&D.depthOcclusion){const Vn=E.paint._values["line-opacity"];Vn&&Vn.value&&Vn.value.kind==="constant"?jn=Vn.value:o.w(`Occlusion opacity for layer ${E.id} is supported only when line-opacity isn't data-driven.`)}J.value.kind!=="constant"&&J.value.isLineProgressConstant===!1&&yn.push("VARIABLE_LINE_WIDTH"),Ct&&(D.emissiveMode!=="dual-source-blending"||de?D.emissiveMode==="mrt-fallback"&&yn.push("USE_MRT1"):yn.push("DUAL_SOURCE_BLENDING"));const An={},jr=(Vn,ca,Na,ea,ia,ii)=>{for(const Ni of Vn){const yi=w.getTile(Ni);if(Ts&&!yi.patternsLoaded())continue;const Ji=yi.getBucket(E);if(!Ji||Ji.elevationType!=="none"&&!ia||Ji.elevationType==="none"&&ia)continue;D.prepareDrawTile();const Ha=[...ca],eo=D.shadowRenderer,vi=Ji.elevationType==="road"&&!!eo&&eo.enabled;let Wo=[0,0,0];if(vi){const po=D.style.directionalLight,jc=D.style.ambientLight;po&&jc&&(Wo=tm(D.style,po,jc)),Ha.push("RENDER_SHADOWS","NORMAL_OFFSET")}const oc=Ji.programConfigurations.get(E.id);let Ed=!1;if(hn&&yi.imageAtlas){const po=o.dV.from(hn),jc=po.getPrimary().scaleSelf(Ss).toString(),am=yi.imageAtlas.patternPositions.get(jc),jg=po.getSecondary(),_m=jg?yi.imageAtlas.patternPositions.get(jg.scaleSelf(Ss).toString()):null;Ed=!!am&&!!_m,am&&oc.setConstantPatternPositions(am,_m)}_n>0&&(Ed||oc.getPatternTransitionVertexBuffer("line-pattern"))&&Ha.push("LINE_PATTERN_TRANSITION"),Ji.elevationGroundScaleVertexBuffer&&Ha.push("ELEVATION_GROUND_SCALE");const Tc=D.isTileAffectedByFog(Ni),hl=D.getOrCreateProgram(Ls,{config:oc,defines:Ha,overrideFog:Tc});if(!Ts&&ss&&xs&&yi.lineAtlas){const po=yi.lineAtlas.getDash(ss,xs);po&&oc.setConstantPatternPositions(po)}vi&&eo.setupShadows(yi.tileID.toUnwrapped(),hl,"vector-tile");let[qi,$i]=E.paint.get("line-trim-offset");(xs==="round"||xs==="square")&&qi!==$i&&(qi===0&&(qi-=1),$i===1&&($i+=1));const Mc=Ct?Ni.projMatrix:null,$d=Xe?1/Ji.tileToMeter/o.aA(yi,1,D.transform.zoom):1,ml=Xe?1/Ji.tileToMeter/o.aA(yi,1,Math.floor(D.transform.zoom)):1,Ti=_s?E.paint._values["line-floorwidth"]:null;let yd;if(Ti&&Ti.value.kind==="constant"){const po=Ji.zoom;po in An||(An[po]=Math.max(.01,E.widthExpression().evaluate({zoom:po}))),yd=Ti.value.value;const jc=Math.floor(D.transform.zoom);Ti.value.value=An[po]*Math.pow(2,jc-yi.tileID.overscaledZ)}const lc=Ts?o.dW(D,yi,E,Mc,Ss,$d,ml,[qi,$i],Wo,_n):o.dX(D,yi,E,Mc,Ji.lineClipsArray.length,Ss,$d,ml,[qi,$i],Wo);if(en){const po=Ji.gradients[E.id];let jc=po.texture;if(E.gradientVersion!==po.version){let am=256;if(E.stepInterpolant){const jg=w.getSource().maxzoom,_m=Ni.canonical.z===jg?Math.ceil(1<{jn!=null&&(jn.value=Rn*Ce),hl.draw(D,it.TRIANGLES,Na,po,Vt,fa.disabled,lc,E.id,Ji.layoutVertexBuffer,Ji.indexBuffer,Ji.segments,E.paint,D.transform.zoom,oc,[Ji.layoutVertexBuffer2,Ji.patternVertexBuffer,Ji.zOffsetVertexBuffer,Ji.elevationGroundScaleVertexBuffer]),jn!=null&&(jn.value=Rn)};if(Kn&&!ia){const po=D.stencilModeForClipping(Ni).ref;po===0&&Ct&&dt.clear({stencil:0});const jc={func:it.EQUAL,mask:255};lc.u_alpha_discard_threshold=.8,gh(new Da(jc,po,255,it.KEEP,it.KEEP,it.INVERT)),lc.u_alpha_discard_threshold=0,gh(new Da(jc,po,255,it.KEEP,it.KEEP,it.KEEP))}else lc.u_alpha_discard_threshold=Kn&&ia&&ii?.8:0,gh(ia?ea:D.stencilModeForClipping(Ni));yd!==void 0&&(Ti.value.value=yd)}};let ur=D.depthModeForSublayer(0,Hr.ReadOnly);const hr=new Hr(D.depthOcclusion?it.GREATER:it.LEQUAL,Hr.ReadOnly,D.depthRangeFor3D);if(E.hasNonElevatedBuckets){const Vn=!Ct&&D.terrain;Ce!==0&&Vn?o.w(`Occlusion opacity for layer ${E.id} is supported on terrain only if the layer has line-z-offset enabled.`):Vn?o.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${E.id}.`):jr(F,yn,ur,Da.disabled,!1,!0)}if(E.hasElevatedBuckets){Le==="hd-road-markup"?st||(ur=hr,yn.push("ELEVATED_ROADS")):(yn.push("ELEVATED"),ur=hr,wt&&yn.push(Bt?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),Ke&&yn.push("ELEVATION_REFERENCE_SEA"));const Vn=Kn?D.stencilModeFor3D():Da.disabled;D.forceTerrainMode=!0,jr(F,yn,ur,Vn,!0,!0),Kn&&jr(F,yn,ur,Vn,!0,!1),D.forceTerrainMode=!1}Kn&&(D.resetStencilClippingMasks(),Ct&&dt.clear({stencil:0})),Ce===0||D.depthOcclusion||Ct||D.layersWithOcclusionOpacity.push(D.currentLayer)}const Jp={additive:{clearColor:new o.aq(0,0,0,0),colorMode:Ia.additive,compositeUniformValue:1},multiply:{clearColor:new o.aq(1,1,1,1),colorMode:Ia.multiply,compositeUniformValue:0}};function j1(D,w){const E=1<=em?1:st.pitch/em))),2*dt}(D.transform),Ce=D.transform.getFreeCameraOptions().position,Le="elevatedStructuresDepthReconstruct",Xe=D.getOrCreateProgram(Le,{defines:["DEPTH_RECONSTRUCTION"]}),Ke=D.getOrCreateProgram(Le);for(const st of F){const dt=w.getTile(st),it=dt.getBucket(E);if(!it)continue;const jt=it.elevatedStructures;if(!jt)continue;const wt=it.elevationBufferData.heightRange,Bt=j1(st.toUnwrapped(),Ce),Vt=D.translatePosMatrix(st.projMatrix,dt,E.paint.get("fill-translate"),E.paint.get("fill-translate-anchor"));let Ct,Ss,rs,_s;if(G==="initialize"){if(!wt||wt.min>=1||jt.depthSegments.segments[0].primitiveLength===0)continue;Ct=Ui(Vt,Bt,ye,1,0),Ss=J,rs=jt.depthSegments,_s=Xe}else if(G==="reset"){if(!wt||wt.min>=0||jt.maskSegments.segments[0].primitiveLength===0)continue;Ct=Ui(Vt,Bt,0,0,1),Ss=de,rs=jt.maskSegments,_s=Xe}else if(G==="geometry"){if(jt.depthSegments.segments[0].primitiveLength===0)continue;Ct=Ui(Vt,Bt,ye,1,0),Ss=J,rs=jt.depthSegments,_s=Ke}_s.draw(D,X.TRIANGLES,Ss,Da.disabled,Ia.disabled,fa.disabled,Ct,E.id,jt.vertexBuffer,jt.indexBuffer,rs,E.paint,D.transform.zoom)}}function N1(D,w,E,F){const{painter:G,sourceCache:X,layer:J,coords:de,colorMode:ye,elevationType:Ce,terrainEnabled:Le,pass:Xe}=D,Ke=G.context.gl,st=J.paint.get("fill-pattern"),dt=J.paint.get("fill-pattern-cross-fade"),it=st.constantOr(null);let jt=Ce;Ce!=="road"||w&&!Le||(jt="none");const wt=jt==="road",Bt=D.painter.shadowRenderer,Vt=wt&&!!Bt&&Bt.enabled,Ct=new Hr(G.context.gl.LEQUAL,Hr.ReadOnly,G.depthRangeFor3D);let Ss=[0,0,0];if(Vt){const ss=G.style.directionalLight,xs=G.style.ambientLight;ss&&xs&&(Ss=tm(G.style,ss,xs))}const rs=st&&st.constantOr(1),_s=G.terrain&&G.terrain.renderingToTexture,Gt=(ss,xs)=>{let Ks,Ts,_n,hn,Rn;xs?(Ks=rs&&!J.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",_n=Ke.LINES):(Ks=rs?"fillPattern":"fill",_n=Ke.TRIANGLES);for(const Kn of de){const en=X.getTile(Kn);if(rs&&!en.patternsLoaded())continue;const Ls=en.getBucket(J);if(!Ls)continue;const yn=w?Ls.elevationBufferData:Ls.bufferData;if(yn.isEmpty())continue;G.prepareDrawTile();const jn=yn.programConfigurations.get(J.id),An=G.isTileAffectedByFog(Kn),jr=[],ur=[];wt&&(jr.push("ELEVATED_ROADS"),ur.push(yn.elevatedLayoutVertexBuffer)),Vt&&jr.push("RENDER_SHADOWS","NORMAL_OFFSET"),_s&&E&&jr.push("USE_MRT1"),rs&&(G.context.activeTexture.set(Ke.TEXTURE0),en.imageAtlasTexture&&en.imageAtlasTexture.bind(Ke.LINEAR,Ke.CLAMP_TO_EDGE),jn.updatePaintBuffers());let hr=!1;if(it&&en.imageAtlas){const ia=en.imageAtlas,ii=o.dV.from(it),Ni=ii.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),yi=ii.getSecondary(),Ji=ia.patternPositions.get(Ni),Ha=yi?ia.patternPositions.get(yi.scaleSelf(o.o.devicePixelRatio).toString()):null;hr=!!Ji&&!!Ha,Ji&&jn.setConstantPatternPositions(Ji,Ha)}dt>0&&(hr||jn.getPatternTransitionVertexBuffer("fill-pattern"))&&jr.push("FILL_PATTERN_TRANSITION");const Vn=G.getOrCreateProgram(Ks,{config:jn,overrideFog:An,defines:jr}),ca=G.translatePosMatrix(Kn.projMatrix,en,J.paint.get("fill-translate"),J.paint.get("fill-translate-anchor"));Vt&&Bt.setupShadows(en.tileID.toUnwrapped(),Vn,"vector-tile");const Na=J.paint.get("fill-emissive-strength");if(xs){hn=yn.lineIndexBuffer,Rn=yn.lineSegments;const ia=G.terrain&&G.terrain.renderingToTexture?G.terrain.drapeBufferSize:[Ke.drawingBufferWidth,Ke.drawingBufferHeight];Ts=Ks==="fillOutlinePattern"&&rs?Xi(ca,Na,G,en,ia,Ss,dt):ga(ca,Na,ia,Ss)}else hn=yn.indexBuffer,Rn=yn.triangleSegments,Ts=rs?wa(ca,Na,G,en,Ss,dt):Vr(ca,Na,Ss);G.uploadCommonUniforms(G.context,Vn,Kn.toUnwrapped());let ea=ss;(Ce==="road"&&!Le||Ce==="offset")&&(ea=Ct),Vn.draw(G,_n,ea,F||G.stencilModeForClipping(Kn),ye,fa.disabled,Ts,J.id,yn.layoutVertexBuffer,hn,Rn,J.paint,G.transform.zoom,jn,ur)}};G.renderPass===Xe&&Gt(G.depthModeForSublayer(1,G.renderPass==="opaque"?Hr.ReadWrite:Hr.ReadOnly),!1),jt==="none"&&G.renderPass==="translucent"&&J.paint.get("fill-antialias")&&Gt(G.depthModeForSublayer(J.getPaintProperty("fill-outline-color")?2:0,Hr.ReadOnly),!0)}function bp(D,w,E,F,G,X,J,de){E.resetLayerRenderingStats(D);const ye=D.context,Ce=ye.gl,Le=D.transform,Xe=E.paint.get("fill-extrusion-pattern"),Ke=E.paint.get("fill-extrusion-pattern-cross-fade"),st=Xe.constantOr(null),dt=Xe.constantOr(1),it=E.paint.get("fill-extrusion-opacity"),jt=D.style.enable3dLights(),wt=E.paint.get(jt&&!dt?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),Bt=[E.paint.get("fill-extrusion-ambient-occlusion-intensity"),wt],Vt=E.layout.get("fill-extrusion-edge-radius"),Ct=Vt>0&&!E.paint.get("fill-extrusion-rounded-roof"),Ss=Ct?0:Vt,rs=Le.projection.name==="globe"?o.e1():0,_s=Le.projection.name==="globe",Gt=_s?o.al(Le.zoom):0,ss=[o.aH(Le.center.lng),o.aL(Le.center.lat)],xs=E.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Ks=E.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(xs?null:E.lut).toArray01().slice(0,3),Ts=E.paint.get("fill-extrusion-flood-light-intensity"),_n=E.paint.get("fill-extrusion-vertical-scale"),hn=E.paint.get("fill-extrusion-line-width").constantOr(1)!==0,Rn=E.paint.get("fill-extrusion-height-alignment"),Kn=E.paint.get("fill-extrusion-base-alignment"),en=Sd(D,E.paint.get("fill-extrusion-cutoff-fade-range")),Ls=E.paint.get("fill-extrusion-front-cutoff"),yn=qj(Le.pitch,Ls,!!D.terrain),jn=yn[2]<1;jn&&(D.maxFrontCutoffRawStart=Math.max(D.maxFrontCutoffRawStart,Ls[0]));const An=[];let jr;_s&&An.push("PROJECTION_GLOBE_VIEW"),Bt[0]>0&&An.push("FAUX_AO"),Ct&&An.push("ZERO_ROOF_RADIUS"),de&&An.push("HAS_CENTROID"),Ts>0&&An.push("FLOOD_LIGHT"),en.shouldRenderCutoff&&An.push("RENDER_CUTOFF"),jn&&An.push("RENDER_FRONT_CUTOFF"),hn&&An.push("RENDER_WALL_MODE");const ur=D.renderPass==="shadow",hr=D.shadowRenderer,Vn=ur&&!!hr,ca=ur?fa.disabled:fa.backCCW;D.shadowRenderer&&(D.shadowRenderer.useNormalOffset=!0);let Na=[0,0,0];if(hr){const ii=D.style.directionalLight,Ni=D.style.ambientLight;ii&&Ni&&(Na=tm(D.style,ii,Ni)),ur||(An.push("RENDER_SHADOWS"),hr.useNormalOffset&&An.push("NORMAL_OFFSET")),jr=An.concat(["SHADOWS_SINGLE_CASCADE"])}const ea=Vn?"fillExtrusionDepth":dt?"fillExtrusionPattern":"fillExtrusion",ia=E.getLayerRenderingStats();for(const ii of F){const Ni=w.getTile(ii),yi=Ni.getBucket(E);if(!yi||yi.projection.name!==Le.projection.name)continue;let Ji=!1;hr&&(Ji=hr.getMaxCascadeForTile(ii.toUnwrapped())===0);const Ha=D.isTileAffectedByFog(ii),eo=yi.programConfigurations.get(E.id);let vi=!1;if(st&&Ni.imageAtlas){const $i=Ni.imageAtlas,Mc=o.dV.from(st),$d=Mc.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),ml=Mc.getSecondary(),Ti=$i.patternPositions.get($d),yd=ml?$i.patternPositions.get(ml.scaleSelf(o.o.devicePixelRatio).toString()):null;vi=!!Ti&&!!yd,Ti&&eo.setConstantPatternPositions(Ti,yd)}Ke>0&&(vi||eo.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&An.push("FILL_EXTRUSION_PATTERN_TRANSITION");const Wo=D.getOrCreateProgram(ea,{config:eo,defines:Ji?jr:An,overrideFog:Ha});if(D.terrain&&D.terrain.setupElevationDraw(Ni,Wo,{useMeterToDem:!0}),!yi.centroidVertexBuffer){const $i=Wo.getAttributeLocation(Ce,"a_centroid_pos");$i!==-1&&Ce.vertexAttribI4ui($i,0,0,0,0)}!ur&&hr&&hr.setupShadows(Ni.tileID.toUnwrapped(),Wo,"vector-tile"),dt&&(D.context.activeTexture.set(Ce.TEXTURE0),Ni.imageAtlasTexture&&Ni.imageAtlasTexture.bind(Ce.LINEAR,Ce.CLAMP_TO_EDGE),eo.updatePaintBuffers());const oc=E.paint.get("fill-extrusion-vertical-gradient"),Ed=1/yi.tileToMeter;let Tc;if(ur&&hr){if(tx(Ni.tileID,yi.maxHeight,D))continue;const $i=hr.calculateShadowPassMatrixFromTile(Ni.tileID.toUnwrapped());Tc=vr($i,Ss,Ed,_n,Rn,Kn)}else{const $i=D.translatePosMatrix(ii.expandedProjMatrix,Ni,E.paint.get("fill-extrusion-translate"),E.paint.get("fill-extrusion-translate-anchor")),Mc=Le.projection.createInversionMatrix(Le,ii.canonical);Tc=dt?qn($i,D,oc,it,Bt,Ss,Ed,ii,Ni,rs,Rn,Kn,Gt,ss,Mc,Ks,_n,Ke):Tr($i,D,oc,it,Bt,Ss,Ed,ii,rs,Rn,Kn,Gt,ss,Mc,Ks,_n,Ts,Na,yn)}D.uploadCommonUniforms(ye,Wo,ii.toUnwrapped(),null,en);let hl=yi.segments;if(Le.projection.name==="mercator"&&!ur&&(hl=yi.getVisibleSegments(Ni.tileID,D.terrain,D.transform.getFrustum(0)),!hl.get().length))continue;if(ia)if(ur)for(const $i of hl.get())ia.numRenderedVerticesInShadowPass+=$i.primitiveLength;else for(const $i of hl.get())ia.numRenderedVerticesInTransparentPass+=$i.primitiveLength;const qi=[];(D.terrain||de)&&qi.push(yi.centroidVertexBuffer),_s&&qi.push(yi.layoutVertexExtBuffer),hn&&qi.push(yi.wallVertexBuffer),Wo.draw(D,ye.gl.TRIANGLES,G,X,J,ca,Tc,E.id,yi.layoutVertexBuffer,yi.indexBuffer,hl,E.paint,D.transform.zoom,eo,qi)}D.shadowRenderer&&(D.shadowRenderer.useNormalOffset=!1)}class Uf{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function qj(D,w,E){if(!(w[2]<1)||E)return[0,0,1];const F=180*D/Math.PI;if(F<15)return[-.5,w[1],w[2]];const G=Math.min(1,Math.max(0,(F-15)/5)),X=G*G*(3-2*G);return[-.5*(1-X)+w[0]*X,w[1],w[2]]}function M0(D,w,E,F,G,X,J,de,ye,Ce,Le,Xe,Ke,st,dt,it,jt,wt,Bt,Vt,Ct){const Ss=w.context,rs=Ss.gl,_s=w.transform,Gt=w.transform.zoom,ss=[],xs=D.translate,Ks=D.translateAnchor,Ts=D.edgeRadius,_n=Sd(w,D.cutoffFadeRange);Le==="clear"?(ss.push("CLEAR_SUBPASS"),Vt&&(ss.push("CLEAR_FROM_TEXTURE"),Ss.activeTexture.set(rs.TEXTURE0),Vt.bind(rs.LINEAR,rs.CLAMP_TO_EDGE))):Le==="sdf"?ss.push("SDF_SUBPASS"):Le==="emissive"&&(ss.push("USE_MRT1"),Ss.activeTexture.set(rs.TEXTURE0),Vt.bind(rs.LINEAR,rs.CLAMP_TO_EDGE)),wt&&ss.push("HAS_CENTROID"),_n.shouldRenderCutoff&&ss.push("RENDER_CUTOFF");const hn=(Rn,Kn,en,Ls,yn)=>{let jn=ss;Kn.groundRadiusBuffer!=null&&(jn=ss.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const An=Kn.programConfigurations.get(F.id),jr=w.isTileAffectedByFog(Rn),ur=w.getOrCreateProgram("fillExtrusionGroundEffect",{config:An,defines:jn,overrideFog:jr}),hr=((ca,Na,ea,ia,ii,Ni,yi,Ji,Ha,eo,vi)=>({u_matrix:Na,u_opacity:ea,u_ao_pass:ia?1:0,u_meter_to_tile:ii,u_ao:Ni,u_flood_light_intensity:yi,u_flood_light_color:Ji,u_attenuation:Ha,u_edge_radius:eo,u_fb:0,u_fb_size:vi,u_dynamic_offset:1}))(0,Ls,Xe,Ce,yn,[Ke,st*yn],dt,it,jt,Gt>=17?0:Ts*yn,Vt?Vt.size[0]:0),Vn=[];wt&&Vn.push(Kn.hiddenByLandmarkVertexBuffer),Kn.groundRadiusBuffer!=null&&Vn.push(Kn.groundRadiusBuffer),w.uploadCommonUniforms(Ss,ur,Rn.toUnwrapped(),null,_n),ur.draw(w,Ss.gl.TRIANGLES,X,J,de,ye,hr,F.id,Kn.vertexBuffer,Kn.indexBuffer,en,F.paint,Gt,An,Vn)};for(const Rn of G){const Kn=E.getTile(Rn),en=Kn.getBucket(F);if(!en||en.projection.name!==_s.projection.name||!en.groundEffect||en.groundEffect&&!en.groundEffect.hasData())continue;const Ls=en.groundEffect,yn=1/en.tileToMeter;{const jn=w.translatePosMatrix(Rn.projMatrix,Kn,xs,Ks),An=Ls.getDefaultSegment();hn(Rn,Ls,An,jn,yn)}if(Bt)for(let jn=0;jn<4;jn++){const An=o.d$[jn](Rn),jr=E.getTile(An);if(!jr)continue;const ur=jr.getBucket(F);if(!ur||ur.projection.name!==_s.projection.name||!ur.groundEffect||ur.groundEffect&&!ur.groundEffect.hasData())continue;const hr=ur.groundEffect;let Vn,ca;jn===0?(Vn=[-o.an,0,0],ca=1):jn===1?(Vn=[o.an,0,0],ca=0):jn===2?(Vn=[0,-o.an,0],ca=3):(Vn=[0,o.an,0],ca=2);const Na=hr.regionSegments[ca];if(!Na)continue;const ea=new Float32Array(16);o.bx(ea,Rn.projMatrix,Vn),hn(Rn,hr,Na,w.translatePosMatrix(ea,Kn,xs,Ks),yn)}}}function My(D,w,E,F,G,X,J){F.centroidVertexArray.length===0&&F.createCentroidsBuffer();const de=X?X.findDEMTileFor(E):null;if(!(de&&de.dem||J))return;X&&de&&de.dem&&F.selfDEMTileTimestamp!==de.dem._timestamp&&(F.borderDoneWithNeighborZ=[-1,-1,-1,-1],F.selfDEMTileTimestamp=de.dem._timestamp);const ye=(wt,Bt)=>{(wt.flags|Bt.flags)&o.e3?(wt.flags|=o.e3,Bt.flags|=o.e3):(wt.flags&=~o.e3,Bt.flags&=~o.e3)},Ce=wt=>new o.P(Math.ceil((wt+o.e4)*o.e5),0),Le=(wt,Bt,Vt)=>{const Ct=Math.ceil((wt+o.e4)*o.e5),Ss=Math.floor(Math.max(0,Math.min(o.an-1,Vt))/4);return new o.P(Ct,Ss<<5|(3&Bt)<<3|7)},Xe=wt=>{const Bt=w.getSource().minzoom,Vt=Ss=>{const rs=w.getTileByID(Ss);if(rs&&rs.hasData())return rs.getBucket(G)},Ct=[0,-1,1];for(const Ss of Ct){if(wt.overscaledZ+Ss(Ke[0]=Math.min(wt.min.y,Bt.min.y),Ke[1]=Math.max(wt.max.y,Bt.max.y),Ke[2]=o.an-Bt.min.x>wt.max.x?Bt.min.x-o.an:wt.max.x,Ke),dt=(wt,Bt)=>(Ke[0]=Math.min(wt.min.x,Bt.min.x),Ke[1]=Math.max(wt.max.x,Bt.max.x),Ke[2]=o.an-Bt.min.y>wt.max.y?Bt.min.y-o.an:wt.max.y,Ke),it=[(wt,Bt)=>st(wt,Bt),(wt,Bt)=>st(Bt,wt),(wt,Bt)=>dt(wt,Bt),(wt,Bt)=>dt(Bt,wt)],jt=(wt,Bt,Vt,Ct,Ss,rs,_s)=>{if(!X)return 0;const Gt=[[rs?Vt:wt,rs?wt:Vt,0],[rs?Vt:Bt,rs?Bt:Vt,0]],ss=_s<0?o.an+_s:_s,xs=[rs?ss:(wt+Bt)/2,rs?(wt+Bt)/2:ss,0];return Vt===0&&_s<0||Vt!==0&&_s>0?X.getForTilePoints(Ss,[xs],!0,Ct):Gt.push(xs),X.getForTilePoints(E,Gt,!0,de),Math.max(Gt[0][2],Gt[1][2],xs[2])/X.exaggeration()};for(let wt=0;wt<4;wt++){const Bt=F.borderFeatureIndices[wt];if(Bt.length===0)continue;const Vt=o.d$[wt](E),Ct=Xe(Vt);if(!(Ct&&Ct instanceof o.e0))continue;const Ss=X?X.findDEMTileFor(Vt):null;if(!(Ss&&Ss.dem||J)||(X&&Ss&&Ss.dem&&F.borderDEMTileTimestamp[wt]!==Ss.dem._timestamp&&(F.borderDoneWithNeighborZ[wt]=-1,F.borderDEMTileTimestamp[wt]=Ss.dem._timestamp),F.borderDoneWithNeighborZ[wt]===Ct.canonical.z))continue;Ct.centroidVertexArray.length===0&&Ct.createCentroidsBuffer();const rs=(wt<2?1:5)-wt,_s=Ct.borderDoneWithNeighborZ[rs]!==F.canonical.z,Gt=Ct.borderFeatureIndices[rs];let ss=0;if(F.canonical.z!==Ct.canonical.z){for(const _n of Bt)F.showCentroid(F.featuresOnBorder[_n]);if(_s)for(const _n of Gt)Ct.showCentroid(Ct.featuresOnBorder[_n]);F.borderDoneWithNeighborZ[wt]=Ct.canonical.z,Ct.borderDoneWithNeighborZ[rs]=F.canonical.z;continue}const xs=new Map,Ks=new Set,Ts=new Set;for(let _n=0;_n1||en.intersectsCount()>1;{let ur=0;if(Ss&&Ss.dem&&!jr){const hr=it[wt](Rn,Ls),Vn=wt%2?o.an-1:0;ur=jt(hr[0],Math.min(o.an-1,hr[1]),Vn,Ss,Vt,wt<2,hr[2])}Rn.centroidXY=Le(ur,wt,An),Ls.centroidXY=Le(ur,rs,An)}if(F.writeCentroidToBuffer(Rn),Ct.writeCentroidToBuffer(Ls),hn.buildingId!==void 0){for(const ur of F.centroidData)ur.buildingId===hn.buildingId&&ur!==Rn&&(ur.centroidXY=Rn.centroidXY,F.writeCentroidToBuffer(ur));for(const ur of Ct.centroidData)ur.buildingId===hn.buildingId&&ur!==Ls&&(ur.centroidXY=Ls.centroidXY,Ct.writeCentroidToBuffer(ur))}}for(const _n of Bt){if(Ks.has(_n))continue;const hn=F.featuresOnBorder[_n],Rn=F.centroidData[hn.centroidDataIndex],Kn=hn.borders[wt];let en;for(;ssKn[0]+3||Ls[0]>Kn[0]-3)break;Ct.showCentroid(en),ss++}if(en&&ssKn[1]-3||(yn++,++ss===Gt.length))break;en=Ct.featuresOnBorder[Gt[ss]]}for(;Ls=Gt.length){F.showCentroid(hn);continue}en=Ct.featuresOnBorder[Gt[Ls]];let jn=!1;if(yn>=1){const ur=en.borders[rs];Math.abs(Kn[0]-ur[0])<3&&Math.abs(Kn[1]-ur[1])<3&&(yn=1,jn=!0,ss=Ls+1)}else if(yn===0){F.showCentroid(hn);continue}const An=Ct.centroidData[en.centroidDataIndex];J&&jn&&ye(Rn,An);const jr=hn.intersectsCount()>1||en.intersectsCount()>1;if(yn>1)ss=Ls,Rn.centroidXY=An.centroidXY=new o.P(0,0);else if(Ss&&Ss.dem&&!jr){const ur=it[wt](Rn,An),hr=wt%2?o.an-1:0,Vn=jt(ur[0],Math.min(o.an-1,ur[1]),hr,Ss,Vt,wt<2,ur[2]);Rn.centroidXY=An.centroidXY=Ce(Vn)}else jr?Rn.centroidXY=An.centroidXY=new o.P(0,0):(Rn.centroidXY=F.encodeBorderCentroid(hn),An.centroidXY=Ct.encodeBorderCentroid(en));F.writeCentroidToBuffer(Rn),Ct.writeCentroidToBuffer(An)}else F.showCentroid(hn)}F.borderDoneWithNeighborZ[wt]=Ct.canonical.z,Ct.borderDoneWithNeighborZ[rs]=F.canonical.z}(F.needsCentroidUpdate||!F.centroidVertexBuffer&&F.centroidVertexArray.length!==0)&&F.uploadCentroid(D)}const Tv=[1,0,0],$j=[0,1,0],Vj=[0,0,1];function tx(D,w,E){const F=E.transform,G=E.shadowRenderer;if(!G)return!0;const X=D.toUnwrapped(),J=F.tileSize*G._cascades[E.currentShadowCascade].scale;let de=w;if(F.elevation){const dt=F.elevation.getMinMaxForTile(D);dt&&(de+=dt.max)}const ye=F.scaleZoom(J);de/=o.e2(F.center.lat,ye);const Ce=[...G.shadowDirection];Ce[2]=-Ce[2];const Le=G.computeSimplifiedTileShadowVolume(X,de,J,Ce);if(!Le)return!1;const Xe=[Tv,$j,Vj,Ce,[Ce[0],0,Ce[2]],[0,Ce[1],Ce[2]]],Ke=o.cl.fromInvProjectionMatrix(F.invProjMatrix,F.worldSize,ye,F.projection.name!=="globe"),st=G.getCurrentCascadeFrustum();return Ke.intersectsPrecise(Le.vertices,Le.planes,Xe)===0||st.intersectsPrecise(Le.vertices,Le.planes,Xe)===0}function Mv(D){const{painter:w,source:E,layer:F,coords:G}=D;let X=D.defines;const J=w.context,de=w.renderPass==="shadow",ye=w.renderPass==="light-beam",Ce=w.shadowRenderer,Le=o.e2(w.transform.center.lat,w.transform.zoom),Xe=Sd(w,F.paint.get("building-cutoff-fade-range"));Xe.shouldRenderCutoff&&(X=X.concat("RENDER_CUTOFF"));const Ke=F.paint.get("building-front-cutoff"),st=Ke[2]<1&&!w.terrain,dt=qj(w.transform.pitch,Ke,!!w.terrain);st&&(X=X.concat("RENDER_FRONT_CUTOFF"),w.maxFrontCutoffRawStart=Math.max(w.maxFrontCutoffRawStart,Ke[0])),D.floodLightIntensity>0&&(X=X.concat("FLOOD_LIGHT"));for(const it of G){const jt=E.getTile(it),wt=jt.getBucket(F);if(!wt)continue;Ce&&Ce.getMaxCascadeForTile(it.toUnwrapped())===0&&(X=X.concat("SHADOWS_SINGLE_CASCADE"));const Bt=wt.programConfigurations.get(F.id);let Vt,Ct,Ss,rs=w.translatePosMatrix(it.expandedProjMatrix,jt,[0,0],"map");if(rs=o.cC(o.bb(),rs,[1,1,D.verticalScale]),de&&Ce){if(tx(jt.tileID,wt.maxHeight*Le,w))continue;let Gt=Ce.calculateShadowPassMatrixFromTile(jt.tileID.toUnwrapped());Gt=o.cC(o.bb(),Gt,[1,1,D.verticalScale]),Ss=Hi(Gt),Vt=Ct=w.getOrCreateProgram("buildingDepth",{config:Bt,defines:X,overrideFog:!1})}else if(ye)Vt=Ct=w.getOrCreateProgram("buildingBloom",{config:Bt,defines:X,overrideFog:!1}),Ss=vl(rs);else{const Gt=w.transform.calculatePosMatrix(it.toUnwrapped(),w.transform.worldSize);o.cC(Gt,Gt,[1,1,D.verticalScale]);const ss=o.bb();o.cC(ss,Gt,[1,-1,1/Le]),o.b7(ss,ss),o.e6(ss,ss);const xs=w.transform.getFreeCameraOptions().position,Ks=1<{if(ye){const xs=Gt.entranceBloom;ss.draw(w,J.gl.TRIANGLES,D.depthMode,Da.disabled,D.blendMode,fa.disabled,Ss,F.id,xs.layoutVertexBuffer,xs.indexBuffer,xs.segmentsBucket,F.paint,w.transform.zoom,Bt,[xs.layoutAttenuationBuffer,xs.layoutColorBuffer])}else{const xs=Gt.segmentsBucket;let Ks=[Gt.layoutNormalBuffer,Gt.layoutCentroidBuffer,Gt.layoutColorBuffer,Gt.layoutFloodLightDataBuffer];Gt.layoutFacadePaintBuffer&&(Ks=Ks.concat([Gt.layoutFacadeDataBuffer,Gt.layoutFacadeVerticalRangeBuffer,Gt.layoutFacadePaintBuffer])),ss.draw(w,J.gl.TRIANGLES,D.depthMode,Da.disabled,D.blendMode,de?fa.disabled:fa.backCW,Ss,F.id,Gt.layoutVertexBuffer,Gt.indexBuffer,xs,F.paint,w.transform.zoom,Bt,Ks)}};w.uploadCommonUniforms(J,Ct,it.toUnwrapped(),null,Xe),wt.buildingWithoutFacade&&_s(wt.buildingWithoutFacade,Ct),wt.buildingWithFacade&&(Vt!==Ct&&w.uploadCommonUniforms(J,Vt,it.toUnwrapped(),null,Xe),_s(wt.buildingWithFacade,Vt))}}function sx(D,w,E,F,G,X,J,de,ye,Ce,Le,Xe,Ke,st){const dt=D.context.gl,it=D.depthModeForSublayer(1,Hr.ReadOnly,dt.LEQUAL,!0),jt=.1*(1-(wt=Le))+3*wt;var wt;const Bt=D._showOverdrawInspector,Vt=Xe,Ct=new Uf;Bt||M0(Ct,D,w,E,F,it,new Da({func:dt.ALWAYS,mask:255},255,255,dt.KEEP,dt.KEEP,dt.REPLACE),new Ia([dt.ONE,dt.ONE,dt.ONE,dt.ONE],o.aq.transparent,[!1,!1,!1,!0],dt.MIN),fa.disabled,G,"sdf",X,J,de,ye,Ce,jt,Vt,!1,void 0);{const Ss=Bt?Da.disabled:new Da({func:dt.EQUAL,mask:255},255,255,dt.KEEP,dt.DECR,dt.DECR),rs=Bt?D.colorModeForRenderPass():new Ia([dt.ONE_MINUS_DST_ALPHA,dt.DST_ALPHA,dt.ONE,dt.ONE],o.aq.transparent,[!0,!0,!0,!0]);M0(Ct,D,w,E,F,it,Ss,rs,fa.disabled,G,"color",X,J,de,ye,Ce,jt,Vt,!1,void 0)}}function J_(D){return[D[0]*o.e7,D[1]*o.e7,D[2]*o.e7,0]}function Fb(D,w,E,F,G,X,J,de,ye){const Ce=F.getSource(),Le=E.globeSharedBuffers;if(!Le)return;let Xe,Ke,st;if(w&&(Xe=F.getTile(w)),Ce instanceof o.aV?(Ke=Ce.texture,st=o.dw(0,0,E.transform)):Xe&&w&&(Ke=Xe.texture,st=o.dw(w.canonical.z,w.canonical.x,E.transform)),!Ke||!st)return;D||(st=o.cC(o.bb(),st,[1,-1,1]));const dt=E.context,it=dt.gl,jt=G.paint.get("raster-resampling")==="nearest"?it.NEAREST:it.LINEAR,wt=E.colorModeForDrapableLayerRenderPass(X),Bt=J.defines;Bt.push("GLOBE_POLES");const Vt=new Hr(it.LEQUAL,Hr.ReadWrite,E.depthRangeFor3D),Ct=Float32Array.from(E.transform.expandedFarZProjMatrix),Ss=Float32Array.from(o.du(o.dv(new o.cn(0,0,0))));E.terrain&&E.terrain.prepareDrawTile(),dt.activeTexture.set(it.TEXTURE0),Ke.bind(jt,it.CLAMP_TO_EDGE),dt.activeTexture.set(it.TEXTURE1),Ke.bind(jt,it.CLAMP_TO_EDGE),"useMipmap"in Ke&&dt.extTextureFilterAnisotropic&&E.transform.pitch>20&&it.texParameterf(it.TEXTURE_2D,dt.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,dt.extTextureFilterAnisotropicMax);const[rs,_s,Gt,ss]=w?Le.getPoleBuffers(w.canonical.z,!1):Le.getPoleBuffers(0,!0),xs=G.paint.get("raster-elevation");let Ks;D?(Ks=rs,E.renderDefaultNorthPole=xs!==0):(Ks=_s,E.renderDefaultSouthPole=xs!==0);const Ts=J_(J.mix),_n=((Rn,Kn,en,Ls,yn,jn,An,jr,ur,hr,Vn,ca,Na,ea)=>Nu(Rn,Kn,en,Ls,new Float32Array(16),new Float32Array(9),[0,0],yn,[0,0],[0,0,0,0],1,{opacity:1,mix:0},An,[0,0],ur,2,Vn,ca,Na,1,0,ea))(E,Ct,Ss,st,o.al(E.transform.zoom),0,G,0,xs,0,Ts,J.offset,J.range,X),hn=E.getOrCreateProgram("raster",{defines:Bt});E.uploadCommonUniforms(dt,hn,null),hn.draw(E,it.TRIANGLES,Vt,ye,wt,de,_n,G.id,Ks,Gt,ss)}function zb(D){if(D.isOrthographic)return[0,0,0,0];const w=D._nearZ,E=D.projection.farthestPixelDistance(D),F=E-w,G=.2*D.height,X=w+G;return[w,E,(X-G-w)/F,(X-w)/F]}function Hj(D,w,E,F){if(D)return w instanceof Jo&&D instanceof dp?w.getTextureDescriptor(D,E,!0):{texture:D.texture,mix:J_(F.mix),offset:F.offset,buffer:0,tileSize:1}}var Bb=o.e8([{name:"a_index",type:"Int16",components:1}]);class sh{constructor(w,E,F,G){const X={width:F[0],height:F[1],data:null},J=w.gl;this.targetColorTexture=new o.T(w,X,J.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new o.T(w,X,J.RGBA8,{useMipmap:!1}),this.context=w,this.updateParticleTexture(E,G),this.lastInvalidatedAt=0}updateParticleTexture(w,E){if(this.particleTextureDimension===E.width)return;(this.particleTexture0||this.particleTexture1||this.particleIndexBuffer||this.particleSegment)&&(this.particleTexture0.destroy(),this.particleTexture1.destroy(),this.particleIndexBuffer.destroy(),this.particleSegment.destroy());const F=this.context.gl,G=E.width*E.height;this.particleTexture0=new o.T(this.context,E,F.RGBA8,{premultiply:!1,useMipmap:!1}),this.particleTexture1=new o.T(this.context,E,F.RGBA8,{premultiply:!1,useMipmap:!1});const X=new o.e9;X.reserve(G);for(let J=0;J0){const Ts=o.ec(E.canonical,ye),_n=o.ed(Ts);Ke=o.aD(new Float32Array(16),ye.globeMatrix,_n),o.aD(Ke,ye.projMatrix,Ke)}const st=o.bb();st[12]+=2*G/(o.o.devicePixelRatio*ye.width),st[13]+=2*X/(o.o.devicePixelRatio*ye.height),o.aD(Ke,st,Ke);const dt=D.getOrCreateProgram("debug",{defines:Xe}),it=w.getTileByID(E.key);D.terrain&&D.terrain.setupElevationDraw(it,dt);const jt=Hr.disabled,wt=Da.disabled,Bt=D.colorModeForRenderPass(),Vt="$debug";de.activeTexture.set(Ce.TEXTURE0),D.emptyTexture.bind(Ce.LINEAR,Ce.CLAMP_TO_EDGE),Le?it._makeGlobeTileDebugBuffers(D.context,ye):it._makeDebugTileBoundsBuffers(D.context,ye.projection);const Ct=it._tileDebugBuffer||D.debugBuffer,Ss=it._tileDebugIndexBuffer||D.debugIndexBuffer,rs=it._tileDebugSegments||D.debugSegments;if(dt.draw(D,Ce.LINE_STRIP,jt,wt,Bt,fa.disabled,vo(Ke,F.toPremultipliedRenderColor(null)),Vt,Ct,Ss,rs,null,null,null,[it._globeTileDebugBorderBuffer]),J){const Ts=it.latestRawTileData,_n=Math.floor((Ts&&Ts.byteLength||0)/1024);let hn=E.canonical.toString();E.overscaledZ!==E.canonical.z&&(hn+=` => ${E.overscaledZ}`),hn+=` ${it.state}`,hn+=` ${_n}kb`,function(Rn,Kn){Rn.initDebugOverlayCanvas();const en=Rn.debugOverlayCanvas,Ls=Rn.context.gl,yn=Rn.debugOverlayCanvas.getContext("2d");yn.clearRect(0,0,en.width,en.height),yn.shadowColor="white",yn.shadowBlur=2,yn.lineWidth=1.5,yn.strokeStyle="white",yn.textBaseline="top",yn.font="bold 36px Open Sans, sans-serif",yn.fillText(Kn,5,5),yn.strokeText(Kn,5,5),Rn.debugOverlayTexture.update(en),Rn.debugOverlayTexture.bind(Ls.LINEAR,Ls.CLAMP_TO_EDGE)}(D,hn)}const _s=w.getTile(E).tileSize,Gt=512/Math.min(_s,512)*(E.overscaledZ/ye.zoom)*.5,ss=it._tileDebugTextBuffer||D.debugBuffer,xs=it._tileDebugTextIndexBuffer||D.quadTriangleIndexBuffer,Ks=it._tileDebugTextSegments||D.debugSegments;dt.draw(D,Ce.TRIANGLES,jt,wt,Ia.alphaBlended,fa.disabled,vo(Ke,o.aq.transparent.toPremultipliedRenderColor(null),Gt),Vt,ss,xs,Ks,null,null,null,[it._globeTileDebugTextBuffer])}function L3(D,w,E,F){P0(D,0,w+E/2,D.transform.width,E,F)}function C1(D,w,E,F){P0(D,w-E/2,0,E,D.transform.height,F)}function P0(D,w,E,F,G,X){const J=D.context,de=J.gl;de.enable(de.SCISSOR_TEST),de.scissor(w*o.o.devicePixelRatio,E*o.o.devicePixelRatio,F*o.o.devicePixelRatio,G*o.o.devicePixelRatio),J.clear({color:X}),de.disable(de.SCISSOR_TEST)}const BN=o.e8([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:ph}=BN;function Gm(D,w,E,F){D.emplaceBack(w,E,F)}class uu{constructor(w){this.vertexArray=new o.ee,this.indices=new o.dC,Gm(this.vertexArray,-1,-1,1),Gm(this.vertexArray,1,-1,1),Gm(this.vertexArray,-1,1,1),Gm(this.vertexArray,1,1,1),Gm(this.vertexArray,-1,-1,-1),Gm(this.vertexArray,1,-1,-1),Gm(this.vertexArray,-1,1,-1),Gm(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=w.createVertexBuffer(this.vertexArray,ph),this.indexBuffer=w.createIndexBuffer(this.indices),this.segment=o.dy.simpleSegment(0,0,36,12)}}function $f(D,w,E,F,G,X){const J=D.context.gl,de=w.paint.get("sky-atmosphere-color"),ye=w.paint.get("sky-atmosphere-halo-color"),Ce=w.paint.get("sky-atmosphere-sun-intensity"),Le=((Xe,Ke,st,dt,it)=>({u_matrix_3f:Xe,u_sun_direction:Ke,u_sun_intensity:st,u_color_tint_r:[dt.r,dt.g,dt.b,dt.a],u_color_tint_m:[it.r,it.g,it.b,it.a],u_luminance:5e-5}))(o.eg(o.dE(),F),G,Ce,de.toPremultipliedRenderColor(null),ye.toPremultipliedRenderColor(null));J.framebufferTexture2D(J.FRAMEBUFFER,J.COLOR_ATTACHMENT0,J.TEXTURE_CUBE_MAP_POSITIVE_X+X,w.skyboxTexture,0),E.draw(D,J.TRIANGLES,Hr.disabled,Da.disabled,Ia.unblended,fa.frontCW,Le,"skyboxCapture",w.skyboxGeometry.vertexBuffer,w.skyboxGeometry.indexBuffer,w.skyboxGeometry.segment)}const qS=o.e8([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class UN{constructor(w){const E=new o.eh;E.emplaceBack(-1,1,1,0,0),E.emplaceBack(1,1,1,1,0),E.emplaceBack(1,-1,1,1,1),E.emplaceBack(-1,-1,1,0,1);const F=new o.dC;F.emplaceBack(0,1,2),F.emplaceBack(2,3,0),this.vertexBuffer=w.createVertexBuffer(E,qS.members),this.indexBuffer=w.createIndexBuffer(F),this.segments=o.dy.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const $S=o.e8([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_size_scale",components:1},{type:"Float32",name:"a_opacity",components:1}]);class Ly{constructor(){this.starsCount=16e3,this.sizeMultiplier=.15,this.sizeRange=100,this.intensityRange=200}}class VS{constructor(w){this.colorModeAlphaBlendedWriteRGB=new Ia([1,Hl,1,Hl],o.aq.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new Ia([1,0,1,0],o.aq.transparent,[!1,!1,!1,!0]),this.params=new Ly,this.updateNeeded=!0}update(w){const E=w.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new UN(E);const F=this.params.sizeRange,G=this.params.intensityRange,X=function(Le){const Xe=o.em(30),Ke=[];for(let st=0;st{const Gt=X.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];_s&&Gt.push("ALPHA_PASS");const ss=w.getOrCreateProgram("globeAtmosphere",{defines:Gt}),xs=((Ts,_n,hn,Rn,Kn,en,Ls,yn,jn,An,jr,ur)=>({u_frustum_tl:Ts,u_frustum_tr:_n,u_frustum_br:hn,u_frustum_bl:Rn,u_horizon:Kn,u_transition:en,u_fadeout_range:Ls,u_atmosphere_fog_color:yn.toArray01(),u_high_color:jn.toArray01(),u_space_color:An.toArray01(),u_temporal_offset:jr,u_horizon_angle:ur}))(X.frustumCorners.TL,X.frustumCorners.TR,X.frustumCorners.BR,X.frustumCorners.BL,X.frustumCorners.horizon,de,jt,Le,Ke,dt,Bt,Ss);w.uploadCommonUniforms(F,ss);const Ks=this.atmosphereBuffer;Ks&&ss.draw(w,G.TRIANGLES,J,Da.disabled,_s?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,fa.backCW,xs,_s?"atmosphere_glow_alpha":"atmosphere_glow",Ks.vertexBuffer,Ks.indexBuffer,Ks.segments)};rs(!1),rs(!0)}drawStars(w,E){const F=o.aC(E.properties.get("star-intensity"),0,1);if(F===0)return;const G=w.context,X=G.gl,J=w.transform,de=w.getOrCreateProgram("stars"),ye=o.bL([]);o.bN(ye,ye,-J._pitch),o.bM(ye,ye,-J.angle),o.bN(ye,ye,o.ap(J._center.lat)),o.ek(ye,ye,-o.ap(J._center.lng));const Ce=o.bR(new Float32Array(16),ye),Le=o.aD([],J.starsProjMatrix,Ce),Xe=o.eg([],Ce),Ke=o.el([],Xe),st=[0,1,0];o.dG(st,st,Ke),o.bJ(st,st,this.params.sizeMultiplier);const dt=[1,0,0];o.dG(dt,dt,Ke),o.bJ(dt,dt,this.params.sizeMultiplier);const it=(jt=st,wt=dt,Bt=F,{u_matrix:Float32Array.from(Le),u_up:jt,u_right:wt,u_intensity_multiplier:Bt});var jt,wt,Bt;w.uploadCommonUniforms(G,de),this.starsVx&&this.starsIdx&&de.draw(w,X.TRIANGLES,Hr.disabled,Da.disabled,this.colorModeAlphaBlendedWriteRGB,fa.disabled,it,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class Dx{constructor(){this.visibleTiles=[]}updateBorders(w,E){const F=[],G=[],X=w._getRenderableCoordinates(!1,!0);for(const ye of X){const Ce=w.getTile(ye);if(!Ce.hasData())continue;const Le=Ce.getBucket(E);Le&&(Le.isEmpty()||(F.push(ye.key),G.push({bucket:Le,tileID:ye.canonical})))}let J=F.length!==this.visibleTiles.length;if(!J){F.sort();for(let ye=0;yeye.tileID.z-Ce.tileID.z||ye.tileID.x-Ce.tileID.x||ye.tileID.y-Ce.tileID.y);for(const ye of G){const Ce=new Array,Le=new Array,Xe=ye.bucket;for(const Ke of Xe.featuresOnBorder)de.has(Ke.featureId)?Le.push(Ke.footprintIndex):(de.add(Ke.featureId),Ce.push(Ke.footprintIndex));Xe.updateFootprintHiddenFlags(Ce,o.en,!1),Xe.updateFootprintHiddenFlags(Le,o.en,!0)}}}function vL(D,w){const E=[...D],F=w.cameraWorldSizeForFog/w.worldSize,G=o.b9([]);return o.cC(G,G,[F,F,1]),o.aD(E,G,E),o.aD(E,w.worldToFogMatrix,E),E}function Oi(D,w,E,F,G){const X=E.material,J=F.context,{baseColorTexture:de,metallicRoughnessTexture:ye}=X.pbrMetallicRoughness,{normalTexture:Ce,occlusionTexture:Le,emissionTexture:Xe}=X;function Ke(dt,it,jt){if(dt&&(D.push(it),J.activeTexture.set(J.gl.TEXTURE0+jt),dt.gfxTexture)){const{minFilter:wt,magFilter:Bt,wrapS:Vt,wrapT:Ct}=dt.sampler;dt.gfxTexture.bindExtraParam(wt,Bt,Vt,Ct)}}Ke(de,"HAS_TEXTURE_u_baseColorTexture",5),Ke(ye,"HAS_TEXTURE_u_metallicRoughnessTexture",6),Ke(Ce,"HAS_TEXTURE_u_normalTexture",7),Ke(Le,"HAS_TEXTURE_u_occlusionTexture",8),Ke(Xe,"HAS_TEXTURE_u_emissionTexture",9),G&&(G.texture||(G.texture=new o.dR(F.context,G.image,[G.image.height,G.image.height,G.image.height],J.gl.RGBA8)),J.activeTexture.set(J.gl.TEXTURE0+10),G.texture&&G.texture.bind(J.gl.LINEAR,J.gl.CLAMP_TO_EDGE),D.push("APPLY_LUT_ON_GPU")),E.texcoordBuffer&&(D.push("HAS_ATTRIBUTE_a_uv_2f"),w.push(E.texcoordBuffer)),E.colorBuffer&&(D.push(E.colorBuffer.itemSize===12?"HAS_ATTRIBUTE_a_color_3f":"HAS_ATTRIBUTE_a_color_4f"),w.push(E.colorBuffer)),E.normalBuffer&&(D.push("HAS_ATTRIBUTE_a_normal_3f"),w.push(E.normalBuffer)),E.pbrBuffer&&(D.push("HAS_ATTRIBUTE_a_pbr"),D.push("HAS_ATTRIBUTE_a_heightBasedEmissiveStrength"),w.push(E.pbrBuffer)),X.alphaMode!=="OPAQUE"&&X.alphaMode!=="MASK"||D.push("UNPREMULT_TEXTURE_IN_SHADER"),X.defined||D.push("DIFFUSE_SHADED");const st=F.shadowRenderer;st&&(D.push("RENDER_SHADOWS"),st.useNormalOffset&&D.push("NORMAL_OFFSET"))}function HS(D,w,E,F,G,X){const J=D.modelOpacity,de=w.context,ye=new Hr(w.context.gl.LEQUAL,D.isLightMesh?Hr.ReadOnly:Hr.ReadWrite,w.depthRangeFor3D),Ce=w.transform,Le=D.mesh,Xe=Le.material,Ke=Xe.pbrMetallicRoughness,st=w.style.fog;let dt;dt=w.transform.projection.zAxisUnit==="pixels"?[...D.nodeModelMatrix]:o.aD([],F.zScaleMatrix,D.nodeModelMatrix),o.aD(dt,F.negCameraPosMatrix,dt);const it=o.b7([],dt);o.e6(it,it);const jt=E.paint.get("model-color-use-theme").constantOr("default")==="none",wt=E.paint.get("model-emissive-strength").constantOr(0),Bt=wc(new Float32Array(D.worldViewProjection),new Float32Array(dt),new Float32Array(it),null,w,J,Ke.baseColorFactor,Xe.emissiveFactor,Ke.metallicFactor,Ke.roughnessFactor,Xe,wt,E,void 0,void 0,D.materialOverride,D.modelColor),Vt={defines:[]},Ct=[],Ss=w.shadowRenderer;Ss&&(Ss.useNormalOffset=!1),Oi(Vt.defines,Ct,Le,w,jt?null:E.lut);let rs=null;if(st){const ss=vL(D.nodeModelMatrix,w.transform);if(rs=new Float32Array(ss),Ce.projection.name!=="globe"){const xs=Le.aabb.min,Ks=Le.aabb.max,[Ts,_n]=st.getOpacityForBounds(ss,xs[0],xs[1],Ks[0],Ks[1]);Vt.overrideFog=Ts>=ha||_n>=ha}}const _s=Sd(w,E.paint.get("model-cutoff-fade-range"));_s.shouldRenderCutoff&&Vt.defines.push("RENDER_CUTOFF");const Gt=w.getOrCreateProgram("model",Vt);w.uploadCommonUniforms(de,Gt,null,rs,_s),w.renderPass!=="shadow"&&Ss&&Ss.setupShadowsFromMatrix(D.nodeModelMatrix,Gt),Gt.draw(w,de.gl.TRIANGLES,ye,G,X,Le.material.doubleSided?fa.disabled:fa.backCCW,Bt,E.id,Le.vertexBuffer,Le.indexBuffer,Le.segments,E.paint,w.transform.zoom,void 0,Ct)}function I3(D,w){return D.style._importedAsBasemap?"basemap":w.scope}function LE(D,w,E,F,G,X,J,de,ye,Ce){const Le=D.transform,Xe=!!w.isGeometryBloom&&w.isGeometryBloom;if(Xe&&D.renderPass==="shadow")return;const Ke=Le.projection.name==="globe"?o.ev(E,Le):[...E];o.aD(Ke,Ke,w.globalMatrix);const st=o.aD([],F,Ke);if(w.meshes)for(const dt of w.meshes){const it=de.get(dt.material.name);if(it&&it.opacity<=0)continue;if(dt.material.alphaMode!=="BLEND"){J.push({mesh:dt,depth:0,modelIndex:G,worldViewProjection:st,nodeModelMatrix:Ke,isLightMesh:Xe,materialOverride:it,modelOpacity:ye,modelColor:Ce,node:w,modelMatrix:E});continue}const jt=o.ah([],dt.centroid,st);!Le.isOrthographic&&jt[2]<=0||X.push({mesh:dt,depth:jt[2],modelIndex:G,worldViewProjection:st,nodeModelMatrix:Ke,isLightMesh:Xe,materialOverride:it,modelOpacity:ye,modelColor:Ce,node:w,modelMatrix:E})}if(w.children)for(const dt of w.children)LE(D,dt,E,F,G,X,J,de,ye,Ce)}function GS(D,w,E,F){const G=E.shadowRenderer;if(!G)return;const X=G.getShadowPassDepthMode(),J=G.calculateShadowPassMatrixFromMatrix(w),de=mh(J);E.getOrCreateProgram("modelDepth").draw(E,E.context.gl.TRIANGLES,X,Da.disabled,Ia.disabled,fa.disabled,de,F.id,D.vertexBuffer,D.indexBuffer,D.segments,F.paint,E.transform.zoom,void 0,void 0)}function IE(D,w,E,F){const G=function(Le,Xe){if(Xe.footprintDebugMesh)return Xe.footprintDebugMesh;if(!Xe.footprint)return null;const Ke=Le.context,st=Xe.footprint.vertices,dt=Xe.footprint.indices,it=new o.dB;it.reserve(st.length);for(const xs of st)it.emplaceBack(xs.x,xs.y);const jt=new o.dC;jt.reserve(dt.length);for(let xs=0;xs0){const Ke=X.terrain,st=Ke.findDEMTileFor(de);st&&st.dem?ye=o.ex.create(Ke,de,st):Xe=0}if(Xe===0&&(J.terrainElevationMin=0,J.terrainElevationMax=0),Xe===J.validForExaggeration&&(Xe===0||ye&&ye._demTile&&ye._demTile.tileID===J.validForDEMTile.id&&ye._dem._timestamp===J.validForDEMTile.timestamp))return!1;for(const Ke in J.instancesPerModel){const st=J.instancesPerModel[Ke];for(let dt=0;dtCe&&(Ce=st.max)}const Le=o.aC(F.x,X,J)-F.x,Xe=o.aC(F.y,de,ye)-F.y,Ke=o.bU(Ce,w.center.lat)-F.z;return w._zoomFromMercatorZ(Math.sqrt(Le*Le+Xe*Xe+Ke*Ke))}function Wc(D,w,E,F,G,X,J){const de=D.context,ye=D.renderPass==="shadow",Ce=D.shadowRenderer,Le=ye&&Ce?Ce.getShadowPassDepthMode():new Hr(de.gl.LEQUAL,Hr.ReadWrite,D.depthRangeFor3D),Xe=D.isTileAffectedByFog(X),Ke=D.transform.projection.name==="globe";if(E.meshes)for(const st of E.meshes){const dt=Ke?[]:["MODEL_POSITION_ON_GPU"],it=[];let jt,wt,Bt;const Vt=!Ke&&F.instancedDataArray.length>20;Vt&&dt.push("INSTANCED_ARRAYS");const Ct=Sd(D,w.paint.get("model-cutoff-fade-range"));if(Ct.shouldRenderCutoff&&dt.push("RENDER_CUTOFF"),ye&&Ce)jt=D.getOrCreateProgram("modelDepth",{defines:dt}),wt=mh(J.shadowTileMatrix,J.shadowTileMatrix,Float32Array.from(E.globalMatrix)),Bt=Ia.disabled;else{Oi(dt,it,st,D,w.paint.get("model-color-use-theme").constantOr("default")==="none"?null:w.lut),jt=D.getOrCreateProgram("model",{defines:dt,overrideFog:Xe});const rs=st.material,_s=rs.pbrMetallicRoughness,Gt=w.paint.get("model-opacity").constantOr(1),ss=w.paint.get("model-emissive-strength").constantOr(0);wt=wc(X.expandedProjMatrix,Float32Array.from(E.globalMatrix),new Float32Array(16),null,D,Gt,_s.baseColorFactor,rs.emissiveFactor,_s.metallicFactor,_s.roughnessFactor,rs,ss,w,G),Ce&&(J.shadowUniformsInitialized?jt.setShadowUniformValues(de,Ce.getShadowUniformValues()):(Ce.setupShadows(X.toUnwrapped(),jt,"model-tile"),J.shadowUniformsInitialized=!0)),Bt=Ct.shouldRenderCutoff||Gt<1||rs.alphaMode!=="OPAQUE"?Ia.alphaBlended:Ia.unblended}D.uploadCommonUniforms(de,jt,X.toUnwrapped(),null,Ct);const Ss=st.material.doubleSided?fa.disabled:fa.backCCW;if(Vt)it.push(F.instancedDataBuffer),jt.draw(D,de.gl.TRIANGLES,Le,Da.disabled,Bt,Ss,wt,w.id,st.vertexBuffer,st.indexBuffer,st.segments,w.paint,D.transform.zoom,void 0,it,F.instancedDataArray.length);else{const rs=ye?"u_instance":"u_normal_matrix";for(let _s=0;_sye[1]?J:ye,X[0]=E.max[0],J=o.aE(o.bE(),X,G),de=J[1]ye[1]?J:ye,X[1]=E.min[1],J=o.aE(o.bE(),X,G),de=J[1]ye[1]?J:ye;const Ce=o.aC(F[0],0,1),Le=100*w.pixelsPerMeter*o.aC(F[1],0,1),Xe=o.aC(F[2],0,1),Ke=o.ey(o.bE(),de,ye,Ce),st=Math.tan(.5*w.fovX),dt=-Ke[2]*st;if(Le===0)return Ke[1]<-Math.abs(dt)?Xe:1;const it=(-Math.abs(dt)-Ke[1])/Le,jt=(Bt,Vt,Ct)=>(1-Ct)*Bt+Ct*Vt,wt=o.aC(jt(1,Xe,it),Xe,1);return jt(1,wt,o.aC((w.pitch-20)/20,0,1))}class DE{}class bL{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(w,E,F){{const Xe=this._storage.get(E.id);if(Xe)return Xe.lastUsedFrameIdx=w,Xe.buf}const G=F.gl,X=G.getBufferParameter(G.ELEMENT_ARRAY_BUFFER,G.BUFFER_SIZE),J=new ArrayBuffer(X),de=new Int16Array(J);G.getBufferSubData(G.ELEMENT_ARRAY_BUFFER,0,new Int16Array(J));const ye=new o.eA;for(let Xe=0;Xe30&&(F.buf.destroy(),this._storage.delete(E))}destroy(){for(const[w,E]of this._storage)E.buf.destroy(),this._storage.delete(w)}}class _L{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const $N=o.e8([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_rainParticleData",components:4}]);class wL{constructor(w){this.revealStart=11,this.revealRange=2}}const OE=o.e8([{type:"Float32",name:"a_pos_2f",components:2}]);class Y9{destroy(){this.vignetteVx&&this.vignetteVx.destroy(),this.vignetteIdx&&this.vignetteIdx.destroy()}draw(w,E){const F=w.getOrCreateProgram("vignette");if(!this.vignetteVx||!this.vignetteIdx){const J=new o.eB,de=new o.dC;J.emplaceBack(-1,-1),J.emplaceBack(1,-1),J.emplaceBack(1,1),J.emplaceBack(-1,1),de.emplaceBack(0,1,2),de.emplaceBack(0,2,3),this.vignetteVx=w.context.createVertexBuffer(J,OE.members),this.vignetteIdx=w.context.createIndexBuffer(de)}const G=o.dy.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){w.uploadCommonUniforms(w.context,F);const J={u_vignetteShape:(X={vignetteShape:[E.start,E.range,Math.pow(10,E.fadePower)],vignetteColor:[E.color.r,E.color.g,E.color.b,E.color.a*E.strength]}).vignetteShape,u_vignetteColor:X.vignetteColor};F.draw(w,w.context.gl.TRIANGLES,Hr.disabled,Da.disabled,Ia.alphaBlended,fa.disabled,J,"vignette",this.vignetteVx,this.vignetteIdx,G)}var X}}class FE{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(w,E){const F=w.getFreeCameraOptions().position,G=F.toAltitude(),X=F.toLngLat(),J=o.ap(X.lng),de=o.ap(X.lat),ye=w.pixelsPerMeter/E,Ce=J*o.eD,Le=o.eD*Math.log(Math.tan(Math.PI/4+de/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 Xe=-this._offsetYPrev+Le,Ke=-this._elevationPrev+G;this._accumulatedOffsetX+=(-this._offsetXPrev+Ce)*ye,this._accumulatedOffsetY+=Xe*ye,this._accumulatedElevation+=Ke*ye,this._offsetXPrev=Ce,this._offsetYPrev=Le,this._elevationPrev=G}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function ee(D,w){return[-(D[0]-Math.floor(D[0]/w)*w),-(D[1]-Math.floor(D[1]/w)*w),-(D[2]-Math.floor(D[2]/w)*w)]}function oe(D){const w=o.em(1323123451230),E=[];for(let F=0;F Rain"),this._vignetteParams={strength:1,start:.7,range:1,fadePower:.4,color:{r:.27,g:.27,b:.27,a:1}},this.particlesCount=16e3}update(w){const E=w.context;if(!this.particlesVx){const F=oe(this.particlesCount),G=new o.eE,X=new o.dC;let J=0;const de=o.em(1323123451230);for(let ye=0;yeF)return;const G=Re(0,1,E.revealStart,E.revealStart+E.revealRange,F);if(!this.particlesVx||!this.particlesIdx)return;const X=structuredClone(this._params);let J=[-X.direction.x,X.direction.y,-100];o.ay(J,J);const de=structuredClone(this._vignetteParams);de.strength*=G,X.overrideStyleParameters||(X.intensity=w.style.rain.state.density,X.timeFactor=w.style.rain.state.intensity,X.color=structuredClone(w.style.rain.state.color),J=structuredClone(w.style.rain.state.direction),X.screenThinning.intensity=w.style.rain.state.centerThinning,X.dropletSizeX=w.style.rain.state.dropletSize[0],X.dropletSizeYScale=w.style.rain.state.dropletSize[1]/w.style.rain.state.dropletSize[0],X.distortionStrength=100*w.style.rain.state.distortionStrength,de.strength=1,de.color=structuredClone(w.style.rain.state.vignetteColor));const ye=this.updateOnRender(w,X.timeFactor),Ce=w.context,Le=Ce.gl,Xe=w.transform;this.screenTexture&&this.screenTexture.size[0]===w.width&&this.screenTexture.size[1]===w.height||(this.screenTexture=new o.T(Ce,{width:w.width,height:w.height,data:null},Le.RGBA8)),X.distortionStrength>0&&(Ce.activeTexture.set(Le.TEXTURE0),this.screenTexture.bind(Le.LINEAR,Le.CLAMP_TO_EDGE),Le.copyTexSubImage2D(Le.TEXTURE_2D,0,0,0,0,0,w.width,w.height));const Ke=w.getOrCreateProgram("rainParticle");w.uploadCommonUniforms(Ce,Ke),Ce.activeTexture.set(Le.TEXTURE0),this.screenTexture.bind(Le.LINEAR,Le.CLAMP_TO_EDGE);const st=[X.color.r,X.color.g,X.color.b,X.color.a],dt=(it,jt)=>{const wt=ee(this._movement.getPosition(),it),Bt=X.dropletSizeX,Vt=X.dropletSizeX*X.dropletSizeYScale,Ct=w.width/2,Ss=w.height/2,rs=Re(0,X.screenThinning.start,0,1,X.screenThinning.intensity),_s=Re(.001,X.screenThinning.range,0,1,X.screenThinning.intensity),Gt=Re(0,X.screenThinning.particleOffset,0,1,X.screenThinning.intensity),ss=(xs={modelview:ye.modelviewMatrix,projection:ye.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:wt,velocityConeAperture:X.velocityConeAperture,velocity:X.velocity,boxSize:it,rainDropletSize:[Bt,Vt],distortionStrength:X.distortionStrength,rainDirection:J,color:st,screenSize:[Xe.width,Xe.height],thinningCenterPos:[Ct,Ss],thinningShape:[rs,_s,Math.pow(10,X.screenThinning.fadePower)],thinningAffectedRatio:X.screenThinning.affectedRatio,thinningParticleOffset:Gt,shapeDirectionalPower:X.shapeDirPower,shapeNormalPower:X.shapeNormalPower,mode:jt?0:1},{u_modelview:Float32Array.from(xs.modelview),u_projection:Float32Array.from(xs.projection),u_time:xs.time,u_cam_pos:xs.camPos,u_texScreen:0,u_velocityConeAperture:xs.velocityConeAperture,u_velocity:xs.velocity,u_boxSize:xs.boxSize,u_rainDropletSize:xs.rainDropletSize,u_distortionStrength:xs.distortionStrength,u_rainDirection:xs.rainDirection,u_color:xs.color,u_screenSize:xs.screenSize,u_thinningCenterPos:xs.thinningCenterPos,u_thinningShape:xs.thinningShape,u_thinningAffectedRatio:xs.thinningAffectedRatio,u_thinningParticleOffset:xs.thinningParticleOffset,u_shapeDirectionalPower:xs.shapeDirectionalPower,u_shapeNormalPower:xs.shapeNormalPower,u_mode:xs.mode});var xs;const Ks=Math.round(X.intensity*this.particlesCount),Ts=o.dy.simpleSegment(0,0,4*Ks,2*Ks);Ke.draw(w,Le.TRIANGLES,Hr.disabled,Da.disabled,Ia.alphaBlended,fa.disabled,ss,"rain_particles",this.particlesVx,this.particlesIdx,Ts)};X.distortionStrength>0&&dt(X.boxSize,!0),dt(X.boxSize,!1),this._vignette.draw(w,de)}}const At=o.e8([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_snowParticleData",components:4},{type:"Float32",name:"a_snowParticleDataHorizontalOscillation",components:2}]);class Os extends nt{constructor(w){super(2.25),this._params={overrideStyleParameters:!1,intensity:.85,timeFactor:.75,velocityConeAperture:70,velocity:40,horizontalOscillationRadius:4,horizontalOscillationRate:1.5,boxSize:2e3,billboardSize:2,shapeFadeStart:.27,shapeFadePower:.21,screenThinning:{intensity:.4,start:.15,range:1.4,fadePower:.24,affectedRatio:1,particleOffset:-.2},color:{r:1,g:1,b:1,a:1},direction:{x:-50,y:-35}},this._revealParams=new wL("Precipitation > Snow"),this._vignetteParams={strength:.3,start:.78,range:.46,fadePower:.2,color:{r:1,g:1,b:1,a:1}},this.particlesCount=16e3}update(w){const E=w.context;if(!this.particlesVx){const F=oe(this.particlesCount),G=new o.eF,X=new o.dC;let J=0;const de=o.em(1323123451230);for(let ye=0;yeJ)return;const de=Re(0,1,X.revealStart,X.revealStart+X.revealRange,J);G.strength*=de,E.overrideStyleParameters||(E.intensity=w.style.snow.state.density,E.timeFactor=w.style.snow.state.intensity,E.color=structuredClone(w.style.snow.state.color),F=structuredClone(w.style.snow.state.direction),E.screenThinning.intensity=w.style.snow.state.centerThinning,E.billboardSize=2.79*w.style.snow.state.flakeSize,G.strength=1,G.color=structuredClone(w.style.snow.state.vignetteColor));const ye=this.updateOnRender(w,E.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const Ce=w.context,Le=Ce.gl,Xe=w.transform,Ke=w.getOrCreateProgram("snowParticle");w.uploadCommonUniforms(Ce,Ke),((st,dt,it)=>{const jt=ee(this._movement.getPosition(),st),wt=Xe.width/2,Bt=Xe.height/2,Vt=Re(0,it.screenThinning.start,0,1,it.screenThinning.intensity),Ct=Re(.001,it.screenThinning.range,0,1,it.screenThinning.intensity),Ss=Re(0,it.screenThinning.particleOffset,0,1,it.screenThinning.intensity),rs=(_s={modelview:ye.modelviewMatrix,projection:ye.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:jt,velocityConeAperture:it.velocityConeAperture,velocity:it.velocity,horizontalOscillationRadius:it.horizontalOscillationRadius,horizontalOscillationRate:it.horizontalOscillationRate,boxSize:st,billboardSize:1*it.billboardSize,simpleShapeParameters:[it.shapeFadeStart,it.shapeFadePower],screenSize:[Xe.width,Xe.height],thinningCenterPos:[wt,Bt],thinningShape:[Vt,Ct,Math.pow(10,it.screenThinning.fadePower)],thinningAffectedRatio:it.screenThinning.affectedRatio,thinningParticleOffset:Ss,color:[it.color.r,it.color.g,it.color.b,it.color.a],direction:F},{u_modelview:Float32Array.from(_s.modelview),u_projection:Float32Array.from(_s.projection),u_time:_s.time,u_cam_pos:_s.camPos,u_velocityConeAperture:_s.velocityConeAperture,u_velocity:_s.velocity,u_horizontalOscillationRadius:_s.horizontalOscillationRadius,u_horizontalOscillationRate:_s.horizontalOscillationRate,u_boxSize:_s.boxSize,u_billboardSize:_s.billboardSize,u_simpleShapeParameters:_s.simpleShapeParameters,u_screenSize:_s.screenSize,u_thinningCenterPos:_s.thinningCenterPos,u_thinningShape:_s.thinningShape,u_thinningAffectedRatio:_s.thinningAffectedRatio,u_thinningParticleOffset:_s.thinningParticleOffset,u_particleColor:_s.color,u_direction:_s.direction});var _s;const Gt=Math.round(it.intensity*this.particlesCount),ss=o.dy.simpleSegment(0,0,4*Gt,2*Gt);this.particlesVx&&this.particlesIdx&&Ke.draw(w,Le.TRIANGLES,Hr.disabled,Da.disabled,Ia.alphaBlended,fa.disabled,rs,"snow_particles",this.particlesVx,this.particlesIdx,ss)})(E.boxSize,0,E),this._vignette.draw(w,G)}}const Yn={symbol:function(D,w,E,F,G){if(D.renderPass!=="translucent")return;const X=Da.disabled,J=D.colorModeForRenderPass(),de=E.layout.get("text-variable-anchor"),ye=E.layout.get("text-size-scale-range"),Ce=o.aC(D.scaleFactor,ye[0],ye[1]);de&&function(Ke,st,dt,it,jt,wt,Bt,Vt){const Ct=st.transform,Ss=jt==="map",rs=wt==="map";for(const _s of Ke){const Gt=it.getTile(_s),ss=Gt.getBucket(dt);if(!ss||!ss.text||!ss.text.segments.get().length)continue;const xs=o.bj(ss.textSizeData,Ct.zoom,Vt),Ks=Um(_s,ss.getProjection(),Ct),Ts=Ct.calculatePixelsToTileUnitsMatrix(Gt),_n=zd(Ks,Gt.tileID.canonical,rs,Ss,Ct,ss.getProjection(),Ts),hn=ss.hasIconTextFit()&&ss.hasIconData();xs&&Gc(ss,Ss,rs,Bt,Ct,_n,_s,Math.pow(2,Ct.zoom-Gt.tileID.overscaledZ),xs,hn)}}(F,D,E,w,E.layout.get("text-rotation-alignment"),E.layout.get("text-pitch-alignment"),G,Ce);const Le=E.paint.get("icon-opacity").constantOr(1)!==0,Xe=E.paint.get("text-opacity").constantOr(1)!==0;E.layout.get("symbol-sort-key").constantOr(1)!==void 0&&(Le||Xe)?Hm(D,w,E,F,X,J):(Le&&Hm(D,w,E,F,X,J,{onlyIcons:!0}),Xe&&Hm(D,w,E,F,X,J,{onlyText:!0})),w.map.showCollisionBoxes&&(wr(D,w,E,F,E.paint.get("text-translate"),E.paint.get("text-translate-anchor"),!0),wr(D,w,E,F,E.paint.get("icon-translate"),E.paint.get("icon-translate-anchor"),!1))},circle:function(D,w,E,F){if(D.renderPass!=="translucent")return;const G=E.paint.get("circle-opacity"),X=E.paint.get("circle-stroke-width"),J=E.paint.get("circle-stroke-opacity"),de=E.layout.get("circle-sort-key").constantOr(1)!==void 0,ye=E.paint.get("circle-emissive-strength");if(G.constantOr(1)===0&&(X.constantOr(1)===0||J.constantOr(1)===0))return;const Ce=D.context,Le=Ce.gl,Xe=D.transform,Ke=!(!D.terrain||!D.terrain.enabled),st=E.layout.get("circle-elevation-reference"),dt=D.depthModeForSublayer(0,Hr.ReadOnly),it=new Hr(D.context.gl.LEQUAL,Hr.ReadOnly,D.depthRangeFor3D),jt=st==="none"||Ke?dt:it,wt=Da.disabled,Bt=D.colorModeForDrapableLayerRenderPass(ye),Vt=Xe.projection.name==="globe",Ct=[o.aH(Xe.center.lng),o.aL(Xe.center.lat)],Ss=[];for(let _s=0;_s_s.sortKey-Gt.sortKey);const rs={useDepthForOcclusion:Xe.depthOcclusionForSymbolsAndCircles};for(const _s of Ss){const{programConfiguration:Gt,program:ss,layoutVertexBuffer:xs,dynamicBuffers:Ks,indexBuffer:Ts,uniformValues:_n,tile:hn}=_s.state,Rn=_s.segments;D.terrain&&D.terrain.setupElevationDraw(hn,ss,rs),D.uploadCommonUniforms(Ce,ss,hn.tileID.toUnwrapped()),ss.draw(D,Le.TRIANGLES,jt,wt,Bt,fa.disabled,_n,E.id,xs,Ts,Rn,E.paint,Xe.zoom,Gt,Ks)}},heatmap:function(D,w,E,F){if(E.paint.get("heatmap-opacity")!==0)if(D.renderPass==="offscreen"){const G=D.context,X=G.gl,J=Da.disabled,de=new Ia([X.ONE,X.ONE,X.ONE,X.ONE],o.aq.transparent,[!0,!0,!0,!0]),ye=D.transform.projection.name==="globe"?.5:.25;E.heatmapFbo=vp.createWithTexture(G,E.heatmapFbo,D.width*ye,D.height*ye),G.clear({color:o.aq.transparent});const Ce=D.transform,Le=Ce.projection.name==="globe",Xe=Le?["PROJECTION_GLOBE_VIEW"]:[],Ke=Le?fa.frontCCW:fa.disabled,st=[o.aH(Ce.center.lng),o.aL(Ce.center.lat)];for(let dt=0;dt({u_image:0,u_color_ramp:1,u_opacity:Xe.paint.get("heatmap-opacity")}))(0,X),X.id,G.viewportBuffer,G.quadTriangleIndexBuffer,G.viewportSegments,X.paint,G.transform.zoom)}(D,E))},line:function(D,w,E,F){const G=E.paint.get("line-opacity"),X=E.paint.get("line-width");if(G.constantOr(1)===0||X.constantOr(1)===0)return;const J=E.paint.get("line-blend-mode");if(J!=="default"&&D.transform.projection.name!=="globe")return D.terrain&&D.terrain.renderingToTexture?void function(de,ye,Ce,Le,Xe){if(de.renderPass!=="translucent")return;const Ke=de.context,st=Ke.gl,dt=de.terrain;if(!dt)return;const it=Ke.bindFramebuffer.current,jt=de.emissiveMode==="mrt-fallback";Ce.lineBlendDrapeFbo=vp.createWithTexture(Ke,Ce.lineBlendDrapeFbo,dt.drapeBufferSize[0],dt.drapeBufferSize[1],!0),Ce.lineBlendDrapeStencil=Ce.lineBlendDrapeFbo._stencilRbo,jt&&st.drawBuffers([st.COLOR_ATTACHMENT0]),Ke.clear({color:Jp[Xe].clearColor,depth:1,stencil:0});const wt=de.currentStencilSource,Bt=de._tileClippingMaskIDs,Vt=de.nextStencilID;de.currentStencilSource=void 0,de._tileClippingMaskIDs={},de.nextStencilID=1;const Ct=de._terrain;de._terrain=null,de._renderTileClippingMasks(Ce,ye,Le),Iu(de,ye,Ce,Le,Jp[Xe].colorMode,!0),de._terrain=Ct,de.currentStencilSource=wt,de._tileClippingMaskIDs=Bt,de.nextStencilID=Vt,Ke.bindFramebuffer.set(it),jt&&st.drawBuffers([st.COLOR_ATTACHMENT0,st.COLOR_ATTACHMENT1]);const Ss=dt.drapeBufferSize;Ke.viewport.set([0,0,Ss[0],Ss[1]]);const rs=Ce.lineBlendDrapeFbo;if(!rs)return;Ke.activeTexture.set(st.TEXTURE0),st.bindTexture(st.TEXTURE_2D,rs.colorAttachment0.get());const _s=Xe==="additive"?1:Ce.paint.get("line-opacity").constantOr(1),Gt=Ce.paint.get("line-emissive-strength").constantOr(0),ss=Xe==="additive"?de.colorModeForDrapableLayerRenderPass(Gt):Jp[Xe].colorMode;de.getOrCreateProgram("lineBlendComposite").draw(de,st.TRIANGLES,Hr.disabled,Da.disabled,ss,fa.disabled,ic(0,_s,Jp[Xe].compositeUniformValue),Ce.id,de.viewportBuffer,de.quadTriangleIndexBuffer,de.viewportSegments,Ce.paint,de.transform.zoom)}(D,w,E,F,J):D.renderPass==="offscreen"?void function(de,ye,Ce,Le,Xe){const Ke=de.context,st=Math.ceil(de.width),dt=Math.ceil(de.height);Ce.lineBlendFbo=vp.createWithTexture(Ke,Ce.lineBlendFbo,st,dt,!0),Ce.lineBlendStencil=Ce.lineBlendFbo._stencilRbo,Ke.clear({color:Jp[Xe].clearColor,depth:1,stencil:0});const it=de.currentStencilSource,jt=de._tileClippingMaskIDs,wt=de.nextStencilID;de.currentStencilSource=void 0,de._tileClippingMaskIDs={},de.nextStencilID=1,de._renderTileClippingMasks(Ce,ye,Le);const Bt=de.renderPass;de.renderPass="translucent",Iu(de,ye,Ce,Le,Jp[Xe].colorMode),de.renderPass=Bt,de.currentStencilSource=it,de._tileClippingMaskIDs=jt,de.nextStencilID=wt,Ke.viewport.set([0,0,de.width,de.height])}(D,w,E,F,J):D.renderPass==="translucent"?void function(de,ye,Ce){const Le=de.context,Xe=Le.gl,Ke=ye.lineBlendFbo;if(!Ke)return;Le.activeTexture.set(Xe.TEXTURE0),Xe.bindTexture(Xe.TEXTURE_2D,Ke.colorAttachment0.get());const st=Ce==="additive"?1:ye.paint.get("line-opacity").constantOr(1),dt=Ce==="additive"?de.colorModeForDrapableLayerRenderPass(ye.paint.get("line-emissive-strength").constantOr(0)):Jp[Ce].colorMode;de.getOrCreateProgram("lineBlendComposite").draw(de,Xe.TRIANGLES,Hr.disabled,Da.disabled,dt,fa.disabled,ic(0,st,Jp[Ce].compositeUniformValue),ye.id,de.viewportBuffer,de.quadTriangleIndexBuffer,de.viewportSegments,ye.paint,de.transform.zoom)}(D,E,J):void 0;D.renderPass==="translucent"&&Iu(D,w,E,F)},fill:function(D,w,E,F){const G=E.paint.get("fill-color"),X=E.paint.get("fill-opacity");if(X.constantOr(1)===0)return;const J=E.paint.get("fill-emissive-strength"),de=D.colorModeForDrapableLayerRenderPass(J),ye=E.paint.get("fill-pattern"),Ce=D.opaquePassEnabledForLayer()&&!ye.constantOr(1)&&G.constantOr(o.aq.transparent).a===1&&X.constantOr(0)===1?"opaque":"translucent";let Le="none";E.layout.get("fill-elevation-reference")!=="none"?Le="road":E.paint.get("fill-z-offset").constantOr(1)!==0&&(Le="offset");const Xe=!(!D.terrain||!D.terrain.enabled),Ke={painter:D,sourceCache:w,layer:E,coords:F,colorMode:de,elevationType:Le,terrainEnabled:Xe,pass:Ce};if(D.renderPass==="shadow")return void(D.shadowRenderer&&Le==="road"&&!Xe&&function(dt){const{painter:it,sourceCache:jt,layer:wt,coords:Bt}=dt,Vt=it.context.gl,Ct=dt.painter.shadowRenderer;for(const Ss of Bt){const rs=jt.getTile(Ss),_s=rs.getBucket(wt);if(!_s)continue;const Gt=_s.elevatedStructures;if(!Gt||!Gt.shadowCasterSegments||Gt.shadowCasterSegments.segments[0].primitiveLength===0)continue;it.prepareDrawTile();const ss=_s.bufferData.programConfigurations.get(wt.id),xs=it.isTileAffectedByFog(Ss),Ks=it.getOrCreateProgram("elevatedStructuresDepth",{config:ss,overrideFog:xs}),Ts=Ct.calculateShadowPassMatrixFromTile(rs.tileID.toUnwrapped());it.uploadCommonUniforms(it.context,Ks,Ss.toUnwrapped());const _n=Mi(Ts,0);Ks.draw(it,Vt.TRIANGLES,Ct.getShadowPassDepthMode(),Da.disabled,Ia.disabled,fa.disabled,_n,wt.id,Gt.vertexBuffer,Gt.indexBuffer,Gt.shadowCasterSegments,wt.paint,it.transform.zoom,ss)}}(Ke));const st=D.emissiveMode==="mrt-fallback";if(Le!=="offset"){if(N1(Ke,!1,st),Le==="road"){const dt=!Xe&&D.renderPass==="translucent";dt&&Ob(D,w,E,F,"geometry"),N1(Ke,!0,st,Da.disabled),dt&&function(it){const{painter:jt,sourceCache:wt,layer:Bt,coords:Vt,colorMode:Ct}=it,Ss=jt.context.gl,rs=it.painter.shadowRenderer,_s=!!rs&&rs.enabled,Gt=new Hr(jt.context.gl.LEQUAL,Hr.ReadOnly,jt.depthRangeFor3D);let ss=[0,0,0];if(_s){const Ks=jt.style.directionalLight,Ts=jt.style.ambientLight;Ks&&Ts&&(ss=tm(jt.style,Ks,Ts))}const xs=Ks=>{for(const Ts of Vt){const _n=wt.getTile(Ts),hn=_n.getBucket(Bt);if(!hn)continue;const Rn=hn.elevatedStructures;if(!Rn)continue;let Kn,en;if(Ks?(Kn=Rn.renderableBridgeSegments,en=Rn.bridgeProgramConfigurations.get(Bt.id)):(Kn=Rn.renderableTunnelSegments,en=Rn.tunnelProgramConfigurations.get(Bt.id)),!Kn||Kn.segments[0].primitiveLength===0)continue;en.updatePaintBuffers(),jt.prepareDrawTile();const Ls=jt.isTileAffectedByFog(Ts),yn=[];_s&&yn.push("RENDER_SHADOWS","NORMAL_OFFSET");const jn=jt.getOrCreateProgram("elevatedStructures",{config:en,overrideFog:Ls,defines:yn}),An=jt.translatePosMatrix(Ts.projMatrix,_n,Bt.paint.get("fill-translate"),Bt.paint.get("fill-translate-anchor"));_s&&rs.setupShadows(_n.tileID.toUnwrapped(),jn,"vector-tile");const jr=yl(An,ss);jt.uploadCommonUniforms(jt.context,jn,Ts.toUnwrapped()),jn.draw(jt,Ss.TRIANGLES,Gt,Da.disabled,Ct,fa.backCCW,jr,Bt.id,Rn.vertexBuffer,Rn.indexBuffer,Kn,Bt.paint,jt.transform.zoom,en,[Rn.vertexBufferNormal])}};xs(!0),xs(!1)}(Ke)}}else N1(Ke,!1,st,D.stencilModeFor3D())},"fill-extrusion":function(D,w,E,F){const G=E.paint.get("fill-extrusion-opacity"),X=D.context,J=X.gl,de=D.terrain,ye=de&&de.renderingToTexture;if(G===0)return;const Ce=D.emissiveMode==="mrt-fallback",Le=D.conflationActive&&D.style.isLayerClipped(E,w.getSource()),Xe=D.style.order.indexOf(E.fqid);if(Le&&function(Ke,st,dt,it,jt){for(const wt of it){const Bt=st.getTile(wt).getBucket(dt);Bt&&(Bt.updateReplacement(wt,Ke.replacementSource,jt),Bt.uploadCentroid(Ke.context))}}(D,w,E,F,Xe),de||Le)for(const Ke of F){const st=w.getTile(Ke).getBucket(E);st&&My(D.context,w,Ke,st,E,de,Le)}if(D.renderPass==="shadow"&&D.shadowRenderer){if(de&&G<.65&&E._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof o.af)return;const Ke=D.shadowRenderer.getShadowPassDepthMode();bp(D,w,E,F,Ke,Da.disabled,Ia.disabled,Le)}else if(D.renderPass==="translucent"){const Ke=!E.paint.get("fill-extrusion-pattern").constantOr(1),st=E.paint.get("fill-extrusion-color").constantOr(o.aq.white);if(!ye&&st.a!==0){const dt=new Hr(D.context.gl.LEQUAL,Hr.ReadWrite,D.depthRangeFor3D);G===1&&Ke?bp(D,w,E,F,dt,Da.disabled,Ia.unblended,Le):(bp(D,w,E,F,dt,Da.disabled,Ia.disabled,Le),bp(D,w,E,F,dt,D.stencilModeFor3D(),D.colorModeForRenderPass(),Le),D.resetStencilClippingMasks())}if(D.style.enable3dLights()&&Ke&&(!de&&D.transform.projection.name!=="globe"||ye)){const dt=E.paint.get("fill-extrusion-opacity"),it=E.paint.get("fill-extrusion-ambient-occlusion-intensity"),jt=E.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),wt=E.paint.get("fill-extrusion-flood-light-intensity"),Bt=E.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Vt=E.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(Bt?null:E.lut).toArray01().slice(0,3),Ct=it>0&&jt>0,Ss=wt>0,rs=(ss,xs,Ks)=>(1-Ks)*ss+Ks*xs,_s=new Uf;_s.translate=E.paint.get("fill-extrusion-translate"),_s.translateAnchor=E.paint.get("fill-extrusion-translate-anchor"),_s.edgeRadius=E.layout.get("fill-extrusion-edge-radius"),_s.cutoffFadeRange=E.paint.get("fill-extrusion-cutoff-fade-range");const Gt=ss=>{const xs=D.depthModeForSublayer(1,Hr.ReadOnly,J.LEQUAL,!0),Ks=E.paint.get(ss?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Ts=rs(.1,3,Ks),_n=D._showOverdrawInspector;if(!_n){const hn=new Da({func:J.ALWAYS,mask:255},255,255,J.KEEP,J.KEEP,J.REPLACE),Rn=new Ia([J.ONE,J.ONE,J.ONE,J.ONE],o.aq.transparent,[!1,!1,!1,!0],J.MIN);M0(_s,D,w,E,F,xs,hn,Rn,fa.disabled,ss,"sdf",dt,it,jt,wt,Vt,Ts,Le,!1)}{const hn=_n?Da.disabled:new Da({func:J.EQUAL,mask:255},255,255,J.KEEP,J.DECR,J.DECR),Rn=_n?D.colorModeForRenderPass():new Ia([J.ONE_MINUS_DST_ALPHA,J.DST_ALPHA,J.ONE,J.ONE],o.aq.transparent,[!0,!0,!0,!0]);M0(_s,D,w,E,F,xs,hn,Rn,fa.disabled,ss,"color",dt,it,jt,wt,Vt,Ts,Le,!1)}};if(ye){const ss=()=>{const Ks=de.drapeBufferSize[0],Ts=de.drapeBufferSize[1];let _n=de.framebufferCopyTexture;return _n&&(!_n||_n.size[0]===Ks&&_n.size[1]===Ts)||(_n&&_n.destroy(),_n=de.framebufferCopyTexture=new o.T(X,new o.q({width:Ks,height:Ts}),J.RGBA8)),_n.bind(J.LINEAR,J.CLAMP_TO_EDGE),J.copyTexSubImage2D(J.TEXTURE_2D,0,0,0,0,0,Ks,Ts),_n},xs=(Ks,Ts,_n)=>{const hn=D.depthModeForSublayer(1,Hr.ReadOnly,J.LEQUAL,!1),Rn=E.paint.get(Ks?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Kn=rs(.1,3,Rn);{const en=new Ia([J.ONE,J.ONE,J.ONE,J.ONE],o.aq.transparent,[!1,!1,!1,!0]);M0(_s,D,w,E,F,hn,Da.disabled,en,fa.disabled,Ks,"clear",dt,it,jt,wt,Vt,Kn,Le,Ts)}{const en=new Da({func:J.ALWAYS,mask:255},255,255,J.KEEP,J.KEEP,J.REPLACE),Ls=new Ia([J.ONE,J.ONE,J.ONE,J.ONE],o.aq.transparent,[!1,!1,!1,!0],J.MIN);M0(_s,D,w,E,F,hn,en,Ls,fa.disabled,Ks,"sdf",dt,it,jt,wt,Vt,Kn,Le,Ts)}Ce&&!Ks&&(_n=ss());{const en=Ks?J.ZERO:J.ONE_MINUS_DST_ALPHA,Ls=new Da({func:J.EQUAL,mask:255},255,255,J.KEEP,J.DECR,J.DECR),yn=new Ia([en,J.DST_ALPHA,J.ONE_MINUS_DST_ALPHA,J.ZERO],o.aq.transparent,[!0,!0,!0,!0]);M0(_s,D,w,E,F,hn,Ls,yn,fa.disabled,Ks,"color",dt,it,jt,wt,Vt,Kn,Le,Ts)}if(!Ce||Ks){const en=new Ia([J.ONE,J.ONE,J.ONE,Ks?J.ZERO:J.ONE],o.aq.transparent,[!1,!1,!1,!0],Ks?J.FUNC_ADD:J.MAX);M0(_s,D,w,E,F,hn,Da.disabled,en,fa.disabled,Ks,"clear",dt,it,jt,wt,Vt,Kn,Le,Ts,_n)}else{J.drawBuffers([J.NONE,J.COLOR_ATTACHMENT1]);const en=new Da({func:J.EQUAL,mask:255},254,255,J.KEEP,J.DECR,J.DECR),Ls=new Ia([J.ONE,J.ONE,J.ONE,J.ONE],o.aq.transparent,[!0,!1,!1,!1],J.MAX);M0(_s,D,w,E,F,hn,en,Ls,fa.disabled,Ks,"emissive",dt,it,jt,wt,Vt,Kn,Le,Ts,_n),J.drawBuffers([J.COLOR_ATTACHMENT0])}};if(Ct||Ss){let Ks;D.prepareDrawTile(),Ce&&!Ct||(Ks=ss()),Ct&&xs(!0,!1,Ks),Ss&&xs(!1,!0,Ks)}}else Ct&&Gt(!0),Ss&&Gt(!1),(Ct||Ss)&&D.resetStencilClippingMasks()}}},building:function(D,w,E,F){D.currentLayer0&&X>0,Ce=!0;const Le=E.paint.get("building-vertical-scale");if(Le<=0)return;D.shadowRenderer||(Ce=!1);const Xe=D.conflationActive&&D.style.isLayerClipped(E,w.getSource()),Ke=D.style.order.indexOf(E.fqid);if(function(st,dt,it,jt,wt,Bt){for(const Vt of Bt){const Ct=dt.getTile(Vt).getBucket(it);Ct&&(wt&&Ct.updateReplacement(Vt,st.replacementSource,jt),Ct.uploadUpdatedIndexBuffer(st.context))}}(D,w,E,Ke,Xe,F),function(st,dt,it,jt){for(const wt of jt){const Bt=dt.getTile(wt).getBucket(it);Bt&&Bt.needsEvaluation()&&Bt.uploadUpdatedColorBuffer(st.context)}}(D,w,E,F),E.resetLayerRenderingStats(D),D.shadowRenderer&&(D.shadowRenderer.useNormalOffset=!0),D.renderPass==="shadow"&&D.shadowRenderer){const st=[],dt=D.shadowRenderer.getShadowPassDepthMode();Mv({painter:D,source:w,layer:E,coords:F,defines:st,blendMode:Ia.disabled,depthMode:dt,opacity:de,verticalScale:Le,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if(D.renderPass==="translucent"){let st=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];Ce&&(st=st.concat("RENDER_SHADOWS")),D.shadowRenderer&&D.shadowRenderer.useNormalOffset&&(st=st.concat("NORMAL_OFFSET"));const dt=E.paint.get("building-facade-emissive-chance"),it=E.paint.get("building-ambient-occlusion-intensity"),jt=E.paint.get("building-flood-light-intensity"),wt=E.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",Bt=E.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(wt?null:E.lut).toArray01().slice(0,3),Vt=E.paint.get("building-flood-light-ground-attenuation"),Ct=jt>0,Ss=new Hr(D.context.gl.LEQUAL,Hr.ReadWrite,D.depthRangeFor3D);de<1&&Mv({painter:D,source:w,layer:E,coords:F,defines:st,blendMode:Ia.disabled,depthMode:Ss,opacity:de,verticalScale:Le,facadeEmissiveChance:dt,facadeAOIntensity:it,floodLightIntensity:jt,floodLightColor:Bt,depthOnly:!0});const rs=D.colorModeForRenderPass();Mv({painter:D,source:w,layer:E,coords:F,defines:st,blendMode:rs,depthMode:Ss,opacity:de,verticalScale:Le,facadeEmissiveChance:dt,facadeAOIntensity:it,floodLightIntensity:jt,floodLightColor:Bt});const _s=E.paint.get("building-front-cutoff");qj(D.transform.pitch,_s,!!D.terrain),ye&&sx(D,w,E,F,!0,de,G,X,jt,Bt,J,Xe),Ct&&sx(D,w,E,F,!1,de,G,X,jt,Bt,Vt,Xe)}else if(D.renderPass==="light-beam"){const st=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],dt=new Hr(D.context.gl.LEQUAL,Hr.ReadOnly,D.depthRangeFor3D);Mv({painter:D,source:w,layer:E,coords:F,defines:st,blendMode:Ia.alphaBlended,depthMode:dt,opacity:de,verticalScale:Le,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}D.shadowRenderer&&(D.shadowRenderer.useNormalOffset=!1),D.resetStencilClippingMasks()},hillshade:function(D,w,E,F){if(D.renderPass!=="offscreen"&&D.renderPass!=="translucent"||D.style.disableElevatedTerrain)return;const G=D.context,X=D.terrain&&D.terrain.renderingToTexture,[J,de]=D.renderPass!=="translucent"||X?[{},F]:D.stencilConfigForOverlap(F);for(const ye of de){const Ce=w.getTile(ye);if(Ce.needsHillshadePrepare&&D.renderPass==="offscreen")ME(D,Ce,E);else if(D.renderPass==="translucent"){const Le=D.depthModeForSublayer(0,Hr.ReadOnly),Xe=E.paint.get("hillshade-emissive-strength"),Ke=D.colorModeForDrapableLayerRenderPass(Xe),st=X&&D.terrain?D.terrain.stencilModeForRTTOverlap(ye):J[ye.overscaledZ];xL(D,ye,Ce,E,Le,st,Ke)}}G.viewport.set([0,0,D.width,D.height]),D.resetStencilClippingMasks()},raster:function(D,w,E,F,G,X){if(D.renderPass!=="translucent")return;const J=E.paint.get("raster-opacity");if(J===0)return;const de=D.transform.projection.name==="globe",ye=E.paint.get("raster-elevation")!==0,Ce=ye&&de,Le=D.terrain&&D.terrain.exaggeration()>0&&ye&&E.paint.get("raster-elevation-reference")==="ground",Xe=!de&&Le;if(D.renderElevatedRasterBackface&&!Ce)return;const Ke=D.context,st=Ke.gl,dt=w.getSource(),it=function(ss,xs,Ks,Ts,_n){const hn=xs.paint.get("raster-color"),Rn=ss.type==="raster-array",Kn=[],en=xs.paint.get("raster-resampling"),Ls=xs.paint.get("raster-color-mix");let yn=xs.paint.get("raster-color-range");const jn=[Ls[0],Ls[1],Ls[2],0],An=Ls[3];let jr=en==="nearest"?Ts.NEAREST:Ts.LINEAR;if(Rn&&(Kn.push("RASTER_ARRAY"),hn||Kn.push("RASTER_COLOR"),en==="linear"&&Kn.push("RASTER_ARRAY_LINEAR"),jr=Ts.NEAREST,!yn&&ss.rasterLayers)){const ur=ss.rasterLayers.find(({id:hr})=>hr===xs.sourceLayer);ur&&ur.fields&&ur.fields.range&&(yn=ur.fields.range)}if(yn=yn||[0,1],hn){Kn.push("RASTER_COLOR"),Ks.activeTexture.set(Ts.TEXTURE2),xs.updateColorRamp(yn);let ur=xs.colorRampTexture;ur||(ur=xs.colorRampTexture=new o.T(Ks,xs.colorRamp,Ts.RGBA8)),ur.bind(jr,Ts.CLAMP_TO_EDGE)}return _n&&Kn.push("USE_MRT1"),{mix:jn,range:yn,offset:An,defines:Kn,resampling:jr}}(dt,E,Ke,st,D.terrain&&D.terrain.renderingToTexture&&D.emissiveMode==="mrt-fallback");if(dt instanceof o.aV&&!F.length&&!de)return;const jt=E.paint.get("raster-emissive-strength"),wt=D.colorModeForDrapableLayerRenderPass(jt),Bt=D.terrain&&D.terrain.renderingToTexture,Vt=!D.options.moving,Ct=E.paint.get("raster-resampling")==="nearest"?st.NEAREST:st.LINEAR;if(dt instanceof o.aV&&!F.length&&(dt.onNorthPole||dt.onSouthPole)){const ss=ye?D.stencilModeFor3D():Da.disabled;return void Fb(!!dt.onNorthPole,null,D,w,E,jt,it,fa.disabled,ss)}if(!F.length)return;const[Ss,rs]=dt instanceof o.aV||Bt?[{},F]:D.stencilConfigForOverlap(F),_s=rs[rs.length-1].overscaledZ;Ce&&it.defines.push("PROJECTION_GLOBE_VIEW"),ye&&it.defines.push("RENDER_CUTOFF","ELEVATED"),Le&&it.defines.push("ELEVATION_REFERENCE_GROUND");const Gt=(ss,xs,Ks)=>{for(const Ts of ss){const _n=Ts.toUnwrapped(),hn=w.getTile(Ts);if(Bt&&(!hn||!hn.hasData()))continue;Ke.activeTexture.set(st.TEXTURE0);const Rn=Hj(hn,dt,E,it);if(!Rn||!Rn.texture)continue;const{texture:Kn,mix:en,offset:Ls,tileSize:yn,buffer:jn}=Rn;let An,jr;Bt?(An=Hr.disabled,jr=Ts.projMatrix):ye?(An=new Hr(st.LEQUAL,Hr.ReadWrite,D.depthRangeFor3D),jr=de?Float32Array.from(D.transform.expandedFarZProjMatrix):D.transform.calculateProjMatrix(_n,Vt)):(An=D.depthModeForSublayer(Ts.overscaledZ-_s,J===1?Hr.ReadWrite:Hr.ReadOnly,st.LESS),jr=D.transform.calculateProjMatrix(_n,Vt));const ur=D.terrain&&Bt?D.terrain.stencilModeForRTTOverlap(Ts):Ss[Ts.overscaledZ],hr=X?0:E.paint.get("raster-fade-duration");hn.registerFadeDuration(hr);const Vn=w.findLoadedParent(Ts,0),ca=_t(hn,Vn,w,D.transform,hr);let Na,ea;!ca.isFading&&hn.refreshedUponExpiration&&(hn.refreshedUponExpiration=!1),D.terrain&&D.terrain.prepareDrawTile(),Ke.activeTexture.set(st.TEXTURE0),Kn.bind(Ct,st.CLAMP_TO_EDGE),Ke.activeTexture.set(st.TEXTURE1),Vn?(Vn.texture&&Vn.texture.bind(Ct,st.CLAMP_TO_EDGE),Na=Math.pow(2,Vn.tileID.overscaledZ-hn.tileID.overscaledZ),ea=[hn.tileID.canonical.x*Na%1,hn.tileID.canonical.y*Na%1]):Kn.bind(Ct,st.CLAMP_TO_EDGE),"useMipmap"in Kn&&Ke.extTextureFilterAnisotropic&&D.transform.pitch>20&&st.texParameterf(st.TEXTURE_2D,Ke.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,Ke.extTextureFilterAnisotropicMax);const ia=D.transform;let ii;const Ni=ye?zb(ia):[0,0,0,0];let yi,Ji,Ha,eo,vi,Wo=0;if(Ce&&dt instanceof o.aV&&dt.coordinates.length>3)yi=Float32Array.from(o.du(o.dv(new o.cn(0,0,0)))),Ji=Float32Array.from(ia.globeMatrix),Ha=Float32Array.from(o.dq(ia)),eo=[o.aH(ia.center.lng),o.aL(ia.center.lat)],ii=dt.elevatedGlobePerspectiveTransform,vi=dt.elevatedGlobeGridMatrix||new Float32Array(9);else if(Ce){const hl=o.dr(Ts.canonical);Wo=o.ds(hl.getCenter().lat),yi=Float32Array.from(o.du(o.dv(Ts.canonical))),Ji=Float32Array.from(ia.globeMatrix),Ha=Float32Array.from(o.dq(ia)),eo=[o.aH(ia.center.lng),o.aL(ia.center.lat)],ii=[0,0],vi=Float32Array.from(o.dt(Ts.canonical,hl,Wo,ia.worldSize/ia._pixelsPerMercatorPixel))}else ii=dt instanceof o.aV?dt.perspectiveTransform:[0,0],yi=new Float32Array(16),Ji=new Float32Array(9),Ha=new Float32Array(16),eo=[0,0],vi=new Float32Array(9);const oc=Nu(D,jr,yi,Ji,Ha,vi,ea||[0,0],o.al(D.transform.zoom),eo,Ni,Na||1,ca,E,ii,ye?E.paint.get("raster-elevation"):0,2,en,Ls,it.range,yn,jn,jt),Ed=D.isTileAffectedByFog(Ts),Tc=D.getOrCreateProgram("raster",{defines:it.defines,overrideFog:Ed});if(D.uploadCommonUniforms(Ke,Tc,_n),dt instanceof o.aV){const hl=dt.elevatedGlobeVertexBuffer,qi=dt.elevatedGlobeIndexBuffer;if(Bt||!de)dt.boundsBuffer&&dt.boundsSegments&&Tc.draw(D,st.TRIANGLES,An,Da.disabled,wt,fa.disabled,oc,E.id,dt.boundsBuffer,D.quadTriangleIndexBuffer,dt.boundsSegments);else if(hl&&qi){const $i=ia.zoom<=o.cJ?dt.elevatedGlobeSegments:dt.getSegmentsForLongitude(ia.center.lng);$i&&Tc.draw(D,st.TRIANGLES,An,Da.disabled,wt,xs,oc,E.id,hl,qi,$i)}}else if(Ce){An=new Hr(st.LEQUAL,Hr.ReadOnly,D.depthRangeFor3D);const hl=D.globeSharedBuffers;if(hl){Le&&(D.terrain.setupElevationDraw(hn,Tc),D.uploadCommonUniforms(Ke,Tc,hn.tileID.toUnwrapped()));const[qi,$i,Mc]=hl.getGridBuffers(Wo,!1),$d=Tc.getAttributeLocation(st,"a_texture_pos");$d!==-1&&st.vertexAttribI4ui($d,0,0,0,0),Tc.draw(D,st.TRIANGLES,An,Ks||ur,D.colorModeForRenderPass(),xs,oc,E.id,qi,$i,Mc)}}else if(Xe)An=new Hr(st.LEQUAL,Hr.ReadWrite,D.depthRangeFor3D),D.terrain.setupElevationDraw(hn,Tc),D.uploadCommonUniforms(Ke,Tc,hn.tileID.toUnwrapped()),ia.pitch>20&&Tc.draw(D,st.TRIANGLES,An,Da.disabled,Ia.disabled,fa.frontCCW,oc,E.id,D.terrain.gridBuffer,D.terrain.gridIndexBuffer,D.terrain.gridSegments),Tc.draw(D,st.TRIANGLES,An,ur,wt,fa.backCCW,oc,E.id,D.terrain.gridBuffer,D.terrain.gridIndexBuffer,D.terrain.gridSegments);else{const{tileBoundsBuffer:hl,tileBoundsIndexBuffer:qi,tileBoundsSegments:$i}=D.getTileBoundsBuffers(hn);Tc.draw(D,st.TRIANGLES,An,ur,wt,fa.disabled,oc,E.id,hl,qi,$i)}}if(!(dt instanceof o.aV)&&Ce)for(const Ts of ss){const _n=Ts.canonical.y===(1<o.d$[jn](_n));en.push(_n);const Ls=_n.canonical.x,yn=_n.canonical.y;for(const jn of en){const An=Ct.getTile(xs?jn.wrapped():jn);if(!An)continue;const jr=An.rasterParticleState;if(!jr)continue;const ur=jn.canonical.x+(1<_s.tileID)),st&&(Ce.activeTexture.set(Le.TEXTURE0),D.imageManager.bind(D.context,E.scope));const rs=[];if(D.terrain&&D.terrain.renderingToTexture&&D.emissiveMode==="mrt-fallback"&&rs.push("USE_MRT1"),ye){const _s=D.getOrCreateProgram(Vt,{overrideFog:!1,overrideRtt:!0,defines:rs}),Gt=new Float32Array(o.b9([])),ss=new o.aR(0,0,0,0,0),xs=st?xd(Gt,de,J,D,0,E.scope,dt,ye,{tileID:ss,tileSize:Ke}):xp(Gt,de,J,G.toPremultipliedRenderColor(X?null:E.lut));return void _s.draw(D,Le.TRIANGLES,wt,jt,Bt,fa.disabled,xs,E.id,D.viewportBuffer,D.quadTriangleIndexBuffer,D.viewportSegments)}for(const _s of Ss){const Gt=D.isTileAffectedByFog(_s),ss=D.getOrCreateProgram(Vt,{overrideFog:Gt,defines:rs}),xs=_s.toUnwrapped(),Ks=F?_s.projMatrix:D.transform.calculateProjMatrix(xs);D.prepareDrawTile();const Ts=w?w.getTile(_s):Ct?Ct[_s.key]:new o.b0(_s,Ke,Xe.zoom,D),_n=st?xd(Ks,de,J,D,0,E.scope,dt,ye,{tileID:_s,tileSize:Ke}):xp(Ks,de,J,G.toPremultipliedRenderColor(X?null:E.lut));D.uploadCommonUniforms(Ce,ss,xs);const{tileBoundsBuffer:hn,tileBoundsIndexBuffer:Rn,tileBoundsSegments:Kn}=D.getTileBoundsBuffers(Ts);ss.draw(D,Le.TRIANGLES,wt,jt,Bt,fa.disabled,_n,E.id,hn,Rn,Kn)}},sky:function(D,w,E){const F=D._atmosphere?o.al(D.transform.zoom):1,G=E.paint.get("sky-opacity")*F;if(G===0)return;const X=D.context,J=E.paint.get("sky-type"),de=new Hr(X.gl.LEQUAL,Hr.ReadOnly,[0,1]),ye=D.frameCounter/1e3%1;J==="atmosphere"?D.renderPass==="offscreen"?E.needsSkyboxCapture(D)&&(function(Ce,Le){const Xe=Ce.context,Ke=Xe.gl;let st=Le.skyboxFbo;if(!st){st=Le.skyboxFbo=Xe.createFramebuffer(32,32,1,null),Le.skyboxGeometry=new uu(Xe),Le.skyboxTexture=Xe.gl.createTexture(),Ke.bindTexture(Ke.TEXTURE_CUBE_MAP,Le.skyboxTexture),Ke.texParameteri(Ke.TEXTURE_CUBE_MAP,Ke.TEXTURE_WRAP_S,Ke.CLAMP_TO_EDGE),Ke.texParameteri(Ke.TEXTURE_CUBE_MAP,Ke.TEXTURE_WRAP_T,Ke.CLAMP_TO_EDGE),Ke.texParameteri(Ke.TEXTURE_CUBE_MAP,Ke.TEXTURE_MIN_FILTER,Ke.LINEAR),Ke.texParameteri(Ke.TEXTURE_CUBE_MAP,Ke.TEXTURE_MAG_FILTER,Ke.LINEAR);for(let wt=0;wt<6;++wt)Ke.texImage2D(Ke.TEXTURE_CUBE_MAP_POSITIVE_X+wt,0,Ke.RGBA,32,32,0,Ke.RGBA,Ke.UNSIGNED_BYTE,null)}Xe.bindFramebuffer.set(st.framebuffer),Xe.viewport.set([0,0,32,32]);const dt=Le.getCenter(Ce,!0),it=Ce.getOrCreateProgram("skyboxCapture"),jt=new Float64Array(16);o.b9(jt),o.ef(jt,jt,.5*-Math.PI),$f(Ce,Le,it,jt,dt,0),o.b9(jt),o.ef(jt,jt,.5*Math.PI),$f(Ce,Le,it,jt,dt,1),o.b9(jt),o.cE(jt,jt,.5*-Math.PI),$f(Ce,Le,it,jt,dt,2),o.b9(jt),o.cE(jt,jt,.5*Math.PI),$f(Ce,Le,it,jt,dt,3),o.b9(jt),$f(Ce,Le,it,jt,dt,4),o.b9(jt),o.ef(jt,jt,Math.PI),$f(Ce,Le,it,jt,dt,5),Xe.viewport.set([0,0,Ce.width,Ce.height])}(D,E),E.markSkyboxValid(D)):D.renderPass==="sky"&&function(Ce,Le,Xe,Ke,st){const dt=Ce.context,it=dt.gl,jt=Ce.transform,wt=Ce.getOrCreateProgram("skybox");dt.activeTexture.set(it.TEXTURE0),it.bindTexture(it.TEXTURE_CUBE_MAP,Le.skyboxTexture);const Bt=((Vt,Ct,Ss,rs,_s)=>({u_matrix:Vt,u_sun_direction:Ct,u_cubemap:0,u_opacity:rs,u_temporal_offset:_s}))(jt.skyboxMatrix,Le.getCenter(Ce,!1),0,Ke,st);Ce.uploadCommonUniforms(dt,wt),wt.draw(Ce,it.TRIANGLES,Xe,Da.disabled,Ce.colorModeForRenderPass(),fa.backCW,Bt,"skybox",Le.skyboxGeometry.vertexBuffer,Le.skyboxGeometry.indexBuffer,Le.skyboxGeometry.segment)}(D,E,de,G,ye):J==="gradient"&&D.renderPass==="sky"&&function(Ce,Le,Xe,Ke,st){const dt=Ce.context,it=dt.gl,jt=Ce.transform,wt=Ce.getOrCreateProgram("skyboxGradient");Le.skyboxGeometry||(Le.skyboxGeometry=new uu(dt)),dt.activeTexture.set(it.TEXTURE0);let Bt=Le.colorRampTexture;Bt||(Bt=Le.colorRampTexture=new o.T(dt,Le.colorRamp,it.RGBA8)),Bt.bind(it.LINEAR,it.CLAMP_TO_EDGE);const Vt=((Ct,Ss,rs,_s,Gt)=>({u_matrix:Ct,u_color_ramp:0,u_center_direction:Ss,u_radius:o.ap(rs),u_opacity:_s,u_temporal_offset:Gt}))(jt.skyboxMatrix,Le.getCenter(Ce,!1),Le.paint.get("sky-gradient-radius"),Ke,st);Ce.uploadCommonUniforms(dt,wt),wt.draw(Ce,it.TRIANGLES,Xe,Da.disabled,Ce.colorModeForRenderPass(),fa.backCW,Vt,"skyboxGradient",Le.skyboxGeometry.vertexBuffer,Le.skyboxGeometry.indexBuffer,Le.skyboxGeometry.segment)}(D,E,de,G,ye)},custom:function(D,w,E,F){const G=D.context,X=E.implementation;if(!D.transform.projection.unsupportedLayers||!D.transform.projection.unsupportedLayers.includes("custom")||D.terrain&&(D.terrain.renderingToTexture||D.renderPass==="offscreen")&&E.isDraped(w)){if(D.renderPass==="offscreen"){const J=X.prerender;if(J){if(D.setCustomLayerDefaults(),G.setColorMode(D.colorModeForRenderPass()),D.transform.projection.name==="globe"){const de=D.transform.pointMerc;J.call(X,G.gl,D.transform.customLayerMatrix(),D.transform.getProjection(),D.transform.globeToMercatorMatrix(),o.al(D.transform.zoom),[de.x,de.y],D.transform.pixelsPerMeterRatio)}else J.call(X,G.gl,D.transform.customLayerMatrix());G.setDirty(),D.setBaseState()}}else if(D.renderPass==="translucent"){if(D.terrain&&D.terrain.renderingToTexture){const de=X.renderToTile;if(de){const ye=F[0].canonical,Ce={x:ye.x+F[0].wrap*(X.wrapTileId?0:1<{Ce&&(Ce.useNormalOffset=!0,Le||(Ce.enabled=!0))},Ke=w.getSource();if(D.renderPass==="light-beam"&&Ke.type!=="batched-model")return;if(Ke.type==="vector"||Ke.type==="geojson")return function(Ct,Ss,rs,_s,Gt){const ss=Ct.transform,xs=ss.projection.name==="globe",Ks=ss.getFreeCameraOptions().position;if(!Ct.modelManager)return;const Ts=Ct.modelManager;rs.modelManager=Ts;const _n=Ct.shadowRenderer;if(!rs._unevaluatedLayout._values.hasOwnProperty("model-id"))return;const hn=rs._unevaluatedLayout._values["model-id"],Rn=Object.assign({},rs.layout.get("model-id").parameters),Kn=Ct.style.order.indexOf(rs.fqid),en=rs.paint.get("model-opacity").constantOr(1);for(const Ls of _s){const yn=Ss.getTile(Ls).getBucket(rs);if(!yn||yn.projection.name!==ss.projection.name)continue;const jn=yn.getModelUris();if(jn&&!yn.modelsRequested&&(Ts.addModelsFromBucket(jn,Gt),yn.modelsRequested=!0),xs)Rn.zoom=Ls.overscaledZ;else{const ea=Iy(Ls,ss);Rn.zoom=ea}const An=hn.possiblyEvaluate(Rn);if(lr(Ct,yn,Ls),or.shadowUniformsInitialized=!1,or.useSingleShadowCascade=!!_n&&_n.getMaxCascadeForTile(Ls.toUnwrapped())===0,Ct.renderPass==="shadow"&&_n){if(Ct.currentShadowCascade===1&&yn.isInsideFirstShadowMapFrustum)continue;const ea=ss.calculatePosMatrix(Ls.toUnwrapped(),ss.worldSize);if(or.tileMatrix.set(ea),or.shadowTileMatrix=Float32Array.from(_n.calculateShadowPassMatrixFromMatrix(ea)),or.aabb.min=[0,0,0],or.aabb.max[0]=or.aabb.max[1]=o.an,or.aabb.max[2]=0,R3(yn,or,Ct,rs.scope))continue}const jr=1<0&&Ct.style.isLayerClipped(rs,Ss.getSource())&&yn.updateReplacement(Ls,Ct.replacementSource,Kn,rs.scope)&&(yn.uploaded=!1,yn.upload(Ct.context));let hr=0;const Vn=new Array,ca=new Array,Na=new Array;for(let ea in yn.instancesPerModel){const ia=yn.instancesPerModel[ea];ia.features.length>0&&!xs&&(ea=An.evaluate(ia.features[0].feature,{}));const ii=Ts.getModel(ea,Gt);if(ii||Ts.hasURLBeenRequested(ea)||yn.modelUris.includes(ea)||(yn.modelUris.push(ea),yn.modelsRequested=!1),ii&&ii.uploaded)if(xs){const Ni=o.bJ([],[Ks.x,Ks.y,Ks.z],Ct.transform.worldSize);o.eo(Ni,Ni);for(let yi=0;yi0&&eo.elevationUpdate(ea.terrain,yi,Ha,ii.source),eo.needsReEvaluation(ea,Ji,ii)&&eo.evaluate(ii))}})(Ct,Ss,rs,_s),function(){const ea=new Map;let ia,ii,Ni;Vn?(ia=_s.length-1,ii=-1,Ni=-1):(ia=0,ii=_s.length,Ni=1);const yi=new Float64Array(16),Ji=o.ce(),Ha=new o.P(0,0);for(let eo=ia;eo!==ii;eo+=Ni){const vi=_s[eo],Wo=Ss.getTile(vi).getBucket(rs);if(!Wo||!Wo.uploaded)continue;let oc=!1;Ks&&(oc=Ks.getMaxCascadeForTile(vi.toUnwrapped())===0);const Ed=ss.calculatePosMatrix(vi.toUnwrapped(),ss.worldSize),Tc=Wo.modelTraits;!jr&&Vn&&(o.b7(yi,Ed),o.ah(Ji,_n,yi),Ha.x=Ji[0],Ha.y=Ji[1]);const hl=[];Wo.setFilter(rs.filter);for(const qi of Wo.getNodesInfo()){if(qi.hiddenByReplacement||!qi.node.meshes)continue;const $i=qi.node;let Mc=0;Ct.terrain&&$i.elevation&&(Mc=$i.elevation*Ct.terrain.exaggeration());const $d=(()=>{const ef=qi.aabb;return An.min=[...ef.min],An.max=[...ef.max],An.min[2]+=Mc,An.max[2]+=Mc,o.ah(An.min,An.min,Ed),o.ah(An.max,An.max,Ed),An})(),ml=qi.evaluatedScale;if(ml[0]<=1&&ml[1]<=1&&ml[2]<=1&&$d.intersects(ur)===0)continue;if(!jr&&Vn){const ef=.16666666666666666;qi.cameraCollisionOpacity=_n[0]>$d.min[0]&&_n[0]<$d.max[0]&&_n[1]>$d.min[1]&&_n[1]<$d.max[1]&&_n[2]*Kn<$d.max[2]&&$i.footprint&&o.bC(Ha,$i.footprint)?Math.max(qi.cameraCollisionOpacity-ef,0):Math.min(1,qi.cameraCollisionOpacity+ef)}const Ti=[...Ed],yd=1/o.cS(vi.canonical),lc=$i.anchor?$i.anchor[0]:0,gh=$i.anchor?$i.anchor[1]:0;o.bx(Ti,Ti,[lc*(ml[0]-1)+qi.evaluatedTranslation[0]*yd,gh*(ml[1]-1)+qi.evaluatedTranslation[1]*yd,Mc+qi.evaluatedTranslation[2]]),o.c4(ml,o.ew)||o.cC(Ti,Ti,ml);const po=o.aD([],Ti,$i.globalMatrix),jc=o.aD([],ss.expandedFarZProjMatrix,po),am=o.aD([],ss.expandedFarZProjMatrix,Ti),jg=o.aE([],[lc,gh,Mc,1],jc)[2];$i.hidden=!1;let _m=Ls;jr||(Vn&&(_m*=qi.cameraCollisionOpacity,_m*=D3(Ti,ss,qi.aabb,hr)),_m*=WS(ca,jg)),_m!==0?hl.push({nodeInfo:qi,depth:jg,opacity:_m,wvpForNode:jc,wvpForTile:am,nodeModelMatrix:po,tileModelMatrix:Ti}):$i.hidden=!0}jr||hl.sort((qi,$i)=>!Vn||qi.opacity===1&&$i.opacity===1?qi.depth<$i.depth?-1:1:qi.opacity===1?-1:$i.opacity===1?1:qi.depth>$i.depth?-1:1);for(const qi of hl){const $i=qi.nodeInfo,Mc=$i.node;if(Ct._debugParams.show3DModelFootprints&&Mc.footprint){const po=Mc.id||Mc.name||"footprint";ea.has(po)||ea.set(po,{node:Mc,mvp:qi.wvpForTile})}let $d=o.aD([],en,qi.tileModelMatrix);o.aD($d,Rn,$d);const ml=o.b7([],$d);o.e6(ml,ml),o.cC(ml,ml,Us),$d=o.aD($d,$d,Mc.globalMatrix);const Ti=Ct.renderPass==="light-beam",yd=rs.paint.get("model-color-use-theme").constantOr("default")==="none",lc=Tc&o.ez.HasMapboxMeshFeatures,gh=lc?0:$i.evaluatedRMEA[0][2];for(let po=0;po=ha||Lv>=ha}}const Rl=jc.material;let E1;Rl.occlusionTexture&&Rl.occlusionTexture.offsetScale&&(E1=Rl.occlusionTexture.offsetScale,_m.defines.push("OCCLUSION_TEXTURE_TRANSFORM"));const T1=Ct.getOrCreateProgram("model",_m);!jr&&Ks&&Ks.setupShadowsFromMatrix(qi.tileModelMatrix,T1,Ks.useNormalOffset),Ct.uploadCommonUniforms(Gt,T1,null,Pv);const Fc=Rl.pbrMetallicRoughness;Fc.metallicFactor=.9,Fc.roughnessFactor=.5;const Kc=wc(new Float32Array(jg),new Float32Array($d),new Float32Array(ml),new Float32Array(Mc.globalMatrix),Ct,qi.opacity,Fc.baseColorFactor,Rl.emissiveFactor,Fc.metallicFactor,Fc.roughnessFactor,Rl,gh,rs,[0,0,0],E1);!am&&($i.hasTranslucentParts||qi.opacity<1)&&T1.draw(Ct,Gt.gl.TRIANGLES,yn,Da.disabled,Ia.disabled,fa.backCCW,Kc,rs.id,jc.vertexBuffer,jc.indexBuffer,jc.segments,rs.paint,Ct.transform.zoom,void 0,ef),T1.draw(Ct,Gt.gl.TRIANGLES,am?jn:yn,Da.disabled,am||qi.opacity<1||$i.hasTranslucentParts?Ia.alphaBlended:Ia.unblended,fa.backCCW,Kc,rs.id,jc.vertexBuffer,jc.indexBuffer,jc.segments,rs.paint,Ct.transform.zoom,void 0,ef)}}}if(Ct._debugParams.show3DModelFootprints&&ea.size>0){const eo=Array.from(ea.keys()).sort();for(const vi of eo){const{node:Wo,mvp:oc}=ea.get(vi);IE(Ct,0,Wo,oc)}}}()}(D,w,E,F),void Xe();if(Ke.type!=="model")return;const st=Ke.getModels(),dt=[],it=D.transform.getFreeCameraOptions().position,jt=o.bJ([],[it.x,it.y,it.z],D.transform.worldSize);o.eo(jt,jt);const wt=[],Bt=[];let Vt=0;for(const Ct of st){const Ss=w.getFeatureState("",Ct.id),rs={type:"Unknown",id:Ct.id,properties:Ct.featureProperties},_s=E.paint.get("model-rotation").evaluate(rs,Ss),Gt=E.paint.get("model-scale").evaluate(rs,Ss),ss=E.paint.get("model-translation").evaluate(rs,Ss),xs=E.paint.get("model-opacity").evaluate(rs,Ss);RE(E,Ct.id,Ss,Ct.featureProperties,Ct.nodeOverrideNames,Ct.nodeOverrides),qN(E,Ct.id,Ss,Ct.featureProperties,Ct.materialOverrideNames,Ct.materialOverrides),Ct.nodeOverrides.size>0&&Ct.computeBoundsAndApplyParent(),Ct.computeModelMatrix(D,_s,Gt,ss,de,J,!1);const Ks=o.b9([]),Ts=o.e2(Ct.position.lat,D.transform.zoom),_n=o.bP([],[1,1,1/Ts]);o.bx(Ks,Ks,jt),dt.push({zScaleMatrix:_n,negCameraPosMatrix:Ks});for(const hn of Ct.nodes)LE(D,hn,Ct.matrix,D.transform.expandedFarZProjMatrix,Vt,wt,Bt,Ct.materialOverrides,xs);Vt++}if(wt.sort((Ct,Ss)=>Ss.depth-Ct.depth),D.renderPass!=="shadow"){if(D._debugParams.show3DModelFootprints){const Ct=D.transform.projMatrix,Ss=new Map,rs=(Gt,ss)=>{if(Gt.footprint){const xs=Gt.id||Gt.name||"footprint";if(!Ss.has(xs)){const Ks=o.aD([],Ct,ss);Ss.set(xs,{node:Gt,mvp:Ks})}}};for(const Gt of Bt)rs(Gt.node,Gt.modelMatrix);for(const Gt of wt)rs(Gt.node,Gt.modelMatrix);const _s=Array.from(Ss.keys()).sort();for(const Gt of _s){const{node:ss,mvp:xs}=Ss.get(Gt);IE(D,0,ss,xs)}}_p(D,E,wt,Bt,dt),Xe()}else{for(const Ct of Bt)GS(Ct.mesh,Ct.nodeModelMatrix,D,E);for(const Ct of wt)GS(Ct.mesh,Ct.nodeModelMatrix,D,E);Xe()}}},Ir={line:function(D,w,E){if(D.hasElevatedBuckets=!1,D.hasNonElevatedBuckets=!1,D._unevaluatedLayout.getValue("line-elevation-reference")!==void 0||D._unevaluatedLayout.getValue("line-z-offset")!==void 0){if(w){const F=w.getVisibleCoordinates();for(const G of F){const X=w.getTile(G).getBucket(D);if(X&&(X.elevationType!=="none"?D.hasElevatedBuckets=!0:D.hasNonElevatedBuckets=!0,D.hasElevatedBuckets&&D.hasNonElevatedBuckets))break}}}else D.hasNonElevatedBuckets=!0},model:function(D,w,E){const F=w.getSource();if(!F.loaded())return;if(F.type==="vector"||F.type==="geojson")return void(E.modelManager&&E.modelManager.upload(E,I3(E,D)));if(F.type==="batched-model"||F.type!=="model")return;const G=F.getModels();for(const X of G)X.upload(E.context)},raster:function(D,w,E){const F=w.getSource();if(!(F instanceof Jo&&F.loaded()))return;const G=D.sourceLayer||F.rasterLayerIds&&F.rasterLayerIds[0];if(!G)return;const X=D.paint.get("raster-array-band")||F.getInitialBand(G);if(X==null)return;const J=w.getIds().map(de=>w.getTileByID(de));for(const de of J)de.updateNeeded(D.id,X)&&F.prepareTile(de,G,D.id,X)},"raster-particle":function(D,w,E){const F=w.getSource();if(!(F instanceof Jo&&F.loaded()))return;const G=D.sourceLayer||F.rasterLayerIds&&F.rasterLayerIds[0];if(!G)return;const X=D.paint.get("raster-particle-array-band")||F.getInitialBand(G);if(X==null)return;const J=w.getIds().map(de=>w.getTileByID(de));for(const de of J)de.updateNeeded(D.id,X)&&F.prepareTile(de,G,D.id,X)}},za={fill:Ob},Zi={fill:function(D,w,E,F){if(!E.layout||E.layout.get("fill-elevation-reference")==="none"||E.paint.get("fill-opacity").constantOr(1)===0)return;const G=D.context.gl,X=new Hr(G.LEQUAL,Hr.ReadOnly,D.depthRangeFor3D),J=new Da({func:G.ALWAYS,mask:255},255,255,G.KEEP,G.KEEP,G.REPLACE),de=D.transform.getFreeCameraOptions().position,ye=D.getOrCreateProgram("elevatedStructuresDepthReconstruct");for(const Ce of F){const Le=w.getTile(Ce),Xe=Le.getBucket(E);if(!Xe)continue;const Ke=Xe.elevatedStructures;if(!Ke||Ke.depthSegments.segments[0].primitiveLength===0)continue;const st=j1(Ce.toUnwrapped(),de),dt=D.translatePosMatrix(Ce.projMatrix,Le,E.paint.get("fill-translate"),E.paint.get("fill-translate-anchor")),it=Ui(dt,st,0,1,0);ye.draw(D,G.TRIANGLES,X,J,Ia.disabled,fa.disabled,it,E.id,Ke.vertexBuffer,Ke.indexBuffer,Ke.depthSegments,E.paint,D.transform.zoom)}}};class Gl{constructor(w,E,F,G,X){this.context=new rm(w,E),this.transform=F,this._tileTextures={},this.frameCopies=[],this.loadTimeStamps=[],this._timeStamp=o.o.now(),this._averageFPS=0,this._fpsHistory=[],this._dt=0,this._debugParams={forceEnablePrecipitation:!1,showTerrainProxyTiles:!1,fpsWindow:30,continousRedraw:!1,show3DModelFootprints:!1,enabledLayers:{}};const J=["fill","line","symbol","circle","heatmap","fill-extrusion","building","raster","raster-particle","hillshade","model","background","sky"];for(const ye of J)this._debugParams.enabledLayers[ye]=!0;for(const ye of J);this.occlusionParams=new _L,this.setup(),this.numSublayers=Vl.maxUnderzooming+Vl.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.deferredRenderGpuTimeQueries=[],this.gpuTimers={},this.frameCounter=0,this._backgroundTiles={},this.conflationActive=!1,this.replacementSource=new o.eG,this.longestCutoffRange=0,this.minCutoffZoom=0,this._fogVisible=!1,this._cachedTileFogOpacities={},this._shadowRenderer=new Xc(this),this._wireframeDebugCache=new bL,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const de=new o.q({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new o.T(this.context,de,w.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=G,this.maxFrontCutoffRawStart=0,this.worldview=X,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(w,E){const F=!!w&&!!w.terrain&&this.transform.projection.supportsTerrain;if(!(F||this._terrain&&this._terrain.enabled))return;this._terrain||(this._terrain=new Cs(this,w));const G=this._terrain;this.transform.elevation=F?G:null,G.update(w,this.transform,E),this.transform.elevation&&!G.enabled&&(this.transform.elevation=null)}_updateFog(w){const E=w.fog;if(!E||this.transform.projection.name==="globe"||E.getOpacity(this.transform.pitch)<1||E.properties.get("horizon-blend")<.03)return void(this.transform.fogCullDistSq=null);const[F,G]=E.getFovAdjustedRange(this.transform._fov);if(F>G)return void(this.transform.fogCullDistSq=null);const X=F+.78*(G-F);this.transform.fogCullDistSq=X*X}get terrain(){return this.transform._terrainEnabled()&&this._terrain&&this._terrain.enabled||this._forceTerrainMode?this._terrain:null}get forceTerrainMode(){return this._forceTerrainMode}set forceTerrainMode(w){w&&!this._terrain&&(this._terrain=new Cs(this,this.style)),this._forceTerrainMode=w}get shadowRenderer(){return this._shadowRenderer&&this._shadowRenderer.enabled?this._shadowRenderer:null}get wireframeDebugCache(){return this._wireframeDebugCache}resize(w,E){if(this.width=w*o.o.devicePixelRatio,this.height=E*o.o.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const F of this.style.order)this.style._mergedLayers[F].resize()}setup(){const w=this.context,E=new o.dB;E.emplaceBack(0,0),E.emplaceBack(o.an,0),E.emplaceBack(0,o.an),E.emplaceBack(o.an,o.an),this.tileExtentBuffer=w.createVertexBuffer(E,o.dx.members),this.tileExtentSegments=o.dy.simpleSegment(0,0,4,2);const F=new o.dB;F.emplaceBack(0,0),F.emplaceBack(o.an,0),F.emplaceBack(0,o.an),F.emplaceBack(o.an,o.an),this.debugBuffer=w.createVertexBuffer(F,o.dx.members),this.debugSegments=o.dy.simpleSegment(0,0,4,5);const G=new o.dB;G.emplaceBack(-1,-1),G.emplaceBack(1,-1),G.emplaceBack(-1,1),G.emplaceBack(1,1),this.viewportBuffer=w.createVertexBuffer(G,o.dx.members),this.viewportSegments=o.dy.simpleSegment(0,0,4,2);const X=new o.eH;X.emplaceBack(0,0,0,0),X.emplaceBack(o.an,0,o.an,0),X.emplaceBack(0,o.an,0,o.an),X.emplaceBack(o.an,o.an,o.an,o.an),this.mercatorBoundsBuffer=w.createVertexBuffer(X,o.eI.members),this.mercatorBoundsSegments=o.dy.simpleSegment(0,0,4,2);const J=new o.dC;J.emplaceBack(0,1,2),J.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=w.createIndexBuffer(J);const de=new o.eJ;for(const Ce of[0,1,3,2,0])de.emplaceBack(Ce);this.debugIndexBuffer=w.createIndexBuffer(de),this.emptyTexture=new o.T(w,new o.q({width:1,height:1},Uint8Array.of(0,0,0,0)),w.gl.RGBA8),this.identityMat=o.bb();const ye=this.context.gl;this.stencilClearMode=new Da({func:ye.ALWAYS,mask:0},0,255,ye.ZERO,ye.ZERO,ye.ZERO),this.loadTimeStamps.push(performance.now())}getMercatorTileBoundsBuffers(){return{tileBoundsBuffer:this.mercatorBoundsBuffer,tileBoundsIndexBuffer:this.quadTriangleIndexBuffer,tileBoundsSegments:this.mercatorBoundsSegments}}getTileBoundsBuffers(w){return w._makeTileBoundsBuffers(this.context,this.transform.projection),w._tileBoundsBuffer?{tileBoundsBuffer:w._tileBoundsBuffer,tileBoundsIndexBuffer:w._tileBoundsIndexBuffer,tileBoundsSegments:w._tileBoundsSegments}:this.getMercatorTileBoundsBuffers()}clearStencil(){const w=this.context.gl;this.nextStencilID=1,this.currentStencilSource=void 0,this._tileClippingMaskIDs={},this.getOrCreateProgram("clippingMask").draw(this,w.TRIANGLES,Hr.disabled,this.stencilClearMode,Ia.disabled,fa.disabled,ht(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs={})}_renderTileClippingMasks(w,E,F){if(!E||this.currentStencilSource===E.id||!w.isTileClipped()||!F||F.length===0)return;if(this._tileClippingMaskIDs&&!this.terrain){let de=!1;for(const ye of F)if(this._tileClippingMaskIDs[ye.key]===void 0){de=!0;break}if(!de)return}this.currentStencilSource=E.id;const G=this.context,X=G.gl;this.nextStencilID+F.length>256&&this.clearStencil(),G.setColorMode(Ia.disabled),G.setDepthMode(Hr.disabled);const J=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const de of F){const ye=E.getTile(de),Ce=this._tileClippingMaskIDs[de.key]=this.nextStencilID++,{tileBoundsBuffer:Le,tileBoundsIndexBuffer:Xe,tileBoundsSegments:Ke}=this.getTileBoundsBuffers(ye);J.draw(this,X.TRIANGLES,Hr.disabled,new Da({func:X.ALWAYS,mask:0},Ce,255,X.KEEP,X.KEEP,X.REPLACE),Ia.disabled,fa.disabled,ht(de.projMatrix),"$clipping",Le,Xe,Ke)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const w=this.nextStencilID++,E=this.context.gl;return new Da({func:E.NOTEQUAL,mask:255},w,255,E.KEEP,E.KEEP,E.REPLACE)}stencilModeForClipping(w){if(this.terrain)return this.terrain.stencilModeForRTTOverlap(w);const E=this.context.gl;return new Da({func:E.EQUAL,mask:255},this._tileClippingMaskIDs[w.key],0,E.KEEP,E.KEEP,E.REPLACE)}stencilConfigForOverlap(w){const E=this.context.gl,F=w.sort((J,de)=>de.overscaledZ-J.overscaledZ),G=F[F.length-1].overscaledZ,X=F[0].overscaledZ-G+1;if(X>1){this.currentStencilSource=void 0,this.nextStencilID+X>256&&this.clearStencil();const J={};for(let de=0;dethis._debugParams.fpsWindow&&this._fpsHistory.splice(0,this._fpsHistory.length-this._debugParams.fpsWindow),this._averageFPS=Math.round(this._fpsHistory.reduce((w,E)=>w+E/this._fpsHistory.length,0))}render(w,E){const F=o.o.now();this._dt=F-this._timeStamp,this._timeStamp=F,this._wireframeDebugCache.update(this.frameCounter),this._debugParams.continousRedraw=w.map.repaint,this.style=w,this.options=E;const G=this.style._mergedLayers,X=!(!this.terrain||!this.terrain.enabled),J=()=>this.style._getOrder(X).filter(en=>{const Ls=G[en];return!(Ls.type in this._debugParams.enabledLayers)||this._debugParams.enabledLayers[Ls.type]});let de=J(),ye=!1,Ce=!1,Le=null,Xe=0,Ke=!1;for(const en of de){const Ls=G[en];Ls.visibility!=="none"&&(Ls.type==="circle"?ye=!0:Ls.type==="building"?(Le=Ls,++Xe):Ls.type==="symbol"&&(Ls.hasOcclusionOpacityProperties?Ce=!0:ye=!0))}this.updateEmissiveMode();let st=de.map(en=>G[en]);const dt=this.style._mergedSourceCaches;this.imageManager=w.imageManager,this.modelManager=w.modelManager,this.symbolFadeChange=w.placement.symbolFadeChange(o.o.now()),this.imageManager.beginFrame();for(const en in dt){const Ls=dt[en];Ls.used&&(Ls.prepare(this.context),Ls.getSource().usedInConflation&&++Xe)}let it=!1;for(const en of st)en.isHidden(this.transform.zoom)||(en.type==="clip"&&(it=!0),this.prepareLayer(en));const jt={},wt={},Bt={},Vt={},Ct={};for(const en in dt){const Ls=dt[en];jt[en]=Ls.getVisibleCoordinates(),wt[en]=jt[en].slice().reverse(),Bt[en]=Ls.getVisibleCoordinates(!0).reverse(),Vt[en]=Ls.getShadowCasterCoordinates(),Ct[en]=Ls.sortCoordinatesByDistance(jt[en])}const Ss=en=>{const Ls=this.style.getLayerSourceCache(en);return Ls&&Ls.used?Ls.getSource():null};if(Xe||it||this._clippingActiveLastFrame){const en=[],Ls=[];let yn=0;for(const jn of st)this.isSourceForClippingOrConflation(jn,Ss(jn))&&(en.push(jn),Ls.push(yn)),yn++;if(en&&(it||en.length>1)||this._clippingActiveLastFrame){it=!1;const jn=[];for(let An=0;An0){const jn=Ss(Ls);jn&&(this.minCutoffZoom=Math.max(jn.minzoom,this.minCutoffZoom)),Ls.minzoom&&(this.minCutoffZoom=Math.max(Ls.minzoom,this.minCutoffZoom))}Ls.is3D(X)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=en),this._lastOcclusionLayer=en)}const rs=this.style&&this.style.fog;rs?(this._fogVisible=rs.getOpacity(this.transform.pitch)!==0,this._fogVisible&&this.transform.projection.name!=="globe"&&(this._fogVisible=rs.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities={},this.terrain&&(this.terrain.updateTileBinding(Bt),this.opaquePassCutoff=0,de=J(),st=de.map(en=>G[en]));const _s=this._shadowRenderer;if(_s){_s.updateShadowParameters(this.transform,this.style.directionalLight);for(const en in dt)for(const Ls of jt[en]){let yn={min:0,max:0};this.terrain&&(yn=this.terrain.getMinMaxForTile(Ls)||yn),_s.addShadowReceiver(Ls.toUnwrapped(),yn.min,yn.max)}}this.transform.projection.name!=="globe"||this.globeSharedBuffers||(this.globeSharedBuffers=new o.eL(this.context)),this.style.fog&&this.transform.projection.supportsFog?(this._atmosphere||(this._atmosphere=new VS(this)),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);const Gt=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.snow),ss=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.rain);if(Gt&&!this._snow&&(this._snow=new Os(this)),!Gt&&this._snow&&(this._snow.destroy(),delete this._snow),ss&&!this._rain&&(this._rain=new lt(this)),!ss&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),Le){this.buildingTileBorderManager||(this.buildingTileBorderManager=new Dx);const en=this.style.getLayerSourceCache(Le);this.buildingTileBorderManager.updateBorders(en,Le)}if(!$e.has(this.context.gl))return;this.renderPass="offscreen";for(const en of st){const Ls=w.getLayerSourceCache(en);if(!en.hasOffscreenPass()||en.isHidden(this.transform.zoom))continue;const yn=Ls?wt[Ls.id]:void 0;(en.type==="custom"||en.type==="raster"||en.type==="raster-particle"||en.isSky()||yn&&yn.length)&&this.renderLayer(this,Ls,en,yn)}this.depthRangeFor3D=[0,1-(st.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,Vt)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const xs=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),Ks=(()=>{if(E.showOverdrawInspector)return o.aq.black;const en=this.style.fog;if(en&&this.transform.projection.supportsFog){const Ls=this.style.getLut(en.scope);if(!xs){const yn=en.properties.get("color-use-theme")==="none",jn=en.properties.get("color").toNonPremultipliedRenderColor(yn?null:Ls).toArray01();return new o.aq(...jn)}if(xs){const yn=en.properties.get("space-color-use-theme")==="none",jn=en.properties.get("space-color").toNonPremultipliedRenderColor(yn?null:Ls).toArray01();return new o.aq(...jn)}}return o.aq.transparent})();if(this.context.clear({color:Ks,depth:1}),this.clearStencil(),this._showOverdrawInspector=E.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&xs&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=de.length-1;this.currentLayer>=0;this.currentLayer--){const en=st[this.currentLayer],Ls=w.getLayerSourceCache(en);if(en.isSky())continue;const yn=Ls?(en.is3D(X)?Ct:wt)[Ls.id]:void 0;this._renderTileClippingMasks(en,Ls,yn),this.renderLayer(this,Ls,en,yn)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&xs&&this._atmosphere.drawAtmosphereGlow(this,this.style.fog),this.renderPass="sky",(!this._atmosphere||o.al(this.transform.zoom)>0)&&(this.transform.projection.name==="globe"||this.transform.isHorizonVisible()))for(this.currentLayer=0;this.currentLayer{for(this.currentLayer=0;this.currentLayer=this._lastOcclusionLayer&&this.layersWithOcclusionOpacity.length>0){const yn=this.currentLayer;this.depthOcclusion=!0;for(const jn of this.layersWithOcclusionOpacity){this.currentLayer=jn;const An=st[this.currentLayer],jr=w.getLayerSourceCache(An),ur=jr?wt[jr.id]:void 0;this.terrain||this._renderTileClippingMasks(An,jr,jr?jt[jr.id]:void 0),this.renderLayer(this,jr,An,ur)}this.depthOcclusion=!1,this.currentLayer=yn,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 en=null;st.forEach(Ls=>{const yn=w.getLayerSourceCache(Ls);yn&&!Ls.isHidden(this.transform.zoom)&&yn.getVisibleCoordinates().length&&(!en||en.getSource().maxzoom0?E.pop():null}terrainRenderModeElevated(){return this.style&&!!this.style.getTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return this.context.extTextureFloatLinear!=null}currentGlobalDefines(w,E,F){const G=F===void 0?this.terrain&&this.terrain.renderingToTexture:F,X=[];return this.style&&this.style.enable3dLights()&&(w==="globeRaster"||w==="terrainRaster"?(X.push("LIGHTING_3D_MODE"),X.push("LIGHTING_3D_ALPHA_EMISSIVENESS")):G||X.push("LIGHTING_3D_MODE")),this.terrainRenderModeElevated()&&(X.push("TERRAIN"),this.linearFloatFilteringSupported()&&X.push("TERRAIN_DEM_FLOAT_FORMAT")),this.transform.projection.name==="globe"&&X.push("GLOBE"),!this._fogVisible||G||E!==void 0&&!E||X.push("FOG"),G&&X.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&X.push("OVERDRAW_INSPECTOR"),X}getOrCreateProgram(w,E){this.cache=this.cache||{};const F=E&&E.defines||[],G=E&&E.config,X=this.currentGlobalDefines(w,E&&E.overrideFog,E&&E.overrideRtt).concat(F),J=Xn.cacheKey(Pj[w],w,X,G);return this.cache[J]||(this.cache[J]=new Xn(this.context,w,Pj[w],G,yp[w],X)),this.cache[J]}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 w=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(w.FUNC_ADD)}initDebugOverlayCanvas(){this.debugOverlayCanvas==null&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new o.T(this.context,this.debugOverlayCanvas,this.context.gl.RGBA8))}destroy(){this._terrain&&this._terrain.destroy(),this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0),this.globeSharedBuffers&&this.globeSharedBuffers.destroy(),this.emptyTexture.destroy(),this.debugOverlayTexture&&this.debugOverlayTexture.destroy(),this._wireframeDebugCache.destroy(),this.depthFBO&&(this.depthFBO.destroy(),this.depthFBO=void 0,this.depthTexture=void 0),this.emptyDepthTexture&&this.emptyDepthTexture.destroy()}prepareDrawTile(){this.terrain&&this.terrain.prepareDrawTile()}uploadCommonLightUniforms(w,E){if(this.style.enable3dLights()){const F=this.style.directionalLight,G=this.style.ambientLight;if(F&&G){const X=((J,de,ye)=>{const Ce=J.properties.get("direction"),Le=J.properties.get("color-use-theme")==="none",Xe=J.properties.get("color").toNonPremultipliedRenderColor(Le?null:ye.getLut(J.scope)).toArray01(),Ke=J.properties.get("intensity"),st=de.properties.get("color-use-theme")==="none",dt=de.properties.get("color").toNonPremultipliedRenderColor(st?null:ye.getLut(de.scope)).toArray01(),it=de.properties.get("intensity"),jt=[Ce.x,Ce.y,Ce.z],wt=o.dD(dt,it),Bt=o.dD(Xe,Ke);return{u_lighting_ambient_color:wt,u_lighting_directional_dir:jt,u_lighting_directional_color:Bt,u_ground_radiance:Ps(jt,Bt,wt)}})(F,G,this.style);E.setLightsUniformValues(w,X)}}}uploadCommonUniforms(w,E,F,G,X){if(this.uploadCommonLightUniforms(w,E),this.terrain&&this.terrain.renderingToTexture)return;const J=this.style.fog;if(J){const de=J.getOpacity(this.transform.pitch),ye=((Ce,Le,Xe,Ke,st,dt,it,jt,wt,Bt,Vt,Ct)=>{const Ss=Ce.transform,rs=Le.properties.get("color-use-theme")==="none",_s=Le.properties.get("color").toNonPremultipliedRenderColor(rs?null:Ce.style.getLut(Le.scope)).toArray01();_s[3]=Ke;const Gt=Ce.frameCounter/1e3%1,[ss,xs]=Le.properties.get("vertical-range");return{u_fog_matrix:Xe?Ss.calculateFogTileMatrix(Xe):Ct||Ce.identityMat,u_fog_range:Le.getFovAdjustedRange(Ss._fov),u_fog_color:_s,u_fog_horizon_blend:Le.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(ss,xs),xs],u_fog_temporal_offset:Gt,u_frustum_tl:st,u_frustum_tr:dt,u_frustum_br:it,u_frustum_bl:jt,u_globe_pos:wt,u_globe_radius:Bt,u_viewport:Vt,u_globe_transition:o.al(Ss.zoom),u_is_globe:+(Ss.projection.name==="globe")}})(this,J,F,de,this.transform.frustumCorners.TL,this.transform.frustumCorners.TR,this.transform.frustumCorners.BR,this.transform.frustumCorners.BL,this.transform.globeCenterInViewSpace,this.transform.globeRadius,[this.transform.width*o.o.devicePixelRatio,this.transform.height*o.o.devicePixelRatio],G);E.setFogUniformValues(w,ye)}X&&E.setCutoffUniformValues(w,X.uniformValues)}setTileLoadedFlag(w){this.tileLoaded=w}saveCanvasCopy(){const w=this.canvasCopy();w&&(this.frameCopies.push(w),this.tileLoaded=!1)}canvasCopy(){const w=this.context.gl,E=w.createTexture();return w.bindTexture(w.TEXTURE_2D,E),w.copyTexImage2D(w.TEXTURE_2D,0,w.RGBA,0,0,w.drawingBufferWidth,w.drawingBufferHeight,0),E}getCanvasCopiesAndTimestamps(){return{canvasCopies:this.frameCopies,timeStamps:this.loadTimeStamps}}averageElevationNeedsEasing(){if(!this.transform._elevation)return!1;const w=this.style&&this.style.fog;return!!w&&w.getOpacity(this.transform.pitch)!==0}getBackgroundTiles(){const w=this._backgroundTiles,E=this._backgroundTiles={},F=this.transform.coveringTiles({tileSize:512});for(const G of F)E[G.key]=w[G.key]||new o.b0(G,512,this.transform.tileZoom,this,void 0,this.worldview);return E}clearBackgroundTiles(){this._backgroundTiles={}}isSourceForClippingOrConflation(w,E){return!(!w.is3D(!(!this.terrain||!this.terrain.enabled))||w.type!=="clip"&&w.type!=="building"&&(w.minzoom&&w.minzoom>this.transform.zoom||(this.style._clipLayerPresent||w.sourceLayer!=="building"&&w.sourceLayer!=="procedural_buildings")&&(!E||E.type!=="batched-model")))}isTileAffectedByFog(w){if(!this.style||!this.style.fog)return!1;if(this.transform.projection.name==="globe")return!0;let E=this._cachedTileFogOpacities[w.key];return E||(this._cachedTileFogOpacities[w.key]=E=this.style.fog.getOpacityForTile(w)),E[0]>=ha||E[1]>=ha}setupDepthForOcclusion(w,E,F){const G=this.context,X=G.gl,J=!!F;var de;F||(F={u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_depth_range_unpack:[0,1],u_occluder_half_size:16,u_occlusion_depth_offset:-1e-4,u_exaggeration:0}),G.activeTexture.set(X.TEXTURE3),w&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(X.NEAREST,X.CLAMP_TO_EDGE),F.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],F.u_depth_range_unpack=[2/((de=this.depthRangeFor3D)[1]-de[0]),-1-2*de[0]/(de[1]-de[0])],F.u_occluder_half_size=.5*this.occlusionParams.occluderSize,F.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(X.NEAREST,X.CLAMP_TO_EDGE),G.activeTexture.set(X.TEXTURE0),J||E.setTerrainUniformValues(G,F)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const w=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=w?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function Ei(D,w){let E=!1,F=null;const G=()=>{F=null,E&&(D(),F=setTimeout(G,w),E=!1)};return()=>(E=!0,F||G(),F)}class fh{constructor(w){this._hashName=w&&encodeURIComponent(w),o.aZ(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=Ei(this._updateHashUnthrottled.bind(this),300)}addTo(w){return this._map=w,window.addEventListener("hashchange",this._onHashChange,!1),w.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 w=this._map;if(!w)return"";const E=Wl(w);if(this._hashName){const F=this._hashName;let G=!1;const X=location.hash.slice(1).split("&").map(J=>{const de=J.split("=")[0];return de===F?(G=!0,`${de}=${E}`):J}).filter(J=>J);return G||X.push(`${F}=${E}`),`#${X.join("&")}`}return`#${E}`}_getCurrentHash(){const w=location.hash.replace("#","");if(this._hashName){let E;return w.split("&").map(F=>F.split("=")).forEach(F=>{F[0]===this._hashName&&(E=F)}),(E&&E[1]||"").split("/")}return w.split("/")}_onHashChange(){const w=this._map;if(!w)return!1;const E=this._getCurrentHash();if(E.length>=3&&!E.some(F=>isNaN(Number(F)))){const F=w.dragRotate.isEnabled()&&w.touchZoomRotate.isEnabled()?+(E[3]||0):w.getBearing();return w.jumpTo({center:[+E[2],+E[1]],zoom:+E[0],bearing:F,pitch:+(E[4]||0)}),!0}return!1}_updateHashUnthrottled(){history.replaceState(history.state,"",location.href.replace(/(#.+)?$/,this.getHashString()))}}function Wl(D,w){const E=D.getCenter(),F=Math.round(100*D.getZoom())/100,G=Math.ceil((F*Math.LN2+Math.log(512/360/.5))/Math.LN10),X=Math.pow(10,G),J=Math.round(E.lng*X)/X,de=Math.round(E.lat*X)/X,ye=D.getBearing(),Ce=D.getPitch();let Le=w?`/${J}/${de}/${F}`:`${F}/${de}/${J}`;return(ye||Ce)&&(Le+="/"+Math.round(10*ye)/10),Ce&&(Le+=`/${Math.round(Ce)}`),Le}const wg={linearity:.3,easing:o.eN(0,0,.3,1)},Ry=Object.assign({deceleration:2500,maxSpeed:1400},wg),Er=Object.assign({deceleration:20,maxSpeed:1400},wg),Cn=Object.assign({deceleration:1e3,maxSpeed:360},wg),$n=Object.assign({deceleration:1e3,maxSpeed:90},wg);class Fi{constructor(w){this._map=w,this.clear()}clear(){this._inertiaBuffer=[]}record(w){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:o.o.now(),settings:w})}_drainInertiaBuffer(){const w=this._inertiaBuffer,E=o.o.now();for(;w.length>0&&E-w[0].time>160;)w.shift()}_onMoveEnd(w){if(this._map._prefersReducedMotion()||(this._drainInertiaBuffer(),this._inertiaBuffer.length<2))return;const E={zoom:0,bearing:0,pitch:0,pan:new o.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:X}of this._inertiaBuffer)E.zoom+=X.zoomDelta||0,E.bearing+=X.bearingDelta||0,E.pitch+=X.pitchDelta||0,X.panDelta&&E.pan._add(X.panDelta),X.around&&(E.around=X.around),X.pinchAround&&(E.pinchAround=X.pinchAround);const F=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,G={};if(E.pan.mag()){const X=cl(E.pan.mag(),F,Object.assign({},Ry,w||{}));G.offset=E.pan.mult(X.amount/E.pan.mag()),G.center=this._map.transform.center,Qi(G,X)}if(E.zoom){const X=cl(E.zoom,F,Er);G.zoom=this._map.transform.zoom+X.amount,Qi(G,X)}if(E.bearing){const X=cl(E.bearing,F,Cn);G.bearing=this._map.transform.bearing+o.aC(X.amount,-179,179),Qi(G,X)}if(E.pitch){const X=cl(E.pitch,F,$n);G.pitch=this._map.transform.pitch+X.amount,Qi(G,X)}if(G.zoom||G.bearing){const X=E.pinchAround===void 0?E.around:E.pinchAround;G.around=X?this._map.unproject(X):this._map.getCenter()}return this.clear(),G.noMoveStart=!0,G}}function Qi(D,w){(!D.duration||D.durationE.unproject(ye)),de=X.reduce((ye,Ce,Le,Xe)=>ye.add(Ce.div(Xe.length)),new o.P(0,0));super(w,{points:X,point:de,lngLats:J,lngLat:E.unproject(de),originalEvent:F}),this._defaultPrevented=!1}}class wp extends o.C{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(w,E){super("wheel",{originalEvent:E}),this._defaultPrevented=!1}}class dd{constructor(w,E){this._map=w,this._clickTolerance=E.clickTolerance}reset(){this._mousedownPos=void 0}wheel(w){return this._firePreventable(new wp(this._map,w))}mousedown(w,E){return this._mousedownPos=E,this._firePreventable(new ho(w.type,this._map,w))}mouseup(w){this._map.fire(new ho(w.type,this._map,w))}preclick(w){const E=new MouseEvent("preclick",w);this._map.fire(new ho(E.type,this._map,E))}click(w,E){this._mousedownPos&&this._mousedownPos.dist(E)>=this._clickTolerance||(this.preclick(w),this._map.fire(new ho(w.type,this._map,w)))}dblclick(w){return this._firePreventable(new ho(w.type,this._map,w))}mouseover(w){this._map.fire(new ho(w.type,this._map,w))}mouseout(w){this._map.fire(new ho(w.type,this._map,w))}touchstart(w){return this._firePreventable(new Bl(w.type,this._map,w))}touchmove(w){this._map.fire(new Bl(w.type,this._map,w))}touchend(w){this._map.fire(new Bl(w.type,this._map,w))}touchcancel(w){this._map.fire(new Bl(w.type,this._map,w))}_firePreventable(w){if(this._map.fire(w),w.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class qb{constructor(w){this._map=w}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(w){this._map.fire(new ho(w.type,this._map,w))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new ho("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(w){this._delayContextMenu?this._contextMenuEvent=w:this._map.fire(new ho(w.type,this._map,w)),this._map.listens("contextmenu")&&w.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class jL{constructor(w,E){this._map=w,this._el=w.getCanvasContainer(),this._container=w.getContainer(),this._clickTolerance=E.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(w,E){this.isEnabled()&&w.shiftKey&&w.button===0&&(S(),this._startPos=this._lastPos=E,this._active=!0)}mousemoveWindow(w,E){if(!this._active)return;const F=E,G=this._startPos,X=this._lastPos;if(!G||!X||X.equals(F)||!this._box&&F.dist(G){this._box&&(this._box.style.transform=`translate(${J}px,${ye}px)`,this._box.style.width=de-J+"px",this._box.style.height=Ce-ye+"px")})}mouseupWindow(w,E){if(!this._active)return;const F=this._startPos,G=E;if(F&&w.button===0){if(this.reset(),L(),F.x!==G.x||F.y!==G.y)return this._map.fire(new o.C("boxzoomend",{originalEvent:w})),{cameraAnimation:X=>X.fitScreenCoordinates(F,G,this._map.getBearing(),{linear:!1})};this._fireEvent("boxzoomcancel",w)}}keydown(w){this._active&&w.keyCode===27&&(this.reset(),this._fireEvent("boxzoomcancel",w))}blur(){this.reset()}reset(){this._active=!1,this._container.classList.remove("mapboxgl-crosshair"),this._box&&(this._box.remove(),this._box=null),A(),delete this._startPos,delete this._lastPos}_fireEvent(w,E){return this._map.fire(new o.C(w,{originalEvent:E}))}}function NL(D,w){const E={};for(let F=0;Fthis.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===0&&(this.startTime=w.timeStamp),F.length===this.numTouches&&(this.centroid=function(G){const X=new o.P(0,0);for(const J of G)X._add(J);return X.div(G.length)}(E),this.touches=NL(F,E)))}touchmove(w,E,F){if(this.aborted||!this.centroid)return;const G=NL(F,E);for(const X in this.touches){const J=G[X];(!J||J.dist(this.touches[X])>30)&&(this.aborted=!0)}}touchend(w,E,F){if((!this.centroid||w.timeStamp-this.startTime>500)&&(this.aborted=!0),F.length===0){const G=!this.aborted&&this.centroid;if(this.reset(),G)return G}}}class Gj{constructor(w){this.singleTap=new $b(w),this.numTaps=w.numTaps,this.reset()}reset(){this.lastTime=1/0,this.lastTap=void 0,this.count=0,this.singleTap.reset()}touchstart(w,E,F){this.singleTap.touchstart(w,E,F)}touchmove(w,E,F){this.singleTap.touchmove(w,E,F)}touchend(w,E,F){const G=this.singleTap.touchend(w,E,F);if(G){const X=w.timeStamp-this.lastTime<500,J=!this.lastTap||this.lastTap.dist(G)<30;if(X&&J||this.reset(),this.count++,this.lastTime=w.timeStamp,this.lastTap=G,this.count===this.numTaps)return this.reset(),G}}}class zE{constructor(){this._zoomIn=new Gj({numTouches:1,numTaps:2}),this._zoomOut=new Gj({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(w,E,F){this._zoomIn.touchstart(w,E,F),this._zoomOut.touchstart(w,E,F)}touchmove(w,E,F){this._zoomIn.touchmove(w,E,F),this._zoomOut.touchmove(w,E,F)}touchend(w,E,F){const G=this._zoomIn.touchend(w,E,F),X=this._zoomOut.touchend(w,E,F);return G?(this._active=!0,w.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:J=>J.easeTo({duration:300,zoom:J.getZoom()+1,around:J.unproject(G)},{originalEvent:w})}):X?(this._active=!0,w.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:J=>J.easeTo({duration:300,zoom:J.getZoom()-1,around:J.unproject(X)},{originalEvent:w})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}const Z9=0,EW=2,TW={[Z9]:1,[EW]:2},VN={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class kL{constructor(w){this.reset(),this._clickTolerance=w.clickTolerance||1}blur(){this.reset()}reset(){this._active=!1,this._moved=!1,this._lastPoint=void 0,this._eventButton=void 0}_correctButton(w,E){return!1}_move(w,E){return{}}mousedown(w,E){if(this._lastPoint)return;const F=R(w);this._correctButton(w,F)&&(this._lastPoint=E,this._eventButton=F)}mousemoveWindow(w,E){const F=this._lastPoint;if(F){if(w.preventDefault(),this._eventButton!=null&&function(G,X){const J=TW[X];return G.buttons===void 0||(G.buttons&J)!==J}(w,this._eventButton))this.reset();else if(this._moved||!(E.dist(F)0&&(this._active=!0);const G=NL(F,E),X=new o.P(0,0),J=new o.P(0,0);let de=0;for(const Ce in G){const Le=G[Ce],Xe=this._touches[Ce];Xe&&(X._add(Le),J._add(Le.sub(Xe)),de++,G[Ce]=Le)}if(this._touches=G,de{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class CL{constructor(){this.reset()}reset(){this._active=!1,this._firstTwoTouches=void 0}_start(w){}_move(w,E,F){return{}}touchstart(w,E,F){this._firstTwoTouches||F.length<2||(this._firstTwoTouches=[F[0].identifier,F[1].identifier],this._start([E[0],E[1]]))}touchmove(w,E,F){const G=this._firstTwoTouches;if(!G)return;w.preventDefault();const[X,J]=G,de=Ru(F,E,X),ye=Ru(F,E,J);if(!de||!ye)return;const Ce=this._aroundCenter?null:de.add(ye).div(2);return this._move([de,ye],Ce,w)}touchend(w,E,F){if(!this._firstTwoTouches)return;const[G,X]=this._firstTwoTouches,J=Ru(F,E,G),de=Ru(F,E,X);J&&de||(this._active&&L(),this.reset())}touchcancel(){this.reset()}enable(w){this._enabled=!0,this._aroundCenter=!!w&&w.around==="center"}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}function Ru(D,w,E){for(let F=0;FMath.abs(D.x)}class LW extends CL{constructor(w){super(),this._map=w}reset(){super.reset(),this._valid=void 0,this._firstMove=void 0,this._lastPoints=void 0}_start(w){this._lastPoints=w,AL(w[0].sub(w[1]))&&(this._valid=!1)}_move(w,E,F){const G=this._lastPoints;if(!G)return;const X=w[0].sub(G[0]),J=w[1].sub(G[1]);return this._map._cooperativeGestures&&!o.eO()&&F.touches.length<3||(this._valid=this.gestureBeginsVertically(X,J,F.timeStamp),!this._valid)?void 0:(this._lastPoints=w,this._active=!0,{pitchDelta:(X.y+J.y)/2*-.5})}gestureBeginsVertically(w,E,F){if(this._valid!==void 0)return this._valid;const G=w.mag()>=2,X=E.mag()>=2;if(!G&&!X)return;if(!G||!X)return this._firstMove==null&&(this._firstMove=F),F-this._firstMove<100&&void 0;const J=w.y>0==E.y>0;return AL(w)&&AL(E)&&J}}const IW={panStep:100,bearingStep:15,pitchStep:10};class F3{constructor(){const w=IW;this._panStep=w.panStep,this._bearingStep=w.bearingStep,this._pitchStep=w.pitchStep,this._rotationDisabled=!1}blur(){this.reset()}reset(){this._active=!1}keydown(w){if(w.altKey||w.ctrlKey||w.metaKey)return;let E=0,F=0,G=0,X=0,J=0;switch(w.keyCode){case 61:case 107:case 171:case 187:E=1;break;case 189:case 109:case 173:E=-1;break;case 37:w.shiftKey?F=-1:(w.preventDefault(),X=-1);break;case 39:w.shiftKey?F=1:(w.preventDefault(),X=1);break;case 38:w.shiftKey?G=1:(w.preventDefault(),J=-1);break;case 40:w.shiftKey?G=-1:(w.preventDefault(),J=1);break;default:return}return this._rotationDisabled&&(F=0,G=0),{cameraAnimation:de=>{const ye=de.getZoom();de.easeTo({duration:300,easeId:"keyboardHandler",easing:RW,zoom:E?Math.round(ye)+E*(w.shiftKey?2:1):ye,bearing:de.getBearing()+F*this._bearingStep,pitch:de.getPitch()+G*this._pitchStep,offset:[-X*this._panStep,-J*this._panStep],center:de.getCenter()},{originalEvent:w})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0}enableRotation(){this._rotationDisabled=!1}}function RW(D){return D*(2-D)}const z3=4.000244140625,DW=1/450;class ez{constructor(w,E){this._map=w,this._el=w.getCanvasContainer(),this._handler=E,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=DW,o.aZ(["_onTimeout","_addScrollZoomBlocker","_showBlockerAlert"],this)}setZoomRate(w){this._defaultZoomRate=w}setWheelZoomRate(w){this._wheelZoomRate=w}isEnabled(){return!!this._enabled}isActive(){return this._active||this._finishTimeout!==void 0}isZooming(){return!!this._zooming}enable(w){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!w&&w.around==="center",this._map._cooperativeGestures&&this._addScrollZoomBlocker())}disable(){this.isEnabled()&&(this._enabled=!1,this._map._cooperativeGestures&&(clearTimeout(this._alertTimer),this._alertContainer.remove()))}wheel(w){if(!this.isEnabled())return;if(this._map._cooperativeGestures){if(!(w.ctrlKey||w.metaKey||this.isZooming()||o.eO()))return void this._showBlockerAlert();this._alertContainer.style.visibility!=="hidden"&&(this._alertContainer.style.visibility="hidden",clearTimeout(this._alertTimer))}let E=w.deltaMode===WheelEvent.DOM_DELTA_LINE?40*w.deltaY:w.deltaY;const F=o.o.now(),G=F-(this._lastWheelEventTime||0);this._lastWheelEventTime=F,E!==0&&E%z3===0?this._type="wheel":E!==0&&Math.abs(E)<4?this._type="trackpad":G>400?(this._type=null,this._lastValue=E,this._timeout=window.setTimeout(this._onTimeout,40,w)):this._type||(this._type=Math.abs(G*E)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,E+=this._lastValue)),w.shiftKey&&E&&(E/=4),this._type&&(this._lastWheelEvent=w,this._delta-=E,this._active||this._start(w)),w.preventDefault()}_onTimeout(w){this._type="wheel",this._delta-=this._lastValue,this._active||this._start(w)}_start(w){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 E=M(this._el,w);this._aroundPoint=this._aroundCenter?this._map.transform.centerPoint:E,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 w=this._map.transform;this._type==="wheel"&&w.projection.wrap&&(w._center.lng>=180||w._center.lng<=-180)&&(this._prevEase=null,this._easing=null,this._lastWheelEvent=null,this._lastWheelEventTime=0);const E=()=>w._terrainEnabled()&&this._aroundCoord?w.computeZoomRelativeTo(this._aroundCoord):w.zoom;if(this._delta!==0){const Ce=this._type==="wheel"&&Math.abs(this._delta)>z3?this._wheelZoomRate:this._defaultZoomRate;let Le=2/(1+Math.exp(-Math.abs(this._delta*Ce)));this._delta<0&&Le!==0&&(Le=1/Le);const Xe=E(),Ke=Math.pow(2,Xe),st=typeof this._targetZoom=="number"?w.zoomScale(this._targetZoom):Ke;this._targetZoom=Math.min(w.maxZoom,Math.max(w.minZoom,w.scaleZoom(st*Le))),this._type==="wheel"&&(this._startZoom=Xe,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const F=typeof this._targetZoom=="number"?this._targetZoom:E(),G=this._startZoom,X=this._easing;let J,de=!1;if(this._type==="wheel"&&G&&X){const Ce=Math.min((o.o.now()-this._lastWheelEventTime)/200,1),Le=X(Ce);J=o.am(G,F,Le),Ce<1?this._frameId||(this._frameId=!0):de=!0}else J=F,de=!0;this._active=!0,de&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let ye=J-E();return ye*this._lastDelta<0&&(ye=0),{noInertia:!0,needsRenderFrame:!de,zoomDelta:ye,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(w){let E=o.eP;if(this._prevEase){const F=this._prevEase,G=(o.o.now()-F.start)/F.duration,X=F.easing(G+.01)-F.easing(G),J=.27/Math.sqrt(X*X+1e-4)*.01,de=Math.sqrt(.0729-J*J);E=o.eN(J,de,.25,1)}return this._prevEase={start:o.o.now(),duration:w,easing:E},E}blur(){this.reset()}reset(){this._active=!1}_addScrollZoomBlocker(){this._map&&!this._alertContainer&&(this._alertContainer=x("div","mapboxgl-scroll-zoom-blocker",this._map._container),this._alertContainer.textContent=/(Mac|iPad)/i.test(navigator.userAgent)?this._map._getUIString("ScrollZoomBlocker.CmdMessage"):this._map._getUIString("ScrollZoomBlocker.CtrlMessage"),this._alertContainer.style.fontSize=`${Math.max(10,Math.min(24,Math.floor(.05*this._el.clientWidth)))}px`)}_showBlockerAlert(){this._alertContainer.style.visibility="visible",this._alertContainer.classList.add("mapboxgl-scroll-zoom-blocker-show"),this._alertContainer.setAttribute("role","alert"),clearTimeout(this._alertTimer),this._alertTimer=window.setTimeout(()=>{this._alertContainer.classList.remove("mapboxgl-scroll-zoom-blocker-show"),this._alertContainer.removeAttribute("role")},200)}}class tz{constructor(w,E){this._clickZoom=w,this._tapZoom=E}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 sz{constructor(){this.reset()}reset(){this._active=!1}blur(){this.reset()}dblclick(w,E){return w.preventDefault(),{cameraAnimation:F=>{F.easeTo({duration:300,zoom:F.getZoom()+(w.shiftKey?-1:1),around:F.unproject(E)},{originalEvent:w})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class yae{constructor(){this._tap=new Gj({numTouches:1,numTaps:1}),this.reset()}reset(){this._active=!1,this._swipePoint=void 0,this._swipeTouch=0,this._tapTime=0,this._tap.reset()}touchstart(w,E,F){this._swipePoint||(this._tapTime&&w.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?F.length>0&&(this._swipePoint=E[0],this._swipeTouch=F[0].identifier):this._tap.touchstart(w,E,F))}touchmove(w,E,F){if(this._tapTime){if(this._swipePoint){if(F[0].identifier!==this._swipeTouch)return;const G=E[0],X=G.y-this._swipePoint.y;return this._swipePoint=G,w.preventDefault(),this._active=!0,{zoomDelta:X/128}}}else this._tap.touchmove(w,E,F)}touchend(w,E,F){this._tapTime?this._swipePoint&&F.length===0&&this.reset():this._tap.touchend(w,E,F)&&(this._tapTime=w.timeStamp)}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class OW{constructor(w,E,F){this._el=w,this._mousePan=E,this._touchPan=F}enable(w){this._inertiaOptions=w||{},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 vae{constructor(w,E,F){this._pitchWithRotate=w.pitchWithRotate,this._mouseRotate=E,this._mousePitch=F}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable()}disable(){this._mouseRotate.disable(),this._mousePitch.disable()}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()}}class bae{constructor(w,E,F,G){this._el=w,this._touchZoom=E,this._touchRotate=F,this._tapDragZoom=G,this._rotationDisabled=!1,this._enabled=!0}enable(w){this._touchZoom.enable(w),this._rotationDisabled||this._touchRotate.enable(w),this._tapDragZoom.enable(),this._el.classList.add("mapboxgl-touch-zoom-rotate")}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("mapboxgl-touch-zoom-rotate")}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable()}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable()}}const EL=D=>D.zoom||D.drag||D.pitch||D.rotate;class _ae extends o.C{}class wae{constructor(){this.constants=[1,1,.01],this.radius=0}setup(w,E){const F=o.ax([],E,w);this.radius=o.ai(F[2]<0?o.eR([],F,this.constants):[F[0],F[1],0])}projectRay(w){o.eR(w,w,this.constants),o.ay(w,w),o.eS(w,w,this.constants);const E=o.bJ([],w,this.radius);if(E[2]>0){const F=o.bJ([],[0,0,1],o.bi(E,[0,0,1])),G=o.bJ([],o.ay([],[E[0],E[1],0]),this.radius),X=o.cT([],E,o.bJ([],o.ax([],o.cT([],G,F),E),2));E[0]=X[0],E[1]=X[1]}return E}}function TL(D){return D.panDelta&&D.panDelta.mag()||D.zoomDelta||D.bearingDelta||D.pitchDelta}class jae{constructor(w,E){this._map=w,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Fi(w),this._bearingSnap=E.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new wae,this._dragOrigin=null,this._eventsInProgress={},this._addDefaultHandlers(E),o.aZ(["handleEvent","handleWindowEvent"],this);const F=this._el;this._listeners=[[F,"touchstart",{passive:!0}],[F,"touchmove",{passive:!1}],[F,"touchend",void 0],[F,"touchcancel",void 0],[F,"mousedown",void 0],[F,"mousemove",void 0],[F,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[F,"mouseover",void 0],[F,"mouseout",void 0],[F,"dblclick",void 0],[F,"click",void 0],[F,"keydown",{capture:!1}],[F,"keyup",void 0],[F,"wheel",{passive:!1}],[F,"contextmenu",void 0],[window,"blur",void 0]];for(const[G,X,J]of this._listeners){const de=G===document?this.handleWindowEvent:this.handleEvent;G.addEventListener(X,de,J)}}destroy(){for(const[w,E,F]of this._listeners){const G=w===document?this.handleWindowEvent:this.handleEvent;w.removeEventListener(E,G,F)}}_addDefaultHandlers(w){const E=this._map,F=E.getCanvasContainer();this._add("mapEvent",new dd(E,w));const G=E.boxZoom=new jL(E,w);this._add("boxZoom",G);const X=new zE,J=new sz;E.doubleClickZoom=new tz(J,X),this._add("tapZoom",X),this._add("clickZoom",J);const de=new yae;this._add("tapDragZoom",de);const ye=E.touchPitch=new LW(E);this._add("touchPitch",ye);const Ce=new X9(w),Le=new SL(w);E.dragRotate=new vae(w,Ce,Le),this._add("mouseRotate",Ce,["mousePitch"]),this._add("mousePitch",Le,["mouseRotate"]);const Xe=new Vb(w),Ke=new MW(E,w);E.dragPan=new OW(F,Xe,Ke),this._add("mousePan",Xe),this._add("touchPan",Ke,["touchZoom","touchRotate"]);const st=new O3,dt=new PW;E.touchZoomRotate=new bae(F,dt,st,de),this._add("touchRotate",st,["touchPan","touchZoom"]),this._add("touchZoom",dt,["touchPan","touchRotate"]),this._add("blockableMapEvent",new qb(E));const it=E.scrollZoom=new ez(E,this);this._add("scrollZoom",it,["mousePan"]);const jt=E.keyboard=new F3;this._add("keyboard",jt);for(const wt of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])w.interactive&&w[wt]&&E[wt].enable(w[wt])}_add(w,E,F){this._handlers.push({handlerName:w,handler:E,allowed:F}),this._handlersById[w]=E}stop(w){if(!this._updatingCamera){for(const{handler:E}of this._handlers)E.reset();this._inertia.clear(),this._fireEvents({},{},w),this._changes=[],this._originalZoom=void 0}}isActive(){for(const{handler:w}of this._handlers)if(w.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return!!EL(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(w,E,F){for(const G in w)if(G!==F&&(!E||E.indexOf(G)<0))return!0;return!1}handleWindowEvent(w){this.handleEvent(w,`${w.type}Window`)}_getMapTouches(w){const E=[];for(const F of w)this._el.contains(F.target)&&E.push(F);return E}handleEvent(w,E){this._updatingCamera=!0;const F=w.type==="renderFrame",G=F?void 0:w,X={needsRenderFrame:!1},J={},de={},ye=w.touches?this._getMapTouches(w.touches):void 0,Ce=ye?I(this._el,ye):F?void 0:M(this._el,w);for(const{handlerName:Ke,handler:st,allowed:dt}of this._handlers){if(!st.isEnabled())continue;let it;this._blockedByActive(de,dt,Ke)?st.reset():st[E||w.type]&&(it=st[E||w.type](w,Ce,ye),this.mergeHandlerResult(X,J,it,Ke,G),it&&it.needsRenderFrame&&this._triggerRenderFrame()),(it||st.isActive())&&(de[Ke]=st)}const Le={};for(const Ke in this._previousActiveHandlers)de[Ke]||(Le[Ke]=G);this._previousActiveHandlers=de,(Object.keys(Le).length||TL(X))&&(this._changes.push([X,J,Le]),this._triggerRenderFrame()),(Object.keys(de).length||TL(X))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:Xe}=X;Xe&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],Xe(this._map))}mergeHandlerResult(w,E,F,G,X){if(!F)return;Object.assign(w,F);const J={handlerName:G,originalEvent:F.originalEvent||X};F.zoomDelta!==void 0&&(E.zoom=J),F.panDelta!==void 0&&(E.drag=J),F.pitchDelta!==void 0&&(E.pitch=J),F.bearingDelta!==void 0&&(E.rotate=J)}_applyChanges(){const w={},E={},F={};for(const[G,X,J]of this._changes)G.panDelta&&(w.panDelta=(w.panDelta||new o.P(0,0))._add(G.panDelta)),G.zoomDelta&&(w.zoomDelta=(w.zoomDelta||0)+G.zoomDelta),G.bearingDelta&&(w.bearingDelta=(w.bearingDelta||0)+G.bearingDelta),G.pitchDelta&&(w.pitchDelta=(w.pitchDelta||0)+G.pitchDelta),G.around!==void 0&&(w.around=G.around),G.aroundCoord!==void 0&&(w.aroundCoord=G.aroundCoord),G.pinchAround!==void 0&&(w.pinchAround=G.pinchAround),G.noInertia&&(w.noInertia=G.noInertia),Object.assign(E,X),Object.assign(F,J);this._updateMapTransform(w,E,F),this._changes=[]}_updateMapTransform(w,E,F){const G=this._map,X=G.transform,J=Bt=>[Bt.x,Bt.y,Bt.z];if((()=>{const Bt=this._eventsInProgress.drag;return Bt&&!this._handlersById[Bt.handlerName].isActive()})()&&!TL(w)){const Bt=X.zoom;X.cameraElevationReference="sea",this._originalZoom!=null&&X._orthographicProjectionAtLowPitch&&X.projection.name!=="globe"&&X.pitch===0?(X.cameraElevationReference="ground",X.zoom=this._originalZoom):(X.recenterOnTerrain(),X.cameraElevationReference="ground"),Bt!==X.zoom&&this._map._update(!0)}if(X._isCameraConstrained&&G._stop(!0),!TL(w))return void this._fireEvents(E,F,!0);let{panDelta:de,zoomDelta:ye,bearingDelta:Ce,pitchDelta:Le,around:Xe,aroundCoord:Ke,pinchAround:st}=w;X._isCameraConstrained&&(ye>0&&(ye=0),X._isCameraConstrained=!1),st!==void 0&&(Xe=st),(ye||(Bt=>E[Bt]&&!this._eventsInProgress[Bt])("drag"))&&Xe&&(this._dragOrigin=J(X.pointCoordinate3D(Xe)),this._originalZoom=X.zoom,this._trackingEllipsoid.setup(X._camera.position,this._dragOrigin)),X.cameraElevationReference="sea",G._stop(!0),Xe=Xe||G.transform.centerPoint,Ce&&(X.bearing+=Ce),Le&&(X.pitch+=Le),X._updateCameraState();const dt=[0,0,0];if(de)if(X.projection.name==="mercator"){const Bt=this._trackingEllipsoid.projectRay(X.screenPointToMercatorRay(Xe).dir),Vt=this._trackingEllipsoid.projectRay(X.screenPointToMercatorRay(Xe.sub(de)).dir);dt[0]=Vt[0]-Bt[0],dt[1]=Vt[1]-Bt[1]}else{const Bt=X.pointCoordinate(Xe);if(X.projection.name==="globe"){de=de.rotate(-X.angle);const Vt=X._pixelsPerMercatorPixel/X.worldSize;dt[0]=-de.x*o.eQ(o.bV(Bt.y))*Vt,dt[1]=-de.y*o.eQ(X.center.lat)*Vt}else{const Vt=X.pointCoordinate(Xe.sub(de));Bt&&Vt&&(dt[0]=Vt.x-Bt.x,dt[1]=Vt.y-Bt.y)}}const it=X.zoom,jt=[0,0,0];if(ye){const Bt=J(Ke||X.pointCoordinate3D(Xe)),Vt={dir:o.ay([],o.ax([],Bt,X._camera.position))};if(Vt.dir[2]<0){const Ct=X.zoomDeltaToMovement(Bt,ye);o.bJ(jt,Vt.dir,Ct)}}const wt=o.cT(dt,dt,jt);X._translateCameraConstrained(wt),ye&&Math.abs(X.zoom-it)>1e-4&&X.recenterOnTerrain(),X.cameraElevationReference="ground",this._map._update(),w.noInertia||this._inertia.record(w),this._fireEvents(E,F,!0)}_fireEvents(w,E,F){const G=EL(this._eventsInProgress),X=EL(w),J={};for(const Le in w){const{originalEvent:Xe}=w[Le];this._eventsInProgress[Le]||(J[`${Le}start`]=Xe),this._eventsInProgress[Le]=w[Le]}!G&&X&&this._fireEvent("movestart",X.originalEvent);for(const Le in J)this._fireEvent(Le,J[Le]);X&&this._fireEvent("move",X.originalEvent);for(const Le in w){const{originalEvent:Xe}=w[Le];this._fireEvent(Le,Xe)}const de={};let ye;for(const Le in this._eventsInProgress){const{handlerName:Xe,originalEvent:Ke}=this._eventsInProgress[Le];this._handlersById[Xe].isActive()||(delete this._eventsInProgress[Le],ye=E[Xe]||Ke,de[`${Le}end`]=ye)}for(const Le in de)this._fireEvent(Le,de[Le]);const Ce=EL(this._eventsInProgress);if(F&&(G||X)&&!Ce){this._updatingCamera=!0;const Le=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),Xe=Ke=>Ke!==0&&-this._bearingSnap{this._frameId=void 0,this.handleEvent(new _ae("renderFrame",{timeStamp:w})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const FW="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class Nae extends o.E{constructor(w,E){super(),this._moving=!1,this._zooming=!1,this.transform=w,this._bearingSnap=E.bearingSnap,this._respectPrefersReducedMotion=E.respectPrefersReducedMotion!==!1,o.aZ(["_renderFrameCallback"],this)}getCenter(){return new o.aU(this.transform.center.lng,this.transform.center.lat)}setCenter(w,E){return this.jumpTo({center:w},E)}panBy(w,E,F){return w=o.P.convert(w).mult(-1),this.panTo(this.transform.center,Object.assign({offset:w},E),F)}panTo(w,E,F){return this.easeTo(Object.assign({center:w},E),F)}getZoom(){return this.transform.zoom}setZoom(w,E){return this.jumpTo({zoom:w},E),this}zoomTo(w,E,F){return this.easeTo(Object.assign({zoom:w},E),F)}zoomIn(w,E){return this.zoomTo(this.getZoom()+1,w,E),this}zoomOut(w,E){return this.zoomTo(this.getZoom()-1,w,E),this}getBearing(){return this.transform.bearing}setBearing(w,E){return this.jumpTo({bearing:w},E),this}getPadding(){return this.transform.padding}setPadding(w,E){return this.jumpTo({padding:w},E),this}rotateTo(w,E,F){return this.easeTo(Object.assign({bearing:w},E),F)}resetNorth(w,E){return this.rotateTo(0,Object.assign({duration:1e3},w),E),this}resetNorthPitch(w,E){return this.easeTo(Object.assign({bearing:0,pitch:0,duration:1e3},w),E),this}snapToNorth(w,E){return Math.abs(this.getBearing())w.aspect?F/(2*Math.tan(.5*w.fovX)*w.aspect):G/(2*Math.tan(.5*w.fovY)*w.aspect)}_cameraForBoundsOnGlobe(w,E,F,G,X,J){const de=w.clone(),ye=this._extendCameraOptions(J);de.bearing=G,de.pitch=X;const Ce=o.aU.convert(E),Le=o.aU.convert(F),Xe=.5*(Ce.lat+Le.lat),Ke=.5*(Ce.lng+Le.lng),st=o.eT(Xe,Ke),dt=o.ay([],st),it=o.ay([],o.bh([],dt,[0,1,0])),jt=o.bh([],it,dt),wt=[it[0],it[1],it[2],0,jt[0],jt[1],jt[2],0,dt[0],dt[1],dt[2],0,0,0,0,1],Bt=[st,o.eT(Ce.lat,Ce.lng),o.eT(Le.lat,Ce.lng),o.eT(Le.lat,Le.lng),o.eT(Ce.lat,Le.lng),o.eT(Xe,Ce.lng),o.eT(Xe,Le.lng),o.eT(Ce.lat,Ke),o.eT(Le.lat,Ke)];let Vt=o.cU.fromPoints(Bt.map(jn=>[o.bi(it,jn),o.bi(jt,jn),o.bi(dt,jn)]));const Ct=o.ah([],Vt.center,wt);o.eU(Ct)===0&&o.eV(Ct,0,0,1),o.ay(Ct,Ct),o.bJ(Ct,Ct,o.aF),de.center=o.eW(Ct);const Ss=de.getWorldToCameraMatrix(),rs=o.b7(new Float64Array(16),Ss);Vt=o.cU.applyTransform(Vt,o.aD([],Ss,wt));const _s=this._extendAABB(Vt,de,ye,G);if(!_s)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Vt=_s,o.ah(Ct,Ct,Ss);const Gt=.5*(Vt.max[2]-Vt.min[2]),ss=this._minimumAABBFrustumDistance(de,Vt),xs=o.bJ([],[0,0,1],Gt),Ks=o.cT(xs,Ct,xs),Ts=ss+(de.pitch===0?0:o.bf(Ct,Ks)),_n=de.globeCenterInViewSpace,hn=o.ax([],Ct,[_n[0],_n[1],_n[2]]);o.ay(hn,hn),o.bJ(hn,hn,Ts);const Rn=o.cT([],Ct,hn);o.ah(Rn,Rn,rs);const Kn=o.eD/o.aF,en=o.ai(Rn),Ls=o.bU(Math.max(en*Kn-o.eD,Number.EPSILON),0),yn=Math.min(de.zoomFromMercatorZAdjusted(Ls),ye.maxZoom);return yn>.5*(o.cJ+o.cv)?(de.setProjection({name:"mercator"}),de.zoom=yn,this._cameraForBounds(de,E,F,G,X,J)):{center:de.center,zoom:yn,bearing:G,pitch:X}}_extendAABB(w,E,F,G){const X=.5*((F.padding.left||0)+(F.padding.right||0)),J=.5*((F.padding.top||0)+(F.padding.bottom||0)),de=J,ye=X,Ce=X,Le=J,Xe=E.width-(ye+Ce),Ke=E.height-(de+Le),st=o.ax([],w.max,w.min),dt=Math.min(Xe/st[0],Ke/st[1]),it=Math.min(E.scaleZoom(E.scale*dt),F.maxZoom);if(isNaN(it))return null;const jt=E.scale/E.zoomScale(it),wt=new o.cU([w.min[0]-ye*jt,w.min[1]-Le*jt,w.min[2]],[w.max[0]+Ce*jt,w.max[1]+de*jt,w.max[2]]),Bt=(typeof F.offset.x=="number"&&typeof F.offset.y=="number"?new o.P(F.offset.x,F.offset.y):o.P.convert(F.offset)).rotate(-o.ap(G));return wt.center[0]-=Bt.x*jt,wt.center[1]+=Bt.y*jt,wt}queryTerrainElevation(w,E){const F=this.transform.elevation;return F?(E=Object.assign({},{exaggerated:!0},E),F.getAtPoint(o.ag.fromLngLat(w),null,E.exaggerated)):null}_cameraForBounds(w,E,F,G,X,J){if(w.projection.name==="globe")return this._cameraForBoundsOnGlobe(w,E,F,G,X,J);const de=w.clone(),ye=this._extendCameraOptions(J);de.bearing=G,de.pitch=X;const Ce=o.aU.convert(E),Le=o.aU.convert(F),Xe=new o.aU(Ce.lng,Le.lat),Ke=new o.aU(Le.lng,Ce.lat),st=de.project(Ce),dt=de.project(Le),it=this.queryTerrainElevation(Ce),jt=this.queryTerrainElevation(Le),wt=this.queryTerrainElevation(Xe),Bt=this.queryTerrainElevation(Ke),Vt=[[st.x,st.y,Math.min(it||0,jt||0,wt||0,Bt||0)],[dt.x,dt.y,Math.max(it||0,jt||0,wt||0,Bt||0)]];let Ct=o.cU.fromPoints(Vt);const Ss=de.getWorldToCameraMatrix(),rs=o.b7(new Float64Array(16),Ss);Ct=o.cU.applyTransform(Ct,Ss);const _s=this._extendAABB(Ct,de,ye,G);if(!_s)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Ct=_s;const Gt=.5*o.ax([],Ct.max,Ct.min)[2],ss=this._minimumAABBFrustumDistance(de,Ct),xs=[0,0,1,0];o.aE(xs,xs,Ss),o.eX(xs,xs);const Ks=o.bJ([],xs,ss+Gt),Ts=o.cT([],Ct.center,Ks);o.ah(Ct.center,Ct.center,rs),o.ah(Ts,Ts,rs);const _n=de.unproject(new o.P(Ct.center[0],Ct.center[1])),hn=o.eY(de.projection,_n),Rn=Math.pow(2,hn),Kn=Math.min(de._zoomFromMercatorZ(Ts[2]*de.pixelsPerMeter*Rn/de.worldSize),ye.maxZoom);return de.mercatorFromTransition&&Kn<.5*(o.cJ+o.cv)?(de.setProjection({name:"globe"}),de.zoom=Kn,this._cameraForBounds(de,E,F,G,X,J)):{center:_n,zoom:Kn,bearing:G,pitch:X}}fitBounds(w,E,F){const G=this.cameraForBounds(w,E);return this._fitInternal(G,E,F)}fitScreenCoordinates(w,E,F,G,X){const J=o.P.convert(w),de=o.P.convert(E),ye=new o.P(Math.min(J.x,de.x),Math.min(J.y,de.y)),Ce=new o.P(Math.max(J.x,de.x),Math.max(J.y,de.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(J,de))return this;const Le=this.transform.pointLocation3D(ye),Xe=this.transform.pointLocation3D(Ce),Ke=this.transform.pointLocation3D(new o.P(ye.x,Ce.y)),st=this.transform.pointLocation3D(new o.P(Ce.x,ye.y)),dt=[Math.min(Le.lng,Xe.lng,Ke.lng,st.lng),Math.min(Le.lat,Xe.lat,Ke.lat,st.lat)],it=[Math.max(Le.lng,Xe.lng,Ke.lng,st.lng),Math.max(Le.lat,Xe.lat,Ke.lat,st.lat)],jt=G&&G.pitch?G.pitch:this.getPitch(),wt=this._cameraForBounds(this.transform,dt,it,F,jt,G);return this._fitInternal(wt,G,X)}_fitInternal(w,E,F){return w?(E=Object.assign(w,E)).linear?this.easeTo(E,F):this.flyTo(E,F):this}jumpTo(w,E){this.stop();const F=w.preloadOnly?this.transform.clone():this.transform;let G=!1,X=!1,J=!1;"zoom"in w&&F.zoom!==+w.zoom&&(G=!0,F.zoom=+w.zoom),w.center!==void 0&&(F.center=o.aU.convert(w.center)),"bearing"in w&&F.bearing!==+w.bearing&&(X=!0,F.bearing=+w.bearing),"pitch"in w&&F.pitch!==+w.pitch&&(J=!0,F.pitch=+w.pitch);const de=typeof w.padding=="number"?this._extendPadding(w.padding):w.padding;if(w.padding!=null&&!F.isPaddingEqual(de))if(w.retainPadding===!1){const ye=F.clone();ye.padding=de,F.setLocationAtPoint(F.center,ye.centerPoint)}else F.padding=de;return w.preloadOnly?(this._preloadTiles(F),this):(this.fire(new o.C("movestart",E)).fire(new o.C("move",E)),G&&this.fire(new o.C("zoomstart",E)).fire(new o.C("zoom",E)).fire(new o.C("zoomend",E)),X&&this.fire(new o.C("rotatestart",E)).fire(new o.C("rotate",E)).fire(new o.C("rotateend",E)),J&&this.fire(new o.C("pitchstart",E)).fire(new o.C("pitch",E)).fire(new o.C("pitchend",E)),this.fire(new o.C("moveend",E)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||o.w(FW),this.transform.getFreeCameraOptions()}setFreeCameraOptions(w,E){const F=this.transform;if(!F.projection.supportsFreeCamera)return o.w(FW),this;this.stop();const G=F.zoom,X=F.pitch,J=F.bearing;F.setFreeCameraOptions(w);const de=G!==F.zoom,ye=X!==F.pitch,Ce=J!==F.bearing;return this.fire(new o.C("movestart",E)).fire(new o.C("move",E)),de&&this.fire(new o.C("zoomstart",E)).fire(new o.C("zoom",E)).fire(new o.C("zoomend",E)),Ce&&this.fire(new o.C("rotatestart",E)).fire(new o.C("rotate",E)).fire(new o.C("rotateend",E)),ye&&this.fire(new o.C("pitchstart",E)).fire(new o.C("pitch",E)).fire(new o.C("pitchend",E)),this.fire(new o.C("moveend",E)),this}easeTo(w,E){this._stop(!1,w.easeId),((w=Object.assign({offset:[0,0],duration:500,easing:o.eP},w)).animate===!1||this._prefersReducedMotion(w))&&(w.duration=0);const F=this.transform,G=this.getZoom(),X=this.getBearing(),J=this.getPitch(),de=this.getPadding(),ye="zoom"in w?+w.zoom:G,Ce="bearing"in w?this._normalizeBearing(w.bearing,X):X,Le="pitch"in w?+w.pitch:J,Xe=this._extendPadding(w.padding),Ke=o.P.convert(w.offset);let st,dt,it;if(F.projection.name==="globe"){const xs=o.ag.fromLngLat(F.center),Ks=Ke.rotate(-F.angle);xs.x+=Ks.x/F.worldSize,xs.y+=Ks.y/F.worldSize;const Ts=xs.toLngLat(),_n=o.aU.convert(w.center||Ts);this._normalizeCenter(_n),st=F.centerPoint.add(Ks),dt=new o.P(xs.x,xs.y).mult(F.worldSize),it=new o.P(o.aH(_n.lng),o.aL(_n.lat)).mult(F.worldSize).sub(dt)}else{st=F.centerPoint.add(Ke);const xs=F.pointLocation(st),Ks=o.aU.convert(w.center||xs);this._normalizeCenter(Ks),dt=F.project(xs),it=F.project(Ks).sub(dt)}const jt=F.zoomScale(ye-G);let wt,Bt;w.around&&(wt=o.aU.convert(w.around),Bt=F.locationPoint(wt));const Vt=this._zooming||ye!==G,Ct=this._rotating||X!==Ce,Ss=this._pitching||Le!==J,rs=!F.isPaddingEqual(Xe),_s=w.retainPadding===!1?F.clone():F,Gt=xs=>Ks=>{if(Vt&&(xs.zoom=o.am(G,ye,Ks)),Ct&&(xs.bearing=o.am(X,Ce,Ks)),Ss&&(xs.pitch=o.am(J,Le,Ks)),rs&&(_s.interpolatePadding(de,Xe,Ks),st=_s.centerPoint.add(Ke)),wt)xs.setLocationAtPoint(wt,Bt);else{const Ts=xs.zoomScale(xs.zoom-G),_n=ye>G?Math.min(2,jt):Math.max(.5,jt),hn=Math.pow(_n,1-Ks),Rn=xs.unproject(dt.add(it.mult(Ks*hn)).mult(Ts));xs.setLocationAtPoint(xs.renderWorldCopies?Rn.wrap():Rn,st)}return w.preloadOnly||this._fireMoveEvents(E),xs};if(w.preloadOnly){const xs=this._emulate(Gt,w.duration,F);return this._preloadTiles(xs),this}const ss={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=Vt,this._rotating=Ct,this._pitching=Ss,this._padding=rs,this._easeId=w.easeId,this._prepareEase(E,w.noMoveStart,ss),this._ease(Gt(F),xs=>{F.cameraElevationReference==="sea"&&F.recenterOnTerrain(),this._afterEase(E,xs)},w),this}_prepareEase(w,E,F={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&this.transform.pitch===0&&this.transform.projection.name!=="globe"&&(this.transform.cameraElevationReference="ground"),E||F.moving||this.fire(new o.C("movestart",w)),this._zooming&&!F.zooming&&this.fire(new o.C("zoomstart",w)),this._rotating&&!F.rotating&&this.fire(new o.C("rotatestart",w)),this._pitching&&!F.pitching&&this.fire(new o.C("pitchstart",w))}_fireMoveEvents(w){this.fire(new o.C("move",w)),this._zooming&&this.fire(new o.C("zoom",w)),this._rotating&&this.fire(new o.C("rotate",w)),this._pitching&&this.fire(new o.C("pitch",w))}_afterEase(w,E){if(this._easeId&&E&&this._easeId===E)return;this._easeId=void 0,this.transform.cameraElevationReference="ground";const F=this._zooming,G=this._rotating,X=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,F&&this.fire(new o.C("zoomend",w)),G&&this.fire(new o.C("rotateend",w)),X&&this.fire(new o.C("pitchend",w)),this.fire(new o.C("moveend",w))}flyTo(w,E){if(this._prefersReducedMotion(w)){const jn=o.aJ(w,["center","zoom","bearing","pitch","around","padding","retainPadding"]);return this.jumpTo(jn,E)}this.stop(),w=Object.assign({offset:[0,0],speed:1.2,curve:1.42,easing:o.eP},w);const F=this.transform,G=this.getZoom(),X=this.getBearing(),J=this.getPitch(),de=this.getPadding(),ye="zoom"in w?o.aC(+w.zoom,F.minZoom,F.maxZoom):G,Ce="bearing"in w?this._normalizeBearing(w.bearing,X):X,Le="pitch"in w?+w.pitch:J,Xe=this._extendPadding(w.padding),Ke=F.zoomScale(ye-G),st=o.P.convert(w.offset);let dt=F.centerPoint.add(st);const it=F.pointLocation(dt),jt=o.aU.convert(w.center||it);this._normalizeCenter(jt);const wt=F.project(it),Bt=F.project(jt).sub(wt);let Vt=w.curve;const Ct=Math.max(F.width,F.height),Ss=Ct/Ke,rs=Bt.mag();if("minZoom"in w){const jn=o.aC(Math.min(w.minZoom,G,ye),F.minZoom,F.maxZoom),An=Ct/F.zoomScale(jn-G);Vt=Math.sqrt(An/rs*2)}const _s=Vt*Vt;function Gt(jn){const An=(Ss*Ss-Ct*Ct+(jn?-1:1)*_s*_s*rs*rs)/(2*(jn?Ss:Ct)*_s*rs);return Math.log(Math.sqrt(An*An+1)-An)}function ss(jn){return(Math.exp(jn)-Math.exp(-jn))/2}function xs(jn){return(Math.exp(jn)+Math.exp(-jn))/2}const Ks=Gt(0);let Ts=function(jn){return xs(Ks)/xs(Ks+Vt*jn)},_n=function(jn){return Ct*((xs(Ks)*(ss(An=Ks+Vt*jn)/xs(An))-ss(Ks))/_s)/rs;var An},hn=(Gt(1)-Ks)/Vt;if(Math.abs(rs)<1e-6||!isFinite(hn)){if(Math.abs(Ct-Ss)<1e-6)return this.easeTo(w,E);const jn=Ssw.maxDuration&&(w.duration=0);const Rn=X!==Ce,Kn=Le!==J,en=!F.isPaddingEqual(Xe),Ls=w.retainPadding===!1?F.clone():F,yn=jn=>An=>{const jr=An*hn,ur=1/Ts(jr);jn.zoom=An===1?ye:G+jn.scaleZoom(ur),Rn&&(jn.bearing=o.am(X,Ce,An)),Kn&&(jn.pitch=o.am(J,Le,An)),en&&(Ls.interpolatePadding(de,Xe,An),dt=Ls.centerPoint.add(st));const hr=An===1?jt:jn.unproject(wt.add(Bt.mult(_n(jr))).mult(ur));return jn.setLocationAtPoint(jn.renderWorldCopies?hr.wrap():hr,dt),jn._updateCameraOnTerrain(),w.preloadOnly||this._fireMoveEvents(E),jn};if(w.preloadOnly){const jn=this._emulate(yn,w.duration,F);return this._preloadTiles(jn),this}return this._zooming=!0,this._rotating=Rn,this._pitching=Kn,this._padding=en,this._prepareEase(E,!1),this._ease(yn(F),()=>this._afterEase(E),w),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(w){}_cancelRenderFrame(w){}_stop(w,E){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const F=this._onEaseEnd;this._onEaseEnd=void 0,F.call(this,E)}if(!w){const F=this.handlers;F&&F.stop(!1)}return this}_ease(w,E,F){F.animate===!1||F.duration===0?(w(1),E()):(this._easeStart=o.o.now(),this._easeOptions=F,this._onEaseFrame=w,this._onEaseEnd=E,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const w=Math.min((o.o.now()-this._easeStart)/this._easeOptions.duration,1),E=this._onEaseFrame;E&&E(this._easeOptions.easing(w)),w<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()}_normalizeBearing(w,E){w=o.bs(w,-180,180);const F=Math.abs(w-E);return Math.abs(w-360-E)180?-360:F<-180?360:0}_prefersReducedMotion(w){return this._respectPrefersReducedMotion&&o.o.prefersReducedMotion&&!(w&&w.essential)}_emulate(w,E,F){const G=Math.ceil(15*E/1e3),X=[],J=w(F.clone());for(let de=0;de<=G;de++){const ye=J(de/G);X.push(ye.clone())}return X}_preloadTiles(w,E){}}class zW{constructor(w={}){this.options=w,o.aZ(["_toggleAttribution","_updateEditLink","_updateData","_updateCompact"],this)}getDefaultPosition(){return"bottom-right"}onAdd(w){const E=this.options&&this.options.compact,F=w._getUIString("AttributionControl.ToggleAttribution");this._map=w,this._container=x("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._compactButton=x("button","mapboxgl-ctrl-attrib-button",this._container),this._compactButton.type="button",this._compactButton.addEventListener("click",this._toggleAttribution),this._compactButton.setAttribute("aria-label",F);const G=x("span","mapboxgl-ctrl-icon",this._compactButton);return G.setAttribute("aria-hidden","true"),G.setAttribute("title",F),this._innerContainer=x("div","mapboxgl-ctrl-attrib-inner",this._container),E&&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),E===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 w=this._editLink;w||(w=this._editLink=this._container.querySelector(".mapbox-improve-map"));const E=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||o.g.ACCESS_TOKEN}];if(w){const F=E.reduce((G,X,J)=>(X.value&&(G+=`${X.key}=${X.value}${JG.length-X.length),w=w.filter((G,X)=>{for(let J=X+1;J=0)return!1;return!0}),this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?w=[...this.options.customAttribution,...w]:w.unshift(this.options.customAttribution));const F=w.map(G=>function(X){const J=new DOMParser().parseFromString(X,"text/html");return Array.from(J.body.querySelectorAll("*")).reverse().forEach(de=>{const ye=de.textContent||"";if(de.tagName!=="A")return void de.replaceWith(...de.childNodes);const Ce=de.getAttribute("href");if(!Ce||!/^(https?:|mailto:)/i.test(Ce))return void de.replaceWith(J.createTextNode(ye));const Le=J.createElement("a");Le.href=Ce,Le.textContent=ye,Le.rel="noopener nofollow";const Xe=de.getAttribute("class");Xe&&(Le.className=Xe),de.replaceWith(Le)}),J.body.innerHTML}(G)).join(" | ");F!==this._attribHTML&&(this._attribHTML=F,w.length?(this._innerContainer.innerHTML=F,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 BW{constructor(){o.aZ(["_updateLogo","_updateCompact"],this)}onAdd(w){this._map=w,this._container=x("div","mapboxgl-ctrl");const E=x("a","mapboxgl-ctrl-logo");return E.target="_blank",E.rel="noopener nofollow",E.href="https://www.mapbox.com/",E.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),E.setAttribute("rel","noopener nofollow"),this._container.appendChild(E),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(w){w&&w.sourceDataType!=="metadata"||(this._container.style.display=this._logoRequired()?"block":"none")}_logoRequired(){if(!this._map.style)return!0;const w=this._map.style._sourceCaches;if(Object.entries(w).length===0)return!0;for(const E in w){const F=w[E].getSource();if(F.hasOwnProperty("mapbox_logo")&&!F.mapbox_logo)return!1}return!0}_updateCompact(){const w=this._container.children;if(w.length){const E=w[0];this._map.getCanvasContainer().offsetWidth<250?E.classList.add("mapboxgl-compact"):E.classList.remove("mapboxgl-compact")}}}class kae{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(w){const E=++this._id;return this._queue.push({callback:w,id:E,cancelled:!1}),E}remove(w){const E=this._currentlyRunning,F=E?this._queue.concat(E):this._queue;for(const G of F)if(G.id===w)return void(G.cancelled=!0)}run(w=0){const E=this._currentlyRunning=this._queue;this._queue=[];for(const F of E)if(!F.cancelled&&(F.callback(w),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}class m8e{constructor(w){this.jumpTo(w)}getValue(w){if(w<=this._startTime)return this._start;if(w>=this._endTime)return this._end;const E=o.dn((w-this._startTime)/(this._endTime-this._startTime));return this._start*(1-E)+this._end*E}isEasing(w){return w>=this._startTime&&w<=this._endTime}jumpTo(w){this._startTime=-1/0,this._endTime=-1/0,this._start=w,this._end=w}easeTo(w,E,F){this._start=this.getValue(E),this._end=w,this._startTime=E,this._endTime=E+F}}const p8e={"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 Ec extends o.C{constructor(w,E,F,G){const{point:X,lngLat:J,originalEvent:de,target:ye}=w;super(w.type,{point:X,lngLat:J,originalEvent:de,target:ye}),this.preventDefault=()=>{w.preventDefault()},this.id=E,this.interaction=F,this.feature=G}}class nz{constructor(w){this.map=w,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(w,E){if(this.typeById.has(w))throw new Error(`Interaction id "${w}" already exists.`);const F=E.filter;let G=E.type;F&&this.filters.set(w,o.dg(F)),G==="mouseover"&&(G="mouseenter"),G==="mouseout"&&(G="mouseleave");const X=this.interactionsByType.get(G)||new Map;G==="mouseenter"||G==="mouseleave"?(this.delegatedInteractions.size===0&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(w,E)):X.size===0&&this.map.on(G,this.handleType),X.size===0&&this.interactionsByType.set(G,X),X.set(w,E),this.typeById.set(w,G)}get(w){const E=this.typeById.get(w);if(!E)return;const F=this.interactionsByType.get(E);return F?F.get(w):void 0}remove(w){const E=this.typeById.get(w);if(!E)return;this.typeById.delete(w),this.filters.delete(w);const F=this.interactionsByType.get(E);F&&(F.delete(w),E==="mouseenter"||E==="mouseleave"?(this.delegatedInteractions.delete(w),this.delegatedInteractions.size===0&&(this.map.off("mousemove",this.handleMove),this.map.off("mouseout",this.handleOut))):F.size===0&&this.map.off(E,this.handleType))}queryTargets(w,E){const F=[];for(const[G,X]of E)X.target&&F.push({targetId:G,target:X.target,filter:this.filters.get(G)});return this.map.style.queryRenderedTargets(w,F,this.map.transform)}handleMove(w){this.prevHoveredFeatures=this.hoveredFeatures,this.hoveredFeatures=new Map;const E=this.queryTargets(w.point,Array.from(this.delegatedInteractions).reverse());E.length&&(w.type="mouseenter",this.handleType(w,E));const F=new Map;for(const[G,{feature:X}]of this.prevHoveredFeatures)this.hoveredFeatures.has(G)||F.set(X.id,X);F.size&&(w.type="mouseleave",this.handleType(w,Array.from(F.values())))}handleOut(w){const E=Array.from(this.hoveredFeatures.values()).map(({feature:F})=>F);E.length&&(w.type="mouseleave",this.handleType(w,E)),this.hoveredFeatures.clear()}handleType(w,E){const F=w.type==="mouseenter";if(F&&!this.interactionsByType.has(w.type))return void o.w("mouseenter interaction required for mouseleave to work.");const G=Array.from(this.interactionsByType.get(w.type)).reverse(),X=!!E;E=E||this.queryTargets(w.point,G);let J=!1;const de=new Set;for(const ye of E){for(const[Ce,Le]of G){if(!Le.target)continue;const Xe=ye.variants?ye.variants[Ce]:null;if(Xe){for(const Ke of Xe){if(Lh(Ke,ye,de,Ce))continue;const st=new o.di(ye,Ke),dt=fg(Ke,ye,Ce);X&&st.id!==void 0&&(st.state=this.map.getFeatureState(st));const it=F?this.prevHoveredFeatures.get(dt):null,jt=new Ec(w,Ce,Le,st),wt=it?it.stop:Le.handler(jt);if(F&&this.hoveredFeatures.set(dt,{feature:ye,stop:wt}),wt!==!1){J=!0;break}}if(J)break}}if(J)break}if(!J)for(const[ye,Ce]of G){const{handler:Le,target:Xe}=Ce;if(!Xe&&Le(new Ec(w,ye,Ce,null))!==!1)break}}}function f8e(D,w){if(Array.isArray(D)&&Array.isArray(w)){const E=new Set(D),F=new Set(w);return E.size===F.size&&D.every(G=>F.has(G))}return o.b6(D,w)}const g8e={center:[0,0],zoom:0,bearing:0,pitch:0,minZoom:-2,maxZoom:22,minPitch:0,maxPitch:85,interactive:!0,scrollZoom:!0,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,touchPitch:!0,cooperativeGestures:!1,performanceMetricsCollection:!0,bearingSnap:7,clickTolerance:3,pitchWithRotate:!0,hash:!1,attributionControl:!0,antialias:!1,failIfMajorPerformanceCaveat:!1,preserveDrawingBuffer:!1,trackResize:!0,renderWorldCopies:!0,refreshExpiredTiles:!0,minTileCacheSize:null,maxTileCacheSize:null,localIdeographFontFamily:"sans-serif",localFontFamily:null,useServerFontComposition:!0,transformRequest:null,accessToken:null,fadeDuration:300,respectPrefersReducedMotion:!0,crossSourceCollisions:!0,collectResourceTiming:!1,testMode:!1,precompilePrograms:!0,scaleFactor:1},x8e={showCompass:!0,showZoom:!0,visualizePitch:!1};class ML{constructor(w,E,F=!1){this._clickTolerance=10,this.element=E,this.mouseRotate=new X9({clickTolerance:w.dragRotate._mouseRotate._clickTolerance}),this.map=w,F&&(this.mousePitch=new SL({clickTolerance:w.dragRotate._mousePitch._clickTolerance})),o.aZ(["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","reset"],this),E.addEventListener("mousedown",this.mousedown),E.addEventListener("touchstart",this.touchstart,{passive:!1}),E.addEventListener("touchmove",this.touchmove),E.addEventListener("touchend",this.touchend),E.addEventListener("touchcancel",this.reset)}down(w,E){this.mouseRotate.mousedown(w,E),this.mousePitch&&this.mousePitch.mousedown(w,E),S()}move(w,E){const F=this.map,G=this.mouseRotate.mousemoveWindow(w,E),X=G&&G.bearingDelta;if(X&&F.setBearing(F.getBearing()+X),this.mousePitch){const J=this.mousePitch.mousemoveWindow(w,E),de=J&&J.pitchDelta;de&&F.setPitch(F.getPitch()+de)}}off(){const w=this.element;w.removeEventListener("mousedown",this.mousedown),w.removeEventListener("touchstart",this.touchstart),w.removeEventListener("touchmove",this.touchmove),w.removeEventListener("touchend",this.touchend),w.removeEventListener("touchcancel",this.reset),this.offTemp()}offTemp(){A(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup)}mousedown(w){this.down(Object.assign({},w,{button:w.button,type:w.type,ctrlKey:!0,preventDefault:()=>w.preventDefault()}),M(this.element,w)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(w){this.move(w,M(this.element,w))}mouseup(w){this.mouseRotate.mouseupWindow(w),this.mousePitch&&this.mousePitch.mouseupWindow(w),this.offTemp()}touchstart(w){w.targetTouches.length!==1?this.reset():(this._startPos=this._lastPos=I(this.element,w.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:()=>w.preventDefault()},this._startPos))}touchmove(w){w.targetTouches.length!==1?this.reset():(this._lastPos=I(this.element,w.targetTouches)[0],this.move({buttons:1,preventDefault:()=>w.preventDefault()},this._lastPos))}touchend(w){w.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)E.width||w.y>E.height;E.locationPoint3D(F).distSqr(w)180;){const F=E.locationPoint3D(D);if(F.x>=0&&F.y>=0&&F.x<=E.width&&F.y<=E.height)break;D.lng>E.center.lng?D.lng-=360:D.lng+=360}return D}const PL={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%)"},A1={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class Hb extends o.E{constructor(w,E){super(),(w instanceof HTMLElement||E)&&(w=Object.assign({element:w},E)),o.aZ(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress","_clearFadeTimer"],this);const{anchor:F="center",color:G="#3FB1CE",scale:X=1,draggable:J=!1,clickTolerance:de=0,rotation:ye=A1.rotation,rotationAlignment:Ce=A1.rotationAlignment,pitchAlignment:Le=A1.pitchAlignment,occludedOpacity:Xe=A1.occludedOpacity,altitude:Ke=A1.altitude}=w||{};this._anchor=F,this._color=G,this._scale=X,this._draggable=J,this._clickTolerance=de,this._rotation=ye,this._rotationAlignment=Ce,this._pitchAlignment=Le,this._occludedOpacity=Xe,this._altitude=Ke,this._state="inactive",this._isDragging=!1,this._updateMoving=()=>this._update(!0),w&&w.element?(this._element=w.element,this._offset=o.P.convert(w&&w.offset||[0,0])):(this._defaultMarker=!0,this._element=this._createDefaultMarker(),this._offset=o.P.convert(w&&w.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",it=>{it.preventDefault()}),this._element.addEventListener("mousedown",it=>{it.preventDefault()});const st=this._element.classList;for(const it in PL)st.remove(`mapboxgl-marker-anchor-${it}`);st.add(`mapboxgl-marker-anchor-${this._anchor}`);const dt=w&&w.className?w.className.trim().split(/\s+/):[];st.add(...dt),this._popup=null}_createDefaultMarker(){const w=x("div"),E=y("svg",{display:"block",height:41*this._scale+"px",width:27*this._scale+"px",viewBox:"0 0 27 41"},w);if(this._altitude===0){const F=y("radialGradient",{id:"shadowGradient"},y("defs",{},E));y("stop",{offset:"10%","stop-opacity":.4},F),y("stop",{offset:"100%","stop-opacity":.05},F),y("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"},E)}return y("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"},E),y("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"},E),y("circle",{fill:"white",cx:13.5,cy:13.5,r:5.5},E),w}addTo(w){return w===this._map||(this.remove(),this._map=w,w.getCanvasContainer().appendChild(this._element),w.on("move",this._updateMoving),w.on("moveend",this._update),w.on("remove",this._clearFadeTimer),w._addMarker(this),this.setDraggable(this._draggable),this._update(),w.on("click",this._onMapClick)),this}remove(){const w=this._map;return w&&(w.off("click",this._onMapClick),w.off("move",this._updateMoving),w.off("moveend",this._update),w.off("mousedown",this._addDragHandler),w.off("touchstart",this._addDragHandler),w.off("mouseup",this._onUp),w.off("touchend",this._onUp),w.off("mousemove",this._onMove),w.off("touchmove",this._onMove),w.off("remove",this._clearFadeTimer),w._removeMarker(this),this._map=void 0),this._clearFadeTimer(),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(w){return this._lngLat=o.aU.convert(w),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(!0),this}setAltitude(w){return w===this._altitude||(this._defaultMarker&&(this._altitude===0&&w!==0||this._altitude!==0&&w===0)&&(this._element=this._createDefaultMarker()),this._altitude=w||A1.altitude,this._update()),this}getAltitude(){return this._altitude}getElement(){return this._element}setPopup(w){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")),w){if(!("offset"in w.options)){const G=Math.sqrt(Math.pow(13.5,2)/2);w.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[G,-1*(38.1-13.5+G)],"bottom-right":[-G,-1*(38.1-13.5+G)],left:[13.5,-1*(38.1-13.5)],right:[-13.5,-1*(38.1-13.5)]}:this._offset}this._popup=w,w._marker=this,w._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(w){const E=w.code,F=w.charCode||w.keyCode;E!=="Space"&&E!=="Enter"&&F!==32&&F!==13||this.togglePopup()}_onMapClick(w){const E=w.originalEvent.target,F=this._element;this._popup&&(E===F||F.contains(E))&&this.togglePopup()}getPopup(){return this._popup}togglePopup(){const w=this._popup;return w?(w.isOpen()?(w.remove(),this._element.setAttribute("aria-expanded","false")):this._map&&(w.addTo(this._map),this._element.setAttribute("aria-expanded","true")),this):this}_behindTerrain(){const w=this._map,E=this._pos;if(!w||!E)return!1;const F=w.unproject(E,this._altitude),G=w.getFreeCameraOptions();if(!G.position)return!1;const X=G.position.toLngLat();return X.distanceTo(F)<.9*X.distanceTo(this._lngLat)}_evaluateOpacity(){const w=this._map;if(!w)return;const E=this._pos;if(!E||E.x<0||E.x>w.transform.width||E.y<0||E.y>w.transform.height)return void this._clearFadeTimer();const F=w.unproject(E,this._altitude);let G;w._showingGlobe()&&o.e$(w.transform,this._lngLat)?G=0:(G=1-w._queryFogOpacity(F),w.transform._terrainEnabled()&&w.getTerrain()&&this._behindTerrain()&&(G*=this._occludedOpacity)),this._element.style.opacity=`${G}`,this._element.style.pointerEvents=G>0?"auto":"none",this._popup&&this._popup._setOpacity(G),this._fadeTimer=null}_clearFadeTimer(){this._fadeTimer&&(clearTimeout(this._fadeTimer),this._fadeTimer=null)}_updateDOM(){const w=this._pos;if(!w||!this._map)return;const E=this._offset.mult(this._scale);this._element.style.transform=` translate(${w.x}px,${w.y}px) ${PL[this._anchor]} ${this._calculateXYTransform()} ${this._calculateZTransform()} translate(${E.x}px,${E.y}px) `}_calculateXYTransform(){const w=this._pos,E=this._map,F=this.getPitchAlignment();if(!E||!w||F!=="map")return"";if(!E._showingGlobe()){const ye=E.getPitch();return ye?`rotateX(${ye}deg)`:""}const G=o.cH(o.f0(E.transform,this._lngLat)),X=w.sub(o.f1(E.transform)),J=Math.abs(X.x)+Math.abs(X.y);if(J===0)return"";const de=G/J;return`rotateX(${-X.y*de}deg) rotateY(${X.x*de}deg)`}_calculateZTransform(){const w=this._pos,E=this._map;if(!E||!w)return"";let F=0;const G=this.getRotationAlignment();if(G==="map")if(E._showingGlobe()){const X=E.project(new o.aU(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),J=E.project(new o.aU(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(X);F=o.cH(Math.atan2(J.y,J.x))-90}else F=-E.getBearing();else if(G==="horizon"){const X=o.aj(4,6,E.getZoom()),J=o.f1(E.transform);J.y+=X*E.transform.height;const de=w.sub(J),ye=o.cH(Math.atan2(de.y,de.x));F=(ye>90?ye-270:ye+90)*(1-X)}return F+=this._rotation,F?`rotateZ(${F}deg)`:""}_update(w){cancelAnimationFrame(this._updateFrameId);const E=this._map;E&&(E.transform.renderWorldCopies&&(this._lngLat=UW(this._lngLat,this._pos,E.transform)),this._pos=E.project(this._lngLat,this._altitude),w===!0?this._updateFrameId=requestAnimationFrame(()=>{this._element&&this._pos&&this._anchor&&(this._pos=this._pos.round(),this._updateDOM())}):this._pos=this._pos.round(),E._requestDomTask(()=>{this._map&&(this._element&&this._pos&&this._anchor&&this._updateDOM(),(E._showingGlobe()||E.getTerrain()||E.getFog())&&!this._fadeTimer&&(this._fadeTimer=window.setTimeout(this._evaluateOpacity.bind(this),60)))}))}getOffset(){return this._offset}setOffset(w){return this._offset=o.P.convert(w),this._update(),this}addClassName(w){return this._element.classList.add(w),this}removeClassName(w){return this._element.classList.remove(w),this}toggleClassName(w){return this._element.classList.toggle(w)}_onMove(w){const E=this._map;if(!E)return;const F=this._pointerdownPos,G=this._positionDelta;if(F&&G){if(!this._isDragging){const X=this._clickTolerance||E._clickTolerance;if(w.point.dist(F)D.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(D.minPitch!=null&&D.maxPitch!=null&&D.minPitch>D.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(D.minPitch!=null&&D.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(D.maxPitch!=null&&D.maxPitch>85)throw new Error("maxPitch must be less than or equal to 85");D.antialias&&o.eZ(window)&&(D.antialias=!1,o.w("Antialiasing is disabled for this WebGL context to avoid browser bug: https://github.com/mapbox/mapbox-gl-js/issues/11609")),super(new Qu(D.minZoom,D.maxZoom,D.minPitch,D.maxPitch,D.renderWorldCopies,null,null),D),this._repaint=!!D.repaint,this._interactive=D.interactive,this._minTileCacheSize=D.minTileCacheSize,this._maxTileCacheSize=D.maxTileCacheSize,this._failIfMajorPerformanceCaveat=D.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=D.preserveDrawingBuffer,this._antialias=D.antialias,this._trackResize=D.trackResize,this._bearingSnap=D.bearingSnap,this._refreshExpiredTiles=D.refreshExpiredTiles,this._fadeDuration=D.fadeDuration,this._isInitialLoad=!0,this._crossSourceCollisions=D.crossSourceCollisions,this._collectResourceTiming=D.collectResourceTiming,this._language=this._parseLanguage(D.language),this._worldview=D.worldview,this._renderTaskQueue=new kae,this._domRenderTaskQueue=new kae,this._controls=[],this._markers=[],this._popups=[],this._mapId=o.r(),this._locale=Object.assign({},p8e,D.locale),this._clickTolerance=D.clickTolerance,this._cooperativeGestures=D.cooperativeGestures,this._performanceMetricsCollection=D.performanceMetricsCollection,this._tessellationStep=D.tessellationStep,this._containerWidth=0,this._containerHeight=0,this._showParseStatus=!0,this._precompilePrograms=D.precompilePrograms,this._averageElevationLastSampledAt=-1/0,this._averageElevationExaggeration=0,this._averageElevation=new m8e(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._scaleFactor=D.scaleFactor,this._requestManager=new V(D.transformRequest,D.accessToken,D.testMode);const E=ue(D.accessToken||o.g.ACCESS_TOKEN);if(E&&"atlas"in E&&typeof E.atlas=="number"&&(this._tokenExpiration=E.atlas),this._silenceAuthErrors=!!D.testMode,this._contextCreateOptions=D.contextCreateOptions?Object.assign({},D.contextCreateOptions):{},typeof D.container=="string"){const F=document.getElementById(D.container);if(!F)throw new Error(`Container '${D.container.toString()}' not found.`);this._container=F}else{if(!(D.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=D.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."),D.maxBounds&&this.setMaxBounds(D.maxBounds),this._spriteFormat="auto",o.aZ(["_onWindowOnline","_onWindowResize","_onVisibilityChange","_onMapScroll","_contextLost","_contextRestored"],this),this._setupContainer(),this._setupPainter(),this.painter===void 0)throw new Error("Failed to initialize WebGL.");if(this.on("move",()=>this._update(!1)),this.on("moveend",()=>this._update(!1)),this.on("zoom",()=>this._update(!0)),this._fullscreenchangeEvent="onfullscreenchange"in document?"fullscreenchange":"webkitfullscreenchange",window.addEventListener("online",this._onWindowOnline,!1),window.addEventListener("resize",this._onWindowResize,!1),window.addEventListener("orientationchange",this._onWindowResize,!1),window.addEventListener(this._fullscreenchangeEvent,this._onWindowResize,!1),window.addEventListener("visibilitychange",this._onVisibilityChange,!1),this.handlers=new jae(this,D),this._localFontFamily=D.localFontFamily,this._localIdeographFontFamily=D.localIdeographFontFamily,this._useServerFontComposition=D.useServerFontComposition,(D.style||!D.testMode)&&this.setStyle(D.style||o.g.DEFAULT_STYLE,{config:D.config,localFontFamily:this._localFontFamily,localIdeographFontFamily:this._localIdeographFontFamily,useServerFontComposition:this._useServerFontComposition}),D.projection&&this.setProjection(D.projection),D.hash&&(this._hash=new fh(typeof D.hash=="string"&&D.hash||void 0).addTo(this)),!this._hash||!this._hash._onHashChange()){w.center==null&&w.zoom==null||(this.transform._unmodified=!1),this.jumpTo({center:D.center,zoom:D.zoom,bearing:D.bearing,pitch:D.pitch});const F=D.bounds;F&&(this.resize(),this.fitBounds(F,Object.assign({},D.fitBoundsOptions,{duration:0})))}this.resize(),D.attributionControl&&this.addControl(new zW({customAttribution:D.customAttribution})),this._logoControl=new BW,this.addControl(this._logoControl,D.logoPosition),this.on("style.load",()=>{this.transform.unmodified&&this.jumpTo(this.style.stylesheet),this._postStyleLoadEvent(),this._postStyleWithAppearanceEvent()}),this.on("data",F=>{this._update(F.dataType==="style"),this.fire(new o.C(`${F.dataType}data`,F))}),this.on("dataloading",F=>{this.fire(new o.C(`${F.dataType}dataloading`,F))}),this._interactions=new nz(this)}_getMapId(){return this._mapId}addControl(D,w){if(w===void 0&&(w=D.getDefaultPosition?D.getDefaultPosition():"top-right"),!D||!D.onAdd)return this.fire(new o.B(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const E=D.onAdd(this);this._controls.push(D);const F=this._controlPositions[w];return w.indexOf("bottom")!==-1?F.insertBefore(E,F.firstChild):F.appendChild(E),this}removeControl(D){if(!D||!D.onRemove)return this.fire(new o.B(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const w=this._controls.indexOf(D);return w>-1&&this._controls.splice(w,1),D.onRemove(this),this}hasControl(D){return this._controls.indexOf(D)>-1}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}resize(D){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 w=!this._moving;return w&&this.fire(new o.C("movestart",D)).fire(new o.C("move",D)),this.fire(new o.C("resize",D)),w&&this.fire(new o.C("moveend",D)),this}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()||null}setMaxBounds(D){return this.transform.setMaxBounds(o.aK.convert(D)),this._update()}setMinZoom(D){if((D=D??-2)>=-2&&D<=this.transform.maxZoom)return this.transform.minZoom=D,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=D,this._update(),this.getZoom()>D?this.setZoom(D):this.fire(new o.C("zoomstart")).fire(new o.C("zoom")).fire(new o.C("zoomend")),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(D){if((D=D??0)<0)throw new Error("minPitch must be greater than or equal to 0");if(D>=0&&D<=this.transform.maxPitch)return this.transform.minPitch=D,this._update(),this.getPitch()85)throw new Error("maxPitch must be less than or equal to 85");if(D>=this.transform.minPitch)return this.transform.maxPitch=D,this._update(),this.getPitch()>D?this.setPitch(D):this.fire(new o.C("pitchstart")).fire(new o.C("pitch")).fire(new o.C("pitchend")),this;throw new Error("maxPitch must be greater than or equal to minPitch")}getMaxPitch(){return this.transform.maxPitch}getScaleFactor(){return this._scaleFactor}setScaleFactor(D){return this._scaleFactor=D,this.painter.scaleFactor=D,this.style&&this.style._setLabelPlacementStale(),this.style._updateFilteredLayers(w=>w.type==="symbol"),this._update(!0),this}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(D){return this.transform.renderWorldCopies=D,this.transform.renderWorldCopies||this._forceMarkerAndPopupUpdate(!0),this._update()}getLanguage(){return this._language}_parseLanguage(D){return D==="auto"?navigator.language:Array.isArray(D)?D.length===0?void 0:D.map(w=>w==="auto"?navigator.language:w):D}setLanguage(D){const w=this._parseLanguage(D);if(!this.style||w===this._language)return this;this._language=w,this.style.reloadSources();for(const E of this._controls)E._setLanguage&&E._setLanguage(this._language);return this}getWorldview(){return this._worldview}setWorldview(D){return this.style&&D!==this._worldview?(this._worldview=D,this._styleDirty=!0,this.style.setWorldview(D),this):this}getProjection(){return this.transform.mercatorFromTransition?{name:"globe",center:[0,0]}:this.transform.getProjection()}_showingGlobe(){return this.transform.projection.name==="globe"}setProjection(D){return this._lazyInitEmptyStyle(),D?typeof D=="string"&&(D={name:D}):D=null,this._useExplicitProjection=!!D,this._prioritizeAndUpdateProjection(D,this.style.projection)}_updateProjectionTransition(){if(this.getProjection().name!=="globe")return;const D=this.transform,w=D.projection.name;let E;w==="globe"&&D.zoom>=o.cv?(D.setMercatorFromTransition(),E=!0):w==="mercator"&&D.zoom=o.cv?this.transform.setMercatorFromTransition():this.transform.setProjection(D),this.style.applyProjectionUpdate();const F=this.transform.getProjection().name==="mercator"&&E!==this.transform.mercatorFromTransition;return(w||F)&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(D,w){return this.transform.locationPoint3D(o.aU.convert(D),w)}unproject(D,w){return this.transform.pointLocation3D(o.P.convert(D),w)}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(D,w,E){const F=G=>{let X=[];if(Array.isArray(w)){const J=w.filter(de=>this.getLayer(de));X=J.length?this.queryRenderedFeatures(G,{layers:J}):[]}else X=this.queryRenderedFeatures(G,{target:w});return X};if(D==="mouseenter"||D==="mouseover"){let G=!1;return{listener:E,targets:w,delegates:{mousemove:J=>{const de=F(J.point);de.length?G||(G=!0,E.call(this,new ho(D,this,J.originalEvent,{features:de}))):G=!1},mouseout:()=>{G=!1}}}}if(D==="mouseleave"||D==="mouseout"){let G=!1;return{listener:E,targets:w,delegates:{mousemove:de=>{F(de.point).length?G=!0:G&&(G=!1,E.call(this,new ho(D,this,de.originalEvent)))},mouseout:de=>{G&&(G=!1,E.call(this,new ho(D,this,de.originalEvent)))}}}}{const G=X=>{const J=F(X.point);J.length&&(X.features=J,E.call(this,X),delete X.features)};return{listener:E,targets:w,delegates:{[D]:G}}}}on(D,w,E){if(typeof w=="function"||E===void 0)return super.on(D,w);if(typeof w=="string"&&(w=[w]),!this._areTargetsValid(w))return this;const F=this._createDelegatedListener(D,w,E);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[D]=this._delegatedListeners[D]||[],this._delegatedListeners[D].push(F);for(const G in F.delegates)this.on(G,F.delegates[G]);return this}once(D,w,E){if(typeof w=="function"||E===void 0)return super.once(D,w);if(typeof w=="string"&&(w=[w]),!this._areTargetsValid(w))return this;const F=this._createDelegatedListener(D,w,E);for(const G in F.delegates)this.once(G,F.delegates[G]);return this}off(D,w,E){if(typeof w=="function"||E===void 0)return super.off(D,w);if(typeof w=="string"&&(w=[w]),!this._areTargetsValid(w))return this;const F=this._delegatedListeners?this._delegatedListeners[D]:void 0;return F&&(G=>{for(let X=0;X{if(E){const G=typeof E=="string"?E:E instanceof Error?E.message:E.error;o.w(`Unable to perform style diff: ${G}. Rebuilding the style from scratch.`),this._updateStyle(D,w)}else F&&this._update(!0)},()=>this._postStyleLoadEvent()),this):(this._localIdeographFontFamily=w.localIdeographFontFamily,this._localFontFamily=w.localFontFamily,this._updateStyle(D,w))}_getUIString(D){const w=this._locale[D];if(w==null)throw new Error(`Missing UI string '${D}'`);return w}_updateStyle(D,w){if(this.style&&(this.style.setEventedParent(null),this.style._remove(),this.style=void 0),D){const E=Object.assign({},w);w&&w.config&&(E.initialConfig=w.config,delete E.config),this.style=new eh(this,E).load(D),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new eh(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(D){return D==null?(this.fire(new o.B(new Error("IDs can't be empty."))),!1):!o.db(D)||(this.fire(new o.B(new Error(`IDs can't contain special symbols: "${D}".`))),!1)}_isTargetValid(D){return"featuresetId"in D?this._isValidId("importId"in D?D.importId:D.featuresetId):"layerId"in D&&this._isValidId(D.layerId)}_areTargetsValid(D){if(Array.isArray(D)){for(const w of D)if(!this._isValidId(w))return!1;return!0}return this._isTargetValid(D)}addSource(D,w){return this._isValidId(D)?(this._lazyInitEmptyStyle(),this.style.addSource(D,w),this._update(!0)):this}isSourceLoaded(D){return!!this._isValidId(D)&&!!this.style&&this.style._isSourceCacheLoaded(D)}areTilesLoaded(){return this.style.areTilesLoaded()}addSourceType(D,w,E){this._lazyInitEmptyStyle(),this.style.addSourceType(D,w,E)}removeSource(D){return this._isValidId(D)?(this.style.removeSource(D),this._updateTerrain(),this._update(!0)):this}getSource(D){return this._isValidId(D)?this.style.getOwnSource(D):null}addImage(D,w,{pixelRatio:E=1,sdf:F=!1,stretchX:G,stretchY:X,content:J}={}){this._lazyInitEmptyStyle();const de=o.I.from(D);if(w instanceof HTMLImageElement||ImageBitmap&&w instanceof ImageBitmap){const{width:ye,height:Ce,data:Le}=o.o.getImageData(w);this.style.addImage(de,{data:new o.q({width:ye,height:Ce},Le),pixelRatio:E,stretchX:G,stretchY:X,content:J,sdf:F,version:0,usvg:!1})}else if(w.width===void 0||w.height===void 0)this.fire(new o.B(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));else{const{width:ye,height:Ce}=w,Le=w;this.style.addImage(de,{data:new o.q({width:ye,height:Ce},new Uint8Array(Le.data)),pixelRatio:E,stretchX:G,stretchY:X,content:J,sdf:F,usvg:!1,version:0,userImage:Le}),Le.onAdd&&Le.onAdd(this,D)}}updateImage(D,w){this._lazyInitEmptyStyle();const E=o.I.from(D),F=this.style.getImage(E);if(!F)return void this.fire(new o.B(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const G=w instanceof HTMLImageElement||ImageBitmap&&w instanceof ImageBitmap?o.o.getImageData(w):w,{width:X,height:J,data:de}=G;if(X===void 0||J===void 0)return void this.fire(new o.B(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(X!==(F.usvg?F.icon.usvg_tree.width:F.data.width)||J!==(F.usvg?F.icon.usvg_tree.height:F.data.height))return void this.fire(new o.B(new Error(`The width and height of the updated image (${X}, ${J}) must be that same as the previous version of the image (${F.data.width}, ${F.data.height})`)));const ye=!(w instanceof HTMLImageElement||ImageBitmap&&w instanceof ImageBitmap);let Ce=!1;F.usvg?(F.data=new o.q({width:X,height:J},new Uint8Array(de)),F.usvg=!1,F.icon=void 0,Ce=!0):F.data.replace(de,ye),this.style.updateImage(E,F,Ce)}hasImage(D){return D?!!this.style&&!!this.style.getImage(o.I.from(D)):(this.fire(new o.B(new Error("Missing required image id"))),!1)}removeImage(D){this.style.removeImage(o.I.from(D))}loadImage(D,w){o.n(this._requestManager.transformRequest(D,o.R.Image),(E,F)=>{w(E,F)})}listImages(){return this.style.listImages().map(D=>D.name)}addModel(D,w){this._lazyInitEmptyStyle(),this.style.addModel(D,w)}hasModel(D){return D?this.style.hasModel(D):(this.fire(new o.B(new Error("Missing required model id"))),!1)}removeModel(D){this.style.removeModel(D)}listModels(){return this.style.listModels()}addLayer(D,w){return this._isValidId(D.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(D,w),this._update(!0)):this}getSlot(D){const w=this.getLayer(D);return w&&w.slot||null}setSlot(D,w){return this.style.setSlot(D,w),this.style.mergeLayers(),this._update(!0)}addImport(D,w){return this.style.addImport(D,w).catch(E=>this.fire(new o.B(new Error("Failed to add import",E)))),this}updateImport(D,w){return typeof w!="string"&&w.id!==D?(this.removeImport(D),this.addImport(w)):(this.style.updateImport(D,w),this._update(!0))}removeImport(D){return this.style.removeImport(D),this}moveImport(D,w){return this.style.moveImport(D,w),this._update(!0)}moveLayer(D,w){return this._isValidId(D)?(this.style.moveLayer(D,w),this._update(!0)):this}removeLayer(D){return this._isValidId(D)?(this.style.removeLayer(D),this._update(!0)):this}getLayer(D){if(!this._isValidId(D))return null;const w=this.style.getOwnLayer(D);return w?w.type==="custom"?w.implementation:w.serialize():void 0}getSlots(){return this.style.getSlots()}setLayerZoomRange(D,w,E){return this._isValidId(D)?(this.style.setLayerZoomRange(D,w,E),this._update(!0)):this}setFilter(D,w,E={}){return this._isValidId(D)?(this.style.setFilter(D,w,E),this._update(!0)):this}getFilter(D){return this._isValidId(D)?this.style.getFilter(D):null}setPaintProperty(D,w,E,F={}){return this._isValidId(D)?(this.style.setPaintProperty(D,w,E,F),this._update(!0)):this}getPaintProperty(D,w){return this._isValidId(D)?this.style.getPaintProperty(D,w):null}setLayoutProperty(D,w,E,F={}){return this._isValidId(D)?(this.style.setLayoutProperty(D,w,E,F),this._update(!0)):this}getLayoutProperty(D,w){return this._isValidId(D)?this.style.getLayoutProperty(D,w):null}setLayerProperty(D,w,E,F={}){return this._isValidId(D)?(w==="appearances"&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(D,w,E,F),this._update(!0)):this}getGlyphsUrl(){return this.style.getGlyphsUrl()}setGlyphsUrl(D){return this.style.setGlyphsUrl(D),this._update(!0)}getSchema(D){return this.style.getSchema(D)}setSchema(D,w){return this.style.setSchema(D,w),this._update(!0)}getConfig(D){return this.style.getConfig(D)}setConfig(D,w){return this.style.setConfig(D,w),this._update(!0)}getConfigProperty(D,w){return this.style.getConfigProperty(D,w)}setConfigProperty(D,w,E){return this.style.setConfigProperty(D,w,E),this._update(!0)}getFeaturesetDescriptors(D){return this.style.getFeaturesetDescriptors(D)}setLights(D){if(this._lazyInitEmptyStyle(),D&&D.length===1&&D[0].type==="flat"){const w=D[0];w.properties?this.style.setFlatLight(w.properties,w.id,{}):this.style.setFlatLight({},"flat")}else this.style.setLights(D),this.painter.terrain&&(this.painter.terrain.invalidateRenderCache=!0);return this._update(!0)}getLights(){const D=this.style.getLights()||[];return D.length===0&&D.push({id:this.style.light.id,type:"flat",properties:this.style.getFlatLight()}),D}setLight(D,w={}){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:D}])}getLight(){return console.log("The `map.getLight` function is deprecated, prefer using `map.getLights` instead."),this.style.getFlatLight()}setTerrain(D){return this._lazyInitEmptyStyle(),!D&&this.transform.projection.requiresDraping?this.style.setTerrainForDraping():this.style.setTerrain(D),this._averageElevationLastSampledAt=-1/0,this._update(!0)}getTerrain(){return this.style?this.style.getTerrain():null}setFog(D){return this._lazyInitEmptyStyle(),this.style.setFog(D),this._update(!0)}getFog(){return this.style?this.style.getFog():null}setSnow(D){return this._lazyInitEmptyStyle(),this.style.setSnow(D),this._update(!0)}getSnow(){return this.style?this.style.getSnow():null}setRain(D){return this._lazyInitEmptyStyle(),this.style.setRain(D),this._update(!0)}getRain(){return this.style?this.style.getRain():null}setColorTheme(D){return this._lazyInitEmptyStyle(),this.style.setColorTheme(D),this._update(!0)}setImportColorTheme(D,w){return this._lazyInitEmptyStyle(),this.style.setImportColorTheme(D,w),this._update(!0)}setCamera(D){return this.style.setCamera(D),this._triggerCameraUpdate(D)}getNearClipOffset(){return this.transform.nearClipOffset}setNearClipOffset(D){const w=this.transform.nearClipOffset!==D;return this.transform.nearClipOffset=D,this._update(w)}_triggerCameraUpdate(D){return this._update(this.transform.setOrthographicProjectionAtLowPitch(D["camera-projection"]==="orthographic"))}getCamera(){return this.style.camera}_queryFogOpacity(D){return this.style&&this.style.fog?this.style.fog.getOpacityAtLatLng(o.aU.convert(D),this.transform):0}setFeatureState(D,w){return D.source&&!this._isValidId(D.source)?this:(this.style.setFeatureState(D,w),this._update())}removeFeatureState(D,w){return D.source&&!this._isValidId(D.source)?this:(this.style.removeFeatureState(D,w),this._update())}getFeatureState(D){return D.source&&!this._isValidId(D.source)?null:this.style.getFeatureState(D)}_selectIndoorFloor(D){this.style.indoorManager.selectFloor(D)}_setIndoorActiveFloorsVisibility(D){this.style.indoorManager.setActiveFloorsVisibility(D)}getIndoorTileOptions(D,w){return this.style.isIndoorEnabled()?this.style.indoorManager.getIndoorTileOptions(D,w):null}_updateContainerDimensions(){if(!this._container)return;const D=this._container.getBoundingClientRect().width||400,w=this._container.getBoundingClientRect().height||300;let E,F,G,X=this._container;for(;X&&(!F||!G);){const J=window.getComputedStyle(X).transform;J&&J!=="none"&&(E=J.match(/matrix.*\((.+)\)/)[1].split(", "),E[0]&&E[0]!=="0"&&E[0]!=="1"&&(F=E[0]),E[3]&&E[3]!=="0"&&E[3]!=="1"&&(G=E[3])),X=X.parentElement}this._containerWidth=F?Math.abs(D/F):D,this._containerHeight=G?Math.abs(w/G):w}_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 D=this._container;D.classList.add("mapboxgl-map"),(this._missingCSSCanary=x("div","mapboxgl-canary",D)).style.visibility="hidden",this._detectMissingCSS();const w=this._canvasContainer=x("div","mapboxgl-canvas-container",D);this._canvas=x("canvas","mapboxgl-canvas",w),this._interactive&&(w.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 E=this._controlContainer=x("div","mapboxgl-control-container",D),F=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach(G=>{F[G]=x("div",`mapboxgl-ctrl-${G}`,E)}),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(D,w){const E=o.o.devicePixelRatio||1;this._canvas.width=E*Math.ceil(D),this._canvas.height=E*Math.ceil(w),this._canvas.style.width=`${D}px`,this._canvas.style.height=`${w}px`}_addMarker(D){this._markers.push(D)}_removeMarker(D){const w=this._markers.indexOf(D);w!==-1&&this._markers.splice(w,1)}_addPopup(D){this._popups.push(D)}_removePopup(D){const w=this._popups.indexOf(D);w!==-1&&this._popups.splice(w,1)}_setupPainter(){const D=Object.assign({},f.supported.webGLContextAttributes,{failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1}),w=this._canvas.getContext("webgl2",D);w?(Ve(w,!0),this.painter=new Gl(w,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview),this.on("data",E=>{if(E.dataType==="source"){const F=this.transform.elevation?this.transform.elevation._source():null;F&&E.sourceCacheId===F.id&&this.style&&this.style._setLabelPlacementStale(),this.painter.setTileLoadedFlag(!0)}}),o.k.testSupport(w)):this.fire(new o.B(new Error("Failed to initialize WebGL")))}_contextLost(D){D.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.fire(new o.C("webglcontextlost",{originalEvent:D}))}_contextRestored(D){this._setupPainter(),this.painter.resize(Math.ceil(this._containerWidth),Math.ceil(this._containerHeight)),this._updateTerrain(),this.style&&(this.style.clearLayers(),this.style.imageManager.destroyAtlasTextures(),this.style.imageManager.imageAtlasCache.destroyTextures(),this.style.reloadModels(),this.style.clearSources()),this._update(),this.fire(new o.C("webglcontextrestored",{originalEvent:D}))}_onMapScroll(D){if(D.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(D){return this.style?(this._styleDirty=this._styleDirty||D,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(D){return this._update(),this._renderTaskQueue.add(D)}_cancelRenderFrame(D){this._renderTaskQueue.remove(D)}_requestDomTask(D){!this.loaded()||this.loaded()&&!this.isMoving()?D():this._domRenderTaskQueue.add(D)}_render(D){let w;this.fire(new o.C("renderstart")),++this._frameId;const E=this.painter.context.extTimerQuery,F=o.o.now(),G=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(w=G.createQuery(),G.beginQuery(E.TIME_ELAPSED_EXT,w)),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(D),this._domRenderTaskQueue.run(D),this._removed)return;this._updateProjectionTransition();const X=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const ye=this.transform.zoom,Ce=this.transform.pitch,Le=o.o.now(),Xe=new o.ae(ye,{now:Le,fadeDuration:X,pitch:Ce,transition:this.style.transition,worldview:this._worldview});this.style.update(Xe)}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let J=!1;if(this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),J=this._updateAverageElevation(F),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):J=this._updateAverageElevation(F),this.style&&(this._placementDirty=this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,X,this._crossSourceCollisions,this.painter.replacementSource)),this.style&&this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showParseStatus:this.showParseStatus,wireframe:{terrain:this.showTerrainWireframe,layers2D:this.showLayers2DWireframe,layers3D:this.showLayers3DWireframe},showOverdrawInspector:this._showOverdrawInspector,showQueryGeometry:!!this._showQueryGeometry,showTileAABBs:this.showTileAABBs,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:X,isInitialLoad:this._isInitialLoad,showPadding:this.showPadding,gpuTiming:!!this.listens("gpu-timing-layer"),gpuTimingDeferredRender:!!this.listens("gpu-timing-deferred-render"),speedIndexTiming:this.speedIndexTiming}),this.fire(new o.C("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,u.mark(d.load),this.fire(new o.C("load"))),this.style&&this.style.hasTransitions()&&(this._styleDirty=!0),this.style&&(this.style.snow||this.style.rain)&&(this._styleDirty=!0),this.style&&this.style.imageManager.hasPatternsInFlight()&&(this._styleDirty=!0),this.style&&!this.style.modelManager.isLoaded()&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles(),w){const ye=o.o.now()-F;G.endQuery(E.TIME_ELAPSED_EXT),setTimeout(()=>{const Ce=G.getQueryParameter(w,G.QUERY_RESULT)/1e6;G.deleteQuery(w),this.fire(new o.C("gpu-timing-frame",{cpuTime:ye,gpuTime:Ce}))},50)}if(this.listens("gpu-timing-layer")){const ye=this.painter.collectGpuTimers();setTimeout(()=>{const Ce=this.painter.queryGpuTimers(ye);this.fire(new o.C("gpu-timing-layer",{layerTimes:Ce}))},50)}if(this.listens("gpu-timing-deferred-render")){const ye=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const Ce=this.painter.queryGpuTimeDeferredRender(ye);this.fire(new o.C("gpu-timing-deferred-render",{gpuTime:Ce}))},50)}const de=this._sourcesDirty||this._styleDirty||this._placementDirty||J;if(de||this._repaint)this.triggerRepaint();else{const ye=this.idle();if(ye&&(J=this._updateAverageElevation(F,!0)),J)this.triggerRepaint();else if(this._triggerFrame(!1),ye&&(this.fire(new o.C("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const Ce=this._calculateSpeedIndex();this.fire(new o.C("speedindexcompleted",{speedIndex:Ce})),this.speedIndexTiming=!1}}!this._loaded||this._fullyLoaded||de||(this._fullyLoaded=!0,u.mark(d.fullLoad),this._performanceMetricsCollection&&Ae(this._requestManager._customAccessToken,{width:this.painter.width,height:this.painter.height,interactionRange:this._interactionRange,visibilityHidden:this._visibilityHidden,terrainEnabled:!!this.painter.style.getTerrain(),fogEnabled:!!this.painter.style.getFog(),projection:this.getProjection().name,zoom:this.transform.zoom,renderer:this.painter.context.renderer,vendor:this.painter.context.vendor}),this._authenticate())}_forceMarkerAndPopupUpdate(D){for(const w of this._markers)D&&!this.getRenderWorldCopies()&&(w._lngLat=w._lngLat.wrap()),w._update();for(const w of this._popups)!D||this.getRenderWorldCopies()||w._trackPointer||(w._lngLat=w._lngLat.wrap()),w._update()}_updateAverageElevation(D,w=!1){const E=G=>(this.transform.averageElevation=G,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return this.transform.averageElevation!==0&&E(0);const F=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(F||(w||D-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(D)){const G=this.transform.averageElevation;let X=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(X)?X=0:this._averageElevationLastSampledAt=D;const J=Math.abs(G-X);if(J>1){if(this._isInitialLoad||F)return this._averageElevation.jumpTo(X),E(X);this._averageElevation.easeTo(X,D,300)}else if(J>1e-4)return this._averageElevation.jumpTo(X),E(X)}return!!this._averageElevation.isEasing(D)&&E(this._averageElevation.getValue(D))}_isTokenExpired(){return this._tokenExpiration!=null&&Date.now()>this._tokenExpiration}_revokeAuth(){const D=this.painter.context.gl;Ve(D,!1),this._logoControl instanceof BW&&this._logoControl._updateLogo(),D&&D.clear(D.DEPTH_BUFFER_BIT|D.COLOR_BUFFER_BIT|D.STENCIL_BUFFER_BIT),this._silenceAuthErrors||this.fire(new o.B(new Error("A valid Mapbox access token is required to use Mapbox GL JS. To create an account or a new access token, visit https://account.mapbox.com/")))}_authenticate(){Ne(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,D=>{D&&(D.message!==H&&D.status!==401||this._revokeAuth())}),this._isTokenExpired()&&this._revokeAuth(),he(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&&ke(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&Me(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){Se(this._requestManager._customAccessToken)}_updateTerrain(){const D=this._isDragging();this.painter.updateTerrain(this.style,D)}_calculateSpeedIndex(){const D=this.painter.canvasCopy(),w=this.painter.getCanvasCopiesAndTimestamps();w.timeStamps.push(performance.now());const E=this.painter.context.gl,F=E.createFramebuffer();function G(X){E.framebufferTexture2D(E.FRAMEBUFFER,E.COLOR_ATTACHMENT0,E.TEXTURE_2D,X,0);const J=new Uint8Array(E.drawingBufferWidth*E.drawingBufferHeight*4);return E.readPixels(0,0,E.drawingBufferWidth,E.drawingBufferHeight,E.RGBA,E.UNSIGNED_BYTE,J),J}return E.bindFramebuffer(E.FRAMEBUFFER,F),this._canvasPixelComparison(G(D),w.canvasCopies.map(G),w.timeStamps)}_canvasPixelComparison(D,w,E){let F=E[1]-E[0];const G=D.length/4;for(let X=0;X{const E=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,E&&this._render(w)}))}_preloadTiles(D){const w=this.style?this.style.getSourceCaches():[];return o.t(w,(E,F)=>E._preloadTiles(D,F),()=>{this.triggerRepaint()}),this}_onWindowOnline(){this._update()}_onWindowResize(D){this._trackResize&&this.resize({originalEvent:D})._update()}_onVisibilityChange(){document.visibilityState==="hidden"&&this._visibilityHidden++}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(D){this._showTileBoundaries!==D&&(this._showTileBoundaries=D,this._update())}get showParseStatus(){return!!this._showParseStatus}set showParseStatus(D){this._showParseStatus!==D&&(this._showParseStatus=D,this._update())}get showTerrainWireframe(){return!!this._showTerrainWireframe}set showTerrainWireframe(D){this._showTerrainWireframe!==D&&(this._showTerrainWireframe=D,this._update())}get showLayers2DWireframe(){return!!this._showLayers2DWireframe}set showLayers2DWireframe(D){this._showLayers2DWireframe!==D&&(this._showLayers2DWireframe=D,this._update())}get showLayers3DWireframe(){return!!this._showLayers3DWireframe}set showLayers3DWireframe(D){this._showLayers3DWireframe!==D&&(this._showLayers3DWireframe=D,this._update())}get speedIndexTiming(){return!!this._speedIndexTiming}set speedIndexTiming(D){this._speedIndexTiming!==D&&(this._speedIndexTiming=D,this._update())}get showPadding(){return!!this._showPadding}set showPadding(D){this._showPadding!==D&&(this._showPadding=D,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(D){this._showCollisionBoxes!==D&&(this._showCollisionBoxes=D,this.style&&D?this.style._generateCollisionBoxes():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(D){this._showOverdrawInspector!==D&&(this._showOverdrawInspector=D,this._update())}get repaint(){return!!this._repaint}set repaint(D){this._repaint!==D&&(this._repaint=D,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(D){this._vertices=D,this._update()}get showTileAABBs(){return!!this._showTileAABBs}set showTileAABBs(D){this._showTileAABBs!==D&&(this._showTileAABBs=D,D&&this._update())}_setCacheLimits(D,w){o.e_(D,w)}get version(){return c}},NavigationControl:class{constructor(D={}){this.options=Object.assign({},x8e,D),this._container=x("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",w=>w.preventDefault()),this.options.showZoom&&(o.aZ(["_setButtonTitle","_updateZoomButtons"],this),this._zoomInButton=this._createButton("mapboxgl-ctrl-zoom-in",w=>{this._map&&this._map.zoomIn({},{originalEvent:w})}),x("span","mapboxgl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("mapboxgl-ctrl-zoom-out",w=>{this._map&&this._map.zoomOut({},{originalEvent:w})}),x("span","mapboxgl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(o.aZ(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-compass",w=>{const E=this._map;E&&(this.options.visualizePitch?E.resetNorthPitch({},{originalEvent:w}):E.resetNorth({},{originalEvent:w}))}),this._compassIcon=x("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}_updateZoomButtons(){const D=this._map;if(!D)return;const w=D.getZoom(),E=w===D.getMaxZoom(),F=w===D.getMinZoom();this._zoomInButton.disabled=E,this._zoomOutButton.disabled=F,this._zoomInButton.setAttribute("aria-disabled",E.toString()),this._zoomOutButton.setAttribute("aria-disabled",F.toString())}_rotateCompassArrow(){const D=this._map;if(!D)return;const w=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(D.transform.pitch*(Math.PI/180)),.5)}) rotateX(${D.transform.pitch}deg) rotateZ(${D.transform.angle*(180/Math.PI)}deg)`:`rotate(${D.transform.angle*(180/Math.PI)}deg)`;D._requestDomTask(()=>{this._compassIcon&&(this._compassIcon.style.transform=w)})}onAdd(D){return this._map=D,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),D.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&D.on("pitch",this._rotateCompassArrow),D.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new ML(D,this._compass,this.options.visualizePitch)),this._container}onRemove(){const D=this._map;D&&(this._container.remove(),this.options.showZoom&&D.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&D.off("pitch",this._rotateCompassArrow),D.off("rotate",this._rotateCompassArrow),this._handler&&this._handler.off(),this._handler=void 0),this._map=void 0)}_createButton(D,w){const E=x("button",D,this._container);return E.type="button",E.addEventListener("click",w),E}_setButtonTitle(D,w){if(!this._map)return;const E=this._map._getUIString(`NavigationControl.${w}`);D.setAttribute("aria-label",E),D.firstElementChild&&D.firstElementChild.setAttribute("title",E)}},GeolocateControl:class extends o.E{constructor(D={}){super();const w=navigator.geolocation;this.options=Object.assign({geolocation:w},LL,D),o.aZ(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=Ei(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(D){return this._map=D,this._container=x("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(D){const w=(E=!!this.options.geolocation)=>{this._supportsGeolocation=E,D(E)};this._supportsGeolocation!==void 0?D(this._supportsGeolocation):navigator.permissions!==void 0?navigator.permissions.query({name:"geolocation"}).then(E=>w(E.state!=="denied")).catch(()=>w()):w()}_isOutOfMapMaxBounds(D){const w=this._map.getMaxBounds(),E=D.coords;return!!w&&(E.longitudew.getEast()||E.latitudew.getNorth())}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting")}}_onSuccess(D){if(this._map){if(this._clearRequestTimeout(),this._isOutOfMapMaxBounds(D))return this._setErrorState(),this.fire(new o.C("outofmaxbounds",D)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=D,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this.options.followUserLocation?(this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active")):(this._watchState="BACKGROUND",this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"));break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background")}this.options.showUserLocation&&this._watchState!=="OFF"&&this._updateMarker(D),this.options.followUserLocation&&(!this.options.trackUserLocation||this._watchState==="ACTIVE_LOCK")&&this._updateCamera(D),this.options.showUserLocation&&this._userLocationDotMarker.removeClassName("mapboxgl-user-location-dot-stale"),this.fire(new o.C("geolocate",Object.assign({coords:D.coords,timestamp:D.timestamp},D.toJSON?{toJSON:D.toJSON.bind(D)}:{}))),this._finish()}}_updateCamera(D){const w=new o.aU(D.coords.longitude,D.coords.latitude),E=D.coords.accuracy,F=this._map.getBearing(),G=Object.assign({bearing:F},this.options.fitBoundsOptions);this._map.fitBounds(w.toBounds(E),G,{geolocateSource:!0})}_updateMarker(D){if(D){const w=new o.aU(D.coords.longitude,D.coords.latitude);this._accuracyCircleMarker.setLngLat(w).addTo(this._map),this._userLocationDotMarker.setLngLat(w).addTo(this._map),this._accuracy=D.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()}_updateCircleRadius(){const D=this._map.transform,w=o.bU(1,D._center.lat)*D.worldSize,E=Math.ceil(2*this._accuracy*w);this._circleElement.style.width=`${E}px`,this._circleElement.style.height=`${E}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(D){if(this._map){if(this._clearRequestTimeout(),this.options.trackUserLocation)if(D.code===1){this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;const w=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.setAttribute("aria-label",w),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",w),this._geolocationWatchID!==void 0&&this._clearWatch()}else{if(D.code===3&&this._noTimeout)return;this._setErrorState()}this._watchState!=="OFF"&&this.options.showUserLocation&&this._userLocationDotMarker.addClassName("mapboxgl-user-location-dot-stale"),this.fire(new o.C("error",{code:D.code,message:D.message,PERMISSION_DENIED:D.PERMISSION_DENIED,POSITION_UNAVAILABLE:D.POSITION_UNAVAILABLE,TIMEOUT:D.TIMEOUT})),this._finish()}}_finish(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0}_startRequestTimeout(){this._clearRequestTimeout();const D=this.options.positionOptions.timeout;D&&(this._requestTimeoutId=window.setTimeout(()=>{this._onError({code:3,message:"Geolocation request timed out"})},D))}_clearRequestTimeout(){this._requestTimeoutId!==void 0&&(clearTimeout(this._requestTimeoutId),this._requestTimeoutId=void 0)}_setupUI(D){if(this._map!==void 0){if(this._container.addEventListener("contextmenu",w=>w.preventDefault()),this._geolocateButton=x("button","mapboxgl-ctrl-geolocate",this._container),x("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",D===!1){o.w("Geolocation support is not available so the GeolocateControl will be disabled.");const w=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.setAttribute("aria-label",w),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",w)}else{const w=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.setAttribute("aria-label",w),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",w)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=x("div","mapboxgl-user-location"),this._dotElement.appendChild(x("div","mapboxgl-user-location-dot")),this._dotElement.appendChild(x("div","mapboxgl-user-location-heading")),this._userLocationDotMarker=new Hb({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=x("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Hb({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",this.trigger.bind(this)),this._setup=!0,this.options.showButton||(this._container.style.display="none"),this.options.trackUserLocation&&this._map.on("movestart",w=>{w.geolocateSource||this._watchState!=="ACTIVE_LOCK"||w.originalEvent&&w.originalEvent.type==="resize"||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this.fire(new o.C("trackuserlocationend")))})}}_onDeviceOrientation(D){this._userLocationDotMarker&&(D.webkitCompassHeading?this._heading=D.webkitCompassHeading:D.absolute===!0&&(this._heading=-1*D.alpha),this._updateMarkerRotationThrottled())}trigger(){if(!this._setup)return o.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new o.C("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":this._numberOfWatches--,this._noTimeout=!1,this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this.fire(new o.C("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new o.C("trackuserlocationstart"))}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"BACKGROUND":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");break;case"BACKGROUND_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error")}if(this._watchState==="OFF"&&this._geolocationWatchID!==void 0)this._clearWatch();else if(this._geolocationWatchID===void 0){let D;this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),this._numberOfWatches++,this._numberOfWatches>1?(D={maximumAge:6e5,timeout:0},this._noTimeout=!0):(D=this.options.positionOptions,this._noTimeout=!1),this._geolocationWatchID=this.options.geolocation.watchPosition(this._onSuccess,this._onError,D),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(D){return this.options.followUserLocation=D??LL.followUserLocation,this.options.trackUserLocation&&this._watchState!=="OFF"&&(this.options.followUserLocation?this._watchState!=="BACKGROUND"&&this._watchState!=="BACKGROUND_ERROR"||(this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new o.C("trackuserlocationstart"))):this._watchState!=="ACTIVE_LOCK"&&this._watchState!=="ACTIVE_ERROR"||(this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),this.fire(new o.C("trackuserlocationend")))),this}_addDeviceOrientationListener(){const D=()=>{const w="ondeviceorientationabsolute"in window?"deviceorientationabsolute":"deviceorientation";window.addEventListener(w,this._onDeviceOrientation)};typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(w=>{w==="granted"&&D()}).catch(console.error):D()}_clearWatch(){this._clearRequestTimeout(),this.options.geolocation.clearWatch(this._geolocationWatchID),window.removeEventListener("deviceorientation",this._onDeviceOrientation),window.removeEventListener("deviceorientationabsolute",this._onDeviceOrientation),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)}},AttributionControl:zW,ScaleControl:class{constructor(D={}){this.options=Object.assign({},bm,D),o.aZ(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const D=this.options.maxWidth||100,w=this._map,E=w._containerHeight/2,F=w._containerWidth/2-D/2,G=w.unproject([F,E]),X=w.unproject([F+D,E]),J=G.distanceTo(X);if(this.options.unit==="imperial"){const de=3.2808*J;de>5280?this._setScale(D,de/5280,"mile"):this._setScale(D,de,"foot")}else this.options.unit==="nautical"?this._setScale(D,J/1852,"nautical-mile"):J>=1e3?this._setScale(D,J/1e3,"kilometer"):this._setScale(D,J,"meter")}_setScale(D,w,E){this._map._requestDomTask(()=>{const F=function(X){const J=Math.pow(10,`${Math.floor(X)}`.length-1);let de=X/J;return de=de>=10?10:de>=5?5:de>=3?3:de>=2?2:de>=1?1:function(ye){const Ce=Math.pow(10,Math.ceil(-Math.log(ye)/Math.LN10));return Math.round(ye*Ce)/Ce}(de),J*de}(w),G=F/w;this._container.innerHTML=E!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:E}).format(F):`${F} ${Gb[E]}`,this._container.style.width=D*G+"px"})}onAdd(D){return this._map=D,this._language=D.getLanguage(),this._container=x("div","mapboxgl-ctrl mapboxgl-ctrl-scale",D.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(D){this._language=D,this._update()}setUnit(D){this.options.unit=D,this._update()}},FullscreenControl:class{constructor(D={}){this._fullscreen=!1,D&&D.container&&(D.container instanceof HTMLElement?this._container=D.container:o.w("Full screen control 'container' must be a DOM element.")),o.aZ(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onwebkitfullscreenchange"in document&&(this._fullscreenchange="webkitfullscreenchange")}onAdd(D){return this._map=D,this._container||(this._container=this._map.getContainer()),this._controlContainer=x("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 D=this._fullscreenButton=x("button","mapboxgl-ctrl-fullscreen",this._controlContainer);x("span","mapboxgl-ctrl-icon",D).setAttribute("aria-hidden","true"),D.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),document.addEventListener(this._fullscreenchange,this._changeIcon)}_updateTitle(){const D=this._getTitle();this._fullscreenButton.setAttribute("aria-label",D),this._fullscreenButton.firstElementChild&&this._fullscreenButton.firstElementChild.setAttribute("title",D)}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_changeIcon(){(document.fullscreenElement||document.webkitFullscreenElement)===this._container!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("mapboxgl-ctrl-shrink"),this._fullscreenButton.classList.toggle("mapboxgl-ctrl-fullscreen"),this._updateTitle())}_onClickFullscreen(){this._isFullscreen()?document.exitFullscreen?document.exitFullscreen():document.webkitCancelFullScreen&&document.webkitCancelFullScreen():this._container.requestFullscreen?this._container.requestFullscreen():this._container.webkitRequestFullscreen&&this._container.webkitRequestFullscreen()}},IndoorControl:class{constructor(){o.aZ(["_onIndoorUpdate","_onStyleData","_scrollUp","_scrollDown","_toggleIndoor"],this),this._visibleFloorStart=0,this._lastSelectedFloorId=null}onAdd(D){return this._map=D,this._container=x("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.style.display="none",this._map.on("styledata",this._onStyleData),this._updateConnection(),this._container}_onStyleData(){this._updateConnection()}_updateConnection(){if(this._map&&this._map.style&&this._map.style.indoorManager){const D=this._map.style.indoorManager;D.off("selector-update",this._onIndoorUpdate),D.on("selector-update",this._onIndoorUpdate),this._onIndoorUpdate(D.getControlState())}}_createButton(D,w){const E=x("button",D,this._container);return E.type="button",E.addEventListener("click",w),E}_setButtonTitle(D,w){D.setAttribute("aria-label",w),D.textContent=w}onRemove(){this._container&&this._container.remove(),this._map&&(this._map.off("styledata",this._onStyleData),this._map.style&&this._map.style.indoorManager.off("selector-update",this._onIndoorUpdate),this._map=null)}getDefaultPosition(){return"top-right"}_onIndoorUpdate(D){if(!D||!D.floors||D.floors.length===0)return this._model=D,void(this._container.style.display="none");const w=this._model;this._model=D,this._container.style.display="inline-block";const E=!w||w.floors.length!==D.floors.length||w.floors.some((F,G)=>F.id!==D.floors[G].id);if(E&&(this._visibleFloorStart=0,this._lastSelectedFloorId=null),D.selectedFloorId){if(D.selectedFloorId!==this._lastSelectedFloorId||E){const F=D.floors.findIndex(G=>G.id===D.selectedFloorId);if(F!==-1){const G=D.floors.length;let X,J;G<=5?(X=0,J=G-1):this._visibleFloorStart===0?(X=0,J=3):this._visibleFloorStart>=G-3?(X=G-3-1,J=G-1):(X=this._visibleFloorStart,J=this._visibleFloorStart+3-1),FJ&&(this._visibleFloorStart=F-2)}}this._lastSelectedFloorId=D.selectedFloorId}this._render()}_render(){if(!this._container||!this._model||!this._model.floors)return;this._container.innerHTML="";const D=this._createButton("mapboxgl-ctrl-indoor-toggle",this._toggleIndoor);x("span","mapboxgl-ctrl-icon",D).setAttribute("aria-hidden","true"),this._model.activeFloorsVisible||D.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.appendChild(D);const w=this._model.floors,E=w.length;if(E<=5)return void w.forEach(J=>this._createFloorButton(J));const F=this._visibleFloorStart===0,G=this._visibleFloorStart>=E-3;if(F)this._createFloorButton(w[0]);else{const J=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);x("span","mapboxgl-ctrl-icon",J).setAttribute("aria-hidden","true"),this._container.appendChild(J)}let X=[];if(X=F?w.slice(1,4):G?w.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):w.slice(this._visibleFloorStart,this._visibleFloorStart+3),X.forEach(J=>this._createFloorButton(J)),G)this._createFloorButton(w[E-1]);else{const J=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);x("span","mapboxgl-ctrl-icon",J).setAttribute("aria-hidden","true"),this._container.appendChild(J)}}_createFloorButton(D){const w=this._createButton("mapboxgl-ctrl-level-button",()=>{const X=D.id;this._model&&this._model.selectedFloorId===X&&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(X))}),E=(D.name||"").trim(),F=D.zIndex.toString(),G=E?Array.from(E).slice(0,3).join(""):F;this._setButtonTitle(w,G),this._model&&this._model.activeFloorsVisible&&D.id===this._model.selectedFloorId&&w.classList.add("mapboxgl-ctrl-level-button-selected"),this._container&&this._container.appendChild(w)}_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 D=this._model&&this._model.floors||[];if(D.length>3){const w=D.length-3;this._visibleFloorStart===w-1&&(this._visibleFloorStart=w-2)}this._render()}}_scrollDown(){if(this._model&&this._model.floors){const D=this._model.floors.length-3;this._visibleFloorStartD&&(this._visibleFloorStart=D),this._render())}}},Popup:class extends o.E{constructor(D){super(),this.options=Object.assign(Object.create(IL),D),this._altitude=this.options.altitude,o.aZ(["_update","_onClose","remove","_onMouseEvent"],this),this._classList=new Set(D&&D.className?D.className.trim().split(/\s+/):[])}addTo(D){return this._map&&this.remove(),this._map=D,this.options.closeOnClick&&D.on("preclick",this._onClose),this.options.closeOnMove&&D.on("move",this._onClose),D.on("remove",this.remove),this._update(),D._addPopup(this),this._focusFirstElement(),this._trackPointer?(D.on("mousemove",this._onMouseEvent),D.on("mouseup",this._onMouseEvent),D._canvasContainer.classList.add("mapboxgl-track-pointer")):D.on("move",this._update),this.fire(new o.C("open")),this}isOpen(){return!!this._map}remove(){this._content&&this._content.remove(),this._container&&(this._container.remove(),this._container=void 0);const D=this._map;return D&&(D.off("move",this._update),D.off("move",this._onClose),D.off("preclick",this._onClose),D.off("click",this._onClose),D.off("remove",this.remove),D.off("mousemove",this._onMouseEvent),D.off("mouseup",this._onMouseEvent),D.off("drag",this._onMouseEvent),D._canvasContainer&&D._canvasContainer.classList.remove("mapboxgl-track-pointer"),D._removePopup(this),this._map=void 0),this.fire(new o.C("close")),this}getLngLat(){return this._lngLat}setLngLat(D){this._lngLat=o.aU.convert(D),this._pos=null,this._trackPointer=!1,this._update();const w=this._map;return w&&(w.on("move",this._update),w.off("mousemove",this._onMouseEvent),w._canvasContainer.classList.remove("mapboxgl-track-pointer")),this}getAltitude(){return this._altitude}setAltitude(D){return this._altitude=D,this._update(),this}trackPointer(){this._trackPointer=!0,this._pos=null,this._update();const D=this._map;return D&&(D.off("move",this._update),D.on("mousemove",this._onMouseEvent),D.on("drag",this._onMouseEvent),D._canvasContainer.classList.add("mapboxgl-track-pointer")),this}getElement(){return this._container}setText(D){return this.setDOMContent(document.createTextNode(D))}setHTML(D){const w=document.createDocumentFragment(),E=document.createElement("body");let F;for(E.innerHTML=D;F=E.firstChild,F;)w.appendChild(F);return this.setDOMContent(w)}getMaxWidth(){return this._container&&this._container.style.maxWidth}setMaxWidth(D){return this.options.maxWidth=D,this._update(),this}setDOMContent(D){let w=this._content;if(w)for(;w.hasChildNodes();)w.firstChild&&w.removeChild(w.firstChild);else w=this._content=x("div","mapboxgl-popup-content",this._container||void 0);if(w.appendChild(D),this.options.closeButton){const E=this._closeButton=x("button","mapboxgl-popup-close-button",w);E.type="button",E.setAttribute("aria-label","Close popup"),E.innerHTML='',E.addEventListener("click",this._onClose)}return this._update(),this._focusFirstElement(),this}addClassName(D){return this._classList.add(D),this._updateClassList(),this}removeClassName(D){return this._classList.delete(D),this._updateClassList(),this}setOffset(D){return this.options.offset=D,this._update(),this}toggleClassName(D){let w;return this._classList.delete(D)?w=!1:(this._classList.add(D),w=!0),this._updateClassList(),w}_onMouseEvent(D){this._update(D.point)}_getAnchor(D){if(this.options.anchor)return this.options.anchor;const w=this._map,E=this._container,F=this._pos;if(!w||!E||!F)return"bottom";const G=E.offsetWidth,X=E.offsetHeight,J=F.xw.transform.width-G/2;if(F.y+Dw.transform.height-X){if(J)return"bottom-left";if(de)return"bottom-right"}return J?"left":de?"right":"bottom"}_updateClassList(){const D=this._container;if(!D)return;const w=[...this._classList];w.push("mapboxgl-popup"),this._anchor&&w.push(`mapboxgl-popup-anchor-${this._anchor}`),this._trackPointer&&w.push("mapboxgl-popup-track-pointer"),D.className=w.join(" ")}_update(D){const w=this._map,E=this._content;if(!w||!this._lngLat&&!this._trackPointer||!E)return;let F=this._container;if(F||(F=this._container=x("div","mapboxgl-popup",w.getContainer()),this._tip=x("div","mapboxgl-popup-tip",F),F.appendChild(E)),this.options.maxWidth&&F.style.maxWidth!==this.options.maxWidth&&(F.style.maxWidth=this.options.maxWidth),w.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=UW(this._lngLat,this._pos,w.transform)),!this._trackPointer||D){const G=this._pos=this._trackPointer&&D instanceof o.P?D:w.project(this._lngLat,this._altitude),X=rz(this.options.offset),J=this._anchor=this._getAnchor(X.y),de=rz(this.options.offset,J),ye=G.add(de).round();w._requestDomTask(()=>{this._container&&J&&(this._container.style.transform=`${PL[J]} translate(${ye.x}px,${ye.y}px)`)})}if(!this._marker&&w._showingGlobe()){const G=o.e$(w.transform,this._lngLat)?0:1;this._setOpacity(G)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const D=this._container.querySelector(y8e);D&&D.focus()}_onClose(){this.remove()}_setOpacity(D){this._container&&(this._container.style.opacity=`${D}`),this._content&&(this._content.style.pointerEvents=D?"auto":"none")}},Marker:Hb,Style:eh,LngLat:o.aU,LngLatBounds:o.aK,Point:o.P,MercatorCoordinate:o.ag,FreeCameraOptions:Ny,Evented:o.E,config:o.g,prewarm:function(){qt().acquire(Ge)},clearPrewarmedResources:function(){const D=pt;D&&(D.isPreloaded()&&D.numActive()===1?(D.release(Ge),pt=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"))},get accessToken(){return o.g.ACCESS_TOKEN},set accessToken(D){o.g.ACCESS_TOKEN=D},get baseApiUrl(){return o.g.API_URL},set baseApiUrl(D){o.g.API_URL=D},get workerCount(){return He.workerCount},set workerCount(D){He.workerCount=D},get maxParallelImageRequests(){return o.g.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(D){o.g.MAX_PARALLEL_IMAGE_REQUESTS=D},clearStorage(D){o.f7(D)},get workerUrl(){return Ue.workerUrl},set workerUrl(D){Ue.workerUrl=D},get workerClass(){return Ue.workerClass},set workerClass(D){Ue.workerClass=D},get workerParams(){return Ue.workerParams},set workerParams(D){Ue.workerParams=D},get dracoUrl(){return o.f6()},set dracoUrl(D){o.g.DRACO_URL=o.o.resolveURL(D)},get meshoptUrl(){return o.f5()},set meshoptUrl(D){const w=o.o.resolveURL(D);o.g.MESHOPT_URL=w,o.g.MESHOPT_SIMD_URL=w},get buildingGenUrl(){return o.f4()},set buildingGenUrl(D){o.g.BUILDING_GEN_URL=o.o.resolveURL(D)},setNow:o.o.setNow,restoreNow:o.o.restoreNow}});var l=a;return l})})(dRt);var TAs=dRt.exports;const bd=od(TAs),jmt={coming_soon:"#3B82F6",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#F97316",under_contract:"#8B5CF6",sold:"#6B7280"},Nmt={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 MAs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function PAs({listings:s,isLoading:t}){const n=Wn(),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;bd.accessToken=l;const h=s.filter(f=>f.latitude!=null&&f.longitude!=null);let m=[-98.5795,39.8283],p=4;if(h.length>0){const f=h.reduce((y,v)=>y+v.longitude,0)/h.length,x=h.reduce((y,v)=>y+v.latitude,0)/h.length;m=[f,x],p=h.length===1?12:10}return a.current=new bd.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:p,center:m}),a.current.addControl(new bd.NavigationControl,"top-right"),()=>{var f;(f=a.current)==null||f.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,T;const p=jmt[m.status]||"#10B981",f=((S=m.photos)==null?void 0:S.find(L=>L.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 bd.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${f!=null&&f.photo_url?``:""}
${MAs(m.price)}
${m.property_address||""}
${m.city}, ${m.state}
${Nmt[m.status]||m.status} ${m.bedrooms?`${m.bedrooms} bed`:""} ${m.bathrooms?`${m.bathrooms} bath`:""}
${(T=m.agent)!=null&&T.name?`
Listed by ${m.agent.name}
`:""}
Click to view details →
`),N=new bd.Marker(v).setLngLat([m.longitude,m.latitude]).setPopup(b).addTo(a.current);i.current.push(N)}),h.length>1){const m=new bd.LngLatBounds;h.forEach(p=>m.extend([p.longitude,p.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(jmt).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:Nmt[h]})]},h))}),e.jsx("div",{ref:r,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}const uOe={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},LAs={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},Vz="#0d0d0d",kmt="#1a1a1a",Td="#c9a84c",rT="#f0d78c";function hRt(){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:p}=mAs(),f=j.useMemo(()=>{if(!p)return[];const z=s.trim().toLowerCase(),$=[...p.cities.map(V=>({label:V.label,value:V.city,type:"city",count:V.count})),...p.neighborhoods.map(V=>({label:V.label,value:V.neighborhood,type:"neighborhood",count:V.count})),...p.zips.map(V=>({label:`ZIP ${V.label}`,value:V.zip,type:"zip",count:V.count}))];return(z?$.filter(V=>V.label.toLowerCase().includes(z)||V.value.toLowerCase().includes(z)):$).slice(0,8)},[p,s]);j.useEffect(()=>{const z=$=>{u.current&&!u.current.contains($.target)&&o(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[]);const{data:x,isLoading:y}=hAs({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=z=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(z),b=()=>{m({status:"",propertyType:"",minPrice:"",maxPrice:""}),t("")},N=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=z=>S?`/${z.slug||z.id}`:`/public/listing/${z.slug||z.id}`,{featured:T,restListings:L,luxeCount:M,cities:I,activeCount:R}=j.useMemo(()=>{const z=x||[],$=z.filter(je=>je.status==="active"),H=$.length>0?$:z,V=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),[K,Z,Q]=V.split("-").map(Number),le=Math.floor(Date.UTC(K,Z-1,Q)/864e5),ue=H.length>0?H[le%H.length]:void 0,se=z.filter(je=>!ue||je.id!==ue.id),ne=Array.from(new Set(z.map(je=>je.city).filter(Boolean))).slice(0,8),ie=z.filter(je=>(je.price||0)>=1e6).length,ce=$.length;return{featured:ue,restListings:se,luxeCount:ie,cities:ne,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:Vz,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: ${Td}; } .lu-gold-line { background: linear-gradient(90deg, transparent, ${Td}, 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(xr,{to:"/",className:"flex items-center gap-3",children:[e.jsx("img",{src:UV,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(xr,{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 ${Td}`,color:Td},children:"About LevelUp"})]}),e.jsx("button",{type:"button",onClick:()=>i(z=>!z),className:"md:hidden inline-flex items-center justify-center w-10 h-10 rounded-full",style:{border:`1px solid ${Td}`,color:Td},"aria-label":"Toggle menu","aria-expanded":a,children:a?e.jsx(er,{className:"w-5 h-5"}):e.jsx(AA,{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(xr,{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 ${Td}`,color:Td},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:EAs,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:Td}}),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:rT},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 ${Td}`,backdropFilter:"blur(12px)"},children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-5 w-5",style:{color:Td}}),e.jsx(xe,{placeholder:"City, neighborhood, or ZIP",value:s,onChange:z=>{t(z.target.value),o(!0),d(-1)},onFocus:()=>o(!0),onKeyDown:z=>{if(!(!l||f.length===0))if(z.key==="ArrowDown")z.preventDefault(),d($=>Math.min($+1,f.length-1));else if(z.key==="ArrowUp")z.preventDefault(),d($=>Math.max($-1,0));else if(z.key==="Enter"&&c>=0){z.preventDefault();const $=f[c];t($.value),o(!1)}else z.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(LM,{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:Td,color:Vz},onClick:()=>o(!1),children:[e.jsx(Fr,{className:"h-5 w-5"}),e.jsx("span",{className:"hidden md:inline",children:"Search"})]})]}),l&&f.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:Td},children:"Suggestions"}),e.jsx("ul",{className:"max-h-80 overflow-y-auto",children:f.map((z,$)=>e.jsx("li",{children:e.jsxs("button",{type:"button",onMouseEnter:()=>d($),onClick:()=>{t(z.value),o(!1)},className:"w-full flex items-center justify-between gap-3 px-5 py-3 text-left transition",style:{background:c===$?"rgba(201,168,76,0.12)":"transparent"},children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[z.type==="city"&&e.jsx(ni,{className:"h-4 w-4 shrink-0",style:{color:Td}}),z.type==="neighborhood"&&e.jsx(_i,{className:"h-4 w-4 shrink-0",style:{color:Td}}),z.type==="zip"&&e.jsx(ra,{className:"h-4 w-4 shrink-0",style:{color:Td}}),e.jsx("span",{className:"text-white/90 truncate",children:z.label})]}),e.jsxs("span",{className:"text-xs text-white/50 shrink-0",children:[z.count," ",z.count===1?"listing":"listings"]})]})},`${z.type}-${z.value}-${$}`))})]}),l&&s.trim()&&f.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(Ns,{value:h.status||"all",onValueChange:z=>m({...h,status:z==="all"?"":z}),children:[e.jsx(ws,{className:"lu-input-dark",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"Any status"}),Object.entries(uOe).map(([z,$])=>e.jsx(et,{value:z,children:$},z))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Type"}),e.jsxs(Ns,{value:h.propertyType||"all",onValueChange:z=>m({...h,propertyType:z==="all"?"":z}),children:[e.jsx(ws,{className:"lu-input-dark",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"Any type"}),Object.entries(LAs).map(([z,$])=>e.jsx(et,{value:z,children:$},z))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Min Price"}),e.jsx(xe,{type:"number",placeholder:"No min",value:h.minPrice,onChange:z=>m({...h,minPrice:z.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(xe,{type:"number",placeholder:"No max",value:h.maxPrice,onChange:z=>m({...h,maxPrice:z.target.value}),className:"lu-input-dark"})]}),N&&e.jsx("div",{className:"sm:col-span-2 md:col-span-4 flex justify-end",children:e.jsxs(U,{variant:"ghost",size:"sm",onClick:b,className:"text-white/70 hover:text-white gap-1",children:[e.jsx(er,{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:R.toString()},{label:"Luxury $1M+",value:M.toString()}].map(z=>e.jsxs("div",{children:[e.jsx("div",{className:"lu-serif text-4xl md:text-5xl",style:{color:rT},children:z.value}),e.jsx("div",{className:"lu-eyebrow text-white/60 mt-1",children:z.label})]},z.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(rl,{className:"h-4 w-4 animate-bounce"})]})]})]}),I.length>0&&e.jsx("section",{className:"py-8 overflow-hidden",style:{background:kmt,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:[...I,...I,...I].map((z,$)=>e.jsxs("span",{className:"flex items-center gap-3 lu-serif text-2xl md:text-3xl text-white/40",children:[z,e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:Td}})]},$))})}),T&&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(cn,{className:"h-4 w-4",style:{color:Td}}),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:rT},children:"standout"}),"."]})]}),e.jsx("div",{className:"hidden md:block h-px flex-1 mx-8 lu-gold-line"})]}),e.jsx(xr,{to:A(T),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 $,H;const z=(($=T.photos)==null?void 0:$.find(V=>V.is_primary))||((H=T.photos)==null?void 0:H[0]);return z?e.jsx("img",{src:z.photo_url,alt:T.property_address||T.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(ra,{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:Td,color:Vz},children:uOe[T.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(ni,{className:"h-3.5 w-3.5",style:{color:Td}}),T.city,T.state?`, ${T.state}`:""]}),T.property_address&&e.jsx("h3",{className:"lu-serif text-3xl md:text-4xl mb-4 leading-tight",children:T.property_address}),e.jsx("div",{className:"lu-serif text-5xl md:text-6xl mb-6",style:{color:rT},children:v(T.price)}),e.jsxs("div",{className:"flex items-center gap-6 text-white/70 mb-8",children:[T.bedrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Xw,{className:"h-4 w-4",style:{color:Td}}),T.bedrooms," bd"]}),T.bathrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(d0,{className:"h-4 w-4",style:{color:Td}}),T.bathrooms," ba"]}),T.square_footage&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(db,{className:"h-4 w-4",style:{color:Td}}),T.square_footage.toLocaleString()," sf"]})]}),T.description&&e.jsx("p",{className:"text-white/60 leading-relaxed mb-8 line-clamp-4",children:T.description}),e.jsxs("div",{className:"inline-flex items-center gap-3 lu-eyebrow group-hover:gap-5 transition-all",style:{color:Td},children:["View Residence ",e.jsx(Oa,{className:"h-4 w-4"})]})]})]})})]})}),e.jsx("section",{id:"collection",className:"py-20 md:py-28",style:{background:kmt},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:Td}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"The Collection"}),e.jsx("span",{className:"h-px w-10",style:{background:Td}})]}),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:rT},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((z,$)=>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"})]},$))}):L.length>0?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-14",children:L.map(z=>{var H,V,K,Z,Q;const $=((H=z.photos)==null?void 0:H.find(le=>le.is_primary))||((V=z.photos)==null?void 0:V[0]);return e.jsxs(xr,{to:A(z),className:"group lu-card-hover block",children:[e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden bg-black mb-5 rounded-lg",children:[$?e.jsx("img",{src:$.photo_url,alt:z.property_address||z.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(ra,{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:Td,border:`1px solid ${Td}`},children:uOe[z.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:[z.bedrooms&&e.jsxs("span",{children:[z.bedrooms," bd"]}),z.bathrooms&&e.jsxs("span",{children:[z.bathrooms," ba"]}),z.square_footage&&e.jsxs("span",{children:[z.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(ni,{className:"h-3 w-3",style:{color:Td}}),z.city,z.state?`, ${z.state}`:""]}),e.jsx("div",{className:"lu-serif text-2xl md:text-3xl mb-1",style:{color:rT},children:v(z.price)}),z.property_address&&e.jsx("p",{className:"text-white/70 text-sm truncate",children:z.property_address}),((K=z.agent)==null?void 0:K.name)&&e.jsxs("p",{className:"text-white/40 text-xs mt-3 flex items-center gap-2",children:[e.jsx(_i,{className:"h-3 w-3"}),z.agent.name,(((Z=z.agent.brokerage)==null?void 0:Z.name)||z.agent.brokerage_name)&&e.jsxs("span",{className:"truncate",children:["· ",((Q=z.agent.brokerage)==null?void 0:Q.name)||z.agent.brokerage_name]})]})]})]},z.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 ${Td}`},children:e.jsx(ra,{className:"h-8 w-8",style:{color:Td}})}),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."}),N&&e.jsx(U,{onClick:b,style:{background:Td,color:Vz},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:Td}}),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:rT},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(PAs,{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%, ${Vz} 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:Td}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"For Agents"}),e.jsx("span",{className:"h-px w-10",style:{background:Td}})]}),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:rT},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:Td,color:Vz},children:["Explore LevelUp",e.jsx(Oa,{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:UV,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($Cs,{}),e.jsx(VCs,{})]})}const IAs=j.lazy(()=>ui(()=>import("./PublicHomeValue-DAY2pzBM.js"),[]));function RAs(){const s=Od(),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(hRt,{}):r==="home-value"||r==="whats-my-home-worth"?e.jsx(j.Suspense,{fallback:e.jsx("div",{}),children:e.jsx(IAs,{})}):r.startsWith("public/")?null:e.jsx(BXe,{slugOverride:r})}const DAs=j.lazy(()=>ui(()=>import("./CommercialMarketplace-GsbSMEAa.js"),[]));function OAs(){const t=Od().pathname.slice(1);return t?t.startsWith("public/")?null:e.jsx(BXe,{slugOverride:t}):e.jsx(j.Suspense,{fallback:e.jsx("div",{className:"min-h-screen bg-[#0a0d12]"}),children:e.jsx(DAs,{})})}function NMe({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 mRt=s=>ct({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}),FAs=()=>ct({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}}),zAs=s=>ct({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}),pRt=()=>{const s=Qt();return yt({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)})},fRt=()=>{const s=Qt();return yt({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)})},_d=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:{}})},BAs=async(s,t)=>{const{error:n}=await q.from("agent_card_leads").insert({card_id:s,...t});if(n)throw n},gRt=s=>ct({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 kMe({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(""),[p,f]=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 BAs(n,{lead_type:r,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:p.trim()||void 0,intent:h||void 0}),_d(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:p.trim()||void 0,intent:h||void 0}}).catch(N=>console.error("Card lead notify failed:",N)),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(""),f("")}catch{re.error("Something went wrong. Please try again.")}finally{y(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"sm:max-w-md rounded-2xl",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{htmlFor:"lead-name",children:"Name *"}),e.jsx(xe,{id:"lead-name",value:i,onChange:b=>l(b.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"lead-phone",children:"Phone"}),e.jsx(xe,{id:"lead-phone",type:"tel",value:d,onChange:b=>u(b.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"lead-email",children:"Email"}),e.jsx(xe,{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(te,{htmlFor:"lead-intent",children:"I'm looking to..."}),e.jsxs(Ns,{value:h,onValueChange:m,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select one"})}),e.jsxs(js,{children:[e.jsx(et,{value:"buy",children:"Buy a home"}),e.jsx(et,{value:"sell",children:"Sell my home"}),e.jsx(et,{value:"both",children:"Buy & Sell"}),e.jsx(et,{value:"other",children:"Something else"})]})]})]}),r!=="connect"&&e.jsxs("div",{children:[e.jsx(te,{htmlFor:"lead-message",children:r==="referral"?"Tell us about them":"Message (optional)"}),e.jsx(xe,{id:"lead-message",value:p,onChange:b=>f(b.target.value),placeholder:r==="referral"?"Their name, phone, situation...":"Anything you'd like us to know"})]}),e.jsx(U,{type:"submit",className:"w-full rounded-2xl",disabled:x,children:x?"Sending...":"Submit"})]})]})})}const UAs=s=>ct({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}),qAs=s=>ct({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}),$As=()=>{const s=Qt();return yt({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)})},VAs=()=>{const s=Qt();return yt({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)})},HAs=()=>{const s=Qt();return yt({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 GAs(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 WAs(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 KAs={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 YAs({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=WAs(n.video_url),i=r||!!a,l=r?GAs(n.video_url):a||n.video_url;return e.jsx("div",{className:KAs[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 ZAs={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 XAs({block:s,variant:t}){const r=s.config.testimonials||[],[a,i]=j.useState(0);if(r.length===0)return null;const l=ZAs[t],o=r[a];return e.jsxs("div",{className:l.container,children:[e.jsxs("div",{className:l.card,children:[e.jsx(tS,{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(rd,{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(gi,{className:"h-4 w-4"})})]})]})}const QAs={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 JAs({block:s,variant:t}){const r=s.config.tags||[];if(r.length===0)return null;const a=QAs[t];return e.jsx("div",{className:a.container,children:r.map((i,l)=>e.jsx("span",{className:a.tag,children:i},l))})}const eEs={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 tEs({block:s,cardId:t,variant:n}){const a=s.config.links||[];if(a.length===0)return null;const i=eEs[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:()=>_d(t,"button_click",`custom_link_${l.label}`),className:i.link,children:[e.jsx("span",{children:l.label}),e.jsx(Sr,{className:`h-4 w-4 ${i.icon}`})]},o))})}const Aqe={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 sEs({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 nEs={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 rEs({block:s,cardId:t,variant:n}){const a=s.config.platforms||[],i=nEs[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=Aqe[l.platform.toLowerCase()];return!c||!l.url?null:e.jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>_d(t,"button_click",`social_${l.platform}`),className:i.linkClass,title:c.label,children:e.jsx(sEs,{path:c.icon,color:c.color})},o)})})]})}function SMe({cardId:s,variant:t}){const{data:n}=UAs(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(YAs,{block:l,variant:t},l.id);case"testimonials":return e.jsx(XAs,{block:l,variant:t},l.id);case"specialties":return e.jsx(JAs,{block:l,variant:t},l.id);case"custom_links":return e.jsx(tEs,{block:l,cardId:s,variant:t},l.id);default:return null}}),i&&e.jsx(rEs,{block:i,cardId:s,variant:t})]})}async function aEs(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 iEs(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 CMe(s){const{first:t,last:n}=iEs(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 aEs(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 oEs({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,N)=>{_d(s.id,"button_click",b),N()},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),_d(s.id,"button_click","book"))},m=()=>{var b,N;_d(s.id,"contact_saved"),CMe({name:i,phone:(b=s.profile)==null?void 0:b.phone,email:(N=s.profile)==null?void 0:N.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},p=async()=>{_d(s.id,"share_event");const b=`https://cards.relevelup.com/${s.slug}`,N="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:N,url:b})}catch{}else await navigator.clipboard.writeText(b),re.success("Link copied!")},f=()=>{a("referral"),n(!0),_d(s.id,"button_click","refer")},x=()=>{a("connect"),n(!0),_d(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(Ea,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(Ci,{src:s.avatar_url||void 0,alt:i}),e.jsx(Ta,{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(U,{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(ba,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Call"})]}),e.jsxs(U,{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(Ki,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Text"})]}),e.jsxs(U,{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(ln,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Email"})]})]}),e.jsxs(U,{onClick:h,className:"w-full h-12 text-base font-semibold rounded-2xl shadow-sm mb-6",variant:"outline",children:[e.jsx(pa,{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(Ua,{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(NMe,{card:s,variant:"standard"}),e.jsx(SMe,{cardId:s.id,variant:"standard"}),e.jsxs("div",{className:"space-y-2 mb-6",children:[s.show_save_contact&&e.jsxs(U,{variant:"ghost",onClick:m,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(pi,{className:"h-4 w-4 mr-3 text-primary"}),"Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs(U,{variant:"ghost",onClick:()=>{_d(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(Ua,{className:"h-4 w-4 mr-3 text-amber-500"}),"Leave a Review"]}),s.show_refer_friend&&e.jsxs(U,{variant:"ghost",onClick:f,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Bn,{className:"h-4 w-4 mr-3 text-primary"}),"Refer a Friend"]}),e.jsxs(U,{variant:"ghost",onClick:x,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(zl,{className:"h-4 w-4 mr-3 text-primary"}),"Connect with Me"]}),e.jsxs(U,{variant:"ghost",onClick:p,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(jd,{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,N)=>e.jsx("a",{href:b.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>_d(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()]||"🔗"},N))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-slate-400",children:"Powered by LevelUp"})})]}),e.jsx(kMe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function lEs({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,N)=>{_d(s.id,"button_click",b),N()},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),_d(s.id,"button_click","book"))},m=()=>{var b,N;_d(s.id,"contact_saved"),CMe({name:i,phone:(b=s.profile)==null?void 0:b.phone,email:(N=s.profile)==null?void 0:N.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},p=async()=>{_d(s.id,"share_event");const b=`https://cards.relevelup.com/${s.slug}`,N="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:N,url:b})}catch{}else await navigator.clipboard.writeText(b),re.success("Link copied!")},f=()=>{a("referral"),n(!0),_d(s.id,"button_click","refer")},x=()=>{a("connect"),n(!0),_d(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(Ea,{className:"h-32 w-32 mx-auto mb-5 ring-2 ring-[#c9a84c]/40 shadow-2xl",children:[e.jsx(Ci,{src:s.avatar_url||void 0,alt:i}),e.jsx(Ta,{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:ba,label:"Call",handler:c},{icon:Ki,label:"Text",handler:d},{icon:ln,label:"Email",handler:u}].map(({icon:b,label:N,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:N})]},N))}),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(pa,{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(Ua,{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(NMe,{card:s,variant:"luxury"}),e.jsx(SMe,{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(pi,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{_d(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(Ua,{className:"h-4 w-4 text-[#c9a84c]"})," Leave a Review"]}),s.show_refer_friend&&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(Bn,{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(zl,{className:"h-4 w-4 text-[#c9a84c]"})," Connect with Me"]}),e.jsxs("button",{onClick:p,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(jd,{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,N)=>e.jsx("a",{href:b.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>_d(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()]||"🔗"},N))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#4a5568]",children:"Powered by LevelUp"})})]}),e.jsx(kMe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function cEs({card:s}){var N,S,A,T;const[t,n]=j.useState(!1),[r,a]=j.useState("booking"),i=((N=s.profile)==null?void 0:N.name)||"Agent",l=i.split(" ").map(L=>L[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:((T=s.bold_theme_colors)==null?void 0:T.button)||"#ff5722"},c=(L,M)=>{const I=parseInt(L.replace("#",""),16),R=Math.max(0,(I>>16)-M),z=Math.max(0,(I>>8&255)-M),$=Math.max(0,(I&255)-M);return`#${(R<<16|z<<8|$).toString(16).padStart(6,"0")}`};c(o.accent,25),c(o.dark,-20),c(o.button,25);const d=(L,M)=>{_d(s.id,"button_click",L),M()},u=()=>d("call",()=>{var L;(L=s.profile)!=null&&L.phone?window.location.href=`tel:${s.profile.phone}`:re.error("Phone number not available")}),h=()=>d("text",()=>{var L;(L=s.profile)!=null&&L.phone?window.location.href=`sms:${s.profile.phone}`:re.error("Phone number not available")}),m=()=>d("email",()=>{var L;(L=s.profile)!=null&&L.email?window.location.href=`mailto:${s.profile.email}`:re.error("Email not available")}),p=()=>{s.booking_url?d("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),_d(s.id,"button_click","book"))},f=()=>{var L,M;_d(s.id,"contact_saved"),CMe({name:i,phone:(L=s.profile)==null?void 0:L.phone,email:(M=s.profile)==null?void 0:M.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},x=async()=>{_d(s.id,"share_event");const L=`https://cards.relevelup.com/${s.slug}`,M="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:M,url:L})}catch{}else await navigator.clipboard.writeText(L),re.success("Link copied!")},y=()=>{a("referral"),n(!0),_d(s.id,"button_click","refer")},v=()=>{a("connect"),n(!0),_d(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(Ea,{className:"h-28 w-28 mx-auto mb-4 shadow-2xl",style:{boxShadow:`0 0 0 4px ${o.accent}`},children:[e.jsx(Ci,{src:s.avatar_url||void 0,alt:i}),e.jsx(Ta,{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:ba,label:"Call",handler:u},{icon:Ki,label:"Text",handler:h},{icon:ln,label:"Email",handler:m}].map(({icon:L,label:M,handler:I})=>e.jsxs("button",{onClick:I,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(L,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:M})]},M))}),e.jsxs("button",{onClick:p,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(pa,{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(Ua,{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(NMe,{card:s,variant:"bold"}),e.jsx(SMe,{cardId:s.id,variant:"bold"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:f,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(pi,{className:"h-4 w-4",style:{color:o.accent}})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{_d(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(Ua,{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(Bn,{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(zl,{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(jd,{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((L,M)=>e.jsx("a",{href:L.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>_d(s.id,"button_click",`social_${L.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[L.platform.toLowerCase()]||"🔗"},M))})]}),e.jsx("div",{className:"text-center py-6",children:e.jsx("p",{className:"text-xs text-white/50",children:"Powered by LevelUp"})})]}),e.jsx(kMe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function dEs({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,N)=>{_d(s.id,"button_click",b),N()},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),_d(s.id,"button_click","book"))},m=()=>{var b,N;_d(s.id,"contact_saved"),CMe({name:i,phone:(b=s.profile)==null?void 0:b.phone,email:(N=s.profile)==null?void 0:N.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},p=async()=>{_d(s.id,"share_event");const b=`https://cards.relevelup.com/${s.slug}`,N="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:N,url:b})}catch{}else await navigator.clipboard.writeText(b),re.success("Link copied!")},f=()=>{a("referral"),n(!0),_d(s.id,"button_click","refer")},x=()=>{a("connect"),n(!0),_d(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(Ea,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(Ci,{src:s.avatar_url||void 0,alt:i}),e.jsx(Ta,{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:ba,label:"Call",handler:c},{icon:Ki,label:"Text",handler:d},{icon:ln,label:"Email",handler:u}].map(({icon:b,label:N,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:N})]},N))}),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(pa,{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(Ua,{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(NMe,{card:s,variant:"classic"}),e.jsx(SMe,{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(pi,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{_d(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(Ua,{className:"h-4 w-4 text-[#d4a843]"})," Leave a Review"]}),s.show_refer_friend&&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(Bn,{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(zl,{className:"h-4 w-4 text-[#5a7a6f]"})," Connect with Me"]}),e.jsxs("button",{onClick:p,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(jd,{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,N)=>e.jsx("a",{href:b.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>_d(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()]||"🔗"},N))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#a0aec0]",children:"Powered by LevelUp"})})]}),e.jsx(kMe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function UXe({card:s}){switch(s.theme){case"luxury":return e.jsx(lEs,{card:s});case"bold":return e.jsx(cEs,{card:s});case"classic":return e.jsx(dEs,{card:s});case"standard":default:return e.jsx(oEs,{card:s})}}function uEs(){const s=Od();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(hEs,{slug:t})}function hEs({slug:s}){return e.jsx(mEs,{slug:s})}function mEs({slug:s}){var i;const{data:t,isLoading:n,error:r}=mRt(s);if(j.useEffect(()=>{t!=null&&t.id&&_d(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(UXe,{card:t})]})}function xRt({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,p]=j.useState(""),[f,x]=j.useState(""),[y,v]=j.useState(!1),[b,N]=j.useState(!1),S=async A=>{if(A.preventDefault(),!l.trim()){re.error("Please enter your name");return}v(!0);try{const{error:T}=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:f.trim()||null});if(T)throw T;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:f.trim()||void 0}}).catch(L=>console.error("Presentation lead notify failed:",L)),N(!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(Xr,{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(te,{htmlFor:"pres-lead-name",children:"Name *"}),e.jsx(xe,{id:"pres-lead-name",value:l,onChange:A=>o(A.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"pres-lead-phone",children:"Phone"}),e.jsx(xe,{id:"pres-lead-phone",type:"tel",value:u,onChange:A=>h(A.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"pres-lead-email",children:"Email"}),e.jsx(xe,{id:"pres-lead-email",type:"email",value:c,onChange:A=>d(A.target.value),placeholder:"you@example.com"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"pres-lead-intent",children:"I'm looking to..."}),e.jsxs(Ns,{value:m,onValueChange:p,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select one"})}),e.jsxs(js,{children:[e.jsx(et,{value:"buy",children:"Buy a home"}),e.jsx(et,{value:"sell",children:"Sell my home"}),e.jsx(et,{value:"both",children:"Buy & Sell"}),e.jsx(et,{value:"other",children:"Something else"})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"pres-lead-message",children:"Message (optional)"}),e.jsx(xe,{id:"pres-lead-message",value:f,onChange:A=>x(A.target.value),placeholder:"Anything you'd like us to know"})]}),e.jsx(U,{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 pEs(){const s=Od();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(fEs,{shareToken:t})}function fEs({shareToken:s}){var f;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 N=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();N=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:N?[N.first_name,N.last_name].filter(Boolean).join(" "):void 0,contact_email:(N==null?void 0:N.email)||void 0,contact_phone:(N==null?void 0:N.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 N=x.replace("/play/","/embed/"),S=N.includes("?")?"&":"?";return`${N}${S}responsive=true`}if(x.includes("iframe.mediadelivery.net")){const N=x.includes("?")?"&":"?";return`${x}${N}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),p=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:[p!=null&&p.video_url?e.jsx("div",{className:"relative w-full rounded-xl overflow-hidden shadow-lg bg-gray-900",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:h(p.video_url),className:"absolute inset-0 w-full h-full border-0",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,loading:"lazy"})}):p!=null&&p.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:p.image_url,alt:p.title,className:"w-full h-auto object-cover",loading:"lazy"})}):e.jsxs("div",{className:"aspect-video bg-gradient-to-br from-blue-50 to-slate-100 rounded-xl flex flex-col items-center justify-center shadow-lg",children:[e.jsx("span",{className:"text-5xl mb-3",children:p==null?void 0:p.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:p==null?void 0:p.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:p==null?void 0:p.description})]}),(p==null?void 0:p.text)&&e.jsx("div",{className:"mt-4 p-4 bg-white rounded-lg border text-gray-700 text-sm leading-relaxed prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:p.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:m.map((x,y)=>e.jsx("button",{onClick:()=>l(y),className:Mt("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?"}),(f=t.cta_url)!=null&&f.trim()?e.jsxs(U,{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(Sr,{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(xRt,{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 gEs(){const{user:s}=vs(),t=Sa(),{data:n}=Sj();return ct({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 ygr(s){const{user:t}=vs();return ct({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 yRt(s){const{user:t}=vs(),n=Qt();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]),ct({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 xEs(){const s=Qt(),t=Sa();return yt({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"]}),ka({title:"Open house created!"})},onError:n=>{ka({title:"Error",description:n.message,variant:"destructive"})}})}function vRt(){const s=Qt();return yt({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 yEs(){const s=Qt();return yt({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"]}),ka({title:"Open house deleted"})}})}function bRt(s){return ct({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 vEs(s){const{user:t}=vs();return ct({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 bEs(s){return ct({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 _Es(){return yt({mutationFn:async s=>{const{error:t}=await q.from("open_house_survey_responses").insert(s);if(t)throw t}})}function wEs(s){const{user:t}=vs();return ct({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 jEs(){const s=Qt();return yt({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 NEs(){const s=Qt();return yt({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 kEs(){const s=Qt();return yt({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 SEs(){const s=Qt();return yt({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 CEs(){return yt({mutationFn:async s=>{const{data:t,error:n}=await q.from("open_house_visitors").insert(s).select("id").single();if(n)throw n;return t}})}function AEs(){return yt({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 EEs(){return yt({mutationFn:async s=>{await q.rpc("increment_open_house_scan",{_slug:s})}})}async function _Rt(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 TEs(s){const{user:t}=vs();return ct({queryKey:["open-house-rooms",s],queryFn:()=>_Rt(s),enabled:!!t&&!!s})}function MEs(s){return ct({queryKey:["public-open-house-rooms",s],queryFn:()=>_Rt(s),enabled:!!s})}function PEs(){const s=Qt();return yt({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 LEs(){const s=Qt();return yt({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 IEs(){const s=Qt();return yt({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 REs(){const s=Qt();return yt({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 DEs(){const s=Qt();return yt({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 OEs(){const s=Qt();return yt({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 FEs(){const s=Qt();return yt({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 zEs(s){const{user:t}=vs();return ct({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 BEs(){const s=Qt();return yt({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 AMe="Switch",[UEs,vgr]=Up(AMe),[qEs,$Es]=UEs(AMe),wRt=j.forwardRef((s,t)=>{const{__scopeSwitch:n,name:r,checked:a,defaultChecked:i,required:l,disabled:o,value:c="on",onCheckedChange:d,form:u,...h}=s,[m,p]=j.useState(null),f=Uo(t,N=>p(N)),x=j.useRef(!1),y=m?u||!!m.closest("form"):!0,[v,b]=Sx({prop:a,defaultProp:i??!1,onChange:d,caller:AMe});return e.jsxs(qEs,{scope:n,checked:v,disabled:o,children:[e.jsx(si.button,{type:"button",role:"switch","aria-checked":v,"aria-required":l,"data-state":SRt(v),"data-disabled":o?"":void 0,disabled:o,value:c,...h,ref:f,onClick:va(s.onClick,N=>{b(S=>!S),y&&(x.current=N.isPropagationStopped(),x.current||N.stopPropagation())})}),y&&e.jsx(kRt,{control:m,bubbles:!x.current,name:r,value:c,checked:v,required:l,disabled:o,form:u,style:{transform:"translateX(-100%)"}})]})});wRt.displayName=AMe;var jRt="SwitchThumb",NRt=j.forwardRef((s,t)=>{const{__scopeSwitch:n,...r}=s,a=$Es(jRt,n);return e.jsx(si.span,{"data-state":SRt(a.checked),"data-disabled":a.disabled?"":void 0,...r,ref:t})});NRt.displayName=jRt;var VEs="SwitchBubbleInput",kRt=j.forwardRef(({__scopeSwitch:s,control:t,checked:n,bubbles:r=!0,...a},i)=>{const l=j.useRef(null),o=Uo(l,i),c=Wne(n),d=Mne(t);return j.useEffect(()=>{const u=l.current;if(!u)return;const h=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(h,"checked").set;if(c!==n&&p){const f=new Event("click",{bubbles:r});p.call(u,n),u.dispatchEvent(f)}},[c,n,r]),e.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...a,tabIndex:-1,ref:o,style:{...a.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});kRt.displayName=VEs;function SRt(s){return s?"checked":"unchecked"}var CRt=wRt,HEs=NRt;const wn=j.forwardRef(({className:s,...t},n)=>e.jsx(CRt,{className:Mt("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(HEs,{className:Mt("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")})}));wn.displayName=CRt.displayName;const GEs=["Excellent","Good","Neutral","Bad","Very Bad"],WEs=[5,4,3,2,1];function KEs({questions:s,visitorId:t,onComplete:n,onSkip:r}){const a=_Es(),[i,l]=j.useState({}),o=s.filter(m=>m.question_type==="rating"),c=s.filter(m=>m.question_type!=="rating"),d=(m,p)=>{l(f=>({...f,[m]:{rating_value:p}}))},u=(m,p)=>{l(f=>({...f,[m]:{text_value:p}}))},h=async()=>{const m=Object.entries(i).filter(([,p])=>p.rating_value!=null||p.text_value&&p.text_value.trim()).map(([p,f])=>{var x;return{visitor_id:t,question_id:p,rating_value:f.rating_value??null,text_value:((x=f.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"}),GEs.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}),WEs.map(p=>{var f;return e.jsx("div",{className:"w-12 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>d(m.id,p),className:`w-6 h-6 rounded-full border-2 transition-all ${((f=i[m.id])==null?void 0:f.rating_value)===p?"bg-slate-900 border-slate-900":"border-slate-300 hover:border-slate-500"}`})},p)})]},m.id))]}),c.map(m=>{var p;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(Fs,{value:((p=i[m.id])==null?void 0:p.text_value)||"",onChange:f=>u(m.id,f.target.value),placeholder:"Your thoughts...",className:"h-16 text-sm resize-none rounded-xl border-slate-200"})]},m.id)}),e.jsx(U,{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(Et,{className:"h-5 w-5 animate-spin"}):"Submit Feedback"})]})}function Eqe(s){return/iframe\.mediadelivery\.net\/embed\//.test(s)}function YEs({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=p=>{p.key==="Escape"?c():p.key==="ArrowLeft"?d():p.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:Mt("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,p)=>e.jsx("button",{onClick:()=>a(p),className:"relative aspect-[4/3] rounded-xl overflow-hidden bg-white/5 group",children:m.kind==="video"?e.jsxs(e.Fragment,{children:[Eqe(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(Wr,{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(rd,{className:"h-6 w-6"})}),l.kind==="video"?Eqe(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(gi,{className:"h-6 w-6"})})]})]}):null}function ZEs({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:Mt("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"?Eqe(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(rd,{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(gi,{className:"h-4 w-4"})]})]})]})}const hOe={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:Ki},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:pa},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:Ur},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:yu}},XEs=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function QEs(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 JEs({openHouse:s,visitorId:t,visitorName:n,visitorEmail:r,visitorPhone:a,previewMode:i=!1}){var Oe;const l=s.profiles,o=((Oe=l==null?void 0:l.name)==null?void 0:Oe.split(" ").map(Se=>Se[0]).join("").slice(0,2))||"?",c=s.brand_color_override||null,[d,u]=j.useState(null),[h,m]=j.useState(""),[p,f]=j.useState(r||""),[x,y]=j.useState(a||""),[v,b]=j.useState(!1),[N,S]=j.useState(null),[A,T]=j.useState(""),[L,M]=j.useState(""),[I,R]=j.useState(""),[z,$]=j.useState([]),[H,V]=j.useState(""),[K,Z]=j.useState(""),[Q,le]=j.useState(""),[ue,se]=j.useState(""),ne=QEs(s.price),ie=s.tour_mode==="rooms",{data:ce=[]}=MEs(ie?s.id:void 0),je=[s.enable_question&&"question",s.enable_showing&&"showing",s.enable_disclosures&&"disclosure",s.enable_offer&&"offer"].filter(Boolean),be=Se=>{u(Se),m(""),T(""),M(""),R(""),$([]),V(""),Z(""),le(""),se("")},he=()=>{u(null)},ge=Se=>{$(Qe=>Qe.includes(Se)?Qe.filter(Ae=>Ae!==Se):[...Qe,Se])},ke=Se=>Se==="showing"?{preferred_date:A||null,preferred_time:L||null,alternate_date:I||null}:Se==="disclosure"?{requested_documents:z}:Se==="offer"?{offer_amount:H||null,financing:K||null,timeline:Q||null,pre_approved:ue||null}:{},Te=d?d==="showing"?!!A:d==="question"?h.trim().length>0:!0:!1,Me=async()=>{if(d){if(i){ka({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 Se=ke(d),{error:Qe}=await q.from("open_house_leads").insert({open_house_id:s.id,visitor_id:t,action_type:d,payload:{message:h.trim()||null,email:p.trim()||null,phone:x.trim()||null,visitor_name:n,...Se}});if(Qe)throw Qe;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:p.trim()||null,visitor_phone:x.trim()||null,extras:Se}}).catch(()=>{}),S(d),ka({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{he(),S(null)},1400)}catch(Se){ka({title:"Something went wrong",description:Se.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(ni,{className:"h-3.5 w-3.5"}),s.city,s.state?`, ${s.state}`:""," ",s.zip]}),ne&&e.jsx("p",{className:"text-3xl font-bold text-white mt-3",children:ne}),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(Xw,{className:"h-4 w-4"}),s.beds," bd"]}),s.baths!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(d0,{className:"h-4 w-4"}),s.baths," ba"]}),s.sqft!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(db,{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(Ea,{className:"h-12 w-12 ring-2 ring-white/20",style:c?{boxShadow:`0 0 0 2px ${c}`}:void 0,children:[e.jsx(Ci,{src:l.avatar_url||"",alt:l.name||""}),e.jsx(Ta,{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(ba,{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(ln,{className:"h-4 w-4"})})]})]}),ie&&ce.length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx(YEs,{rooms:ce}),e.jsx(ZEs,{rooms:ce})]}),je.length>0&&e.jsx("div",{className:"mt-5 grid grid-cols-1 sm:grid-cols-2 gap-3",children:je.map(Se=>{const Qe=hOe[Se],Ae=Qe.icon;return e.jsxs("button",{onClick:()=>be(Se),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(Ae,{className:"h-5 w-5"})}),e.jsx("span",{className:"font-medium text-sm",children:Qe.label})]},Se)})}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-8",children:"Powered by LevelUp Virtual Open House"})]}),e.jsx(my,{open:!!d,onOpenChange:Se=>!Se&&he(),children:e.jsx(g0,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:d&&e.jsxs(e.Fragment,{children:[e.jsxs(vv,{className:"text-left",children:[e.jsx(bv,{children:hOe[d].title}),e.jsxs(pG,{children:[(l==null?void 0:l.name)||"The agent"," will be notified by email."]})]}),N===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(zr,{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(te,{className:"text-xs",children:"Email"}),e.jsx(xe,{type:"email",value:p,onChange:Se=>f(Se.target.value),placeholder:"you@example.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Phone"}),e.jsx(xe,{type:"tel",value:x,onChange:Se=>y(Se.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(te,{className:"text-xs",children:"Preferred date *"}),e.jsx(xe,{type:"date",value:A,onChange:Se=>T(Se.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Preferred time"}),e.jsx(xe,{type:"time",value:L,onChange:Se=>M(Se.target.value),className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Alternate date (optional)"}),e.jsx(xe,{type:"date",value:I,onChange:Se=>R(Se.target.value),className:"mt-1"})]})]}),d==="disclosure"&&e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Which documents? (select all that apply)"}),e.jsx("div",{className:"mt-2 space-y-2",children:XEs.map(Se=>e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(xi,{checked:z.includes(Se),onCheckedChange:()=>ge(Se)}),e.jsx("span",{children:Se})]},Se))})]}),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(te,{className:"text-xs",children:"Estimated offer"}),e.jsx(xe,{value:H,onChange:Se=>V(Se.target.value),placeholder:"$",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Financing"}),e.jsxs(Ns,{value:K,onValueChange:Z,children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{placeholder:"Select..."})}),e.jsxs(js,{children:[e.jsx(et,{value:"Cash",children:"Cash"}),e.jsx(et,{value:"Conventional",children:"Conventional"}),e.jsx(et,{value:"FHA",children:"FHA"}),e.jsx(et,{value:"VA",children:"VA"}),e.jsx(et,{value:"Other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Timeline"}),e.jsxs(Ns,{value:Q,onValueChange:le,children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{placeholder:"Select..."})}),e.jsxs(js,{children:[e.jsx(et,{value:"ASAP",children:"ASAP"}),e.jsx(et,{value:"30 days",children:"30 days"}),e.jsx(et,{value:"60 days",children:"60 days"}),e.jsx(et,{value:"90+ days",children:"90+ days"})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Pre-approved?"}),e.jsxs(Ns,{value:ue,onValueChange:se,children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{placeholder:"Select..."})}),e.jsxs(js,{children:[e.jsx(et,{value:"Yes",children:"Yes"}),e.jsx(et,{value:"No",children:"No"}),e.jsx(et,{value:"In progress",children:"In progress"})]})]})]})]})]}),e.jsxs("div",{children:[e.jsxs(te,{className:"text-xs",children:["Message",d==="question"?" *":" (optional)"]}),e.jsx(Fs,{value:h,onChange:Se=>m(Se.target.value),placeholder:hOe[d].placeholder,rows:4,className:"mt-1"})]}),e.jsx(U,{onClick:Me,disabled:v||!Te,className:"w-full h-12 text-white hover:opacity-90",style:c?{backgroundColor:c}:void 0,children:v?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const eTs=kN({first_name:sl().trim().min(1,"First name is required").max(50),last_name:sl().trim().max(50).optional(),email:sl().trim().email("Please enter a valid email").max(255).optional().or(ux("")),phone:sl().trim().max(20).optional().or(ux(""))}),tTs=[{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 ARt({slug:s}={}){var Ve;const t=Di(),n=s||t.slug,[r]=fc(),a=r.get("kiosk")==="1"||r.get("mode")==="kiosk",i=8,{data:l,isLoading:o,error:c}=bRt(n),d=CEs(),u=AEs(),h=EEs(),m=j.useRef(!1),[p,f]=j.useState("welcome"),[x,y]=j.useState(null),[v,b]=j.useState({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),[N,S]=j.useState(""),[A,T]=j.useState(!1),[L,M]=j.useState(!1),[I,R]=j.useState(""),[z,$]=j.useState(""),[H,V]=j.useState(i),K=j.useCallback(()=>{y(null),b({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),S(""),T(!1),M(!1),R(""),$(""),V(i),f(a?"info":"welcome")},[a]),Z=j.useCallback((qe,Ze)=>{l!=null&&l.id&&q.functions.invoke("guestbook-lead-notify",{body:{open_house_id:l.id,visitor_id:qe,first_name:Ze.first_name??v.first_name,last_name:Ze.last_name??v.last_name,email:Ze.email??v.email,phone:Ze.phone??v.phone,visitor_intent:Ze.visitor_intent??N,message:Ze.message,wants_market_updates:Ze.wants_market_updates??A,has_agent:Ze.has_agent??L,working_with_agent_name:Ze.working_with_agent_name??I,visitor_address:Ze.visitor_address??v.visitor_address}}).catch(Ue=>console.error("Guest book lead notify failed:",Ue))},[l==null?void 0:l.id,v,N,A,L,I]);j.useEffect(()=>{if(!a||p!=="done")return;V(i);const qe=setInterval(()=>{V(Ze=>Ze<=1?(clearInterval(qe),K(),0):Ze-1)},1e3);return()=>clearInterval(qe)},[a,p,K]),j.useEffect(()=>{if(!a)return;f(Ze=>Ze==="welcome"?"info":Ze);let qe=null;return(async()=>{var Ze,Ue;try{qe=await((Ue=(Ze=navigator.wakeLock)==null?void 0:Ze.request)==null?void 0:Ue.call(Ze,"screen"))}catch{}})(),()=>{var Ze;try{(Ze=qe==null?void 0:qe.release)==null||Ze.call(qe)}catch{}}},[a]);const Q=j.useCallback(()=>{var Ze;const qe=document.documentElement;document.fullscreenElement||(Ze=qe.requestFullscreen||qe.webkitRequestFullscreen)==null||Ze.call(qe).catch(()=>{})},[]),{data:le,isLoading:ue}=bEs(l==null?void 0:l.id),se=!!(l!=null&&l.enable_survey),ne=(l==null?void 0:l.ask_visitor_intent)!==!1,ie=(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(()=>{p==="pending_survey"&&(ue||f(se&&((le==null?void 0:le.length)??0)>0?"survey":"done"))},[p,ue,se,le]);const ce=qe=>{if(!qe)return"";const[Ze,Ue]=qe.split(":"),Ye=parseInt(Ze),Ge=Ye>=12?"PM":"AM";return`${Ye>12?Ye-12:Ye||12}:${Ue} ${Ge}`},je=async()=>{$("");const qe=eTs.safeParse(v);if(!qe.success){$(qe.error.issues[0].message);return}if(!v.email&&!v.phone){$("Please provide either an email or phone number");return}const Ze=(l==null?void 0:l.kind)==="virtual";let Ue=null;if(!x&&(l!=null&&l.id))try{const Ye=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:ie&&v.visitor_address.trim()?v.visitor_address.trim():void 0,wants_market_updates:A,has_agent:L,working_with_agent_name:L&&I.trim()?I.trim():void 0,partial_signin:Ze?!1:ne});Ue=Ye.id,y(Ye.id)}catch{if(Ze){$("We could not start the virtual tour. Please try again.");return}}if(Ze){ne?f("intent"):(Ue&&Z(Ue,{}),f("done"));return}if(!ne){Ue&&Z(Ue,{}),se?!ue&&le&&le.length>0?f("survey"):f("pending_survey"):f("done");return}f("intent")},be=async qe=>{S(qe);try{let Ze=x;if(Ze?await u.mutateAsync({visitor_id:Ze,visitor_intent:qe,wants_market_updates:A,has_agent:L,working_with_agent_name:L&&I.trim()?I.trim():null,partial_signin:!1}):(Ze=(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:ie&&v.visitor_address.trim()?v.visitor_address.trim():void 0,visitor_intent:qe,wants_market_updates:A,has_agent:L,working_with_agent_name:L&&I.trim()?I.trim():void 0,partial_signin:!1})).id,y(Ze)),Ze&&Z(Ze,{visitor_intent:qe,wants_market_updates:A,has_agent:L,working_with_agent_name:L&&I.trim()?I.trim():null}),(l==null?void 0:l.kind)==="virtual"){f("done");return}se?!ue&&le&&le.length>0?f("survey"):f("pending_survey"):f("done")}catch{$("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(ra,{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 he=l.profiles,ge=((Ve=he==null?void 0:he.name)==null?void 0:Ve.split(" ").map(qe=>qe[0]).join("").slice(0,2))||"?",ke=l.event_type==="community",Te=l.kind==="virtual",Me=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(Te&&(Me||p==="done"))return!Me&&!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"})]}),Me&&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(JEs,{openHouse:l,visitorId:Me?"preview":x,visitorName:Me?"Preview Visitor":`${v.first_name} ${v.last_name}`.trim(),visitorEmail:Me?"":v.email,visitorPhone:Me?"":v.phone,previewMode:Me})]});const Se=`${Te?"Virtual Open House":ke?"Community Event":"Open House"} — ${l.property_address}`,Ae=[[l.city,l.state].filter(Boolean).join(", "),l.event_date?Gs(new Date(l.event_date+"T00:00:00"),"EEE, MMM d"):null,he!=null&&he.name?`Hosted by ${he.name}`:null].filter(Boolean).join(" · "),Fe=l.photo_url||"",Ne=Fe&&Fe.includes("/storage/v1/object/public/")?Fe.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":Fe||"https://dashboard.relevelup.com/og-image.png",$e=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:Se}),e.jsx("meta",{name:"description",content:Ae||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:title",content:Se}),e.jsx("meta",{property:"og:description",content:Ae||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:image",content:Ne}),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:$e}),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:Se}),e.jsx("meta",{name:"twitter:description",content:Ae||`Sign in to ${l.property_address}`}),e.jsx("meta",{name:"twitter:image",content:Ne}),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(Ea,{className:"h-16 w-16 mx-auto mb-3 ring-2 ring-white/20",children:[e.jsx(Ci,{src:(he==null?void 0:he.avatar_url)||"",alt:(he==null?void 0:he.name)||""}),e.jsx(Ta,{className:"bg-white/10 text-white text-lg",children:ge})]}),e.jsx("p",{className:"text-white/60 text-sm",children:he==null?void 0:he.name}),(he==null?void 0:he.title)&&e.jsx("p",{className:"text-white/40 text-xs",children:he.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(ni,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Te&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pa,{className:"h-3 w-3"}),Gs(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(Yr,{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:ke?e.jsx(_i,{className:"h-5 w-5 text-white"}):e.jsx(ra,{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(ni,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Te&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pa,{className:"h-3 w-3"}),Gs(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(Yr,{className:"h-3 w-3"}),ce(l.start_time),l.end_time?` – ${ce(l.end_time)}`:""]})]})]})]})]})}),e.jsxs("div",{className:"p-6",children:[p==="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(U,{onClick:()=>f("info"),className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Sign In ",e.jsx(Oa,{className:"h-5 w-5 ml-2"})]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Quick & easy — takes 30 seconds"})]}),p==="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:()=>f("welcome"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(Aa,{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(te,{className:"text-slate-600 text-xs",children:"First Name *"}),e.jsx(xe,{value:v.first_name,onChange:qe=>b(Ze=>({...Ze,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(te,{className:"text-slate-600 text-xs",children:"Last Name"}),e.jsx(xe,{value:v.last_name,onChange:qe=>b(Ze=>({...Ze,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(te,{className:"text-slate-600 text-xs",children:"Email"}),e.jsx(xe,{type:"email",value:v.email,onChange:qe=>b(Ze=>({...Ze,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(te,{className:"text-slate-600 text-xs",children:"Phone"}),e.jsx(xe,{type:"tel",value:v.phone,onChange:qe=>b(Ze=>({...Ze,phone:qe.target.value})),placeholder:"(555) 123-4567",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),ie&&e.jsxs("div",{children:[e.jsx(te,{className:"text-slate-600 text-xs",children:"Your Home Address"}),e.jsx(xe,{value:v.visitor_address,onChange:qe=>b(Ze=>({...Ze,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=>T(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:L?"Yes":"No"}),e.jsx(wn,{checked:L,onCheckedChange:M})]})]}),L&&e.jsx(xe,{value:I,onChange:qe=>R(qe.target.value),placeholder:"Agent's name",className:"mt-1 h-10 rounded-xl border-slate-200 text-sm"})]}),z&&e.jsx("p",{className:"text-destructive text-sm",children:z}),e.jsxs(U,{onClick:je,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",e.jsx(Oa,{className:"h-5 w-5 ml-2"})]})]}),p==="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:()=>f("info"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(Aa,{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:tTs.map(qe=>e.jsxs("button",{onClick:()=>be(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))}),z&&e.jsx("p",{className:"text-destructive text-sm text-center",children:z})]}),p==="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..."})]}),p==="survey"&&x&&le&&e.jsx(KEs,{questions:le,visitorId:x,onComplete:()=>f("done"),onSkip:()=>f("done")}),p==="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(zr,{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,". ",ke?"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(Ur,{className:"h-4 w-4"}),"View Seller's Disclosures"]}),(he==null?void 0:he.name)&&e.jsxs("p",{className:"text-sm text-slate-400",children:["Your host today: ",e.jsx("strong",{className:"text-slate-600",children:he.name})]}),a&&e.jsxs("div",{className:"pt-4 space-y-3",children:[e.jsx(U,{onClick:K,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 ",H,"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(bq,{className:"h-3 w-3"})," Tablet Mode"]}),e.jsx("button",{onClick:Q,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(KX,{className:"h-3 w-3"})})]})]})})]})}function sTs(s){return ct({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 nTs(){const s=Qt();return yt({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 rTs(s){const t=Qt();return yt({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 aTs(s){const t=Qt();return yt({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 iTs=kN({first_name:sl().trim().min(1,"First name is required").max(50),last_name:sl().trim().max(50).optional(),email:sl().trim().email("Please enter a valid email").max(255),phone:sl().trim().max(20).optional().or(ux("")),message:sl().trim().max(500).optional().or(ux(""))}),mOe=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}`},oTs=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 ERt({slug:s}={}){const t=Di(),n=s||t.slug,{data:r,isLoading:a,error:i}=bRt(n),l=nTs(),[o,c]=j.useState({first_name:"",last_name:"",email:"",phone:"",message:""}),[d,u]=j.useState(!1),[h,m]=j.useState(""),[p,f]=j.useState(""),[x,y]=j.useState(!1),v=j.useMemo(()=>oTs(r==null?void 0:r.event_date),[r==null?void 0:r.event_date]),b=j.useMemo(()=>{const M=r==null?void 0:r.photo_url;return M?M.includes("/storage/v1/object/public/")?M.replace("/object/public/","/render/image/public/")+"?width=1600&quality=80":M:""},[r]),N=r==null?void 0:r.profiles,S=[r==null?void 0:r.city,r==null?void 0:r.state].filter(Boolean).join(", "),A=async()=>{f("");const M=iTs.safeParse(o);if(!M.success){f(M.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(I){f((I==null?void 0:I.message)||"Something went wrong. Please try again.")}},T=j.useMemo(()=>{if(!r||!v)return"";const M=V=>String(V).padStart(2,"0"),I=`${v.getFullYear()}${M(v.getMonth()+1)}${M(v.getDate())}`,R=(r.start_time||"12:00").slice(0,5).replace(":","")+"00",z=(r.end_time||"14:00").slice(0,5).replace(":","")+"00",$=encodeURIComponent(`Open House — ${r.property_address}`),H=encodeURIComponent([r.property_address,S,r.zip].filter(Boolean).join(", "));return`https://calendar.google.com/calendar/render?action=TEMPLATE&text=${$}&dates=${I}T${R}/${I}T${z}&location=${H}`},[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(ra,{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 L=`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 ${Gs(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(pa,{className:"h-4 w-4 text-[#d4b978]"}),Gs(v,"EEEE, MMMM d, yyyy")]}),r.start_time&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Yr,{className:"h-4 w-4 text-[#d4b978]"}),mOe(r.start_time),r.end_time?` – ${mOe(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(boe,{icon:e.jsx(ra,{className:"h-4 w-4"}),label:"Price",value:`$${Number(r.price).toLocaleString()}`}):null,r.beds?e.jsx(boe,{icon:e.jsx(C4,{className:"h-4 w-4"}),label:"Beds",value:String(r.beds)}):null,r.baths?e.jsx(boe,{icon:e.jsx(d0,{className:"h-4 w-4"}),label:"Baths",value:String(r.baths)}):null,r.sqft?e.jsx(boe,{icon:e.jsx(I4,{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(zr,{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?Gs(v,"EEEE, MMMM d"):"soon",r.start_time?` at ${mOe(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:[T&&e.jsx(U,{asChild:!0,className:"bg-[#1b3a4b] hover:bg-[#25505f]",children:e.jsxs("a",{href:T,target:"_blank",rel:"noreferrer",children:[e.jsx(sv,{className:"mr-2 h-4 w-4"}),"Add to calendar"]})}),e.jsx(U,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:L,target:"_blank",rel:"noreferrer",children:[e.jsx(ni,{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(te,{htmlFor:"rsvp-first",children:"First name *"}),e.jsx(xe,{id:"rsvp-first",value:o.first_name,onChange:M=>c(I=>({...I,first_name:M.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"rsvp-last",children:"Last name"}),e.jsx(xe,{id:"rsvp-last",value:o.last_name,onChange:M=>c(I=>({...I,last_name:M.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"rsvp-email",children:"Email *"}),e.jsx(xe,{id:"rsvp-email",type:"email",value:o.email,onChange:M=>c(I=>({...I,email:M.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"rsvp-phone",children:"Phone"}),e.jsx(xe,{id:"rsvp-phone",type:"tel",value:o.phone,onChange:M=>c(I=>({...I,phone:M.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(wn,{checked:d,onCheckedChange:u})]}),d&&e.jsx(xe,{value:h,onChange:M=>m(M.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(te,{htmlFor:"rsvp-msg",children:"Anything you'd like us to know?"}),e.jsx(Fs,{id:"rsvp-msg",rows:3,value:o.message,onChange:M=>c(I=>({...I,message:M.target.value})),className:"resize-y"})]}),p&&e.jsx("p",{className:"mt-3 text-sm text-destructive",children:p}),e.jsx(U,{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(Oa,{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."})]})}),(N==null?void 0:N.name)&&e.jsxs("section",{className:"rounded-2xl bg-white/70 border border-[#e4dcd3] p-5 flex items-center gap-4",children:[e.jsxs(Ea,{className:"h-14 w-14",children:[e.jsx(Ci,{src:N.avatar_url||void 0,alt:N.name}),e.jsx(Ta,{children:N.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:N.name}),N.title&&e.jsx("p",{className:"text-sm text-[#5b6b72]",children:N.title}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-4 text-sm text-[#406E71]",children:[N.phone&&e.jsx("a",{href:`tel:${N.phone}`,children:N.phone}),N.email&&e.jsx("a",{href:`mailto:${N.email}`,className:"truncate",children:N.email})]})]})]}),e.jsx("div",{className:"text-center",children:e.jsxs("a",{href:L,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1.5 text-sm text-[#406E71] hover:underline",children:[e.jsx(ni,{className:"h-4 w-4"}),"Get directions to ",r.property_address]})})]})]})}function boe({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 bgr(s){const{user:t}=vs();return ct({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 _gr(){const s=Qt(),{user:t}=vs();return yt({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 wgr(){const s=Qt();return yt({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 lTs(s){return ct({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 Z4=(s,t,n)=>n>t?t:n{},qV=()=>{};const hP={},MRt=s=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(s);function PRt(s){return typeof s=="object"&&s!==null}const LRt=s=>/^0[^.\s]+$/u.test(s);function IRt(s){let t;return()=>(t===void 0&&(t=s()),t)}const nN=s=>s,dTs=(s,t)=>n=>t(s(n)),Qne=(...s)=>s.reduce(dTs),cee=(s,t,n)=>{const r=t-s;return r===0?1:(n-s)/r};class HXe{constructor(){this.subscriptions=[]}add(t){return VXe(this.subscriptions,t),()=>pCe(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,B2=s=>s/1e3;function RRt(s,t){return t?s*(1e3/t):0}const DRt=(s,t,n)=>(((1-3*n+3*t)*s+(3*n-6*t))*s+3*t)*s,uTs=1e-7,hTs=12;function mTs(s,t,n,r,a){let i,l,o=0;do l=t+(n-t)/2,i=DRt(l,r,a)-s,i>0?n=l:t=l;while(Math.abs(i)>uTs&&++omTs(i,0,1,s,n);return i=>i===0||i===1?i:DRt(a(i),t,r)}const ORt=s=>t=>t<=.5?s(2*t)/2:(2-s(2*(1-t)))/2,FRt=s=>t=>1-s(1-t),zRt=Jne(.33,1.53,.69,.99),GXe=FRt(zRt),BRt=ORt(GXe),URt=s=>s>=1?1:(s*=2)<1?.5*GXe(s):.5*(2-Math.pow(2,-10*(s-1))),WXe=s=>1-Math.sin(Math.acos(s)),qRt=FRt(WXe),$Rt=ORt(WXe),pTs=Jne(.42,0,1,1),fTs=Jne(0,0,.58,1),VRt=Jne(.42,0,.58,1),gTs=s=>Array.isArray(s)&&typeof s[0]!="number",HRt=s=>Array.isArray(s)&&typeof s[0]=="number",Smt={linear:nN,easeIn:pTs,easeInOut:VRt,easeOut:fTs,circIn:WXe,circInOut:$Rt,circOut:qRt,backIn:GXe,backInOut:BRt,backOut:zRt,anticipate:URt},xTs=s=>typeof s=="string",Cmt=s=>{if(HRt(s)){qV(s.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,r,a]=s;return Jne(t,n,r,a)}else if(xTs(s))return qV(Smt[s]!==void 0,`Invalid easing type '${s}'`,"invalid-easing-type"),Smt[s];return s},_oe=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Amt={value:null,addProjectionMetrics:null};function yTs(s,t){let n=new Set,r=new Set,a=!1,i=!1;const l=new WeakSet;let o={delta:0,timestamp:0,isProcessing:!1},c=0;function d(h){l.has(h)&&(u.schedule(h),s()),c++,h(o)}const u={schedule:(h,m=!1,p=!1)=>{const x=p&&a?n:r;return m&&l.add(h),x.add(h),h},cancel:h=>{r.delete(h),l.delete(h)},process:h=>{if(o=h,a){i=!0;return}a=!0;const m=n;n=r,r=m,n.forEach(d),t&&Amt.value&&Amt.value.frameloop[t].push(c),c=0,n.clear(),a=!1,i&&(i=!1,u.process(h))}};return u}const vTs=40;function GRt(s,t){let n=!1,r=!0;const a={delta:0,timestamp:0,isProcessing:!1},i=()=>n=!0,l=_oe.reduce((N,S)=>(N[S]=yTs(i,t?S:void 0),N),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:u,update:h,preRender:m,render:p,postRender:f}=l,x=()=>{const N=hP.useManualTiming,S=N?a.timestamp:performance.now();n=!1,N||(a.delta=r?1e3/60:Math.max(Math.min(S-a.timestamp,vTs),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),p.process(a),f.process(a),a.isProcessing=!1,n&&t&&(r=!1,s(x))},y=()=>{n=!0,r=!0,a.isProcessing||s(x)};return{schedule:_oe.reduce((N,S)=>{const A=l[S];return N[S]=(T,L=!1,M=!1)=>(n||y(),A.schedule(T,L,M)),N},{}),cancel:N=>{for(let S=0;S<_oe.length;S++)l[_oe[S]].cancel(N)},state:a,steps:l}}const{schedule:mm,cancel:mP,state:Ky,steps:pOe}=GRt(typeof requestAnimationFrame<"u"?requestAnimationFrame:nN,!0);let C5e;function bTs(){C5e=void 0}const eb={now:()=>(C5e===void 0&&eb.set(Ky.isProcessing||hP.useManualTiming?Ky.timestamp:performance.now()),C5e),set:s=>{C5e=s,queueMicrotask(bTs)}},WRt=s=>t=>typeof t=="string"&&t.startsWith(s),KRt=WRt("--"),_Ts=WRt("var(--"),KXe=s=>_Ts(s)?wTs.test(s.split("/*")[0].trim()):!1,wTs=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function Emt(s){return typeof s!="string"?!1:s.split("/*")[0].includes("var(--")}const yG={test:s=>typeof s=="number",parse:parseFloat,transform:s=>s},dee={...yG,transform:s=>Z4(0,1,s)},woe={...yG,default:1},kQ=s=>Math.round(s*1e5)/1e5,YXe=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function jTs(s){return s==null}const NTs=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,ZXe=(s,t)=>n=>!!(typeof n=="string"&&NTs.test(n)&&n.startsWith(s)||t&&!jTs(n)&&Object.prototype.hasOwnProperty.call(n,t)),YRt=(s,t,n)=>r=>{if(typeof r!="string")return r;const[a,i,l,o]=r.match(YXe);return{[s]:parseFloat(a),[t]:parseFloat(i),[n]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},kTs=s=>Z4(0,255,s),fOe={...yG,transform:s=>Math.round(kTs(s))},VD={test:ZXe("rgb","red"),parse:YRt("red","green","blue"),transform:({red:s,green:t,blue:n,alpha:r=1})=>"rgba("+fOe.transform(s)+", "+fOe.transform(t)+", "+fOe.transform(n)+", "+kQ(dee.transform(r))+")"};function STs(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 Tqe={test:ZXe("#"),parse:STs,transform:VD.transform},ere=s=>({test:t=>typeof t=="string"&&t.endsWith(s)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${s}`}),kT=ere("deg"),B4=ere("%"),fo=ere("px"),CTs=ere("vh"),ATs=ere("vw"),Tmt={...B4,parse:s=>B4.parse(s)/100,transform:s=>B4.transform(s*100)},gU={test:ZXe("hsl","hue"),parse:YRt("hue","saturation","lightness"),transform:({hue:s,saturation:t,lightness:n,alpha:r=1})=>"hsla("+Math.round(s)+", "+B4.transform(kQ(t))+", "+B4.transform(kQ(n))+", "+kQ(dee.transform(r))+")"},dx={test:s=>VD.test(s)||Tqe.test(s)||gU.test(s),parse:s=>VD.test(s)?VD.parse(s):gU.test(s)?gU.parse(s):Tqe.parse(s),transform:s=>typeof s=="string"?s:s.hasOwnProperty("red")?VD.transform(s):gU.transform(s),getAnimatableNone:s=>{const t=dx.parse(s);return t.alpha=0,dx.transform(t)}},ETs=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function TTs(s){var t,n;return isNaN(s)&&typeof s=="string"&&(((t=s.match(YXe))==null?void 0:t.length)||0)+(((n=s.match(ETs))==null?void 0:n.length)||0)>0}const ZRt="number",XRt="color",MTs="var",PTs="var(",Mmt="${}",LTs=/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 $V(s){const t=s.toString(),n=[],r={color:[],number:[],var:[]},a=[];let i=0;const o=t.replace(LTs,c=>(dx.test(c)?(r.color.push(i),a.push(XRt),n.push(dx.parse(c))):c.startsWith(PTs)?(r.var.push(i),a.push(MTs),n.push(c)):(r.number.push(i),a.push(ZRt),n.push(parseFloat(c))),++i,Mmt)).split(Mmt);return{values:n,split:o,indexes:r,types:a}}function ITs(s){return $V(s).values}function QRt({split:s,types:t}){const n=s.length;return r=>{let a="";for(let i=0;itypeof s=="number"?0:dx.test(s)?dx.getAnimatableNone(s):s,OTs=(s,t)=>typeof s=="number"?t!=null&&t.trim().endsWith("/")?s:0:DTs(s);function FTs(s){const t=$V(s);return QRt(t)(t.values.map((r,a)=>OTs(r,t.split[a])))}const aS={test:TTs,parse:ITs,createTransformer:RTs,getAnimatableNone:FTs};function gOe(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 zTs({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=gOe(c,o,s+1/3),i=gOe(c,o,s),l=gOe(c,o,s-1/3)}return{red:Math.round(a*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function fCe(s,t){return n=>n>0?t:s}const rp=(s,t,n)=>s+(t-s)*n,xOe=(s,t,n)=>{const r=s*s,a=n*(t*t-r)+r;return a<0?0:Math.sqrt(a)},BTs=[Tqe,VD,gU],UTs=s=>BTs.find(t=>t.test(s));function Pmt(s){const t=UTs(s);if(TMe(!!t,`'${s}' is not an animatable color. Use the equivalent color code instead.`,"color-not-animatable"),!t)return!1;let n=t.parse(s);return t===gU&&(n=zTs(n)),n}const Lmt=(s,t)=>{const n=Pmt(s),r=Pmt(t);if(!n||!r)return fCe(s,t);const a={...n};return i=>(a.red=xOe(n.red,r.red,i),a.green=xOe(n.green,r.green,i),a.blue=xOe(n.blue,r.blue,i),a.alpha=rp(n.alpha,r.alpha,i),VD.transform(a))},Mqe=new Set(["none","hidden"]);function qTs(s,t){return Mqe.has(s)?n=>n<=0?s:t:n=>n>=1?t:s}function $Ts(s,t){return n=>rp(s,t,n)}function XXe(s){return typeof s=="number"?$Ts:typeof s=="string"?KXe(s)?fCe:dx.test(s)?Lmt:GTs:Array.isArray(s)?JRt:typeof s=="object"?dx.test(s)?Lmt:VTs:fCe}function JRt(s,t){const n=[...s],r=n.length,a=s.map((i,l)=>XXe(i)(i,t[l]));return i=>{for(let l=0;l{for(const i in r)n[i]=r[i](a);return n}}function HTs(s,t){const n=[],r={color:0,var:0,number:0};for(let a=0;a{const n=aS.createTransformer(t),r=$V(s),a=$V(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?Mqe.has(s)&&!a.values.length||Mqe.has(t)&&!r.values.length?qTs(s,t):Qne(JRt(HTs(r,a),a.values),n):(TMe(!0,`Complex values '${s}' and '${t}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,"complex-values-different"),fCe(s,t))};function eDt(s,t,n){return typeof s=="number"&&typeof t=="number"&&typeof n=="number"?rp(s,t,n):XXe(s)(s,t)}const WTs=s=>{const t=({timestamp:n})=>s(n);return{start:(n=!0)=>mm.update(t,n),stop:()=>mP(t),now:()=>Ky.isProcessing?Ky.timestamp:eb.now()}},tDt=(s,t,n=10)=>{let r="";const a=Math.max(Math.round(t/n),2);for(let i=0;i=gCe?1/0:t}function KTs(s,t=100,n){const r=n({...s,keyframes:[0,t]}),a=Math.min(QXe(r),gCe);return{type:"keyframes",ease:i=>r.next(a*i).value/t,duration:B2(a)}}const mf={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 Pqe(s,t){return s*Math.sqrt(1-t*t)}const YTs=12;function ZTs(s,t,n){let r=n;for(let a=1;a{const u=d*l,h=u*s,m=u-n,p=Pqe(d,l),f=Math.exp(-h);return yOe-m/p*f},i=d=>{const h=d*l*s,m=h*n+n,p=Math.pow(l,2)*Math.pow(d,2)*s,f=Math.exp(-h),x=Pqe(Math.pow(d,2),l);return(-a(d)+yOe>0?-1:1)*((m-p)*f)/x}):(a=d=>{const u=Math.exp(-d*s),h=(d-n)*s+1;return-yOe+u*h},i=d=>{const u=Math.exp(-d*s),h=(n-d)*(s*s);return u*h});const o=5/s,c=ZTs(a,i,o);if(s=A_(s),isNaN(c))return{stiffness:mf.stiffness,damping:mf.damping,duration:s};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:l*2*Math.sqrt(r*d),duration:s}}}const QTs=["duration","bounce"],JTs=["stiffness","damping","mass"];function Imt(s,t){return t.some(n=>s[n]!==void 0)}function e6s(s){let t={velocity:mf.velocity,stiffness:mf.stiffness,damping:mf.damping,mass:mf.mass,isResolvedFromDuration:!1,...s};if(!Imt(s,JTs)&&Imt(s,QTs))if(t.velocity=0,s.visualDuration){const n=s.visualDuration,r=2*Math.PI/(n*1.2),a=r*r,i=2*Z4(.05,1,1-(s.bounce||0))*Math.sqrt(a);t={...t,mass:mf.mass,stiffness:a,damping:i}}else{const n=XTs({...s,velocity:0});t={...t,...n,mass:mf.mass},t.isResolvedFromDuration=!0}return t}function xCe(s=mf.visualDuration,t=mf.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:p}=e6s({...n,velocity:-B2(n.velocity||0)}),f=m||0,x=d/(2*Math.sqrt(c*u)),y=l-i,v=B2(Math.sqrt(c/u)),b=Math.abs(y)<5;r||(r=b?mf.restSpeed.granular:mf.restSpeed.default),a||(a=b?mf.restDelta.granular:mf.restDelta.default);let N,S,A,T,L,M;if(x<1)A=Pqe(v,x),T=(f+x*v*y)/A,N=R=>{const z=Math.exp(-x*v*R);return l-z*(T*Math.sin(A*R)+y*Math.cos(A*R))},L=x*v*T+y*A,M=x*v*y-T*A,S=R=>Math.exp(-x*v*R)*(L*Math.sin(A*R)+M*Math.cos(A*R));else if(x===1){N=z=>l-Math.exp(-v*z)*(y+(f+v*y)*z);const R=f+v*y;S=z=>Math.exp(-v*z)*(v*R*z-f)}else{const R=v*Math.sqrt(x*x-1);N=V=>{const K=Math.exp(-x*v*V),Z=Math.min(R*V,300);return l-K*((f+x*v*y)*Math.sinh(Z)+R*y*Math.cosh(Z))/R};const z=(f+x*v*y)/R,$=x*v*z-y*R,H=x*v*y-z*R;S=V=>{const K=Math.exp(-x*v*V),Z=Math.min(R*V,300);return K*($*Math.sinh(Z)+H*Math.cosh(Z))}}const I={calculatedDuration:p&&h||null,velocity:R=>A_(S(R)),next:R=>{if(!p&&x<1){const $=Math.exp(-x*v*R),H=Math.sin(A*R),V=Math.cos(A*R),K=l-$*(T*H+y*V),Z=A_($*(L*H+M*V));return o.done=Math.abs(Z)<=r&&Math.abs(l-K)<=a,o.value=o.done?l:K,o}const z=N(R);if(p)o.done=R>=h;else{const $=A_(S(R));o.done=Math.abs($)<=r&&Math.abs(l-z)<=a}return o.value=o.done?l:z,o},toString:()=>{const R=Math.min(QXe(I),gCe),z=tDt($=>I.next(R*$).value,R,30);return R+"ms "+z},toTransition:()=>{}};return I}xCe.applyToOptions=s=>{const t=KTs(s,100,xCe);return s.ease=t.ease,s.duration=A_(t.duration),s.type="keyframes",s};const t6s=5;function sDt(s,t,n){const r=Math.max(t-t6s,0);return RRt(n-s(r),t-r)}function Lqe({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},p=M=>o!==void 0&&Mc,f=M=>o===void 0?c:c===void 0||Math.abs(o-M)-x*Math.exp(-M/r),N=M=>v+b(M),S=M=>{const I=b(M),R=N(M);m.done=Math.abs(I)<=d,m.value=m.done?v:R};let A,T;const L=M=>{p(m.value)&&(A=M,T=xCe({keyframes:[m.value,f(m.value)],velocity:sDt(N,M,m.value),damping:a,stiffness:i,restDelta:d,restSpeed:u}))};return L(0),{calculatedDuration:null,next:M=>{let I=!1;return!T&&A===void 0&&(I=!0,S(M),L(M)),A!==void 0&&M>=A?T.next(M-A):(!I&&S(M),m)}}}function s6s(s,t,n){const r=[],a=n||hP.mix||eDt,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=s6s(t,r,a),c=o.length,d=u=>{if(l&&u1)for(;hd(Z4(s[0],s[i-1],u)):d}function r6s(s,t){const n=s[s.length-1];for(let r=1;r<=t;r++){const a=cee(0,t,r);s.push(rp(n,1,a))}}function a6s(s){const t=[0];return r6s(t,s.length-1),t}function i6s(s,t){return s.map(n=>n*t)}function o6s(s,t){return s.map(()=>t||VRt).splice(0,s.length-1)}function SQ({duration:s=300,keyframes:t,times:n,ease:r="easeInOut"}){const a=gTs(r)?r.map(Cmt):Cmt(r),i={done:!1,value:t[0]},l=i6s(n&&n.length===t.length?n:a6s(t),s),o=n6s(l,t,{ease:Array.isArray(a)?a:o6s(t,a)});return{calculatedDuration:s,next:c=>(i.value=o(c),i.done=c>=s,i)}}const l6s=s=>s!==null;function MMe(s,{repeat:t,repeatType:n="loop"},r,a=1){const i=s.filter(l6s),o=a<0||t&&n!=="loop"&&t%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const c6s={decay:Lqe,inertia:Lqe,tween:SQ,keyframes:SQ,spring:xCe};function nDt(s){typeof s.type=="string"&&(s.type=c6s[s.type])}class JXe{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 d6s=s=>s/100;class yCe extends JXe{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!==eb.now()&&this.tick(eb.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;nDt(t);const{type:n=SQ,repeat:r=0,repeatDelay:a=0,repeatType:i,velocity:l=0}=t;let{keyframes:o}=t;const c=n||SQ;c!==SQ&&typeof o[0]!="number"&&(this.mixKeyframes=Qne(d6s,eDt(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=QXe(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:p,type:f,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 N=this.currentTime,S=r;if(h){const M=Math.min(this.currentTime,a)/o;let I=Math.floor(M),R=M%1;!R&&M>=1&&(R=1),R===1&&I--,I=Math.min(I,h+1),!!(I%2)&&(m==="reverse"?(R=1-R,p&&(R-=p/o)):m==="mirror"&&(S=l)),N=Z4(0,1,R)*o}let A;b?(this.delayState.value=u[0],A=this.delayState):A=S.next(N),i&&!b&&(A.value=i(A.value));let{done:T}=A;!b&&c!==null&&(T=this.playbackSpeed>=0?this.currentTime>=a:this.currentTime<=0);const L=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&T);return L&&f!==Lqe&&(A.value=MMe(u,this.options,y,this.speed)),x&&x(A.value),L&&this.finish(),A}then(t,n){return this.finished.then(t,n)}get duration(){return B2(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+B2(t)}get time(){return B2(this.currentTime)}set time(t){t=A_(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 sDt(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(eb.now()),this.playbackSpeed=t,n&&this.driver&&(this.time=B2(this.currentTime))}play(){var a,i;if(this.isStopped)return;const{driver:t=WTs,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(eb.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 u6s(s){for(let t=1;ts*180/Math.PI,Iqe=s=>{const t=HD(Math.atan2(s[1],s[0]));return Rqe(t)},h6s={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:s=>(Math.abs(s[0])+Math.abs(s[3]))/2,rotate:Iqe,rotateZ:Iqe,skewX:s=>HD(Math.atan(s[1])),skewY:s=>HD(Math.atan(s[2])),skew:s=>(Math.abs(s[1])+Math.abs(s[2]))/2},Rqe=s=>(s=s%360,s<0&&(s+=360),s),Rmt=Iqe,Dmt=s=>Math.sqrt(s[0]*s[0]+s[1]*s[1]),Omt=s=>Math.sqrt(s[4]*s[4]+s[5]*s[5]),m6s={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Dmt,scaleY:Omt,scale:s=>(Dmt(s)+Omt(s))/2,rotateX:s=>Rqe(HD(Math.atan2(s[6],s[5]))),rotateY:s=>Rqe(HD(Math.atan2(-s[2],s[0]))),rotateZ:Rmt,rotate:Rmt,skewX:s=>HD(Math.atan(s[4])),skewY:s=>HD(Math.atan(s[1])),skew:s=>(Math.abs(s[1])+Math.abs(s[4]))/2};function Dqe(s){return s.includes("scale")?1:0}function Oqe(s,t){if(!s||s==="none")return Dqe(t);const n=s.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,a;if(n)r=m6s,a=n;else{const o=s.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=h6s,a=o}if(!a)return Dqe(t);const i=r[t],l=a[1].split(",").map(f6s);return typeof i=="function"?i(l):l[i]}const p6s=(s,t)=>{const{transform:n="none"}=getComputedStyle(s);return Oqe(n,t)};function f6s(s){return parseFloat(s.trim())}const vG=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],bG=new Set(vG),Fmt=s=>s===yG||s===fo,g6s=new Set(["x","y","z"]),x6s=vG.filter(s=>!g6s.has(s));function y6s(s){const t=[];return x6s.forEach(n=>{const r=s.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith("scale")?1:0))}),t}const Q6={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})=>Oqe(t,"x"),y:(s,{transform:t})=>Oqe(t,"y")};Q6.translateX=Q6.x;Q6.translateY=Q6.y;const VF=new Set;let Fqe=!1,zqe=!1,Bqe=!1;function rDt(){if(zqe){const s=Array.from(VF).filter(r=>r.needsMeasurement),t=new Set(s.map(r=>r.element)),n=new Map;t.forEach(r=>{const a=y6s(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)})}zqe=!1,Fqe=!1,VF.forEach(s=>s.complete(Bqe)),VF.clear()}function aDt(){VF.forEach(s=>{s.readKeyframes(),s.needsMeasurement&&(zqe=!0)})}function v6s(){Bqe=!0,aDt(),rDt(),Bqe=!1}class eQe{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?(VF.add(this),Fqe||(Fqe=!0,mm.read(aDt),mm.resolveKeyframes(rDt))):(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])}u6s(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),VF.delete(this)}cancel(){this.state==="scheduled"&&(VF.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const b6s=s=>s.startsWith("--");function iDt(s,t,n){b6s(t)?s.style.setProperty(t,n):s.style[t]=n}const _6s={};function oDt(s,t){const n=IRt(s);return()=>_6s[t]??n()}const w6s=oDt(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),lDt=oDt(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),vZ=([s,t,n,r])=>`cubic-bezier(${s}, ${t}, ${n}, ${r})`,zmt={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:vZ([0,.65,.55,1]),circOut:vZ([.55,0,1,.45]),backIn:vZ([.31,.01,.66,-.59]),backOut:vZ([.33,1.53,.69,.99])};function cDt(s,t){if(s)return typeof s=="function"?lDt()?tDt(s,t):"ease-out":HRt(s)?vZ(s):Array.isArray(s)?s.map(n=>cDt(n,t)||zmt.easeOut):zmt[s]}function j6s(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=cDt(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 dDt(s){return typeof s=="function"&&"applyToOptions"in s}function N6s({type:s,...t}){return dDt(s)&&lDt()?s.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class uDt extends JXe{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,qV(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const d=N6s(t);this.animation=j6s(n,r,a,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const u=MMe(a,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(u),iDt(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 B2(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+B2(t)}get time(){return B2(Number(this.animation.currentTime)||0)}set time(t){const n=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=A_(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&&w6s()?(this.animation.timeline=t,n&&(this.animation.rangeStart=n),r&&(this.animation.rangeEnd=r),nN):a(this)}}const hDt={anticipate:URt,backInOut:BRt,circInOut:$Rt};function k6s(s){return s in hDt}function S6s(s){typeof s.ease=="string"&&k6s(s.ease)&&(s.ease=hDt[s.ease])}const vOe=10;class C6s extends uDt{constructor(t){S6s(t),nDt(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 yCe({...l,autoplay:!1}),c=Math.max(vOe,eb.now()-this.startTime),d=Z4(0,vOe,c-vOe),u=o.sample(c).value,{name:h}=this.options;i&&h&&iDt(i,h,u),n.setWithVelocity(o.sample(Math.max(0,c-d)).value,u,d),o.stop()}}const Bmt=(s,t)=>t==="zIndex"?!1:!!(typeof s=="number"||Array.isArray(s)||typeof s=="string"&&(aS.test(s)||s==="0")&&!s.startsWith("url("));function A6s(s){const t=s[0];if(s.length===1)return!0;for(let n=0;nObject.hasOwnProperty.call(Element.prototype,"animate"));function I6s(s){var h;const{motionValue:t,name:n,repeatDelay:r,repeatType:a,damping:i,type:l,keyframes:o}=s;if(!(((h=t==null?void 0:t.owner)==null?void 0:h.current)instanceof HTMLElement))return!1;const{onUpdate:d,transformTemplate:u}=t.owner.getProps();return L6s()&&n&&(mDt.has(n)||P6s.has(n)&&M6s(o))&&(n!=="transform"||!u)&&!d&&!r&&a!=="mirror"&&i!==0&&l!=="inertia"}const R6s=40;class D6s extends JXe{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 f;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=eb.now();const m={autoplay:t,delay:n,type:r,repeat:a,repeatDelay:i,repeatType:l,name:c,motionValue:d,element:u,...h},p=(u==null?void 0:u.KeyframeResolver)||eQe;this.keyframeResolver=new p(o,(x,y,v)=>this.onKeyframesResolved(x,y,m,!v),c,d,u),(f=this.keyframeResolver)==null||f.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=eb.now();let h=!0;E6s(t,i,l,o)||(h=!1,(hP.instantAnimations||!c)&&(u==null||u(MMe(t,r,n))),t[0]=t[t.length-1],Uqe(r),r.repeat=0);const p={startTime:a?this.resolvedAt?this.resolvedAt-this.createdAt>R6s?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...r,keyframes:t},f=h&&!d&&I6s(p),x=(b=(v=p.motionValue)==null?void 0:v.owner)==null?void 0:b.current;let y;if(f)try{y=new C6s({...p,element:x})}catch{y=new yCe(p)}else y=new yCe(p);y.finished.then(()=>{this.notifyFinished()}).catch(nN),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(),v6s()),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 pDt(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 O6s=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function F6s(s){const t=O6s.exec(s);if(!t)return[,];const[,n,r,a]=t;return[`--${n??r}`,a]}const z6s=4;function fDt(s,t,n=1){qV(n<=z6s,`Max CSS variable fallback depth detected in property "${s}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[r,a]=F6s(s);if(!r)return;const i=window.getComputedStyle(t).getPropertyValue(r);if(i){const l=i.trim();return MRt(l)?parseFloat(l):l}return KXe(a)?fDt(a,t,n+1):a}const B6s={type:"spring",stiffness:500,damping:25,restSpeed:10},U6s=s=>({type:"spring",stiffness:550,damping:s===0?2*Math.sqrt(550):30,restSpeed:10}),q6s={type:"keyframes",duration:.8},$6s={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},V6s=(s,{keyframes:t})=>t.length>2?q6s:bG.has(s)?s.startsWith("scale")?U6s(t[1]):B6s:$6s;function gDt(s,t){if(s!=null&&s.inherit&&t){const{inherit:n,...r}=s;return{...t,...r}}return s}function tQe(s,t){const n=(s==null?void 0:s[t])??(s==null?void 0:s.default)??s;return n!==s?gDt(n,s):n}const H6s=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function G6s(s){for(const t in s)if(!H6s.has(t))return!0;return!1}const sQe=(s,t,n,r={},a,i)=>l=>{const o=tQe(r,s)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-A_(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};G6s(o)||Object.assign(u,V6s(s,u)),u.duration&&(u.duration=A_(u.duration)),u.repeatDelay&&(u.repeatDelay=A_(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let h=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(Uqe(u),u.delay===0&&(h=!0)),(hP.instantAnimations||hP.skipAnimations||a!=null&&a.shouldSkipAnimations)&&(h=!0,Uqe(u),u.delay=0),u.allowFlatten=!o.type&&!o.ease,h&&!i&&t.get()!==void 0){const m=MMe(u.keyframes,o);if(m!==void 0){mm.update(()=>{u.onUpdate(m),u.onComplete()});return}}return o.isSync?new yCe(u):new D6s(u)};function Umt(s){const t=[{},{}];return s==null||s.values.forEach((n,r)=>{t[0][r]=n.get(),t[1][r]=n.getVelocity()}),t}function nQe(s,t,n,r){if(typeof t=="function"){const[a,i]=Umt(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]=Umt(r);t=t(n!==void 0?n:s.custom,a,i)}return t}function HF(s,t,n){const r=s.getProps();return nQe(r,t,n!==void 0?n:r.custom,s)}const xDt=new Set(["width","height","top","left","right","bottom",...vG]),qmt=30,W6s=s=>!isNaN(parseFloat(s));class K6s{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const a=eb.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=eb.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=W6s(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 HXe);const r=this.events[t].add(n);return t==="change"?()=>{r(),mm.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=eb.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>qmt)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,qmt);return RRt(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 VV(s,t){return new K6s(s,t)}const qqe=s=>Array.isArray(s);function Y6s(s,t,n){s.hasValue(t)?s.getValue(t).set(n):s.addValue(t,VV(n))}function Z6s(s){return qqe(s)?s[s.length-1]||0:s}function X6s(s,t){const n=HF(s,t);let{transitionEnd:r={},transition:a={},...i}=n||{};i={...i,...r};for(const l in i){const o=Z6s(i[l]);Y6s(s,l,o)}}const rv=s=>!!(s&&s.getVelocity);function Q6s(s){return!!(rv(s)&&s.add)}function $qe(s,t){const n=s.getValue("willChange");if(Q6s(n))return n.add(t);if(!n&&hP.WillChange){const r=new hP.WillChange("auto");s.addValue("willChange",r),r.add(t)}}function rQe(s){return s.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const J6s="framerAppearId",yDt="data-"+rQe(J6s);function vDt(s){return s.props[yDt]}function eMs({protectedKeys:s,needsAnimating:t},n){const r=s.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function bDt(s,t,{delay:n=0,transitionOverride:r,type:a}={}){let{transition:i,transitionEnd:l,...o}=t;const c=s.getDefaultTransition();i=i?gDt(i,c):c;const d=i==null?void 0:i.reduceMotion;r&&(i=r);const u=[],h=a&&s.animationState&&s.animationState.getState()[a];for(const m in o){const p=s.getValue(m,s.latestValues[m]??null),f=o[m];if(f===void 0||h&&eMs(h,m))continue;const x={delay:n,...tQe(i||{},m)},y=p.get();if(y!==void 0&&!p.isAnimating()&&!Array.isArray(f)&&f===y&&!x.velocity){mm.update(()=>p.set(f));continue}let v=!1;if(window.MotionHandoffAnimation){const S=vDt(s);if(S){const A=window.MotionHandoffAnimation(S,m,mm);A!==null&&(x.startTime=A,v=!0)}}$qe(s,m);const b=d??s.shouldReduceMotion;p.start(sQe(m,p,f,b&&xDt.has(m)?{type:!1}:x,s,v));const N=p.animation;N&&u.push(N)}if(l){const m=()=>mm.update(()=>{l&&X6s(s,l)});u.length?Promise.all(u).then(m):m()}return u}function Vqe(s,t,n={}){var c;const r=HF(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(bDt(s,r,n)):()=>Promise.resolve(),l=s.variantChildren&&s.variantChildren.size?(d=0)=>{const{delayChildren:u=0,staggerChildren:h,staggerDirection:m}=a;return tMs(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 tMs(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(Vqe(c,t,{...l,delay:n+(typeof r=="function"?0:r)+pDt(s.variantChildren,c,r,a,i)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(o)}function sMs(s,t,n={}){s.notify("AnimationStart",t);let r;if(Array.isArray(t)){const a=t.map(i=>Vqe(s,i,n));r=Promise.all(a)}else if(typeof t=="string")r=Vqe(s,t,n);else{const a=typeof t=="function"?HF(s,t,n.custom):t;r=Promise.all(bDt(s,a,n))}return r.then(()=>{s.notify("AnimationComplete",t)})}const nMs={test:s=>s==="auto",parse:s=>s},_Dt=s=>t=>t.test(s),wDt=[yG,fo,B4,kT,ATs,CTs,nMs],$mt=s=>wDt.find(_Dt(s));function rMs(s){return typeof s=="number"?s===0:s!==null?s==="none"||s==="0"||LRt(s):!0}const aMs=new Set(["brightness","contrast","saturate","opacity"]);function iMs(s){const[t,n]=s.slice(0,-1).split("(");if(t==="drop-shadow")return s;const[r]=n.match(YXe)||[];if(!r)return s;const a=n.replace(r,"");let i=aMs.has(t)?1:0;return r!==n&&(i*=100),t+"("+i+a+")"}const oMs=/\b([a-z-]*)\(.*?\)/gu,Hqe={...aS,getAnimatableNone:s=>{const t=s.match(oMs);return t?t.map(iMs).join(" "):s}},Gqe={...aS,getAnimatableNone:s=>{const t=aS.parse(s);return aS.createTransformer(s)(t.map(r=>typeof r=="number"?0:typeof r=="object"?{...r,alpha:1}:r))}},Vmt={...yG,transform:Math.round},lMs={rotate:kT,rotateX:kT,rotateY:kT,rotateZ:kT,scale:woe,scaleX:woe,scaleY:woe,scaleZ:woe,skew:kT,skewX:kT,skewY:kT,distance:fo,translateX:fo,translateY:fo,translateZ:fo,x:fo,y:fo,z:fo,perspective:fo,transformPerspective:fo,opacity:dee,originX:Tmt,originY:Tmt,originZ:fo},aQe={borderWidth:fo,borderTopWidth:fo,borderRightWidth:fo,borderBottomWidth:fo,borderLeftWidth:fo,borderRadius:fo,borderTopLeftRadius:fo,borderTopRightRadius:fo,borderBottomRightRadius:fo,borderBottomLeftRadius:fo,width:fo,maxWidth:fo,height:fo,maxHeight:fo,top:fo,right:fo,bottom:fo,left:fo,inset:fo,insetBlock:fo,insetBlockStart:fo,insetBlockEnd:fo,insetInline:fo,insetInlineStart:fo,insetInlineEnd:fo,padding:fo,paddingTop:fo,paddingRight:fo,paddingBottom:fo,paddingLeft:fo,paddingBlock:fo,paddingBlockStart:fo,paddingBlockEnd:fo,paddingInline:fo,paddingInlineStart:fo,paddingInlineEnd:fo,margin:fo,marginTop:fo,marginRight:fo,marginBottom:fo,marginLeft:fo,marginBlock:fo,marginBlockStart:fo,marginBlockEnd:fo,marginInline:fo,marginInlineStart:fo,marginInlineEnd:fo,fontSize:fo,backgroundPositionX:fo,backgroundPositionY:fo,...lMs,zIndex:Vmt,fillOpacity:dee,strokeOpacity:dee,numOctaves:Vmt},cMs={...aQe,color:dx,backgroundColor:dx,outlineColor:dx,fill:dx,stroke:dx,borderColor:dx,borderTopColor:dx,borderRightColor:dx,borderBottomColor:dx,borderLeftColor:dx,filter:Hqe,WebkitFilter:Hqe,mask:Gqe,WebkitMask:Gqe},jDt=s=>cMs[s],dMs=new Set([Hqe,Gqe]);function NDt(s,t){let n=jDt(s);return dMs.has(n)||(n=aS),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const uMs=new Set(["auto","none","0"]);function hMs(s,t,n){let r=0,a;for(;r{t.getValue(c).set(d)}),this.resolveNoneKeyframes()}}function iQe(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 kDt=(s,t)=>t&&typeof s=="number"?t.transform(s):s;function A5e(s){return PRt(s)&&"offsetHeight"in s&&!("ownerSVGElement"in s)}const{schedule:oQe,cancel:jgr}=GRt(queueMicrotask,!1),ck={x:!1,y:!1};function SDt(){return ck.x||ck.y}function pMs(s){return s==="x"||s==="y"?ck[s]?null:(ck[s]=!0,()=>{ck[s]=!1}):ck.x||ck.y?null:(ck.x=ck.y=!0,()=>{ck.x=ck.y=!1})}function CDt(s,t){const n=iQe(s),r=new AbortController,a={passive:!0,...t,signal:r.signal};return[n,a,()=>r.abort()]}function fMs(s){return!(s.pointerType==="touch"||SDt())}function gMs(s,t,n={}){const[r,a,i]=CDt(s,n);return r.forEach(l=>{let o=!1,c=!1,d;const u=()=>{l.removeEventListener("pointerleave",f)},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))},p=()=>{o=!0,window.addEventListener("pointerup",m,a),window.addEventListener("pointercancel",m,a)},f=y=>{if(y.pointerType!=="touch"){if(o){c=!0;return}h(y)}},x=y=>{if(!fMs(y))return;c=!1;const v=t(l,y);typeof v=="function"&&(d=v,l.addEventListener("pointerleave",f,a))};l.addEventListener("pointerenter",x,a),l.addEventListener("pointerdown",p,a)}),i}const ADt=(s,t)=>t?s===t?!0:ADt(s,t.parentElement):!1,lQe=s=>s.pointerType==="mouse"?typeof s.button!="number"||s.button<=0:s.isPrimary!==!1,xMs=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function yMs(s){return xMs.has(s.tagName)||s.isContentEditable===!0}const vMs=new Set(["INPUT","SELECT","TEXTAREA"]);function bMs(s){return vMs.has(s.tagName)||s.isContentEditable===!0}const E5e=new WeakSet;function Hmt(s){return t=>{t.key==="Enter"&&s(t)}}function bOe(s,t){s.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const _Ms=(s,t)=>{const n=s.currentTarget;if(!n)return;const r=Hmt(()=>{if(E5e.has(n))return;bOe(n,"down");const a=Hmt(()=>{bOe(n,"up")}),i=()=>bOe(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 Gmt(s){return lQe(s)&&!SDt()}const Wmt=new WeakSet;function wMs(s,t,n={}){const[r,a,i]=CDt(s,n),l=o=>{const c=o.currentTarget;if(!Gmt(o)||Wmt.has(o))return;E5e.add(c),n.stopPropagation&&Wmt.add(o);const d=t(c,o),u=(p,f)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",m),E5e.has(c)&&E5e.delete(c),Gmt(p)&&typeof d=="function"&&d(p,{success:f})},h=p=>{u(p,c===window||c===document||n.useGlobalTarget||ADt(c,p.target))},m=p=>{u(p,!1)};window.addEventListener("pointerup",h,a),window.addEventListener("pointercancel",m,a)};return r.forEach(o=>{(n.useGlobalTarget?window:o).addEventListener("pointerdown",l,a),A5e(o)&&(o.addEventListener("focus",d=>_Ms(d,a)),!yMs(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function cQe(s){return PRt(s)&&"ownerSVGElement"in s}const T5e=new WeakMap;let ST;const EDt=(s,t,n)=>(r,a)=>a&&a[0]?a[0][s+"Size"]:cQe(r)&&"getBBox"in r?r.getBBox()[t]:r[n],jMs=EDt("inline","width","offsetWidth"),NMs=EDt("block","height","offsetHeight");function kMs({target:s,borderBoxSize:t}){var n;(n=T5e.get(s))==null||n.forEach(r=>{r(s,{get width(){return jMs(s,t)},get height(){return NMs(s,t)}})})}function SMs(s){s.forEach(kMs)}function CMs(){typeof ResizeObserver>"u"||(ST=new ResizeObserver(SMs))}function AMs(s,t){ST||CMs();const n=iQe(s);return n.forEach(r=>{let a=T5e.get(r);a||(a=new Set,T5e.set(r,a)),a.add(t),ST==null||ST.observe(r)}),()=>{n.forEach(r=>{const a=T5e.get(r);a==null||a.delete(t),a!=null&&a.size||ST==null||ST.unobserve(r)})}}const M5e=new Set;let xU;function EMs(){xU=()=>{const s={get width(){return window.innerWidth},get height(){return window.innerHeight}};M5e.forEach(t=>t(s))},window.addEventListener("resize",xU)}function TMs(s){return M5e.add(s),xU||EMs(),()=>{M5e.delete(s),!M5e.size&&typeof xU=="function"&&(window.removeEventListener("resize",xU),xU=void 0)}}function Kmt(s,t){return typeof s=="function"?TMs(s):AMs(s,t)}function MMs(s){return cQe(s)&&s.tagName==="svg"}const PMs=[...wDt,dx,aS],LMs=s=>PMs.find(_Dt(s)),Ymt=()=>({translate:0,scale:1,origin:0,originPoint:0}),yU=()=>({x:Ymt(),y:Ymt()}),Zmt=()=>({min:0,max:0}),Wx=()=>({x:Zmt(),y:Zmt()}),IMs=new WeakMap;function PMe(s){return s!==null&&typeof s=="object"&&typeof s.start=="function"}function uee(s){return typeof s=="string"||Array.isArray(s)}const dQe=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],uQe=["initial",...dQe];function LMe(s){return PMe(s.animate)||uQe.some(t=>uee(s[t]))}function TDt(s){return!!(LMe(s)||s.variants)}function RMs(s,t,n){for(const r in t){const a=t[r],i=n[r];if(rv(a))s.addValue(r,a);else if(rv(i))s.addValue(r,VV(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,VV(l!==void 0?l:a,{owner:s}))}}for(const r in n)t[r]===void 0&&s.removeValue(r);return t}const Wqe={current:null},MDt={current:!1},DMs=typeof window<"u";function OMs(){if(MDt.current=!0,!!DMs)if(window.matchMedia){const s=window.matchMedia("(prefers-reduced-motion)"),t=()=>Wqe.current=s.matches;s.addEventListener("change",t),t()}else Wqe.current=!1}const Xmt=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let vCe={};function PDt(s){vCe=s}function FMs(){return vCe}class zMs{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=eQe,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 p=eb.now();this.renderScheduledAtthis.bindToMotionValue(i,a)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(MDt.current||OMs(),this.shouldReduceMotion=Wqe.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(),mP(this.notifyUpdate),mP(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&&mDt.has(t)&&this.current instanceof HTMLElement){const{factory:l,keyframes:o,times:c,ease:d,duration:u}=n.accelerate,h=new uDt({element:this.current,name:t,keyframes:o,times:c,ease:d,duration:A_(u)}),m=l(h);this.valueSubscriptions.set(t,()=>{m(),h.cancel()});return}const r=bG.has(t);r&&this.onBindTransform&&this.onBindTransform();const a=n.on("change",l=>{this.latestValues[t]=l,this.props.onUpdate&&mm.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(),n.owner&&n.stop()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in vCe){const n=vCe[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):Wx()}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=VV(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"&&(MRt(r)||LRt(r))?r=parseFloat(r):!LMs(r)&&aS.test(n)&&(r=NDt(t,n)),this.setBaseTarget(t,rv(r)?r.get():r)),rv(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=nQe(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&&!rv(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 HXe),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){oQe.render(this.render)}}class LDt extends zMs{constructor(){super(...arguments),this.KeyframeResolver=mMs}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;rv(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class $P{constructor(t){this.isMounted=!1,this.node=t}update(){}}function IDt({top:s,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:s,max:r}}}function BMs({x:s,y:t}){return{top:t.min,right:s.max,bottom:t.max,left:s.min}}function UMs(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 _Oe(s){return s===void 0||s===1}function Kqe({scale:s,scaleX:t,scaleY:n}){return!_Oe(s)||!_Oe(t)||!_Oe(n)}function gD(s){return Kqe(s)||RDt(s)||s.z||s.rotate||s.rotateX||s.rotateY||s.skewX||s.skewY}function RDt(s){return Qmt(s.x)||Qmt(s.y)}function Qmt(s){return s&&s!=="0%"}function bCe(s,t,n){const r=s-n,a=t*r;return n+a}function Jmt(s,t,n,r,a){return a!==void 0&&(s=bCe(s,a,r)),bCe(s,n,r)+t}function Yqe(s,t=0,n=1,r,a){s.min=Jmt(s.min,t,n,r,a),s.max=Jmt(s.max,t,n,r,a)}function DDt(s,{x:t,y:n}){Yqe(s.x,t.translate,t.scale,t.originPoint),Yqe(s.y,n.translate,n.scale,n.originPoint)}const ept=.999999999999,tpt=1.0000000000001;function qMs(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;cept&&(t.x=1),t.yept&&(t.y=1)}function s4(s,t){s.min+=t,s.max+=t}function spt(s,t,n,r,a=.5){const i=rp(s.min,s.max,a);Yqe(s,t,n,i,r)}function npt(s,t){return typeof s=="string"?parseFloat(s)/100*(t.max-t.min):s}function P5e(s,t,n){const r=n??s;spt(s.x,npt(t.x,r.x),t.scaleX,t.scale,t.originX),spt(s.y,npt(t.y,r.y),t.scaleY,t.scale,t.originY)}function ODt(s,t){return IDt(UMs(s.getBoundingClientRect(),t))}function $Ms(s,t,n){const r=ODt(s,n),{scroll:a}=t;return a&&(s4(r.x,a.offset.x),s4(r.y,a.offset.y)),r}const VMs={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},HMs=vG.length;function GMs(s,t,n){let r="",a=!0;for(let i=0;i{if(!t.target)return s;if(typeof s=="string")if(fo.test(s))s=parseFloat(s);else return s;const n=rpt(s,t.target.x),r=rpt(s,t.target.y);return`${n}% ${r}%`}},WMs={correct:(s,{treeScale:t,projectionDelta:n})=>{const r=s,a=aS.parse(s);if(a.length>5)return r;const i=aS.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=rp(o,c,.5);return typeof a[2+l]=="number"&&(a[2+l]/=d),typeof a[3+l]=="number"&&(a[3+l]/=d),i(a)}},Zqe={borderRadius:{...ZK,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:ZK,borderTopRightRadius:ZK,borderBottomLeftRadius:ZK,borderBottomRightRadius:ZK,boxShadow:WMs};function zDt(s,{layout:t,layoutId:n}){return bG.has(s)||s.startsWith("origin")||(t||n!==void 0)&&(!!Zqe[s]||s==="opacity")}function mQe(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)(rv(r[o])||a&&rv(a[o])||zDt(o,s)||((l=n==null?void 0:n.getValue(o))==null?void 0:l.liveStyle)!==void 0)&&(i[o]=r[o]);return i}function KMs(s){return window.getComputedStyle(s)}class YMs extends LDt{constructor(){super(...arguments),this.type="html",this.renderInstance=FDt}readValueFromInstance(t,n){var r;if(bG.has(n))return(r=this.projection)!=null&&r.isProjecting?Dqe(n):p6s(t,n);{const a=KMs(t),i=(KRt(n)?a.getPropertyValue(n):a[n])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(t,{transformPagePoint:n}){return ODt(t,n)}build(t,n,r){hQe(t,n,r.transformTemplate)}scrapeMotionValuesFromProps(t,n,r){return mQe(t,n,r)}}const ZMs={offset:"stroke-dashoffset",array:"stroke-dasharray"},XMs={offset:"strokeDashoffset",array:"strokeDasharray"};function QMs(s,t,n=1,r=0,a=!0){s.pathLength=1;const i=a?ZMs:XMs;s[i.offset]=`${-r}`,s[i.array]=`${t} ${n}`}const JMs=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function BDt(s,{attrX:t,attrY:n,attrScale:r,pathLength:a,pathSpacing:i=1,pathOffset:l=0,...o},c,d,u){if(hQe(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 p of JMs)h[p]!==void 0&&(m[p]=h[p],delete h[p]);t!==void 0&&(h.x=t),n!==void 0&&(h.y=n),r!==void 0&&(h.scale=r),a!==void 0&&QMs(h,a,i,l,!1)}const UDt=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"]),qDt=s=>typeof s=="string"&&s.toLowerCase()==="svg";function ePs(s,t,n,r){FDt(s,t,void 0,r);for(const a in t.attrs)s.setAttribute(UDt.has(a)?a:rQe(a),t.attrs[a])}function $Dt(s,t,n){const r=mQe(s,t,n);for(const a in s)if(rv(s[a])||rv(t[a])){const i=vG.indexOf(a)!==-1?"attr"+a.charAt(0).toUpperCase()+a.substring(1):a;r[i]=s[a]}return r}class tPs extends LDt{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Wx}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(bG.has(n)){const r=jDt(n);return r&&r.default||0}return n=UDt.has(n)?n:rQe(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,r){return $Dt(t,n,r)}build(t,n,r){BDt(t,n,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(t,n,r,a){ePs(t,n,r,a)}mount(t){this.isSVGTag=qDt(t.tagName),super.mount(t)}}const sPs=uQe.length;function VDt(s){if(!s)return;if(!s.isControllingVariants){const n=s.parent?VDt(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})=>sMs(s,n,r)))}function iPs(s){let t=aPs(s),n=apt(),r=!0,a=!1;const i=d=>(u,h)=>{var p;const m=HF(s,h,d==="exit"?(p=s.presenceContext)==null?void 0:p.custom:void 0);if(m){const{transition:f,transitionEnd:x,...y}=m;u={...u,...y,...x}}return u};function l(d){t=d(s)}function o(d){const{props:u}=s,h=VDt(s.parent)||{},m=[],p=new Set;let f={},x=1/0;for(let v=0;vx&&A,R=!1;const z=Array.isArray(S)?S:[S];let $=z.reduce(i(b),{});T===!1&&($={});const{prevResolvedValues:H={}}=N,V={...H,...$},K=le=>{I=!0,p.has(le)&&(R=!0,p.delete(le)),N.needsAnimating[le]=!0;const ue=s.getValue(le);ue&&(ue.liveStyle=!1)};for(const le in V){const ue=$[le],se=H[le];if(f.hasOwnProperty(le))continue;let ne=!1;qqe(ue)&&qqe(se)?ne=!HDt(ue,se):ne=ue!==se,ne?ue!=null?K(le):p.add(le):ue!==void 0&&p.has(le)?K(le):N.protectedKeys[le]=!0}N.prevProp=S,N.prevResolvedValues=$,N.isActive&&(f={...f,...$}),(r||a)&&s.blockInitialAnimation&&(I=!1);const Z=L&&M;I&&(!Z||R)&&m.push(...z.map(le=>{const ue={type:b};if(typeof le=="string"&&(r||a)&&!Z&&s.manuallyAnimateOnMount&&s.parent){const{parent:se}=s,ne=HF(se,le);if(se.enteringChildren&&ne){const{delayChildren:ie}=ne.transition||{};ue.delay=pDt(se.enteringChildren,s,ie)}}return{animation:le,options:ue}}))}if(p.size){const v={};if(typeof u.initial!="boolean"){const b=HF(s,Array.isArray(u.initial)?u.initial[0]:u.initial);b&&b.transition&&(v.transition=b.transition)}p.forEach(b=>{const N=s.getBaseTarget(b),S=s.getValue(b);S&&(S.liveStyle=!0),v[b]=N??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(p=>{var f;return(f=p.animationState)==null?void 0:f.setActive(d,u)}),n[d].isActive=u;const h=o(d);for(const p in n)n[p].protectedKeys={};return h}return{animateChanges:o,setActive:c,setAnimateFunction:l,getState:()=>n,reset:()=>{n=apt(),a=!0}}}function oPs(s,t){return typeof t=="string"?t!==s:Array.isArray(t)?!HDt(t,s):!1}function ZL(s=!1){return{isActive:s,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function apt(){return{animate:ZL(!0),whileInView:ZL(),whileHover:ZL(),whileTap:ZL(),whileDrag:ZL(),whileFocus:ZL(),exit:ZL()}}function Xqe(s,t){s.min=t.min,s.max=t.max}function tk(s,t){Xqe(s.x,t.x),Xqe(s.y,t.y)}function ipt(s,t){s.translate=t.translate,s.scale=t.scale,s.originPoint=t.originPoint,s.origin=t.origin}const GDt=1e-4,lPs=1-GDt,cPs=1+GDt,WDt=.01,dPs=0-WDt,uPs=0+WDt;function tb(s){return s.max-s.min}function hPs(s,t,n){return Math.abs(s-t)<=n}function opt(s,t,n,r=.5){s.origin=r,s.originPoint=rp(t.min,t.max,s.origin),s.scale=tb(n)/tb(t),s.translate=rp(n.min,n.max,s.origin)-s.originPoint,(s.scale>=lPs&&s.scale<=cPs||isNaN(s.scale))&&(s.scale=1),(s.translate>=dPs&&s.translate<=uPs||isNaN(s.translate))&&(s.translate=0)}function CQ(s,t,n,r){opt(s.x,t.x,n.x,r?r.originX:void 0),opt(s.y,t.y,n.y,r?r.originY:void 0)}function lpt(s,t,n,r=0){const a=r?rp(n.min,n.max,r):n.min;s.min=a+t.min,s.max=s.min+tb(t)}function mPs(s,t,n,r){lpt(s.x,t.x,n.x,r==null?void 0:r.x),lpt(s.y,t.y,n.y,r==null?void 0:r.y)}function cpt(s,t,n,r=0){const a=r?rp(n.min,n.max,r):n.min;s.min=t.min-a,s.max=s.min+tb(t)}function _Ce(s,t,n,r){cpt(s.x,t.x,n.x,r==null?void 0:r.x),cpt(s.y,t.y,n.y,r==null?void 0:r.y)}function dpt(s,t,n,r,a){return s-=t,s=bCe(s,1/n,r),a!==void 0&&(s=bCe(s,1/a,r)),s}function pPs(s,t=0,n=1,r=.5,a,i=s,l=s){if(B4.test(t)&&(t=parseFloat(t),t=rp(l.min,l.max,t/100)-l.min),typeof t!="number")return;let o=rp(i.min,i.max,r);s===i&&(o-=t),s.min=dpt(s.min,t,n,o,a),s.max=dpt(s.max,t,n,o,a)}function upt(s,t,[n,r,a],i,l){pPs(s,t[n],t[r],t[a],t.scale,i,l)}const fPs=["x","scaleX","originX"],gPs=["y","scaleY","originY"];function hpt(s,t,n,r){upt(s.x,t,fPs,n?n.x:void 0,r?r.x:void 0),upt(s.y,t,gPs,n?n.y:void 0,r?r.y:void 0)}function mpt(s){return s.translate===0&&s.scale===1}function KDt(s){return mpt(s.x)&&mpt(s.y)}function ppt(s,t){return s.min===t.min&&s.max===t.max}function xPs(s,t){return ppt(s.x,t.x)&&ppt(s.y,t.y)}function fpt(s,t){return Math.round(s.min)===Math.round(t.min)&&Math.round(s.max)===Math.round(t.max)}function YDt(s,t){return fpt(s.x,t.x)&&fpt(s.y,t.y)}function gpt(s){return tb(s.x)/tb(s.y)}function xpt(s,t){return s.translate===t.translate&&s.scale===t.scale&&s.originPoint===t.originPoint}function k5(s){return[s("x"),s("y")]}function yPs(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,rotateX:h,rotateY:m,skewX:p,skewY:f}=n;d&&(r=`perspective(${d}px) ${r}`),u&&(r+=`rotate(${u}deg) `),h&&(r+=`rotateX(${h}deg) `),m&&(r+=`rotateY(${m}deg) `),p&&(r+=`skewX(${p}deg) `),f&&(r+=`skewY(${f}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 ZDt=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],vPs=ZDt.length,ypt=s=>typeof s=="string"?parseFloat(s):s,vpt=s=>typeof s=="number"||fo.test(s);function bPs(s,t,n,r,a,i){a?(s.opacity=rp(0,n.opacity??1,_Ps(r)),s.opacityExit=rp(t.opacity??1,0,wPs(r))):i&&(s.opacity=rp(t.opacity??1,n.opacity??1,r));for(let l=0;lrt?1:n(cee(s,t,r))}function jPs(s,t,n){const r=rv(s)?s:VV(s);return r.start(sQe("",r,t,n)),r.animation}function hee(s,t,n,r={passive:!0}){return s.addEventListener(t,n,r),()=>s.removeEventListener(t,n)}const NPs=(s,t)=>s.depth-t.depth;class kPs{constructor(){this.children=[],this.isDirty=!1}add(t){VXe(this.children,t),this.isDirty=!0}remove(t){pCe(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(NPs),this.isDirty=!1,this.children.forEach(t)}}function SPs(s,t){const n=eb.now(),r=({timestamp:a})=>{const i=a-n;i>=t&&(mP(r),s(i-t))};return mm.setup(r,!0),()=>mP(r)}function L5e(s){return rv(s)?s.get():s}class CPs{constructor(){this.members=[]}add(t){VXe(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&&(pCe(this.members,r),r.unmount())}t.scheduleRender()}remove(t){if(pCe(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 I5e={hasAnimatedSinceResize:!0,hasEverUpdated:!1},wOe=["","X","Y","Z"],APs=1e3;let EPs=0;function jOe(s,t,n,r){const{latestValues:a}=t;a[s]&&(n[s]=a[s],t.setStaticValue(s,0),r&&(r[s]=0))}function QDt(s){if(s.hasCheckedOptimisedAppear=!0,s.root===s)return;const{visualElement:t}=s.options;if(!t)return;const n=vDt(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:a,layoutId:i}=s.options;window.MotionCancelOptimisedAnimation(n,"transform",mm,!(a||i))}const{parent:r}=s;r&&!r.hasCheckedOptimisedAppear&&QDt(r)}function JDt({attachResizeListener:s,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:a}){return class{constructor(l={},o=t==null?void 0:t()){this.id=EPs++,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(PPs),this.nodes.forEach(FPs),this.nodes.forEach(zPs),this.nodes.forEach(LPs)},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;mm.read(()=>{h=window.innerWidth}),s(l,()=>{const p=window.innerWidth;p!==h&&(h=p,this.root.updateBlockedByResize=!0,u&&u(),u=SPs(m,250),I5e.hasAnimatedSinceResize&&(I5e.hasAnimatedSinceResize=!1,this.nodes.forEach(jpt)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:h,hasRelativeLayoutChanged:m,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const f=this.options.transition||d.getDefaultTransition()||VPs,{onLayoutAnimationStart:x,onLayoutAnimationComplete:y}=d.getProps(),v=!this.targetLayout||!YDt(this.targetLayout,p),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 N={...tQe(f,"layout"),onPlay:x,onComplete:y};(d.shouldReduceMotion||this.options.layoutRoot)&&(N.delay=0,N.type=!1),this.startAnimation(N),this.setAnimationOrigin(u,b)}else h||jpt(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=p})}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(),mP(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(BPs),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&&QDt(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&&!tb(this.snapshot.measuredBox.x)&&!tb(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let c=0;c{const A=S/1e3;Npt(h.x,l.x,A),Npt(h.y,l.y,A),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(_Ce(m,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),qPs(this.relativeTarget,this.relativeTargetOrigin,m,A),N&&xPs(this.relativeTarget,N)&&(this.isProjectionDirty=!1),N||(N=Wx()),tk(N,this.relativeTarget)),x&&(this.animationValues=u,bPs(u,d,this.latestValues,A,b,v)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=A},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(l){var o,c,d;this.notifyListeners("animationStart"),(o=this.currentAnimation)==null||o.stop(),(d=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||d.stop(),this.pendingAnimation&&(mP(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=mm.update(()=>{I5e.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=VV(0)),this.motionValue.jump(0,!1),this.currentAnimation=jPs(this.motionValue,[0,1e3],{...l,velocity:0,isSync:!0,onUpdate:u=>{this.mixTargetDelta(u),l.onUpdate&&l.onUpdate(u)},onStop:()=>{},onComplete:()=>{l.onComplete&&l.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const l=this.getStack();l&&l.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(APs),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&&eOt(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||Wx();const h=tb(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+h;const m=tb(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+m}tk(o,c),P5e(o,u),CQ(this.projectionDeltaWithTransform,this.layoutCorrected,o,u)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new CPs),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&&jOe("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(_pt),this.root.sharedNodes.clear()}}}function TPs(s){s.updateLayout()}function MPs(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")k5(h=>{const m=l?t.measuredBox[h]:t.layoutBox[h],p=tb(m);m.min=r[h].min,m.max=m.min+p});else if(i==="x"||i==="y"){const h=i==="x"?"y":"x";Xqe(l?t.measuredBox[h]:t.layoutBox[h],r[h])}else eOt(i,t.layoutBox,r)&&k5(h=>{const m=l?t.measuredBox[h]:t.layoutBox[h],p=tb(r[h]);m.max=m.min+p,s.relativeTarget&&!s.currentAnimation&&(s.isProjectionDirty=!0,s.relativeTarget[h].max=s.relativeTarget[h].min+p)});const o=yU();CQ(o,r,t.layoutBox);const c=yU();l?CQ(c,s.applyTransform(a,!0),t.measuredBox):CQ(c,r,t.layoutBox);const d=!KDt(o);let u=!1;if(!s.resumeFrom){const h=s.getClosestProjectingParent();if(h&&!h.resumeFrom){const{snapshot:m,layout:p}=h;if(m&&p){const f=s.options.layoutAnchor||void 0,x=Wx();_Ce(x,t.layoutBox,m.layoutBox,f);const y=Wx();_Ce(y,r,p.layoutBox,f),YDt(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 PPs(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 LPs(s){s.isProjectionDirty=s.isSharedProjectionDirty=s.isTransformDirty=!1}function IPs(s){s.clearSnapshot()}function _pt(s){s.clearMeasurements()}function RPs(s){s.isLayoutDirty=!0,s.updateLayout()}function wpt(s){s.isLayoutDirty=!1}function DPs(s){s.isAnimationBlocked&&s.layout&&!s.isLayoutDirty&&(s.snapshot=s.layout,s.isLayoutDirty=!0)}function OPs(s){const{visualElement:t}=s.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),s.resetTransform()}function jpt(s){s.finishAnimation(),s.targetDelta=s.relativeTarget=s.target=void 0,s.isProjectionDirty=!0}function FPs(s){s.resolveTargetDelta()}function zPs(s){s.calcProjection()}function BPs(s){s.resetSkewAndRotation()}function UPs(s){s.removeLeadSnapshot()}function Npt(s,t,n){s.translate=rp(t.translate,0,n),s.scale=rp(t.scale,1,n),s.origin=t.origin,s.originPoint=t.originPoint}function kpt(s,t,n,r){s.min=rp(t.min,n.min,r),s.max=rp(t.max,n.max,r)}function qPs(s,t,n,r){kpt(s.x,t.x,n.x,r),kpt(s.y,t.y,n.y,r)}function $Ps(s){return s.animationValues&&s.animationValues.opacityExit!==void 0}const VPs={duration:.45,ease:[.4,0,.1,1]},Spt=s=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(s),Cpt=Spt("applewebkit/")&&!Spt("chrome/")?Math.round:nN;function Apt(s){s.min=Cpt(s.min),s.max=Cpt(s.max)}function HPs(s){Apt(s.x),Apt(s.y)}function eOt(s,t,n){return s==="position"||s==="preserve-aspect"&&!hPs(gpt(t),gpt(n),.2)}function GPs(s){var t;return s!==s.root&&((t=s.scroll)==null?void 0:t.wasRoot)}const WPs=JDt({attachResizeListener:(s,t)=>hee(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}),NOe={current:void 0},tOt=JDt({measureScroll:s=>({x:s.scrollLeft,y:s.scrollTop}),defaultParent:()=>{if(!NOe.current){const s=new WPs({});s.mount(window),s.setOptions({layoutScroll:!0}),NOe.current=s}return NOe.current},resetTransform:(s,t)=>{s.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:s=>window.getComputedStyle(s).position==="fixed"}),pQe=j.createContext({transformPagePoint:s=>s,isStatic:!1,reducedMotion:"never"});function Ept(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function KPs(...s){return t=>{let n=!1;const r=s.map(a=>{const i=Ept(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a{const{width:p,height:f,top:x,left:y,right:v,bottom:b}=c.current;if(t||i===!1||!o.current||!p||!f)return;const N=n==="left"?`left: ${y}`:`right: ${v}`,S=r==="bottom"?`bottom: ${b}`:`top: ${x}`;o.current.dataset.motionPopId=l;const A=document.createElement("style");d&&(A.nonce=d);const T=a??document.head;return T.appendChild(A),A.sheet&&A.sheet.insertRule(` [data-motion-pop-id="${l}"] { position: absolute !important; width: ${p}px !important; height: ${f}px !important; ${N}px !important; ${S}px !important; } `),()=>{var L;(L=o.current)==null||L.removeAttribute("data-motion-pop-id"),T.contains(A)&&T.removeChild(A)}},[t]),e.jsx(ZPs,{isPresent:t,childRef:o,sizeRef:c,pop:i,children:i===!1?s:j.cloneElement(s,{ref:h})})}const QPs=({children:s,initial:t,isPresent:n,onExitComplete:r,custom:a,presenceAffectsLayout:i,mode:l,anchorX:o,anchorY:c,root:d})=>{const u=$Xe(JPs),h=j.useId();let m=!0,p=j.useMemo(()=>(m=!1,{id:h,initial:t,isPresent:n,custom:a,onExitComplete:f=>{u.set(f,!0);for(const x of u.values())if(!x)return;r&&r()},register:f=>(u.set(f,!1),()=>u.delete(f))}),[n,u,r]);return i&&m&&(p={...p}),j.useMemo(()=>{u.forEach((f,x)=>u.set(x,!1))},[n]),j.useEffect(()=>{!n&&!u.size&&r&&r()},[n]),s=e.jsx(XPs,{pop:l==="popLayout",isPresent:n,anchorX:o,anchorY:c,root:d,children:s}),e.jsx(EMe.Provider,{value:p,children:s})};function JPs(){return new Map}function sOt(s=!0){const t=j.useContext(EMe);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 joe=s=>s.key||"";function Tpt(s){const t=[];return j.Children.forEach(s,n=>{j.isValidElement(n)&&t.push(n)}),t}const _G=({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]=sOt(l),m=j.useMemo(()=>Tpt(s),[s]),p=l&&!u?[]:m.map(joe),f=j.useRef(!0),x=j.useRef(m),y=$Xe(()=>new Map),v=j.useRef(new Set),[b,N]=j.useState(m),[S,A]=j.useState(m);TRt(()=>{f.current=!1,x.current=m;for(let M=0;M{const I=joe(M),R=l&&!u?!1:m===S||p.includes(I),z=()=>{if(v.current.has(I))return;if(y.has(I))v.current.add(I),y.set(I,!0);else return;let $=!0;y.forEach(H=>{H||($=!1)}),$&&(L==null||L(),A(x.current),l&&(h==null||h()),r&&r())};return e.jsx(QPs,{isPresent:R,initial:!f.current||n?void 0:!1,custom:t,presenceAffectsLayout:a,mode:i,root:d,onExitComplete:R?void 0:z,anchorX:o,anchorY:c,children:M},I)})})},nOt=j.createContext({strict:!1}),Mpt={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 Ppt=!1;function eLs(){if(Ppt)return;const s={};for(const t in Mpt)s[t]={isEnabled:n=>Mpt[t].some(r=>!!n[r])};PDt(s),Ppt=!0}function rOt(){return eLs(),FMs()}function tLs(s){const t=rOt();for(const n in s)t[n]={...t[n],...s[n]};PDt(t)}const sLs=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 wCe(s){return s.startsWith("while")||s.startsWith("drag")&&s!=="draggable"||s.startsWith("layout")||s.startsWith("onTap")||s.startsWith("onPan")||s.startsWith("onLayout")||sLs.has(s)}let aOt=s=>!wCe(s);function nLs(s){typeof s=="function"&&(aOt=t=>t.startsWith("on")?!wCe(t):s(t))}try{nLs(require("@emotion/is-prop-valid").default)}catch{}function rLs(s,t,n){const r={};for(const a in s)a==="values"&&typeof s.values=="object"||rv(s[a])||(aOt(a)||n===!0&&wCe(a)||!t&&!wCe(a)||s.draggable&&a.startsWith("onDrag"))&&(r[a]=s[a]);return r}const IMe=j.createContext({});function aLs(s,t){if(LMe(s)){const{initial:n,animate:r}=s;return{initial:n===!1||uee(n)?n:void 0,animate:uee(r)?r:void 0}}return s.inherit!==!1?t:{}}function iLs(s){const{initial:t,animate:n}=aLs(s,j.useContext(IMe));return j.useMemo(()=>({initial:t,animate:n}),[Lpt(t),Lpt(n)])}function Lpt(s){return Array.isArray(s)?s.join(" "):s}const fQe=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function iOt(s,t,n){for(const r in t)!rv(t[r])&&!zDt(r,n)&&(s[r]=t[r])}function oLs({transformTemplate:s},t){return j.useMemo(()=>{const n=fQe();return hQe(n,t,s),Object.assign({},n.vars,n.style)},[t])}function lLs(s,t){const n=s.style||{},r={};return iOt(r,n,s),Object.assign(r,oLs(s,t)),r}function cLs(s,t){const n={},r=lLs(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 oOt=()=>({...fQe(),attrs:{}});function dLs(s,t,n,r){const a=j.useMemo(()=>{const i=oOt();return BDt(i,t,qDt(r),s.transformTemplate,s.style),{...i.attrs,style:{...i.style}}},[t]);if(s.style){const i={};iOt(i,s.style,s),a.style={...i,...a.style}}return a}const uLs=["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 gQe(s){return typeof s!="string"||s.includes("-")?!1:!!(uLs.indexOf(s)>-1||/[A-Z]/u.test(s))}function hLs(s,t,n,{latestValues:r},a,i=!1,l){const c=(l??gQe(s)?dLs:cLs)(t,r,a,s),d=rLs(t,typeof s=="string",i),u=s!==j.Fragment?{...d,...c,ref:n}:{},{children:h}=t,m=j.useMemo(()=>rv(h)?h.get():h,[h]);return j.createElement(s,{...u,children:m})}function mLs({scrapeMotionValuesFromProps:s,createRenderState:t},n,r,a){return{latestValues:pLs(n,r,a,s),renderState:t()}}function pLs(s,t,n,r){const a={},i=r(s,{});for(const m in i)a[m]=L5e(i[m]);let{initial:l,animate:o}=s;const c=LMe(s),d=TDt(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"&&!PMe(h)){const m=Array.isArray(h)?h:[h];for(let p=0;p(t,n)=>{const r=j.useContext(IMe),a=j.useContext(EMe),i=()=>mLs(s,t,r,a);return n?i():$Xe(i)},fLs=lOt({scrapeMotionValuesFromProps:mQe,createRenderState:fQe}),gLs=lOt({scrapeMotionValuesFromProps:$Dt,createRenderState:oOt}),xLs=Symbol.for("motionComponentSymbol");function yLs(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));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&&(i?t.mount(i):t.unmount())},[t])}const cOt=j.createContext({});function OB(s){return s&&typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,"current")}function vLs(s,t,n,r,a,i){var N,S;const{visualElement:l}=j.useContext(IMe),o=j.useContext(nOt),c=j.useContext(EMe),d=j.useContext(pQe),u=d.reducedMotion,h=d.skipAnimations,m=j.useRef(null),p=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}),p.current&&m.current&&(m.current.manuallyAnimateOnMount=!0));const f=m.current,x=j.useContext(cOt);f&&!f.projection&&a&&(f.type==="html"||f.type==="svg")&&bLs(m.current,n,a,x);const y=j.useRef(!1);j.useInsertionEffect(()=>{f&&y.current&&f.update(n,c)});const v=n[yDt],b=j.useRef(!!v&&typeof window<"u"&&!((N=window.MotionHandoffIsComplete)!=null&&N.call(window,v))&&((S=window.MotionHasOptimisedAnimation)==null?void 0:S.call(window,v)));return TRt(()=>{p.current=!0,f&&(y.current=!0,window.MotionIsMounted=!0,f.updateFeatures(),f.scheduleRenderMicrotask(),b.current&&f.animationState&&f.animationState.animateChanges())}),j.useEffect(()=>{f&&(!b.current&&f.animationState&&f.animationState.animateChanges(),b.current&&(queueMicrotask(()=>{var A;(A=window.MotionHandoffMarkAsComplete)==null||A.call(window,v)}),b.current=!1),f.enteringChildren=void 0)}),f}function bLs(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:dOt(s.parent)),s.projection.setOptions({layoutId:a,layout:i,alwaysMeasureLayout:!!l||o&&OB(o),visualElement:s,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:h,layoutScroll:c,layoutRoot:d,layoutAnchor:u})}function dOt(s){if(s)return s.options.allowProjection!==!1?s.projection:dOt(s.parent)}function kOe(s,{forwardMotionProps:t=!1,type:n}={},r,a){r&&tLs(r);const i=n?n==="svg":gQe(s),l=i?gLs:fLs;function o(d,u){let h;const m={...j.useContext(pQe),...d,layoutId:_Ls(d)},{isStatic:p}=m,f=iLs(d),x=l(d,p);if(!p&&typeof window<"u"){wLs();const y=jLs(m);h=y.MeasureLayout,f.visualElement=vLs(s,x,m,a,y.ProjectionNode,i)}return e.jsxs(IMe.Provider,{value:f,children:[h&&f.visualElement?e.jsx(h,{visualElement:f.visualElement,...m}):null,hLs(s,d,yLs(x,f.visualElement,u),x,p,t,i)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const c=j.forwardRef(o);return c[xLs]=s,c}function _Ls({layoutId:s}){const t=j.useContext(qXe).id;return t&&s!==void 0?t+"-"+s:s}function wLs(s,t){j.useContext(nOt).strict}function jLs(s){const t=rOt(),{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 NLs(s,t){if(typeof Proxy>"u")return kOe;const n=new Map,r=(i,l)=>kOe(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,kOe(l,void 0,s,t)),n.get(l))})}const kLs=(s,t)=>t.isSVG??gQe(s)?new tPs(t):new YMs(t,{allowProjection:s!==j.Fragment});class SLs extends $P{constructor(t){super(t),t.animationState||(t.animationState=iPs(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();PMe(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 CLs=0;class ALs extends $P{constructor(){super(...arguments),this.id=CLs++,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"){const c=HF(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 ELs={animation:{Feature:SLs},exit:{Feature:ALs}};function tre(s){return{point:{x:s.pageX,y:s.pageY}}}const TLs=s=>t=>lQe(t)&&s(t,tre(t));function AQ(s,t,n,r){return hee(s,t,TLs(n),r)}const uOt=({current:s})=>s?s.ownerDocument.defaultView:null,Ipt=(s,t)=>Math.abs(s-t);function MLs(s,t){const n=Ipt(s.x,t.x),r=Ipt(s.y,t.y);return Math.sqrt(n**2+r**2)}const Rpt=new Set(["auto","scroll"]);class hOt{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=p=>{this.handleScroll(p.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=Noe(this.lastRawMoveEventInfo,this.transformPagePoint));const p=SOe(this.lastMoveEventInfo,this.history),f=this.startEvent!==null,x=MLs(p.offset,{x:0,y:0})>=this.distanceThreshold;if(!f&&!x)return;const{point:y}=p,{timestamp:v}=Ky;this.history.push({...y,timestamp:v});const{onStart:b,onMove:N}=this.handlers;f||(b&&b(this.lastMoveEvent,p),this.startEvent=this.lastMoveEvent),N&&N(this.lastMoveEvent,p)},this.handlePointerMove=(p,f)=>{this.lastMoveEvent=p,this.lastRawMoveEventInfo=f,this.lastMoveEventInfo=Noe(f,this.transformPagePoint),mm.update(this.updatePoint,!0)},this.handlePointerUp=(p,f)=>{this.end();const{onEnd:x,onSessionEnd:y,resumeAnimation:v}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&v&&v(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const b=SOe(p.type==="pointercancel"?this.lastMoveEventInfo:Noe(f,this.transformPagePoint),this.history);this.startEvent&&x&&x(p,b),y&&y(p,b)},!lQe(t))return;this.dragSnapToOrigin=i,this.handlers=n,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=a||window;const c=tre(t),d=Noe(c,this.transformPagePoint),{point:u}=d,{timestamp:h}=Ky;this.history=[{...u,timestamp:h}];const{onSessionStart:m}=n;m&&m(t,SOe(d,this.history)),this.removeListeners=Qne(AQ(this.contextWindow,"pointermove",this.handlePointerMove),AQ(this.contextWindow,"pointerup",this.handlePointerUp),AQ(this.contextWindow,"pointercancel",this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(t){let n=t.parentElement;for(;n;){const r=getComputedStyle(n);(Rpt.has(r.overflowX)||Rpt.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),mm.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),mP(this.updatePoint)}}function Noe(s,t){return t?{point:t(s.point)}:s}function Dpt(s,t){return{x:s.x-t.x,y:s.y-t.y}}function SOe({point:s},t){return{point:s,delta:Dpt(s,mOt(t)),offset:Dpt(s,PLs(t)),velocity:LLs(t,.1)}}function PLs(s){return s[0]}function mOt(s){return s[s.length-1]}function LLs(s,t){if(s.length<2)return{x:0,y:0};let n=s.length-1,r=null;const a=mOt(s);for(;n>=0&&(r=s[n],!(a.timestamp-r.timestamp>A_(t)));)n--;if(!r)return{x:0,y:0};r===s[0]&&s.length>2&&a.timestamp-r.timestamp>A_(t)*2&&(r=s[1]);const i=B2(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 ILs(s,{min:t,max:n},r){return t!==void 0&&sn&&(s=r?rp(n,s,r.max):Math.min(s,n)),s}function Opt(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 RLs(s,{top:t,left:n,bottom:r,right:a}){return{x:Opt(s.x,n,a),y:Opt(s.y,t,r)}}function Fpt(s,t){let n=t.min-s.min,r=t.max-s.max;return t.max-t.minr?n=cee(t.min,t.max-r,s.min):r>a&&(n=cee(s.min,s.max-a,t.min)),Z4(0,1,n)}function FLs(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 Qqe=.35;function zLs(s=Qqe){return s===!1?s=0:s===!0&&(s=Qqe),{x:zpt(s,"left","right"),y:zpt(s,"top","bottom")}}function zpt(s,t,n){return{min:Bpt(s,t),max:Bpt(s,n)}}function Bpt(s,t){return typeof s=="number"?s:s[t]||0}const BLs=new WeakMap;class ULs{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=Wx(),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(tre(h).point),this.stopAnimation()},l=(h,m)=>{const{drag:p,dragPropagation:f,onDragStart:x}=this.getProps();if(p&&!f&&(this.openDragLock&&this.openDragLock(),this.openDragLock=pMs(p),!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),k5(v=>{let b=this.getAxisMotionValue(v).get()||0;if(B4.test(b)){const{projection:N}=this.visualElement;if(N&&N.layout){const S=N.layout.layoutBox[v];S&&(b=tb(S)*(parseFloat(b)/100))}}this.originPoint[v]=b}),x&&mm.update(()=>x(h,m),!1,!0),$qe(this.visualElement,"transform");const{animationState:y}=this.visualElement;y&&y.setActive("whileDrag",!0)},o=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m;const{dragPropagation:p,dragDirectionLock:f,onDirectionLock:x,onDrag:y}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:v}=m;if(f&&this.currentDirection===null){this.currentDirection=$Ls(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&&mm.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 hOt(t,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:r,contextWindow:uOt(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&&mm.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||!koe(t,a,this.currentDirection))return;const i=this.getAxisMotionValue(t);let l=this.originPoint[t]+r[t];this.constraints&&this.constraints[t]&&(l=ILs(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&&OB(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&r?this.constraints=RLs(r.layoutBox,t):this.constraints=!1,this.elastic=zLs(n),a!==this.constraints&&!OB(t)&&r&&this.constraints&&!this.hasMutatedConstraints&&k5(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=FLs(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!OB(t))return!1;const r=t.current;qV(r!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.","drag-constraints-ref");const{projection:a}=this.visualElement;if(!a||!a.layout)return!1;const i=$Ms(r,a.root,this.visualElement.getTransformPagePoint());let l=DLs(a.layout.layoutBox,i);if(n){const o=n(BMs(l));this.hasMutatedConstraints=!!o,o&&(l=IDt(o))}return l}startAnimation(t){const{drag:n,dragMomentum:r,dragElastic:a,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=k5(u=>{if(!koe(u,n,this.currentDirection))return;let h=c&&c[u]||{};(l===!0||l===u)&&(h={min:0,max:0});const m=a?200:1e6,p=a?40:1e7,f={type:"inertia",velocity:r?t[u]:0,bounceStiffness:m,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...i,...h};return this.startAxisValueAnimation(u,f)});return Promise.all(d).then(o)}startAxisValueAnimation(t,n){const r=this.getAxisMotionValue(t);return $qe(this.visualElement,t),r.start(sQe(t,r,0,n,this.visualElement,!1))}stopAnimation(){k5(t=>this.getAxisMotionValue(t).stop())}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,r=this.visualElement.getProps(),a=r[n];return a||this.visualElement.getValue(t,(r.initial?r.initial[t]:void 0)||0)}snapToCursor(t){k5(n=>{const{drag:r}=this.getProps();if(!koe(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]-rp(l,o,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:r}=this.visualElement;if(!OB(n)||!r||!this.constraints)return;this.stopAnimation();const a={x:0,y:0};k5(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();a[l]=OLs({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(),k5(l=>{if(!koe(l,t,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(rp(c,d,a[l]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;BLs.set(this.visualElement,this);const t=this.visualElement.current,n=AQ(t,"pointerdown",d=>{const{drag:u,dragListener:h=!0}=this.getProps(),m=d.target,p=m!==t&&bMs(m);u&&h&&!p&&this.start(d)});let r;const a=()=>{const{dragConstraints:d}=this.getProps();OB(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),r||(r=qLs(t,d.current,()=>this.scalePositionWithinConstraints())))},{projection:i}=this.visualElement,l=i.addEventListener("measure",a);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),mm.read(a);const o=hee(window,"resize",()=>this.scalePositionWithinConstraints()),c=i.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u})=>{this.isDragging&&u&&(k5(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=Qqe,dragMomentum:o=!0}=t;return{...t,drag:n,dragDirectionLock:r,dragPropagation:a,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function Upt(s){let t=!0;return()=>{if(t){t=!1;return}s()}}function qLs(s,t,n){const r=Kmt(s,Upt(n)),a=Kmt(t,Upt(n));return()=>{r(),a()}}function koe(s,t,n){return(t===!0||t===s)&&(n===null||n===s)}function $Ls(s,t=10){let n=null;return Math.abs(s.y)>t?n="y":Math.abs(s.x)>t&&(n="x"),n}class VLs extends $P{constructor(t){super(t),this.removeGroupControls=nN,this.removeListeners=nN,this.controls=new ULs(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||nN}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 COe=s=>(t,n)=>{s&&mm.update(()=>s(t,n),!1,!0)};class HLs extends $P{constructor(){super(...arguments),this.removePointerDownListener=nN}onPointerDown(t){this.session=new hOt(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:uOt(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:r,onPanEnd:a}=this.node.getProps();return{onSessionStart:COe(t),onStart:COe(n),onMove:COe(r),onEnd:(i,l)=>{delete this.session,a&&mm.postRender(()=>a(i,l))}}}mount(){this.removePointerDownListener=AQ(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 AOe=!1;class GLs 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),AOe&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),I5e.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}),AOe=!0,a||t.layoutDependency!==n||n===void 0||t.isPresent!==i?l.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?l.promote():l.relegate()||mm.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(),oQe.postRender(()=>{!r.currentAnimation&&r.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r}=this.props,{projection:a}=t;AOe=!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 pOt(s){const[t,n]=sOt(),r=j.useContext(qXe);return e.jsx(GLs,{...s,layoutGroup:r,switchLayoutGroup:j.useContext(cOt),isPresent:t,safeToRemove:n})}const WLs={pan:{Feature:HLs},drag:{Feature:VLs,ProjectionNode:tOt,MeasureLayout:pOt}};function qpt(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&&mm.postRender(()=>i(t,tre(t)))}class KLs extends $P{mount(){const{current:t}=this.node;t&&(this.unmount=gMs(t,(n,r)=>(qpt(this.node,r,"Start"),a=>qpt(this.node,a,"End"))))}unmount(){}}class YLs extends $P{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=Qne(hee(this.node.current,"focus",()=>this.onFocus()),hee(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function $pt(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&&mm.postRender(()=>i(t,tre(t)))}class ZLs extends $P{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:r}=this.node.props;this.unmount=wMs(t,(a,i)=>($pt(this.node,i,"Start"),(l,{success:o})=>$pt(this.node,l,o?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:(r==null?void 0:r.tap)===!1})}unmount(){}}const Jqe=new WeakMap,EOe=new WeakMap,XLs=s=>{const t=Jqe.get(s.target);t&&t(s)},QLs=s=>{s.forEach(XLs)};function JLs({root:s,...t}){const n=s||document;EOe.has(n)||EOe.set(n,{});const r=EOe.get(n),a=JSON.stringify(t);return r[a]||(r[a]=new IntersectionObserver(QLs,{root:s,...t})),r[a]}function eIs(s,t,n){const r=JLs(t);return Jqe.set(s,n),r.observe(s),()=>{Jqe.delete(s),r.unobserve(s)}}const tIs={some:0,all:1};class sIs extends $P{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:tIs[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(),p=u?h:m;p&&p(d)};this.stopObserver=eIs(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(nIs(t,n))&&this.startObserver()}unmount(){var t;(t=this.stopObserver)==null||t.call(this),this.hasEnteredView=!1,this.isInView=!1}}function nIs({viewport:s={}},{viewport:t={}}={}){return n=>s[n]!==t[n]}const rIs={inView:{Feature:sIs},tap:{Feature:ZLs},focus:{Feature:YLs},hover:{Feature:KLs}},aIs={layout:{ProjectionNode:tOt,MeasureLayout:pOt}},iIs={...ELs,...rIs,...WLs,...aIs},kr=NLs(iIs,kLs),oIs={some:0,all:1};function lIs(s,t,{root:n,margin:r,amount:a="some"}={}){const i=iQe(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:oIs[a]});return i.forEach(d=>c.observe(d)),()=>c.disconnect()}function cIs(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 lIs(s.current,c,d)},[t,s,n,a,r]),l}function dIs(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 Vpt(s){return s.visitor_intent==="buying"&&!s.has_agent}function uIs({token:s}={}){var f;const t=Di(),n=s||t.token,{data:r,isLoading:a,isError:i}=lTs(n),l=Qt(),o=(f=r==null?void 0:r.open_houses)==null?void 0:f.id,{data:c}=ct({queryKey:["cohost-visitors",o],queryFn:async()=>{const{data:x,error:y}=await q.from("open_house_visitors").select("*").eq("open_house_id",o).order("created_at",{ascending:!1});if(y)throw y;return x},enabled:!!o});if(j.useEffect(()=>{if(!o)return;const x=q.channel(`cohost-visitors-${o}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"open_house_visitors",filter:`open_house_id=eq.${o}`},()=>{l.invalidateQueries({queryKey:["cohost-visitors",o]})}).subscribe();return()=>{q.removeChannel(x)}},[o,l]),a)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex items-center justify-center",children:e.jsx("div",{className:"animate-pulse text-white/40",children:"Validating access..."})});if(i||!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 d=r.open_houses,u=(c==null?void 0:c.length)||0,h=(c==null?void 0:c.filter(x=>x.visitor_intent==="buying").length)||0,m=(c==null?void 0:c.filter(Vpt).length)||0,p=x=>{if(!x)return"";const[y,v]=x.split(":"),b=parseInt(y);return`${b>12?b-12:b||12}:${v} ${b>=12?"PM":"AM"}`};return e.jsxs("div",{className:"fixed inset-0 bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex flex-col",children:[e.jsxs("div",{className:"border-b border-white/10 px-4 sm:px-6 py-3 flex items-center justify-between bg-black/30 backdrop-blur-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{className:"text-xs font-medium text-emerald-400 uppercase tracking-wider",children:"Live · Co-Host View"})]}),e.jsx("h1",{className:"text-white font-bold text-sm sm:text-base truncate",children:d.property_address})]}),e.jsxs("div",{className:"flex items-center gap-4 sm:gap-6 text-white/70",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Bn,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:u})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-orange-400",children:[e.jsx(Xd,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:m})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ra,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:h})]})]})]}),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:Gs(new Date(d.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy")}),d.start_time&&e.jsxs("span",{children:[p(d.start_time),d.end_time?` – ${p(d.end_time)}`:""]})]}),e.jsx(Gi,{className:"flex-1 p-4 sm:p-6",children:c!=null&&c.length?e.jsx("div",{className:"space-y-2 max-w-3xl mx-auto",children:e.jsx(_G,{children:c.map((x,y)=>{var N;const v=dIs(x.visitor_intent),b=Vpt(x);return e.jsxs(kr.div,{initial:{opacity:0,x:-40,scale:.95},animate:{opacity:1,x:0,scale:1},transition:{duration:.4,delay:y*.05},className:`flex items-center gap-4 p-4 rounded-xl border ${b?"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 ${b?"bg-gradient-to-br from-orange-500 to-amber-500 text-white":"bg-white/10 text-white/80"}`,children:(N=x.first_name[0])==null?void 0:N.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:[x.first_name," ",x.last_name||""]}),b&&e.jsx(Be,{className:"bg-orange-500/20 text-orange-300 border-orange-500/40 text-[10px] px-1.5 py-0",children:"🔥 HOT"}),x.has_agent&&e.jsx(Be,{variant:"outline",className:"text-[10px] px-1.5 py-0 border-yellow-500/40 text-yellow-400",children:"⚠️ Has Agent"})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsxs(Be,{variant:"outline",className:`text-[10px] px-1.5 py-0 ${v.color}`,children:[v.emoji," ",v.label]}),e.jsx("span",{className:"text-white/30 text-xs",children:Gs(new Date(x.created_at),"h:mm a")})]})]})]},x.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(mv,{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 hIs(){const t=Od().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(uIs,{token:n})}if(t.startsWith("rsvp/")){const n=t.slice(5);if(n)return e.jsx(ERt,{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(ARt,{slug:t})}function mIs({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(kr.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(kr.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(kr.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(ra,{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(ni,{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(ba,{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(ln,{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(vu,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function fOt({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=hN(a,new Date);if(z4(a)&&!ry(a))return null;const o=ry(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(kr.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(kr.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 gOt({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(kr.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 Su(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 Hpt(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 pIs=[{key:"contract_date",label:"Contract Accepted",icon:T4},{key:"earnest_money_due_date",label:"Earnest Money",icon:yu},{key:"inspection_date",label:"Inspection",icon:Fr},{key:"inspection_contingency_date",label:"Inspection Deadline",icon:Ur},{key:"appraisal_date",label:"Appraisal",icon:ra},{key:"loan_approval_date",label:"Loan Approval",icon:tq},{key:"title_docs_due_date",label:"Title & Disclosures",icon:Ur},{key:"final_walkthrough_date",label:"Final Walkthrough",icon:SA},{key:"target_close_date",label:"Target Close",icon:pa}];function fIs(s,t){const n=Gs(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 gIs(s,t){const n=Gs(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 yOt({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=pIs.map(p=>p.key==="target_close_date"&&c?{...p,label:"Closed",date:c,done:!0}:{...p,date:o[p.key],done:d.includes(p.key)}).filter(p=>!!p.date);if(u.length===0)return null;const h=(p,f,x)=>{const y=Su(f);if(x==="google")window.open(fIs(p,y),"_blank");else{const v=gIs(p,y),b=document.createElement("a");b.href=v,b.download=`${p.replace(/\s+/g,"-").toLowerCase()}.ics`,b.click()}},m=u.filter(p=>p.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:p,date:f,done:x,icon:y})=>{const v=Su(f),b=z4(v)&&!ry(v),N=ry(v),S=!b&&!N,A=x?"Completed":N?"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))":N?"hsl(var(--portal-gold) / 0.25)":"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.7)",boxShadow:N?"0 0 12px hsl(var(--portal-gold) / 0.5)":"none"},children:x?e.jsx(Xr,{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:p}),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:Gs(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||N?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-dim))",border:`1px solid hsl(var(--portal-gold) / ${x||N?.5:.18})`},children:A})]}),S&&e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx("button",{onClick:()=>h(p,f,"google"),className:"p-1.5 rounded transition-colors",style:{color:"hsl(var(--portal-ink-dim))"},onMouseEnter:T=>{T.currentTarget.style.color="hsl(var(--portal-gold))"},onMouseLeave:T=>{T.currentTarget.style.color="hsl(var(--portal-ink-dim))"},title:"Add to Google Calendar",children:e.jsx(sv,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>h(p,f,"apple"),className:"text-[9px] tracking-widest px-1.5 py-1 rounded",style:{color:"hsl(var(--portal-ink-dim))"},title:"Download .ics",children:".ICS"})]})]},p)})]})]})}function vOt({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(Ur,{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(pi,{className:"w-4 h-4 flex-shrink-0",style:{color:"hsl(var(--portal-gold) / 0.5)"}})]},r.id))})]})}function bOt({slug:s,wrapper:t}){const n=Wn(),[r,a]=j.useState(null),{data:i=[]}=ct({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(Et,{className:"w-4 h-4 animate-spin",style:{color:"hsl(var(--portal-gold))"}}):e.jsx(Pg,{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(zr,{className:"w-4 h-4",style:{color:"hsl(var(--portal-ink-muted))"}}):e.jsx(Yr,{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 _Ot({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(xx,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}}):e.jsx(bx,{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:Gs(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 wG=[{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"}],xIs=[{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 yIs(s){return ct({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 vIs(){const s=Sa(),{brokerageId:t}=vs();return ct({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 bIs(){const s=Qt();return yt({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 wOt(){const s=Qt();return yt({mutationFn:async t=>{const{error:n}=await q.from("vendors").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function _Is(){const s=Sa(),t=Qt();return yt({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 jOt(s){return ct({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(p=>u.set(p.vendor_id,{display_order:p.display_order,is_visible:p.is_visible}));const h=new Map;return(d||[]).forEach(p=>h.set(p.vendor_id,p.is_visible)),(l||[]).filter(p=>{if(h.get(p.id)===!1)return!1;const f=u.get(p.id);return!(f&&f.is_visible===!1&&!p.is_required)}).map(p=>{var f;return{...p,display_order:((f=u.get(p.id))==null?void 0:f.display_order)??p.sort_order??0}}).sort((p,f)=>(p.display_order||0)-(f.display_order||0))},enabled:!!(s!=null&&s.id)&&!!(s!=null&&s.owner_user_id)})}async function Gpt(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 NOt(s,t){return ct({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 kOt({portalId:s,ownerUserId:t,currentStage:n,brandingColor:r,layout:a="list"}){const{data:i=[],isLoading:l}=jOt({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,N)=>{switch(N){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 N=d(b,b.action_type);Gpt({vendorId:b.id,portalId:s,agentUserId:t,actionTaken:b.action_type}),N&&window.open(N,b.action_type==="call"||b.action_type==="email"||b.action_type==="quote"?"_self":"_blank")},h=b=>{const N=d(b,b.action_type);return[{action:"website",label:"Website",icon:e.jsx(fl,{className:"w-3.5 h-3.5"})},{action:"email",label:"Email",icon:e.jsx(ln,{className:"w-3.5 h-3.5"})},{action:"call",label:"Call",icon:e.jsx(ba,{className:"w-3.5 h-3.5"})},{action:"book",label:"Book",icon:e.jsx(pa,{className:"w-3.5 h-3.5"})}].filter(A=>A.action!==b.action_type).map(A=>{const T=d(b,A.action);return!T||T===N?null:e.jsxs("button",{onClick:()=>{Gpt({vendorId:b.id,portalId:s,agentUserId:t,actionTaken:A.action}),window.open(T,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"}},p=b=>{switch(b.action_type){case"book":return e.jsx(pa,{className:"w-3.5 h-3.5"});case"call":return e.jsx(ba,{className:"w-3.5 h-3.5"});case"email":case"quote":return e.jsx(ln,{className:"w-3.5 h-3.5"});case"website":return e.jsx(fl,{className:"w-3.5 h-3.5"})}},f=b=>{var N;return((N=wG.find(S=>S.value===b))==null?void 0:N.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(cn,{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(we,{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:f(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(U,{size:"sm",onClick:()=>u(b),style:{backgroundColor:c},className:"text-white hover:opacity-90 w-full",children:[p(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,N)=>((b[N.category]=b[N.category]||[]).push(N),b),{});return e.jsxs(we,{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,N])=>e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:f(b)}),e.jsx("div",{className:"space-y-2",children:N.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(U,{size:"sm",onClick:()=>u(S),style:{backgroundColor:c},className:"text-white hover:opacity-90 shrink-0",children:[p(S),e.jsx("span",{className:"ml-1.5 text-xs",children:m(S)})]})]},S.id))})]},b))}),y]})}function wIs(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 jIs(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 SOt({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=wIs(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 p=async T=>{await q.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:T,user_agent:navigator.userAgent.slice(0,500)})},f=()=>`${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),p("copy_link"),setTimeout(()=>u(!1),2e3)},y=()=>{p("share_sms");const T=encodeURIComponent(f());window.location.href=`sms:?&body=${T}`},v=()=>{p("share_email");const T=encodeURIComponent("A referral you'll thank me for"),L=encodeURIComponent(f());window.location.href=`mailto:?subject=${T}&body=${L}`},b=()=>{p("open_form"),window.open(m,"_blank")},N=a||"Know someone buying or selling?",S=c?jIs(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(cn,{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(Ro,{className:"w-3 h-3"}),"Referral Program"]}),e.jsx("h3",{className:"text-xl font-bold leading-tight mb-2 font-serif",children:N}),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(Oa,{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(vu,{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(ln,{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(Xr,{className:"w-3.5 h-3.5"}):e.jsx(Pa,{className:"w-3.5 h-3.5"}),d?"Copied":"Copy"]})]})]})]}),o&&e.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",onClick:()=>p("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(Oa,{className:"w-4 h-4 text-slate-400"})]})})]})}function COt(s){return ct({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 AOt(){const s=Qt();return yt({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"]})}})}function NIs(){const s=Qt();return yt({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"]})}})}function EOt({portalId:s,clientName:t,agentName:n,agentAvatar:r,deviceFingerprint:a}){const{data:i,isLoading:l}=COt(s),o=AOt(),[c,d]=j.useState(""),u=`portal_msg_name_${s}`,[h,m]=j.useState(()=>localStorage.getItem(u)||t||""),p=j.useRef(null);j.useEffect(()=>{var y;(y=p.current)==null||y.scrollIntoView({block:"nearest"})},[i==null?void 0:i.length]);const f=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(Ki,{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(Et,{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"," ·"," ",Gs(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:p})]}),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:f,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(Et,{className:"w-4 h-4 animate-spin"}):e.jsx($r,{className:"w-4 h-4"}),"Send message"]})]})]})}function kIs(s){return s==="buy-side"?"Home Search in Progress":s==="listing"?"Your Home Is On The Market":"Active Phase"}function SIs(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 CIs={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. 🎉"}},TOt=["Lead","Consultation","Agreement Signed","Active","Under Contract","Closing","Closed Won"];function RMe(s){return TOt.map(t=>{if(t==="Active")return{key:"Active",label:kIs(s),description:SIs(s)};const n=CIs[t];return{key:t,label:n.label,description:n.description}})}function jCe(s){if(!s)return 0;const t=TOt.indexOf(s);return t>=0?t:0}function AIs({portal:s,linkedPortal:t,activePortal:n,activeTab:r,onTabChange:a,agentProfile:i,branding:l,updates:o,documents:c}){var K,Z,Q;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,p=m==null?void 0:m.deal_pipeline_stages,f=p==null?void 0:p.is_won_stage,x=m==null?void 0:m.deal_type,y=n==null?void 0:n.stage_mapping;let v=RMe(x);y&&y.length>0&&(v=y.map((le,ue)=>{var se,ne;return{key:`custom-${ue}`,label:le.label||((se=v[ue])==null?void 0:se.label)||`Stage ${ue+1}`,description:le.description||((ne=v[ue])==null?void 0:ne.description)||"",video_url:le.video_url||void 0}}));const b=y&&y.length>0?Math.min(jCe(p==null?void 0:p.name),v.length-1):jCe(p==null?void 0:p.name),N=v[b],S=N==null?void 0:N.video_url,A=f&&n.show_post_close_tips!==!1&&n.referral_enabled!==!1,T=m!=null&&m.property_address?`${m.property_address}, ${m.city||""}, ${m.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,L=!!t,M=(K=s==null?void 0:s.deal_pipeline)==null?void 0:K.deal_type,I=(Z=t==null?void 0:t.deal_pipeline)==null?void 0:Z.deal_type,R=le=>le==="listing"?"Your Sale":le==="buy-side"?"Your Purchase":"Transaction",z=v.length>1?Math.round((b+1)/v.length*100):0,{data:$=[]}=jOt({id:n==null?void 0:n.id,owner_user_id:n==null?void 0:n.owner_user_id}),H=$.some(le=>!le.stage_filter||le.stage_filter.length===0||!(p!=null&&p.name)?!0:le.stage_filter.includes(p.name)),V=()=>{var le;(le=document.getElementById("trusted-vendors"))==null||le.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(kr.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(Im,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}}),"Secure & Encrypted"]})]}),e.jsxs(kr.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(ra,{className:"w-3 h-3"}),x==="listing"?"Sale":x==="buy-side"?"Purchase":"Transaction",f&&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"}),T&&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(ni,{className:"w-4 h-4",style:{color:"var(--portal-hero-accent)"}}),e.jsx("span",{className:"text-base",children:T})]}),(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(EIs,{pct:z}),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)"}})]}),L&&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(le=>{const ue=le==="primary"?M:I,se=r===le;return e.jsx("button",{onClick:()=>a(le),className:"portal-serif px-5 py-2 rounded-lg transition-all",style:{fontSize:"1rem",background:se?"hsl(var(--portal-surface-3))":"transparent",color:se?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",borderBottom:se?"1px solid hsl(var(--portal-gold))":"1px solid transparent"},children:R(ue)},le)})}),e.jsxs(kr.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(a5,{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:((Q=i==null?void 0:i.name)==null?void 0:Q.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(TOe,{href:`tel:${i.phone}`,icon:ba,label:"Call",sub:i.phone}),(i==null?void 0:i.phone)&&e.jsx(TOe,{href:`sms:${i.phone}`,icon:vu,label:"Text message"}),(i==null?void 0:i.email)&&e.jsx(TOe,{href:`mailto:${i.email}`,icon:ln,label:"Email",sub:i.email})]})]}),e.jsxs(a5,{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(MOe,{icon:pa,label:"Target close",value:Wpt(m.target_close_date)}),(m==null?void 0:m.contract_date)&&e.jsx(MOe,{icon:Yr,label:"Under contract",value:Wpt(m.contract_date)}),e.jsx(MOe,{icon:rl,label:"Progress",value:`${z}%`})]})]})]})}),e.jsxs("main",{className:"col-span-6 space-y-5",children:[A&&e.jsx(SOt,{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(fOt,{targetCloseDate:m==null?void 0:m.target_close_date,actualCloseDate:m==null?void 0:m.actual_close_date,clientName:n.client_name}),N&&e.jsx(a5,{children:e.jsx(xOt,{currentStage:N,nextStepText:n.next_step_text,nextStepVideoUrl:S||n.next_step_video_url})}),e.jsx(a5,{children:e.jsx(gOt,{journeyStages:v,currentIndex:b})}),o&&o.length>0&&e.jsx(a5,{children:e.jsx(_Ot,{updates:o})}),(n==null?void 0:n.id)&&e.jsx(a5,{children:e.jsx(EOt,{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(a5,{children:e.jsx(yOt,{deal:m,portal:n})}),(n==null?void 0:n.slug)&&e.jsx(bOt,{slug:n.slug,wrapper:le=>e.jsx(a5,{children:le})}),c&&c.length>0&&e.jsx(a5,{children:e.jsx(vOt,{documents:c})}),H&&e.jsx(a5,{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:le=>{le.currentTarget.style.background="hsl(var(--portal-gold) / 0.12)"},onMouseLeave:le=>{le.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(xq,{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(rl,{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(kOt,{portalId:n.id,ownerUserId:n.owner_user_id,currentStage:p==null?void 0:p.name,brandingColor:"hsl(var(--portal-gold))",layout:"grid"})})]})]})}function a5({children:s}){return e.jsx(kr.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 TOe({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 MOe({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 EIs({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(kr.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 Wpt(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 TIs({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=yt({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.")}}),p=t!=null&&t.property_address?`${t.property_address}, ${t.city||""}, ${t.state||""}`:null,f="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"}),p&&e.jsxs("div",{className:"flex items-center justify-center gap-1 text-slate-500 text-sm mt-1",children:[e.jsx(ni,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:p.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(te,{className:"text-xs font-medium text-slate-700",children:"First Name *"}),e.jsx(xe,{required:!0,value:l.first_name,onChange:b=>o(N=>({...N,first_name:b.target.value})),className:f,placeholder:"John"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(xe,{value:l.last_name,onChange:b=>o(N=>({...N,last_name:b.target.value})),className:f,placeholder:"Doe"})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(xe,{type:"email",value:l.email,onChange:b=>o(N=>({...N,email:b.target.value})),className:f,placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(xe,{type:"tel",value:l.phone,onChange:b=>o(N=>({...N,phone:b.target.value})),className:f,placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(te,{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(N=>({...N,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(te,{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(N=>({...N,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(te,{className:"text-xs font-medium text-slate-700",children:[b.question_text," ",b.is_required&&"*"]}),b.field_type==="text"&&e.jsx(xe,{required:b.is_required,value:c[b.id]||"",onChange:N=>d(S=>({...S,[b.id]:N.target.value})),className:f}),b.field_type==="textarea"&&e.jsx("textarea",{required:b.is_required,value:c[b.id]||"",onChange:N=>d(S=>({...S,[b.id]:N.target.value})),className:`${x} min-h-[80px]`}),b.field_type==="dropdown"&&e.jsxs("select",{required:b.is_required,value:c[b.id]||"",onChange:N=>d(S=>({...S,[b.id]:N.target.value})),className:`${x} h-10`,children:[e.jsx("option",{value:"",children:"Select..."}),(b.options||[]).map(N=>e.jsx("option",{value:N,children:N},N))]}),b.field_type==="toggle"&&e.jsx("div",{className:"mt-1.5 flex gap-2",children:["Yes","No"].map(N=>e.jsx("button",{type:"button",onClick:()=>d(S=>({...S,[b.id]:N})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c[b.id]===N?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200"}`,children:N},N))})]},b.id)),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs font-medium text-slate-700",children:"Notes for your agent"}),e.jsx("textarea",{value:l.notes,onChange:b=>o(N=>({...N,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(te,{className:"text-xs font-medium text-slate-700",children:"First Name"}),e.jsx(xe,{value:l.spouse_first_name,onChange:b=>o(N=>({...N,spouse_first_name:b.target.value})),className:f})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(xe,{value:l.spouse_last_name,onChange:b=>o(N=>({...N,spouse_last_name:b.target.value})),className:f})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(xe,{type:"email",value:l.spouse_email,onChange:b=>o(N=>({...N,spouse_email:b.target.value})),className:f})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(xe,{type:"tel",value:l.spouse_phone,onChange:b=>o(N=>({...N,spouse_phone:b.target.value})),className:f})]})]})]}),e.jsx(U,{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 MIs(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 MOt(){const s=Sa();return ct({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 PIs(s){return ct({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 LIs(){const s=Sa(),t=Qt();return yt({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 POt(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 IIs(s,t){return ct({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 RIs(s){return ct({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 LOt({slug:s}){var le,ue,se,ne,ie,ce;const[t,n]=j.useState(!1),[r,a]=j.useState("primary"),[i]=j.useState(()=>{const je=`portal_fp_${s}`;let be=localStorage.getItem(je);return be||(be=localStorage.getItem("portal_fp"),be?localStorage.setItem(je,be):(be=crypto.randomUUID(),localStorage.setItem(je,be),localStorage.setItem("portal_fp",be))),be});j.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:l,isLoading:o,error:c}=IIs(s,!0),d=l==null?void 0:l.linked_portal_id,{data:u}=RIs(d),h=(le=l==null?void 0:l.deal_pipeline)==null?void 0:le.owner_user_id;ct({queryKey:["portal-stages",h],queryFn:async()=>{const{data:je,error:be}=await q.from("deal_pipeline_stages").select("*").eq("owner_user_id",h).order("sort_order",{ascending:!0});if(be)throw be;return je},enabled:!!h});const{data:m}=ct({queryKey:["portal-agent",h],queryFn:async()=>{const{data:je,error:be}=await q.from("profiles").select("id, name, avatar_url, phone, email").eq("id",h).single();if(be)throw be;return je},enabled:!!h}),{data:p}=PIs(h),f=r==="linked"&&u?u:l,x=f==null?void 0:f.id,y=MIs(p,f==null?void 0:f.branding_override),v=y.portal_theme==="azure"?"azure":"noir";j.useEffect(()=>{const je=`portal-theme-${v}`;return document.body.classList.add(je),()=>document.body.classList.remove(je)},[v]);const{data:b}=ct({queryKey:["portal-updates-public",x],queryFn:async()=>{const{data:je,error:be}=await q.from("portal_updates").select("*").eq("portal_id",x).order("created_at",{ascending:!1});if(be)throw be;return je},enabled:!!x}),N=(ue=f==null?void 0:f.deal_pipeline)==null?void 0:ue.id,{data:S}=ct({queryKey:["portal-documents",N],queryFn:async()=>{const{data:je,error:be}=await q.from("deal_files").select("*").eq("deal_id",N).eq("visible_on_portal",!0).order("created_at",{ascending:!1});if(be)throw be;return je},enabled:!!N}),A=l==null?void 0:l.id,T=A?`portal_onboarded_${A}_${i}`:null,L=T?localStorage.getItem(T)==="1":!1,{data:M,isLoading:I}=ct({queryKey:["portal-onboarding-check",A,i],queryFn:async()=>{const{data:je,error:be}=await q.from("portal_onboarding_submissions").select("id").eq("portal_id",A).eq("device_fingerprint",i).maybeSingle();if(be)throw be;return je&&T&&localStorage.setItem(T,"1"),je},enabled:!!A&&!!(l!=null&&l.require_onboarding)&&!L,staleTime:5*60*1e3}),R=!!(l!=null&&l.require_onboarding)&&!L&&!M&&!t,{data:z}=ct({queryKey:["portal-custom-questions-public",h],queryFn:async()=>{const{data:je,error:be}=await q.from("portal_custom_questions").select("*").eq("owner_user_id",h).eq("is_active",!0).order("sort_order",{ascending:!0});if(be)throw be;return je},enabled:!!h&&R}),$=L||!!M||t||!(l!=null&&l.require_onboarding);if(o||l!=null&&l.require_onboarding&&!L&&I)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:"hsl(var(--portal-bg))"},children:e.jsx(Et,{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(Im,{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(!$){const je=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(TIs,{portal:l,dealData:je,agentProfile:m,customQuestions:z||[],deviceFingerprint:i,onComplete:()=>{T&&localStorage.setItem(T,"1"),n(!0)}})})}const H=(se=l==null?void 0:l.deal_pipeline)==null?void 0:se.deal_type,V=(ne=u==null?void 0:u.deal_pipeline)==null?void 0:ne.deal_type,K=!!u,Z=je=>je==="listing"?"Your Sale":je==="buy-side"?"Your Purchase":"Transaction",Q=je=>je==="listing"?e.jsx(ra,{className:"w-3.5 h-3.5"}):e.jsx(C_,{className:"w-3.5 h-3.5"});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden lg:block",children:e.jsx(AIs,{portal:l,linkedPortal:u,activePortal:f,activeTab:r,onTabChange:a,agentProfile:m,branding:y,updates:b,documents:S})}),e.jsxs("div",{className:"lg:hidden min-h-screen pb-16",style:{background:"var(--portal-gradient-noir)"},children:[e.jsx(mIs,{dealData:f==null?void 0:f.deal_pipeline,agentProfile:m,welcomeMessage:(f==null?void 0:f.welcome_message)||y.welcome_message,isWon:(ce=(ie=f==null?void 0:f.deal_pipeline)==null?void 0:ie.deal_pipeline_stages)==null?void 0:ce.is_won_stage,branding:y}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 space-y-5 mt-8",children:[K&&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(je=>{const be=r===je,he=je==="primary"?H:V;return e.jsxs("button",{onClick:()=>a(je),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:be?"hsl(var(--portal-surface-3))":"transparent",color:be?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",boxShadow:be?"0 1px 0 hsl(var(--portal-gold) / 0.3) inset":"none"},children:[Q(he),e.jsx("span",{style:{fontSize:"1rem"},children:Z(he)})]},je)})}),e.jsx(DIs,{portal:f,updates:b,documents:S,agentProfile:m}),x&&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(EOt,{portalId:x,clientName:f==null?void 0:f.client_name,agentName:m==null?void 0:m.name,agentAvatar:m==null?void 0:m.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(Im,{className:"w-3 h-3"}),e.jsx("span",{className:"text-[10px] tracking-[0.2em] uppercase",children:"Secure Client Portal"})]}),m&&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:m.name})]})]})]})]})]})}function DIs({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=RMe(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(jCe(l==null?void 0:l.name),u.length-1):jCe(l==null?void 0:l.name),m=u[h],p=m==null?void 0:m.video_url,f=o&&s.show_post_close_tips!==!1&&s.referral_enabled!==!1;return e.jsxs(e.Fragment,{children:[f&&e.jsx(SOt,{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(fOt,{targetCloseDate:i==null?void 0:i.target_close_date,actualCloseDate:i==null?void 0:i.actual_close_date,clientName:s.client_name}),e.jsx(gOt,{journeyStages:u,currentIndex:h}),m&&e.jsx(xOt,{currentStage:m,nextStepText:s.next_step_text,nextStepVideoUrl:p||s.next_step_video_url}),e.jsx(yOt,{deal:i,portal:s}),(s==null?void 0:s.slug)&&e.jsx(bOt,{slug:s.slug}),n&&n.length>0&&e.jsx(vOt,{documents:n}),(s==null?void 0:s.id)&&(s==null?void 0:s.owner_user_id)&&e.jsx(kOt,{portalId:s.id,ownerUserId:s.owner_user_id,currentStage:l==null?void 0:l.name}),t&&t.length>0&&e.jsx(_Ot,{updates:t})]})}function IOt({slug:s}){const t=Di(),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(""),[p,f]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState("buying"),[N,S]=j.useState("");j.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:A,isLoading:T,error:L}=ct({queryKey:["portal-referral-target",n],queryFn:async()=>{if(!n)return null;const{data:R,error:z}=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(z)throw z;return R},enabled:!!n}),{data:M}=ct({queryKey:["portal-referral-agent",A==null?void 0:A.owner_user_id],queryFn:async()=>{const{data:R}=await q.from("profiles").select("id, name, avatar_url").eq("id",A.owner_user_id).single();return R},enabled:!!(A!=null&&A.owner_user_id)}),I=async R=>{if(R.preventDefault(),!A||!h.trim()){re.error("Please enter your friend's name");return}if(!p.trim()&&!x.trim()){re.error("Please add at least an email or phone for your friend");return}a(!0);try{const{error:z}=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:p.trim()||null,friend_phone:x.trim()||null,friend_interest:v,friend_message:N.trim()||null});if(z)throw z;l(!0)}catch(z){re.error(z.message||"Could not submit referral")}finally{a(!1)}};return T?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"})}):L||!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(Xr,{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 ",(M==null?void 0:M.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(Aa,{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:[M!=null&&M.avatar_url?e.jsx("img",{src:M.avatar_url,alt:M.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(Ro,{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(Ro,{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 ",(M==null?void 0:M.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:I,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(te,{htmlFor:"friend_name",className:"text-sm",children:["Their name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(xe,{id:"friend_name",value:h,onChange:R=>m(R.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(te,{htmlFor:"friend_email",className:"text-sm",children:"Email"}),e.jsx(xe,{id:"friend_email",type:"email",value:p,onChange:R=>f(R.target.value),placeholder:"jane@email.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"friend_phone",className:"text-sm",children:"Phone"}),e.jsx(xe,{id:"friend_phone",type:"tel",value:x,onChange:R=>y(R.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(te,{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(R=>e.jsx("button",{type:"button",onClick:()=>b(R.v),className:`rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${v===R.v?"bg-[#406E71] text-white border-[#406E71]":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:R.l},R.v))})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"friend_message",className:"text-sm",children:"A note (optional)"}),e.jsx("textarea",{id:"friend_message",value:N,onChange:R=>S(R.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(te,{htmlFor:"referrer_name",className:"text-sm",children:"Your name"}),e.jsx(xe,{id:"referrer_name",value:o,onChange:R=>c(R.target.value),placeholder:A.client_name||"Your name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"referrer_email",className:"text-sm",children:"Your email"}),e.jsx(xe,{id:"referrer_email",type:"email",value:d,onChange:R=>u(R.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(Et,{className:"w-4 h-4 animate-spin"}):e.jsx(Ro,{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 OIs(){const t=Od().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(IOt,{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(LOt,{slug:t})}function FIs(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 NCe({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(()=>FIs(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(ra,{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 ROt({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,p]=u.split(/[-/T]/);return h?`${m}/${p}/${h}`:null};return e.jsx(zs,{open:t,onOpenChange:u=>{u||n()},children:e.jsxs(Ds,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(Vs,{className:"px-6 pt-6 pb-2",children:[e.jsx($s,{className:"text-xl",children:s.address}),e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(ni,{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(NCe,{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(NCe,{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(ra,{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(yu,{className:"w-6 h-6 text-muted-foreground"}),(l||0).toLocaleString()]}),o&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",o,"/sqft"]})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx(Be,{variant:"outline",children:s.status}),s.daysOnMarket!=null&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[s.daysOnMarket," DOM"]})]})]}),(s.listDate||s.statusChangeDate||s.soldDate)&&e.jsxs("div",{className:"px-6 pt-4",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-2",children:"Timeline"}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(POe,{label:"Active",date:c(s.listDate),active:!0}),e.jsx(POe,{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(POe,{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(Soe,{icon:e.jsx(Xw,{className:"w-4 h-4"}),label:"Beds",value:s.bedrooms??"—"}),e.jsx(Soe,{icon:e.jsx(d0,{className:"w-4 h-4"}),label:"Baths",value:s.bathrooms??"—"}),e.jsx(Soe,{icon:e.jsx(I4,{className:"w-4 h-4"}),label:"SqFt",value:((d=s.sqft)==null?void 0:d.toLocaleString())??"—"}),e.jsx(Soe,{icon:e.jsx(pa,{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(F1,{label:"MLS #",value:s.mlsNumber}),e.jsx(F1,{label:"Property Type",value:s.propertySubType||s.propertyType}),e.jsx(F1,{label:"Lot Size",value:s.lotSize}),e.jsx(F1,{label:"Garage",value:s.garageSpaces}),e.jsx(F1,{label:"Stories",value:s.stories}),e.jsx(F1,{label:"HOA",value:s.hoaFee?`$${s.hoaFee}/${(s.hoaFrequency||"mo").toLowerCase()}`:null}),e.jsx(F1,{label:"Tax (annual)",value:s.taxAmount?`$${s.taxAmount.toLocaleString()}`:null}),e.jsx(F1,{label:"Heating",value:s.heating}),e.jsx(F1,{label:"Cooling",value:s.cooling}),e.jsx(F1,{label:"Parking",value:s.parking}),e.jsx(F1,{label:"Elementary",value:s.elementarySchool}),e.jsx(F1,{label:"Middle",value:s.middleSchool}),e.jsx(F1,{label:"High",value:s.highSchool}),e.jsx(F1,{label:"Listed By",value:s.listAgentFullName}),e.jsx(F1,{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 Soe({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 F1({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 POe({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 Coe({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=p=>1-Math.pow(1-p,3),m=setTimeout(()=>{const p=f=>{d||(d=f);const x=f-d,y=Math.min(1,x/t);o(Math.round(u+(s-u)*h(y))),y<1&&(c.current=requestAnimationFrame(p))};c.current=requestAnimationFrame(p)},i);return()=>{clearTimeout(m),c.current&&cancelAnimationFrame(c.current)}},[s,t,i]),e.jsxs("span",{className:a,children:[n,l.toLocaleString(),r]})}function zIs({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,p]=j.useState(i),{commission:f,closing:x,net:y}=j.useMemo(()=>{const N=Math.round(l*u/100),S=Math.round(l*m/100);return{commission:N,closing:S,net:Math.max(0,l-N-S-(c||0))}},[l,u,m,c]),v=N=>`$${N.toLocaleString()}`,b=n>s?(l-s)/(n-s)*100:50;return e.jsxs(we,{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(rc,{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(rg,{value:[l],min:s,max:n,step:1e3,onValueChange:([N])=>o(N)}),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(te,{className:"text-xs",children:"Mortgage payoff"}),e.jsx(xe,{type:"number",inputMode:"numeric",value:c||"",placeholder:"$0",onChange:N=>d(Number(N.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Commission %"}),e.jsx(xe,{type:"number",step:"0.25",value:u,onChange:N=>h(Number(N.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Closing costs %"}),e.jsx(xe,{type:"number",step:"0.25",value:m,onChange:N=>p(Number(N.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(f)]}),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(yQ,{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 DOt({tokenOverride:s}={}){var Me,Oe,Se,Qe,Ae,Fe,Ne,$e,Ve,qe,Ze,Ue;const t=Di(),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(""),[p,f]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState(!1),[N,S]=j.useState(!1),[A,T]=j.useState(null),[L,M]=j.useState(null),[I,R]=j.useState(!1),{toast:z}=Ai();j.useEffect(()=>{n&&(async()=>{const{data:Ye}=await q.from("cmas").select("*").eq("share_token",n).eq("status","shared").maybeSingle();if(!Ye){u(!1);return}a(Ye);const[{data:Ge},{data:He}]=await Promise.all([q.from("cma_comps").select("*").eq("cma_id",Ye.id).order("position"),q.from("profiles").select("id,name,email,phone,avatar_url,brokerage_name,website_url,title,bio").eq("id",Ye.agent_id).maybeSingle()]);c((Ge||[]).filter(pt=>pt.selected)),l(He);const tt=localStorage.getItem("cma_visitor_token")||crypto.randomUUID();localStorage.setItem("cma_visitor_token",tt),await q.from("cma_views").insert({cma_id:Ye.id,visitor_token:tt,user_agent:navigator.userAgent}),u(!1)})()},[n]);const $=async Ye=>{if(!r)return;const Ge=localStorage.getItem("cma_visitor_token")||"";await q.from("cma_views").insert({cma_id:r.id,visitor_token:Ge,reactions:{[Ye]:!0}}),q.functions.invoke("cma-reply-notify",{body:{shareToken:n,reaction:Ye,visitorToken:Ge}}).catch(()=>{}),z({title:"Thanks — your agent just got notified ✨"})},H=!(r!=null&&r.contact_id),V=async()=>{if(!r||!h.trim())return;if(H&&(!p.trim()||!x.trim())){z({title:"Please add your name and email",variant:"destructive"});return}b(!0);const Ye=localStorage.getItem("cma_visitor_token")||"",{data:Ge,error:He}=await q.functions.invoke("cma-reply-notify",{body:{shareToken:n,message:h,visitorToken:Ye,viewerName:p.trim()||void 0,viewerEmail:x.trim()||void 0}});if(b(!1),He||!(Ge!=null&&Ge.success)){z({title:"Could not send",description:(He==null?void 0:He.message)||(Ge==null?void 0:Ge.error),variant:"destructive"});return}m(""),S(!0),z({title:"Message sent to your agent"})},K=j.useMemo(()=>{const Ye=o.map(Ge=>{const He=Ge.snapshot,tt=(He==null?void 0:He.soldPrice)||(He==null?void 0:He.price);return tt&&(He!=null&&He.sqft)?tt/He.sqft:null}).filter(Ge=>!!Ge).sort((Ge,He)=>Ge-He);return Ye.length?Math.round(Ye[Math.floor(Ye.length/2)]):null},[o]);if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsx(Et,{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(ra,{className:"w-12 h-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h1",{className:"text-xl font-semibold",children:"CMA not found"}),e.jsx("p",{className:"text-muted-foreground",children:"This report may have been removed or unpublished."})]})});const Z=r.subject||{},Q=(Me=r.settings)==null?void 0:Me.personalVideo,le=(Oe=Z.photos)==null?void 0:Oe[0],ue=r.contact_first_name?r.contact_first_name:null,se=((i==null?void 0:i.name)||"A").split(" ").map(Ye=>Ye[0]).slice(0,2).join("").toUpperCase(),ne=i!=null&&i.phone?`tel:${String(i.phone).replace(/[^\d+]/g,"")}`:null,ie=i!=null&&i.email?`mailto:${i.email}`:null,ce=i!=null&&i.phone?`sms:${String(i.phone).replace(/[^\d+]/g,"")}`:null,je=r.price_low??null,be=r.price_likely??null,he=r.price_high??null,ge=je&&be&&he,ke=be&&Z.sqft?Math.round(be/Z.sqft):null,Te=ke&&K?Math.round((ke-K)/K*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:se}),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(_i,{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:[ne&&e.jsx(U,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:ne,children:[e.jsx(ba,{className:"w-4 h-4 mr-1"}),"Call"]})}),ie&&e.jsx(U,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:ie,children:[e.jsx(ln,{className:"w-4 h-4 mr-1"}),"Email"]})})]})]})}),e.jsxs("div",{className:"relative overflow-hidden",children:[le?e.jsxs("div",{className:"absolute inset-0",children:[e.jsx("img",{src:le,alt:Z.address,className:"w-full h-full object-cover scale-110 animate-[kenburns_18s_ease-out_infinite_alternate]",style:{animation:"kenburns 22s ease-in-out infinite alternate"}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-950/85 via-slate-900/75 to-primary/60"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-background via-background/20 to-transparent"})]}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-primary/30 via-primary/10 to-background"}),e.jsx("style",{children:` @keyframes kenburns { 0% { transform: scale(1.08) translate(0, 0); } 100% { transform: scale(1.18) translate(-1.5%, -1%); } } `}),e.jsx("div",{className:"relative container mx-auto max-w-6xl px-4 md:px-8 pt-12 md:pt-20 pb-16 md:pb-24",children:e.jsxs("div",{className:"grid md:grid-cols-5 gap-8 items-center",children:[e.jsxs("div",{className:`${Q!=null&&Q.url?"md:col-span-3":"md:col-span-5"} text-white animate-fade-in`,children:[e.jsxs(Be,{className:"mb-4 bg-white/15 text-white border-white/20 backdrop-blur-sm hover:bg-white/20",children:[e.jsx(cn,{className:"w-3 h-3 mr-1"}),ue?`Prepared for ${ue}`:r.buyer_mode?"Your Buyer Analysis":"Your Market Analysis"]}),e.jsx("h1",{className:"text-3xl md:text-5xl lg:text-6xl font-bold leading-[1.05] tracking-tight",children:Z.address}),e.jsxs("p",{className:"text-white/70 mt-2 text-base md:text-lg flex items-center gap-2",children:[e.jsx(ni,{className:"w-4 h-4"}),Z.city,", ",Z.state," ",Z.zip]}),ge&&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(Coe,{to:be,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(Coe,{to:je,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(Coe,{to:be,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(Coe,{to:he,prefix:"$",delayMs:800})})]})]})]})]}),(Q==null?void 0:Q.url)&&e.jsx("div",{className:"md:col-span-2 animate-scale-in",children:e.jsxs("button",{onClick:()=>R(!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:[Q.thumb?e.jsx("img",{src:Q.thumb,alt:"",className:"w-full h-full object-cover"}):e.jsx("video",{src:Q.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(lu,{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 ",((Se=i==null?void 0:i.name)==null?void 0:Se.split(" ")[0])||"your agent"]})]})]})})]})})]}),I&&(Q==null?void 0:Q.url)&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4 animate-fade-in",onClick:()=>R(!1),children:e.jsxs("div",{className:"relative w-full max-w-4xl",onClick:Ye=>Ye.stopPropagation(),children:[e.jsx("video",{src:Q.url,controls:!0,autoPlay:!0,className:"w-full rounded-xl"}),e.jsx(U,{variant:"ghost",className:"absolute -top-12 right-0 text-white hover:bg-white/10",onClick:()=>R(!1),children:"Close"})]})}),e.jsxs("div",{className:"container mx-auto max-w-6xl px-4 md:px-8 py-10 md:py-16 space-y-10 md:space-y-14",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4 -mt-20 md:-mt-24 relative z-10",children:[{label:"Beds",value:Z.bedrooms??"—"},{label:"Baths",value:Z.bathrooms??"—"},{label:"Sq Ft",value:((Qe=Z.sqft)==null?void 0:Qe.toLocaleString())??"—"},{label:"Year Built",value:Z.yearBuilt??"—"}].map((Ye,Ge)=>e.jsx(we,{className:"shadow-lg animate-fade-in",style:{animationDelay:`${Ge*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:Ye.value}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 uppercase tracking-wider",children:Ye.label})]})},Ge))}),((Fe=(Ae=r.settings)==null?void 0:Ae.priceOverride)==null?void 0:Fe.enabled)&&(($e=(Ne=r.settings)==null?void 0:Ne.priceOverride)==null?void 0:$e.note)&&e.jsx(we,{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})]})}),ge&&e.jsx(zIs,{low:je,likely:be,high:he}),K&&ke&&e.jsxs("div",{className:"grid md:grid-cols-3 gap-4",children:[e.jsx(we,{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 ",Z.city,", the median sale rate is ",e.jsxs("strong",{className:"text-foreground",children:["$",K,"/sqft"]}),". Applied to your home's ",(Ve=Z.sqft)==null?void 0:Ve.toLocaleString()," sqft, the comps support a value near ",e.jsxs("strong",{className:"text-foreground",children:["$",(K*(Z.sqft||0)).toLocaleString()]}),". Your agent's suggested price reflects local nuance and condition."]})]})}),e.jsx(we,{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:["$",ke,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:["$",K,"/sqft"]})]}),Te!==null&&Te!==0&&e.jsxs("p",{className:`text-sm font-medium mt-1 ${Te>0?"text-emerald-600":"text-rose-600"}`,children:[Te>0?"▲":"▼"," ",Math.abs(Te),"% ",Te>0?"above":"below"," the median"]})]})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-baseline justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold",children:"Homes like yours"}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold",children:"The Comparables"})]}),e.jsxs(Be,{variant:"outline",className:"text-xs",children:[o.length," comps"]})]}),e.jsx("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-4",children:o.map((Ye,Ge)=>{var pt;const He=Ye.snapshot,tt=He.soldPrice||He.price;return e.jsxs(we,{className:`overflow-hidden cursor-pointer transition-all duration-300 hover:shadow-xl hover:-translate-y-1 animate-fade-in ${L===Ge?"ring-2 ring-primary":""}`,style:{animationDelay:`${Ge*60}ms`},onClick:()=>T(Ge),onMouseEnter:()=>M(Ge),onMouseLeave:()=>M(null),children:[e.jsxs("div",{className:"relative",children:[e.jsx(NCe,{photos:He.photos,className:"w-full h-44"}),e.jsxs(Be,{className:"absolute top-2 left-2 bg-black/70 text-white border-0 backdrop-blur-sm",children:["#",Ge+1]}),e.jsx(Be,{variant:"outline",className:"absolute top-2 right-2 bg-white/95 border-0",children:He.status})]}),e.jsxs(Ie,{className:"p-4",children:[e.jsx("div",{className:"font-semibold leading-tight truncate",children:He.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[He.city,", ",He.state]}),e.jsx("div",{className:"flex justify-between items-center mt-3 text-sm",children:e.jsxs("span",{className:"text-muted-foreground",children:[He.bedrooms??"?","bd · ",He.bathrooms??"?","ba · ",((pt=He.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:["$",tt==null?void 0:tt.toLocaleString()]}),He.sqft&&tt?e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:["$",Math.round(tt/He.sqft),"/sqft"]}):null]})]})]},Ge)})})]}),e.jsx(ROt,{comp:A!==null?(qe=o[A])==null?void 0:qe.snapshot:null,open:A!==null,onClose:()=>T(null)}),e.jsx(we,{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",ue?`, ${ue}`:"","?"]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["One tap. ",((Ze=i==null?void 0:i.name)==null?void 0:Ze.split(" ")[0])||"Your agent"," hears you instantly."]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[{kind:"love",icon:ko,label:"I love this price"},{kind:"fair",icon:wx,label:"Seems fair"},{kind:"lower",icon:nS,label:"I'd price lower"},{kind:"higher",icon:rc,label:"I'd price higher"},{kind:"ready_to_list",icon:a1,label:"Ready to list"},{kind:"want_walkthrough",icon:xa,label:"Want a walkthrough"},{kind:"need_time",icon:pa,label:"Need more time"},{kind:"have_questions",icon:MC,label:"I have questions"}].map(({kind:Ye,icon:Ge,label:He})=>e.jsxs(U,{variant:"outline",className:"bg-card hover:bg-primary hover:text-primary-foreground hover:scale-105 transition-all",onClick:()=>$(Ye),children:[e.jsx(Ge,{className:"w-4 h-4 mr-2"}),He]},Ye))}),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(vu,{className:"w-4 h-4"}),"Ask your agent a question"]}),N?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! ",((Ue=i==null?void 0:i.name)==null?void 0:Ue.split(" ")[0])||"Your agent"," was notified and will get back to you shortly."]}):e.jsxs(e.Fragment,{children:[H&&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:p,onChange:Ye=>f(Ye.target.value)}),e.jsx("input",{type:"email",className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your email",value:x,onChange:Ye=>y(Ye.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:Ye=>m(Ye.target.value)}),e.jsx(U,{onClick:V,disabled:!h.trim()||v,className:"mt-2",children:v?"Sending…":"Send to agent"})]})]})]})}),i&&e.jsx(we,{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:se}),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:[ne&&e.jsx(U,{asChild:!0,children:e.jsxs("a",{href:ne,children:[e.jsx(ba,{className:"w-4 h-4 mr-2"}),i.phone]})}),ie&&e.jsx(U,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:ie,children:[e.jsx(ln,{className:"w-4 h-4 mr-2"}),"Email"]})}),i.website_url&&e.jsx(U,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:i.website_url,target:"_blank",rel:"noreferrer",children:[e.jsx(fl,{className:"w-4 h-4 mr-2"}),"Website"]})})]})]})]})})})]}),i&&(ne||ce||ie)&&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:[ne&&e.jsx(U,{className:"flex-1",asChild:!0,children:e.jsxs("a",{href:ne,children:[e.jsx(ba,{className:"w-4 h-4 mr-1.5"}),"Call"]})}),ce&&e.jsx(U,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:ce,children:[e.jsx(vu,{className:"w-4 h-4 mr-1.5"}),"Text"]})}),ie&&e.jsx(U,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:ie,children:[e.jsx(ln,{className:"w-4 h-4 mr-1.5"}),"Email"]})})]})]})}function BIs(){const t=Od().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(DOt,{tokenOverride:t})}const e$e="levelup_affiliate_ref",UIs=30,qIs=()=>{const[s]=fc();j.useEffect(()=>{const t=s.get("ref");if(t){const n={code:t.toUpperCase(),timestamp:Date.now()};localStorage.setItem(e$e,JSON.stringify(n)),console.log("[Affiliate] Stored referral code:",t)}},[s])},$Is=()=>{try{const s=localStorage.getItem(e$e);if(!s)return null;const t=JSON.parse(s),n=UIs*24*60*60*1e3;return Date.now()-t.timestamp>n?(localStorage.removeItem(e$e),console.log("[Affiliate] Referral code expired"),null):t.code}catch{return null}},kCe="/assets/levelup-logo-header-_ZX7DvlA.png",VIs="/assets/scale-your-team-ku4MPatU.png";function HIs({open:s,onOpenChange:t}){return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Vs,{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(_i,{className:"h-5 w-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx($s,{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 GIs=1,WIs="665c2a91-46f5-4190-86be-a519a6a161f5",KIs="b4ed24ae-0b44-4f4d-8676-c620f649ed8a",YIs="/__l5e/assets-v1/665c2a91-46f5-4190-86be-a519a6a161f5/ld-mission_control.png",ZIs="a/v1/b4ed24ae-0b44-4f4d-8676-c620f649ed8a/665c2a91-46f5-4190-86be-a519a6a161f5/ld-mission_control.png",XIs="ld-mission_control.png",QIs=1232947,JIs="image/png",e8s="2026-08-31T01:20:08Z",sre={version:GIs,asset_id:WIs,project_id:KIs,url:YIs,r2_key:ZIs,original_filename:XIs,size:QIs,content_type:JIs,created_at:e8s},t8s=1,s8s="87e20faa-12c2-420e-ac38-396f7c9dfbc7",n8s="b4ed24ae-0b44-4f4d-8676-c620f649ed8a",r8s="/__l5e/assets-v1/87e20faa-12c2-420e-ac38-396f7c9dfbc7/ld-crm.png",a8s="a/v1/b4ed24ae-0b44-4f4d-8676-c620f649ed8a/87e20faa-12c2-420e-ac38-396f7c9dfbc7/ld-crm.png",i8s="ld-crm.png",o8s=1220316,l8s="image/png",c8s="2026-08-31T01:20:11Z",DMe={version:t8s,asset_id:s8s,project_id:n8s,url:r8s,r2_key:a8s,original_filename:i8s,size:o8s,content_type:l8s,created_at:c8s},d8s=1,u8s="8a8a9d3c-927e-443a-8134-a03e03a6d358",h8s="b4ed24ae-0b44-4f4d-8676-c620f649ed8a",m8s="/__l5e/assets-v1/8a8a9d3c-927e-443a-8134-a03e03a6d358/ld-deal_pipeline.png",p8s="a/v1/b4ed24ae-0b44-4f4d-8676-c620f649ed8a/8a8a9d3c-927e-443a-8134-a03e03a6d358/ld-deal_pipeline.png",f8s="ld-deal_pipeline.png",g8s=1256901,x8s="image/png",y8s="2026-08-31T01:20:15Z",OMe={version:d8s,asset_id:u8s,project_id:h8s,url:m8s,r2_key:p8s,original_filename:f8s,size:g8s,content_type:x8s,created_at:y8s},v8s=1,b8s="88744d60-e523-40f0-ae8f-819cde5b8494",_8s="b4ed24ae-0b44-4f4d-8676-c620f649ed8a",w8s="/__l5e/assets-v1/88744d60-e523-40f0-ae8f-819cde5b8494/ld-staging_studio.png",j8s="a/v1/b4ed24ae-0b44-4f4d-8676-c620f649ed8a/88744d60-e523-40f0-ae8f-819cde5b8494/ld-staging_studio.png",N8s="ld-staging_studio.png",k8s=1671765,S8s="image/png",C8s="2026-08-31T01:20:18Z",FMe={version:v8s,asset_id:b8s,project_id:_8s,url:w8s,r2_key:j8s,original_filename:N8s,size:k8s,content_type:S8s,created_at:C8s},A8s=1,E8s="ff8e4f35-9fa2-44a5-a971-f65d6ae1f975",T8s="b4ed24ae-0b44-4f4d-8676-c620f649ed8a",M8s="/__l5e/assets-v1/ff8e4f35-9fa2-44a5-a971-f65d6ae1f975/ld-coaching.png",P8s="a/v1/b4ed24ae-0b44-4f4d-8676-c620f649ed8a/ff8e4f35-9fa2-44a5-a971-f65d6ae1f975/ld-coaching.png",L8s="ld-coaching.png",I8s=1071609,R8s="image/png",D8s="2026-08-31T01:20:22Z",zMe={version:A8s,asset_id:E8s,project_id:T8s,url:M8s,r2_key:P8s,original_filename:L8s,size:I8s,content_type:R8s,created_at:D8s},O8s=1,F8s="3fe72f74-aad2-4e11-971d-a9cb53d86896",z8s="b4ed24ae-0b44-4f4d-8676-c620f649ed8a",B8s="/__l5e/assets-v1/3fe72f74-aad2-4e11-971d-a9cb53d86896/ld-marketing_studio.png",U8s="a/v1/b4ed24ae-0b44-4f4d-8676-c620f649ed8a/3fe72f74-aad2-4e11-971d-a9cb53d86896/ld-marketing_studio.png",q8s="ld-marketing_studio.png",$8s=1078276,V8s="image/png",H8s="2026-08-31T01:20:24Z",BMe={version:O8s,asset_id:F8s,project_id:z8s,url:B8s,r2_key:U8s,original_filename:q8s,size:$8s,content_type:V8s,created_at:H8s},G8s=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:sre.url},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:DMe.url},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:OMe.url},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:FMe.url},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:zMe.url},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:BMe.url}];function W8s({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(cn,{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 Jj={individual_agent:{name:"Individual Agent",price:"$39",period:"/month",description:"Perfect for independent agents ready to level up",features:["Full dashboard access","300+ professional templates","Academy training library","Community & networking","Live events & workshops","Social media content","Newsletter resources","Email support"],trial:"7-day free trial",popular:!1},brokerage_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"],popular:!1}},K8s=[{icon:$h,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:$c,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:pa,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:vu,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:Ur,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Ro,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],Y8s=[{category:"Marketing Studio",icon:Th,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:Gu,items:["Custom lead websites","Open House Guest Book","RSVP pages","Resource landing pages","Listing Revival™","FSBO Breakthrough","Attract system"]},{category:"CRM & Deals",icon:cy,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:Lg,items:["AI Staging Studio","Video library & sharing","Screen recording","Virtual backgrounds","AI blog writer","YouTube → Blog","Ask AI assistant"]},{category:"Growth & Coaching",icon:Kh,items:["Academy courses","Live weekly coaching","Coaching programs","1:1 coaching booking","Private community","Live events & workshops"]},{category:"Brokerage Tools",icon:_i,items:["Manager dashboard","Team analytics","Agent onboarding","Office form libraries","Listing Exchange","Brand kits","Recruiting pipeline"]}],Z8s=[{icon:Bn,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:cn,title:"Smart Touchpoint Plans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:ba,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:lg,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:ni,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:Cl,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:ko,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:Af,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],X8s=[{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."}],Q8s=()=>{const{user:s,loading:t}=vs(),n=Wn(),[r]=fc();j.useEffect(()=>{const L=window.location.host==="listings.relevelup.com",M=window.location.pathname==="/";if(L&&M){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,p]=j.useState(""),[f,x]=j.useState(""),[y,v]=j.useState(!1),[b,N]=j.useState(!1),S=(L,M=!1)=>{o({tier:L,skipTrial:M}),d(!0)};qIs(),j.useEffect(()=>{const L=window.location.host==="listings.relevelup.com",M=location.pathname.startsWith("/public/");!t&&s&&!L&&!M&&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(L,M=!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(L+(M?"_direct":""));const I=$Is();try{const{data:R,error:z}=await q.functions.invoke("create-checkout",{body:{tier:L,email:u,name:m.trim(),couponCode:f.trim()||void 0,skipTrial:M,referralCode:I}});if(z)throw z;if(R!=null&&R.url)window.open(R.url,"_blank","noopener,noreferrer"),re.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(R){console.error("Checkout error:",R),re.error(R.message||"Failed to start checkout. Please try again.")}finally{v(!1),i(null),d(!1),o(null)}},T=()=>{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:kCe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx(U,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var L;return(L=document.getElementById("features"))==null?void 0:L.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx(U,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var L;return(L=document.getElementById("pricing"))==null?void 0:L.scrollIntoView({behavior:"smooth"})},children:"Pricing"}),e.jsx(U,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>n("/blog"),children:"Blog"}),e.jsx(U,{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(cn,{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(U,{size:"lg",onClick:()=>{var L;return(L=document.getElementById("free-trial"))==null?void 0:L.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(Oa,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]}),e.jsx(U,{size:"lg",variant:"outline",onClick:()=>{var L;return(L=document.getElementById("features"))==null?void 0:L.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(Ua,{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(Af,{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(Im,{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:sre.url,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(rc,{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($h,{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(pa,{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(U,{size:"lg",variant:"outline",onClick:()=>{var L;return(L=document.getElementById("brokerage"))==null?void 0:L.scrollIntoView({behavior:"smooth"})},className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/5",children:[e.jsx(_i,{className:"mr-2 h-5 w-5"}),"Brokerage Partnership"]}),e.jsxs(U,{size:"lg",onClick:()=>{var L;return(L=document.getElementById("pricing"))==null?void 0:L.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:[e.jsx(So,{className:"mr-2 h-5 w-5"}),"Individual Membership"]})]})]})})}),e.jsx("section",{id:"features",className:"py-20 bg-muted/30",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("span",{className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-semibold mb-5",children:[e.jsx(L4,{className:"w-4 h-4"}),"40+ tools & counting"]}),e.jsx("h2",{className:"text-3xl md:text-4xl mb-6 font-sans font-bold",children:"What's inside our members only portal?"}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Everything you need to grow your business, all in one place."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:K8s.map((L,M)=>e.jsxs(we,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(Tt,{children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:e.jsx(L.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(It,{className:"text-xl font-sans",children:L.title})]}),e.jsx(Ie,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:L.description})})]},M))}),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:Y8s.map(L=>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(L.icon,{className:"h-4 w-4 text-white"})}),e.jsx("span",{className:"text-sm font-bold uppercase tracking-wider text-white/90",children:L.category})]}),e.jsx("ul",{className:"space-y-2.5",children:L.items.map(M=>e.jsxs("li",{className:"flex items-center gap-2.5 text-white/70 text-sm",children:[e.jsx(Xr,{className:"h-3.5 w-3.5 text-emerald-300 shrink-0"}),M]},M))})]},L.category))}),e.jsxs("p",{className:"text-center text-white/50 text-sm mt-10 flex items-center justify-center gap-2",children:[e.jsx(cn,{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:G8s.map(L=>e.jsx(W8s,{slot:L},L.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(cn,{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:Z8s.map((L,M)=>e.jsxs(we,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(Tt,{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(L.icon,{className:"w-6 h-6 text-white"})}),e.jsx(It,{className:"text-lg font-semibold text-white",children:L.title})]}),e.jsx(Ie,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:L.description})})]},M))}),e.jsx("div",{className:"text-center mt-12",children:e.jsxs(U,{size:"lg",onClick:()=>{var L;return(L=document.getElementById("pricing"))==null?void 0:L.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(Oa,{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(_i,{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((L,M)=>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(Xr,{className:"w-4 h-4 text-[#4a6b6d]"})}),e.jsx("span",{className:"text-foreground",children:L})]},M))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-4",children:[e.jsxs(U,{size:"lg",onClick:()=>{var L;return(L=document.getElementById("pricing"))==null?void 0:L.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["See Brokerage Plans",e.jsx(gi,{className:"ml-2 w-5 h-5"})]}),e.jsxs(U,{size:"lg",variant:"outline",onClick:()=>N(!0),className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/10",children:[e.jsx(pa,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),e.jsx("div",{className:"relative hidden md:block",children:e.jsx("img",{src:VIs,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:X8s.map((L,M)=>e.jsx(we,{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(I=>e.jsx(Ua,{className:"w-5 h-5 fill-yellow-400 text-yellow-400"},I))}),e.jsxs("p",{className:"text-lg mb-6 italic text-muted-foreground",children:['"',L.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:L.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:L.role})]})]})},M))})]})}),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(U,{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(Oa,{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(we,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(Tt,{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(So,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx(It,{className:"text-xl font-sans",children:Jj.individual_agent.name})]}),e.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold",children:Jj.individual_agent.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:Jj.individual_agent.period})]}),e.jsx(Jn,{className:"text-base mt-2",children:Jj.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(Yr,{className:"w-4 h-4"}),Jj.individual_agent.trial]})]}),e.jsx(Ie,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:Jj.individual_agent.features.map((L,M)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(Xr,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:L})]},M))})}),e.jsxs(J3e,{className:"flex flex-col gap-3 pt-4",children:[e.jsx(U,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>S("individual_agent"),children:"Start Free Trial"}),e.jsx(U,{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(we,{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(Tt,{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(_i,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(It,{className:"text-xl font-sans",children:Jj.brokerage_over_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Jj.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:Jj.brokerage_over_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:Jj.brokerage_over_25.period})]}),e.jsx(Jn,{className:"text-base mt-2",children:Jj.brokerage_over_25.description})]}),e.jsx(Ie,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:Jj.brokerage_over_25.features.map((L,M)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(Xr,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:L})]},M))})}),e.jsx(J3e,{className:"pt-4",children:e.jsx(U,{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(Im,{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(we,{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(_i,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp serves all brokerages."})]})}),e.jsx(we,{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(Ql,{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(we,{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(tN,{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(we,{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(Ur,{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(U,{size:"lg",onClick:()=>{var L;return(L=document.getElementById("pricing"))==null?void 0:L.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(Oa,{className:"ml-2 w-5 h-5"})]}),e.jsx(U,{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:kCe,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(HIs,{open:b,onOpenChange:N}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Ds,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{htmlFor:"dialog-name",children:["Full Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(xe,{id:"dialog-name",type:"text",placeholder:"John Smith",value:m,onChange:L=>p(L.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(te,{htmlFor:"dialog-email",children:["Email Address ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(xe,{id:"dialog-email",type:"email",placeholder:"you@example.com",value:u,onChange:L=>h(L.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(te,{htmlFor:"dialog-coupon",children:["Discount Code ",e.jsx("span",{className:"text-muted-foreground",children:"(Optional)"})]}),e.jsx(xe,{id:"dialog-coupon",type:"text",placeholder:"Enter discount code",value:f,onChange:L=>x(L.target.value),className:"mt-1"})]})]}),e.jsx(U,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:T,disabled:y,children:y?"Loading...":"Continue to Checkout"})]})})]})},Kpt=()=>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: August 25, 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(xr,{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(xr,{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"}),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. 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:"12. 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:"13. 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"}),"."]})]})]})]})})]}),Ypt=()=>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: January 17, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"1. Acceptance of Terms"}),e.jsx("p",{children:'By accessing or using the LevelUp platform ("Service"), you agree to be bound by these Terms of Service. If you do not agree to these terms, please do not use our Service.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"2. Description of Service"}),e.jsx("p",{children:"LevelUp provides a platform for real estate professionals to access training, resources, marketing tools, and community features. We reserve the right to modify or discontinue the Service at any time."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"3. User Accounts"}),e.jsx("p",{children:"To use certain features, you must create an account. You agree to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Provide accurate and complete information"}),e.jsx("li",{children:"Maintain the security of your account credentials"}),e.jsx("li",{children:"Notify us immediately of any unauthorized access"}),e.jsx("li",{children:"Accept responsibility for all activities under your account"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"4. Acceptable Use"}),e.jsx("p",{children:"You agree not to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Violate any applicable laws or regulations"}),e.jsx("li",{children:"Infringe on the rights of others"}),e.jsx("li",{children:"Upload malicious code or interfere with the Service"}),e.jsx("li",{children:"Attempt to gain unauthorized access to any part of the Service"}),e.jsx("li",{children:"Use the Service for any unlawful purpose"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"5. Intellectual Property"}),e.jsx("p",{children:"The Service and its original content, features, and functionality are owned by LevelUp and are protected by international copyright, trademark, and other intellectual property laws."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"6. Third-Party Integrations"}),e.jsx("p",{children:"Our Service may integrate with third-party platforms such as Facebook and Instagram. Your use of these integrations is subject to the terms and policies of those third parties. We are not responsible for the content or practices of any third-party services."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"7. Payment Terms"}),e.jsx("p",{children:"Certain features may require payment. By subscribing to paid features, you agree to pay all applicable fees. All payments are non-refundable unless otherwise specified."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"8. Limitation of Liability"}),e.jsx("p",{children:"To the maximum extent permitted by law, LevelUp shall not be liable for any indirect, incidental, special, consequential, or punitive damages resulting from your use of the Service."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"9. Termination"}),e.jsx("p",{children:"We may terminate or suspend your account at any time, without prior notice, for conduct that we believe violates these Terms or is harmful to other users, us, or third parties."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"10. Changes to Terms"}),e.jsx("p",{children:"We reserve the right to modify these Terms at any time. We will notify you of significant changes by posting a notice on our platform. Continued use of the Service constitutes acceptance of the modified terms."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"11. SMS / Text Messaging Terms"}),e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-4 mb-4 text-sm",children:[e.jsx("strong",{children:"To opt in:"})," Submit our public SMS opt-in form at"," ",e.jsx("a",{href:"/sms-opt-in",className:"text-primary hover:underline font-medium",children:"/sms-opt-in"})," ","— consent is captured with timestamp and the exact disclosure text shown below."]}),e.jsx("p",{children:"By opting in to receive text messages from LevelUp, 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. 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"})]})]})]})]})})]}),J8s=()=>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(xr,{to:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"})," and the"," ",e.jsx(xr,{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"}),"."]})]})]})]})})]}),Zpt=()=>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(xr,{to:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"})," and"," ",e.jsx(xr,{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"}),"."]})]})]})]})})]}),Xpt="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.",eRs=kN({name:sl().trim().min(1,"Name is required").max(200),phone:sl().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:sl().trim().email("Enter a valid email").max(320).optional().or(ux(""))});function tRs(){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,p]=j.useState(!1),f=Wn(),x=async y=>{var N;if(y.preventDefault(),!l){re.error("Please check the consent box to opt in.");return}const v=eRs.safeParse({name:s,phone:n,email:a});if(!v.success){re.error(((N=v.error.issues[0])==null?void 0:N.message)??"Please check your inputs.");return}d(!0);const{error:b}=await q.from("sms_opt_in_consents").insert({name:v.data.name,phone:v.data.phone,email:v.data.email||null,consent_text:Xpt,source:"web_form",user_agent:navigator.userAgent.slice(0,500)});if(d(!1),b){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"}),e.jsx("meta",{name:"description",content:"Opt in to receive SMS account notifications and real-time lead alerts from LevelUp. Review consent terms, message frequency, and STOP/HELP instructions."}),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(Ki,{className:"w-7 h-7"})}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"LevelUp — SMS Opt-In"}),e.jsx("p",{className:"text-muted-foreground mt-3 max-w-xl mx-auto",children:"Sign up to receive SMS account notifications and real-time lead alerts from LevelUp. These messages help subscribed real estate agents review and respond to new consumer inquiries submitted through their websites."})]}),e.jsx("div",{className:"mb-6 rounded-lg border border-primary/30 bg-primary/5 p-4 text-center",children:e.jsx("p",{className:"text-sm font-medium",children:"SMS notifications are optional. You may use LevelUp without providing a mobile number or consenting to text messages."})}),m?e.jsxs(we,{className:"p-8 text-center",children:[e.jsx(zr,{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(U,{className:"mt-6",onClick:()=>f("/auth"),children:"Continue to LevelUp"})]}):u?e.jsxs(we,{className:"p-8 text-center",children:[e.jsx(zr,{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(we,{className:"p-6 md:p-8",children:e.jsxs("form",{onSubmit:x,className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(te,{htmlFor:"name",children:"Full Name (only if you opt in to SMS)"}),e.jsx(xe,{id:"name",value:s,onChange:y=>t(y.target.value),maxLength:200,autoComplete:"name",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"phone",children:"Mobile Number (only if you opt in to SMS)"}),e.jsx(xe,{id:"phone",type:"tel",value:n,onChange:y=>r(y.target.value),maxLength:30,placeholder:"(555) 123-4567",autoComplete:"tel",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"email",children:"Email (optional)"}),e.jsx(xe,{id:"email",type:"email",value:a,onChange:y=>i(y.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(xi,{id:"consent",checked:l,onCheckedChange:y=>o(y===!0),className:"mt-0.5"}),e.jsx(te,{htmlFor:"consent",className:"text-sm leading-relaxed font-normal cursor-pointer",children:Xpt})]})}),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(xr,{to:"/terms-of-service",className:"text-primary underline underline-offset-2",children:"SMS Terms & Conditions"})," ","and"," ",e.jsx(xr,{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(U,{type:"submit",disabled:!l||c,className:"w-full",size:"lg",children:c?"Submitting…":"Opt in to SMS"}),e.jsx(U,{type:"button",variant:"outline",size:"lg",className:"w-full",disabled:c,onClick:()=>p(!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(cg,{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 xQe="/assets/levelup-logo-horizontal-DEFNc0ms.png",sRs=kN({email:sl().email("Invalid email address"),password:sl().min(6,"Password must be at least 6 characters")}),OOt="https://dashboard.relevelup.com",Aoe="/oauth-connect",nRs=`${OOt}/profile?reset=true`,R5e="levelupOAuthRouteHistory";function Qpt(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function rRs(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(R5e)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(R5e,JSON.stringify([{route:s,at:t}])),!1}}function aRs(){sessionStorage.removeItem(R5e)}const iRs=()=>{const{signIn:s,user:t,loading:n}=vs(),r=(t==null?void 0:t.id)??null,a=Wn(),[i]=fc(),l=i.get("authorization_id")??"",o=i.get("next")??"",[c,d]=j.useState(!1),[u,h]=j.useState({}),[m,p]=j.useState(""),[f,x]=j.useState(!1),[y,v]=j.useState(!1),[b,N]=j.useState(null),S=j.useRef(!1);j.useEffect(()=>{if(l&&window.location.hostname==="tile-portal.lovable.app"){const L=new URL("/auth",OOt);L.searchParams.set("next",`${Aoe}?authorization_id=${encodeURIComponent(l)}`),window.location.replace(L.toString());return}if(l){const L=`${Aoe}?authorization_id=${encodeURIComponent(l)}`;sessionStorage.setItem("redirectAfterLogin",L);return}o&&Qpt(o)&&sessionStorage.setItem("redirectAfterLogin",o)},[l,o]),j.useEffect(()=>{if(n||!r||S.current)return;const L=l?`${Aoe}?authorization_id=${encodeURIComponent(l)}`:sessionStorage.getItem("redirectAfterLogin")||"/dashboard";if(!Qpt(L)){sessionStorage.removeItem("redirectAfterLogin"),S.current=!0,a("/dashboard",{replace:!0});return}const M=L.startsWith(Aoe)||L.startsWith("/oauth/consent")||L.startsWith("/.lovable/oauth/consent");if(M&&rRs("auth")){N("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}S.current=!0,M||(aRs(),sessionStorage.removeItem("redirectAfterLogin")),a(L,{replace:!0})},[l,n,a,r]);const A=async L=>{L.preventDefault(),h({}),d(!0);const M=new FormData(L.currentTarget),I=M.get("email"),R=M.get("password");try{sRs.parse({email:I,password:R}),await s(I,R)}catch(z){if(z instanceof sks){const $={};z.issues.forEach(H=>{H.path[0]&&($[H.path[0]]=H.message)}),h($)}}finally{d(!1)}},T=async()=>{if(!m){re.error("Please enter your email address");return}x(!0);try{const{error:L}=await q.functions.invoke("send-password-reset",{body:{email:m,redirectTo:nRs}});if(L)throw L;re.success("Password reset email sent! Check your inbox."),v(!1),p("")}catch(L){re.error(L instanceof Error?L.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(xr,{to:"/",className:"inline-flex items-center gap-2 text-sm text-white/80 hover:text-white transition-colors",children:[e.jsx(Aa,{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:xQe,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(we,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Tt,{className:"space-y-1 text-center pb-4",children:[e.jsx(It,{className:"text-3xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Welcome Back"}),e.jsx(Jn,{className:"text-gray-600",children:b||"Sign in to access your dashboard"})]}),e.jsx(Ie,{children:e.jsxs("form",{onSubmit:A,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"signin-email",className:"text-gray-700",children:"Email"}),e.jsx(xe,{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(te,{htmlFor:"signin-password",className:"text-gray-700",children:"Password"}),e.jsx(xe,{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(U,{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(al,{asChild:!0,children:e.jsx(U,{variant:"link",className:"w-full text-sm text-[#4a6b6d] hover:text-[#3d5a5c]",children:"Forgot password?"})}),e.jsxs(Ds,{className:"bg-white",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{htmlFor:"reset-email",className:"text-gray-700",children:"Email"}),e.jsx(xe,{id:"reset-email",type:"email",placeholder:"your@email.com",value:m,onChange:L=>p(L.target.value),className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"})]}),e.jsx(U,{onClick:T,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",disabled:f,children:f?"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(xr,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})})]})]})},Jpt=()=>q.auth.oauth,oRs="https://dashboard.relevelup.com",lRs="/oauth-connect",D5e="levelupOAuthRouteHistory",cRs="https://relzejiswnotikjgvjhz.supabase.co/auth/v1",dRs="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM";function uRs(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function hRs(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(D5e)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(D5e,JSON.stringify([{route:s,at:t}])),!1}}function mRs(){sessionStorage.removeItem(D5e)}async function eft(s,t,n){const r=await fetch(`${cRs}${s}`,{...n,headers:{Authorization:`Bearer ${t}`,apikey:dRs,"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 LOe(){var x;const{user:s,session:t,loading:n}=vs(),r=(s==null?void 0:s.id)??null,a=(t==null?void 0:t.access_token)??null,[i]=fc(),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=`${lRs}?authorization_id=${encodeURIComponent(l)}`;if(window.location.hostname==="tile-portal.lovable.app"){window.location.href=`${oRs}${v}`;return}if(n)return;if(!r){if(hRs("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}uRs(v)&&sessionStorage.setItem("redirectAfterLogin",v),window.location.replace(`/auth?next=${encodeURIComponent(v)}`);return}if(!a)return;mRs(),sessionStorage.removeItem("redirectAfterLogin");const b=Jpt(),{data:N,error:S}=b?await b.getAuthorizationDetails(l):await eft(`/oauth/authorizations/${encodeURIComponent(l)}`,a);if(!y)return;if(S){u(S.message);return}const A=(N==null?void 0:N.redirect_url)??(N==null?void 0:N.redirect_to);if(A&&!(N!=null&&N.client)){window.location.href=A;return}c(N)})(),()=>{y=!1}},[a,l,n,r]);async function p(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=Jpt(),{data:b,error:N}=v?y?await v.approveAuthorization(l,{skipBrowserRedirect:!0}):await v.denyAuthorization(l,{skipBrowserRedirect:!0}):await eft(`/oauth/authorizations/${encodeURIComponent(l)}/consent`,t.access_token,{method:"POST",body:JSON.stringify({action:y?"approve":"deny"})});if(N){m(!1),u(N.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(we,{className:"w-full max-w-md",children:e.jsxs(Tt,{children:[e.jsx(It,{children:"Authorization error"}),e.jsx(Jn,{children:d})]})})});if(!o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx(Et,{className:"h-8 w-8 animate-spin text-primary"})});const f=((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(we,{className:"w-full max-w-md",children:[e.jsxs(Tt,{children:[e.jsxs(It,{children:["Connect ",f," to LevelUp"]}),e.jsxs(Jn,{children:[f," 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(U,{variant:"outline",disabled:h,onClick:()=>p(!1),children:"Deny"}),e.jsx(U,{disabled:h,onClick:()=>p(!0),children:h?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):"Approve"})]})]})})}const pRs="https://chatgpt.com/plugins/plugin_asdk_app_6a7b9baf757081918ac4ab6fcbdb2639?q=levelup",tft="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/mcp",fRs="https://tile-portal.lovable.app/mcp-oauth-bridge.html",gRs=[{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'."}],xRs=[{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 yRs(){const[s,t]=j.useState(!1),n=async()=>{try{await navigator.clipboard.writeText(tft),t(!0),re.success("MCP URL copied to clipboard"),setTimeout(()=>t(!1),2e3)}catch{re.error("Could not copy URL")}};return e.jsx(qs,{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(we,{className:"border-primary/20 bg-primary/5",children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(cn,{className:"h-5 w-5 text-primary"}),"Install from the ChatGPT Store"]}),e.jsx(Jn,{children:"The easiest way to connect. Tap the button below, then install the LevelUp plugin in ChatGPT."})]}),e.jsx(Ie,{children:e.jsx(U,{asChild:!0,size:"lg",className:"w-full sm:w-auto",children:e.jsxs("a",{href:pRs,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Sr,{className:"h-4 w-4 mr-2"}),"Open LevelUp in the ChatGPT Store"]})})})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"Quick steps"}),e.jsx(Jn,{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:gRs.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(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"Manual MCP setup"}),e.jsx(Jn,{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:tft}),e.jsx(U,{variant:"outline",size:"icon",onClick:n,"aria-label":"Copy MCP URL",children:s?e.jsx(Yo,{className:"h-4 w-4 text-green-600"}):e.jsx(Pa,{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(tc,{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:fRs}),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:xRs.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(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"What ChatGPT can see"}),e.jsx(Jn,{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(Sr,{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 vRs=()=>{const[s]=fc(),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(we,{className:"max-w-lg w-full",children:[e.jsxs(Tt,{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(Yo,{className:"w-10 h-10 text-green-500"})}),e.jsx(It,{className:"text-2xl",children:"Welcome to LevelUp!"}),e.jsx(Jn,{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(ln,{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."})})]})]})})},bRs=()=>{const{user:s}=vs(),[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState(""),o=async u=>{var h;if(!(s!=null&&s.email)){re.error("Please sign in to upgrade");return}n(!0),a(u);try{const{data:m,error:p}=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(p)throw p;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(qs,{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(te,{htmlFor:"coupon",className:"text-sm font-medium",children:"Have a discount code?"}),e.jsx(xe,{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(we,{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(Tt,{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(Bn,{className:"h-7 w-7 text-primary"})}),e.jsx(It,{className:"text-xl",children:"Individual Agent"}),e.jsx(Jn,{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(Xr,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsx("span",{children:u})]},h))}),e.jsxs(U,{className:"w-full",size:"lg",onClick:()=>o("individual_agent"),disabled:t,children:[t&&r==="individual_agent"?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(we,{className:"border-2 border-purple-500/20 hover:border-purple-500/50 transition-colors",children:[e.jsxs(Tt,{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(_i,{className:"h-7 w-7 text-purple-600"})}),e.jsx(It,{className:"text-xl",children:"Brokerage"}),e.jsx(Jn,{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(Xr,{className:"h-4 w-4 text-purple-600 mt-0.5 shrink-0"}),e.jsx("span",{children:u})]},h))}),e.jsxs(U,{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(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(_i,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]})]}),e.jsx(we,{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(ba,{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(ln,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})})]})})},_Rs=()=>{const{user:s,loading:t,isBrokerageManager:n,brokerageId:r}=vs(),a=Wn(),[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(),p=m.session;if(!s||!p){re.error("Please sign in again to create your brokerage."),a("/auth");return}c(!0);try{console.log("[SetupBrokerage] Creating brokerage…",{hasUser:!!s,hasSession:!!p,userId:s==null?void 0:s.id});const{data:f,error:x}=await q.functions.invoke("create-brokerage",{body:{name:i.trim()}});if(console.log("[SetupBrokerage] create-brokerage response",{data:f,error:x}),x)throw x;if(!(f!=null&&f.ok))throw new Error((f==null?void 0:f.error)||"Failed to create brokerage");c(!1),u(!0),re.success("Brokerage created! Setting up your account..."),setTimeout(()=>{a("/profile?setup=true")},2e3)}catch(f){console.error("Error creating brokerage:",f),re.error(f.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(we,{className:"max-w-lg w-full",children:[e.jsxs(Tt,{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(Et,{className:"w-10 h-10 text-primary animate-spin"})}),e.jsx(It,{className:"text-2xl",children:"Setting Up Your Brokerage"}),e.jsx(Jn,{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(Yo,{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(Et,{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(we,{className:"max-w-lg w-full",children:[e.jsxs(Tt,{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(_i,{className:"w-10 h-10 text-primary"})}),e.jsx(It,{className:"text-2xl",children:"Set Up Your Brokerage"}),e.jsx(Jn,{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(te,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(xe,{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(Bn,{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(Yo,{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(Yo,{className:"w-4 h-4 text-green-500"}),"Access exclusive brokerage resources"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(Yo,{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(Yo,{className:"w-4 h-4 text-green-500"}),"Share resources with your agents"]})]})]}),e.jsxs(U,{onClick:h,className:"w-full",disabled:o||!i.trim(),children:[o?"Creating...":"Create Brokerage",e.jsx(Oa,{className:"w-4 h-4 ml-2"})]})]})]})})},sft=()=>{const s=Wn(),[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(we,{className:"w-full max-w-md",children:[e.jsxs(Tt,{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(It,{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(Jn,{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(U,{onClick:i,className:"w-full",children:"Go to Login"})})]})})},IOe="https://dashboard.relevelup.com",nft=()=>{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 u=new URL(r);return u.hostname.endsWith(".supabase.co")&&u.pathname.startsWith("/auth/v1/verify")}catch{return!1}},[r]);j.useEffect(()=>{document.title=i.doc},[i]);const[o,c]=j.useState(null),d=async()=>{if(!(!l||!r)){if(t(!0),c(null),window.location.origin!==IOe&&window.location.hostname!=="localhost"){window.location.href=`${IOe}${window.location.pathname}${window.location.search}`;return}try{const u=new URL(r),h=u.searchParams.get("token")||u.searchParams.get("token_hash"),m=u.searchParams.get("type")||(a==="claim"?"invite":a);if(h){const{error:p}=await q.auth.verifyOtp({token_hash:h,type:m});if(!p){const f=u.searchParams.get("redirect_to");let x=m==="recovery"?"/profile?reset=true":"/dashboard";if(f)try{const y=new URL(f);x=`${y.pathname}${y.search}`}catch{}window.location.replace(`${IOe}${x}`);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:xQe,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(we,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Tt,{className:"text-center",children:[e.jsx(It,{className:"text-2xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:i.title}),e.jsx(Jn,{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?e.jsx(U,{onClick:d,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}):e.jsx(U,{onClick:()=>window.location.href="/auth",className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg",children:"Go to Sign In"}),e.jsx("p",{className:"text-xs text-center text-gray-500 pt-2",children:"For your security, these links expire and can only be used once."})]})]})]})})]})},wRs=()=>{const s=Wn(),[t]=fc(),[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,p]=j.useState(!1),[f,x]=j.useState(!1),[y,v]=j.useState(!1),[b,N]=j.useState(null),[S,A]=j.useState(null),[T,L]=j.useState(null),[M,I]=j.useState(null);j.useEffect(()=>{const H=t.get("code");H&&(r(H),R(H))},[t]);const R=async H=>{x(!0);const{data:V,error:K}=await q.from("invite_codes").select("id, code, max_uses, uses_count, expires_at, is_active, brokerage_id, trial_days").eq("code",H.toUpperCase().trim()).single();if(K||!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){H.preventDefault(),R(n)},$=async H=>{var V;if(H.preventDefault(),!c.trim()){re.error("Please enter your name");return}if(l.length<6){re.error("Password must be at least 6 characters");return}p(!0);try{const K="https://dashboard.relevelup.com/",{data:Z,error:Q}=await q.auth.signUp({email:a.trim(),password:l,options:{emailRedirectTo:K,data:{name:c.trim()}}});if(Q){Q.message.includes("already registered")?re.error("This email is already registered. Please sign in instead."):re.error(Q.message);return}if(Z.user){await q.rpc("add_default_signup_tag",{user_id:Z.user.id});const le=n.toUpperCase().trim();S?await q.functions.invoke("assign-brokerage",{body:{userId:Z.user.id,brokerageId:S,inviteCode:le}}):M?await q.functions.invoke("assign-brokerage",{body:{userId:Z.user.id,trialDays:M,inviteCode:le}}):await q.functions.invoke("assign-brokerage",{body:{userId:Z.user.id,grandfathered:!0,inviteCode:le}}),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(K){console.error("Signup error:",K),re.error("An unexpected error occurred")}finally{p(!1)}};return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(we,{className:"w-full max-w-md",children:[e.jsxs(Tt,{className:"text-center",children:[e.jsx(It,{className:"text-2xl font-bold text-primary",children:T?`Join ${T}`:"Join LevelUp"}),e.jsx(Jn,{children:y?T?`Create your account to join ${T}`:"Create your account to get started":"Enter your invite code to continue"})]}),e.jsx(Ie,{children:y?e.jsxs("form",{onSubmit:$,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"name",children:"Full Name"}),e.jsx(xe,{id:"name",type:"text",placeholder:"John Doe",value:c,onChange:H=>d(H.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"email",children:"Email"}),e.jsx(xe,{id:"email",type:"email",placeholder:"you@example.com",value:a,onChange:H=>i(H.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(xe,{id:"password",type:u?"text":"password",placeholder:"••••••••",value:l,onChange:H=>o(H.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(Vg,{className:"h-4 w-4"}):e.jsx(xa,{className:"h-4 w-4"})})]})]}),e.jsx(U,{type:"submit",className:"w-full",disabled:m,children:m?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating Account..."]}):"Create Account"})]}):e.jsxs("form",{onSubmit:z,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"inviteCode",children:"Invite Code"}),e.jsx(xe,{id:"inviteCode",type:"text",placeholder:"Enter your invite code",value:n,onChange:H=>r(H.target.value),required:!0,autoFocus:!0})]}),e.jsx(U,{type:"submit",className:"w-full",disabled:f,children:f?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}),"Verifying..."]}):"Verify Code"})]})})]})})},nre=()=>{const{user:s,isCoach:t}=vs();return ct({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}})},jRs=()=>{const{data:s}=nre();return ct({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}))}})},yQe=()=>{const{user:s}=vs();return ct({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}}})},NRs=s=>ct({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}}}),vQe=s=>ct({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||[]}}),bQe=s=>ct({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||[]}}),kRs=[{key:"onboarding",label:"Onboarding"},{key:"active",label:"Active"},{key:"thriving",label:"Thriving"},{key:"at_risk",label:"At Risk"},{key:"graduated",label:"Graduated"}];function SRs(){const s=Wn(),{data:t,isLoading:n}=nre(),{data:r=[],isLoading:a}=jRs();if(n)return e.jsx(qs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(qs,{title:"Coaching",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(Kh,{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."})]})});kRs.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(qs,{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(cn,{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(ROe,{icon:Kh,label:"Active agents",value:i}),e.jsx(ROe,{icon:nc,label:"This month",value:"—"}),e.jsx(ROe,{icon:Xd,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(U,{size:"sm",variant:"outline",onClick:()=>s("/coaching/waitlist"),children:"Waitlist"}),e.jsx(U,{size:"sm",variant:"outline",onClick:()=>s("/coaching/settings"),children:"Profile Settings"}),e.jsx(U,{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(we,{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(we,{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(Ea,{className:"h-14 w-14",children:[e.jsx(Ci,{src:((o=l.agent)==null?void 0:o.avatar_url)||void 0}),e.jsx(Ta,{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(Oa,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:(u=l.agent)==null?void 0:u.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-3",children:[e.jsx(Be,{variant:"secondary",className:"capitalize",children:(l.pipeline_stage||"active").replace("_"," ")}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Started ",Nd(new Date(l.started_at),{addSuffix:!0})]})]})]})]})})},l.id)})})]})]})})}function ROe({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 FOt({assignmentId:s}){const{user:t}=vs(),n=Qt(),[r,a]=j.useState(""),[i,l]=j.useState(!1),o=j.useRef(null),{data:c=[]}=ct({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(we,{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:Mt("flex gap-2",h?"justify-end":"justify-start"),children:[!h&&e.jsx(Ea,{className:"h-8 w-8 mt-1",children:e.jsx(Ta,{className:"text-xs",children:(u.sender_id||"?").charAt(0).toUpperCase()})}),e.jsxs("div",{className:Mt("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:Mt("text-[10px] mt-1",h?"text-white/70":"text-muted-foreground"),children:Nd(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(Fs,{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(U,{onClick:d,disabled:i||!r.trim(),size:"icon",className:"bg-[#406E71] hover:bg-[#2a4c64]",children:e.jsx($r,{className:"h-4 w-4"})})]})})]})}var _Qe="Progress",wQe=100,[CRs,kgr]=Up(_Qe),[ARs,ERs]=CRs(_Qe),zOt=j.forwardRef((s,t)=>{const{__scopeProgress:n,value:r=null,max:a,getValueLabel:i=TRs,...l}=s;(a||a===0)&&!rft(a)&&console.error(MRs(`${a}`,"Progress"));const o=rft(a)?a:wQe;r!==null&&!aft(r,o)&&console.error(PRs(`${r}`,"Progress"));const c=aft(r,o)?r:null,d=SCe(c)?i(c,o):void 0;return e.jsx(ARs,{scope:n,value:c,max:o,children:e.jsx(si.div,{"aria-valuemax":o,"aria-valuemin":0,"aria-valuenow":SCe(c)?c:void 0,"aria-valuetext":d,role:"progressbar","data-state":qOt(c,o),"data-value":c??void 0,"data-max":o,...l,ref:t})})});zOt.displayName=_Qe;var BOt="ProgressIndicator",UOt=j.forwardRef((s,t)=>{const{__scopeProgress:n,...r}=s,a=ERs(BOt,n);return e.jsx(si.div,{"data-state":qOt(a.value,a.max),"data-value":a.value??void 0,"data-max":a.max,...r,ref:t})});UOt.displayName=BOt;function TRs(s,t){return`${Math.round(s/t*100)}%`}function qOt(s,t){return s==null?"indeterminate":s===t?"complete":"loading"}function SCe(s){return typeof s=="number"}function rft(s){return SCe(s)&&!isNaN(s)&&s>0}function aft(s,t){return SCe(s)&&!isNaN(s)&&s<=t&&s>=0}function MRs(s,t){return`Invalid prop \`max\` of value \`${s}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${wQe}\`.`}function PRs(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 ${wQe} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}var $Ot=zOt,LRs=UOt;const ro=j.forwardRef(({className:s,value:t,...n},r)=>e.jsx($Ot,{ref:r,className:Mt("relative h-4 w-full overflow-hidden rounded-full bg-secondary",s),...n,children:e.jsx(LRs,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));ro.displayName=$Ot.displayName;function VOt({agentUserId:s}){const t=new Date().getFullYear(),n=`${t}-01-01`,r=`${t}-12-31`,{data:a=[]}=ct({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}=ct({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,p=(u==null?void 0:u.gci_goal)||0,f=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(rc,{className:"h-5 w-5"})," ",t," KPIs"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(DOe,{icon:Eh,label:"Transactions",value:o.toString(),goal:h,current:o,suffix:h?`/ ${h}`:""}),e.jsx(DOe,{icon:rc,label:"Volume",value:f(c),goal:m,current:c,suffix:m?`of ${f(m)}`:""}),e.jsx(DOe,{icon:yu,label:"GCI",value:f(d),goal:p,current:d,suffix:p?`of ${f(p)}`:""})]}),o===0&&e.jsx(we,{children:e.jsxs(Ie,{className:"p-4 text-sm text-muted-foreground text-center",children:["No transactions logged for ",t," yet."]})})]})}function DOe({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(we,{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(ro,{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 HOt({assignmentId:s,canEdit:t}){const n=Qt(),[r,a]=j.useState(!1),[i,l]=j.useState(null),{data:o=[]}=ct({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(Gu,{className:"h-5 w-5"})," Goals"]}),t&&e.jsxs(U,{size:"sm",onClick:()=>{l(null),a(!0)},children:[e.jsx(an,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),o.length===0?e.jsx(we,{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(we,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold",children:d.title}),e.jsx(Be,{variant:"outline",className:"capitalize",children:d.status||"active"})]}),d.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:d.description})]}),t&&e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>{l(d),a(!0)},children:e.jsx(ri,{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(ro,{value:m})]}),d.due_date&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Due ",Gs(new Date(d.due_date),"PP")]})]})},d.id)}),t&&e.jsx(IRs,{open:r,onOpenChange:a,assignmentId:s,goal:i,onSaved:c})]})}function IRs({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())||""),[p,f]=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 T,L;l((r==null?void 0:r.title)||""),c((r==null?void 0:r.description)||""),u((r==null?void 0:r.target_metric)||""),m(((T=r==null?void 0:r.target_value)==null?void 0:T.toString())||""),f(((L=r==null?void 0:r.current_value)==null?void 0:L.toString())||"0"),y((r==null?void 0:r.due_date)||"")});const N=async()=>{if(!i.trim())return;b(!0);const T={assignment_id:n,title:i,description:o||null,target_metric:d||null,target_value:h?Number(h):null,current_value:p?Number(p):0,due_date:x||null},{error:L}=r!=null&&r.id?await q.from("coaching_goals").update(T).eq("id",r.id):await q.from("coaching_goals").insert(T);if(b(!1),L)return re.error(L.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(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:r!=null&&r.id?"Edit Goal":"New Goal"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(xe,{placeholder:"Title",value:i,onChange:T=>l(T.target.value)}),e.jsx(Fs,{placeholder:"Description (optional)",rows:2,value:o,onChange:T=>c(T.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(xe,{placeholder:"transactions",value:d,onChange:T=>u(T.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Target"}),e.jsx(xe,{type:"number",value:h,onChange:T=>m(T.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Current"}),e.jsx(xe,{type:"number",value:p,onChange:T=>f(T.target.value)})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Due date"}),e.jsx(xe,{type:"date",value:x,onChange:T=>y(T.target.value)})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(U,{onClick:N,disabled:v,children:r!=null&&r.id?"Save":"Create"})]})]})})}function GOt({assignmentId:s}){const t=Qt(),{user:n}=vs(),r=j.useRef(null),[a,i]=j.useState(!1),{data:l=[]}=ct({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 p;const m=(p=h.target.files)==null?void 0:p[0];if(!(!m||!n)){i(!0);try{const f=`${s}/${Date.now()}-${m.name}`,{error:x}=await q.storage.from("coaching-files").upload(f,m);if(x)throw x;const{error:y}=await q.from("coaching_shared_files").insert({assignment_id:s,uploaded_by:n.id,file_url:f,file_name:m.name,file_size_bytes:m.size,mime_type:m.type});if(y)throw y;re.success("File uploaded"),o()}catch(f){re.error(f.message||"Upload failed")}finally{i(!1),r.current&&(r.current.value="")}}},d=async h=>{const{data:m,error:p}=await q.storage.from("coaching-files").createSignedUrl(h.file_url,60);if(p||!m)return re.error("Could not get download link");window.open(m.signedUrl,"_blank")},u=async h=>{await Yi("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(U,{size:"sm",onClick:()=>{var h;return(h=r.current)==null?void 0:h.click()},disabled:a,children:[e.jsx(qa,{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(we,{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(we,{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(Ur,{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 · `:"",Gs(new Date(h.created_at),"PP")]})]}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>d(h),children:e.jsx(pi,{className:"h-4 w-4"})}),h.uploaded_by===(n==null?void 0:n.id)&&e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>u(h),children:e.jsx(In,{className:"h-4 w-4"})})]})},h.id))})]})}function RRs(){var m,p,f,x;const{id:s}=Di(),t=Wn(),n=Qt(),{data:r,isLoading:a}=NRs(s),{data:i=[]}=vQe(s),{data:l=[]}=bQe(s),[o,c]=j.useState(!1),[d,u]=j.useState(!1);if(a)return e.jsx(qs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!r)return e.jsx(qs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Assignment not found."})});const h=r;return e.jsxs(qs,{title:"Coaching",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-6xl mx-auto space-y-6",children:[e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>t("/coaching"),children:[e.jsx(Aa,{className:"h-4 w-4 mr-2"})," Back to roster"]}),e.jsxs(we,{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(Ea,{className:"h-24 w-24 ring-4 ring-background",children:[e.jsx(Ci,{src:((m=h.agent)==null?void 0:m.avatar_url)||void 0}),e.jsx(Ta,{className:"text-2xl",children:(((p=h.agent)==null?void 0:p.name)||"?").charAt(0)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-2xl font-bold",children:((f=h.agent)==null?void 0:f.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(x=h.agent)==null?void 0:x.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(Be,{variant:"secondary",className:"capitalize",children:(h.pipeline_stage||"active").replace("_"," ")}),e.jsx(Be,{variant:"outline",className:"capitalize",children:h.status})]})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(ORs,{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(DRs,{assignment:h}),e.jsxs(oa,{defaultValue:"sessions",children:[e.jsxs(la,{className:"w-full flex flex-wrap justify-start h-auto",children:[e.jsxs(Kt,{value:"sessions",children:[e.jsx(pa,{className:"h-4 w-4 mr-2"}),"Sessions"]}),e.jsxs(Kt,{value:"actions",children:[e.jsx(cy,{className:"h-4 w-4 mr-2"}),"Actions"]}),e.jsxs(Kt,{value:"goals",children:[e.jsx(Gu,{className:"h-4 w-4 mr-2"}),"Goals"]}),e.jsxs(Kt,{value:"kpis",children:[e.jsx(rc,{className:"h-4 w-4 mr-2"}),"KPIs"]}),e.jsxs(Kt,{value:"messages",children:[e.jsx(Ki,{className:"h-4 w-4 mr-2"}),"Messages"]}),e.jsxs(Kt,{value:"files",children:[e.jsx(r1,{className:"h-4 w-4 mr-2"}),"Files"]}),e.jsxs(Kt,{value:"notes",children:[e.jsx(Ur,{className:"h-4 w-4 mr-2"}),"Private Notes"]})]}),e.jsxs(Zt,{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(U,{size:"sm",onClick:()=>c(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-1"})," New Session"]})]}),i.length===0?e.jsx(we,{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(we,{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:Gs(new Date(y.scheduled_at),"PPp")}),e.jsx(Be,{variant:"outline",className:"capitalize",children:y.status}),y.template&&e.jsx(Be,{variant:"secondary",children:y.template}),y.zoom_join_url&&e.jsx("a",{href:y.zoom_join_url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary underline",children:"Join Zoom"})]}),y.agenda&&e.jsxs("p",{className:"text-sm mb-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent's agenda:"})," ",y.agenda]}),y.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:y.summary}),y.private_notes&&e.jsxs("div",{className:"mt-2 p-2 rounded bg-muted/50 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground mb-1",children:[e.jsx(Ql,{className:"h-3 w-3"})," Private"]}),e.jsx("p",{className:"whitespace-pre-wrap",children:y.private_notes})]})]})})})},y.id))})]}),e.jsxs(Zt,{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(U,{size:"sm",onClick:()=>u(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-1"})," Add"]})]}),l.length===0?e.jsx(we,{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(we,{children:e.jsxs(Ie,{className:"p-3 flex items-center gap-3",children:[e.jsx(xi,{checked:y.status==="done",onCheckedChange:async v=>{await q.from("coaching_action_items").update({status:v?"done":"open",completed_at:v?new Date().toISOString():null}).eq("id",y.id),n.invalidateQueries({queryKey:["coaching-action-items",h.id]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:y.status==="done"?"line-through text-muted-foreground":"font-medium",children:y.title}),y.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:y.description})]}),y.due_date&&e.jsx(Be,{variant:"outline",children:Gs(new Date(y.due_date),"MMM d")}),e.jsx(Be,{variant:"secondary",className:"capitalize",children:y.priority})]})},y.id))})]}),e.jsx(Zt,{value:"goals",children:e.jsx(HOt,{assignmentId:h.id,canEdit:!0})}),e.jsx(Zt,{value:"kpis",children:h.agent_id&&e.jsx(VOt,{agentUserId:h.agent_id})}),e.jsx(Zt,{value:"messages",children:e.jsx(FOt,{assignmentId:h.id})}),e.jsx(Zt,{value:"files",children:e.jsx(GOt,{assignmentId:h.id})}),e.jsx(Zt,{value:"notes",className:"space-y-4",children:e.jsx(we,{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(FRs,{open:o,onOpenChange:c,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-sessions",h.id]})}),e.jsx(zRs,{open:d,onOpenChange:u,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-action-items",h.id]})})]})}function DRs({assignment:s}){const t=Qt(),[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(we,{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(pa,{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(xe,{type:"number",min:1,max:31,placeholder:"Default",value:n,onChange:o=>r(o.target.value),className:"w-28"}),e.jsxs(U,{size:"sm",variant:"outline",onClick:l,disabled:a,children:[e.jsx(Ho,{className:"h-4 w-4 mr-1"})," Save"]})]})})}function ORs({value:s,onChange:t}){return e.jsxs(Ns,{value:s,onValueChange:t,children:[e.jsx(ws,{className:"w-40",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"onboarding",children:"Onboarding"}),e.jsx(et,{value:"active",children:"Active"}),e.jsx(et,{value:"thriving",children:"Thriving"}),e.jsx(et,{value:"at_risk",children:"At Risk"}),e.jsx(et,{value:"graduated",children:"Graduated"})]})]})}function FRs({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,p]=j.useState(""),[f,x]=j.useState(!1),[y,v]=j.useState(!0),[b,N]=j.useState(null),[S,A]=j.useState(!1),T=async()=>{A(!0);const{data:M,error:I}=await q.functions.invoke("coaching-prep-brief",{body:{assignmentId:n}});if(A(!1),I||M!=null&&M.error)return re.error((M==null?void 0:M.error)||(I==null?void 0:I.message)||"Failed to generate brief");N(M.brief||"No brief returned.")},L=async()=>{x(!0);const{data:M,error:I}=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(I)return x(!1),re.error(I.message);if(re.success("Session saved"),y&&u.trim()&&(M!=null&&M.id)){const{error:R}=await q.functions.invoke("coaching-send-recap",{body:{sessionId:M.id}});R?re.error("Saved, but recap email failed: "+R.message):re.success("Recap emailed to agent")}x(!1),r==null||r(),t(!1),h(""),p(""),N(null)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx($s,{children:"New Session"}),e.jsxs(U,{size:"sm",variant:"outline",onClick:T,disabled:S,children:[S?e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(cn,{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(cn,{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(xe,{type:"datetime-local",value:a,onChange:M=>i(M.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Duration (min)"}),e.jsx(xe,{type:"number",value:l,onChange:M=>o(Number(M.target.value))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Template"}),e.jsxs(Ns,{value:c,onValueChange:d,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"weekly_1on1",children:"Weekly 1:1"}),e.jsx(et,{value:"grow",children:"GROW Model"}),e.jsx(et,{value:"goal_review",children:"Goal Review"}),e.jsx(et,{value:"breakthrough",children:"Breakthrough Session"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Summary (agent sees this)"}),e.jsx(Fs,{rows:4,value:u,onChange:M=>h(M.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(Ql,{className:"h-3 w-3"})," Private notes (only you)"]}),e.jsx(Fs,{rows:3,value:m,onChange:M=>p(M.target.value),placeholder:"Your private observations…"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm pt-1",children:[e.jsx(xi,{checked:y,onCheckedChange:M=>v(!!M)}),e.jsx($r,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Email recap to agent on save"]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{onClick:L,disabled:f,children:[e.jsx(Ho,{className:"h-4 w-4 mr-1"})," Save Session"]})]})]})})}function zRs({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,p]=j.useState(!1),f=async()=>{if(!a.trim())return;p(!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(p(!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(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"New Action Item"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(xe,{placeholder:"Title",value:a,onChange:x=>i(x.target.value)}),e.jsx(Fs,{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(xe,{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(Ns,{value:u,onValueChange:h,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"low",children:"Low"}),e.jsx(et,{value:"medium",children:"Medium"}),e.jsx(et,{value:"high",children:"High"})]})]})]})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(U,{onClick:f,disabled:m,children:"Add"})]})]})})}function t$e({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(Ua,{style:{width:t,height:t},className:r<=s?"fill-yellow-400 text-yellow-400":"text-muted-foreground/40"})},r))})}function BRs({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(t$e,{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(we,{children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs(Ea,{className:"h-9 w-9",children:[e.jsx(Ci,{src:((o=l.profile)==null?void 0:o.avatar_url)||void 0}),e.jsx(Ta,{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(t$e,{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 URs({coachId:s,assignmentId:t}){const{user:n}=vs(),[r,a]=j.useState(null),[i,l]=j.useState(0),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(!1);j.useEffect(()=>{n&&(async()=>{const{data:f}=await q.from("coaching_reviews").select("*").eq("coach_id",s).eq("agent_id",n.id).maybeSingle();f&&(a(f),l(f.rating),c(f.title||""),u(f.body||""))})()},[n,s]);const p=async()=>{if(!n)return;if(!i)return re.error("Pick a rating");m(!0);const f={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(f).eq("id",r.id):await q.from("coaching_reviews").insert(f);if(m(!1),x)return re.error(x.message);re.success("Thanks for your review!"),a({...f,id:r==null?void 0:r.id})};return e.jsx(we,{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(t$e,{value:i,size:28,onChange:l}),e.jsx(xe,{placeholder:"Title (optional)",value:o,onChange:f=>c(f.target.value)}),e.jsx(Fs,{rows:4,placeholder:"What was your experience like?",value:d,onChange:f=>u(f.target.value)}),e.jsx(U,{onClick:p,disabled:h,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:h?"Saving…":r?"Update review":"Submit review"})]})})}const Eoe=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},OOe=s=>Gs(s,"yyyy-MM-dd"),ift=s=>{const[t,n]=s.split(":").map(Number),r=t>=12?"PM":"AM";return`${t%12||12}:${String(n).padStart(2,"0")} ${r}`};function qRs({assignmentId:s,upcoming:t=[]}){const n=Qt(),[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:p,isLoading:f}=ct({queryKey:["coaching-booking-context",s],queryFn:()=>Eoe({action:"context"})});j.useEffect(()=>{var le;!r&&((le=p==null?void 0:p.booking_types)!=null&&le.length)&&a(p.booking_types[0].id)},[p,r]);const x=j.useMemo(()=>new Date,[]),[y,v]=j.useState(()=>Bh(new Date)),b=(p==null?void 0:p.max_advance_days)||30,N=j.useMemo(()=>jh(vf(x),b-1),[x,b]),S=j.useMemo(()=>{const le=Bh(y);return le{const le=u_(y);return le>N?N:le},[y,N]),T=Math.max(0,nv(A,S)+1),{data:L={},isFetching:M}=ct({queryKey:["coaching-availability",r,OOe(S),T],enabled:!!r&&T>0,queryFn:async()=>(await Eoe({action:"availability",booking_type_id:r,start:OOe(S),days:T})).availability||{}}),I=j.useMemo(()=>{const le=Bh(y),ue=u_(y).getDate(),se=le.getDay(),ne=Array.from({length:se},()=>null);for(let ie=0;ieObject.entries(L).filter(([,le])=>le.length>0),[L]),z=i?L[i]||[]:[],$=M,H=j.useMemo(()=>{const le=[{label:"Morning",items:[]},{label:"Afternoon",items:[]},{label:"Evening",items:[]}];for(const ue of z){const se=Number(ue.split(":")[0]);se<12?le[0].items.push(ue):se<17?le[1].items.push(ue):le[2].items.push(ue)}return le.filter(ue=>ue.items.length>0)},[z]),V=(p==null?void 0:p.booking_types.find(le=>le.id===r))||null,K=((p==null?void 0:p.sessions_remaining)??0)<=0,Z=async()=>{if(!(!r||!i||!o)){m(!0);try{await Eoe({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(le){re.error(le.message||"Could not book that session")}finally{m(!1)}}},Q=async le=>{if(await Yi("Cancel this coaching session?"))try{await Eoe({action:"cancel",session_id:le}),re.success("Session cancelled"),n.invalidateQueries({queryKey:["coaching-booking-context",s]}),n.invalidateQueries({queryKey:["coaching-sessions",s]})}catch(ue){re.error(ue.message||"Could not cancel")}};return f?e.jsx(we,{children:e.jsxs(Ie,{className:"p-8 flex items-center justify-center text-muted-foreground gap-2",children:[e.jsx(Et,{className:"h-4 w-4 animate-spin"})," Loading your coach's calendar…"]})}):p!=null&&p.scheduler_ready?e.jsxs("div",{className:"space-y-4",children:[e.jsx(we,{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(nc,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-medium",children:[p.sessions_remaining," of ",p.sessions_limit," sessions left this month"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your allowance resets on the 1st."})]})]}),K&&e.jsx(Be,{variant:"secondary",children:"All booked up"})]})}),t.length>0&&e.jsx(we,{children:e.jsxs(Ie,{className:"p-4 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Upcoming sessions"}),t.map(le=>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:Gs(new Date(le.scheduled_at),"EEE, MMM d · p")}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[le.duration_minutes||30," minutes"]})]}),le.zoom_join_url&&e.jsx(U,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:le.zoom_join_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Wr,{className:"h-4 w-4 mr-1"})," Join"]})}),e.jsxs(U,{size:"sm",variant:"ghost",onClick:()=>Q(le.id),children:[e.jsx(ou,{className:"h-4 w-4 mr-1"})," Cancel"]})]},le.id))]})}),e.jsx(we,{children:e.jsxs(Ie,{className:"p-4 md:p-6 space-y-5",children:[e.jsxs("div",{children:[e.jsx(te,{className:"mb-2 block",children:"Session type"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:p.booking_types.map(le=>e.jsxs("button",{onClick:()=>{a(le.id),c(null)},className:`text-left p-3 rounded-lg border transition-colors ${r===le.id?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx("div",{className:"font-medium",children:le.name}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1 mt-1",children:[e.jsx(Yr,{className:"h-3 w-3"})," ",le.duration_minutes," min"]}),le.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:le.description})]},le.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(te,{className:"block",children:"Pick a day"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(U,{size:"icon",variant:"ghost",className:"h-7 w-7",disabled:Kne(y,x),onClick:()=>v(dy(y,-1)),"aria-label":"Previous month",children:e.jsx(rd,{className:"h-4 w-4"})}),e.jsx("span",{className:"text-sm font-medium w-28 text-center",children:Gs(y,"MMMM yyyy")}),e.jsx(U,{size:"icon",variant:"ghost",className:"h-7 w-7",disabled:Bh(dy(y,1))>N,onClick:()=>v(dy(y,1)),"aria-label":"Next month",children:e.jsx(gi,{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((le,ue)=>e.jsx("div",{className:"text-[11px] text-muted-foreground text-center py-1",children:le},ue))}),e.jsx("div",{className:"grid grid-cols-7 gap-1",children:I.map((le,ue)=>{if(!le)return e.jsx("div",{},`b${ue}`);const se=OOe(le),ne=(L[se]||[]).length,ce=le>=vf(x)&&le<=N&&ne>0,je=i===se;return e.jsxs("button",{disabled:!ce,onClick:()=>{l(se),c(null)},className:`aspect-square rounded-lg border text-sm flex flex-col items-center justify-center gap-1 transition-colors ${je?"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?`${ne} opening${ne===1?"":"s"}`:"No openings",children:[e.jsx("span",{className:"leading-none",children:Gs(le,"d")}),e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${je?"bg-primary-foreground":ce?"bg-primary":"bg-transparent"}`})]},se)})}),e.jsx("div",{className:"mt-3 flex items-center gap-2 text-xs text-muted-foreground",children:M?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-3 w-3 animate-spin"})," Loading your coach's openings…"]}):e.jsxs(e.Fragment,{children:[e.jsx(cn,{className:"h-3 w-3 text-primary"}),R.length===0?"No openings this month — try the next month.":`${R.length} day${R.length===1?"":"s"} with openings this month`]})})]}),e.jsxs("div",{children:[e.jsx(te,{className:"mb-2 block",children:i?`Available times · ${Gs(new Date(`${i}T12:00:00`),"EEE, MMM d")}`:"Available times"}),i?$?e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(Et,{className:"h-4 w-4 animate-spin"})," Checking availability…"]}):z.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:H.map(le=>e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:le.label}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:le.items.map(ue=>e.jsx("button",{onClick:()=>c(ue),className:`py-2 rounded-lg border text-sm transition-colors ${o===ue?"border-primary bg-primary/10 font-medium":"hover:bg-muted/50"}`,children:ift(ue)},ue))})]},le.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."}),!M&&R.length>0&&e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:R.slice(0,3).map(([le,ue])=>e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>{l(le),c(null)},children:[Gs(new Date(`${le}T12:00:00`),"EEE MMM d")," · ",ue.length," open"]},le))})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(te,{htmlFor:"agenda",children:"What do you want to work on? (optional)"}),e.jsx(Fs,{id:"agenda",rows:3,value:d,onChange:le=>u(le.target.value),placeholder:"Share context so your coach can prep."})]}),e.jsxs(U,{onClick:Z,disabled:h||K,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[h?e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(zr,{className:"h-4 w-4 mr-1"}),"Book ",V==null?void 0:V.name," — ",i&&Gs(new Date(`${i}T12:00:00`),"MMM d")," at ",ift(o)]}),K&&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(we,{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 $Rs(){const{user:s}=vs(),{isMember:t,pkg:n}=_S(),{data:r}=ct({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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between gap-2 space-y-0",children:[e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(iy,{className:"h-4 w-4 text-primary"})," Coaching prep"]}),a.length>0&&e.jsxs(Be,{variant:"secondary",children:[i,"/",a.length," done"]})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-border/60 p-3",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-medium",children:"Onboarding questionnaire"}),e.jsx("div",{className:"text-muted-foreground text-xs",children:r!=null&&r.submitted?"Submitted — your coach has it.":"Complete this before session one."})]}),e.jsx(U,{asChild:!0,size:"sm",variant:r!=null&&r.submitted?"outline":"default",children:e.jsx(xr,{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(zr,{className:"h-4 w-4 mt-0.5 text-primary"}):e.jsx(Nf,{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 VRs(){var m,p,f,x,y,v;const{user:s}=vs(),{data:t,isLoading:n,refetch:r}=yQe(),a=Qt(),i=t==null?void 0:t.id,{data:l=[]}=vQe(i),{data:o=[]}=bQe(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(qs,{title:"My Coach",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(qs,{title:"My Coach",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(Kh,{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(qs,{title:"My Coach",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-5xl mx-auto space-y-6",children:[e.jsx(we,{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(Ea,{className:"h-24 w-24 ring-4 ring-white/20",children:[e.jsx(Ci,{src:((m=c.coachProfile)==null?void 0:m.avatar_url)||void 0}),e.jsx(Ta,{className:"text-2xl bg-white/20 text-white",children:(((p=c.coachProfile)==null?void 0:p.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/80 mb-1",children:[e.jsx(cn,{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:((f=c.coachProfile)==null?void 0:f.name)||"Your Coach"}),((x=c.coach)==null?void 0:x.headline)&&e.jsx("p",{className:"text-white/80 mt-1",children:c.coach.headline}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[((y=c.coach)==null?void 0:y.is_certified)&&e.jsx(Be,{className:"bg-yellow-400/20 text-yellow-100 border-yellow-300/30",children:"LevelUp Certified"}),e.jsx(Be,{variant:"secondary",className:"bg-white/15 text-white border-white/20",children:"Active Program"})]})]})]})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(FOe,{icon:cy,label:"Open action items",value:d.length}),e.jsx(FOe,{icon:Gu,label:"Completed",value:u}),e.jsx(FOe,{icon:pa,label:"Sessions",value:l.length})]}),e.jsx($Rs,{}),((v=c.coach)==null?void 0:v.id)&&e.jsx(URs,{coachId:c.coach.id,assignmentId:i}),e.jsxs(oa,{defaultValue:"book",children:[e.jsxs(la,{className:"flex flex-wrap h-auto w-full justify-start",children:[e.jsxs(Kt,{value:"book",children:[e.jsx(sv,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Book"})]}),e.jsxs(Kt,{value:"actions",children:[e.jsx(cy,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(Kt,{value:"sessions",children:[e.jsx(pa,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Recaps"})]}),e.jsxs(Kt,{value:"goals",children:[e.jsx(Gu,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Goals"})]}),e.jsxs(Kt,{value:"kpis",children:[e.jsx(rc,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"KPIs"})]}),e.jsxs(Kt,{value:"messages",children:[e.jsx(Ki,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Messages"})]}),e.jsxs(Kt,{value:"files",children:[e.jsx(r1,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Files"})]})]}),e.jsx(Zt,{value:"book",children:e.jsx(qRs,{assignmentId:i,upcoming:h})}),e.jsx(Zt,{value:"actions",className:"space-y-2",children:o.length===0?e.jsx(we,{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(we,{children:e.jsxs(Ie,{className:"p-3 flex items-center gap-3",children:[e.jsx(xi,{checked:b.status==="done",onCheckedChange:async N=>{await q.from("coaching_action_items").update({status:N?"done":"open",completed_at:N?new Date().toISOString():null}).eq("id",b.id),a.invalidateQueries({queryKey:["coaching-action-items",i]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:b.status==="done"?"line-through text-muted-foreground":"font-medium",children:b.title}),b.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:b.description})]}),b.due_date&&e.jsx(Be,{variant:"outline",children:Gs(new Date(b.due_date),"MMM d")}),e.jsx(Be,{variant:"secondary",className:"capitalize",children:b.priority})]})},b.id))}),e.jsx(Zt,{value:"sessions",className:"space-y-3",children:l.length===0?e.jsx(we,{children:e.jsx(Ie,{className:"p-6 text-center text-muted-foreground",children:"No sessions logged yet."})}):l.map(b=>e.jsx(we,{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:Gs(new Date(b.scheduled_at),"PPp")}),e.jsx(Be,{variant:"outline",className:"capitalize",children:b.status})]}),b.summary?e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:b.summary}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"Recap coming soon."})]})},b.id))}),e.jsx(Zt,{value:"goals",children:e.jsx(HOt,{assignmentId:i,canEdit:!1})}),e.jsx(Zt,{value:"kpis",children:s&&e.jsx(VOt,{agentUserId:s.id})}),e.jsx(Zt,{value:"messages",children:e.jsx(FOt,{assignmentId:i})}),e.jsx(Zt,{value:"files",children:e.jsx(GOt,{assignmentId:i})})]})]})})}function FOe({icon:s,label:t,value:n}){return e.jsx(we,{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 oft="coaching_access",zOe=s=>((s==null?void 0:s.name)||(s==null?void 0:s.email)||"?").trim().slice(0,2).toUpperCase(),BOe=s=>!!s.expires_at&&new Date(s.expires_at).getTime()<=Date.now();function HRs(){const s=Qt(),[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}=ct({queryKey:["coaching-entitlements"],queryFn:async()=>{const{data:R,error:z}=await q.from("feature_entitlements").select("id, user_id, enabled, expires_at, tier, notes, enabled_at").eq("feature_key",oft).order("enabled_at",{ascending:!1});if(z)throw z;return R||[]}}),{data:p=[]}=ct({queryKey:["coaching-assigned-agents"],queryFn:async()=>{const{data:R,error:z}=await q.from("coaching_assignments").select("agent_id, coach_id, status").eq("status","active");if(z)throw z;return R||[]}}),f=j.useMemo(()=>{const R=new Set;return h.forEach(z=>R.add(z.user_id)),p.forEach(z=>R.add(z.agent_id)),Array.from(R)},[h,p]),{data:x={}}=ct({queryKey:["coaching-access-profiles",f.join(",")],enabled:f.length>0,queryFn:async()=>{const R={};for(let z=0;z{R[H.id]=H})}return R}});j.useEffect(()=>{const R=t.trim();if(R.length<2){a([]),l(!1);return}l(!0);const z=setTimeout(async()=>{const{data:$}=await q.from("profiles").select("id, name, email, avatar_url").or(`email.ilike.%${R}%,name.ilike.%${R}%`).limit(12);a($||[]),l(!1)},250);return()=>clearTimeout(z)},[t]);const y=j.useMemo(()=>{const R=new Map;return h.forEach(z=>R.set(z.user_id,z)),R},[h]),v=j.useMemo(()=>new Set(p.map(R=>R.agent_id)),[p]),b=()=>{s.invalidateQueries({queryKey:["coaching-entitlements"]}),s.invalidateQueries({queryKey:["coaching-access-profiles"]}),s.invalidateQueries({queryKey:["coaching-access"]})},N=async(R,z={})=>{var V;const{data:$}=await q.auth.getUser(),{error:H}=await q.from("feature_entitlements").upsert({user_id:R,feature_key:oft,enabled:z.enabled??!0,expires_at:z.expires_at??null,notes:z.notes??null,tier:z.tier??null,enabled_by:((V=$==null?void 0:$.user)==null?void 0:V.id)??null,enabled_at:new Date().toISOString(),updated_at:new Date().toISOString()},{onConflict:"user_id,feature_key"});return H?(re.error(H.message),!1):(b(),!0)},S=async R=>{await N(R.id)&&re.success(`Coaching access granted to ${R.name||R.email}`),n(""),a([])},A=async(R,z)=>{const{error:$}=await q.from("feature_entitlements").update({enabled:z,updated_at:new Date().toISOString()}).eq("id",R.id);if($)return re.error($.message);re.success(z?"Access enabled":"Access paused"),b()},T=async R=>{if(!await Yi({title:"Revoke coaching access?",description:`${R.profile.name||R.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:$}=await q.from("feature_entitlements").delete().eq("id",R.entitlement.id);if($)return re.error($.message);re.success("Coaching access revoked"),b()},L=j.useMemo(()=>{const R=d.trim().toLowerCase(),z=h.map($=>({entitlement:$,profile:x[$.user_id]}));return R?z.filter(({profile:$})=>`${($==null?void 0:$.name)||""} ${($==null?void 0:$.email)||""}`.toLowerCase().includes(R)):z},[h,x,d]),M=h.filter(R=>R.enabled&&!BOe(R)).length,I=p.filter(R=>!y.has(R.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(UOe,{icon:cg,label:"Granted access",value:M,hint:"Standalone entitlements"}),e.jsx(UOe,{icon:Bn,label:"Coached members",value:v.size,hint:"Active coach assignments"}),e.jsx(UOe,{icon:cn,label:"Total with access",value:new Set([...h.filter(R=>R.enabled&&!BOe(R)).map(R=>R.user_id),...v]).size,hint:"Unique members"})]}),e.jsx(we,{children:e.jsxs(Ie,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(SA,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{className:"pl-9",placeholder:"Search members by name or email…",value:t,onChange:R=>n(R.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(Et,{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(R=>{const z=y.get(R.id),$=v.has(R.id);return e.jsxs("div",{className:"flex items-center gap-3 p-2.5 hover:bg-muted/40",children:[e.jsxs(Ea,{className:"h-8 w-8",children:[e.jsx(Ci,{src:R.avatar_url||void 0}),e.jsx(Ta,{className:"text-xs",children:zOe(R)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:R.name||R.email}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:R.email})]}),z?e.jsx(Be,{variant:"outline",className:"shrink-0",children:"Already granted"}):$?e.jsxs(Be,{variant:"outline",className:"shrink-0",children:[e.jsx(ad,{className:"h-3 w-3 mr-1"}),"Has coach"]}):e.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[e.jsx(U,{size:"sm",variant:"outline",onClick:()=>c({profile:R}),children:"Options"}),e.jsxs(U,{size:"sm",className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>S(R),children:[e.jsx(zl,{className:"h-4 w-4 mr-1"})," Grant"]})]})]},R.id)})})]})}),e.jsx(we,{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(cg,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Members with granted access"}),e.jsx(Be,{variant:"outline",children:h.length}),e.jsx("div",{className:"ml-auto w-full sm:w-64",children:e.jsx(xe,{placeholder:"Filter list…",value:d,onChange:R=>u(R.target.value)})})]}),m?e.jsxs("div",{className:"p-6 text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(Et,{className:"h-4 w-4 animate-spin"})," Loading…"]}):L.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:L.map(({entitlement:R,profile:z})=>{const $=BOe(R);return e.jsxs("div",{className:"flex items-center gap-3 p-3 flex-wrap",children:[e.jsxs(Ea,{className:"h-9 w-9",children:[e.jsx(Ci,{src:(z==null?void 0:z.avatar_url)||void 0}),e.jsx(Ta,{className:"text-xs",children:zOe(z)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:(z==null?void 0:z.name)||(z==null?void 0:z.email)||R.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:z==null?void 0:z.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[$?e.jsx(Be,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:"Expired"}):R.enabled?e.jsx(Be,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:"Active"}):e.jsx(Be,{variant:"outline",children:"Paused"}),v.has(R.user_id)&&e.jsxs(Be,{variant:"outline",children:[e.jsx(ad,{className:"h-3 w-3 mr-1"}),"Has coach"]}),R.tier&&e.jsx(Be,{variant:"outline",children:R.tier}),R.expires_at&&e.jsxs("span",{className:"text-xs text-muted-foreground inline-flex items-center gap-1",children:[e.jsx(ch,{className:"h-3 w-3"}),$?"Expired":"Expires"," ",new Date(R.expires_at).toLocaleDateString()]})]}),R.notes&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic truncate",children:R.notes})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(wn,{checked:R.enabled&&!$,onCheckedChange:H=>A(R,H)}),e.jsx(U,{size:"sm",variant:"outline",onClick:()=>c({profile:z||{id:R.user_id,name:null,email:null},entitlement:R}),children:"Edit"}),e.jsx(U,{size:"sm",variant:"ghost",className:"text-rose-600 hover:bg-rose-50",onClick:()=>T({profile:z||{id:R.user_id,name:null,email:null},entitlement:R}),children:e.jsx(er,{className:"h-4 w-4"})})]})]},R.id)})})]})}),e.jsx(we,{children:e.jsxs(Ie,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Access through a coach assignment"}),e.jsx(Be,{variant:"outline",children:I.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."}),I.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:I.map(R=>{const z=x[R.agent_id];return e.jsxs("div",{className:"flex items-center gap-2 border rounded-full pl-1 pr-3 py-1",children:[e.jsxs(Ea,{className:"h-6 w-6",children:[e.jsx(Ci,{src:(z==null?void 0:z.avatar_url)||void 0}),e.jsx(Ta,{className:"text-[10px]",children:zOe(z)})]}),e.jsx("span",{className:"text-sm",children:(z==null?void 0:z.name)||(z==null?void 0:z.email)||R.agent_id})]},R.agent_id)})})]})}),e.jsx(GRs,{state:o,onClose:()=>c(null),onSave:async R=>{if(!o)return;await N(o.profile.id,R)&&(re.success("Coaching access saved"),c(null))}})]})}function UOe({icon:s,label:t,value:n,hint:r}){return e.jsx(we,{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 GRs({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 f=s.entitlement;a(f!=null&&f.expires_at?f.expires_at.slice(0,10):""),l((f==null?void 0:f.notes)||""),c((f==null?void 0:f.tier)||""),u(f?f.enabled:!0)},[s]);const p=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:f=>!f&&t(),children:e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:s!=null&&s.entitlement?"Edit coaching access":"Grant coaching access"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-medium",children:(s==null?void 0:s.profile.name)||(s==null?void 0:s.profile.email)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:s==null?void 0:s.profile.email})]}),e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Access enabled"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to pause without removing the grant."})]}),e.jsx(wn,{checked:d,onCheckedChange:u})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Expires on (optional)"}),e.jsx(xe,{type:"date",value:r,onChange:f=>a(f.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(te,{children:"Tier / plan label (optional)"}),e.jsx(xe,{value:o,onChange:f=>c(f.target.value),placeholder:"e.g. Premium, Beta, Comp"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Internal notes"}),e.jsx(Fs,{value:i,onChange:f=>l(f.target.value),rows:3,placeholder:"Why this member has access…"})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx(U,{onClick:p,disabled:h,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:h?"Saving…":"Save access"})]})]})})}function WRs(){const s=Qt(),[t,n]=j.useState(""),[r,a]=j.useState("active"),{data:i=[]}=ct({queryKey:["admin-coaches-lite"],queryFn:async()=>{const{data:p,error:f}=await q.from("coaches").select("id, user_id");if(f)throw f;const x=(p||[]).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(p||[]).map(b=>{var N,S;return{id:b.id,label:((N=v.get(b.user_id))==null?void 0:N.name)||((S=v.get(b.user_id))==null?void 0:S.email)||b.user_id}})}}),{data:l=[],isLoading:o}=ct({queryKey:["admin-coaching-assignments"],queryFn:async()=>{const{data:p,error:f}=await q.from("coaching_assignments").select("*").order("created_at",{ascending:!1});if(f)throw f;const x=[...new Set((p||[]).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(p||[]).map(b=>({...b,agent:v.get(b.agent_id)}))}}),c=p=>{var f;return((f=i.find(x=>x.id===p))==null?void 0:f.label)||"—"},d=j.useMemo(()=>{const p=t.trim().toLowerCase();return l.filter(f=>{var x,y;return r!=="all"&&f.status!==r?!1:p?(((x=f.agent)==null?void 0:x.name)||"").toLowerCase().includes(p)||(((y=f.agent)==null?void 0:y.email)||"").toLowerCase().includes(p)||c(f.coach_id).toLowerCase().includes(p):!0})},[l,t,r,i]),u=()=>{s.invalidateQueries({queryKey:["admin-coaching-assignments"]}),s.invalidateQueries({queryKey:["coach-roster"]})},h=async(p,f)=>{var v,b;if(f===p.coach_id||!await Yi({title:"Switch coach?",description:`${((v=p.agent)==null?void 0:v.name)||((b=p.agent)==null?void 0:b.email)} will move from ${c(p.coach_id)} to ${c(f)}. Session history stays with the assignment.`,confirmText:"Switch coach"}))return;const{error:y}=await q.from("coaching_assignments").update({coach_id:f}).eq("id",p.id);if(y)return re.error(y.message);re.success("Coach switched"),u()},m=async(p,f)=>{var y,v;if(f==="ended"&&!await Yi({title:"End assignment?",description:`${((y=p.agent)==null?void 0:y.name)||((v=p.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:f,ended_at:f==="ended"?new Date().toISOString():null}).eq("id",p.id);if(x)return re.error(x.message);re.success(f==="ended"?"Assignment ended":"Assignment reactivated"),u()};return e.jsx(we,{children:e.jsxs(Ie,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach assignments"}),e.jsx(Be,{variant:"secondary",className:"ml-auto",children:d.length})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Switch an agent to a different coach, end an assignment, or reactivate a past one."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(xe,{placeholder:"Search by agent or coach…",value:t,onChange:p=>n(p.target.value)}),e.jsxs(Ns,{value:r,onValueChange:p=>a(p),children:[e.jsx(ws,{className:"sm:w-40",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"active",children:"Active"}),e.jsx(et,{value:"ended",children:"Ended"}),e.jsx(et,{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(p=>{var f,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:((f=p.agent)==null?void 0:f.name)||((x=p.agent)==null?void 0:x.email)||p.agent_id}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[(y=p.agent)==null?void 0:y.email," · ",p.pipeline_stage||"onboarding",p.status==="ended"&&" · ended"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kX,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(Ns,{value:p.coach_id,onValueChange:v=>h(p,v),children:[e.jsx(ws,{className:"w-full md:w-56 h-9",children:e.jsx(ks,{})}),e.jsx(js,{children:i.map(v=>e.jsx(et,{value:v.id,children:v.label},v.id))})]}),p.status==="active"?e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>m(p,"ended"),children:[e.jsx(Nq,{className:"h-4 w-4 mr-1"})," End"]}):e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>m(p,"active"),children:[e.jsx(Kg,{className:"h-4 w-4 mr-1"})," Reactivate"]})]})]},p.id)})})]})})}function KRs(){const s=Qt(),[t,n]=j.useState(""),[r,a]=j.useState([]),[i,l]=j.useState(null),{data:o=[],isLoading:c}=ct({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 p=h.map(y=>y.user_id),{data:f}=await q.from("profiles").select("id, name, email, avatar_url").in("id",p),x=new Map((f||[]).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:p}=await q.from("profiles").select("id, email, name, avatar_url").or(`email.ilike.%${h}%,name.ilike.%${h}%`).limit(10);a(p||[])},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:p}=await q.from("coaches").insert({user_id:h.id});if(p&&!String(p.message).includes("duplicate"))return re.error(p.message);re.success(`${h.name||h.email} is now a coach`),n(""),a([]),s.invalidateQueries({queryKey:["admin-coaches"]})},u=async(h,m)=>{const{error:p}=await q.from("coaches").update({is_certified:m}).eq("id",h);if(p)return re.error(p.message);re.success(m?"Marked Certified":"Removed certification"),s.invalidateQueries({queryKey:["admin-coaches"]})};return e.jsxs(qs,{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(Kh,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"LevelUp Coaching"})]}),e.jsxs(oa,{defaultValue:"coaches",className:"space-y-6",children:[e.jsxs(la,{className:"flex-wrap h-auto",children:[e.jsx(Kt,{value:"coaches",children:"Coaches"}),e.jsx(Kt,{value:"assignments",children:"Assignments"}),e.jsx(Kt,{value:"access",children:"Coaching Access"}),e.jsx(Kt,{value:"applications",children:"Applications"}),e.jsx(Kt,{value:"settings",children:"Settings"})]}),e.jsx(Zt,{value:"assignments",className:"space-y-6",children:e.jsx(WRs,{})}),e.jsx(Zt,{value:"access",className:"space-y-6",children:e.jsx(HRs,{})}),e.jsx(Zt,{value:"applications",className:"space-y-6",children:e.jsx(XRs,{})}),e.jsx(Zt,{value:"settings",className:"space-y-6",children:e.jsx(YRs,{})}),e.jsxs(Zt,{value:"coaches",className:"space-y-6",children:[e.jsx(we,{children:e.jsxs(Ie,{className:"p-4 space-y-3",children:[e.jsx(xe,{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(U,{size:"sm",onClick:()=>d(h),children:[e.jsx(an,{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(we,{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,p,f;return e.jsx(we,{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)||((p=h.profile)==null?void 0:p.email)||h.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(f=h.profile)==null?void 0:f.email}),e.jsxs("div",{className:"flex gap-2 mt-2 flex-wrap",children:[h.is_certified&&e.jsxs(Be,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(cn,{className:"h-3 w-3 mr-1"}),"Certified"]}),h.accepting_clients&&e.jsx(Be,{variant:"outline",children:"Accepting clients"})]})]}),e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>l(h.id),children:[e.jsx(zl,{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(wn,{checked:h.is_certified,onCheckedChange:x=>u(h.id,x)})]})]})},h.id)})})]})]})]})]}),e.jsx(ZRs,{coachId:i,onClose:()=>l(null)})]})}function YRs(){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(we,{children:e.jsxs(Ie,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(PM,{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(te,{children:"Fee (bps)"}),e.jsx(xe,{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(U,{onClick:l,disabled:n,className:"bg-[#406E71] hover:bg-[#2a4c64] self-end",children:n?"Saving…":"Save"})]})]})})}function ZRs({coachId:s,onClose:t}){const[n,r]=j.useState(""),[a,i]=j.useState([]),[l,o]=j.useState(!1),c=Qt();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(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Assign Agent"})}),e.jsx(xe,{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(Mr,{children:e.jsx(U,{variant:"outline",onClick:t,children:"Close"})})]})})}function XRs(){const s=Qt(),[t,n]=j.useState("pending"),[r,a]=j.useState(null),{data:i=[],isLoading:l}=ct({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}=ct({queryKey:["coach-applications-pending-count"],queryFn:async()=>{const{count:u}=await q.from("coach_applications").select("id",{count:"exact",head:!0}).eq("status","pending");return u||0}}),c=async(u,h)=>{const{error:m}=await q.from("coach_applications").update({status:h,reviewed_at:new Date().toISOString()}).eq("id",u);if(m)return re.error(m.message);re.success(`Marked ${h}`),s.invalidateQueries({queryKey:["coach-applications"]}),s.invalidateQueries({queryKey:["coach-applications-pending-count"]}),a(null)},d=u=>u==="approved"?e.jsxs(Be,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:[e.jsx(Xr,{className:"h-3 w-3 mr-1"}),"Approved"]}):u==="rejected"?e.jsxs(Be,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:[e.jsx(er,{className:"h-3 w-3 mr-1"}),"Rejected"]}):e.jsxs(Be,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(Yr,{className:"h-3 w-3 mr-1"}),"Pending"]});return e.jsxs(we,{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(AM,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach Applications"}),o>0&&e.jsxs(Be,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[o," pending"]}),e.jsx("div",{className:"ml-auto flex gap-1 flex-wrap",children:["pending","approved","rejected","all"].map(u=>e.jsx(U,{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(ln,{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(Ds,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:r&&e.jsxs(e.Fragment,{children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-3",children:[r.full_name,d(r.status)]})}),e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Hz,{icon:ln,label:"Email",value:r.email,link:`mailto:${r.email}`}),r.phone&&e.jsx(Hz,{icon:ba,label:"Phone",value:r.phone,link:`tel:${r.phone}`}),r.brokerage&&e.jsx(Hz,{label:"Brokerage",value:r.brokerage}),r.years_experience&&e.jsx(Hz,{label:"Years",value:r.years_experience}),r.website_url&&e.jsx(Hz,{icon:Sr,label:"Website",value:r.website_url,link:r.website_url}),r.linkedin_url&&e.jsx(Hz,{icon:Sr,label:"LinkedIn",value:r.linkedin_url,link:r.linkedin_url})]}),r.specialties&&e.jsx(qOe,{label:"Specialties",children:r.specialties}),e.jsx(qOe,{label:"Why they want to coach",children:r.why_coach}),r.results_story&&e.jsx(qOe,{label:"Results story",children:r.results_story}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Admin notes"}),e.jsx(Fs,{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(Mr,{className:"gap-2 flex-wrap",children:[r.status!=="rejected"&&e.jsxs(U,{variant:"outline",onClick:()=>c(r.id,"rejected"),className:"text-rose-600 border-rose-200 hover:bg-rose-50",children:[e.jsx(er,{className:"h-4 w-4 mr-1"})," Reject"]}),r.status!=="pending"&&e.jsxs(U,{variant:"outline",onClick:()=>c(r.id,"pending"),children:[e.jsx(Yr,{className:"h-4 w-4 mr-1"})," Move to pending"]}),r.status!=="approved"&&e.jsxs(U,{onClick:()=>c(r.id,"approved"),className:"bg-emerald-600 hover:bg-emerald-700",children:[e.jsx(Xr,{className:"h-4 w-4 mr-1"})," Approve"]})]})]})})})]})}function Hz({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 qOe({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 QRs(){const s=Wn(),{data:t}=nre(),n=Qt(),[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(null),{data:d,refetch:u}=ct({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=[]}=ct({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 N,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=(N=v==null?void 0:v.context)==null?void 0:N.json)==null?void 0:S.call(N));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)},p=d||{},f=!!(t!=null&&t.use_platform_stripe),x=f||p.connected&&p.charges_enabled;return e.jsx(qs,{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(U,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(Aa,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Billing & Packages"})]}),e.jsx(we,{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(oy,{className:"h-5 w-5"})," Stripe Connect"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:f?"Your coaching sales are billed through the main LevelUp Stripe account.":"Payouts go directly to your bank. LevelUp takes a small platform fee from each charge."})]}),x?e.jsxs(Be,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40 flex items-center gap-1",children:[e.jsx(zr,{className:"h-3 w-3"})," ",f?"Using LevelUp billing":"Connected"]}):p.connected?e.jsxs(Be,{variant:"secondary",className:"flex items-center gap-1",children:[e.jsx(Vo,{className:"h-3 w-3"})," Setup incomplete"]}):e.jsx(Be,{variant:"outline",children:"Not connected"})]}),!f&&e.jsxs(U,{onClick:m,disabled:r,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[x?"Update Stripe details":p.connected?"Finish Stripe setup":"Connect Stripe",e.jsx(Sr,{className:"h-4 w-4 ml-1"})]})]})}),e.jsx(we,{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(U,{size:"sm",onClick:()=>{c(null),l(!0)},disabled:!x,children:[e.jsx(an,{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(U,{variant:"ghost",size:"icon",onClick:()=>{c(y),l(!0)},children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:async()=>{await Yi("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(In,{className:"h-4 w-4"})})]},y.id))})]})}),e.jsx(JRs,{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 JRs({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"),[p,f]=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"),f((r==null?void 0:r.is_active)??!0),y((r==null?void 0:r.accepting_clients)??!0))},[s,r]);const N=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:p,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(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:r!=null&&r.id?"Edit Package":"New Package"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(xe,{placeholder:"Name (e.g. Accelerator)",value:i,onChange:S=>l(S.target.value)}),e.jsx(Fs,{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(xe,{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(Ns,{value:h,onValueChange:m,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"month",children:"Monthly"}),e.jsx(et,{value:"year",children:"Yearly"}),e.jsx(et,{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:p,onChange:S=>f(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(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(U,{onClick:N,disabled:v,children:r!=null&&r.id?"Save":"Create"})]})]})})}function lft({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),p=j.useRef([]),[f,x]=j.useState(!1),y=s==="photo"?"image/*":"video/*",v=s==="photo"?10*1024*1024:200*1024*1024,b=async(M,I)=>{var K;const{data:R}=await q.auth.getUser(),z=(K=R.user)==null?void 0:K.id;if(!z)return re.error("Not signed in");if(M.size>v)return re.error(`File too large. Max ${s==="photo"?"10MB":"200MB"}.`);i(!0);const $=`${z}/${s}-${Date.now()}.${I}`,{error:H}=await q.storage.from("coach-media").upload($,M,{upsert:!0,contentType:M.type||(s==="photo"?"image/jpeg":"video/webm")});if(H)return i(!1),re.error(H.message);const{data:V}=await q.storage.from("coach-media").createSignedUrl($,60*60*24*365*10);i(!1),V!=null&&V.signedUrl&&(n(V.signedUrl),re.success("Uploaded"),d(null))},N=async M=>{const I=M.name.split(".").pop()||(s==="photo"?"jpg":"webm");await b(M,I)},S=async()=>{try{const M=await navigator.mediaDevices.getUserMedia({video:!0,audio:!0});h.current=M,x(!0),setTimeout(()=>{u.current&&(u.current.srcObject=M,u.current.play())},50);const I=new MediaRecorder(M,{mimeType:"video/webm"});p.current=[],I.ondataavailable=R=>R.data.size>0&&p.current.push(R.data),I.onstop=()=>{const R=new Blob(p.current,{type:"video/webm"});d(R),M.getTracks().forEach(z=>z.stop())},m.current=I,I.start(),o(!0)}catch(M){re.error(M.message||"Could not access camera")}},A=()=>{var M;(M=m.current)==null||M.stop(),o(!1)},T=()=>{var M;(M=h.current)==null||M.getTracks().forEach(I=>I.stop()),x(!1),o(!1),d(null)},L=async()=>{c&&(await b(c,"webm"),T())};return j.useEffect(()=>()=>{var M;return(M=h.current)==null?void 0:M.getTracks().forEach(I=>I.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:M=>{var R;const I=(R=M.target.files)==null?void 0:R[0];I&&N(I),M.target.value=""}}),e.jsxs(U,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:()=>{var M;return(M=r.current)==null?void 0:M.click()},children:[a?e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(qa,{className:"h-4 w-4 mr-1"}),s==="photo"?"Upload photo":"Upload video"]}),s==="video"&&e.jsxs(U,{type:"button",variant:"outline",size:"sm",onClick:S,disabled:a||f,children:[e.jsx(_x,{className:"h-4 w-4 mr-1"})," Record intro"]}),t&&e.jsxs(U,{type:"button",variant:"ghost",size:"sm",onClick:()=>n(""),children:[e.jsx(In,{className:"h-4 w-4 mr-1"})," Remove"]})]}),f&&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(U,{type:"button",size:"sm",onClick:A,className:"bg-red-600 hover:bg-red-700",children:[e.jsx(db,{className:"h-4 w-4 mr-1"})," Stop"]}),!c&&!l&&e.jsxs(U,{type:"button",size:"sm",onClick:()=>{var M;return(M=m.current)==null?void 0:M.start()},children:[e.jsx(Wr,{className:"h-4 w-4 mr-1"})," Start"]}),c&&e.jsxs(e.Fragment,{children:[e.jsxs(U,{type:"button",size:"sm",onClick:L,disabled:a,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[a?e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(qa,{className:"h-4 w-4 mr-1"}),"Use this recording"]}),e.jsx(U,{type:"button",size:"sm",variant:"outline",onClick:()=>{d(null),S()},children:"Re-record"})]}),e.jsx(U,{type:"button",size:"sm",variant:"ghost",onClick:T,children:"Cancel"})]})]})]})}function WOt(){const{user:s}=vs(),t=Qt(),n=ct({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=ct({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=ct({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=ct({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=ct({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=yt({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:N}=await q.from("agent_booking_types").insert(b.map(T=>({...T,user_id:s.id})));if(N)throw N;const S=[1,2,3,4,5].map(T=>({user_id:s.id,day_of_week:T,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=yt({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=yt({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=yt({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=yt({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=yt({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)}),p=yt({mutationFn:async y=>{const{blocked_date:v,end_date:b,reason:N}=y,S=R=>{const[z,$,H]=R.split("-").map(Number);return new Date(z,$-1,H)},A=R=>`${R.getFullYear()}-${String(R.getMonth()+1).padStart(2,"0")}-${String(R.getDate()).padStart(2,"0")}`,T=S(v),L=b?S(b):T;if(L366)throw new Error("Range too large (max 1 year)");const{error:I}=await q.from("agent_blocked_dates").upsert(M,{onConflict:"user_id,blocked_date",ignoreDuplicates:!0});if(I)throw I;return M.length},onSuccess:y=>{t.invalidateQueries({queryKey:["blocked-dates"]}),re.success(y&&y>1?`${y} dates blocked`:"Date blocked")},onError:y=>re.error(y.message)}),f=yt({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=yt({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(N=>console.error("Google calendar cleanup failed:",N))},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:p,removeBlockedDate:f,cancelBooking:x}}const cft=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function KOt({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=cft.map((h,m)=>s.filter(p=>p.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(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Yr,{className:"h-5 w-5"}),"Weekly Availability"]}),e.jsx(Jn,{children:"Set your available hours for each day"})]}),e.jsx(Ie,{className:"space-y-2",children:cft.map((h,m)=>{const p=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:[p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-1",children:"Unavailable"}):p.map(f=>{var x,y;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(x=f.start_time)==null?void 0:x.slice(0,5),onBlur:v=>t({id:f.id,start_time:v.target.value})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(xe,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(y=f.end_time)==null?void 0:y.slice(0,5),onBlur:v=>t({id:f.id,end_time:v.target.value})}),e.jsx(wn,{checked:f.is_active,onCheckedChange:v=>t({id:f.id,is_active:v})}),e.jsx(U,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>n(f.id),children:e.jsx(In,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},f.id)}),r===m?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"time",className:"w-28 h-8 text-sm",value:i,onChange:f=>l(f.target.value)}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(xe,{type:"time",className:"w-28 h-8 text-sm",value:o,onChange:f=>c(f.target.value)}),e.jsx(U,{size:"sm",className:"h-8",onClick:u,children:"Add"}),e.jsx(U,{variant:"ghost",size:"sm",className:"h-8",onClick:()=>a(null),children:"Cancel"})]}):e.jsxs(U,{variant:"ghost",size:"sm",className:"h-7 text-xs text-muted-foreground",onClick:()=>a(m),children:[e.jsx(an,{className:"h-3 w-3 mr-1"})," Add hours"]})]})]},h)})})]})}function dft(s){const[t,n,r]=s.split("-").map(Number);return Gs(new Date(t,n-1,r),"MMM d, yyyy")}function eDs(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 YOt({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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(GU,{className:"h-5 w-5"}),"Blocked Dates"]}),e.jsx(Jn,{children:"Block a single day or a full date range (vacations, holidays, etc.)"})]}),e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>a(!0),children:[e.jsx(an,{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(xe,{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(xe,{type:"date",value:o,min:i||void 0,onChange:m=>c(m.target.value),className:"w-40",placeholder:"Optional"})]}),e.jsx(xe,{placeholder:"Reason (optional)",value:d,onChange:m=>u(m.target.value),className:"flex-1 min-w-[180px]"}),e.jsx(U,{size:"sm",onClick:h,children:"Add"}),e.jsx(U,{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:eDs(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:[dft(m.start),m.end!==m.start&&` – ${dft(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(er,{className:"h-3.5 w-3.5"})})]},m.ids[0]))})]})]})}function tDs(){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}=WOt(),[p,f]=j.useState("1-on-1 Coaching Session"),[x,y]=j.useState(45),v=j.useMemo(()=>t.filter(N=>N.is_coaching_only),[t]);if(a)return e.jsx(we,{children:e.jsxs(Ie,{className:"p-6 flex items-center gap-2 text-muted-foreground",children:[e.jsx(Et,{className:"h-4 w-4 animate-spin"})," Loading your calendar…"]})});if(!s)return e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(ch,{className:"h-5 w-5"})," Coaching calendar"]}),e.jsx(Jn,{children:"Set up your scheduler once, then open availability for the members assigned to you."})]}),e.jsx(Ie,{children:e.jsxs(U,{onClick:()=>i.mutate(),disabled:i.isPending,children:[i.isPending&&e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Set up my calendar"]})})]});const b=()=>{p.trim()&&(o.mutate({name:p.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}),f("1-on-1 Coaching Session"),y(45))};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Wr,{className:"h-5 w-5"})," Coaching session types"]}),e.jsx(Jn,{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(N=>e.jsxs("div",{className:"flex flex-wrap items-center gap-3 rounded-lg border p-3",children:[e.jsx(xe,{className:"h-9 max-w-[240px]",defaultValue:N.name,onBlur:S=>S.target.value!==N.name&&o.mutate({id:N.id,name:S.target.value})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"number",min:10,max:240,step:5,className:"h-9 w-20",defaultValue:N.duration_minutes,onBlur:S=>o.mutate({id:N.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(wn,{checked:N.is_active,onCheckedChange:S=>o.mutate({id:N.id,is_active:S})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:N.is_active?"Bookable":"Paused"})]}),e.jsx(Be,{variant:"secondary",children:"Coaching only"}),e.jsx(U,{variant:"ghost",size:"sm",className:"ml-auto h-8 w-8 p-0",onClick:async()=>{await Yi({title:"Delete session type?",description:`"${N.name}" will no longer be bookable.`,confirmText:"Delete",destructive:!0})&&c.mutate(N.id)},children:e.jsx(In,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},N.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(te,{className:"text-xs",children:"New session type"}),e.jsx(xe,{value:p,onChange:N=>f(N.target.value),className:"h-9"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Minutes"}),e.jsx(xe,{type:"number",min:10,max:240,step:5,className:"h-9 w-24",value:x,onChange:N=>y(parseInt(N.target.value)||30)})]}),e.jsxs(U,{onClick:b,disabled:o.isPending,children:[e.jsx(an,{className:"h-4 w-4 mr-1"})," Add"]})]})]})]}),e.jsx(KOt,{slots:n,onSave:N=>d.mutate(N),onDelete:N=>u.mutate(N)}),e.jsx(YOt,{blockedDates:r,onAdd:N=>h.mutate(N),onRemove:N=>m.mutate(N)}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"Scheduling rules"}),e.jsx(Jn,{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(te,{className:"text-xs",children:"Buffer between sessions (min)"}),e.jsx(xe,{type:"number",min:0,max:120,step:5,className:"h-9",defaultValue:s.buffer_minutes,onBlur:N=>l.mutate({buffer_minutes:parseInt(N.target.value)||0})})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Minimum notice (hours)"}),e.jsx(xe,{type:"number",min:0,max:168,className:"h-9",defaultValue:s.min_notice_hours,onBlur:N=>l.mutate({min_notice_hours:parseInt(N.target.value)||0})})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Bookable up to (days out)"}),e.jsx(xe,{type:"number",min:1,max:365,className:"h-9",defaultValue:s.max_advance_days,onBlur:N=>l.mutate({max_advance_days:parseInt(N.target.value)||30})})]})]})]})]})}async function XK(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 ZOt(s=!0,t="coach"){const n=Qt(),r=ct({queryKey:["google-calendar-connection",t],enabled:s,queryFn:async()=>await XK(t,{action:"status"})}),a=()=>n.invalidateQueries({queryKey:["google-calendar-connection",t]}),i=yt({mutationFn:async()=>{const d=await XK(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=yt({mutationFn:()=>XK(t,{action:"disconnect"}),onSuccess:a}),o=yt({mutationFn:d=>XK(t,{action:"settings",...d}),onSuccess:a}),c=yt({mutationFn:()=>XK(t,{action:"refresh_calendars"}),onSuccess:a});return{status:r,connect:i,disconnect:l,updateSettings:o,refreshCalendars:c}}function XOt({scope:s="coach"}){const{status:t,connect:n,disconnect:r,updateSettings:a,refreshCalendars:i}=ZOt(!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(we,{children:[e.jsx(Tt,{children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(cv,{className:"h-5 w-5"})," Google Calendar"]}),e.jsx(Jn,{children:l?"Hide times you're already booked on Google, and push every new booking straight onto your calendar.":"Hide times you're already booked on Google, and push new coaching sessions straight onto your calendar."})]}),(o==null?void 0:o.connected)&&e.jsxs(Be,{className:"bg-emerald-600 hover:bg-emerald-600 shrink-0",children:[e.jsx(zr,{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(Et,{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(Vo,{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(Vo,{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(U,{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(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(cv,{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(te,{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(wn,{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(te,{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(wn,{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(te,{className:"text-xs",children:"Calendar to use"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ns,{value:o.selected_calendar_id||"primary",onValueChange:d=>a.mutate({calendar_id:d},{onError:u=>re.error(u.message)}),children:[e.jsx(ws,{className:"h-9",children:e.jsx(ks,{placeholder:"Primary calendar"})}),e.jsxs(js,{children:[e.jsx(et,{value:"primary",children:"Primary calendar"}),o.calendars.filter(d=>!d.primary).map(d=>e.jsx(et,{value:d.id,children:d.summary||d.id},d.id))]})]}),e.jsx(U,{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(no,{className:`h-4 w-4 ${i.isPending?"animate-spin":""}`})})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[e.jsxs(U,{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(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(no,{className:"h-4 w-4 mr-2"}),"Reconnect"]}),e.jsxs(U,{variant:"ghost",size:"sm",className:"text-destructive",disabled:r.isPending,onClick:async()=>{await Yi({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(jq,{className:"h-4 w-4 mr-2"})," Disconnect"]})]})]})]})]})}function sDs(){const s=Wn(),{data:t,isLoading:n}=nre(),r=Qt(),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,p]=j.useState(""),[f,x]=j.useState(!1),[y,v]=j.useState([]),[b,N]=j.useState(""),[S,A]=j.useState(2),[T,L]=j.useState(!1);j.useEffect(()=>{if(!t)return;const $=t;i($.slug||""),o($.headline||""),d($.bio||""),h($.photo_url||""),p($.intro_video_url||""),x(!!$.accepting_clients),v($.specialties||[]),A($.default_sessions_per_month??2)},[t]);const M=async()=>{if(!t)return;L(!0);const{error:$}=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:f,specialties:y,default_sessions_per_month:S}).eq("id",t.id);if(L(!1),$)return re.error($.message);re.success("Profile saved"),r.invalidateQueries({queryKey:["my-coach-profile"]})},I=()=>{const $=b.trim();if($){if(y.includes($))return N("");v([...y,$]),N("")}};if(n)return e.jsx(qs,{title:"Coach Settings",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(qs,{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 R=t,z=R.slug?`${window.location.origin}/coaches/${R.slug}`:null;return e.jsx(qs,{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(U,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(Aa,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Coach Profile"})]}),e.jsxs("div",{className:"flex gap-2",children:[z&&e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>window.open(z,"_blank"),children:[e.jsx(Sr,{className:"h-4 w-4 mr-1"})," View public"]}),e.jsxs(U,{onClick:M,disabled:T,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[e.jsx(Ho,{className:"h-4 w-4 mr-1"})," ",T?"Saving…":"Save"]})]})]}),R.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(we,{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(wn,{checked:f,onCheckedChange:x})]}),e.jsxs("div",{children:[e.jsx(te,{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(xe,{value:a,onChange:$=>i($.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"")),placeholder:"your-name"})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Headline"}),e.jsx(xe,{value:l,onChange:$=>o($.target.value),placeholder:"e.g. Helping new agents close their first 10 deals",maxLength:140})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Bio"}),e.jsx(Fs,{rows:6,value:c,onChange:$=>d($.target.value),placeholder:"Tell agents who you are, what you've done, how you coach…"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Profile photo"}),e.jsx(lft,{kind:"photo",value:u,onChange:h})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Intro video"}),e.jsx(lft,{kind:"video",value:m,onChange:p})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:y.map($=>e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[$,e.jsx("button",{onClick:()=>v(y.filter(H=>H!==$)),children:e.jsx(er,{className:"h-3 w-3"})})]},$))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:b,onChange:$=>N($.target.value),placeholder:"Add a specialty…",onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),I())}}),e.jsx(U,{type:"button",variant:"outline",onClick:I,children:e.jsx(an,{className:"h-4 w-4"})})]})]})]})}),e.jsx(we,{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(te,{children:"Sessions each agent can book per month"}),e.jsx(xe,{type:"number",min:1,max:31,value:S,onChange:$=>A(Math.max(1,parseInt($.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(U,{variant:"outline",onClick:()=>s("/mission-control/scheduler"),children:"Open full Scheduler"})]})]})}),e.jsx(XOt,{}),e.jsx(tDs,{}),e.jsx(we,{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(U,{variant:"outline",onClick:()=>s("/coaching/billing"),children:"Go to Billing"})]})})}),e.jsx(nDs,{coachId:R.id})]})})}function nDs({coachId:s}){const[t,n]=j.useState("");Qt();const{data:r=[],refetch:a}=ct({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 Yi("Revoke this invite?")&&(await q.from("coaching_invites").delete().eq("id",c),a())};return e.jsx(we,{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(Rc,{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(xe,{placeholder:"agent@email.com",value:t,onChange:c=>n(c.target.value),onKeyDown:c=>c.key==="Enter"&&i()}),e.jsxs(U,{onClick:i,children:[e.jsx(an,{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(U,{variant:"ghost",size:"icon",onClick:()=>l(c.token),children:e.jsx(Pa,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>o(c.id),children:e.jsx(In,{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 rDs="google_calendar";function aDs(){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:rDs,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(Et,{className:"h-6 w-6 animate-spin mx-auto text-[#406E71]"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s})]})})}const Toe=[{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 iDs(){const s=Wn(),t=Qt(),{data:n,isLoading:r}=nre(),[a,i]=j.useState("pending"),[l,o]=j.useState(""),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,p]=j.useState(""),[f,x]=j.useState(!1),[y,v]=j.useState(""),{data:b=[],isLoading:N}=ct({queryKey:["coaching-waitlist",n==null?void 0:n.id],enabled:!!(n!=null&&n.id),queryFn:async()=>{const{data:R,error:z}=await q.from("coaching_waitlist").select("*").eq("coach_id",n.id).order("created_at",{ascending:!1});if(z)throw z;return R||[]}}),S=j.useMemo(()=>b.filter(R=>{if(a!=="all"&&R.status!==a)return!1;if(l){const z=l.toLowerCase();return(R.name||"").toLowerCase().includes(z)||(R.email||"").toLowerCase().includes(z)||(R.brokerage||"").toLowerCase().includes(z)}return!0}),[b,a,l]),A=j.useMemo(()=>{const R={all:b.length};for(const z of Toe)R[z.value]=0;for(const z of b)R[z.status]=(R[z.status]||0)+1;return R},[b]),T=async(R,z)=>{const{error:$}=await q.from("coaching_waitlist").update(z).eq("id",R);if($)return re.error($.message);t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),(c==null?void 0:c.id)===R&&d(H=>({...H,...z}))},L=async R=>{if(!await Yi("Remove this person from the waitlist?"))return;const{error:z}=await q.from("coaching_waitlist").delete().eq("id",R);if(z)return re.error(z.message);re.success("Removed"),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),d(null)},M=async()=>{if(!c)return;const{data:R,error:z}=await q.functions.invoke("coaching-waitlist-invite",{body:{waitlistId:c.id,message:m}});if(z||R!=null&&R.error)return re.error((R==null?void 0:R.error)||(z==null?void 0:z.message)||"Could not send invite");re.success(`Invite sent to ${c.name}`),h(!1),p(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})},I=async()=>{if(!n)return;const{data:R,error:z}=await q.functions.invoke("coaching-waitlist-invite",{body:{coachId:n.id,notifyAll:!0,message:y}});if(z||R!=null&&R.error)return re.error((R==null?void 0:R.error)||(z==null?void 0:z.message)||"Could not notify");re.success(`Notified ${(R==null?void 0:R.count)||0} agents`),x(!1),v(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})};return r?e.jsx(qs,{title:"Waitlist",children:e.jsx("div",{className:"p-8",children:"Loading…"})}):n?e.jsxs(qs,{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(U,{variant:"ghost",size:"sm",className:"mb-2 -ml-2",onClick:()=>s("/coaching"),children:[e.jsx(Aa,{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(iy,{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(U,{variant:"outline",onClick:()=>x(!0),disabled:!A.pending,title:A.pending?"":"No pending applicants",children:[e.jsx(rq,{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,")"]}),Toe.map(R=>e.jsxs("button",{onClick:()=>i(R.value),className:`px-3 py-1.5 rounded-full text-sm border ${a===R.value?"bg-[#406E71] text-white border-[#406E71]":"bg-white hover:bg-muted"}`,children:[R.label," (",A[R.value]||0,")"]},R.value))]}),e.jsx(xe,{placeholder:"Search by name, email, brokerage…",value:l,onChange:R=>o(R.target.value),className:"max-w-md"}),N?e.jsx("div",{className:"text-muted-foreground",children:"Loading…"}):S.length===0?e.jsx(we,{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(R=>{const z=Toe.find($=>$.value===R.status);return e.jsx(we,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>d(R),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:R.name}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:R.email}),R.brokerage&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:R.brokerage})]}),e.jsx(Be,{className:(z==null?void 0:z.tone)||"",children:(z==null?void 0:z.label)||R.status})]}),e.jsxs("div",{className:"flex items-center justify-between mt-3 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Joined ",Nd(new Date(R.created_at),{addSuffix:!0})]}),R.preferred_package&&e.jsxs("span",{className:"truncate ml-2",children:["→ ",R.preferred_package]})]})]})},R.id)})})]}),e.jsx(zs,{open:!!c,onOpenChange:R=>!R&&d(null),children:e.jsx(Ds,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:c&&e.jsxs(e.Fragment,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:c.name}),e.jsxs(Pr,{children:["Joined ",Nd(new Date(c.created_at),{addSuffix:!0})]})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsx(QK,{label:"Email",value:c.email}),e.jsx(QK,{label:"Phone",value:c.phone}),e.jsx(QK,{label:"Brokerage",value:c.brokerage}),e.jsx(QK,{label:"Years",value:c.years_in_business}),e.jsx(QK,{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 ",Nd(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(Ns,{value:c.status,onValueChange:R=>T(c.id,{status:R}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:Toe.map(R=>e.jsx(et,{value:R.value,children:R.label},R.value))})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Private notes"}),e.jsx(Fs,{rows:3,defaultValue:c.coach_notes||"",onBlur:R=>{R.target.value!==(c.coach_notes||"")&&T(c.id,{coach_notes:R.target.value})}})]})]}),e.jsxs(Mr,{className:"flex-wrap gap-2",children:[e.jsxs(U,{variant:"outline",className:"text-destructive",onClick:()=>L(c.id),children:[e.jsx(In,{className:"h-4 w-4 mr-1"})," Remove"]}),e.jsx(U,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`mailto:${c.email}`,children:[e.jsx(ln,{className:"h-4 w-4 mr-1"})," Email directly"]})}),e.jsxs(U,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>{p(""),h(!0)},children:[e.jsx($r,{className:"h-4 w-4 mr-1"})," Invite to subscribe"]})]})]})})}),e.jsx(zs,{open:u,onOpenChange:h,children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(Fs,{rows:4,placeholder:"Hey! A spot just opened up and I'd love to work with you…",value:m,onChange:R=>p(R.target.value)})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsxs(U,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:M,children:[e.jsx($r,{className:"h-4 w-4 mr-1"})," Send invite"]})]})]})}),e.jsx(zs,{open:f,onOpenChange:x,children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(Fs,{rows:4,placeholder:"Good news — I just opened up new coaching spots…",value:y,onChange:R=>v(R.target.value)}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsxs(U,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:I,children:[e.jsx(rq,{className:"h-4 w-4 mr-1"})," Send to ",A.pending||0," agents"]})]})]})})]}):e.jsx(qs,{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 QK({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 oDs(){const{data:s=[],isLoading:t}=ct({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(cn,{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(zr,{className:"h-4 w-4 text-yellow-300"})," Vetted by LevelUp"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Al,{className:"h-4 w-4 text-yellow-300"})," Top-producer experience"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ua,{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(xr,{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(cn,{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(Oa,{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(cn,{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(zr,{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(zr,{className:"h-4 w-4 text-yellow-300"})," Recurring revenue"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(zr,{className:"h-4 w-4 text-yellow-300"})," Certified status"]})]})]}),e.jsxs("div",{className:"mt-8 md:mt-0",children:[e.jsxs(xr,{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(Oa,{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 lDs=kN({name:sl().trim().min(1,"Name required").max(120),email:sl().trim().email("Invalid email").max(255),phone:sl().trim().max(40).optional().or(ux("")),brokerage:sl().trim().max(160).optional().or(ux("")),years_in_business:sl().max(40).optional().or(ux("")),biggest_challenge:sl().trim().max(1e3).optional().or(ux("")),preferred_package:sl().max(120).optional().or(ux("")),message:sl().trim().max(1500).optional().or(ux(""))});function cDs({open:s,onOpenChange:t,coachId:n,coachName:r,packages:a=[]}){const{user:i}=vs(),[l,o]=j.useState(!1),[c,d]=j.useState({name:"",email:(i==null?void 0:i.email)||"",phone:"",brokerage:"",years_in_business:"",biggest_challenge:"",preferred_package:"",message:""}),u=(m,p)=>d(f=>({...f,[m]:p})),h=async()=>{var f;const m=lDs.safeParse(c);if(!m.success){re.error(((f=m.error.issues[0])==null?void 0:f.message)||"Please check your entries");return}o(!0);const{error:p}=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),p){re.error(p.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(Ds,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{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(te,{children:"Name *"}),e.jsx(xe,{value:c.name,onChange:m=>u("name",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Email *"}),e.jsx(xe,{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(te,{children:"Phone"}),e.jsx(xe,{value:c.phone,onChange:m=>u("phone",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Brokerage"}),e.jsx(xe,{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(te,{children:"Years in business"}),e.jsxs(Ns,{value:c.years_in_business,onValueChange:m=>u("years_in_business",m),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select…"})}),e.jsxs(js,{children:[e.jsx(et,{value:"< 1 year",children:"Less than 1 year"}),e.jsx(et,{value:"1-3 years",children:"1-3 years"}),e.jsx(et,{value:"4-7 years",children:"4-7 years"}),e.jsx(et,{value:"8-15 years",children:"8-15 years"}),e.jsx(et,{value:"15+ years",children:"15+ years"})]})]})]}),a.length>0&&e.jsxs("div",{children:[e.jsx(te,{children:"Preferred package"}),e.jsxs(Ns,{value:c.preferred_package,onValueChange:m=>u("preferred_package",m),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Any"})}),e.jsx(js,{children:a.map(m=>e.jsx(et,{value:m.name,children:m.name},m.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Biggest challenge right now"}),e.jsx(Fs,{rows:2,value:c.biggest_challenge,onChange:m=>u("biggest_challenge",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Anything else?"}),e.jsx(Fs,{rows:2,value:c.message,onChange:m=>u("message",m.target.value)})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),disabled:l,children:"Cancel"}),e.jsx(U,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:h,disabled:l,children:l?"Submitting…":"Join Waitlist"})]})]})})}function dDs(){var x;const{slug:s}=Di(),t=Wn(),{user:n}=vs(),[r,a]=j.useState(null),[i,l]=j.useState(!1),{data:o,isLoading:c}=ct({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:N},{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:N,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,p=u,f=(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(U,{variant:"ghost",size:"sm",className:"text-white/80 hover:text-white hover:bg-white/10 mb-6",onClick:()=>t("/coaches"),children:[e.jsx(Aa,{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(Ea,{className:"h-28 w-28 ring-4 ring-white/20",children:[e.jsx(Ci,{src:p.photo_url||(h==null?void 0:h.avatar_url)}),e.jsx(Ta,{className:"text-3xl bg-white/20",children:((h==null?void 0:h.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[p.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(cn,{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"}),p.headline&&e.jsx("p",{className:"text-white/80 text-lg mt-2",children:p.headline}),((x=p.specialties)==null?void 0:x.length)>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-4",children:p.specialties.map(y=>e.jsx(Be,{className:"bg-white/15 text-white border-white/20",children:y},y))})]})]})]})}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-12 grid grid-cols-1 md:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[p.intro_video_url&&e.jsx("div",{className:"aspect-video rounded-xl overflow-hidden bg-black",children:e.jsx("video",{src:p.intro_video_url,controls:!0,className:"w-full h-full"})}),p.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:p.bio})]}),e.jsx(BRs,{coachId:p.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(we,{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(we,{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:f(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(U,{variant:"outline",className:"w-full",onClick:()=>l(!0),children:[e.jsx(iy,{className:"h-4 w-4 mr-1"})," Join Waitlist"]})]}):e.jsxs(U,{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(Xr,{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(U,{variant:"ghost",size:"sm",className:"w-full text-muted-foreground",onClick:()=>l(!0),children:[e.jsx(iy,{className:"h-4 w-4 mr-1"})," Join the waitlist instead"]})]})]}),e.jsx(cDs,{open:i,onOpenChange:l,coachId:p.id,coachName:h==null?void 0:h.name,packages:m.map(y=>({id:y.id,name:y.name}))})]})}const uDs=kN({full_name:sl().trim().min(2,"Please enter your full name").max(100),email:sl().trim().email("Enter a valid email").max(255),phone:sl().trim().max(40).optional().or(ux("")),brokerage:sl().trim().max(150).optional().or(ux("")),years_experience:sl().trim().max(40).optional().or(ux("")),specialties:sl().trim().max(500).optional().or(ux("")),why_coach:sl().trim().min(20,"Tell us a bit more — at least 20 characters").max(2e3),results_story:sl().trim().max(2e3).optional().or(ux("")),website_url:sl().trim().max(300).optional().or(ux("")),linkedin_url:sl().trim().max(300).optional().or(ux(""))});function hDs(){const s=Wn(),[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=uDs.safeParse(i);if(!u.success){const p=(m=Object.values(u.error.flatten().fieldErrors)[0])==null?void 0:m[0];return re.error(p||"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(zr,{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(U,{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(xr,{to:"/coaches",className:"inline-flex items-center gap-2 text-white/70 hover:text-white text-sm mb-8",children:[e.jsx(Aa,{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(cn,{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(Bn,{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(rc,{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(Eh,{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(zr,{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(Al,{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(Ua,{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(i5,{label:"Full name *",children:e.jsx(xe,{value:i.full_name,onChange:d=>o("full_name",d.target.value),required:!0,maxLength:100})}),e.jsx(i5,{label:"Email *",children:e.jsx(xe,{type:"email",value:i.email,onChange:d=>o("email",d.target.value),required:!0,maxLength:255})}),e.jsx(i5,{label:"Phone",children:e.jsx(xe,{value:i.phone,onChange:d=>o("phone",d.target.value),maxLength:40})}),e.jsx(i5,{label:"Current brokerage",children:e.jsx(xe,{value:i.brokerage,onChange:d=>o("brokerage",d.target.value),maxLength:150})}),e.jsx(i5,{label:"Years in real estate",children:e.jsx(xe,{value:i.years_experience,onChange:d=>o("years_experience",d.target.value),placeholder:"e.g. 8",maxLength:40})}),e.jsx(i5,{label:"Coaching specialties",children:e.jsx(xe,{value:i.specialties,onChange:d=>o("specialties",d.target.value),placeholder:"Lead gen, listings, luxury, teams…",maxLength:500})}),e.jsx(i5,{label:"Website",children:e.jsx(xe,{value:i.website_url,onChange:d=>o("website_url",d.target.value),placeholder:"https://",maxLength:300})}),e.jsx(i5,{label:"LinkedIn",children:e.jsx(xe,{value:i.linkedin_url,onChange:d=>o("linkedin_url",d.target.value),placeholder:"https://linkedin.com/in/",maxLength:300})})]}),e.jsx(i5,{label:"Why do you want to coach with LevelUp? *",children:e.jsx(Fs,{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(i5,{label:"Tell us about results you've created — for yourself or other agents.",children:e.jsx(Fs,{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(U,{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 i5({label:s,children:t}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-sm font-semibold text-[#1c3447]",children:s}),t]})}const jQe="/assets/testimonial-avatar-1-BsCQFauB.jpg",NQe="/assets/testimonial-avatar-2-B6VPVc2t.jpg",kQe="/assets/testimonial-avatar-3-GuEFwYUE.jpg",SQe="/assets/testimonial-avatar-4-98iKMtkB.jpg",CQe="/assets/testimonial-avatar-5-ZsZfyxMX.jpg",mDs=[jQe,NQe,kQe,SQe,CQe],pDs=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:sre.url},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:DMe.url},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:OMe.url},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:FMe.url},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:zMe.url},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:BMe.url}];function fDs({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(cn,{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 gDs=kN({name:sl().trim().min(2,"Name must be at least 2 characters").max(100),email:sl().trim().email("Please enter a valid email address").max(255),phone:sl().trim().min(10,"Please enter a valid phone number").max(20).optional().or(ux("")),brokerage:sl().trim().max(200).optional().or(ux(""))}),xDs=[{icon:$h,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:$c,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:pa,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:vu,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:Ur,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Ro,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],yDs=[{category:"Marketing Studio",icon:Th,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:Gu,items:["Custom lead websites","Open House Guest Book","RSVP pages","Resource landing pages","Listing Revival™","FSBO Breakthrough","Attract system"]},{category:"CRM & Deals",icon:cy,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:Lg,items:["AI Staging Studio","Video library & sharing","Screen recording","Virtual backgrounds","AI blog writer","YouTube → Blog","Ask AI assistant"]},{category:"Growth & Coaching",icon:Kh,items:["Academy courses","Live weekly coaching","Coaching programs","1:1 coaching booking","Private community","Live events & workshops"]},{category:"Brokerage Tools",icon:_i,items:["Manager dashboard","Team analytics","Agent onboarding","Office form libraries","Listing Exchange","Brand kits","Recruiting pipeline"]}],vDs=[{icon:Bn,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:cn,title:"Smart TouchPlans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:ba,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:lg,title:"Birthday Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:ni,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:Cl,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:ko,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:Af,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],bDs=[{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."}],Moe="bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]",_Ds=()=>{const s=Wn(),[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=gDs.safeParse(r);if(!u.success){const p={};u.error.issues.forEach(f=>{f.path[0]&&(p[f.path[0]]=f.message)}),l(p);return}n(!0);try{const p=typeof window<"u"&&localStorage.getItem("levelup_referral_code")||void 0,{data:f,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:p}});if(x){console.error("Trial signup error:",x),re.error(x.message||"Something went wrong. Please try again.");return}if(f!=null&&f.error){re.error(f.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(p){console.error("Trial signup error:",p),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:kCe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx(U,{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(U,{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(cn,{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(zr,{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(zr,{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:mDs.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(Ua,{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(Im,{className:"h-4 w-4 text-white/60"})," Cancel anytime"]}),e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Af,{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(we,{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(pv,{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(te,{htmlFor:"name",children:"Full Name *"}),e.jsx(xe,{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(te,{htmlFor:"email",children:"Email Address *"}),e.jsx(xe,{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(te,{htmlFor:"phone",children:"Phone Number"}),e.jsx(xe,{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(te,{htmlFor:"brokerage",children:"Brokerage Name"}),e.jsx(xe,{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(U,{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(Et,{className:"mr-2 h-5 w-5 animate-spin"}),"Creating Your Account..."]}):e.jsxs(e.Fragment,{children:["Start My Free Trial",e.jsx(Oa,{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 ${Moe}`})}),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:pDs.map(d=>e.jsx(fDs,{slot:d},d.key))}),e.jsx("div",{className:"text-center mt-12",children:e.jsxs(U,{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(Oa,{className:"ml-2 w-5 h-5"})]})})]})]}),e.jsx("section",{id:"features",className:"py-20 bg-muted/30",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("span",{className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-semibold mb-5",children:[e.jsx(L4,{className:"w-4 h-4"}),"40+ tools & counting"]}),e.jsx("h2",{className:"text-3xl md:text-4xl mb-6 font-sans font-bold",children:"What's inside our members only portal?"}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Everything you need to grow your business, all in one place."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:xDs.map((d,u)=>e.jsxs(we,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(Tt,{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(It,{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 ${Moe}`})}),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:yDs.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(Xr,{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(cn,{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 ${Moe}`})}),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(cn,{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:vDs.map((d,u)=>e.jsxs(we,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(Tt,{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(It,{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:bDs.map((d,u)=>e.jsx(we,{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(Ua,{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(Im,{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(Af,{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(Bn,{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(we,{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 ${Moe}`})}),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(U,{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(Oa,{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:UV,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."})]})})})]})]})},wDs=()=>{const s=Wn();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:kCe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsx(U,{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(we,{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(zr,{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(Wg,{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(ln,{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(U,{onClick:()=>s("/auth"),className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["Go to Sign In",e.jsx(Oa,{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:UV,alt:"LevelUp",className:"h-8"}),e.jsxs("p",{className:"text-sm text-white/40",children:["© ",new Date().getFullYear()," LevelUp Consulting Group. All rights reserved."]})]})})})]})]})},jDs="https://us06web.zoom.us/meeting/register/7Ybq3ZIkRn2_RLkkv_uY8A",Poe="ld-open-house-invite-dismissed";function QOt({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(`${Poe}-${s}`))return;let o=null;const c=d=>{d.clientY<=0&&!localStorage.getItem(`${Poe}-${s}`)&&a(!0)};return o=setTimeout(()=>{localStorage.getItem(`${Poe}-${s}`)||a(!0)},n),document.addEventListener("mouseleave",c),()=>{o&&clearTimeout(o),document.removeEventListener("mouseleave",c)}},[s,n]);const i=()=>{a(!1),localStorage.setItem(`${Poe}-${s}`,"1")};return e.jsx(zs,{open:r,onOpenChange:l=>!l&&i(),children:e.jsx(Ds,{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(er,{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(Wr,{className:"h-6 w-6 ld-gold-text"})}),e.jsxs(Vs,{children:[e.jsx($s,{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(pa,{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(U,{asChild:!0,size:"lg",className:"w-full bg-accent text-accent-foreground hover:bg-accent/90 font-bold",children:e.jsxs("a",{href:jDs,target:"_blank",rel:"noreferrer",className:"gap-2",children:["Register for the Open House",e.jsx(Sr,{className:"h-4 w-4"})]})}),e.jsx(U,{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 JOt=Date.UTC(2026,8,12,3,59,59),$Oe="Friday, September 11 at 11:59 PM ET",VOe=300,Loe=39*12,NDs=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:sre.url},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:DMe.url},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:OMe.url},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:FMe.url},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:zMe.url},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:BMe.url}],kDs=[{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."}],SDs="https://www.google.com/search?q=levelup+consulting+group#lrd=0x8842f50045c4bd33:0xc9b99b5330a91b3f,1,,,,",eFt=[{icon:Bn,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:$F,title:"Full CRM & Contact Hub",desc:"Contacts, tags, smart follow-ups, lead ponds and team assignments — your database finally organized.",value:600},{icon:a1,title:"Deal Pipeline",desc:"Track every transaction from offer to closing with tasks, forms and commission math built in.",value:480},{icon:_x,title:"Staging Studio",desc:"AI virtual staging with MLS-ready before/after photos — no photographer or stager needed.",value:1200},{icon:$c,title:"Marketing & Social Studio",desc:"300+ branded templates, social posts, postcards and the weekly Reels engine.",value:720},{icon:fl,title:"Lead Sites",desc:"SEO-optimized neighborhood and listing websites that rank on Google and capture leads 24/7.",value:960},{icon:Kh,title:"Academy Training",desc:"On-demand video training on lead gen, marketing and tech — live weekly sessions too.",value:588},{icon:Iw,title:"Forms & E-Signature",desc:"Upload any PDF, map fields, send for signature — done from one place.",value:300},{icon:Wr,title:"Weekly Reels & Video Tools",desc:"Personalized Instagram scripts delivered every Monday, plus screen recording and virtual backgrounds.",value:468},{icon:Ki,title:"Reviews Engine",desc:"Collect Google and video reviews with a single link — your reputation on autopilot.",value:240},{icon:cn,title:"ChatGPT App + 30 AI Tools",desc:"Your entire business controllable from ChatGPT — create contacts, open houses, marketing assets and more.",value:500},{icon:pa,title:"My Calendar & Booking",desc:"Agent-first calendar with time zones, Google Calendar sync and self-serve booking links.",value:144}],uft=eFt.reduce((s,t)=>s+t.value,0),CDs=[{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 tFt(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 hft({dark:s=!1}){const{d:t,h:n,m:r,sec:a,expired:i}=tFt(JOt);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 mft(){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(Ua,{className:"h-4 w-4 fill-accent text-accent"},t))})}function ADs({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(cn,{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 EDs(){const{expired:s}=tFt(JOt),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState(0),d=j.useMemo(()=>[jQe,NQe,kQe,SQe,CQe],[]),u=Loe-VOe,h=async()=>{if(!r.trim()||!r.includes("@")){re.error("Enter your email to claim the offer.");return}l(!0);try{const{data:m,error:p}=await q.functions.invoke("create-checkout",{body:{tier:"individual_annual",email:r.trim(),name:t.trim()||void 0,skipTrial:!0}});if(p){const f=p instanceof Rne?await p.context.text():p.message;throw new Error(f||"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 ${$Oe}.`}),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:["$",Loe]})]})]}),e.jsx(U,{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:UV,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,p)=>e.jsx("img",{src:m,alt:"",className:"h-7 w-7 rounded-full border-2 border-white/20 object-cover"},p))}),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 ",$Oe]})]}),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,p)=>e.jsx(Ua,{className:"h-4 w-4 fill-accent text-accent"},p))}),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 ($",Loe,"/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(hft,{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(U,{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(Oa,{className:"ml-2 h-4 w-4"})]})})]}):e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx(xe,{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(xe,{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(U,{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(Et,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:["Lock in $300/yr ",e.jsx(Oa,{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(Ql,{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 $",uft.toLocaleString(),"/year at market rates."]})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-5",children:[eFt.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:["$",uft.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:NDs.map(m=>e.jsx(ADs,{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(mft,{}),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:kDs.map(m=>e.jsxs("blockquote",{className:"bg-card border rounded-2xl p-5 flex flex-col gap-3",children:[e.jsx(mft,{}),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:SDs,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(er,{className:"h-4 w-4 mt-0.5 shrink-0"})," $",Loe," per year"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(er,{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(Xr,{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:["$",VOe]}),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(Xr,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," $",VOe," per year — save $",u," vs monthly"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(eq,{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(Xr,{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(Im,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," Manage or cancel anytime from your profile"]})]}),e.jsx(U,{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:CDs.map((m,p)=>e.jsxs("div",{className:"bg-card border rounded-2xl overflow-hidden",children:[e.jsxs("button",{onClick:()=>c(o===p?null:p),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===p?"rotate-45":""} text-muted-foreground text-xl leading-none`,children:"+"})]}),o===p&&e.jsx("p",{className:"px-6 pb-5 text-sm text-muted-foreground leading-relaxed",children:m.a})]},p))})]})}),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(hft,{dark:!0})}),e.jsx(U,{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(Oa,{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(Ql,{className:"h-3 w-3"})," Secure Stripe checkout · Ends ",$Oe]}),e.jsxs("p",{className:"text-white/50 text-sm mt-10",children:["© ",new Date().getFullYear()," LevelUp Consulting Group"]})]})]}),e.jsx(QOt,{pageKey:"individual-labor-day-2026",headline:"Not ready to join the LevelUp family yet?"})]})}const sFt=Date.UTC(2026,8,12,3,59,59),HOe="Friday, September 11 at 11:59 PM ET",bZ=399,O5e=499,pft=(O5e-bZ)*12,TDs=[{key:"dashboard",label:"Agent Command Center",caption:"Every agent's day — smart queue, calendar and pipeline in one view.",src:sre.url},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history for every agent.",src:DMe.url},{key:"pipeline",label:"Deal Pipeline",caption:"Every transaction with tasks, forms and commission tracking built in.",src:OMe.url},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:FMe.url},{key:"coaching",label:"Coaching",caption:"Live coaching sessions your agents book themselves.",src:zMe.url},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded.",src:BMe.url}],MDs=[{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."}],PDs="https://www.google.com/search?q=levelup+consulting+group#lrd=0x8842f50045c4bd33:0xc9b99b5330a91b3f,1,,,,",LDs=[{icon:hv,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:$F,title:"Full CRM & Contact Hub",desc:"Contacts, tags, smart follow-ups, lead ponds and team assignments — every agent's database finally organized."},{icon:a1,title:"Deal Pipeline",desc:"Transactions from offer to closing with tasks, forms and commission math built in."},{icon:_x,title:"Staging Studio",desc:"AI virtual staging with MLS-ready before/after photos for every listing."},{icon:$c,title:"Marketing & Social Studio",desc:"300+ branded templates, social posts, postcards and the weekly Reels engine."},{icon:fl,title:"Lead Sites",desc:"SEO-optimized websites that rank on Google and capture leads 24/7."},{icon:Kh,title:"Academy Training",desc:"On-demand video training on lead gen, marketing and tech."},{icon:Iw,title:"Forms & E-Signature",desc:"Upload any PDF, map fields, send for signature — done from one place."},{icon:Wr,title:"Weekly Reels & Video Tools",desc:"Personalized Instagram scripts every Monday, plus screen recording and virtual backgrounds."}],IDs=[{icon:_i,title:"Your Own Brokerage Hub",desc:"Brand profiles, announcements and resources pushed to every agent from one place."},{icon:Iw,title:"Brokerage Form Library",desc:"Publish your official forms office-wide — agents use them read-only or copy to customize."},{icon:zl,title:"Recruiting Pipeline",desc:"Customizable recruiting stages to attract and track your next agents."},{icon:Th,title:"Office-Wide Communication",desc:"Broadcasts, brokerage content and resource libraries your agents actually use."}],RDs=[{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 nFt(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 fft({dark:s=!1}){const{d:t,h:n,m:r,sec:a,expired:i}=nFt(sFt);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 gft(){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(Ua,{className:"h-4 w-4 fill-accent text-accent"},t))})}function DDs({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(cn,{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 ODs(){const{expired:s}=nFt(sFt),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState(0),d=j.useMemo(()=>[jQe,NQe,kQe,SQe,CQe],[]),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 p=m instanceof Rne?await m.context.text():m.message;throw new Error(p||"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 ${HOe}.`}),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:["$",bZ,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:["$",O5e]})]})]}),e.jsx(U,{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:UV,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 ",HOe]})]}),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(Ua,{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(fft,{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(U,{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(Oa,{className:"ml-2 h-4 w-4"})]})})]}):e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx(xe,{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(xe,{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(U,{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(Et,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:["Partner at $399/mo ",e.jsx(Oa,{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(Ql,{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:LDs.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:IDs.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:TDs.map(h=>e.jsx(DDs,{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(gft,{}),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:MDs.map(h=>e.jsxs("blockquote",{className:"bg-card border rounded-2xl p-5 flex flex-col gap-3",children:[e.jsx(gft,{}),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:PDs,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 $",bZ,"."]})]}),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:["$",O5e]}),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(er,{className:"h-4 w-4 mt-0.5 shrink-0"})," $",(O5e*12).toLocaleString()," per year"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(er,{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(Xr,{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 $",pft.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:["$",bZ]}),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(Xr,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," $",(bZ*12).toLocaleString()," per year — save $",pft.toLocaleString()," vs standard"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(eq,{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(Xr,{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(Im,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," Manage or cancel anytime from your profile"]})]}),e.jsx(U,{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:RDs.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(fft,{dark:!0})}),e.jsx(U,{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(Oa,{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(Ql,{className:"h-3 w-3"})," Secure Stripe checkout · Ends ",HOe]}),e.jsxs("p",{className:"text-white/50 text-sm mt-10",children:["© ",new Date().getFullYear()," LevelUp Consulting Group"]})]})]}),e.jsx(QOt,{pageKey:"brokerage-labor-day-2026",headline:"Not ready to partner with LevelUp yet?"})]})}const FDs=["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"],zDs=["Everything in Individual, plus:","Unlimited agent seats","Brokerage admin dashboard","Team performance analytics","Agent onboarding tools","Priority support"],BDs=()=>{const{user:s,loading:t}=vs(),n=Wn(),[r]=fc(),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)}`)},p=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)}},f=(x,y,v,b,N,S,A)=>e.jsxs(we,{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(Be,{className:"absolute -top-3 left-1/2 -translate-x-1/2 bg-primary text-primary-foreground",children:"Recommended for you"}),e.jsxs(Ie,{className:"p-6 text-center space-y-4",children:[e.jsx("div",{className:`mx-auto h-12 w-12 rounded-full flex items-center justify-center ${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:N.map(T=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx(Xr,{className:`h-4 w-4 mt-0.5 shrink-0 ${A?"text-primary":"text-amber-600"}`}),e.jsx("span",{children:T})]},T))}),e.jsx(U,{className:"w-full",variant:A?"default":"outline",disabled:l||t,onClick:()=>p(x),children:l&&c===x?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Opening secure checkout…"]}):s?e.jsxs(e.Fragment,{children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Upgrade to ",y]}):e.jsxs(e.Fragment,{children:[e.jsx(EM,{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:xQe,alt:"LevelUp",className:"h-10 mx-auto mb-8"}),e.jsx(Be,{variant:"outline",className:"mb-4 border-primary/40 text-primary",children:"Upgrade your membership"}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-bold mb-3 text-[#2a4c64]",children:"Keep your momentum going"}),e.jsx("p",{className:"text-muted-foreground text-lg max-w-2xl mx-auto",children:s?"Choose your plan below — payment connects to your existing account and everything you set up stays right where you left it.":"Whether you're on a free trial or it just ended, sign in with your existing LevelUp account, choose your plan, and your payment connects right to it — nothing gets lost or duplicated."})]}),e.jsxs("div",{className:"max-w-md mx-auto mb-8",children:[e.jsx(te,{htmlFor:"upgrade-coupon",className:"text-sm font-medium",children:"Have a discount code?"}),e.jsx(xe,{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:[f("individual_agent","Individual Agent","$39","Perfect for solo agents ready to level up",FDs,e.jsx(Bn,{className:"h-6 w-6 text-primary"}),!0),f("brokerage_over_25","Brokerage","$499","For teams and brokerages",zDs,e.jsx(_i,{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(ba,{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(ln,{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."})]})})},UDs=kN({viewerName:sl().min(1,"Name is required").max(100,"Name must be less than 100 characters"),viewerEmail:sl().email("Please enter a valid email").max(255,"Email must be less than 255 characters"),viewerPhone:sl().max(20,"Phone must be less than 20 characters").optional(),message:sl().min(1,"Message is required").max(1e3,"Message must be less than 1000 characters")});function qDs({shareToken:s,agentName:t,hasContact:n}){const[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(null),d=eMe({resolver:tMe(UDs),defaultValues:{viewerName:"",viewerEmail:"",viewerPhone:"",message:""}}),u=async h=>{a(!0),c(null);try{const{data:m,error:p}=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(p)throw new Error(p.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(we,{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(zr,{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(we,{children:[e.jsxs(Tt,{className:"pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(vu,{className:"h-5 w-5 text-primary"}),e.jsx(It,{className:"text-lg",children:"Reply to this video"})]}),e.jsx(Jn,{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(aMe,{...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(hf,{control:d.control,name:"viewerName",render:({field:h})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"Your Name *"}),e.jsx(Ip,{children:e.jsx(xe,{placeholder:"John Smith",...h})}),e.jsx(J1,{})]})}),e.jsx(hf,{control:d.control,name:"viewerEmail",render:({field:h})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"Email *"}),e.jsx(Ip,{children:e.jsx(xe,{type:"email",placeholder:"john@example.com",...h})}),e.jsx(J1,{})]})})]}),!n&&e.jsx(hf,{control:d.control,name:"viewerPhone",render:({field:h})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"Phone (optional)"}),e.jsx(Ip,{children:e.jsx(xe,{type:"tel",placeholder:"(555) 123-4567",...h})}),e.jsx(J1,{})]})}),e.jsx(hf,{control:d.control,name:"message",render:({field:h})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"Message *"}),e.jsx(Ip,{children:e.jsx(Fs,{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(J1,{})]})}),o&&e.jsx("p",{className:"text-sm text-destructive",children:o}),e.jsx(U,{type:"submit",className:"w-full gap-2",disabled:r,children:r?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx($r,{className:"h-4 w-4"}),"Send Message"]})})]})})})]})}const $Ds=()=>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(Ua,{className:"absolute top-[5%] left-[8%] w-6 h-6 text-blue-600/30 fill-blue-600/20"}),e.jsx(Ua,{className:"absolute top-[15%] left-[20%] w-4 h-4 text-blue-600/25 fill-blue-600/15"}),e.jsx(Ua,{className:"absolute top-[8%] left-[28%] w-5 h-5 text-blue-600/30 fill-blue-600/20"}),e.jsx(Ua,{className:"absolute top-[25%] left-[12%] w-4 h-4 text-blue-600/20 fill-blue-600/10"}),e.jsx(Ua,{className:"absolute top-[20%] right-[15%] w-5 h-5 text-red-500/25 fill-red-500/15 animate-pulse"}),e.jsx(NA,{className:"absolute bottom-[20%] right-[10%] w-12 h-12 text-blue-600/15 rotate-12"})]}),VDs=()=>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(cn,{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(Ua,{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(cn,{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(Ua,{className:"absolute bottom-[25%] left-[10%] w-6 h-6 text-blue-500/25 fill-blue-500/15 animate-pulse"}),e.jsx(Ua,{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(NA,{className:"absolute top-[8%] left-[5%] w-10 h-10 text-red-500/20 rotate-12"})]}),HDs=()=>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(Hk,{className:"w-20 h-20 text-pink-400 rotate-12"})}),e.jsx("div",{className:"absolute top-[2%] right-[8%] opacity-15",children:e.jsx(Hk,{className:"w-16 h-16 text-rose-400 -rotate-12"})}),e.jsx("div",{className:"absolute bottom-[15%] left-[8%] opacity-15",children:e.jsx(Hk,{className:"w-14 h-14 text-purple-400 rotate-45"})}),e.jsx("div",{className:"absolute bottom-[20%] right-[5%] opacity-20",children:e.jsx(Hk,{className:"w-16 h-16 text-pink-300 -rotate-6"})}),e.jsx(ko,{className:"absolute top-[15%] left-[30%] w-5 h-5 text-rose-300/40 fill-rose-300/20 animate-pulse"}),e.jsx(ko,{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(ko,{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"})]}),GDs=()=>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(Eh,{className:"absolute top-[8%] left-[12%] w-12 h-12 text-blue-600/15"}),e.jsx(Ua,{className:"absolute top-[15%] left-[22%] w-5 h-5 text-amber-500/25 fill-amber-500/15"}),e.jsx(Eh,{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(Ua,{className:"absolute bottom-[25%] left-[15%] w-6 h-6 text-blue-500/20 fill-blue-500/10 animate-pulse"}),e.jsx(Ua,{className:"absolute top-[20%] right-[22%] w-5 h-5 text-indigo-400/20 fill-indigo-400/10 animate-pulse",style:{animationDelay:"0.5s"}})]}),WDs=()=>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(Hk,{className:"absolute top-[20%] left-[32%] w-7 h-7 text-purple-400/30"}),e.jsx(Hk,{className:"absolute top-[12%] right-[28%] w-6 h-6 text-pink-400/30"}),e.jsx(KU,{className:"absolute top-[18%] left-[52%] w-5 h-5 text-sky-400/35"})]}),KDs=()=>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(CF,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-orange-400/25"}),e.jsx(CF,{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(cn,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-purple-400/35 animate-pulse"}),e.jsx(cn,{className:"absolute bottom-[28%] right-[25%] w-5 h-5 text-orange-400/30 animate-pulse",style:{animationDelay:"0.5s"}})]}),YDs=()=>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(DM,{className:"absolute bottom-[8%] left-[5%] w-20 h-20 text-green-600/18"}),e.jsx(DM,{className:"absolute bottom-[12%] right-[8%] w-16 h-16 text-emerald-600/15"}),e.jsx(DM,{className:"absolute bottom-[10%] left-[28%] w-12 h-12 text-green-500/12"}),e.jsx($w,{className:"absolute top-[5%] left-[15%] w-10 h-10 text-sky-300/30 animate-pulse"}),e.jsx($w,{className:"absolute top-[10%] right-[20%] w-8 h-8 text-blue-300/25 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx($w,{className:"absolute top-[18%] left-[45%] w-6 h-6 text-sky-200/25 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx($w,{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(Ua,{className:"absolute top-[3%] left-[50%] -translate-x-1/2 w-10 h-10 text-amber-400/35 fill-amber-400/25"})]}),ZDs=()=>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(ko,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-red-400/22 fill-red-400/12"}),e.jsx(ko,{className:"absolute top-[20%] right-[25%] w-5 h-5 text-orange-400/22 fill-orange-400/12"})]}),XDs=()=>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(Ua,{className:"absolute top-[5%] left-[15%] w-12 h-12 text-yellow-400/35 fill-yellow-400/25 animate-pulse"}),e.jsx(Ua,{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(Ua,{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(Ua,{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(cn,{className:"absolute top-[3%] left-[50%] w-10 h-10 text-yellow-400/40"}),e.jsx(Wg,{className:"absolute bottom-[18%] left-[10%] w-12 h-12 text-purple-400/18 rotate-12"}),e.jsx(Wg,{className:"absolute bottom-[20%] right-[12%] w-10 h-10 text-amber-400/15 -rotate-12"})]}),QDs=()=>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(Ua,{className:"absolute top-[8%] left-[50%] -translate-x-1/2 w-14 h-14 text-yellow-400/28 fill-yellow-400/18"}),e.jsx(cn,{className:"absolute top-[5%] left-[20%] w-7 h-7 text-blue-400/35"}),e.jsx(cn,{className:"absolute top-[10%] right-[18%] w-6 h-6 text-sky-400/30"})]}),JDs=()=>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(pA,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-green-500/25"}),e.jsx(pA,{className:"absolute top-[8%] right-[12%] w-12 h-12 text-emerald-500/20"}),e.jsx(pA,{className:"absolute bottom-[18%] left-[12%] w-14 h-14 text-green-400/22"}),e.jsx(pA,{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"})]})]})]}),eOs=()=>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(Ua,{className:"absolute top-[5%] left-[42%] w-10 h-10 text-amber-400/30 fill-amber-400/20"}),e.jsx(Ua,{className:"absolute top-[15%] right-[25%] w-7 h-7 text-yellow-400/25 fill-yellow-400/15"}),e.jsx(Eh,{className:"absolute bottom-[20%] right-[12%] w-12 h-12 text-blue-500/18"}),e.jsx(Eh,{className:"absolute top-[18%] left-[28%] w-8 h-8 text-indigo-400/15"}),e.jsx(NA,{className:"absolute top-[8%] left-[60%] w-10 h-10 text-indigo-400/18"})]}),tOs=()=>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(lg,{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(Wg,{className:"absolute top-[8%] left-[45%] w-10 h-10 text-purple-400/22 rotate-12"}),e.jsx(Ro,{className:"absolute bottom-[18%] right-[15%] w-12 h-12 text-rose-400/18"})]}),sOs=()=>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(ko,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-rose-400/28 fill-rose-400/18"}),e.jsx(ko,{className:"absolute top-[8%] right-[12%] w-14 h-14 text-pink-400/25 fill-pink-400/15"}),e.jsx(ko,{className:"absolute bottom-[15%] left-[12%] w-12 h-12 text-red-400/22 fill-red-400/12"}),e.jsx(ko,{className:"absolute bottom-[18%] right-[10%] w-13 h-13 text-rose-300/25 fill-rose-300/15"}),e.jsx(ko,{className:"absolute top-[15%] left-[30%] w-6 h-6 text-pink-300/35 fill-pink-300/20 animate-pulse"}),e.jsx(ko,{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(ko,{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(ko,{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"})]}),nOs=()=>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(eN,{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(eN,{className:"absolute top-[15%] left-[18%] w-10 h-10 text-yellow-400/30"}),e.jsx(cn,{className:"absolute top-[10%] left-[42%] w-7 h-7 text-amber-400/35"}),e.jsx(eN,{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"})]}),rOs=()=>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(ra,{className:"absolute top-[8%] left-[10%] w-14 h-14 text-teal-500/22"}),e.jsx(ra,{className:"absolute bottom-[15%] right-[8%] w-16 h-16 text-emerald-500/18"}),e.jsx(C_,{className:"absolute top-[12%] right-[18%] w-10 h-10 text-amber-400/25"}),e.jsx(C_,{className:"absolute bottom-[22%] left-[22%] w-8 h-8 text-yellow-400/22"}),e.jsx(ko,{className:"absolute top-[18%] left-[40%] w-6 h-6 text-rose-400/22 fill-rose-400/12"}),e.jsx(ko,{className:"absolute top-[22%] right-[35%] w-5 h-5 text-teal-400/20 fill-teal-400/10"}),e.jsx(cn,{className:"absolute top-[5%] left-[55%] w-8 h-8 text-teal-400/30"}),e.jsx(Wg,{className:"absolute bottom-[20%] left-[48%] w-10 h-10 text-cyan-400/18 rotate-12"})]}),aOs=()=>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(Wg,{className:"absolute top-[5%] left-[12%] w-14 h-14 text-emerald-400/25 rotate-12"}),e.jsx(Wg,{className:"absolute top-[8%] right-[10%] w-12 h-12 text-teal-400/22 -rotate-12"}),e.jsx(C_,{className:"absolute bottom-[18%] left-[18%] w-12 h-12 text-amber-400/25"}),e.jsx(ra,{className:"absolute bottom-[15%] right-[12%] w-14 h-14 text-teal-500/18"}),e.jsx(cn,{className:"absolute top-[15%] left-[42%] w-10 h-10 text-emerald-400/35"}),e.jsx(cn,{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"})]}),iOs=()=>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(C_,{className:"absolute bottom-[12%] left-[50%] -translate-x-1/2 w-24 h-24 text-amber-400/25 rotate-45"}),e.jsx(C_,{className:"absolute top-[10%] left-[12%] w-10 h-10 text-yellow-400/30"}),e.jsx(C_,{className:"absolute top-[12%] right-[15%] w-9 h-9 text-amber-300/25"}),e.jsx(ra,{className:"absolute top-[8%] left-[42%] w-12 h-12 text-teal-500/18"}),e.jsx(Wg,{className:"absolute bottom-[22%] right-[18%] w-12 h-12 text-orange-400/18 rotate-12"}),e.jsx(cn,{className:"absolute top-[5%] right-[35%] w-8 h-8 text-yellow-400/35"}),e.jsx(Ua,{className:"absolute top-[18%] left-[28%] w-6 h-6 text-amber-400/25 fill-amber-400/15"})]}),oOs=()=>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(ra,{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(C_,{className:"absolute top-[10%] right-[12%] w-10 h-10 text-amber-400/28"}),e.jsx(ko,{className:"absolute top-[8%] left-[18%] w-8 h-8 text-rose-400/25 fill-rose-400/15"}),e.jsx(cn,{className:"absolute top-[12%] left-[45%] w-8 h-8 text-teal-400/30"}),e.jsx(G2,{className:"absolute top-[15%] right-[28%] w-10 h-10 text-emerald-400/20"})]}),xft=()=>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"})]}),lOs=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(ko,{className:"absolute top-6 left-[12%] w-4 h-4 text-rose-300/50 fill-rose-300/30 animate-pulse"}),e.jsx(ko,{className:"absolute top-10 right-[18%] w-3 h-3 text-pink-300/50 fill-pink-300/30 animate-pulse delay-150"}),e.jsx(ko,{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(ko,{className:"absolute top-14 right-[35%] w-3.5 h-3.5 text-pink-300/40 fill-pink-300/20 animate-pulse delay-200"})]}),cOs=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(G2,{className:"absolute top-5 left-[10%] w-4 h-4 text-blue-400/50 animate-pulse"}),e.jsx(cn,{className:"absolute top-10 right-[15%] w-3 h-3 text-amber-400/50 animate-pulse delay-100"}),e.jsx(ra,{className:"absolute top-8 left-[38%] w-3 h-3 text-teal-300/40 animate-pulse delay-200"})]}),dOs=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(M4,{className:"absolute top-5 left-[12%] w-4 h-4 text-amber-500/50 animate-pulse"}),e.jsx(aq,{className:"absolute top-10 right-[15%] w-3 h-3 text-rose-400/50 animate-pulse delay-100"}),e.jsx(M4,{className:"absolute top-8 left-[40%] w-3 h-3 text-amber-400/40 animate-pulse delay-200"})]}),JK=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(cn,{className:"absolute top-5 left-[10%] w-4 h-4 text-emerald-400/50 animate-pulse"}),e.jsx(Wg,{className:"absolute top-10 right-[12%] w-5 h-5 text-amber-400/50 animate-pulse delay-150"}),e.jsx(cn,{className:"absolute top-8 left-[45%] w-3 h-3 text-sky-400/40 animate-pulse delay-300"})]}),yft=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(ra,{className:"absolute top-6 left-[12%] w-4 h-4 text-teal-400/40 animate-pulse"}),e.jsx(cn,{className:"absolute top-10 right-[15%] w-3 h-3 text-emerald-400/50 animate-pulse delay-100"}),e.jsx(ra,{className:"absolute top-4 right-[40%] w-3 h-3 text-cyan-400/30 animate-pulse delay-200"})]}),s$e=[{id:"default",name:"Classic",description:"Clean, professional look for any occasion",icon:e.jsx(cn,{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(ko,{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(lOs,{})},{id:"thinking_of_you",name:"Thinking of You",description:"Let them know they're on your mind",icon:e.jsx(AX,{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(JK,{})},{id:"check_in",name:"Check-in",description:"Touch base with your contacts",icon:e.jsx(M4,{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(dOs,{})},{id:"market_update",name:"Market Update",description:"Share real estate market insights",icon:e.jsx(Cl,{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(Bn,{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(JK,{})},{id:"congratulations",name:"Congratulations",description:"Celebrate their achievements",icon:e.jsx(Eh,{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(xft,{})},{id:"welcome_neighborhood",name:"Welcome to the Neighborhood",description:"Greet new neighbors",icon:e.jsx(ni,{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(yft,{})},{id:"just_because",name:"Just Because",description:"No reason needed to connect",icon:e.jsx(aq,{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(JK,{})},{id:"birthday",name:"Birthday",description:"Celebrate their special day",icon:e.jsx(lg,{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(tOs,{})},{id:"valentines_day",name:"Valentine's Day",description:"Show appreciation on this special day",icon:e.jsx(ko,{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(sOs,{})},{id:"groundhog_day",name:"Groundhog Day",description:"A fun seasonal greeting",icon:e.jsx(eN,{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(nOs,{})},{id:"new_years",name:"New Year's Day",description:"Ring in the new year",icon:e.jsx(Ua,{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(XDs,{})},{id:"easter",name:"Easter",description:"Celebrate the spring season",icon:e.jsx(KU,{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(WDs,{})},{id:"mothers_day",name:"Mother's Day",description:"Celebrate the amazing moms",icon:e.jsx(Hk,{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(HDs,{})},{id:"fathers_day",name:"Father's Day",description:"Celebrate the amazing dads",icon:e.jsx(Eh,{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(GDs,{})},{id:"memorial_day",name:"Memorial Day",description:"Honor those who served",icon:e.jsx(NA,{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($Ds,{})},{id:"independence_day",name:"4th of July",description:"Celebrate Independence Day",icon:e.jsx(Xd,{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(VDs,{})},{id:"labor_day",name:"Labor Day",description:"Celebrate the workers",icon:e.jsx(Eh,{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(eOs,{})},{id:"halloween",name:"Halloween",description:"Spooky seasonal greetings",icon:e.jsx(CF,{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(KDs,{})},{id:"thanksgiving",name:"Thanksgiving",description:"Express gratitude this season",icon:e.jsx(ko,{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(ZDs,{})},{id:"christmas",name:"Christmas",description:"Spread holiday cheer",icon:e.jsx(DM,{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(YDs,{})},{id:"hanukkah",name:"Hanukkah",description:"Celebrate the Festival of Lights",icon:e.jsx(cn,{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(QDs,{})},{id:"st_patricks_day",name:"St. Patrick's Day",description:"Celebrate the luck of the Irish",icon:e.jsx(pA,{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(JDs,{})},{id:"home_anniversary",name:"Home Anniversary",description:"Celebrate their home ownership milestone",icon:e.jsx(ra,{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(rOs,{})},{id:"under_contract",name:"Under Contract",description:"Celebrate this exciting milestone",icon:e.jsx(Wg,{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(aOs,{})},{id:"just_listed",name:"Just Listed",description:"Announce a new listing",icon:e.jsx(pa,{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(yft,{})},{id:"just_sold",name:"Just Sold",description:"Celebrate a successful sale",icon:e.jsx(yu,{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(JK,{})},{id:"price_reduction",name:"Price Reduction",description:"Notify about a price change",icon:e.jsx(nS,{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(G2,{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(cOs,{})},{id:"closing_day",name:"Closing Day",description:"Celebrate their closing day",icon:e.jsx(C_,{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(iOs,{})},{id:"move_in_day",name:"Move-in Day",description:"Welcome them to their new home",icon:e.jsx(ra,{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(oOs,{})},{id:"offer_accepted",name:"Offer Accepted",description:"Celebrate their accepted offer",icon:e.jsx(wx,{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(JK,{})},{id:"pre_approval",name:"Pre-Approval Congrats",description:"Congratulate on pre-approval",icon:e.jsx(Eh,{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(xft,{})}],uOs=[{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 hOs(s){return s$e.filter(t=>t.category===s)}function Dq(s){return s$e.find(t=>t.id===s)||s$e[0]}function vft(){const{shareToken:s,recipientToken:t}=Di(),[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,p]=j.useState(!0),f=j.useRef(null),x=j.useRef(0),y=j.useRef(0),v=(()=>{const $=new URLSearchParams(window.location.search);return t||$.get("rt")||null})(),b=j.useCallback(($,H=!1)=>{if(!v||$<=0)return;const V=Math.max(1,Math.round($));if(V<=y.current)return;const Z=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${encodeURIComponent(v)}&e=watch&ws=${V}`;H&&navigator.sendBeacon?navigator.sendBeacon(Z):fetch(Z,{method:"GET",keepalive:H}).catch(()=>{}),y.current=Math.max(y.current,V)},[v]);j.useEffect(()=>{var le;if(!m||!(n!=null&&n.playback_url)||!v)return;let $=!1;const H=()=>{x.current>0&&b(x.current,!0)},V=()=>{document.visibilityState==="hidden"&&H()},K=()=>{H()},Z=()=>{var se;if($||!f.current||!((se=window.playerjs)!=null&&se.Player))return;const ue=new window.playerjs.Player(f.current);ue.on("timeupdate",ne=>{const ie=Math.floor(Number((ne==null?void 0:ne.seconds)??0));!Number.isFinite(ie)||ie<=0||(x.current=Math.max(x.current,ie))}),ue.on("pause",()=>{x.current>0&&b(x.current)}),ue.on("ended",()=>{x.current>0&&b(x.current,!0)})},Q=document.querySelector('script[data-bunny-playerjs="true"]');if((le=window.playerjs)!=null&&le.Player)Z();else if(Q)Q.addEventListener("load",Z,{once:!0});else{const ue=document.createElement("script");ue.src="https://assets.mediadelivery.net/playerjs/playerjs-latest.min.js",ue.async=!0,ue.defer=!0,ue.dataset.bunnyPlayerjs="true",ue.onload=Z,document.body.appendChild(ue)}return document.addEventListener("visibilitychange",V),window.addEventListener("beforeunload",K),()=>{$=!0,document.removeEventListener("visibilitychange",V),window.removeEventListener("beforeunload",K),H()}},[m,n==null?void 0:n.playback_url,v,b]),j.useEffect(()=>{x.current=0,y.current=0},[v,s]),j.useEffect(()=>{const $=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="msgsndr"]',"[data-chat-widget]"].forEach(Z=>{document.querySelectorAll(Z).forEach(Q=>{Q.style.display="none"})})};$();const H=[setTimeout($,500),setTimeout($,1500),setTimeout($,3e3)],V=new MutationObserver($);return V.observe(document.body,{childList:!0,subtree:!0}),()=>{H.forEach(clearTimeout),V.disconnect()}},[]),j.useEffect(()=>{(async()=>{if(!s){h("Invalid share link"),d(!1);return}const{data:H,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||!H){h("Video not found or has been removed"),d(!1);return}r(H);try{await q.rpc("log_video_view",{p_video_id:H.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch(K){console.warn("Failed to log video view:",K)}if(H.owner_user_id){const{data:K}=await q.from("profiles").select("id, name, email, phone").eq("id",H.owner_user_id).single();if(K){i(K);try{const{data:Z}=await q.storage.from("avatars").list(`${H.owner_user_id}`);if(Z&&Z.length>0){const{data:Q}=q.storage.from("avatars").getPublicUrl(`${H.owner_user_id}/${Z[0].name}`);o(Q.publicUrl)}}catch{}}}d(!1)})()},[s]);const N=$=>{if(!$)return"0:00";const H=Math.floor($/60),V=$%60;return`${H}:${V.toString().padStart(2,"0")}`},S=$=>$.includes("iframe.mediadelivery.net/play/")?$.replace("/play/","/embed/")+"?autoplay=true&responsive=true":$,A=$=>{if(!$)return"?";const H=$.split(" ");return H.length>=2?`${H[0][0]}${H[1][0]}`.toUpperCase():$.substring(0,2).toUpperCase()},T=Dq((n==null?void 0:n.page_template)||"default"),L=(n==null?void 0:n.recipient_name)||null,M=T.headerText(L),R=`https://dashboard.relevelup.com/share/video/${s}`;if(c)return e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:e.jsx(Et,{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(we,{className:"max-w-md w-full",children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(Wr,{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 z=T.id!=="default";return e.jsxs(e.Fragment,{children:[e.jsxs(dl,{children:[e.jsx("title",{children:M}),e.jsx("meta",{name:"description",content:T.subText}),e.jsx("meta",{property:"og:title",content:M}),e.jsx("meta",{property:"og:description",content:T.subText}),e.jsx("meta",{property:"og:type",content:"video.other"}),e.jsx("meta",{property:"og:url",content:R}),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:M}),e.jsx("meta",{name:"twitter:description",content:T.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:Mt("min-h-screen flex items-center justify-center p-4 bg-gradient-to-b relative",T.gradientClasses),children:[z&&T.decorativeElement,e.jsxs("div",{className:"max-w-2xl w-full space-y-6 relative z-10",children:[z&&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:Mt("w-14 h-14 rounded-full flex items-center justify-center shadow-sm",T.accentColor==="primary"&&"bg-primary/10 text-primary",T.accentColor==="amber"&&"bg-amber-100 text-amber-600 dark:bg-amber-900/50 dark:text-amber-400",T.accentColor==="teal"&&"bg-teal-100 text-teal-600 dark:bg-teal-900/50 dark:text-teal-400",T.accentColor==="rose"&&"bg-rose-100 text-rose-600 dark:bg-rose-900/50 dark:text-rose-400",T.accentColor==="emerald"&&"bg-emerald-100 text-emerald-600 dark:bg-emerald-900/50 dark:text-emerald-400",T.accentColor==="yellow"&&"bg-yellow-100 text-yellow-600 dark:bg-yellow-900/50 dark:text-yellow-400",T.accentColor==="pink"&&"bg-pink-100 text-pink-600 dark:bg-pink-900/50 dark:text-pink-400",T.accentColor==="blue"&&"bg-blue-100 text-blue-600 dark:bg-blue-900/50 dark:text-blue-400",T.accentColor==="red"&&"bg-red-100 text-red-600 dark:bg-red-900/50 dark:text-red-400",T.accentColor==="orange"&&"bg-orange-100 text-orange-600 dark:bg-orange-900/50 dark:text-orange-400",T.accentColor==="green"&&"bg-green-100 text-green-600 dark:bg-green-900/50 dark:text-green-400",T.accentColor==="violet"&&"bg-violet-100 text-violet-600 dark:bg-violet-900/50 dark:text-violet-400",T.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:T.icon})})}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold mb-2",children:M}),e.jsx("p",{className:"text-muted-foreground",children:T.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(Ea,{className:"h-14 w-14 border-2 border-primary/20",children:[e.jsx(Ci,{src:l||void 0,alt:a.name||"Agent"}),e.jsx(Ta,{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:z?"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(U,{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(ba,{className:"h-4 w-4"})})}),a.email&&e.jsx(U,{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(ln,{className:"h-4 w-4"})})})]})]}),e.jsx(we,{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:f,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:()=>p(!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:$=>{var V;$.currentTarget.style.display="none";const H=(V=$.currentTarget.parentElement)==null?void 0:V.querySelector(".video-fallback");H&&(H.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(Wr,{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(lu,{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:N(n.duration_seconds)})]})}),!z&&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(U,{size:"lg",onClick:()=>p(!0),className:"gap-2",children:[e.jsx(lu,{className:"h-5 w-5"}),"Watch Video"]})}),e.jsx(qDs,{shareToken:s,agentName:(a==null?void 0:a.name)||null,hasContact:!!n.contact_id})]})]})]})}function mOs(){return j.useEffect(()=>(document.body.classList.add("video-landing-page"),()=>{document.body.classList.remove("video-landing-page")}),[]),e.jsx(LZe,{})}function pOs(){const{token:s}=Di();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(Et,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{children:"Loading video preview…"})]})})}const fOs=[{key:"residential",title:"Residential",tagline:"Homes, condos, land & luxury",path:"/mission-control/listings/new/residential",icon:ra,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:_i,points:["Pitch Mode to win the assignment","Institutional-grade microsite","Gated OM & investor tracking"],featured:!0}];function gOs(){const s=Wn(),{search:t}=Od();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(U,{variant:"ghost",size:"sm",className:"mb-6 -ml-2",onClick:()=>s("/mission-control/listings"),children:[e.jsx(Aa,{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:fOs.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(cn,{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(Oa,{className:"h-4 w-4 transition-transform group-hover:translate-x-0.5"})]})]},n.key)})})]})})}const rFt=()=>ct({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}}),aFt=s=>{const{user:t,brokerageId:n}=vs();return ct({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(p=>p.id)),m=u.filter(p=>!h.has(p.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=>EQe(AQe(o)))}})};function AQe(s){return s&&Array.isArray(s.commercial)&&(s.commercial=s.commercial[0]??null),s}function EQe(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 TQe=()=>{const{user:s}=vs();return ct({queryKey:["my-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("listings").select(` *, photos:listing_photos(*), commercial:commercial_listing_details(*) `).eq("agent_id",s.id).order("created_at",{ascending:!1});if(n)throw n;return t.map(r=>EQe(AQe(r)))},enabled:!!s})},rre=s=>{const{user:t}=vs();return ct({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}),EQe(AQe(n))},enabled:!!s})},iFt=()=>{const s=Qt(),{user:t}=vs();return yt({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"]})}})},xOs=()=>{const s=Qt();return yt({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"]})}})},oFt=()=>{const s=Qt();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("listings").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["listing",t.id]})}})},lFt=()=>{const s=Qt();return yt({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"]})}})},cFt=()=>{const s=Qt();return yt({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"]})}})},dFt=()=>{const s=Qt();return yt({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"]})}})},uFt=()=>{const s=Qt();return yt({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"]})}})},hFt=()=>{const s=Qt();return yt({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"]})}})},yOs=()=>{const{user:s}=vs();return ct({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})},mFt=()=>{const s=Qt(),{user:t}=vs();return yt({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"]})}})},pFt=s=>{const{user:t}=vs();return ct({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})},vOs=()=>{const s=Qt(),{user:t}=vs();return yt({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"]})}})},bOs=s=>{const{user:t}=vs();return ct({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})},_Os=()=>{const{user:s}=vs();return yt({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}})},wOs=()=>{const{user:s}=vs();return ct({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})},jOs=()=>{const s=Qt(),{user:t}=vs();return yt({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"]})}})},NOs=()=>ct({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}}}),kOs=()=>{const{user:s,brokerageId:t}=vs();return ct({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})},GOe=q,Xm=s=>s===""||s==null?null:Number(String(s).replace(/[^0-9.\-]/g,"")),SOs={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 bft({label:s,placeholder:t,items:n,onChange:r}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:s}),n.map((a,i)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:a,placeholder:t,onChange:l=>r(n.map((o,c)=>c===i?l.target.value:o))}),e.jsx(U,{type:"button",variant:"ghost",size:"icon",onClick:()=>r(n.filter((l,o)=>o!==i)),children:e.jsx(er,{className:"h-4 w-4"})})]},i)),e.jsxs(U,{type:"button",variant:"outline",size:"sm",onClick:()=>r([...n,""]),children:[e.jsx(an,{className:"mr-1.5 h-3.5 w-3.5"})," Add"]})]})}function WOe({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(te,{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(te,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:o.label}),e.jsx(xe,{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(U,{type:"button",variant:"ghost",size:"icon",onClick:()=>a(r.filter((o,c)=>c!==l)),children:e.jsx(er,{className:"h-4 w-4"})})]},l)),e.jsxs(U,{type:"button",variant:"outline",size:"sm",onClick:()=>a([...r,{}]),children:[e.jsx(an,{className:"mr-1.5 h-3.5 w-3.5"})," Add row"]})]})}const COs=[{key:"radius_1",label:"1 mile"},{key:"radius_3",label:"3 miles"},{key:"radius_5",label:"5 miles"}],AOs=[{key:"population",label:"Population"},{key:"households",label:"Households"},{key:"avg_income",label:"Avg income"},{key:"daytime_pop",label:"Daytime pop."}];function _ft(){const{listingId:s}=Di(),t=Wn(),{user:n,loading:r}=vs(),a=!!s,{data:i,isLoading:l}=rre(s||""),{data:o}=rRt(s);iFt();const c=oFt(),d=aRt(),u=iRt(),[h,m]=j.useState(null),[p,f]=j.useState(SOs),[x,y]=j.useState([""]),[v,b]=j.useState([]),[N,S]=j.useState([]),[A,T]=j.useState([]),[L,M]=j.useState([]),[I,R]=j.useState({}),[z,$]=j.useState(!1),[H,V]=j.useState([]),[K,Z]=j.useState([]),Q=!a||!!(n!=null&&n.id)&&(i==null?void 0:i.agent_id)===n.id;j.useEffect(()=>{!a||r||l||!i||Q||(re.error("Only the listing agent can edit this commercial listing"),t(`/mission-control/listings/${i.id}/commercial`,{replace:!0}))},[r,i,a,Q,l,t]);const le=he=>{if(!(he!=null&&he.length))return;const ge=Array.from(he);V(ke=>[...ke,...ge]),Z(ke=>[...ke,...ge.map(Te=>URL.createObjectURL(Te))])},ue=he=>{URL.revokeObjectURL(K[he]),V(ge=>ge.filter((ke,Te)=>Te!==he)),Z(ge=>ge.filter((ke,Te)=>Te!==he))},se=async he=>{if(!H.length)return;const{count:ge}=await GOe.from("listing_photos").select("id",{count:"exact",head:!0}).eq("listing_id",he),ke=ge??0;for(let Te=0;Tef(ke=>({...ke,[he]:ge}));j.useEffect(()=>{!a||!i||(m(i.lifecycle_stage==="pitch"?"pitch":"assignment"),f(he=>({...he,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 he;o&&(f(ge=>({...ge,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((he=o.investment_highlights)!=null&&he.length?o.investment_highlights:[""]),b(o.property_highlights??[]),S((o.spaces??[]).map(ge=>({...ge,sf:(ge==null?void 0:ge.sf)!=null?String(ge.sf):""}))),T((o.tenants??[]).map(ge=>({...ge,sf:(ge==null?void 0:ge.sf)!=null?String(ge.sf):""}))),M(o.traffic_counts??[]),R(o.demographics??{}))},[o]);const ie=p.deal_type==="lease"||p.deal_type==="sale_or_lease",ce=p.deal_type!=="lease",je=j.useMemo(()=>({deal_type:p.deal_type,commercial_type:p.commercial_type,opportunity_title:p.opportunity_title||null,submarket:p.submarket||null,asking_price:Xm(p.asking_price),lease_rate:Xm(p.lease_rate),lease_rate_unit:p.lease_rate_unit,lease_type:p.lease_type||null,building_sf:Xm(p.building_sf),available_sf:Xm(p.available_sf),lot_acres:Xm(p.lot_acres),units:Xm(p.units),floors:Xm(p.floors),parking_spaces:Xm(p.parking_spaces),zoning:p.zoning||null,occupancy_pct:Xm(p.occupancy_pct),tenancy:p.tenancy||null,noi:Xm(p.noi),cap_rate:Xm(p.cap_rate),gross_income:Xm(p.gross_income),operating_expenses:Xm(p.operating_expenses),broker_coop_pct:Xm(p.broker_coop_pct),call_for_offers_at:p.call_for_offers_at?new Date(p.call_for_offers_at).toISOString():null,is_confidential:p.is_confidential,hide_address:p.hide_address,requires_nda:p.requires_nda,om_gate_mode:p.om_gate_mode,opportunity_zone:p.opportunity_zone,investment_highlights:x.map(he=>he.trim()).filter(Boolean),spaces:N.filter(he=>Object.values(he).some(ge=>String(ge??"").trim())),tenants:A.filter(he=>Object.values(he).some(ge=>String(ge??"").trim())),traffic_counts:L.filter(he=>String(he.road??"").trim()||String(he.count??"").trim()),demographics:Object.fromEntries(Object.entries(I).filter(([,he])=>Object.values(he??{}).some(ge=>String(ge??"").trim()))),property_highlights:v.map(he=>he.trim()).filter(Boolean),price_per_sf:Xm(p.asking_price)&&Xm(p.building_sf)?Math.round(Xm(p.asking_price)/Xm(p.building_sf)*100)/100:null,price_per_unit:Xm(p.asking_price)&&Xm(p.units)?Math.round(Xm(p.asking_price)/Xm(p.units)):null}),[p,x,v,N,A,L,I]),be=async()=>{if(a&&!Q){re.error("Only the listing agent can edit this commercial listing");return}if(!p.city||!p.state){re.error("City and state are required");return}if(!a&&!h){re.error("Choose whether you already have the assignment");return}$(!0);try{let he=s;const ge={property_address:p.property_address||null,city:p.city,state:p.state,neighborhood:p.submarket||null,price:Xm(p.asking_price)??0,property_type:"commercial",description:p.description||null,year_built:Xm(p.year_built),square_footage:Xm(p.building_sf)},ke=h==="pitch",Te=ke?{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:p.site_only?!1:p.is_public,allow_sharing:p.site_only?!1:p.allow_sharing,share_with_brokerage:p.site_only?!1:p.share_with_brokerage,open_to_referrals:p.open_to_referrals,open_to_social_promotion:p.site_only?!1:p.open_to_social_promotion,show_on_lead_site:p.site_only?!0:p.show_on_lead_site},Me=!ke&&(Te.is_public||Te.show_on_lead_site||Te.allow_sharing)?"active":"coming_soon";if(a&&he)await c.mutateAsync({id:he,...ge,...Te,...Me==="active"?{status:"active"}:{}});else{const Oe=await GOe.from("listings").insert({...ge,...Te,agent_id:n.id,listing_class:"commercial",lifecycle_stage:ke?"pitch":"won",status:Me}).select().single();if(Oe.error)throw Oe.error;he=Oe.data.id,ke&&await u.mutateAsync({listingId:he,values:{launch_plan:nRt}})}await d.mutateAsync({listingId:he,values:je}),await se(he),re.success(a?"Commercial listing updated":"Commercial listing created"),t(`/mission-control/listings/${he}/commercial`)}catch(he){console.error(he),re.error(he.message||"Could not save listing")}finally{$(!1)}};return a&&(r||l||!i||!Q)?e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:e.jsx(Et,{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(U,{variant:"ghost",size:"sm",className:"-ml-2 mb-6",onClick:()=>t("/mission-control/listings/new"),children:[e.jsx(Aa,{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(Al,{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(Gu,{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(U,{variant:"ghost",size:"sm",className:"-ml-2 mb-6",onClick:()=>t(a?`/mission-control/listings/${s}/commercial`:"/mission-control/listings"),children:[e.jsx(Aa,{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(_i,{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(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-base",children:"The opportunity"}),e.jsx(Jn,{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(te,{children:"Deal type"}),e.jsxs(Ns,{value:p.deal_type,onValueChange:he=>ne("deal_type",he),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:Object.entries(uP).map(([he,ge])=>e.jsx(et,{value:he,children:ge},he))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Property type"}),e.jsxs(Ns,{value:p.commercial_type,onValueChange:he=>ne("commercial_type",he),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:Object.entries(qP).map(([he,ge])=>e.jsx(et,{value:he,children:ge},he))})]})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsxs(te,{children:["Opportunity name ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(xe,{value:p.opportunity_title,placeholder:"e.g. Gateway Logistics Center",onChange:he=>ne("opportunity_title",he.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(te,{children:"Property story"}),e.jsx(Fs,{rows:5,value:p.description,placeholder:"The narrative an investor, tenant or owner should read first.",onChange:he=>ne("description",he.target.value)})]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(te,{children:"Street address"}),e.jsx(xe,{value:p.property_address,onChange:he=>ne("property_address",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"City *"}),e.jsx(xe,{value:p.city,onChange:he=>ne("city",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"State *"}),e.jsx(xe,{value:p.state,maxLength:2,onChange:he=>ne("state",he.target.value.toUpperCase())})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Submarket"}),e.jsx(xe,{value:p.submarket,placeholder:"e.g. North Loop",onChange:he=>ne("submarket",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Zoning"}),e.jsx(xe,{value:p.zoning,onChange:he=>ne("zoning",he.target.value)})]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(te,{children:"Asking price"}),e.jsx(xe,{value:p.asking_price,placeholder:"4750000",onChange:he=>ne("asking_price",he.target.value)})]}),ie&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Lease rate"}),e.jsx(xe,{value:p.lease_rate,placeholder:"24.50",onChange:he=>ne("lease_rate",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Rate basis"}),e.jsxs(Ns,{value:p.lease_rate_unit,onValueChange:he=>ne("lease_rate_unit",he),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"sf_year",children:"Per SF / year"}),e.jsx(et,{value:"sf_month",children:"Per SF / month"}),e.jsx(et,{value:"month",children:"Per month"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Lease structure"}),e.jsxs(Ns,{value:p.lease_type||"none",onValueChange:he=>ne("lease_type",he==="none"?"":he),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select"})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"Not specified"}),xAs.map(he=>e.jsx(et,{value:he,children:he},he))]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Broker co-op (%)"}),e.jsx(xe,{value:p.broker_coop_pct,placeholder:"2.5",onChange:he=>ne("broker_coop_pct",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Call for offers"}),e.jsx(xe,{type:"date",value:p.call_for_offers_at,onChange:he=>ne("call_for_offers_at",he.target.value)})]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(te,{children:"Building SF"}),e.jsx(xe,{value:p.building_sf,onChange:he=>ne("building_sf",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Available SF"}),e.jsx(xe,{value:p.available_sf,onChange:he=>ne("available_sf",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Lot acres"}),e.jsx(xe,{value:p.lot_acres,onChange:he=>ne("lot_acres",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Units"}),e.jsx(xe,{value:p.units,onChange:he=>ne("units",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Floors"}),e.jsx(xe,{value:p.floors,onChange:he=>ne("floors",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Parking spaces"}),e.jsx(xe,{value:p.parking_spaces,onChange:he=>ne("parking_spaces",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Year built"}),e.jsx(xe,{value:p.year_built,onChange:he=>ne("year_built",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Tenancy"}),e.jsxs(Ns,{value:p.tenancy||"none",onValueChange:he=>ne("tenancy",he==="none"?"":he),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select"})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"Not specified"}),e.jsx(et,{value:"single",children:"Single tenant"}),e.jsx(et,{value:"multi",children:"Multi-tenant"}),e.jsx(et,{value:"vacant",children:"Vacant"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Occupancy (%)"}),e.jsx(xe,{value:p.occupancy_pct,onChange:he=>ne("occupancy_pct",he.target.value)})]})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-base",children:"Investment metrics"}),e.jsx(Jn,{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(te,{children:"NOI"}),e.jsx(xe,{value:p.noi,onChange:he=>ne("noi",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Cap rate (%)"}),e.jsx(xe,{value:p.cap_rate,onChange:he=>ne("cap_rate",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Gross income"}),e.jsx(xe,{value:p.gross_income,onChange:he=>ne("gross_income",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Operating expenses"}),e.jsx(xe,{value:p.operating_expenses,onChange:he=>ne("operating_expenses",he.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(te,{children:"Opportunity Zone"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlight qualified OZ tax treatment."})]}),e.jsx(wn,{checked:p.opportunity_zone,onCheckedChange:he=>ne("opportunity_zone",he)})]})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-base",children:"Highlights"}),e.jsx(Jn,{children:"3–6 reasons this opportunity matters. These headline the microsite."})]}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsx(bft,{label:"Investment highlights",placeholder:"e.g. 12-year NNN lease to investment-grade tenant",items:x,onChange:y}),e.jsx(bft,{label:"Property highlights",placeholder:"e.g. 32' clear height, 14 dock doors",items:v,onChange:b})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-base",children:"Spaces, tenants & market data"}),e.jsx(Jn,{children:"Everything here is optional — the microsite only renders the sections you fill in."})]}),e.jsxs(Ie,{className:"space-y-8",children:[e.jsx(WOe,{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:N,onChange:S}),e.jsx(WOe,{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:T}),e.jsx(WOe,{label:"Traffic counts",columns:[{key:"road",label:"Road",placeholder:"US-98"},{key:"count",label:"Vehicles / day",placeholder:"42,500 VPD"}],rows:L,onChange:M}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Demographics"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"1 / 3 / 5-mile radius cards on the microsite."})]}),COs.map(he=>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:he.label}),AOs.map(ge=>{var ke;return e.jsxs("div",{className:"min-w-[120px] flex-1 space-y-1",children:[e.jsx(te,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:ge.label}),e.jsx(xe,{value:((ke=I[he.key])==null?void 0:ke[ge.key])??"",onChange:Te=>R({...I,[he.key]:{...I[he.key]??{},[ge.key]:Te.target.value}})})]},ge.key)})]},he.key))]})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-base",children:"Photography"}),e.jsx(Jn,{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(an,{className:"mr-2 h-4 w-4"}),"Add photos",e.jsx("input",{type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:he=>le(he.target.files)})]}),K.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-3 gap-2 sm:grid-cols-4",children:K.map((he,ge)=>e.jsxs("div",{className:"group relative aspect-[4/3] overflow-hidden rounded-md border",children:[e.jsx("img",{src:he,alt:`Commercial photo ${ge+1}`,className:"h-full w-full object-cover"}),e.jsx("button",{type:"button",onClick:()=>ue(ge),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(er,{className:"h-3 w-3"})})]},he))}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[K.length," photo",K.length===1?"":"s"," upload when you save."]})]})]})]}),h!=="pitch"&&e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-base",children:"Distribution & sharing"}),e.jsx(Jn,{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(te,{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(wn,{checked:p.site_only,onCheckedChange:he=>f(ge=>({...ge,site_only:he,is_public:he?!1:ge.is_public,show_on_lead_site:he?!0:ge.show_on_lead_site,share_with_brokerage:he?!1:ge.share_with_brokerage}))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Publish publicly"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Go live on commercial.relevelup.com to capture leads."})]}),e.jsx(wn,{checked:p.is_public,disabled:p.site_only,onCheckedChange:he=>ne("is_public",he)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Show on my website"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Feature it on your own lead site."})]}),e.jsx(wn,{checked:p.show_on_lead_site,onCheckedChange:he=>ne("show_on_lead_site",he)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Allow sharing"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other LevelUp agents can share it from the Exchange."})]}),e.jsx(wn,{checked:p.allow_sharing,disabled:p.site_only,onCheckedChange:he=>ne("allow_sharing",he)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Share with my brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents inside your brokerage."})]}),e.jsx(wn,{checked:p.share_with_brokerage,disabled:p.site_only,onCheckedChange:he=>ne("share_with_brokerage",he)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Open to referrals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Accept tenant / buyer referrals from other agents."})]}),e.jsx(wn,{checked:p.open_to_referrals,onCheckedChange:he=>ne("open_to_referrals",he)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Social promotion"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other agents may promote it on social media."})]}),e.jsx(wn,{checked:p.open_to_social_promotion,disabled:p.site_only,onCheckedChange:he=>ne("open_to_social_promotion",he)})]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(te,{children:"Confidential offering"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Teaser presentation, no address, search engines blocked."})]}),e.jsx(wn,{checked:p.is_confidential,onCheckedChange:he=>ne("is_confidential",he)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Hide street address"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show city / submarket only."})]}),e.jsx(wn,{checked:p.hide_address,onCheckedChange:he=>ne("hide_address",he)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Offering Memorandum access"}),e.jsxs(Ns,{value:p.om_gate_mode,onValueChange:he=>ne("om_gate_mode",he),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"open",children:"Open download"}),e.jsx(et,{value:"email",children:"Require name, email & company"}),e.jsx(et,{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(U,{onClick:be,disabled:z,children:[z&&e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}),a?"Save changes":"Create & continue"]})]})})]})}function UMe(s){return ct({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 fFt(){const{user:s}=vs(),t=Qt();return yt({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 gFt(){const s=Qt();return yt({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 EOs(){const s=Qt();return yt({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 TOs(){const s=Qt();return yt({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 MQe(s){const{data:t,error:n}=await q.storage.from("listing-documents").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}function MOs(){for(var s=arguments.length,t=new Array(s),n=0;nr=>{t.forEach(a=>a(r))},t)}const qMe=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function jG(s){const t=Object.prototype.toString.call(s);return t==="[object Window]"||t==="[object global]"}function PQe(s){return"nodeType"in s}function O_(s){var t,n;return s?jG(s)?s:PQe(s)&&(t=(n=s.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function LQe(s){const{Document:t}=O_(s);return s instanceof t}function are(s){return jG(s)?!1:s instanceof O_(s).HTMLElement}function xFt(s){return s instanceof O_(s).SVGElement}function NG(s){return s?jG(s)?s.document:PQe(s)?LQe(s)?s:are(s)||xFt(s)?s.ownerDocument:document:document:document}const X4=qMe?j.useLayoutEffect:j.useEffect;function IQe(s){const t=j.useRef(s);return X4(()=>{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 mee(s,t){t===void 0&&(t=[s]);const n=j.useRef(s);return X4(()=>{n.current!==s&&(n.current=s)},t),n}function ire(s,t){const n=j.useRef();return j.useMemo(()=>{const r=s(n.current);return n.current=r,r},[...t])}function CCe(s){const t=IQe(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 n$e(s){const t=j.useRef();return j.useEffect(()=>{t.current=s},[s]),t.current}let KOe={};function ore(s,t){return j.useMemo(()=>{if(t)return t;const n=KOe[s]==null?0:KOe[s]+1;return KOe[s]=n,s+"-"+n},[s,t])}function yFt(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 Oq=yFt(1),pee=yFt(-1);function LOs(s){return"clientX"in s&&"clientY"in s}function RQe(s){if(!s)return!1;const{KeyboardEvent:t}=O_(s.target);return t&&s instanceof t}function IOs(s){if(!s)return!1;const{TouchEvent:t}=O_(s.target);return t&&s instanceof t}function r$e(s){if(IOs(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 LOs(s)?{x:s.clientX,y:s.clientY}:null}const pP=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[pP.Translate.toString(s),pP.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:t,duration:n,easing:r}=s;return t+" "+n+"ms "+r}}}),wft="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function ROs(s){return s.matches(wft)?s:s.querySelector(wft)}const DOs={display:"none"};function OOs(s){let{id:t,value:n}=s;return Dt.createElement("div",{id:t,style:DOs},n)}function FOs(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 Dt.createElement("div",{id:t,style:a,role:"status","aria-live":r,"aria-atomic":!0},n)}function zOs(){const[s,t]=j.useState("");return{announce:j.useCallback(r=>{r!=null&&t(r)},[]),announcement:s}}const vFt=j.createContext(null);function BOs(s){const t=j.useContext(vFt);j.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(s)},[s,t])}function UOs(){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 qOs={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. `},$Os={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 VOs(s){let{announcements:t=$Os,container:n,hiddenTextDescribedById:r,screenReaderInstructions:a=qOs}=s;const{announce:i,announcement:l}=zOs(),o=ore("DndLiveRegion"),[c,d]=j.useState(!1);if(j.useEffect(()=>{d(!0)},[]),BOs(j.useMemo(()=>({onDragStart(h){let{active:m}=h;i(t.onDragStart({active:m}))},onDragMove(h){let{active:m,over:p}=h;t.onDragMove&&i(t.onDragMove({active:m,over:p}))},onDragOver(h){let{active:m,over:p}=h;i(t.onDragOver({active:m,over:p}))},onDragEnd(h){let{active:m,over:p}=h;i(t.onDragEnd({active:m,over:p}))},onDragCancel(h){let{active:m,over:p}=h;i(t.onDragCancel({active:m,over:p}))}}),[i,t])),!c)return null;const u=Dt.createElement(Dt.Fragment,null,Dt.createElement(OOs,{id:r,value:a.draggable}),Dt.createElement(FOs,{id:o,announcement:l}));return n?tv.createPortal(u,n):u}var Qx;(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"})(Qx||(Qx={}));function ACe(){}function HV(s,t){return j.useMemo(()=>({sensor:s,options:t??{}}),[s,t])}function $Me(){for(var s=arguments.length,t=new Array(s),n=0;n[...t].filter(r=>r!=null),[...t])}const pS=Object.freeze({x:0,y:0});function bFt(s,t){return Math.sqrt(Math.pow(s.x-t.x,2)+Math.pow(s.y-t.y,2))}function _Ft(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return n-r}function HOs(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return r-n}function jft(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 wFt(s,t){if(!s||s.length===0)return null;const[n]=s;return n[t]}function Nft(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 VMe=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=Nft(t,t.left,t.top),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=bFt(Nft(c),a);i.push({id:o,data:{droppableContainer:l,value:d}})}}return i.sort(_Ft)},GOs=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=jft(t),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=jft(c),u=a.reduce((m,p,f)=>m+bFt(d[f],p),0),h=Number((u/4).toFixed(4));i.push({id:o,data:{droppableContainer:l,value:h}})}}return i.sort(_Ft)};function WOs(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=WOs(o,t);c>0&&a.push({id:l,data:{droppableContainer:i,value:c}})}}return a.sort(HOs)};function YOs(s,t,n){return{...s,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function jFt(s,t){return s&&t?{x:s.left-t.left,y:s.top-t.top}:pS}function ZOs(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 XOs=ZOs(1);function QOs(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 JOs(s,t,n){const r=QOs(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 eFs={ignoreTransform:!1};function kG(s,t){t===void 0&&(t=eFs);let n=s.getBoundingClientRect();if(t.ignoreTransform){const{transform:d,transformOrigin:u}=O_(s).getComputedStyle(s);d&&(n=JOs(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 kft(s){return kG(s,{ignoreTransform:!0})}function tFs(s){const t=s.innerWidth,n=s.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function sFs(s,t){return t===void 0&&(t=O_(s).getComputedStyle(s)),t.position==="fixed"}function nFs(s,t){t===void 0&&(t=O_(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 HMe(s,t){const n=[];function r(a){if(t!=null&&n.length>=t||!a)return n;if(LQe(a)&&a.scrollingElement!=null&&!n.includes(a.scrollingElement))return n.push(a.scrollingElement),n;if(!are(a)||xFt(a)||n.includes(a))return n;const i=O_(s).getComputedStyle(a);return a!==s&&nFs(a,i)&&n.push(a),sFs(a,i)?n:r(a.parentNode)}return s?r(s):n}function NFt(s){const[t]=HMe(s,1);return t??null}function YOe(s){return!qMe||!s?null:jG(s)?s:PQe(s)?LQe(s)||s===NG(s).scrollingElement?window:are(s)?s:null:null}function kFt(s){return jG(s)?s.scrollX:s.scrollLeft}function SFt(s){return jG(s)?s.scrollY:s.scrollTop}function a$e(s){return{x:kFt(s),y:SFt(s)}}var X0;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(X0||(X0={}));function CFt(s){return!qMe||!s?!1:s===document.scrollingElement}function AFt(s){const t={x:0,y:0},n=CFt(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 rFs={x:.2,y:.2};function aFs(s,t,n,r,a){let{top:i,left:l,right:o,bottom:c}=n;r===void 0&&(r=10),a===void 0&&(a=rFs);const{isTop:d,isBottom:u,isLeft:h,isRight:m}=AFt(s),p={x:0,y:0},f={x:0,y:0},x={height:t.height*a.y,width:t.width*a.x};return!d&&i<=t.top+x.height?(p.y=X0.Backward,f.y=r*Math.abs((t.top+x.height-i)/x.height)):!u&&c>=t.bottom-x.height&&(p.y=X0.Forward,f.y=r*Math.abs((t.bottom-x.height-c)/x.height)),!m&&o>=t.right-x.width?(p.x=X0.Forward,f.x=r*Math.abs((t.right-x.width-o)/x.width)):!h&&l<=t.left+x.width&&(p.x=X0.Backward,f.x=r*Math.abs((t.left+x.width-l)/x.width)),{direction:p,speed:f}}function iFs(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 EFt(s){return s.reduce((t,n)=>Oq(t,a$e(n)),pS)}function oFs(s){return s.reduce((t,n)=>t+kFt(n),0)}function lFs(s){return s.reduce((t,n)=>t+SFt(n),0)}function cFs(s,t){if(t===void 0&&(t=kG),!s)return;const{top:n,left:r,bottom:a,right:i}=t(s);NFt(s)&&(a<=0||i<=0||n>=window.innerHeight||r>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const dFs=[["x",["left","right"],oFs],["y",["top","bottom"],lFs]];let DQe=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=HMe(n),a=EFt(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[i,l,o]of dFs)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 EQ{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 uFs(s){const{EventTarget:t}=O_(s);return s instanceof t?s:NG(s)}function ZOe(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 j2;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(j2||(j2={}));function Sft(s){s.preventDefault()}function hFs(s){s.stopPropagation()}var Hd;(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"})(Hd||(Hd={}));const TFt={start:[Hd.Space,Hd.Enter],cancel:[Hd.Esc],end:[Hd.Space,Hd.Enter,Hd.Tab]},mFs=(s,t)=>{let{currentCoordinates:n}=t;switch(s.code){case Hd.Right:return{...n,x:n.x+25};case Hd.Left:return{...n,x:n.x-25};case Hd.Down:return{...n,y:n.y+25};case Hd.Up:return{...n,y:n.y-25}}};class GMe{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 EQ(NG(n)),this.windowListeners=new EQ(O_(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(j2.Resize,this.handleCancel),this.windowListeners.add(j2.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(j2.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&cFs(r),n(pS)}handleKeyDown(t){if(RQe(t)){const{active:n,context:r,options:a}=this.props,{keyboardCodes:i=TFt,coordinateGetter:l=mFs,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}:pS;this.referenceCoordinates||(this.referenceCoordinates=u);const h=l(t,{active:n,context:r.current,currentCoordinates:u});if(h){const m=pee(h,u),p={x:0,y:0},{scrollableAncestors:f}=r.current;for(const x of f){const y=t.code,{isTop:v,isRight:b,isLeft:N,isBottom:S,maxScroll:A,minScroll:T}=AFt(x),L=iFs(x),M={x:Math.min(y===Hd.Right?L.right-L.width/2:L.right,Math.max(y===Hd.Right?L.left:L.left+L.width/2,h.x)),y:Math.min(y===Hd.Down?L.bottom-L.height/2:L.bottom,Math.max(y===Hd.Down?L.top:L.top+L.height/2,h.y))},I=y===Hd.Right&&!b||y===Hd.Left&&!N,R=y===Hd.Down&&!S||y===Hd.Up&&!v;if(I&&M.x!==h.x){const z=x.scrollLeft+m.x,$=y===Hd.Right&&z<=A.x||y===Hd.Left&&z>=T.x;if($&&!m.y){x.scrollTo({left:z,behavior:o});return}$?p.x=x.scrollLeft-z:p.x=y===Hd.Right?x.scrollLeft-A.x:x.scrollLeft-T.x,p.x&&x.scrollBy({left:-p.x,behavior:o});break}else if(R&&M.y!==h.y){const z=x.scrollTop+m.y,$=y===Hd.Down&&z<=A.y||y===Hd.Up&&z>=T.y;if($&&!m.x){x.scrollTo({top:z,behavior:o});return}$?p.y=x.scrollTop-z:p.y=y===Hd.Down?x.scrollTop-A.y:x.scrollTop-T.y,p.y&&x.scrollBy({top:-p.y,behavior:o});break}}this.handleMove(t,Oq(pee(h,this.referenceCoordinates),p))}}}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()}}GMe.activators=[{eventName:"onKeyDown",handler:(s,t,n)=>{let{keyboardCodes:r=TFt,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 Cft(s){return!!(s&&"distance"in s)}function Aft(s){return!!(s&&"delay"in s)}class OQe{constructor(t,n,r){var a;r===void 0&&(r=uFs(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=NG(l),this.documentListeners=new EQ(this.document),this.listeners=new EQ(r),this.windowListeners=new EQ(O_(l)),this.initialCoordinates=(a=r$e(i))!=null?a:pS,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(j2.Resize,this.handleCancel),this.windowListeners.add(j2.DragStart,Sft),this.windowListeners.add(j2.VisibilityChange,this.handleCancel),this.windowListeners.add(j2.ContextMenu,Sft),this.documentListeners.add(j2.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Aft(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(Cft(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(j2.Click,hFs,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(j2.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=r$e(t))!=null?n:pS,d=pee(a,c);if(!r&&o){if(Cft(o)){if(o.tolerance!=null&&ZOe(d,o.tolerance))return this.handleCancel();if(ZOe(d,o.distance))return this.handleStart()}if(Aft(o)&&ZOe(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===Hd.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const pFs={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class SG extends OQe{constructor(t){const{event:n}=t,r=NG(n.target);super(t,pFs,r)}}SG.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 fFs={move:{name:"mousemove"},end:{name:"mouseup"}};var i$e;(function(s){s[s.RightClick=2]="RightClick"})(i$e||(i$e={}));class gFs extends OQe{constructor(t){super(t,fFs,NG(t.event.target))}}gFs.activators=[{eventName:"onMouseDown",handler:(s,t)=>{let{nativeEvent:n}=s,{onActivation:r}=t;return n.button===i$e.RightClick?!1:(r==null||r({event:n}),!0)}}];const XOe={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class xFs extends OQe{constructor(t){super(t,XOe)}static setup(){return window.addEventListener(XOe.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(XOe.move.name,t)};function t(){}}}xFs.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 TQ;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(TQ||(TQ={}));var ECe;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})(ECe||(ECe={}));function yFs(s){let{acceleration:t,activator:n=TQ.Pointer,canScroll:r,draggingRect:a,enabled:i,interval:l=5,order:o=ECe.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:u,delta:h,threshold:m}=s;const p=bFs({delta:h,disabled:!i}),[f,x]=POs(),y=j.useRef({x:0,y:0}),v=j.useRef({x:0,y:0}),b=j.useMemo(()=>{switch(n){case TQ.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case TQ.DraggableRect:return a}},[n,a,c]),N=j.useRef(null),S=j.useCallback(()=>{const T=N.current;if(!T)return;const L=y.current.x*v.current.x,M=y.current.y*v.current.y;T.scrollBy(L,M)},[]),A=j.useMemo(()=>o===ECe.TreeOrder?[...d].reverse():d,[o,d]);j.useEffect(()=>{if(!i||!d.length||!b){x();return}for(const T of A){if((r==null?void 0:r(T))===!1)continue;const L=d.indexOf(T),M=u[L];if(!M)continue;const{direction:I,speed:R}=aFs(T,M,b,t,m);for(const z of["x","y"])p[z][I[z]]||(R[z]=0,I[z]=0);if(R.x>0||R.y>0){x(),N.current=T,f(S,l),y.current=R,v.current=I;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(p),f,d,A,u,JSON.stringify(m)])}const vFs={x:{[X0.Backward]:!1,[X0.Forward]:!1},y:{[X0.Backward]:!1,[X0.Forward]:!1}};function bFs(s){let{delta:t,disabled:n}=s;const r=n$e(t);return ire(a=>{if(n||!r||!a)return vFs;const i={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[X0.Backward]:a.x[X0.Backward]||i.x===-1,[X0.Forward]:a.x[X0.Forward]||i.x===1},y:{[X0.Backward]:a.y[X0.Backward]||i.y===-1,[X0.Forward]:a.y[X0.Forward]||i.y===1}}},[n,t,r])}function _Fs(s,t){const n=t!=null?s.get(t):void 0,r=n?n.node.current:null;return ire(a=>{var i;return t==null?null:(i=r??a)!=null?i:null},[r,t])}function wFs(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 fee;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(fee||(fee={}));var o$e;(function(s){s.Optimized="optimized"})(o$e||(o$e={}));const Eft=new Map;function jFs(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=mee(h),p=j.useCallback(function(v){v===void 0&&(v=[]),!m.current&&l(b=>b===null?v:b.concat(v.filter(N=>!b.includes(N))))},[m]),f=j.useRef(null),x=ire(v=>{if(h&&!n)return Eft;if(!v||v===Eft||u.current!==s||i!=null){const b=new Map;for(let N of s){if(!N)continue;if(i&&i.length>0&&!i.includes(N.id)&&N.rect.current){b.set(N.id,N.rect.current);continue}const S=N.node.current,A=S?new DQe(c(S),S):null;N.rect.current=A,A&&b.set(N.id,A)}return b}return v},[s,i,n,h,c]);return j.useEffect(()=>{u.current=s},[s]),j.useEffect(()=>{h||p()},[n,h]),j.useEffect(()=>{i&&i.length>0&&l(null)},[JSON.stringify(i)]),j.useEffect(()=>{h||typeof o!="number"||f.current!==null||(f.current=setTimeout(()=>{p(),f.current=null},o))},[o,h,p,...r]),{droppableRects:x,measureDroppableContainers:p,measuringScheduled:i!=null};function y(){switch(d){case fee.Always:return!1;case fee.BeforeDragging:return n;default:return!n}}}function MFt(s,t){return ire(n=>s?n||(typeof t=="function"?t(s):s):null,[t,s])}function NFs(s,t){return MFt(s,t)}function kFs(s){let{callback:t,disabled:n}=s;const r=IQe(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 WMe(s){let{callback:t,disabled:n}=s;const r=IQe(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 SFs(s){return new DQe(kG(s),s)}function Tft(s,t,n){t===void 0&&(t=SFs);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=kFs({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=WMe({callback:i});return X4(()=>{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 CFs(s){const t=MFt(s);return jFt(s,t)}const Mft=[];function AFs(s){const t=j.useRef(s),n=ire(r=>s?r&&r!==Mft&&s&&t.current&&s.parentNode===t.current.parentNode?r:HMe(s):Mft,[s]);return j.useEffect(()=>{t.current=s},[s]),n}function EFs(s){const[t,n]=j.useState(null),r=j.useRef(s),a=j.useCallback(i=>{const l=YOe(i.target);l&&n(o=>o?(o.set(l,a$e(l)),new Map(o)):null)},[]);return j.useEffect(()=>{const i=r.current;if(s!==i){l(i);const o=s.map(c=>{const d=YOe(c);return d?(d.addEventListener("scroll",a,{passive:!0}),[d,a$e(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=YOe(c);d==null||d.removeEventListener("scroll",a)})}},[a,s]),j.useMemo(()=>s.length?t?Array.from(t.values()).reduce((i,l)=>Oq(i,l),pS):EFt(s):pS,[s,t])}function Pft(s,t){t===void 0&&(t=[]);const n=j.useRef(null);return j.useEffect(()=>{n.current=null},t),j.useEffect(()=>{const r=s!==pS;r&&!n.current&&(n.current=s),!r&&n.current&&(n.current=null)},[s]),n.current?pee(s,n.current):pS}function TFs(s){j.useEffect(()=>{if(!qMe)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 MFs(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 PFt(s){return j.useMemo(()=>s?tFs(s):null,[s])}const Lft=[];function PFs(s,t){t===void 0&&(t=kG);const[n]=s,r=PFt(n?O_(n):null),[a,i]=j.useState(Lft);function l(){i(()=>s.length?s.map(c=>CFt(c)?r:new DQe(t(c),c)):Lft)}const o=WMe({callback:l});return X4(()=>{o==null||o.disconnect(),l(),s.forEach(c=>o==null?void 0:o.observe(c))},[s]),a}function LFs(s){if(!s)return null;if(s.children.length>1)return s;const t=s.children[0];return are(t)?t:s}function IFs(s){let{measure:t}=s;const[n,r]=j.useState(null),a=j.useCallback(d=>{for(const{target:u}of d)if(are(u)){r(h=>{const m=t(u);return h?{...h,width:m.width,height:m.height}:m});break}},[t]),i=WMe({callback:a}),l=j.useCallback(d=>{const u=LFs(d);i==null||i.disconnect(),u&&(i==null||i.observe(u)),r(u?t(u):null)},[t,i]),[o,c]=CCe(l);return j.useMemo(()=>({nodeRef:o,rect:n,setRef:c}),[n,o,c])}const RFs=[{sensor:SG,options:{}},{sensor:GMe,options:{}}],DFs={current:{}},F5e={draggable:{measure:kft},droppable:{measure:kft,strategy:fee.WhileDragging,frequency:o$e.Optimized},dragOverlay:{measure:kG}};class MQ 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 OFs={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new MQ,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:ACe},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:F5e,measureDroppableContainers:ACe,windowRect:null,measuringScheduled:!1},FFs={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:ACe,draggableNodes:new Map,over:null,measureDroppableContainers:ACe},KMe=j.createContext(FFs),LFt=j.createContext(OFs);function zFs(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new MQ}}}function BFs(s,t){switch(t.type){case Qx.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case Qx.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 Qx.DragEnd:case Qx.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Qx.RegisterDroppable:{const{element:n}=t,{id:r}=n,a=new MQ(s.droppable.containers);return a.set(r,n),{...s,droppable:{...s.droppable,containers:a}}}case Qx.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 MQ(s.droppable.containers);return l.set(n,{...i,disabled:a}),{...s,droppable:{...s.droppable,containers:l}}}case Qx.UnregisterDroppable:{const{id:n,key:r}=t,a=s.droppable.containers.get(n);if(!a||r!==a.key)return s;const i=new MQ(s.droppable.containers);return i.delete(n),{...s,droppable:{...s.droppable,containers:i}}}default:return s}}function UFs(s){let{disabled:t}=s;const{active:n,activatorEvent:r,draggableNodes:a}=j.useContext(KMe),i=n$e(r),l=n$e(n==null?void 0:n.id);return j.useEffect(()=>{if(!t&&!r&&i&&l!=null){if(!RQe(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=ROs(u);if(h){h.focus();break}}})}},[r,t,a,l,i]),null}function qFs(s,t){let{transform:n,...r}=t;return s!=null&&s.length?s.reduce((a,i)=>i({transform:a,...r}),n):n}function $Fs(s){return j.useMemo(()=>({draggable:{...F5e.draggable,...s==null?void 0:s.draggable},droppable:{...F5e.droppable,...s==null?void 0:s.droppable},dragOverlay:{...F5e.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 VFs(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;X4(()=>{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=jFt(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=NFt(d);m&&m.scrollBy({top:h.y,left:h.x})}},[t,l,o,r,n])}const IFt=j.createContext({...pS,scaleX:1,scaleY:1});var qT;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(qT||(qT={}));const YMe=j.memo(function(t){var n,r,a,i;let{id:l,accessibility:o,autoScroll:c=!0,children:d,sensors:u=RFs,collisionDetection:h=KOs,measuring:m,modifiers:p,...f}=t;const x=j.useReducer(BFs,void 0,zFs),[y,v]=x,[b,N]=UOs(),[S,A]=j.useState(qT.Uninitialized),T=S===qT.Initialized,{draggable:{active:L,nodes:M,translate:I},droppable:{containers:R}}=y,z=L!=null?M.get(L):null,$=j.useRef({initial:null,translated:null}),H=j.useMemo(()=>{var Gn;return L!=null?{id:L,data:(Gn=z==null?void 0:z.data)!=null?Gn:DFs,rect:$}:null},[L,z]),V=j.useRef(null),[K,Z]=j.useState(null),[Q,le]=j.useState(null),ue=mee(f,Object.values(f)),se=ore("DndDescribedBy",l),ne=j.useMemo(()=>R.getEnabled(),[R]),ie=$Fs(m),{droppableRects:ce,measureDroppableContainers:je,measuringScheduled:be}=jFs(ne,{dragging:T,dependencies:[I.x,I.y],config:ie.droppable}),he=_Fs(M,L),ge=j.useMemo(()=>Q?r$e(Q):null,[Q]),ke=br(),Te=NFs(he,ie.draggable.measure);VFs({activeNode:L!=null?M.get(L):null,config:ke.layoutShiftCompensation,initialRect:Te,measure:ie.draggable.measure});const Me=Tft(he,ie.draggable.measure,Te),Oe=Tft(he?he.parentElement:null),Se=j.useRef({activatorEvent:null,active:null,activeNode:he,collisionRect:null,collisions:null,droppableRects:ce,draggableNodes:M,draggingNode:null,draggingNodeRect:null,droppableContainers:R,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Qe=R.getNodeFor((n=Se.current.over)==null?void 0:n.id),Ae=IFs({measure:ie.dragOverlay.measure}),Fe=(r=Ae.nodeRef.current)!=null?r:he,Ne=T?(a=Ae.rect)!=null?a:Me:null,$e=!!(Ae.nodeRef.current&&Ae.rect),Ve=CFs($e?null:Me),qe=PFt(Fe?O_(Fe):null),Ze=AFs(T?Qe??he:null),Ue=PFs(Ze),Ye=qFs(p,{transform:{x:I.x-Ve.x,y:I.y-Ve.y,scaleX:1,scaleY:1},activatorEvent:Q,active:H,activeNodeRect:Me,containerNodeRect:Oe,draggingNodeRect:Ne,over:Se.current.over,overlayNodeRect:Ae.rect,scrollableAncestors:Ze,scrollableAncestorRects:Ue,windowRect:qe}),Ge=ge?Oq(ge,I):null,He=EFs(Ze),tt=Pft(He),pt=Pft(He,[Me]),ft=Oq(Ye,tt),qt=Ne?XOs(Ne,Ye):null,Ut=H&&qt?h({active:H,collisionRect:qt,droppableRects:ce,droppableContainers:ne,pointerCoordinates:Ge}):null,Wt=wFt(Ut,"id"),[us,zt]=j.useState(null),bt=$e?Ye:Oq(Ye,pt),As=YOs(bt,(i=us==null?void 0:us.rect)!=null?i:null,Me),vt=j.useRef(null),Ws=j.useCallback((Gn,On)=>{let{sensor:Rr,options:cr}=On;if(V.current==null)return;const Hs=M.get(V.current);if(!Hs)return;const _r=Gn.nativeEvent,nn=new Rr({active:V.current,activeNode:Hs,event:_r,options:cr,context:Se,onAbort(es){if(!M.get(es))return;const{onDragAbort:Hn}=ue.current,kn={id:es};Hn==null||Hn(kn),b({type:"onDragAbort",event:kn})},onPending(es,ar,Hn,kn){if(!M.get(es))return;const{onDragPending:sn}=ue.current,un={id:es,constraint:ar,initialCoordinates:Hn,offset:kn};sn==null||sn(un),b({type:"onDragPending",event:un})},onStart(es){const ar=V.current;if(ar==null)return;const Hn=M.get(ar);if(!Hn)return;const{onDragStart:kn}=ue.current,Un={activatorEvent:_r,active:{id:ar,data:Hn.data,rect:$}};tv.unstable_batchedUpdates(()=>{kn==null||kn(Un),A(qT.Initializing),v({type:Qx.DragStart,initialCoordinates:es,active:ar}),b({type:"onDragStart",event:Un}),Z(vt.current),le(_r)})},onMove(es){v({type:Qx.DragMove,coordinates:es})},onEnd:Zn(Qx.DragEnd),onCancel:Zn(Qx.DragCancel)});vt.current=nn;function Zn(es){return async function(){const{active:Hn,collisions:kn,over:Un,scrollAdjustedTranslate:sn}=Se.current;let un=null;if(Hn&&sn){const{cancelDrop:Ar}=ue.current;un={activatorEvent:_r,active:Hn,collisions:kn,delta:sn,over:Un},es===Qx.DragEnd&&typeof Ar=="function"&&await Promise.resolve(Ar(un))&&(es=Qx.DragCancel)}V.current=null,tv.unstable_batchedUpdates(()=>{v({type:es}),A(qT.Uninitialized),zt(null),Z(null),le(null),vt.current=null;const Ar=es===Qx.DragEnd?"onDragEnd":"onDragCancel";if(un){const fs=ue.current[Ar];fs==null||fs(un),b({type:Ar,event:un})}})}}},[M]),on=j.useCallback((Gn,On)=>(Rr,cr)=>{const Hs=Rr.nativeEvent,_r=M.get(cr);if(V.current!==null||!_r||Hs.dndKit||Hs.defaultPrevented)return;const nn={active:_r};Gn(Rr,On.options,nn)===!0&&(Hs.dndKit={capturedBy:On.sensor},V.current=cr,Ws(Rr,On))},[M,Ws]),Ms=wFs(u,on);TFs(u),X4(()=>{Me&&S===qT.Initializing&&A(qT.Initialized)},[Me,S]),j.useEffect(()=>{const{onDragMove:Gn}=ue.current,{active:On,activatorEvent:Rr,collisions:cr,over:Hs}=Se.current;if(!On||!Rr)return;const _r={active:On,activatorEvent:Rr,collisions:cr,delta:{x:ft.x,y:ft.y},over:Hs};tv.unstable_batchedUpdates(()=>{Gn==null||Gn(_r),b({type:"onDragMove",event:_r})})},[ft.x,ft.y]),j.useEffect(()=>{const{active:Gn,activatorEvent:On,collisions:Rr,droppableContainers:cr,scrollAdjustedTranslate:Hs}=Se.current;if(!Gn||V.current==null||!On||!Hs)return;const{onDragOver:_r}=ue.current,nn=cr.get(Wt),Zn=nn&&nn.rect.current?{id:nn.id,rect:nn.rect.current,data:nn.data,disabled:nn.disabled}:null,es={active:Gn,activatorEvent:On,collisions:Rr,delta:{x:Hs.x,y:Hs.y},over:Zn};tv.unstable_batchedUpdates(()=>{zt(Zn),_r==null||_r(es),b({type:"onDragOver",event:es})})},[Wt]),X4(()=>{Se.current={activatorEvent:Q,active:H,activeNode:he,collisionRect:qt,collisions:Ut,droppableRects:ce,draggableNodes:M,draggingNode:Fe,draggingNodeRect:Ne,droppableContainers:R,over:us,scrollableAncestors:Ze,scrollAdjustedTranslate:ft},$.current={initial:Ne,translated:qt}},[H,he,Ut,qt,M,Fe,Ne,ce,R,us,Ze,ft]),yFs({...ke,delta:I,draggingRect:qt,pointerCoordinates:Ge,scrollableAncestors:Ze,scrollableAncestorRects:Ue});const dn=j.useMemo(()=>({active:H,activeNode:he,activeNodeRect:Me,activatorEvent:Q,collisions:Ut,containerNodeRect:Oe,dragOverlay:Ae,draggableNodes:M,droppableContainers:R,droppableRects:ce,over:us,measureDroppableContainers:je,scrollableAncestors:Ze,scrollableAncestorRects:Ue,measuringConfiguration:ie,measuringScheduled:be,windowRect:qe}),[H,he,Me,Q,Ut,Oe,Ae,M,R,ce,us,je,Ze,Ue,ie,be,qe]),rn=j.useMemo(()=>({activatorEvent:Q,activators:Ms,active:H,activeNodeRect:Me,ariaDescribedById:{draggable:se},dispatch:v,draggableNodes:M,over:us,measureDroppableContainers:je}),[Q,Ms,H,Me,v,se,M,us,je]);return Dt.createElement(vFt.Provider,{value:N},Dt.createElement(KMe.Provider,{value:rn},Dt.createElement(LFt.Provider,{value:dn},Dt.createElement(IFt.Provider,{value:As},d)),Dt.createElement(UFs,{disabled:(o==null?void 0:o.restoreFocus)===!1})),Dt.createElement(VOs,{...o,hiddenTextDescribedById:se}));function br(){const Gn=(K==null?void 0:K.autoScrollEnabled)===!1,On=typeof c=="object"?c.enabled===!1:c===!1,Rr=T&&!Gn&&!On;return typeof c=="object"?{...c,enabled:Rr}:{enabled:Rr}}}),HFs=j.createContext(null),Ift="button",GFs="Draggable";function WFs(s){let{id:t,data:n,disabled:r=!1,attributes:a}=s;const i=ore(GFs),{activators:l,activatorEvent:o,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:h,over:m}=j.useContext(KMe),{role:p=Ift,roleDescription:f="draggable",tabIndex:x=0}=a??{},y=(c==null?void 0:c.id)===t,v=j.useContext(y?IFt:HFs),[b,N]=CCe(),[S,A]=CCe(),T=MFs(l,t),L=mee(n);X4(()=>(h.set(t,{id:t,key:i,node:b,activatorNode:S,data:L}),()=>{const I=h.get(t);I&&I.key===i&&h.delete(t)}),[h,t]);const M=j.useMemo(()=>({role:p,tabIndex:x,"aria-disabled":r,"aria-pressed":y&&p===Ift?!0:void 0,"aria-roledescription":f,"aria-describedby":u.draggable}),[r,p,x,y,f,u.draggable]);return{active:c,activatorEvent:o,activeNodeRect:d,attributes:M,isDragging:y,listeners:r?void 0:T,node:b,over:m,setNodeRef:N,setActivatorNodeRef:A,transform:v}}function KFs(){return j.useContext(LFt)}const YFs="Droppable",ZFs={timeout:25};function XFs(s){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:a}=s;const i=ore(YFs),{active:l,dispatch:o,over:c,measureDroppableContainers:d}=j.useContext(KMe),u=j.useRef({disabled:n}),h=j.useRef(!1),m=j.useRef(null),p=j.useRef(null),{disabled:f,updateMeasurementsFor:x,timeout:y}={...ZFs,...a},v=mee(x??r),b=j.useCallback(()=>{if(!h.current){h.current=!0;return}p.current!=null&&clearTimeout(p.current),p.current=setTimeout(()=>{d(Array.isArray(v.current)?v.current:[v.current]),p.current=null},y)},[y]),N=WMe({callback:b,disabled:f||!l}),S=j.useCallback((M,I)=>{N&&(I&&(N.unobserve(I),h.current=!1),M&&N.observe(M))},[N]),[A,T]=CCe(S),L=mee(t);return j.useEffect(()=>{!N||!A.current||(N.disconnect(),h.current=!1,N.observe(A.current))},[A,N]),j.useEffect(()=>(o({type:Qx.RegisterDroppable,element:{id:r,key:i,disabled:n,node:A,rect:m,data:L}}),()=>o({type:Qx.UnregisterDroppable,key:i,id:r})),[r]),j.useEffect(()=>{n!==u.current.disabled&&(o({type:Qx.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:T}}function ZMe(s,t,n){const r=s.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function QFs(s,t){return s.reduce((n,r,a)=>{const i=t.get(r);return i&&(n[a]=i),n},Array(s.length))}function Ioe(s){return s!==null&&s>=0}function JFs(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=t7s(n,l,a);if(l===a){const d=n[i];return d?{x:aa&&l<=i?{x:-o.width-c,y:0,...Roe}:l=i?{x:o.width+c,y:0,...Roe}:{x:0,y:0,...Roe}};function t7s(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=ZMe(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}},Doe={scaleX:1,scaleY:1},s7s=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,...Doe}:a=l?{x:0,y:o.height+c,...Doe}:{x:0,y:0,...Doe}};function n7s(s,t,n){const r=s[t],a=s[t-1],i=s[t+1];return r?nr.map(T=>typeof T=="object"&&"id"in T?T.id:T),[r]),f=l!=null,x=l?p.indexOf(l.id):-1,y=d?p.indexOf(d.id):-1,v=j.useRef(p),b=!JFs(p,v.current),N=y!==-1&&x===-1||b,S=e7s(i);X4(()=>{b&&f&&u(p)},[b,p,f,u]),j.useEffect(()=>{v.current=p},[p]);const A=j.useMemo(()=>({activeIndex:x,containerId:h,disabled:S,disableTransforms:N,items:p,overIndex:y,useDragOverlay:m,sortedRects:QFs(p,c),strategy:a}),[x,h,S.draggable,S.droppable,N,p,y,c,m,a]);return Dt.createElement(DFt.Provider,{value:A},t)}const r7s=s=>{let{id:t,items:n,activeIndex:r,overIndex:a}=s;return ZMe(n,r,a).indexOf(t)},a7s=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},i7s={duration:200,easing:"ease"},OFt="transform",o7s=pP.Transition.toString({property:OFt,duration:0,easing:"linear"}),l7s={roleDescription:"sortable"};function c7s(s){let{disabled:t,index:n,node:r,rect:a}=s;const[i,l]=j.useState(null),o=j.useRef(n);return X4(()=>{if(!t&&n!==o.current&&r.current){const c=a.current;if(c){const d=kG(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 QMe(s){let{animateLayoutChanges:t=a7s,attributes:n,disabled:r,data:a,getNewIndex:i=r7s,id:l,strategy:o,resizeObserverConfig:c,transition:d=i7s}=s;const{items:u,containerId:h,activeIndex:m,disabled:p,disableTransforms:f,sortedRects:x,overIndex:y,useDragOverlay:v,strategy:b}=j.useContext(DFt),N=d7s(r,p),S=u.indexOf(l),A=j.useMemo(()=>({sortable:{containerId:h,index:S,items:u},...a}),[h,a,S,u]),T=j.useMemo(()=>u.slice(u.indexOf(l)),[u,l]),{rect:L,node:M,isOver:I,setNodeRef:R}=XFs({id:l,data:A,disabled:N.droppable,resizeObserverConfig:{updateMeasurementsFor:T,...c}}),{active:z,activatorEvent:$,activeNodeRect:H,attributes:V,setNodeRef:K,listeners:Z,isDragging:Q,over:le,setActivatorNodeRef:ue,transform:se}=WFs({id:l,data:A,attributes:{...l7s,...n},disabled:N.draggable}),ne=MOs(R,K),ie=!!z,ce=ie&&!f&&Ioe(m)&&Ioe(y),je=!v&&Q,be=je&&ce?se:null,ge=ce?be??(o??b)({rects:x,activeNodeRect:H,activeIndex:m,overIndex:y,index:S}):null,ke=Ioe(m)&&Ioe(y)?i({id:l,items:u,activeIndex:m,overIndex:y}):S,Te=z==null?void 0:z.id,Me=j.useRef({activeId:Te,items:u,newIndex:ke,containerId:h}),Oe=u!==Me.current.items,Se=t({active:z,containerId:h,isDragging:Q,isSorting:ie,id:l,index:S,items:u,newIndex:Me.current.newIndex,previousItems:Me.current.items,previousContainerId:Me.current.containerId,transition:d,wasDragging:Me.current.activeId!=null}),Qe=c7s({disabled:!Se,index:S,node:M,rect:L});return j.useEffect(()=>{ie&&Me.current.newIndex!==ke&&(Me.current.newIndex=ke),h!==Me.current.containerId&&(Me.current.containerId=h),u!==Me.current.items&&(Me.current.items=u)},[ie,ke,h,u]),j.useEffect(()=>{if(Te===Me.current.activeId)return;if(Te!=null&&Me.current.activeId==null){Me.current.activeId=Te;return}const Fe=setTimeout(()=>{Me.current.activeId=Te},50);return()=>clearTimeout(Fe)},[Te]),{active:z,activeIndex:m,attributes:V,data:A,rect:L,index:S,newIndex:ke,items:u,isOver:I,isSorting:ie,isDragging:Q,listeners:Z,node:M,overIndex:y,over:le,setNodeRef:ne,setActivatorNodeRef:ue,setDroppableNodeRef:R,setDraggableNodeRef:K,transform:Qe??ge,transition:Ae()};function Ae(){if(Qe||Oe&&Me.current.newIndex===S)return o7s;if(!(je&&!RQe($)||!d)&&(ie||Se))return pP.Transition.toString({...d,property:OFt})}}function d7s(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 TCe(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 u7s=[Hd.Down,Hd.Right,Hd.Up,Hd.Left],FFt=(s,t)=>{let{context:{active:n,collisionRect:r,droppableRects:a,droppableContainers:i,over:l,scrollableAncestors:o}}=t;if(u7s.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 Hd.Down:r.topm.top&&c.push(h);break;case Hd.Left:r.left>m.left&&c.push(h);break;case Hd.Right:r.left1&&(u=d[1].id),u!=null){const h=i.get(n.id),m=i.get(u),p=m?a.get(m.id):null,f=m==null?void 0:m.node.current;if(f&&p&&h&&m){const y=HMe(f).some((T,L)=>o[L]!==T),v=zFt(h,m),b=h7s(h,m),N=y||!v?{x:0,y:0}:{x:b?r.width-p.width:0,y:b?r.height-p.height:0},S={x:p.left,y:p.top};return N.x&&N.y?S:pee(S,N)}}}};function zFt(s,t){return!TCe(s)||!TCe(t)?!1:s.data.current.sortable.containerId===t.data.current.sortable.containerId}function h7s(s,t){return!TCe(s)||!TCe(t)||!zFt(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(er,{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(Ua,{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 BFt({photos:s,uploading:t,onUpload:n,onRemove:r,onReorder:a,onSetPrimary:i}){var h,m;const l=$Me(HV(SG,{activationConstraint:{distance:5}})),o=[...s].sort((p,f)=>(p.sort_order??0)-(f.sort_order??0)),c=((h=o.find(p=>p.is_primary))==null?void 0:h.id)??null,d=c??((m=o[0])==null?void 0:m.id),u=p=>{var T;const{active:f,over:x}=p;if(!x||f.id===x.id)return;const y=o.findIndex(L=>L.id===f.id),v=o.findIndex(L=>L.id===x.id),b=[...o],[N]=b.splice(y,1);b.splice(v,0,N);const S=c??((T=b[0])==null?void 0:T.id),A=b.map((L,M)=>({...L,sort_order:M,is_primary:L.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(YMe,{sensors:l,collisionDetection:VMe,onDragEnd:u,children:e.jsx(XMe,{items:o.map(p=>p.id),strategy:lre,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[o.map(p=>e.jsx(m7s,{photo:p,isPrimary:p.id===d,onRemove:r,onSetPrimary:i},p.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(Et,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(qa,{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:p=>n(p.target.files),disabled:t})]})]})})})]})}function JMe({open:s,onOpenChange:t,listingId:n,listingSlug:r,listingTitle:a,isCommercial:i=!1}){const{user:l}=vs(),[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(!1);j.useEffect(()=>{(async()=>{if(!(!s||!l)){u(!0);try{const{data:v,error:b}=await q.from("listing_shares").select("id, share_token, click_count, lead_count").eq("listing_id",n).eq("sharing_agent_id",l.id).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(b)throw b;if(v&&v.share_token)c(v);else if(v&&!v.share_token){const{data:N,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(N)}else{const{data:N,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(N)}}catch(v){console.error("Error creating share link:",v),re.error("Failed to generate share link")}finally{u(!1)}}})()},[s,l,n]);const p=o!=null&&o.share_token?`${i?bAs:"https://listings.relevelup.com"}/${r||n}?ref=${o.share_token}`:"",f=async()=>{try{await navigator.clipboard.writeText(p),m(!0),re.success("Link copied to clipboard!"),setTimeout(()=>m(!1),2e3)}catch{re.error("Failed to copy link")}},x=y=>{const v=encodeURIComponent(p),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(Ds,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(cn,{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(te,{children:"Your Referral Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:d?"Generating...":p,readOnly:!0,className:"font-mono text-sm"}),e.jsx(U,{onClick:f,disabled:d||!p,variant:h?"default":"outline",children:h?e.jsx(Xr,{className:"h-4 w-4"}):e.jsx(Pa,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Share via"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{variant:"outline",className:"flex-1",onClick:()=>x("email"),disabled:d,children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Email"]}),e.jsxs(U,{variant:"outline",className:"flex-1",onClick:()=>x("text"),disabled:d,children:[e.jsx(Ki,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(U,{variant:"outline",className:"flex-1",onClick:()=>x("facebook"),disabled:d,children:[e.jsx(zp,{className:"h-4 w-4 mr-2"}),"Facebook"]})]})]}),o&&(o.click_count>0||o.lead_count>0)&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx(te,{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(xa,{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(Bn,{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 p7s=Object.defineProperty,MCe=Object.getOwnPropertySymbols,UFt=Object.prototype.hasOwnProperty,qFt=Object.prototype.propertyIsEnumerable,Rft=(s,t,n)=>t in s?p7s(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,l$e=(s,t)=>{for(var n in t||(t={}))UFt.call(t,n)&&Rft(s,n,t[n]);if(MCe)for(var n of MCe(t))qFt.call(t,n)&&Rft(s,n,t[n]);return s},c$e=(s,t)=>{var n={};for(var r in s)UFt.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&MCe)for(var r of MCe(s))t.indexOf(r)<0&&qFt.call(s,r)&&(n[r]=s[r]);return n};/** * @license QR Code generator library (TypeScript) * Copyright (c) Project Nayuki. * SPDX-License-Identifier: MIT */var S7;(s=>{const t=class vd{constructor(c,d,u,h){if(this.version=c,this.errorCorrectionLevel=d,this.modules=[],this.isFunction=[],cvd.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 f=0;f7)throw new RangeError("Invalid value");let f,x;for(f=u;;f++){const N=vd.getNumDataCodewords(f,d)*8,S=l.getTotalBits(c,f);if(S<=N){x=S;break}if(f>=h)throw new RangeError("Data too long")}for(const N of[vd.Ecc.MEDIUM,vd.Ecc.QUARTILE,vd.Ecc.HIGH])p&&x<=vd.getNumDataCodewords(f,N)*8&&(d=N);let y=[];for(const N of c){n(N.mode.modeBits,4,y),n(N.numChars,N.mode.numCharCountBits(f),y);for(const S of N.getData())y.push(S)}a(y.length==x);const v=vd.getNumDataCodewords(f,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 N=236;y.lengthb[S>>>3]|=N<<7-(S&7)),new vd(f,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,p=Math.floor(u/3);this.setFunctionModule(m,p,h),this.setFunctionModule(p,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)),p=c+h,f=d+u;0<=p&&p{(N!=x-m||A>=f)&&b.push(S[N])});return a(b.length==p),b}drawCodewords(c){if(c.length!=Math.floor(vd.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(f,x),p||(c+=this.finderPenaltyCountPatterns(x)*vd.PENALTY_N3),p=this.modules[m][y],f=1);c+=this.finderPenaltyTerminateAndCount(p,f,x)*vd.PENALTY_N3}for(let m=0;m5&&c++):(this.finderPenaltyAddHistory(f,x),p||(c+=this.finderPenaltyCountPatterns(x)*vd.PENALTY_N3),p=this.modules[y][m],f=1);c+=this.finderPenaltyTerminateAndCount(p,f,x)*vd.PENALTY_N3}for(let m=0;mp+(f?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*vd.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.lengthvd.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(vd.getNumRawDataModules(c)/8)-vd.ECC_CODEWORDS_PER_BLOCK[d.ordinal][c]*vd.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((p,f)=>u[f]^=vd.reedSolomonMultiply(p,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 Gf{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 Gf(Gf.Mode.BYTE,c.length,d)}static makeNumeric(c){if(!Gf.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={}))})(S7||(S7={}));(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={}))})(S7||(S7={}));var vU=S7;/** * @license qrcode.react * Copyright (c) Paul O'Shannessy * SPDX-License-Identifier: ISC */var f7s={L:vU.QrCode.Ecc.LOW,M:vU.QrCode.Ecc.MEDIUM,Q:vU.QrCode.Ecc.QUARTILE,H:vU.QrCode.Ecc.HIGH},$Ft=128,VFt="L",HFt="#FFFFFF",GFt="#000000",WFt=!1,KFt=1,g7s=4,x7s=0,y7s=.1;function YFt(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 ZFt(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 v7s(s,t,n,r){if(r==null)return null;const a=s.length+n*2,i=Math.floor(t*y7s),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 f=Math.floor(d),x=Math.floor(u),y=Math.ceil(o+d-f),v=Math.ceil(c+u-x);m={x:f,y:x,w:y,h:v}}const p=r.crossOrigin;return{x:d,y:u,h:c,w:o,excavation:m,opacity:h,crossOrigin:p}}function b7s(s,t){return t!=null?Math.max(Math.floor(t),0):s?g7s:x7s}function XFt({value:s,level:t,minVersion:n,includeMargin:r,marginSize:a,imageSettings:i,size:l,boostLevel:o}){let c=Dt.useMemo(()=>{const f=(Array.isArray(s)?s:[s]).reduce((x,y)=>(x.push(...vU.QrSegment.makeSegments(y)),x),[]);return vU.QrCode.encodeSegments(f,f7s[t],n,void 0,void 0,o)},[s,t,n,o]);const{cells:d,margin:u,numCells:h,calculatedImageSettings:m}=Dt.useMemo(()=>{let p=c.getModules();const f=b7s(r,a),x=p.length+f*2,y=v7s(p,l,f,i);return{cells:p,margin:f,numCells:x,calculatedImageSettings:y}},[c,l,i,r,a]);return{qrcode:c,margin:u,cells:d,numCells:h,calculatedImageSettings:m}}var _7s=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),w7s=Dt.forwardRef(function(t,n){const r=t,{value:a,size:i=$Ft,level:l=VFt,bgColor:o=HFt,fgColor:c=GFt,includeMargin:d=WFt,minVersion:u=KFt,boostLevel:h,marginSize:m,imageSettings:p}=r,x=c$e(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:y}=x,v=c$e(x,["style"]),b=p==null?void 0:p.src,N=Dt.useRef(null),S=Dt.useRef(null),A=Dt.useCallback(V=>{N.current=V,typeof n=="function"?n(V):n&&(n.current=V)},[n]),[T,L]=Dt.useState(!1),{margin:M,cells:I,numCells:R,calculatedImageSettings:z}=XFt({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:m,imageSettings:p,size:i});Dt.useEffect(()=>{if(N.current!=null){const V=N.current,K=V.getContext("2d");if(!K)return;let Z=I;const Q=S.current,le=z!=null&&Q!==null&&Q.complete&&Q.naturalHeight!==0&&Q.naturalWidth!==0;le&&z.excavation!=null&&(Z=ZFt(I,z.excavation));const ue=window.devicePixelRatio||1;V.height=V.width=i*ue;const se=i/R*ue;K.scale(se,se),K.fillStyle=o,K.fillRect(0,0,R,R),K.fillStyle=c,_7s?K.fill(new Path2D(YFt(Z,M))):I.forEach(function(ne,ie){ne.forEach(function(ce,je){ce&&K.fillRect(je+M,ie+M,1,1)})}),z&&(K.globalAlpha=z.opacity),le&&K.drawImage(Q,z.x+M,z.y+M,z.w,z.h)}}),Dt.useEffect(()=>{L(!1)},[b]);const $=l$e({height:i,width:i},y);let H=null;return b!=null&&(H=Dt.createElement("img",{src:b,key:b,style:{display:"none"},onLoad:()=>{L(!0)},ref:S,crossOrigin:z==null?void 0:z.crossOrigin})),Dt.createElement(Dt.Fragment,null,Dt.createElement("canvas",l$e({style:$,height:i,width:i,ref:A,role:"img"},v)),H)});w7s.displayName="QRCodeCanvas";var fS=Dt.forwardRef(function(t,n){const r=t,{value:a,size:i=$Ft,level:l=VFt,bgColor:o=HFt,fgColor:c=GFt,includeMargin:d=WFt,minVersion:u=KFt,boostLevel:h,title:m,marginSize:p,imageSettings:f}=r,x=c$e(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:y,cells:v,numCells:b,calculatedImageSettings:N}=XFt({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:p,imageSettings:f,size:i});let S=v,A=null;f!=null&&N!=null&&(N.excavation!=null&&(S=ZFt(v,N.excavation)),A=Dt.createElement("image",{href:f.src,height:N.h,width:N.w,x:N.x+y,y:N.y+y,preserveAspectRatio:"none",opacity:N.opacity,crossOrigin:N.crossOrigin}));const T=YFt(S,y);return Dt.createElement("svg",l$e({height:i,width:i,viewBox:`0 0 ${b} ${b}`,ref:n,role:"img"},x),!!m&&Dt.createElement("title",null,m),Dt.createElement("path",{fill:o,d:`M0,0 h${b}v${b}H0z`,shapeRendering:"crispEdges"}),Dt.createElement("path",{fill:c,d:T,shapeRendering:"crispEdges"}),A)});fS.displayName="QRCodeSVG";function QFt({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"}),p=document.createElement("a");p.href=URL.createObjectURL(m),p.download=`${o}.svg`,p.click(),URL.revokeObjectURL(p.href)},u=(h=1024)=>{const m=c();if(!m)return;const p=new Image,f=new Blob([m],{type:"image/svg+xml;charset=utf-8"}),x=URL.createObjectURL(f);p.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(p,0,0,h,h),URL.revokeObjectURL(x),y.toBlob(b=>{if(!b)return;const N=document.createElement("a");N.href=URL.createObjectURL(b),N.download=`${o}.png`,N.click(),URL.revokeObjectURL(N.href)},"image/png"))},p.src=x};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(fS,{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(U,{onClick:()=>u(),className:"gap-2",children:[e.jsx(pi,{className:"h-4 w-4"}),"PNG"]}),e.jsxs(U,{variant:"outline",onClick:d,className:"gap-2",children:[e.jsx(pi,{className:"h-4 w-4"}),"SVG"]}),e.jsxs(U,{variant:"outline",onClick:async()=>{await navigator.clipboard.writeText(n),re.success("Link copied")},className:"gap-2",children:[e.jsx(Pa,{className:"h-4 w-4"}),"Copy link"]})]})]})})}var j7s="Separator",Dft="horizontal",N7s=["horizontal","vertical"],JFt=j.forwardRef((s,t)=>{const{decorative:n,orientation:r=Dft,...a}=s,i=k7s(r)?r:Dft,o=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return e.jsx(si.div,{"data-orientation":i,...o,...a,ref:t})});JFt.displayName=j7s;function k7s(s){return N7s.includes(s)}var e7t=JFt;const hc=j.forwardRef(({className:s,orientation:t="horizontal",decorative:n=!0,...r},a)=>e.jsx(e7t,{ref:a,decorative:n,orientation:t,className:Mt("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",s),...r}));hc.displayName=e7t.displayName;const F_=()=>ct({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}}),t7t=()=>{const s=Sa(),t=1e3;return ct({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(p=>p.id),o=Array.from(new Set(i.map(p=>p.lead_source_id).filter(p=>!!p))),c=(p,f=250)=>{const x=[];for(let y=0;y{const{data:f,error:x}=await q.from("innercircle_contact_tags").select("id, contact_id, relationship_type_id, relationship_type:relationship_types(*)").in("contact_id",p);if(x)throw x;return f??[]})),Promise.all(c(o).map(async p=>{const{data:f,error:x}=await q.from("lead_sources").select("id, name").in("id",p);if(x)throw x;return f??[]}))]),h=new Map;d.flat().forEach(p=>{const f=h.get(p.contact_id)??[];f.push(p),h.set(p.contact_id,f)});const m=new Map(u.flat().map(p=>[p.id,p]));return i.map(p=>({...p,lead_source_ref:p.lead_source_id?m.get(p.lead_source_id)??null:null,tags:h.get(p.id)??[]}))},enabled:!!t,staleTime:10*60*1e3})},S7s=s=>ct({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}),s7t=()=>{const s=Sa();return ct({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})},ePe=()=>{const s=Qt(),t=Sa();return yt({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"]}),ka({title:"Contact created successfully"})},onError:n=>{ka({title:"Error creating contact",description:n.message,variant:"destructive"})}})},FQe=()=>{const s=Qt();return yt({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"]}),ka({title:"Contact updated successfully"})},onError:t=>{ka({title:"Error updating contact",description:t.message,variant:"destructive"})}})},n7t=()=>{const s=Qt();return yt({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"]}),ka({title:"Spouse link updated"})},onError:t=>{ka({title:"Error linking spouse",description:t.message,variant:"destructive"})}})},zQe=()=>{const s=Qt();return yt({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"]}),ka({title:"Contact deleted successfully"})},onError:t=>{ka({title:"Error deleting contact",description:t.message,variant:"destructive"})}})},cre=()=>ct({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}}),C7s=s=>ct({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}}),A7s=()=>ct({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}}),E7s=()=>{const s=Qt(),t=Sa();return yt({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"]}),ka({title:"Plan created successfully"})},onError:n=>{ka({title:"Error creating plan",description:n.message,variant:"destructive"})}})},T7s=()=>{const s=Qt(),t=Sa();return yt({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"]}),ka({title:"Plan duplicated successfully",description:"You can now edit your copy of this plan."})},onError:n=>{ka({title:"Error duplicating plan",description:n.message,variant:"destructive"})}})},M7s=()=>{const s=Qt();return yt({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"]}),ka({title:"Plan updated successfully"})}})},P7s=()=>{const s=Qt();return yt({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"]}),ka({title:"Plan deleted successfully"})}})},L7s=()=>{const s=Qt();return yt({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"]}),ka({title:"Plan schedule updated"})}})},I7s=()=>{const s=Qt();return yt({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"]}),ka({title:"Script created successfully"})},onError:t=>{ka({title:"Error creating script",description:t.message,variant:"destructive"})}})},R7s=()=>{const s=Sa();return ct({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})},D7s=()=>{const s=Qt(),t=Sa();return yt({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"]}),ka({title:"Plan enrollment updated"})}})},CG=(s=7)=>{const t=Sa();return ct({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})},r7t=()=>{const s=Sa();return ct({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})},O7s=(s=90)=>{const{data:t}=Cb(),{data:n}=r7t();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=Qt(),t=Sa();return yt({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"]}),ka({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{}}})},a7t="agentos_weekly_touch_goal",Oft=20,i7t=()=>{if(typeof window>"u")return Oft;const s=localStorage.getItem(a7t);if(s){const t=parseInt(s,10);if(!isNaN(t)&&t>0)return t}return Oft},F7s=s=>{localStorage.setItem(a7t,s.toString())},sPe=()=>{const{data:s}=CG(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=i7t();return{actionsThisWeek:r,weeklyGoal:i,streak:a,progress:Math.min(r/i*100,100)}},z7s=()=>{const s=Sa();return ct({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})},B7s=()=>{const s=Qt();return Sa(),yt({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&&ka({title:`${t} contact(s) enrolled in plans`})}})},BQe=()=>{const s=Sa(),{data:t}=z7s(),{data:n}=CG(30);return ct({queryKey:["today-actions",s,t==null?void 0:t.length,n==null?void 0:n.length],queryFn:async()=>{var f;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(!((f=x.plan)!=null&&f.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,N=x.plan.items.find(S=>S.month_number===b);if(N&&N.action_type){const S=`${x.contact_id}-${N.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:N.action_type,script:N.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 U7s(){const{user:s}=vs(),{limitFor:t,isRestricted:n}=_S(),r=n?t("mass_email"):null,{data:a=0,refetch:i}=ct({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 q7s({onSelect:s}){const{user:t}=vs(),[n,r]=j.useState("root"),[a,i]=j.useState(null),{data:l=[],isLoading:o}=ct({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}=ct({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}=ct({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),p=u.filter(v=>v.is_shared),f=l.find(v=>v.id===a);if(o)return e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(Et,{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(So,{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(gi,{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(fl,{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:[p.length," team template",p.length===1?"":"s"]})]})]}),e.jsx(gi,{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(gi,{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(rd,{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(So,{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(Et,{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(cn,{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(Gi,{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(fl,{className:"h-3.5 w-3.5"})," Shared Library"]}),h?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(Et,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No shared templates yet."}):e.jsx(Gi,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:p.map(v=>e.jsxs("button",{onClick:()=>x(v),className:"w-full p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:v.name}),e.jsx(Be,{variant:"secondary",className:"text-[10px] shrink-0",children:"Shared"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:v.subject||"(no subject)"})]},v.id))})})]}):e.jsxs("div",{className:"space-y-2",children:[y,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx("span",{children:f==null?void 0:f.icon})," ",f==null?void 0:f.name]}),d?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(Et,{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(Gi,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:c.map(v=>e.jsxs("button",{onClick:()=>s(v),className:"w-full p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"font-medium text-sm",children:v.title}),v.tone&&e.jsx(Be,{variant:"secondary",className:"text-[10px] shrink-0",children:v.tone})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:v.subject})]},v.id))})})]})}function AG(){var a;const{user:s}=vs(),{data:t,isLoading:n}=ct({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 dre(){const{user:s}=vs();return ct({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 nPe({open:s,onOpenChange:t,hasPending:n,pendingEmails:r}){const a=Wn();return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"sm:max-w-md",children:[e.jsxs(Vs,{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(Vo,{className:"h-5 w-5"})}),e.jsx($s,{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(Yr,{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(ln,{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(Mr,{className:"gap-2 sm:gap-2",children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Not now"}),e.jsxs(U,{onClick:()=>{t(!1),a("/mission-control/integrations")},children:[e.jsx(Sr,{className:"h-4 w-4 mr-1"}),n?"Manage senders":"Verify my email"]})]})]})})}function rPe(){const{user:s}=vs(),t=Qt(),{data:n,isLoading:r}=ct({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=yt({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=yt({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}=ct({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=yt({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 o7t({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),p=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(()=>{p.current&&clearTimeout(p.current);const x=s.trim();if(!n||x.length<1||x.includes("@")&&x.indexOf("@")>0&&/\S+@\S+\.\S+/.test(x)){o([]);return}return p.current=setTimeout(async()=>{d(!0);const y=`%${x}%`,v=q,{data:b,error:N}=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),!N&&b&&(o(b),h(0),i(b.length>0))},180),()=>{p.current&&clearTimeout(p.current)}},[s,n]);const f=x=>{x.email&&(t(x.email),i(!1))};return e.jsxs("div",{ref:m,className:"relative",children:[e.jsx(xe,{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(),f(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(Et,{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:()=>f(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(So,{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 $7s(){const{user:s}=vs(),{data:t,isLoading:n}=ct({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 V7s(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 H7s(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 QOe=25*1024*1024,Fft=Math.floor(6.5*1024*1024),G7s=750*1024,e2=50,W7s=["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 Ooe(s){return s<1024?s+" B":s<1024*1024?(s/1024).toFixed(1)+" KB":(s/(1024*1024)).toFixed(1)+" MB"}function K7s(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 Y7s(s){if(!s)return"";const t=s.trim();return t.split(/\s+/)[0]||t}function t2(s,t){const n=Y7s(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 wS({open:s,onOpenChange:t,contact:n,bulkContacts:r,defaultSubject:a="",defaultBody:i="",gmailEmail:l,onSendComplete:o,sendSource:c,logTouchpoint:d=!0}){const{user:u}=vs(),h=Qt(),{isReady:m,settings:p}=AG(),{data:f}=dre(),[x,y]=j.useState(!1),{intakePage:v}=rPe(),b=v?`https://contacts.relevelup.com/${v.slug}`:null,N=!!r&&r.length>0,S=U7s(),A=m,T=N?r:n?[n]:[],L=T[0],M=N?Math.ceil(T.length/e2):1,I=N&&T.length>e2,[R,z]=j.useState((L==null?void 0:L.email)||""),[$,H]=j.useState(a),[V,K]=j.useState(i),[Z,Q]=j.useState(!1),[le,ue]=j.useState(!1),[se,ne]=j.useState([]),ie=j.useRef(new Map),[ce,je]=j.useState(a),[be,he]=j.useState(i),[ge,ke]=j.useState(!1),[Te,Me]=j.useState("composing"),[Oe,Se]=j.useState(0),[Qe,Ae]=j.useState(0),[Fe,Ne]=j.useState(0),[$e,Ve]=j.useState(0),qe=j.useRef(!1),Ze=j.useRef(0),[Ue,Ye]=j.useState(!0),{signatureHtml:Ge,hasSignature:He,signatureEnabledByDefault:tt}=$7s(),[pt,ft]=j.useState(!0),[qt,Ut]=j.useState(null);j.useEffect(()=>{s&&ft(He)},[s,He]),j.useEffect(()=>{if(s){const nn=/<[a-z][\s\S]*>/i.test(i),Zn=nn?H7s(i):i;As.current=nn?{plain:Zn,html:i}:null,z((L==null?void 0:L.email)||""),je(a),he(Zn),H(t2(a,L||{first_name:""})),K(t2(Zn,L||{first_name:""})),ue(!a&&!i),ke(!1),ne([]),ie.current=new Map,Me("composing"),Se(0),Ae(0),Ne(0),Ve(0),qe.current=!1,Ze.current=0,Ut(null)}},[s,L,a,i]);const Wt=async nn=>{const Zn=nn.target.files;if(!Zn)return;const es=se.reduce((kn,Un)=>kn+Un.size,0),ar=[];let Hn=es;for(const kn of Array.from(Zn)){if(!W7s.includes(kn.type)){re.error(`${kn.name}: Unsupported file type`);continue}if(Hn+kn.size>QOe){re.error(`Total attachments exceed ${Ooe(QOe)} limit`);break}try{const Un=await K7s(kn);ar.push({name:kn.name,type:kn.type,size:kn.size,data:Un}),Hn+=kn.size}catch{re.error(`Failed to read ${kn.name}`)}}ne(kn=>[...kn,...ar]),nn.target.value=""},us=nn=>{const Zn=se[nn];Zn&&ie.current.delete(`${Zn.name}::${Zn.size}`),ne(es=>es.filter((ar,Hn)=>Hn!==nn))},zt=async()=>{if(se.length===0||!u)return{inline:[],paths:[]};const nn=[],Zn=[];for(const es of se){const ar=`${es.name}::${es.size}`,Hn=ie.current.get(ar);if(Hn){Zn.push(Hn);continue}if(es.size<=G7s){nn.push(es);continue}const kn=es.name.replace(/[^a-zA-Z0-9._-]/g,"_"),Un=`${u.id}/${Date.now()}-${kn}`,sn=atob(es.data),un=new Uint8Array(sn.length);for(let fs=0;fs{if(!/<[a-z][\s\S]*>/i.test(nn)||typeof window>"u")return nn;const Zn=nn.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,""),es=document.createElement("div");return es.innerHTML=Zn,(es.textContent||es.innerText||"").replace(/\u00a0/g," ").replace(/\n{3,}/g,` `).trim()},As=j.useRef(null),vt=As.current&&be===As.current.plain?As.current.html:null,Ws=nn=>{const Zn=/<[a-z][\s\S]*>/i.test(nn.body),es=Zn?bt(nn.body):nn.body;As.current=Zn?{plain:es,html:nn.body}:null,je(nn.subject),he(es),H(t2(nn.subject,L||{first_name:""})),K(t2(es,L||{first_name:""})),ue(!1)},on=nn=>/<\s*(p|div|span|table|tr|td|img|br|h[1-6]|a|body|html|section|article|ul|ol|li)\b/i.test(nn)?nn:nn.split(/\n\n+/).map(Zn=>`

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

`).join(""),Ms=(nn,Zn)=>{const es="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-email-track";let ar=nn.replace(/]*?)href=(["'])(.*?)\2([^>]*)>/gi,(kn,Un,sn,un,Ar)=>{if(!un||/^(mailto:|tel:|#)/i.test(un)||un.includes("/bulk-email-track")||un.includes("/ses-campaign-track"))return kn;const fs=`${es}?s=${Zn}&t=click&u=${encodeURIComponent(un)}`;return``});const Hn=``;return/<\/body>/i.test(ar)?ar=ar.replace(/<\/body>/i,`${Hn}`):ar=`${ar}${Hn}`,ar},dn=async nn=>{if(!(nn!=null&&nn.email))return re.error("Please enter a recipient email"),!1;const Zn=nn||{first_name:""},es=t2(ce,Zn),ar=As.current,Hn=ar&&be===ar.plain,kn=t2(Hn?ar.html:be,Zn);let Un=Hn?kn:on(kn);pt&&Ge&&(Un=V7s(Un,t2(Ge,Zn)));const sn=u&&nn.id?crypto.randomUUID():null;sn&&(Un=Ms(Un,sn));try{if(u&&nn.email){const fs=new Date(Date.now()-6e5).toISOString(),{data:ot}=await q.from("bulk_email_sends").select("id").eq("user_id",u.id).eq("contact_email",nn.email).eq("subject",es).gte("sent_at",fs).limit(1);if(ot&&ot.length>0)return console.log(`Skipping duplicate send to ${nn.email} (same subject within 10 min)`),re.info(`Skipped ${nn.first_name||nn.email} — already sent this in the last 10 min`),!0}const{inline:un,paths:Ar}=await zt();if(A){const fs=(p==null?void 0:p.display_name)||"ReLevelUp",ot=`${fs.toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,mt=`${fs} <${ot}>`;let Nt=Ar[0];if(!Nt&&un.length>0&&u){const ls=un[0],Is=ls.name.replace(/[^a-zA-Z0-9._-]/g,"_"),ps=`${u.id}/${Date.now()}-${Is}`,Ht=atob(ls.data),Xs=new Uint8Array(Ht.length);for(let zn=0;zn({name:mt,type:Nt,data:Pt})),attachment_paths:Ar,skip_signature:!0}});if(ot)throw ot;if(!(fs!=null&&fs.success))throw new Error((fs==null?void 0:fs.error)||"Failed to send")}if(u&&nn.id&&sn&&(await q.from("bulk_email_sends").insert({id:sn,user_id:u.id,contact_id:nn.id,contact_email:nn.email,subject:es,source:c||(A?"ses_bulk":"sphere_gaps")}),d))try{await q.from("contact_touch_logs").insert({owner_user_id:u.id,contact_id:nn.id,action_type_id:"9a88a47c-cb2a-4401-a2b5-111a76b19f9d",notes:`Mass Email: ${es}`,completed_at:new Date().toISOString()})}catch(fs){console.warn("touch log insert failed",fs)}return!0}catch(un){return console.error("Send error:",un),re.error("Failed to send to "+nn.first_name+": "+(un instanceof Error?un.message:"Unknown error")),!1}},rn=()=>{const nn=Oe*e2;return T.slice(nn,nn+e2)},br=async(nn=0,Zn=Ue)=>{if(!$||!V){re.error("Please fill in subject and message");return}Q(!0),Me("sending");let es=Math.max(0,Math.min(nn,T.length)),ar=!1;for(;esAr+1):Ne(Ar=>Ar+1),snsetTimeout(Ar,150))}if(h.invalidateQueries({queryKey:["bulk-email-sends"]}),h.invalidateQueries({queryKey:["contact-touch-logs"]}),h.invalidateQueries({queryKey:["contacts-last-touch"]}),ar||qe.current||es>=T.length)break;if(!Zn){Q(!1),Me("batch_complete");return}if(Ve(0),await new Promise(sn=>setTimeout(sn,1500)),qe.current){ar=!0;break}}Q(!1),Me(ar||qe.current?"batch_complete":"all_done")},Gn=async()=>{var Zn;if(!$||!V){re.error("Please fill in subject and message");return}const nn=N?(r==null?void 0:r.length)||0:1;if(S.wouldExceed(nn)){re.error(`Your package includes ${(Zn=S.limit)==null?void 0:Zn.toLocaleString()} emails per month. You have ${S.remaining.toLocaleString()} left — request an upgrade for unlimited sending.`);return}if(A&&f&&!f.hasVerifiedSes&&!f.hasGmail){y(!0);return}if(!N){const es=L||{id:"",first_name:"",last_name:"",email:R.trim()};if(!es.email){re.error("Please enter a recipient email");return}Q(!0);try{await dn(es)&&(h.invalidateQueries({queryKey:["bulk-email-sends"]}),re.success("Email sent successfully!"),t(!1),o==null||o())}finally{Q(!1)}return}qe.current=!1,Ze.current=0,await br(0)},On=async()=>{qe.current=!1,Ve(0),await br(Ze.current,!1)},Rr=async()=>{qe.current=!1,Ye(!0),Ve(0),await br(Ze.current,!0)},cr=()=>{if(Z){qe.current=!0;return}t(!1),o==null||o()},Hs=Oe*e2;Math.min(Hs+e2,T.length);const _r=N&&T.length>0?Math.round((Qe+Fe)/T.length*100):0;return e.jsxs(zs,{open:s,onOpenChange:cr,children:[e.jsxs(Ds,{className:"sm:max-w-[600px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:`h-5 w-5 ${A?"text-orange-500":"text-red-500"}`}),N?`Send to ${T.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: ",p==null?void 0:p.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,N&&Te==="composing"&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Composing email for ",e.jsxs("span",{className:"font-medium",children:[T.length," contacts"]}),". You'll review each personalized email before sending."]})]}),Te==="sending"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Et,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending batch ",Oe+1," of ",M,"..."]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[$e," of ",rn().length," in this batch"]}),Ue&&M>1&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Auto-continuing through all ",M," batches — keep this window open."]})]}),e.jsx(ro,{value:$e/Math.max(rn().length,1)*100,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Overall: ",Qe+Fe," / ",T.length]}),e.jsxs("span",{children:[Qe," sent • ",Fe," failed"]})]}),e.jsx(U,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{qe.current=!0},children:"Stop Sending"})]}),Te==="batch_complete"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(zr,{className:"h-8 w-8 text-emerald-500 mx-auto"}),e.jsxs("p",{className:"font-medium",children:["Sending paused after batch ",Oe+1]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Qe," sent, ",Fe," failed so far"]})]}),e.jsx(ro,{value:_r,className:"h-2"}),e.jsxs("p",{className:"text-xs text-center text-muted-foreground",children:[T.length-Qe-Fe," contacts remaining (",Math.max(M-Oe-1,0)," batches left)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{variant:"outline",className:"flex-1",onClick:cr,children:"Done for Now"}),e.jsxs(U,{className:"flex-1 gap-2",onClick:Rr,children:[e.jsx($r,{className:"h-4 w-4"}),"Resume Sending"]})]}),e.jsxs(U,{variant:"ghost",size:"sm",className:"w-full",onClick:On,children:["Send just the next ",Math.min(e2,Math.max(T.length-(Qe+Fe),0))," contacts"]})]}),Te==="all_done"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(zr,{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:[Qe," emails sent successfully",Fe>0&&e.jsxs("span",{className:"text-destructive",children:[" • ",Fe," failed"]})]})]}),e.jsx(U,{className:"w-full",onClick:cr,children:"Close"})]}),Te==="composing"&&e.jsxs("div",{className:"space-y-4",children:[le?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(Ur,{className:"h-4 w-4"})," Choose a Template"]}),e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>ue(!1),className:"h-7 px-2 text-xs",children:[e.jsx(er,{className:"h-3 w-3 mr-1"})," Write from scratch"]})]}),e.jsx(q7s,{onSelect:Ws})]}):e.jsxs(U,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>ue(!0),children:[e.jsx(Ur,{className:"h-4 w-4"}),"Browse Templates"]}),e.jsx(hc,{}),!N&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"gmail-to",children:"To"}),e.jsx(o7t,{value:R,onChange:z,userId:u==null?void 0:u.id})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"gmail-subject",children:"Subject"}),e.jsx(xe,{id:"gmail-subject",value:$,onChange:nn=>{H(nn.target.value),je(nn.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(te,{htmlFor:"gmail-body",children:"Message"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(Be,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{K(nn=>nn+"{{first_name}}"),he(nn=>nn+"{{first_name}}")},children:"{{first_name}}"}),e.jsx(Be,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{K(nn=>nn+"{{last_name}}"),he(nn=>nn+"{{last_name}}")},children:"{{last_name}}"}),b&&e.jsx(Be,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-primary/10 border-primary/40 text-primary",onClick:()=>{const nn=` When you get a sec, can you share your latest contact info with me? It only takes about a minute: ${b} `;K(Zn=>Zn+nn),he(Zn=>Zn+nn)},title:"Insert your Connect Page link",children:"+ Connect Page"})]})]}),vt&&!ge?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 items-center justify-between gap-2 border-b bg-muted/40 px-3 py-2",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Branded email preview"}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>ke(!0),children:"Edit as plain text"})]}),e.jsx("div",{className:"max-h-[420px] overflow-y-auto [&_img]:max-w-full",dangerouslySetInnerHTML:{__html:t2(vt,L||{first_name:"there"})}})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This designed template is sent as-is, personalized for each recipient."})]}):e.jsx(Fs,{id:"gmail-body",value:V,onChange:nn=>{K(nn.target.value),he(nn.target.value)},placeholder:"Write your message...",rows:10,className:"resize-y"}),N&&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:He?"Your saved signature is added to the bottom of this email.":"Add a signature in Profile settings to use this."})]}),e.jsx(wn,{checked:pt&&He,onCheckedChange:ft,disabled:!He})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(U,{type:"button",variant:"outline",size:"sm",className:"gap-2",onClick:()=>{var nn;return(nn=document.getElementById("gmail-attachments"))==null?void 0:nn.click()},disabled:Z,children:[e.jsx(MM,{className:"h-4 w-4"}),"Attach Files"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["PDF, images, Word, Excel (max ",Ooe(QOe)," 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})]}),se.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:se.map((nn,Zn)=>e.jsxs(Be,{variant:"secondary",className:"gap-1.5 pl-2 pr-1 py-1",children:[e.jsx(MM,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[140px] truncate text-xs",children:nn.name}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["(",Ooe(nn.size),")"]}),e.jsx("button",{type:"button",onClick:()=>us(Zn),className:"ml-0.5 rounded-full p-0.5 hover:bg-muted",children:e.jsx(er,{className:"h-3 w-3"})})]},Zn))}),A&&se.some(nn=>nn.size>Fft)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Files over ",Ooe(Fft)," will be sent as secure download links."]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),N?e.jsxs(U,{onClick:()=>{Ut(T[0]||null),Me("reviewing")},disabled:!$||!V,className:"gap-2",children:["Review Emails",e.jsx(Oa,{className:"h-4 w-4"})]}):e.jsxs(U,{onClick:Gn,disabled:Z||!$||!V||!R.trim(),className:"gap-2",children:[Z?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx($r,{className:"h-4 w-4"}),Z?"Sending...":"Send Email"]})]})]}),Te==="reviewing"&&N&&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."]}),I&&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:["📦 ",T.length," contacts will be sent in ",M," batches of up to ",e2,"."]}),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:Ue,onChange:nn=>Ye(nn.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(te,{children:["Recipients (",T.length,")"]}),e.jsx("div",{className:"bg-muted p-1.5 rounded-md space-y-0.5 max-h-32 overflow-y-auto",children:T.map(nn=>e.jsxs("div",{className:`text-sm px-2 py-1 rounded cursor-pointer transition-colors ${(qt==null?void 0:qt.id)===nn.id?"bg-primary/10 text-primary font-medium":"text-muted-foreground hover:bg-accent hover:text-foreground"}`,onClick:()=>Ut(nn),children:[nn.first_name," ",nn.last_name," — ",nn.email]},nn.id))})]}),qt&&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(ln,{className:"h-3.5 w-3.5"}),"Preview for ",qt.first_name," ",qt.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:"})," ",qt.email]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Subject:"})," ",t2(ce,qt)]})]}),e.jsx(hc,{}),vt?e.jsx("div",{className:"rounded-lg border bg-background max-h-72 overflow-y-auto [&_img]:max-w-full",dangerouslySetInnerHTML:{__html:t2(vt,qt)}}):e.jsx("div",{className:"text-sm whitespace-pre-wrap bg-background rounded p-2.5 max-h-40 overflow-y-auto border",children:t2(be,qt)})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsxs(U,{variant:"outline",onClick:()=>{Me("composing"),Ut(null)},children:[e.jsx(Aa,{className:"h-4 w-4 mr-1"}),"Back to Edit"]}),e.jsxs(U,{onClick:Gn,disabled:Z,className:"gap-2",children:[Z?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx($r,{className:"h-4 w-4"}),I?`Send First ${e2}`:`Send to ${T.length}`]})]})]})]}),e.jsx(nPe,{open:x,onOpenChange:y,hasPending:!!(f!=null&&f.hasPendingSes),pendingEmails:f==null?void 0:f.pendingEmails})]})}function Z7s(s){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s)}const X7s={single_family:"Single Family Home",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury Home",commercial:"Commercial",other:"Property"};function l7t({open:s,onOpenChange:t,listing:n}){const{user:r}=vs(),{data:a=[],isLoading:i}=Cb(),{data:l=[]}=F_(),[o,c]=j.useState(""),[d,u]=j.useState("all"),[h,m]=j.useState(new Set),[p,f]=j.useState(!1),[x,y]=j.useState(null);j.useEffect(()=>{s||(c(""),u("all"),m(new Set),f(!1))},[s]),j.useEffect(()=>{!s||!r||(async()=>{const{data:M}=await q.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle();y((M==null?void 0:M.gmail_email)||null)})()},[s,r]);const v=j.useMemo(()=>a.filter(M=>M.email),[a]),b=j.useMemo(()=>{let M=v;if(d!=="all"&&(M=M.filter(I=>{var R;return(R=I.tags)==null?void 0:R.some(z=>z.relationship_type_id===d)})),o.trim()){const I=o.toLowerCase();M=M.filter(R=>`${R.first_name||""} ${R.last_name||""}`.toLowerCase().includes(I)||(R.email||"").toLowerCase().includes(I))}return M},[v,o,d]),N=()=>{h.size===b.length?m(new Set):m(new Set(b.map(M=>M.id)))},S=M=>{const I=new Set(h);I.has(M)?I.delete(M):I.add(M),m(I)},A=j.useMemo(()=>v.filter(M=>h.has(M.id)).map(M=>({id:M.id,first_name:M.first_name||"there",last_name:M.last_name,email:M.email})),[v,h]),{defaultSubject:T,defaultBody:L}=j.useMemo(()=>{var ne,ie,ce,je;const M=n.property_address||`${n.city}, ${n.state}`,I=Z7s(n.price),R=X7s[n.property_type]||"home",z=n.bedrooms?`${n.bedrooms} bed`:"",$=n.bathrooms?`${n.bathrooms} bath`:"",H=n.square_footage?`${n.square_footage.toLocaleString()} sqft`:"",V=[z,$,H].filter(Boolean).join(" • "),K=`https://listings.relevelup.com/${n.slug||n.id}`,Z=((ie=(ne=n.photos)==null?void 0:ne.find(be=>be.is_primary))==null?void 0:ie.photo_url)||((je=(ce=n.photos)==null?void 0:ce[0])==null?void 0:je.photo_url)||"",le={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",ue=`${le}: ${M} — ${I}`,se=`

Hi {{first_name}},

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

${Z?` ${M} `:""}
${le}

${I}

${M}

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

${V?`

${V} • ${R}

`:""} 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:ue,defaultBody:se}},[n]);return p?e.jsx(wS,{open:p,onOpenChange:M=>{f(M),M||t(!1)},bulkContacts:A,defaultSubject:T,defaultBody:L,gmailEmail:x}):e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"sm:max-w-[640px] max-h-[90vh] flex flex-col",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(cn,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search contacts...",value:o,onChange:M=>c(M.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:d,onValueChange:u,children:[e.jsx(ws,{className:"sm:w-[180px]",children:e.jsx(ks,{placeholder:"Filter by tag"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All contacts"}),l.map(M=>e.jsx(et,{value:M.id,children:M.name},M.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm border-y py-2",children:[e.jsxs("button",{type:"button",onClick:N,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(xi,{checked:b.length>0&&h.size===b.length,className:"pointer-events-none"}),e.jsx("span",{children:h.size===b.length&&b.length>0?"Deselect all":`Select all (${b.length})`})]}),e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Bn,{className:"h-3 w-3"}),h.size," selected"]})]}),e.jsx(Gi,{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(Et,{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(M=>e.jsxs("label",{className:"flex items-center gap-3 p-2 rounded-md hover:bg-muted/50 cursor-pointer",children:[e.jsx(xi,{checked:h.has(M.id),onCheckedChange:()=>S(M.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[M.first_name," ",M.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:M.email})]}),M.tags&&M.tags.length>0&&e.jsx("div",{className:"flex gap-1 flex-wrap justify-end max-w-[40%]",children:M.tags.slice(0,2).map(I=>{var R;return e.jsx(Be,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:(R=I.relationship_type)==null?void 0:R.name},I.id)})})]},M.id))})}),e.jsx(hc,{}),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(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{onClick:()=>f(!0),disabled:h.size===0,className:"gap-2",children:[e.jsx(ln,{className:"h-4 w-4"}),"Compose Email (",h.size,")"]})]})]})]})})}const Q7s=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)}`},zft=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),XL="#D4AF37",Bft="#0F172A",Uft=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}),qft=(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)},_Z=(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()}…`},J7s=(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},t9s=s=>s instanceof DOMException||s instanceof Error?s.name:null;function UQe({listingId:s,open:t,onOpenChange:n}){var A,T;const{data:r}=rre(s||""),[a,i]=j.useState(null),[l,o]=j.useState(!1),[c,d]=j.useState(null),[u,h]=j.useState(null),m=((r==null?void 0:r.photos)||[]).slice().sort((L,M)=>L.is_primary&&!M.is_primary?-1:!L.is_primary&&M.is_primary?1:(L.sort_order??0)-(M.sort_order??0));j.useEffect(()=>{var M;if(!t)return;const L=((M=m[0])==null?void 0:M.photo_url)||null;h(I=>I||L)},[t,r==null?void 0:r.id,m.length]),j.useEffect(()=>{let L=!1;if(!(!t||!(r!=null&&r.agent_id)))return(async()=>{var z,$,H,V;const{data:M}=await q.from("profiles").select("name, phone, phone_e164, avatar_url, brokerage:brokerages!profiles_brokerage_id_fkey(name)").eq("id",r.agent_id).maybeSingle();if(L)return;const I=M,R=((z=I==null?void 0:I.brokerage)==null?void 0:z.name)||((H=($=r.agent)==null?void 0:$.brokerage)==null?void 0:H.name)||null;i({name:(I==null?void 0:I.name)||((V=r.agent)==null?void 0:V.name)||"Agent",phone:(I==null?void 0:I.phone)||(I==null?void 0:I.phone_e164)||null,avatar_url:(I==null?void 0:I.avatar_url)||null,brokerage:R})})(),()=>{L=!0}},[t,r==null?void 0:r.agent_id]),j.useEffect(()=>{if(!t){d(null),h(null);return}if(!r||!a)return;const L=setTimeout(()=>{p()},350);return()=>clearTimeout(L)},[t,r==null?void 0:r.id,a==null?void 0:a.name,u]);const p=async()=>{if(!(!r||!a)){o(!0);try{const L=document.createElement("canvas");L.width=1080,L.height=1080;const M=L.getContext("2d");if(!M)throw new Error("Canvas unavailable");if(M.fillStyle=Bft,M.fillRect(0,0,1080,1080),b){const V=await Uft(b);qft(M,V,0,0,1080,1080)}const I=M.createLinearGradient(0,0,0,1080);I.addColorStop(0,"rgba(15,23,42,0.58)"),I.addColorStop(.34,"rgba(15,23,42,0.16)"),I.addColorStop(.62,"rgba(15,23,42,0.48)"),I.addColorStop(1,"rgba(15,23,42,0.98)"),M.fillStyle=I,M.fillRect(0,0,1080,1080),M.fillStyle=XL,M.fillRect(56,62,72,2),M.font="600 22px Arial, sans-serif",e9s(M,"JUST LISTED",146,72,8),M.save(),M.shadowColor="rgba(0,0,0,0.55)",M.shadowBlur=24,M.shadowOffsetY=4,M.fillStyle="#F8FAFC",M.font="600 64px Georgia, serif",M.textBaseline="top";const R=J7s(M,r.property_address||`${r.city||""}, ${r.state||""}`.trim(),952,2);let z=R.length>1?590:654;R.forEach(V=>{M.fillText(V,64,z),z+=70}),M.restore();const $=[r.city,r.state].filter(Boolean).join(", ")+(r.neighborhood?` · ${r.neighborhood}`:"");M.fillStyle="rgba(248,250,252,0.9)",M.font="600 26px Arial, sans-serif",M.fillText(_Z(M,$.toUpperCase(),952),64,z+8),M.fillStyle=XL,M.font="700 56px Arial, sans-serif",M.fillText(zft(r.price),64,z+58),S.length>0&&(M.fillStyle="rgba(248,250,252,0.86)",M.font="600 22px Arial, sans-serif",M.fillText(_Z(M,S.join(" · "),430),360,z+78));const H=M.createLinearGradient(0,880,0,1080);if(H.addColorStop(0,"rgba(15,23,42,0.96)"),H.addColorStop(1,"#0B1322"),M.fillStyle=H,M.fillRect(0,880,1080,200),M.fillStyle=XL,M.fillRect(0,880,1080,2),M.save(),M.beginPath(),M.arc(124,980,60,0,Math.PI*2),M.closePath(),M.fillStyle="#1E293B",M.fill(),M.lineWidth=6,M.strokeStyle=XL,M.stroke(),M.clip(),a.avatar_url)try{const V=await Uft(a.avatar_url);qft(M,V,64,920,120,120)}catch{M.fillStyle=XL,M.font="700 48px Arial, sans-serif",M.textAlign="center",M.textBaseline="middle",M.fillText(a.name.charAt(0).toUpperCase(),124,982)}else M.fillStyle=XL,M.font="700 48px Arial, sans-serif",M.textAlign="center",M.textBaseline="middle",M.fillText(a.name.charAt(0).toUpperCase(),124,982);M.restore(),M.textAlign="left",M.textBaseline="alphabetic",M.fillStyle="#F8FAFC",M.font="600 38px Georgia, serif",M.fillText(_Z(M,a.name,N?430:820),212,970),a.brokerage&&(M.fillStyle=XL,M.font="600 20px Arial, sans-serif",M.fillText(_Z(M,a.brokerage.toUpperCase(),N?430:820),212,1008)),N&&(M.textAlign="right",M.fillStyle="rgba(212,175,55,0.86)",M.font="600 16px Arial, sans-serif",M.fillText("CALL · TEXT",1016,958),M.fillStyle="#F8FAFC",M.font="600 38px Arial, sans-serif",M.fillText(N,1016,1008)),d(L.toDataURL("image/png"))}catch(L){console.error("Generate graphic error",L),re.error("Could not generate graphic")}finally{o(!1)}}},f=async L=>(await fetch(L)).blob(),x=async()=>{if(!c)return;const L=document.createElement("a");L.href=c,L.download=`just-listed-${(r==null?void 0:r.slug)||(r==null?void 0:r.id)||"graphic"}.png`,L.click(),re.success("Downloaded!")},y=async()=>{if(c)try{const L=await f(c);await navigator.clipboard.write([new ClipboardItem({"image/png":L})]),re.success("Copied to clipboard")}catch{re.error("Copy not supported in this browser")}},v=async()=>{if(c)try{const L=await f(c),M=new File([L],"just-listed.png",{type:"image/png"});navigator.canShare&&navigator.canShare({files:[M]})?await navigator.share({files:[M],title:"Just Listed"}):x()}catch(L){t9s(L)!=="AbortError"&&re.error("Share failed")}},b=u||((A=m[0])==null?void 0:A.photo_url)||null,N=Q7s(a==null?void 0:a.phone),S=[r!=null&&r.bedrooms?`${r.bedrooms} BD`:null,r!=null&&r.bathrooms?`${r.bathrooms} BA`:null,r!=null&&r.square_footage?`${r.square_footage.toLocaleString()} SF`:null].filter(Boolean);return e.jsx(zs,{open:t,onOpenChange:n,children:e.jsx(Ds,{className:"!max-w-[480px] !w-[calc(100vw-2rem)] !p-0 !gap-0 !block overflow-hidden",style:{maxHeight:"calc(100vh - 2rem)"},children:e.jsxs("div",{className:"flex flex-col",style:{maxHeight:"calc(100vh - 2rem)"},children:[e.jsxs(Vs,{className:"px-5 pt-5 pb-3 shrink-0",children:[e.jsxs($s,{className:"flex items-center gap-2 pr-8",children:[e.jsx(cn,{className:"h-5 w-5 text-amber-500 shrink-0"}),e.jsx("span",{className:"truncate",children:"Your Just Listed Graphic"})]}),e.jsx(Pr,{className:"text-xs",children:"Square 1080×1080 — perfect for Instagram, Facebook, LinkedIn."})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 pb-3",children:[e.jsxs("div",{className:"relative mx-auto flex items-center justify-center rounded-lg overflow-hidden",style:{width:"280px",maxWidth:"100%",height:"280px",background:Bft},children:[b&&e.jsx("img",{src:b,alt:"Selected property",className:"absolute inset-0 h-full w-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-slate-950/65 via-slate-950/25 to-slate-950"}),e.jsxs("div",{className:"absolute left-4 right-4 top-4 flex items-center gap-2",children:[e.jsx("span",{className:"h-px w-6 bg-amber-400"}),e.jsx("span",{className:"text-[9px] font-semibold uppercase tracking-[0.28em] text-amber-300",children:"Just Listed"})]}),e.jsxs("div",{className:"absolute left-4 right-4 bottom-[64px] text-white",children:[e.jsx("div",{className:"line-clamp-2 font-serif text-[18px] font-semibold leading-[1.05] drop-shadow-lg",children:(r==null?void 0:r.property_address)||`${(r==null?void 0:r.city)||""}, ${(r==null?void 0:r.state)||""}`}),e.jsxs("div",{className:"mt-1 truncate text-[9px] font-semibold uppercase tracking-[0.18em] text-white/85",children:[[r==null?void 0:r.city,r==null?void 0:r.state].filter(Boolean).join(", "),r!=null&&r.neighborhood?` · ${r.neighborhood}`:""]}),e.jsxs("div",{className:"mt-1.5 flex items-center gap-2",children:[e.jsx("span",{className:"text-[16px] font-bold text-amber-300",children:r?zft(r.price):""}),S.length>0&&e.jsx("span",{className:"truncate text-[8px] font-semibold uppercase tracking-[0.14em] text-white/80",children:S.join(" · ")})]})]}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 flex h-[52px] items-center border-t border-amber-400 bg-slate-950/95 px-4",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded-full border-2 border-amber-400 bg-slate-800 text-xs font-bold text-amber-300",children:a!=null&&a.avatar_url?e.jsx("img",{src:a.avatar_url,alt:"",className:"h-full w-full object-cover"}):(T=a==null?void 0:a.name)==null?void 0:T.charAt(0).toUpperCase()}),e.jsxs("div",{className:"ml-2 min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-serif text-xs font-semibold text-white",children:a==null?void 0:a.name}),(a==null?void 0:a.brokerage)&&e.jsx("div",{className:"truncate text-[7px] font-semibold uppercase tracking-[0.18em] text-amber-300",children:a.brokerage})]}),N&&e.jsx("div",{className:"ml-2 shrink-0 text-[9px] font-semibold text-white",children:N})]}),l&&e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 bg-slate-950/80 text-white/85",children:[e.jsx(Et,{className:"h-7 w-7 animate-spin"}),e.jsx("p",{className:"text-xs",children:"Crafting your graphic…"})]})]}),m.length>1&&e.jsxs("div",{className:"mt-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose photo"}),e.jsx("div",{className:"flex gap-2 pb-2",style:{overflowX:"auto",overflowY:"hidden",WebkitOverflowScrolling:"touch"},children:m.map(L=>{const M=u===L.photo_url;return e.jsx("button",{type:"button",onClick:()=>h(L.photo_url),className:`relative shrink-0 h-14 w-14 rounded-md overflow-hidden border-2 transition ${M?"border-amber-500 ring-2 ring-amber-500/30":"border-transparent hover:border-muted-foreground/40"}`,children:e.jsx("img",{src:L.photo_url,alt:"",className:"w-full h-full object-cover"})},L.id)})})]})]}),e.jsxs("div",{className:"px-5 pb-5 pt-2 shrink-0 border-t bg-background flex flex-wrap justify-end gap-2",children:[e.jsx(U,{variant:"outline",size:"sm",onClick:()=>void p(),disabled:l||!r||!a,children:"Regenerate"}),e.jsxs(U,{variant:"outline",size:"sm",onClick:y,disabled:!c,className:"gap-1.5",children:[e.jsx(Pa,{className:"h-3.5 w-3.5"})," Copy"]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:v,disabled:!c,className:"gap-1.5",children:[e.jsx(jd,{className:"h-3.5 w-3.5"})," Share"]}),e.jsxs(U,{size:"sm",onClick:x,disabled:!c,className:"gap-1.5",children:[e.jsx(pi,{className:"h-3.5 w-3.5"})," Download"]})]})]})})})}function s9s({listing:s,canEdit:t}){const n=Wn(),{data:r,isLoading:a}=_As(s.id),i=iRt(),l=oRt(),[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(nRt),[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 p=r!=null&&r.preview_token?`${window.location.origin}/commercial-pitch/${r.preview_token}`:null,f=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(Et,{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(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-base",children:"Owner & decision makers"}),e.jsx(Jn,{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(te,{children:"Owner name"}),e.jsx(xe,{value:o.owner_name,onChange:v=>c({...o,owner_name:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Entity / company"}),e.jsx(xe,{value:o.owner_company,onChange:v=>c({...o,owner_company:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Email"}),e.jsx(xe,{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(te,{children:"Phone"}),e.jsx(xe,{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(te,{children:"Decision-maker intel"}),e.jsx(Fs,{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(te,{children:"Pitch date"}),e.jsx(xe,{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(te,{children:"Competing brokers"}),e.jsx(xe,{value:o.competitors,onChange:v=>c({...o,competitors:v.target.value})})]})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-base",children:"Positioning & pricing strategy"}),e.jsx(Jn,{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(te,{children:"Proposed positioning"}),e.jsx(Fs,{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(te,{children:"Pricing strategy"}),e.jsx(Fs,{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(te,{children:"Private pitch notes"}),e.jsx(Fs,{rows:3,value:o.pitch_notes,onChange:v=>c({...o,pitch_notes:v.target.value}),placeholder:"Never shown to the owner."})]})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-base",children:"Proposed launch plan"}),e.jsx(Jn,{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(xe,{value:v.label,placeholder:"Milestone",onChange:N=>u(d.map((S,A)=>A===b?{...S,label:N.target.value}:S))}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>u(d.filter((N,S)=>S!==b)),children:e.jsx(er,{className:"h-4 w-4"})})]}),e.jsx(Fs,{className:"mt-2",rows:2,value:v.detail??"",placeholder:"What happens in this step",onChange:N=>u(d.map((S,A)=>A===b?{...S,detail:N.target.value}:S))})]},b)),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>u([...d,{label:"",detail:""}]),children:[e.jsx(an,{className:"mr-1.5 h-3.5 w-3.5"})," Add step"]})]})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(we,{className:"border-primary/30 bg-gradient-to-br from-primary/[0.06] to-transparent",children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-base",children:"Owner preview"}),e.jsx(Jn,{children:"A private, seller-facing page showing exactly what happens the day they hire you."})]}),e.jsx(Ie,{className:"space-y-3",children:p?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:p})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{variant:"outline",size:"sm",className:"flex-1",onClick:()=>{navigator.clipboard.writeText(p),re.success("Link copied")},children:[e.jsx(Pa,{className:"mr-1.5 h-3.5 w-3.5"})," Copy"]}),e.jsxs(U,{size:"sm",className:"flex-1",onClick:()=>window.open(p,"_blank"),children:[e.jsx(Sr,{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(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Outcome"})}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsxs(U,{className:"w-full",children:[e.jsx(Al,{className:"mr-2 h-4 w-4"})," Won listing"]})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Convert this pitch into a Commercial Launch?"}),e.jsx(Ll,{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(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:x,children:"Yes — we won it"})]})]})]}),e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsxs(U,{variant:"outline",className:"w-full",children:[e.jsx(ou,{className:"mr-2 h-4 w-4"})," Lost opportunity"]})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Mark as lost?"}),e.jsx(Ll,{children:"Kept private in your archive so you can learn from it."})]}),e.jsx(xe,{placeholder:"Reason (optional)",value:h,onChange:v=>m(v.target.value)}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:y,children:"Mark lost"})]})]})]})]})]})]})]}),e.jsx("div",{className:"sticky bottom-4 flex justify-end",children:e.jsxs(U,{onClick:f,disabled:i.isPending,size:"lg",className:"shadow-lg",children:[i.isPending?e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ho,{className:"mr-2 h-4 w-4"}),"Save pitch"]})})]}):e.jsx(we,{children:e.jsxs(Tt,{children:[e.jsx(It,{className:"text-base",children:"Private pitch workspace"}),e.jsx(Jn,{children:"Only the listing agent can view or update pitch strategy and owner information."})]})})}function n9s({listingId:s}){const{data:t=[],isLoading:n}=UMe(s),r=fFt(),a=gFt(),i=EOs(),l=j.useRef(null),[o,c]=j.useState("om"),[d,u]=j.useState("email"),h=async p=>{if(p!=null&&p.length)try{for(const f of Array.from(p))await r.mutateAsync({listingId:s,file:f,docKind:o,gateLevel:d});re.success("Document uploaded")}catch(f){re.error(f.message||"Upload failed")}finally{l.current&&(l.current.value="")}},m=async p=>{try{window.open(await MQe(p),"_blank")}catch{re.error("Could not open document")}};return e.jsx("div",{className:"space-y-6",children:e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-base",children:"Deal room"}),e.jsx(Jn,{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(Ns,{value:o,onValueChange:p=>c(p),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:Object.entries(kqe).map(([p,f])=>e.jsx(et,{value:p,children:f},p))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Access"}),e.jsxs(Ns,{value:d,onValueChange:p=>u(p),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:Object.entries(fmt).map(([p,f])=>e.jsx(et,{value:p,children:f},p))})]})]}),e.jsxs("div",{className:"flex items-end",children:[e.jsxs(U,{className:"w-full",onClick:()=>{var p;return(p=l.current)==null?void 0:p.click()},disabled:r.isPending,children:[r.isPending?e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(qa,{className:"mr-2 h-4 w-4"}),"Upload"]}),e.jsx("input",{ref:l,type:"file",multiple:!0,className:"hidden",onChange:p=>h(p.target.files)})]})]}),n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(Et,{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(Ur,{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(p=>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(Ur,{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:p.title||p.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(p.file_size/1024/1024).toFixed(2)," MB · ",p.download_count??0," downloads"]})]}),e.jsx(Be,{variant:"secondary",children:kqe[p.doc_kind||"other"]}),e.jsxs(Ns,{value:p.gate_level||"email",onValueChange:f=>i.mutate({id:p.id,listingId:s,values:{gate_level:f}}),children:[e.jsxs(ws,{className:"w-[190px]",children:[p.gate_level==="public"?e.jsx(pi,{className:"mr-2 h-3.5 w-3.5"}):p.gate_level==="nda"?e.jsx(cg,{className:"mr-2 h-3.5 w-3.5"}):e.jsx(Ql,{className:"mr-2 h-3.5 w-3.5"}),e.jsx(ks,{})]}),e.jsx(js,{children:Object.entries(fmt).map(([f,x])=>e.jsx(et,{value:f,children:x},f))})]}),e.jsx(U,{variant:"outline",size:"sm",onClick:()=>m(p.storage_path),children:"Preview"}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>a.mutate({id:p.id,storage_path:p.storage_path,listingId:s}),children:e.jsx(In,{className:"h-4 w-4"})})]},p.id))})]})]})})}const r9s={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 a9s({listingId:s}){const{data:t=[],isLoading:n}=FXe(s),{data:r=[]}=OXe(s),a=j.useMemo(()=>{const o={};for(const c of r)c.lead_id&&(o[c.lead_id]=(o[c.lead_id]??0)+(xmt[c.event_type]??1));return o},[r]),i=j.useMemo(()=>[...t].map(o=>({...o,score:(a[o.id]??0)+(xmt[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(Et,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[l.length>0&&e.jsxs(we,{className:"border-amber-500/30 bg-amber-500/[0.04]",children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-base",children:"High-interest prospects"}),e.jsx(Jn,{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=ymt(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||Sqe[o.investor_role||"other"]})]}),e.jsx(Be,{variant:"outline",className:c.tone,children:c.label})]}),e.jsxs("div",{className:"mt-3 flex gap-2",children:[e.jsx(U,{asChild:!0,size:"sm",variant:"outline",children:e.jsxs("a",{href:`mailto:${o.email}`,children:[e.jsx(ln,{className:"mr-1.5 h-3.5 w-3.5"})," Email"]})}),o.phone&&e.jsx(U,{asChild:!0,size:"sm",variant:"ghost",children:e.jsxs("a",{href:`tel:${o.phone}`,children:[e.jsx(ba,{className:"mr-1.5 h-3.5 w-3.5"})," Call"]})})]})]},o.id)})})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-base",children:"Investors & inquiries"}),e.jsx(Jn,{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(Bn,{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=ymt(o.score);return e.jsxs("div",{className:"flex flex-wrap items-center gap-3 p-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"truncate text-sm font-medium",children:[[o.first_name,o.last_name].filter(Boolean).join(" ")||o.email,o.company&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",o.company]})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[o.email,o.phone?` · ${o.phone}`:""," · ",new Date(o.created_at).toLocaleDateString()]}),o.message&&e.jsxs("p",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:['"',o.message,'"']})]}),o.investor_role&&e.jsx(Be,{variant:"secondary",children:Sqe[o.investor_role]??o.investor_role}),e.jsx(Be,{variant:"outline",children:r9s[o.lead_type]??o.lead_type}),e.jsx(Be,{variant:"outline",className:c.tone,children:c.label}),e.jsx(U,{asChild:!0,size:"sm",variant:"outline",children:e.jsx("a",{href:`mailto:${o.email}`,children:"Reply"})})]},o.id)})})})]})]})}const i9s={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 o9s({listing:s}){const{data:t=[],isLoading:n}=OXe(s.id),{data:r=[]}=FXe(s.id),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(!1),u=async p=>{d(!0);try{const{data:f,error:x}=await q.functions.invoke("commercial-seller-report",{body:{action:p?"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(f!=null&&f.error)throw new Error(f.error);re.success(p?"Activity report sent to your owner":"Weekly report generated")}catch(f){re.error(f.message||"Could not build the report")}finally{d(!1)}},h=j.useMemo(()=>{const p=y=>{const v=Array.isArray(y)?y:[y];return t.filter(b=>v.includes(b.event_type)).length},f=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:p("page_view")||s.view_count||0,unique:f.size,repeat:[...x.values()].filter(y=>y>3).length,omRequests:p(["om_request","om_download"]),downloads:p(["doc_download","om_download"]),tours:p("tour_request"),inquiries:r.length,shares:s.share_count??0}},[t,r,s]),m=[{label:"Microsite views",value:h.views,icon:xa},{label:"Unique visitors",value:h.unique,icon:Bn},{label:"Repeat visitors",value:h.repeat,icon:Lm},{label:"OM requests",value:h.omRequests,icon:DX},{label:"Document downloads",value:h.downloads,icon:pi},{label:"Tour requests",value:h.tours,icon:Lm},{label:"Total inquiries",value:h.inquiries,icon:Bn},{label:"Shares",value:h.shares,icon:jd}];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(p=>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(p.icon,{className:"h-3.5 w-3.5"}),e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.16em]",children:p.label})]}),e.jsx("p",{className:"mt-1.5 text-2xl font-semibold tabular-nums",children:p.value})]},p.label))}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-base",children:"Send the weekly owner report"}),e.jsx(Jn,{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(te,{children:"Owner email(s)"}),e.jsx(xe,{placeholder:"owner@example.com, asset.manager@example.com",value:a,onChange:p=>i(p.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Broker note (optional)"}),e.jsx(Fs,{rows:2,placeholder:"What you did this week and what happens next.",value:l,onChange:p=>o(p.target.value)})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(U,{onClick:()=>u(!0),disabled:c,children:[c?e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(ln,{className:"mr-2 h-4 w-4"}),"Send report"]}),e.jsx(U,{variant:"outline",onClick:()=>u(!1),disabled:c,children:"Save without sending"})]})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-base",children:"Owner activity report"}),e.jsx(Jn,{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(Et,{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(Lm,{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(p=>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:i9s[p.event_type]??p.event_type}),p.lead_id&&e.jsx(Be,{variant:"secondary",className:"shrink-0",children:"Identified"})]}),e.jsx("p",{className:"shrink-0 text-xs text-muted-foreground",children:new Date(p.created_at).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})})]},p.id))})})]})]})}function l9s({listing:s,details:t,publicUrl:n}){var f,x;const r=Wn(),[a,i]=j.useState(!1),l=s.photos??[],[o,c]=j.useState(0),d=(f=l[o])==null?void 0:f.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)??[],p=s.agent;return e.jsxs(qs,{title:"Commercial Listing",children:[e.jsxs("div",{className:"mx-auto max-w-6xl px-4 py-6",children:[e.jsxs(U,{variant:"ghost",size:"sm",className:"-ml-2 mb-4",onClick:()=>r("/mission-control/listings"),children:[e.jsx(Aa,{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:UM(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(pc,{className:"mr-2 h-5 w-5"})," No photos yet"]})}),l.length>1&&e.jsx("div",{className:"mt-3 flex gap-2 overflow-x-auto pb-1",children:l.map((y,v)=>e.jsx("button",{onClick:()=>c(v),className:`h-16 w-24 shrink-0 overflow-hidden rounded-lg border-2 ${v===o?"border-primary":"border-transparent"}`,children:e.jsx("img",{src:y.photo_url,alt:"",className:"h-full w-full object-cover"})},y.id??v))}),e.jsxs("div",{className:"mt-6 flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[e.jsxs(Be,{variant:"outline",className:"border-primary/30 bg-primary/10 text-primary",children:[e.jsx(_i,{className:"mr-1 h-3 w-3"})," Commercial"]}),(t==null?void 0:t.deal_type)&&e.jsx(Be,{variant:"secondary",children:uP[t.deal_type]}),(t==null?void 0:t.commercial_type)&&e.jsx(Be,{variant:"secondary",children:qP[t.commercial_type]}),(t==null?void 0:t.is_confidential)&&e.jsxs(Be,{variant:"outline",children:[e.jsx(Ql,{className:"mr-1 h-3 w-3"})," Confidential"]})]}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight md:text-3xl",children:UM(s,t)}),e.jsxs("p",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(ni,{className:"h-4 w-4"})," ",Xne(s,t)]}),e.jsx("p",{className:"mt-2 text-2xl font-semibold",children:BV(t,s.price)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.is_public&&e.jsxs(U,{variant:"outline",onClick:()=>window.open(n,"_blank"),children:[e.jsx(Sr,{className:"mr-2 h-4 w-4"})," View microsite"]}),s.allow_sharing&&e.jsxs(U,{onClick:()=>i(!0),children:[e.jsx(jd,{className:"mr-2 h-4 w-4"})," Share link"]})]})]}),e.jsx("div",{className:"mt-6",children:e.jsx(cRt,{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(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(cn,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsx("span",{children:y})]},v))})]}),h.length>0&&e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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:[fA(y.sf),y.rate,y.use,y.availability].filter(Boolean).join(" · ")})]},v))})]}),m.length>0&&e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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:[fA(y.sf),y.rent,y.lease_expiry].filter(Boolean).join(" · ")})]},v))})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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:(p==null?void 0:p.name)||"LevelUp Member"}),((x=p==null?void 0:p.brokerage)==null?void 0:x.name)&&e.jsx("p",{className:"text-muted-foreground",children:p.brokerage.name})]}),(p==null?void 0:p.email)&&e.jsxs(U,{variant:"outline",className:"w-full",onClick:()=>window.open(`mailto:${p.email}`),children:[e.jsx(ln,{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(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(JMe,{open:a,onOpenChange:i,listingId:s.id,listingSlug:s.slug??null,listingTitle:UM(s,t),isCommercial:!0})]})}function c9s(){const{listingId:s=""}=Di(),t=Wn(),{user:n}=vs(),[r,a]=fc(),{data:i,isLoading:l}=rre(s),{data:o}=rRt(s),{data:c=[]}=UMe(s),{data:d=[]}=OXe(s),{data:u=[]}=FXe(s),h=aRt(),m=oRt(),p=wAs(),f=cFt(),x=dFt(),y=uFt(),v=hFt(),[b,N]=j.useState(!1),[S,A]=j.useState(!1),[T,L]=j.useState(!1),[M,I]=j.useState(!1),[R,z]=j.useState(!1),$=r.get("tab")||"overview",H=ie=>a({tab:ie},{replace:!0}),V=i?`${window.location.origin}/public/listing/${i.slug||i.id}`:"",K=j.useMemo(()=>{var ie;return vAs(o,{photoCount:((ie=i==null?void 0:i.photos)==null?void 0:ie.length)??0,hasOm:c.some(ce=>ce.doc_kind==="om"),isPublic:!!(i!=null&&i.is_public)})},[o,i,c]),Z=async ie=>{var ce;if(!(!ie||!i)){N(!0);try{for(const je of Array.from(ie)){const be=je.name.split(".").pop(),he=`${n==null?void 0:n.id}/${i.id}/${Date.now()}-${Math.random().toString(36).slice(2)}.${be}`,{error:ge}=await q.storage.from("listing-photos").upload(he,je);if(ge)throw ge;const{data:{publicUrl:ke}}=q.storage.from("listing-photos").getPublicUrl(he);await f.mutateAsync({listingId:i.id,photoUrl:ke,isPrimary:!((ce=i.photos)!=null&&ce.length)})}re.success("Photos uploaded")}catch(je){re.error(je.message||"Upload failed")}finally{N(!1)}}};if(l)return e.jsx(qs,{title:"Commercial Launch",children:e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:e.jsx(Et,{className:"h-6 w-6 animate-spin text-muted-foreground"})})});if(!i)return e.jsx(qs,{title:"Commercial Launch",children:e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center text-muted-foreground",children:"Listing not found"})});const Q=i.lifecycle_stage==="pitch",le=i.lifecycle_stage??"won",ue=dOe.findIndex(ie=>ie.key===le),se=UM(i,o),ne=!!(n!=null&&n.id)&&i.agent_id===n.id;return ne?e.jsx(qs,{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(U,{variant:"ghost",size:"sm",className:"-ml-2 mb-4",onClick:()=>t("/mission-control/listings"),children:[e.jsx(Aa,{className:"mr-2 h-4 w-4"})," Listing Exchange"]}),e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[e.jsxs(Be,{variant:"outline",className:"border-primary/30 bg-primary/10 text-primary",children:[e.jsx(_i,{className:"mr-1 h-3 w-3"})," Commercial Launch"]}),(o==null?void 0:o.deal_type)&&e.jsx(Be,{variant:"secondary",children:uP[o.deal_type]}),(o==null?void 0:o.commercial_type)&&e.jsx(Be,{variant:"secondary",children:qP[o.commercial_type]}),Q&&e.jsxs(Be,{className:"bg-amber-500/15 text-amber-600 hover:bg-amber-500/15",children:[e.jsx(Gu,{className:"mr-1 h-3 w-3"})," Pitch — private"]}),(o==null?void 0:o.is_confidential)&&e.jsxs(Be,{variant:"outline",children:[e.jsx(Ql,{className:"mr-1 h-3 w-3"})," Confidential"]})]}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight md:text-3xl",children:se}),e.jsx("p",{className:"text-muted-foreground",children:Xne(i,o)}),e.jsx("p",{className:"mt-2 text-xl font-semibold",children:BV(o,i.price)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[!ne&&e.jsxs(Be,{variant:"outline",className:"self-center",children:[e.jsx(Ql,{className:"mr-1 h-3 w-3"})," View only — listing agent controls updates"]}),ne&&e.jsxs(U,{variant:"outline",onClick:()=>t(`/mission-control/listings/${i.id}/commercial/edit`),children:[e.jsx(ri,{className:"mr-2 h-4 w-4"})," Edit details"]}),ne&&!Q&&!i.is_public&&e.jsxs(U,{onClick:()=>{p.mutate({listingId:i.id,values:{is_public:!0,allow_sharing:!0,status:"active"}}),le==="won"&&m.mutate({listingId:i.id,stage:"launched"})},children:[e.jsx(Sr,{className:"mr-2 h-4 w-4"})," Publish & go live"]}),!Q&&i.is_public&&e.jsxs(U,{variant:"outline",onClick:()=>window.open(V,"_blank"),children:[e.jsx(Sr,{className:"mr-2 h-4 w-4"})," View microsite"]})]})]}),!Q&&e.jsx("div",{className:"mt-6 flex flex-wrap items-center gap-2",children:dOe.filter(ie=>ie.key!=="pitch").map((ie,ce)=>{const je=dOe.findIndex(ge=>ge.key===ie.key),be=je===ue,he=jene&&m.mutate({listingId:i.id,stage:ie.key}),className:`flex items-center gap-2 rounded-full border px-3.5 py-1.5 text-xs font-medium transition-colors ${be?"border-primary bg-primary text-primary-foreground":he?"border-primary/30 bg-primary/10 text-primary":"text-muted-foreground hover:bg-muted"} ${ne?"":"cursor-default"}`,children:[he&&e.jsx(Xr,{className:"h-3 w-3"})," ",ie.label,ce<4&&e.jsx("span",{className:"ml-1 opacity-40",children:"›"})]},ie.key)})})]})}),e.jsx("div",{className:"mx-auto max-w-7xl px-4 py-8",children:Q?e.jsx(s9s,{listing:i,canEdit:ne}):e.jsxs(oa,{value:ne||["overview","marketing"].includes($)?$:"overview",onValueChange:H,children:[e.jsxs(la,{className:"mb-6 flex w-full flex-wrap justify-start",children:[e.jsx(Kt,{value:"overview",children:"Overview"}),e.jsx(Kt,{value:"marketing",children:"Marketing"}),ne&&e.jsx(Kt,{value:"investors",children:"Investors & Leads"}),ne&&e.jsx(Kt,{value:"reporting",children:"Reporting"}),ne&&e.jsx(Kt,{value:"documents",children:"Documents"}),ne&&e.jsx(Kt,{value:"settings",children:"Settings"})]}),e.jsxs(Zt,{value:"overview",className:"space-y-6",children:[e.jsx(cRt,{details:o}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs(we,{className:"lg:col-span-2",children:[e.jsxs(Tt,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{className:"text-base",children:"Launch readiness"}),e.jsx(Jn,{children:"Everything an institutional-quality launch needs."})]}),e.jsxs("span",{className:"text-2xl font-semibold tabular-nums",children:[K.score,"%"]})]}),e.jsx(ro,{value:K.score,className:"mt-3"})]}),e.jsx(Ie,{className:"space-y-2",children:k5e.map(ie=>{const ce=K.done.includes(ie.key);return e.jsxs("button",{disabled:!ne,onClick:()=>ne&&h.mutate({listingId:i.id,values:{launch_checklist:{...(o==null?void 0:o.launch_checklist)??{},[ie.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(Xr,{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:ie.label}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:ie.detail})]})]},ie.key)})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Quick actions"})}),e.jsxs(Ie,{className:"grid gap-2",children:[e.jsxs(U,{variant:"outline",className:"justify-start",onClick:()=>A(!0),children:[e.jsx(jd,{className:"mr-2 h-4 w-4"})," Share link"]}),e.jsxs(U,{variant:"outline",className:"justify-start",onClick:()=>L(!0),children:[e.jsx(Sf,{className:"mr-2 h-4 w-4"})," Signage QR code"]}),ne&&e.jsxs(U,{variant:"outline",className:"justify-start",onClick:()=>I(!0),children:[e.jsx(ln,{className:"mr-2 h-4 w-4"})," Email brokers & investors"]}),ne&&e.jsxs(U,{variant:"outline",className:"justify-start",onClick:()=>z(!0),children:[e.jsx(cn,{className:"mr-2 h-4 w-4"})," Generate social post"]}),ne&&e.jsxs(U,{variant:"outline",className:"justify-start",onClick:()=>H("documents"),children:[e.jsx(Ql,{className:"mr-2 h-4 w-4"})," Manage gated OM"]})]})]}),(o==null?void 0:o.call_for_offers_at)&&e.jsxs(we,{className:"border-amber-500/30 bg-amber-500/[0.05]",children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{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(ch,{className:"h-4 w-4"}),new Date(o.call_for_offers_at).toLocaleDateString(void 0,{month:"long",day:"numeric",year:"numeric"})]})})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Recent engagement"})}),e.jsxs(Ie,{className:"space-y-2",children:[d.slice(0,6).map(ie=>e.jsxs("div",{className:"flex items-center justify-between gap-2 text-sm",children:[e.jsx("span",{className:"truncate capitalize",children:ie.event_type.replace(/_/g," ")}),e.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:new Date(ie.created_at).toLocaleDateString(void 0,{month:"short",day:"numeric"})})]},ie.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(Zt,{value:"marketing",className:"space-y-6",children:[e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-base",children:"Photography"}),e.jsx(Jn,{children:"The first image becomes the cinematic microsite hero."})]}),e.jsx(Ie,{children:ne?e.jsx(BFt,{photos:i.photos??[],uploading:b,onUpload:Z,onRemove:ie=>x.mutate({photoId:ie,listingId:i.id}),onReorder:ie=>y.mutate({photos:ie.map(ce=>({id:ce.id,sort_order:ce.sort_order,is_primary:ce.is_primary}))}),onSetPrimary:ie=>v.mutate({photoId:ie,listingId:i.id})}):e.jsxs("div",{className:"grid grid-cols-2 gap-3 md:grid-cols-4",children:[(i.photos??[]).map(ie=>e.jsx("img",{src:ie.photo_url,alt:se,className:"aspect-[4/3] w-full rounded-lg object-cover",loading:"lazy"},ie.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:fl,title:"Property microsite",body:"Institutional-grade public page with gated OM.",action:()=>window.open(V,"_blank"),cta:"Preview"},{icon:Sf,title:"Signage QR",body:"On-site sign that routes to the microsite.",action:()=>L(!0),cta:"Create"},...ne?[{icon:ln,title:"Broker & investor email",body:"Send to targeted segments of your database.",action:()=>I(!0),cta:"Compose"},{icon:cn,title:"Social & LinkedIn",body:"Branded launch graphics and copy.",action:()=>z(!0),cta:"Generate"}]:[]].map(ie=>e.jsxs(we,{className:"flex flex-col",children:[e.jsxs(Tt,{className:"pb-3",children:[e.jsx(ie.icon,{className:"mb-2 h-5 w-5"}),e.jsx(It,{className:"text-sm",children:ie.title}),e.jsx(Jn,{className:"text-xs",children:ie.body})]}),e.jsx(Ie,{className:"mt-auto",children:e.jsx(U,{size:"sm",variant:"outline",className:"w-full",onClick:ie.action,children:ie.cta})})]},ie.title))})]}),ne&&e.jsx(Zt,{value:"investors",children:e.jsx(a9s,{listingId:i.id})}),ne&&e.jsx(Zt,{value:"reporting",children:e.jsx(o9s,{listing:i})}),ne&&e.jsx(Zt,{value:"documents",children:e.jsx(n9s,{listingId:i.id})}),ne&&e.jsx(Zt,{value:"settings",className:"space-y-6",children:e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-base",children:"Visibility"}),e.jsx(Jn,{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(te,{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(wn,{checked:!!i.is_public,onCheckedChange:ie=>{p.mutate({listingId:i.id,values:{is_public:ie,allow_sharing:ie?!0:i.allow_sharing}}),ie&&le==="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(te,{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(wn,{checked:!!i.share_with_brokerage,onCheckedChange:ie=>p.mutate({listingId:i.id,values:{share_with_brokerage:ie}})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Confidential offering"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Teaser mode, address hidden, search engines blocked."})]}),e.jsx(wn,{checked:!!(o!=null&&o.is_confidential),onCheckedChange:ie=>h.mutate({listingId:i.id,values:{is_confidential:ie}})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Hide street address"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show city / submarket only."})]}),e.jsx(wn,{checked:!!(o!=null&&o.hide_address),onCheckedChange:ie=>h.mutate({listingId:i.id,values:{hide_address:ie}})})]}),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(U,{variant:"ghost",size:"icon",onClick:()=>{navigator.clipboard.writeText(V),re.success("Copied")},children:e.jsx(Pa,{className:"h-3.5 w-3.5"})})]})]})]})})]})}),e.jsx(JMe,{open:S,onOpenChange:A,listingId:i.id,listingSlug:i.slug,listingTitle:se,isCommercial:!0}),e.jsx(QFt,{open:T,onOpenChange:L,url:V,title:se,fileBase:i.slug||i.id}),e.jsx(l7t,{open:M,onOpenChange:I,listing:i}),e.jsx(UQe,{open:R,onOpenChange:z,listingId:i.id})]})}):Q?e.jsx(qs,{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(l9s,{listing:i,details:o,publicUrl:V})}function d9s(){var m,p,f;const{token:s=""}=Di(),{data:t,isLoading:n,error:r}=ct({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=(p=(m=a.photos)==null?void 0:m[0])==null?void 0:p.photo_url,d=zXe(i).slice(0,4),u=l.launch_plan??[],h=[{icon:fl,label:"Dedicated property microsite",detail:"An institutional-grade page built for this asset alone."},{icon:Ur,label:"Offering Memorandum & teaser",detail:"Gated, tracked and released only to qualified prospects."},{icon:ln,label:"Targeted broker & investor email",detail:"Direct outreach to buyers, brokers and 1031 capital."},{icon:Sf,label:"Signage, QR & social distribution",detail:"On-site and digital presence working together."},{icon:Cl,label:"Weekly owner activity reporting",detail:"Views, OM requests, downloads, tours and prospect interest."},{icon:cg,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 — ",UM(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:UM(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(ni,{className:"h-4 w-4"})," ",Xne(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:uP[(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:qP[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:BV(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:((f=o.brokerage)==null?void 0:f.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 u9s={office_exclusive:"Office Exclusive",coming_soon:"Coming Soon",pre_market:"Pre-Market",active:"Active"},h9s=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s||0);function m9s(){var ie;const[s]=fc(),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),[p,f]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState(""),[N,S]=j.useState(""),[A,T]=j.useState("tour"),[L,M]=j.useState(!1),[I,R]=j.useState(!1),z=async()=>{if(!p.trim()||!x.trim()){re.error("Please enter your name and email");return}M(!0);try{const je=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:p.trim(),email:x.trim(),phone:v.trim()||null,message:N.trim()||null,intent:A})}),be=await je.json();if(!je.ok||!(be!=null&&be.success))throw new Error((be==null?void 0:be.error)||"Could not send");R(!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{M(!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(je=>je.json()).then(je=>{je.error?l("This private listing link is no longer valid."):a({listing:je.listing,agent:je.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(Ql,{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:$,agent:H}=r,V=(ie=$.photos)!=null&&ie.length?$.photos:[],K=V[0],Z=u9s[$.status]||$.status,Q=(H==null?void 0:H.sender_name)||(H==null?void 0:H.name)||"Your Agent",le=(H==null?void 0:H.sender_email)||null,ue=encodeURIComponent(`Interested in ${$.address}`),se=encodeURIComponent(`Hi ${Q}, I'd love to learn more about ${$.address}, ${$.city}. Thanks!`),ne=H!=null&&H.booking_slug?`https://dashboard.relevelup.com/book/${H.booking_slug}`:null;return e.jsxs(e.Fragment,{children:[e.jsxs(dl,{children:[e.jsxs("title",{children:["Private Listing · ",$.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(Ql,{className:"h-3.5 w-3.5"}),e.jsxs("span",{className:"font-medium tracking-wide uppercase",children:["Private listing · Shared by ",Q]})]}),e.jsxs("div",{className:"relative",children:[K?e.jsx("button",{type:"button",className:"block w-full",onClick:()=>{u(0),m(!0)},children:e.jsx("img",{src:K,alt:$.address,className:"w-full h-[42vh] md:h-[60vh] object-cover"})}):e.jsx("div",{className:"w-full h-[42vh] md:h-[60vh] bg-slate-200 flex items-center justify-center text-slate-400",children:"No photos available"}),e.jsx("div",{className:"absolute top-4 left-4",children:e.jsx(Be,{className:"bg-indigo-600 text-white border-0 text-xs px-2.5 py-1 shadow",children:Z})}),V.length>1&&e.jsxs("div",{className:"absolute bottom-4 right-4 bg-black/60 text-white text-xs px-2.5 py-1 rounded-full",children:[V.length," photos"]})]}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 sm:px-6 -mt-10 relative z-10",children:[e.jsx(we,{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:$.address}),e.jsxs("p",{className:"text-slate-600 mt-1 flex items-center gap-1.5",children:[e.jsx(ni,{className:"h-4 w-4"}),$.city,", ",$.state," ",$.zip]})]}),e.jsx("div",{className:"text-right",children:e.jsx("p",{className:"text-3xl sm:text-4xl font-bold text-indigo-600",children:h9s($.price)})})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mt-6",children:[$.bedrooms?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(Xw,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:$.bedrooms}),e.jsx("p",{className:"text-xs text-slate-500",children:"Beds"})]}):null,$.bathrooms?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(d0,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:$.bathrooms}),e.jsx("p",{className:"text-xs text-slate-500",children:"Baths"})]}):null,$.sqft?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(db,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:$.sqft.toLocaleString()}),e.jsx("p",{className:"text-xs text-slate-500",children:"Sq Ft"})]}):null]}),$.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:$.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,je)=>e.jsx("button",{type:"button",onClick:()=>{u(je),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"})},je))})]})]})}),e.jsxs(we,{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:[Q," will get back to you personally."]})]}),e.jsx(Ie,{className:"p-6 sm:p-8",children:I?e.jsxs("div",{className:"flex flex-col items-center text-center py-6",children:[e.jsx(zr,{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:[Q," 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:()=>T(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(te,{htmlFor:"pl-name",children:"Your name *"}),e.jsx(xe,{id:"pl-name",value:p,onChange:ce=>f(ce.target.value),placeholder:"Jane Doe",maxLength:120})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"pl-email",children:"Email *"}),e.jsx(xe,{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(te,{htmlFor:"pl-phone",children:"Phone (optional)"}),e.jsx(xe,{id:"pl-phone",value:v,onChange:ce=>b(ce.target.value),placeholder:"(555) 555-5555",maxLength:40})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"pl-msg",children:"Message (optional)"}),e.jsx(Fs,{id:"pl-msg",value:N,onChange:ce=>S(ce.target.value),placeholder:`I'd love to see ${$.address}…`,rows:4,maxLength:2e3})]}),e.jsx(U,{onClick:z,disabled:L,className:"w-full bg-indigo-600 hover:bg-indigo-700 h-11 text-base",children:L?"Sending…":"Send to "+Q.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(we,{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:[H!=null&&H.avatar_url?e.jsx("img",{src:H.avatar_url,alt:Q,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:Q.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:Q}),(H==null?void 0:H.brokerage_name)&&e.jsx("p",{className:"text-slate-600 text-sm",children:H.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:[le&&e.jsx(U,{asChild:!0,className:"bg-indigo-600 hover:bg-indigo-700",children:e.jsxs("a",{href:`mailto:${le}?subject=${ue}&body=${se}`,children:[e.jsx(ln,{className:"h-4 w-4 mr-1.5"}),"Email"]})}),(H==null?void 0:H.phone)&&e.jsx(U,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:`tel:${H.phone}`,children:[e.jsx(ba,{className:"h-4 w-4 mr-1.5"}),H.phone]})}),ne&&e.jsx(U,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:ne,target:"_blank",rel:"noreferrer",children:[e.jsx(ch,{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(er,{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(rd,{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(gi,{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 p9s(){var i;const{slug:s}=Di(),{data:t,isLoading:n,error:r}=mRt(s);if(j.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]),j.useEffect(()=>{t!=null&&t.id&&_d(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(UXe,{card:t})]})}const f9s="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1600&q=80",g9s="https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?w=1600&q=80",x9s="https://images.unsplash.com/photo-1500534314209-a25ddb2bd429?w=1600&q=80",y9s="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=1600&q=80",v9s="https://images.unsplash.com/photo-1519741497674-611481863552?w=1600&q=80",b9s="https://images.unsplash.com/photo-1494526585095-c41746248156?w=1600&q=80",z5e={"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:b9s},"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:f9s},"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:g9s},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:x9s},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:y9s},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:v9s}},_9s=["#111111","#2f7a7d","#c9a84c","#d84a7a","#3b6fa0","#9b72cf","#e85d3a","#4a6741"];function c7t(s){return s&&s in z5e?z5e[s]:z5e["minimal-mono"]}function w9s(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 d7t({slugOverride:s}={}){var dn;const{slug:t}=Di(),n=s||t,[r]=fc(),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),[p,f]=j.useState(null),[x,y]=j.useState(null),[v,b]=j.useState(!1),[N,S]=j.useState(!1),[A,T]=j.useState(0),[L,M]=j.useState(!1),[I,R]=j.useState(""),[z,$]=j.useState(""),[H,V]=j.useState(""),[K,Z]=j.useState(""),[Q,le]=j.useState(""),[ue,se]=j.useState(""),[ne,ie]=j.useState(""),[ce,je]=j.useState(""),[be,he]=j.useState(""),[ge,ke]=j.useState(""),[Te,Me]=j.useState(""),[Oe,Se]=j.useState(""),[Qe,Ae]=j.useState(""),[Fe,Ne]=j.useState([]),[$e,Ve]=j.useState([]),[qe,Ze]=j.useState(""),[Ue,Ye]=j.useState(""),[Ge,He]=j.useState(""),[tt,pt]=j.useState([]);j.useEffect(()=>{ft()},[n,a]);const ft=async()=>{if(!n)return;l(!0);const{data:rn,error:br}=await q.from("contact_intake_pages").select("*").eq("slug",n).eq("is_active",!0).maybeSingle();if(br||!rn){M(!0),l(!1);return}u(rn),m.current=rn;const{data:Gn}=await q.from("profiles").select("name, avatar_url, title, phone, email, brokerage_id").eq("id",rn.user_id).single();if(Gn){let On;if(Gn.brokerage_id){const{data:Hs}=await q.from("brokerages").select("name").eq("id",Gn.brokerage_id).single();On=(Hs==null?void 0:Hs.name)||void 0}let Rr=Gn.avatar_url||null;if(!Rr){const{data:Hs}=q.storage.from("avatars").getPublicUrl(`${rn.user_id}/avatar.jpg`);Hs!=null&&Hs.publicUrl&&(Rr=`${Hs.publicUrl}?t=${Date.now()}`)}const cr={...Gn,avatar_url:Rr,brokerage_name:On};c(cr),h.current=cr}if(a)try{console.log("[ConnectPage] Resolving token:",a,"for page:",rn.id);const{data:On,error:Rr}=await q.functions.invoke("process-intake-submissions",{body:{action:"resolve_token",token:a,page_id:rn.id}});if(console.log("[ConnectPage] Resolve result:",{resolved:On,resolveErr:Rr}),!Rr&&(On!=null&&On.contact_id)){y(On.contact_id);const cr=On.contact;cr&&(f(cr),R(cr.first_name||""),$(cr.last_name||""),V(cr.email||""),Z(cr.phone||""),le(cr.address||""),se(cr.city||""),ie(cr.state||""),je(cr.zip||""),he(cr.birthday||""),ke(cr.home_anniversary||""))}}catch(On){console.error("Failed to resolve token:",On)}l(!1)},qt=async()=>{var rn,br;if(!I.trim()){re.error("Please enter your first name");return}if(!n){re.error("Invalid page. Please refresh.");return}S(!0);try{let Gn=(rn=m.current)==null?void 0:rn.id,On=(br=m.current)==null?void 0:br.user_id;if(!Gn||!On){const{data:Hs}=await q.from("contact_intake_pages").select("id, user_id").eq("slug",n).eq("is_active",!0).maybeSingle();if(!Hs){re.error("This page is no longer active. Please contact the agent directly."),S(!1);return}Gn=Hs.id,On=Hs.user_id}const Rr={intake_page_id:Gn,agent_user_id:On,existing_contact_id:x,first_name:I.trim(),last_name:z.trim()||null,email:H.trim()||null,phone:K.trim()||null,address:Q.trim()||null,city:ue.trim()||null,state:ne.trim()||null,zip:ce.trim()||null,birthday:be||null,home_anniversary:ge||null,real_estate_interest:Te||null,message:Oe.trim()||null,life_events:{spouse_name:Qe.trim()||null,kids:Fe.filter(Hs=>Hs.name.trim()),pets:$e.filter(Hs=>Hs.name.trim()),favorite_spots:qe.trim()||null,dream_neighborhood:Ue.trim()||null,wedding_anniversary:Ge||null},referrals:tt.filter(Hs=>Hs.name.trim()&&Hs.contact.trim())},{error:cr}=await q.from("contact_intake_submissions").insert(Rr);if(console.log("[ConnectPage] Insert result:",{error:cr}),cr)throw cr;a&&await q.from("contact_intake_tokens").update({used_at:new Date().toISOString()}).eq("token",a);try{const Hs=[I.trim(),z.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:On,contactName:Hs,contactEmail:H.trim()||null,contactPhone:K.trim()||null,slug:n})})}catch(Hs){console.warn("Connect page notification failed (non-blocking):",Hs)}b(!0)}catch(Gn){console.error(Gn),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(Et,{className:"h-8 w-8 animate-spin text-slate-400"})});if(L)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(kr.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(kr.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(zr,{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(ko,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})]})]});const Ut=!!a&&!!p,Wt=(d==null?void 0:d.show_little_things)??!0,us=[{title:Ut?"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:I,onChange:rn=>R(rn.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:z,onChange:rn=>$(rn.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:H,onChange:rn=>V(rn.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:K,onChange:rn=>Z(rn.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:Q,onChange:rn=>le(rn.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:ue,onChange:rn=>se(rn.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:ne,onChange:rn=>ie(rn.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:rn=>je(rn.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:be,onChange:rn=>he(rn.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:ge,onChange:rn=>ke(rn.target.value),className:"connect-input"})]})]})]})},...Wt?[{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:Qe,onChange:rn=>Ae(rn.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:Ge,onChange:rn=>He(rn.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:()=>Ne(rn=>[...rn,{name:"",age:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(an,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[Fe.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),Fe.map((rn,br)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:rn.name,onChange:Gn=>Ne(On=>On.map((Rr,cr)=>cr===br?{...Rr,name:Gn.target.value}:Rr)),placeholder:"Child's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:rn.age,onChange:Gn=>Ne(On=>On.map((Rr,cr)=>cr===br?{...Rr,age:Gn.target.value}:Rr)),placeholder:"Age",className:"connect-input shrink-0",style:{width:"5rem"}}),e.jsx("button",{type:"button",onClick:()=>Ne(Gn=>Gn.filter((On,Rr)=>Rr!==br)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(er,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},br))]})]}),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:()=>Ve(rn=>[...rn,{name:"",kind:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(an,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[$e.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),$e.map((rn,br)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:rn.name,onChange:Gn=>Ve(On=>On.map((Rr,cr)=>cr===br?{...Rr,name:Gn.target.value}:Rr)),placeholder:"Pet's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:rn.kind,onChange:Gn=>Ve(On=>On.map((Rr,cr)=>cr===br?{...Rr,kind:Gn.target.value}:Rr)),placeholder:"Dog, cat…",className:"connect-input shrink-0",style:{width:"7rem"}}),e.jsx("button",{type:"button",onClick:()=>Ve(Gn=>Gn.filter((On,Rr)=>Rr!==br)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(er,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},br))]})]}),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:rn=>Ze(rn.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:Ue,onChange:rn=>Ye(rn.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."})]}),tt.length<3&&e.jsxs("button",{type:"button",onClick:()=>pt(rn=>[...rn,{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(an,{className:"h-3 w-3"})," Add"]})]}),e.jsx("div",{className:"space-y-2",children:tt.map((rn,br)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:rn.name,onChange:Gn=>pt(On=>On.map((Rr,cr)=>cr===br?{...Rr,name:Gn.target.value}:Rr)),placeholder:"Their name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:rn.contact,onChange:Gn=>pt(On=>On.map((Rr,cr)=>cr===br?{...Rr,contact:Gn.target.value}:Rr)),placeholder:"Phone or email",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("button",{type:"button",onClick:()=>pt(Gn=>Gn.filter((On,Rr)=>Rr!==br)),className:"p-2 rounded-md hover:bg-black/5","aria-label":"Remove",children:e.jsx(er,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},br))})]})]})}]:[],{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(rn=>e.jsxs("button",{type:"button",onClick:()=>Me(Te===rn.value?"":rn.value),className:`p-3.5 rounded-xl border-2 text-left transition-all ${Te===rn.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:rn.label}),e.jsx("span",{className:"block text-xs text-slate-500 mt-0.5",children:rn.desc})]},rn.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:Oe,onChange:rn=>Se(rn.target.value),placeholder:"Feel free to drop a note...",rows:3,className:"connect-input resize-none"})]})]})}],zt=us.length,bt=c7t(d==null?void 0:d.theme),As=w9s(bt,(d==null?void 0:d.accent_color)||null),vt=(d==null?void 0:d.cover_image_url)||bt.defaultCover,Ws=(d==null?void 0:d.headline)||"Let's stay connected",on=(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)||""),Ms=["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:`${Ws} — ${(o==null?void 0:o.name)||"your agent"}`}),vt&&e.jsx("meta",{property:"og:image",content:vt}),e.jsx("meta",{property:"og:title",content:`Connect with ${(o==null?void 0:o.name)||"me"}`}),e.jsx("meta",{property:"og:description",content:Ws}),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(kr.img,{src:vt,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(kr.h1,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.15,duration:.6},style:{color:"#fff",fontFamily:bt.headingFont,fontWeight:500,letterSpacing:"-0.01em"},className:"text-3xl sm:text-4xl leading-tight",children:Ws}),on&&e.jsx(kr.p,{initial:{opacity:0},animate:{opacity:.9},transition:{delay:.35,duration:.6},style:{color:"#fff"},className:"text-sm mt-2",children:on})]})]}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 pb-12 -mt-12 relative",children:[e.jsxs(kr.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:bt.accent,color:bt.accentText,border:"4px solid var(--c-surface)"},children:e.jsx("span",{className:"text-3xl font-bold",children:((dn=o==null?void 0:o.name)==null?void 0:dn.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(ba,{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(ln,{className:"h-4 w-4"})})]})]}),e.jsx(kr.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:zt}).map((rn,br)=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-all duration-500",style:{background:br<=A?"var(--c-accent)":"color-mix(in srgb, var(--c-text) 12%, transparent)"}},br))}),e.jsxs(kr.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:Ms?"0 20px 40px -20px rgba(0,0,0,0.5)":"0 20px 40px -20px rgba(0,0,0,0.15)"},children:[e.jsx(_G,{mode:"wait",children:e.jsxs(kr.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(cn,{className:"h-4 w-4",style:{color:"var(--c-accent)"}}),e.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--c-text)"},children:us[A].title})]}),us[A].subtitle&&e.jsx("p",{className:"text-xs mt-1 ml-6",style:{color:"var(--c-text-muted)"},children:us[A].subtitle})]}),us[A].fields]},A)}),e.jsxs("div",{className:"flex justify-between mt-8",children:[A>0?e.jsx("button",{type:"button",onClick:()=>T(rn=>rn-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&&!I.trim()){re.error("Please enter your first name");return}T(rn=>rn+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:()=>qt(),disabled:N,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:N?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):"Submit"})]}),A>0&&AT(rn=>rn+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(ko,{className:"h-3 w-3"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})})]})]})}const EG=()=>({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 eY({banners:s,autoPlayInterval:t=5e3,className:n}){const[r,a]=j.useState(0),[i,l]=j.useState(!1),{trackEngagement:o}=EG(),c=j.useCallback(p=>{o("newsletter",p.id,p.title,"click_link")},[o]),d=j.useCallback(()=>{a(p=>(p+1)%s.length)},[s.length]),u=j.useCallback(()=>{a(p=>(p-1+s.length)%s.length)},[s.length]),h=j.useCallback(p=>{a(p)},[]);if(j.useEffect(()=>{if(s.length<=1||i)return;const p=setInterval(d,t);return()=>clearInterval(p)},[s.length,i,t,d]),!s||s.length===0)return null;const m=s[r];return e.jsxs("div",{className:Mt("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(U,{variant:"ghost",size:"icon",className:Mt("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(rd,{className:"h-6 w-6"})}),e.jsx(U,{variant:"ghost",size:"icon",className:Mt("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(gi,{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((p,f)=>e.jsx("button",{onClick:()=>h(f),className:Mt("w-2 h-2 rounded-full transition-all duration-300",f===r?"bg-white w-6":"bg-white/50 hover:bg-white/70"),"aria-label":`Go to slide ${f+1}`},f))})]}),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(U,{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 j9s=["reserved","scheduled_for_charge","paid","payment_failed","completed"],GV=s=>!!s&&(s.access_override||j9s.includes(s.status)),gf=(s,t="usd")=>new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase(),maximumFractionDigits:s%100===0?0:2}).format(s/100),gee=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`},d$e=(s,t="usd",n)=>`One-time payment: ${gf(s,t)} for the ${gee(n)}`,qQe=[{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}],xee=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:[]}},N9s=(s,t)=>!s.hidden.includes(t),$ft=(s,t)=>s.required.includes(t)&&!s.hidden.includes(t),Zd=(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,aPe=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&&rct({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||[]}}),$Qe=s=>ct({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}}),h7t=s=>ct({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}}),VQe=()=>{const{user:s}=vs();return ct({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||[]}})},HQe=s=>{const{data:t=[],...n}=VQe();return{...n,data:s&&t.find(r=>r.program_id===s)||null}},k9s=()=>{const{user:s}=vs(),t=Qt();return yt({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")})},m7t=s=>{const{user:t}=vs();return ct({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}})},S9s=()=>{const s=Qt();return yt({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"]})}})},C9s=(s,t)=>{const{user:n}=vs(),r=t||(n==null?void 0:n.id);return ct({queryKey:["program-workspace",s,r],enabled:!!s&&!!r,queryFn:async()=>{const a=r,[i,l,o,c,d,u,h,m,p,f,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:p.data||[],analysis:f.data||null}}})},A9s=s=>{const{user:t}=vs(),n=Qt();return yt({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")})},E9s=s=>{const{user:t}=vs(),n=Qt();return yt({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")})},T9s=s=>{const{user:t}=vs(),n=Qt();return yt({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")})},M9s=s=>{const{user:t}=vs(),n=Qt();return yt({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")})},P9s=s=>ct({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||[]}}),L9s=s=>{const t=Qt();return yt({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")}})},I9s=()=>{const s=Qt();return yt({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")})},R9s=()=>yt({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}}),D9s=()=>yt({mutationFn:async s=>{const{error:t}=await q.rpc("program_clear_discount",{_enrollment_id:s});if(t)throw t}}),O9s=s=>ct({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||[]}}),F9s=s=>{const t=Qt();return yt({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")})},z9s=()=>{const s=Qt();return yt({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")})},B9s=s=>ct({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||[]}}}),U9s=s=>{const t=Qt();return yt({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")})},q9s=()=>{const s=Qt();return yt({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")})},p7t=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},PQ=s=>!!s&&/\.(mp4|webm|mov|m4v)(\?|$)/i.test(s),f7t=[{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"}],TG="event-images",ure=s=>{if(s.file_path){const{data:t}=q.storage.from(TG).getPublicUrl(s.file_path);return t.publicUrl}return s.url||null},LQ=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(TG).download(s.file_path);if(r||!n){const c=ure(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)},g7t=s=>ct({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||[]}}),$9s=s=>{const t=Qt();return yt({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")})},V9s=()=>{const s=Qt();return yt({mutationFn:async t=>{t.file_path&&await q.storage.from(TG).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")})},H9s=(s,t)=>ct({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||[]}}),G9s=(s,t)=>{const n=Qt(),{user:r}=vs();return yt({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")})},W9s=()=>{const s=Qt();return yt({mutationFn:async t=>{t.file_path&&await q.storage.from(TG).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")})},K9s=s=>{const{user:t}=vs();return ct({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}})},Y9s=s=>{const t=Qt(),{user:n}=vs();return yt({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")})},Z9s=s=>ct({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}})}}),X9s=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)},Q9s=()=>{const{data:s=[]}=u7t(),{data:t=[]}=VQe(),n=new Set(t.filter(GV).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=X9s(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(pv,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("h3",{className:"text-lg font-semibold leading-tight",children:a.name}),l&&e.jsx(Be,{variant:"secondary",children:l})]}),e.jsxs("p",{className:"mt-0.5 text-sm text-muted-foreground",children:[a.kickoff_at?`Starts ${Zd(a.kickoff_at)} · `:"","Your program dashboard is live — lessons, resources and sessions inside."]})]})]}),e.jsx(U,{asChild:!0,size:"lg",className:"shrink-0",children:e.jsxs(xr,{to:`/programs/${a.slug}/workspace`,children:["Open program dashboard",e.jsx(Oa,{className:"ml-1.5 h-4 w-4"})]})})]},a.id)})})},J9s={url:"/exp-agent-advantage.webp"};function ezs({className:s}){const{isMember:t,program:n,packageName:r}=_S();return!t||!((n==null?void 0:n.name)||"").toLowerCase().includes("exp")?null:e.jsxs(we,{className:Mt("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:J9s.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(cn,{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 tzs({className:s}){var T,L,M;const{user:t}=vs(),{isMember:n,program:r,pkg:a,packageName:i}=_S(),l=j.useMemo(()=>!n||!(a!=null&&a.includes_coaching)?!1:((r==null?void 0:r.name)||"").toLowerCase().includes("exp"),[n,a,r]),{data:o}=yQe(),c=o==null?void 0:o.id,{data:d=[]}=vQe(c),{data:u=[]}=bQe(c),{data:h}=ct({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:I},{data:R},{data:z}]=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)]),$=new Set((z||[]).map(H=>H.item_id));return{submitted:!!(I!=null&&I.submitted_at),items:(R||[]).map(H=>({...H,done:$.has(H.id)}))}}});if(!l)return null;const m=((T=o==null?void 0:o.coachProfile)==null?void 0:T.name)||"Your LevelUp Coach",p=((L=o==null?void 0:o.coachProfile)==null?void 0:L.avatar_url)||void 0,f=(M=o==null?void 0:o.coach)==null?void 0:M.headline,y=d.filter(I=>I.status!=="cancelled"&&new Date(I.scheduled_at).getTime()>Date.now()).sort((I,R)=>new Date(I.scheduled_at).getTime()-new Date(R.scheduled_at).getTime())[0],v=u.filter(I=>I.status!=="done"),b=u.length-v.length,N=(h==null?void 0:h.items)||[],S=N.filter(I=>I.done).length,A=N.length?Math.round(S/N.length*100):0;return e.jsxs(we,{className:Mt("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(Ea,{className:"h-16 w-16 ring-4 ring-white/20 md:h-20 md:w-20",children:[e.jsx(Ci,{src:p,alt:m}),e.jsx(Ta,{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(cn,{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:f||"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(U,{asChild:!0,className:"bg-white text-[#2a4c64] hover:bg-white/90",children:e.jsxs(xr,{to:"/my-coach",children:[e.jsx(sv,{className:"mr-2 h-4 w-4"})," Book a session"]})}),e.jsx(U,{asChild:!0,variant:"outline",className:"border-white/40 bg-white/10 text-white hover:bg-white/20 hover:text-white",children:e.jsxs(xr,{to:"/my-coach",children:[e.jsx(Ki,{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(Wr,{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:Gs(new Date(y.scheduled_at),"EEE, MMM d")}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Gs(new Date(y.scheduled_at),"h:mm a"),y.title?` · ${y.title}`:""]}),y.meeting_url&&e.jsx(U,{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(U,{asChild:!0,size:"sm",className:"mt-3",children:e.jsx(xr,{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(cy,{className:"h-3.5 w-3.5"})," Action items"]}),e.jsxs("div",{className:"mt-2 flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl font-bold text-foreground",children:v.length}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"open"}),b>0&&e.jsxs(Be,{variant:"secondary",className:"ml-auto",children:[b," done"]})]}),e.jsxs("ul",{className:"mt-2 space-y-1",children:[v.slice(0,3).map(I=>e.jsxs("li",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Nf,{className:"mt-1 h-3 w-3 shrink-0"}),e.jsx("span",{className:"line-clamp-1",children:I.title||I.description})]},I.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(iy,{className:"h-3.5 w-3.5"})," Coaching prep"]}),h!=null&&h.submitted?N.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,"/",N.length," complete"]}),e.jsxs("span",{className:"text-muted-foreground",children:[A,"%"]})]}),e.jsx(ro,{value:A,className:"mt-2 h-2"}),e.jsx("ul",{className:"mt-3 space-y-1",children:N.slice(0,3).map(I=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[I.done?e.jsx(zr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}):e.jsx(Nf,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground/50"}),e.jsx("span",{className:Mt("line-clamp-1",I.done?"text-muted-foreground line-through":"text-foreground"),children:I.title})]},I.id))})]}):e.jsxs("p",{className:"mt-2 flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Kh,{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(U,{asChild:!0,size:"sm",className:"mt-3",children:e.jsx(xr,{to:"/coaching/onboarding",children:"Start questionnaire"})})]})]})]})]})}function szs(s){return"EST"}function yee(s){const n=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"America/New_York"}).format(s),r=szs();return`${n} ${r}`}function GD(s){const t=new Date,n=new Date(s),r=Xht(n,-15),a=Xht(n,30);return t>a?"ended":Pk(t,{start:n,end:a})?"live":Pk(t,{start:r,end:n})?"starting_soon":"upcoming"}function GQe(s){const t=GD(s);return t==="starting_soon"||t==="live"}const nzs=GQe,rzs=({events:s,registrations:t,onNavigateToEvents:n})=>{const[r,a]=j.useState(new Date);j.useEffect(()=>{const p=setInterval(()=>{a(new Date)},3e4);return()=>clearInterval(p)},[]);const i=s.filter(p=>GQe(p.event_date));if(i.length===0)return null;const l=i[0],o=GD(l.event_date),c=t.find(p=>p.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(mv,{className:"h-4 w-4"}),"Live Now"]}):e.jsxs(e.Fragment,{children:[e.jsx(Yr,{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 ${yee(new Date(l.event_date))}`:`Starts at ${yee(new Date(l.event_date))}`})]}),e.jsx("div",{className:"flex items-center gap-2",children:u?e.jsxs(U,{onClick:()=>window.open(d,"_blank"),className:`${m.button} text-white gap-2`,children:[e.jsx(Sr,{className:"h-4 w-4"}),h?"Join Now":"Join When Live"]}):e.jsxs(U,{variant:"outline",onClick:n,className:`${m.outlineButton} gap-2`,children:[e.jsx(Bn,{className:"h-4 w-4"}),"Register & Join"]})})]})})]})};function Ax(){const{user:s}=vs(),{data:t,isLoading:n}=ct({queryKey:["gmail-integration",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:h,error:m}=await q.from("gmail_integrations").select("*").eq("user_id",s.id).maybeSingle();if(m)throw m;return h}}),{data:r,isLoading:a}=ct({queryKey:["user-verified-ses-sender",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{const{data:h}=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 h}}),i=!!(t!=null&&t.is_active),l=(t==null?void 0:t.gmail_email)||null,o=!!(r!=null&&r.email),c=(r==null?void 0:r.email)||null;return{isGmailConnected:i,gmailEmail:l,hasVerifiedSes:o,sesEmail:c,canSendEmail:i||o,sendMethod:i?"gmail":o?"mass_email":"none",isLoading:n||a}}function azs(){var A;const{user:s}=vs(),{isGmailConnected:t,hasVerifiedSes:n,isLoading:r}=Ax(),a=_S(),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:T})=>{c(!!T),u(!0)})},[s==null?void 0:s.id]);const{data:h,isLoading:m}=ct({queryKey:["new-agent-onboarding",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:3e4,queryFn:async()=>{const[T,L,M,I,R,z]=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)]),$=(z.data||[]).map(ue=>ue.id);let H=!1;if($.length){const{count:ue}=await q.from("coaching_sessions").select("id",{count:"exact",head:!0}).in("assignment_id",$);H=(ue||0)>0}const V=T.data,K=!!(V!=null&&V.avatar_url&&(V!=null&&V.phone)&&(V!=null&&V.bio)),Z=L.count||0,Q=(M.count||0)>0,le=I.count||0;return{profile:V,profileComplete:K,contactsCount:Z,contactsComplete:Z>=5,eventsRegistered:Q,communityComplete:le>0,nextOnboardingEvent:R.data||null,coachingBooked:H}}}),p=t||n,f=[{id:"profile",complete:!!(h!=null&&h.profileComplete)},{id:"email",complete:p},{id:"contacts",complete:!!(h!=null&&h.contactsComplete)},{id:"event",complete:!!(h!=null&&h.eventsRegistered)},{id:"community",complete:!!(h!=null&&h.communityComplete)}],x=l?f.filter(T=>T.id!=="community"&&T.id!=="event"):f;i&&x.push({id:"coaching",complete:!!(h!=null&&h.coachingBooked)});const y=x.filter(T=>T.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 izs={profile:{title:"Complete Your Profile",description:"Add your headshot, phone, and short bio so contacts recognize you.",icon:So,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:ln,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:Bn,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:pa,accent:"from-[#8b5cf6] to-[#a78bfa]",cta:"Register"},community:{title:"Say Hi in the Community",description:"Introduce yourself and connect with other LevelUp agents.",icon:Ki,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:Kh,accent:"from-[#0ea5e9] to-[#38bdf8]",cta:"Book Session"}};function ozs(){var x,y;const s=Wn(),{user:t}=vs(),{steps:n,completedCount:r,totalCount:a,allComplete:i,dismissed:l,dismiss:o,data:c,loading:d}=azs(),[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],p=r/a*100,f=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:N}=await q.from("event_registrations").insert({user_id:t.id,event_id:b.id});N&&!String(N.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(we,{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(er,{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(cn,{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(ro,{value:p,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(U,{onClick:()=>h(!0),className:"bg-[#f5f0e0] text-[#2a4c64] hover:bg-white font-semibold",children:["Continue Setup ",e.jsx(Oa,{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(dv,{className:"h-4 w-4"})]}):e.jsxs(e.Fragment,{children:["Show steps ",e.jsx(rl,{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=izs[v.id],N=b.icon;return e.jsx("div",{className:Mt("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&&f(v.id),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Mt("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(zr,{className:"h-5 w-5"}):e.jsx(N,{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:Mt("font-semibold text-sm",v.complete&&"text-muted-foreground line-through"),children:b.title})}),e.jsx("p",{className:Mt("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(U,{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(),f(v.id)},children:[b.cta," ",e.jsx(Oa,{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 lzs(s){return ct({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 czs(s,t){return ct({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 dzs(s,t=4){return ct({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 uzs(s){const t=Qt();return yt({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 hzs(){const s=Qt();return yt({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 mzs(s){const t=Qt();return yt({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 pzs(){const s=Qt();return yt({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 fzs(s){const t=Qt();return yt({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 gzs={video:lu,pdf:Ur,link:ad,event:pa,graphic:$c},xzs={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 yzs(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 vzs(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 bzs({item:s}){const t=Wn(),n=gzs[s.content_type]||ad,r=xzs[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"?yzs(s.url):null);j.useEffect(()=>{l||!s.url||s.content_type!=="video"||!vzs(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(we,{className:"group cursor-pointer overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",onClick:()=>t(`/brokerage-content/${s.id}`),children:[o?e.jsx("div",{className:"aspect-video bg-muted/50 overflow-hidden",children:e.jsx("img",{src:o,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300",referrerPolicy:"no-referrer"})}):e.jsx("div",{className:"aspect-video bg-muted/20 flex items-center justify-center",children:e.jsx(n,{className:"h-8 w-8 text-muted-foreground/30"})}),e.jsxs(Ie,{className:"p-3",children:[e.jsx("div",{className:"flex items-center gap-1.5 mb-1.5",children:e.jsxs(Be,{variant:"secondary",className:`text-[10px] px-1.5 py-0 ${r}`,children:[e.jsx(n,{className:"h-3 w-3 mr-0.5"}),s.content_type]})}),e.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:s.title}),s.content_type==="event"&&s.event_date&&e.jsx("p",{className:"text-xs text-primary mt-1 font-medium",children:Gs(new Date(s.event_date),"MMM d · h:mm a")})]})]})}function _zs(){const{brokerageId:s}=vs(),t=Wn(),{data:n=[],isLoading:r}=dzs(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(_i,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Brokerage Content"})]}),e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage-content"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Oa,{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(bzs,{item:a},a.id))})]})}const x7t=({className:s,variant:t="default"})=>e.jsx(Be,{variant:"outline",className:Mt("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"}),wzs={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"},jzs={coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",active:"Active",under_contract:"Under Contract",sold:"Sold",withdrawn:"Withdrawn"};function Nzs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function kzs(){const s=Wn(),{data:t,isLoading:n}=rFt(),{data:r,isLoading:a}=aFt({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(we,{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(x7t,{})]}),e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control/listings"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Oa,{className:"h-4 w-4"})]})]}),c.length===0?e.jsx(we,{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(ra,{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(U,{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,p;const h=((m=u.photos)==null?void 0:m.find(f=>f.is_primary))||((p=u.photos)==null?void 0:p[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(ra,{className:"h-8 w-8 text-muted-foreground/50"})}),u.is_featured&&e.jsx("div",{className:"absolute top-1.5 left-1.5",children:e.jsxs(Be,{className:"gap-1 bg-amber-500 text-white border-0 text-[10px] px-1.5 py-0.5",children:[e.jsx(Ua,{className:"h-2.5 w-2.5 fill-current"}),"Featured"]})}),e.jsx("div",{className:"absolute top-1.5 right-1.5",children:e.jsx(Be,{className:`text-[10px] px-1.5 py-0.5 ${wzs[u.status]}`,children:jzs[u.status]})})]}),e.jsxs("div",{className:"p-2",children:[e.jsx("p",{className:"font-bold text-sm text-foreground",children:Nzs(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 y7t(s=10,t){return ct({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(p=>p.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 v7t(s){return ct({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 b7t(s){return ct({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 _7t(s,t){return ct({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 Szs(){const{user:s,brokerageId:t,isAdmin:n}=vs();Wn();const r=!!t,[a,i]=j.useState("brokerage"),l=()=>{if(n)return null;if(r)return a==="global"?null:t},{data:o,isLoading:c}=y7t(5,l()),{data:d}=v7t(s==null?void 0:s.id),{data:u}=_7t(s==null?void 0:s.id,l()),{data:h}=b7t(s==null?void 0:s.id),m=n||r,p=()=>n?"Agent Leaderboard":r?a==="global"?"All LevelUp":"My Brokerage":"My Points";if(c)return e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(Al,{className:"h-4 w-4 text-yellow-500"}),p()]})}),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 f=x=>x===0?e.jsx(Al,{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(we,{children:[e.jsxs(Tt,{className:"pb-2",children:[e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(Al,{className:"h-4 w-4 text-yellow-500"}),p()]}),!n&&r&&e.jsxs("div",{className:"flex gap-1 mt-2",children:[e.jsx(U,{variant:a==="brokerage"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("brokerage"),children:"My Brokerage"}),e.jsx(U,{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,N,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:f(v)}),e.jsx(Ea,{className:"h-6 w-6",children:e.jsx(Ta,{className:"text-xs",children:((N=(b=y.profile)==null?void 0:b.name)==null?void 0:N.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(xr,{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(Ro,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(gi,{className:"h-4 w-4"})]})]})]})}return e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(Al,{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(Xd,{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(Eh,{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(xr,{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(Ro,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(gi,{className:"h-4 w-4"})]})]}):e.jsxs("div",{className:"text-center text-muted-foreground py-4 text-sm",children:[e.jsx(Ua,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground/50"}),e.jsx("p",{children:"Attend events to earn points!"}),e.jsxs(xr,{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(Ro,{className:"h-4 w-4"}),"Visit Reward Store",e.jsx(gi,{className:"h-4 w-4"})]})]})})]})}const g9=()=>ct({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}}),WQe=()=>{const s=Qt(),{user:t}=vs();return yt({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)}})},Czs=()=>{const s=Qt();return yt({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")}})},Azs=()=>{const s=Qt();return yt({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")}})},KQe=(s,t)=>{const{user:n,isAdmin:r}=vs(),a=r&&t?t:n==null?void 0:n.id;return ct({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})},YQe=s=>{const{user:t,isAdmin:n}=vs(),r=n&&s?s:t==null?void 0:t.id;return ct({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})},iPe=()=>{const s=Qt(),{user:t}=vs();return yt({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)}})},Ezs=()=>{const s=Qt();return yt({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)}})},Tzs=()=>{const s=Qt();return yt({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)}})},w7t=(s,t)=>{const{user:n,isAdmin:r}=vs(),a=r&&t?t:n==null?void 0:n.id;return ct({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})},Mzs=()=>{const s=Qt(),{user:t}=vs();return yt({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)}})},oPe=()=>{const{user:s}=vs();return ct({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)})},Pzs=()=>{const s=Qt(),{user:t}=vs();return yt({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)}})},j7t=(s,t)=>{const{data:n,isLoading:r}=KQe(s,t),{data:a,isLoading:i}=YQe(t),{data:l}=oPe(),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,T)=>A+Number(T.sale_price),0),p=d.reduce((A,T)=>A+(Number(T.commission_amount)||0),0),f=d.reduce((A,T)=>{const L=Number(T.commission_amount)||0;if(!L)return A;let M=L;return T.brokerage_split_pct&&(M-=L*(T.brokerage_split_pct/100)),T.team_split_pct&&(M-=L*(T.team_split_pct/100)),T.franchise_fee_pct&&(M-=L*(T.franchise_fee_pct/100)),T.referral_fee_pct&&(M-=L*(T.referral_fee_pct/100)),T.transaction_fee&&(M-=T.transaction_fee),A+Math.max(0,M)},0),x={};d.forEach(A=>{var L;const T=((L=A.lead_source)==null?void 0:L.name)||"Unknown";x[T]=(x[T]||0)+1});const y=Object.entries(x).map(([A,T])=>({name:A,count:T})).sort((A,T)=>T.count-A.count),v=y[0]||null,b={};d.forEach(A=>{const T=Su(A.close_date).toLocaleString("default",{month:"short"});b[T]=(b[T]||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?p:0,totalNetToAgent:o?f:0,topLeadSource:v,transactionsByMonth:S,leadSourceBreakdown:y}};return{yearStats:c(n),lifetimeStats:c(a),isLoading:r||i,showCommission:o}},Lzs=()=>{const{isAdmin:s}=vs();return ct({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})},$T={recency:40,touchpoints:30,transactions:20,referrals:10},Vft={warm:70,cooling:40};function Izs(s){return s===null?0:s<=14?$T.recency:s<=30?$T.recency*.85:s<=60?$T.recency*.65:s<=90?$T.recency*.4:s<=180?$T.recency*.2:$T.recency*.05}function Rzs(s){const t=Math.min(s/12,1);return Math.round($T.touchpoints*t)}function Dzs(s){return s?$T.transactions:0}function Ozs(){return 0}function Fzs(s){return s>=Vft.warm?"warm":s>=Vft.cooling?"cooling":"at-risk"}function hre(){const{data:s,isLoading:t}=Cb(),{data:n}=r7t(),{data:r}=CG(365),{data:a}=YQe(),i=j.useMemo(()=>{if(!s)return[];const o=new Date,c=$D(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,p=m?hN(o,new Date(m)):null,f=d[h.id]||0,x=u.has(h.id),y=Izs(p),v=Rzs(f),b=Dzs(x),N=Ozs(),S=Math.round(y+v+b+N),A={score:S,status:Fzs(S),breakdown:{recency:Math.round(y),touchpoints:Math.round(v),transactions:Math.round(b),referrals:Math.round(N)},lastTouchDate:m,daysSinceTouch:p,touchCountLast12Months:f,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,p)=>m+p.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 zzs(s){const{contactsWithScores:t,isLoading:n}=hre(),r=j.useMemo(()=>t.find(a=>a.id===s),[t,s]);return{score:r==null?void 0:r.relationshipScore,isLoading:n}}function N7t(){const s=Wn(),{stats:t,contactsWithScores:n,isLoading:r}=hre();if(r)return e.jsxs(we,{children:[e.jsx(Tt,{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(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsxs(It,{className:"text-lg flex items-center gap-2",children:[e.jsx(Bn,{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(U,{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(we,{children:[e.jsxs(Tt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(It,{className:"text-lg flex items-center gap-2",children:[e.jsx(rc,{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(ro,{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(ro,{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(ro,{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(nS,{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(gi,{className:"h-3 w-3"})]})]},c.id))})]}),e.jsxs(U,{variant:"outline",size:"sm",className:"w-full",onClick:()=>s("/mission-control/contacts?filter=at-risk"),children:["View All At-Risk Contacts",e.jsx(gi,{className:"h-4 w-4 ml-1"})]})]})]})}const Bzs=()=>{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"},Uzs=()=>new Intl.DateTimeFormat("en-US",{weekday:"long",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date);function qzs({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 $zs({name:s,eventsThisWeek:t=0}){const n=Wn(),{user:r}=vs(),{data:a}=BQe(),{data:i}=t7t(),l=sPe(),{hasAccess:o,hasAssignment:c}=KIt(),{hasFeature:d}=_S(),{data:u}=ct({queryKey:["hub-active-listings",r==null?void 0:r.id],enabled:!!(r!=null&&r.id),queryFn:async()=>{const{count:N,error:S}=await q.from("listings").select("id",{count:"exact",head:!0}).eq("agent_id",r.id);return S?0:N||0}}),h=j.useMemo(()=>{if(!i)return 0;const N=Date.now()-7*24*60*60*1e3;return i.filter(S=>S.created_at&&new Date(S.created_at).getTime()>=N).length},[i]),m=(a==null?void 0:a.length)||0,p=(l==null?void 0:l.streak)||0,f=(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:p,to:"/mission-control",icon:Xd}],b=[{label:"Add Contact",icon:zl,to:"/mission-control/contacts?new=true"},...d("social")?[{label:"Create Post",icon:jd,to:"/social-swag-2"}]:[],...d("presentations")?[{label:"Listing Presentation",icon:hv,to:"/mission-control/listing-presentations"}]:[],...o?[{label:"Book Coaching",icon:ch,to:c?"/my-coach":"/coaching"}]:[],{label:"Ask AI",icon:cn,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:Uzs()}),e.jsxs("h1",{className:"mt-1 text-2xl sm:text-3xl font-bold",children:[Bzs(),", ",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(N=>e.jsxs("button",{onClick:()=>n(N.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:[N.icon&&e.jsx(N.icon,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),e.jsx("span",{className:"text-xl font-bold",children:N.value})]}),e.jsx("p",{className:"mt-0.5 text-[11px] hub-ink-muted",children:N.label})]},N.label))})]}),e.jsxs("div",{className:"hub-glass flex items-center gap-4 rounded-2xl px-4 py-3 lg:self-center",children:[e.jsx(qzs,{value:f,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:f>=x?"Goal crushed 🎉":`${x-f} 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(Oa,{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(N=>e.jsxs("button",{onClick:()=>n(N.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(N.icon,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),N.label]},N.label))})]})}const bU=24*60*60*1e3,Vzs=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}},Foe=s=>{const t=Vzs(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,Gzs=s=>s===0?"today":s===1?"tomorrow":`in ${s} days`,Wzs={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}},Kzs=(s=5)=>{const t=Sa(),{data:n,isLoading:r}=BQe(),{data:a,isLoading:i}=Cb(),l=ct({queryKey:["smart-queue",t,n==null?void 0:n.length,a==null?void 0:a.length],queryFn:async()=>{var L;const o=[],c=new Set,d=M=>{var I;!((I=M.contact)!=null&&I.id)||c.has(M.contact.id)||(c.add(M.contact.id),o.push(M))};if((n||[]).forEach((M,I)=>{var R;d({key:`plan-${M.contact.id}-${I}`,contact:M.contact,kind:"plan",actionLabel:((R=M.actionType)==null?void 0:R.name)||"Touch",reason:M.planName?`${M.planName}${M.relationshipTypeName?` · ${M.relationshipTypeName}`:""}`:"Scheduled touch",priority:0,planAction:M})}),o.length>=s)return o.slice(0,s);const u=a||[],h=new Map(u.map(M=>[M.id,M])),[{data:m},{data:p},{data:f}]=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*bU).toISOString()),q.from("contact_touch_logs").select("contact_id").eq("owner_user_id",t).gte("completed_at",new Date(Date.now()-90*bU).toISOString())]),x=new Set([...(m||[]).map(M=>M.contact_id),...(p||[]).map(M=>M.contact_id)]),y=new Set((f||[]).map(M=>M.contact_id)),v=M=>!x.has(M)&&!c.has(M);for(const M of u){if(!v(M.id))continue;const R=[{days:Foe(M.birthday),label:"Birthday"},{days:Foe(M.home_anniversary),label:"Home anniversary"},{days:Foe(M.wedding_anniversary),label:"Wedding anniversary"},{days:Foe(M.spouse_birthday),label:`${M.spouse_name||"Spouse"}'s birthday`}].find(z=>Hzs(z.days,7));R&&d({key:`milestone-${M.id}`,contact:M,kind:"milestone",actionLabel:"Send wishes",reason:`${R.label} ${Gzs(R.days)}`,priority:R.days===0?1:5+R.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 M of b||[]){const I=h.get(M.contact_id);if(!I||!v(M.contact_id))continue;const R=Wzs[M.signal_type]||{reason:M.title||"Recent activity",action:"Follow up",priority:27};d({key:`signal-${M.contact_id}`,contact:I,kind:"signal",actionLabel:R.action,reason:R.reason,priority:R.priority})}const{data:N}=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 M of N||[]){const I=h.get(M.contact_id);!I||!v(M.contact_id)||d({key:`deal-${M.contact_id}`,contact:I,kind:"deal",actionLabel:"Check in",reason:`Open deal with no contact in 2 weeks${M.property_address?` · ${M.property_address}`:""}`,priority:30})}const S=Date.now()-3*bU;for(const M of u)v(M.id)&&(y.has(M.id)||new Date(M.created_at).getTime()v(M.id)&&!y.has(M.id)&&new Date(M.created_at).getTime()M.id.localeCompare(I.id));if(T.length>0){const M=new Date().getDate()*7%T.length;for(let I=0;IM.priority-I.priority).slice(0,s)},enabled:!!t&&!r&&!i});return{...l,isLoading:l.isLoading||r||i}},Yzs=()=>{const s=Sa(),t=Qt();return yt({mutationFn:async n=>{const r=new Date(Date.now()+14*bU).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"]}),ka({title:"Snoozed for 14 days"})},onError:n=>ka({title:"Could not snooze",description:n.message,variant:"destructive"})})},Zzs=s=>(s||"?").split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase(),Xzs={plan:{icon:cv,tint:"var(--nav-crm)"},milestone:{icon:lg,tint:"var(--nav-events)"},signal:{icon:Xd,tint:"var(--nav-marketing)"},deal:{icon:og,tint:"var(--nav-listings)"},new:{icon:cn,tint:"var(--nav-apps)"},cold:{icon:$w,tint:"var(--nav-more)"}};function Qzs(){const s=Wn(),{data:t,isLoading:n}=Kzs(5),r=Yzs(),a=sPe(),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(Gu,{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(U,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>s("/mission-control"),children:["Agent OS ",e.jsx(gi,{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(zr,{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(U,{size:"sm",variant:"outline",className:"mt-3 gap-1.5",onClick:()=>s("/mission-control/contacts?new=true"),children:[e.jsx(zl,{className:"h-3.5 w-3.5"})," Add Contact"]})]}):e.jsx(wN,{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=Xzs[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:Zzs(u)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium text-foreground",children:u}),e.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-1.5",children:[e.jsxs(Be,{variant:"secondary",className:"gap-1 text-[10px]",style:{background:`hsl(${h.tint} / 0.12)`,color:`hsl(${h.tint})`},children:[e.jsx(m,{className:"h-3 w-3"}),c.actionLabel]}),e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:c.reason})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx(Jzs,{contact:d,onOpen:()=>s(`/mission-control/contacts/${d.id}`)}),e.jsxs(Bg,{children:[e.jsx(Ug,{asChild:!0,children:e.jsx(U,{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(er,{className:"h-4 w-4"})})}),e.jsx(ng,{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(ro,{value:Math.min(i/l*100,100),className:"h-2"})]})]})}function Jzs({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(U,{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(ba,{className:"h-4 w-4"})})}),n&&e.jsx(U,{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(Ki,{className:"h-4 w-4"})})}),r&&e.jsx(U,{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(ln,{className:"h-4 w-4"})})}),e.jsx(U,{size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Open contact",onClick:t,children:e.jsx(gi,{className:"h-4 w-4"})})]})}const eBs=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 tBs({events:s,registrations:t}){const n=Wn(),{data:r}=yQe(),{data:a}=ct({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:nzs(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(nc,{className:"h-4 w-4",style:{color:"hsl(var(--nav-events))"}})}),"Up Next"]}),e.jsxs(U,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>n("/events"),children:["All ",e.jsx(gi,{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(nc,{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(U,{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(mv,{className:"h-4 w-4 text-destructive"}):l.kind==="coaching"?e.jsx(Kh,{className:"h-4 w-4",style:{color:"hsl(var(--nav-academy))"}}):e.jsx(Wr,{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":`${eBs(l.date)} · ${yee(l.date)}`," ·"," ",l.subtitle]})]}),l.joinUrl&&e.jsxs(U,{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(Sr,{className:"h-3 w-3"})," Join"]})]})},l.id))})]})}const Hft=s=>s>=1e6?`$${(s/1e6).toFixed(1)}M`:s>=1e3?`$${Math.round(s/1e3)}K`:`$${s}`;function sBs(){const s=Wn(),{data:t,isLoading:n}=ct({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,p,f;const h=((m=u.stage)==null?void 0:m.id)||"none";d[h]||(d[h]={name:((p=u.stage)==null?void 0:p.name)||"Unassigned",color:((f=u.stage)==null?void 0:f.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(P4,{className:"h-4 w-4",style:{color:"hsl(var(--nav-listings))"}})}),"Pipeline"]}),e.jsxs(U,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>s("/mission-control/pipeline"),children:["Open ",e.jsx(gi,{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(U,{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:Hft(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:Hft(t.wonVolume)})," volume"]})]})]})}function nBs(){const s=Wn(),{user:t}=vs(),{hasFeature:n}=_S(),{data:r}=ct({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:hv,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:ra,hue:"--nav-websites",to:`/mission-control/listings/${u.id}`})),i.push({id:"marketing",label:"Create a post",sub:"Marketing Studio",icon:Th,hue:"--nav-marketing",to:"/marketing-studio"}),i.slice(0,8)}}),a=(r||[]).filter(i=>{const l=FPt(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(Yr,{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(Oa,{className:"h-4 w-4 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"})]},i.id))})]})}function rBs({videos:s,kits:t,templates:n,services:r}){const a=Wn(),i=[{id:"videos",label:"Academy",icon:$h,hue:"--nav-academy",items:s,viewAll:"/academy",emptyText:"No new videos yet."},{id:"kits",label:"Resource Kits",icon:r1,hue:"--nav-apps",items:t,viewAll:"/toolbox",emptyText:"No resource kits yet."},{id:"templates",label:"Templates",icon:kM,hue:"--nav-marketing",items:n,viewAll:"/templates",emptyText:"No new templates yet.",fit:"contain"},{id:"services",label:"Services",icon:cn,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(U,{variant:"ghost",size:"sm",className:"gap-1 text-muted-foreground hover:text-foreground",onClick:()=>a(c.viewAll),children:["View All ",e.jsx(Oa,{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 aBs=()=>{var se;const{user:s,isAdmin:t}=vs(),n=Wn(),{hasFeature:r}=_S(),[a,i]=j.useState([]),[l,o]=j.useState([]),[c,d]=j.useState([]),[u,h]=j.useState([]),[m,p]=j.useState([]),[f,x]=j.useState([]),[y,v]=j.useState(new Set),[b,N]=j.useState([]),[S,A]=j.useState([]),[T,L]=j.useState([]),[M,I]=j.useState(null),[R,z]=j.useState(!0);j.useEffect(()=>{$()},[s]);const $=async()=>{var ne,ie,ce,je,be;try{const[he,ge,ke,Te,Me,Oe,Se,Qe,Ae,Fe,Ne]=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()]);(ne=Ne.data)!=null&&ne.name&&I(Ne.data.name);const $e=((ie=he.data)==null?void 0:ie.map(Ge=>Ge.tag))||[],Ve=new Set(((ce=ke.data)==null?void 0:ce.map(Ge=>Ge.app_id))||[]);v(Ve);const Ze=(((je=ge.data)==null?void 0:je.filter(Ge=>!Ge.required_tags||Ge.required_tags.length===0?!0:Ge.required_tags.some(He=>$e.includes(He))))||[]).sort((Ge,He)=>Ge.name==="LevelUp Members Portal"?-1:He.name==="LevelUp Members Portal"?1:0);i(Ze.slice(0,6));const Ue=((be=Te.data)==null?void 0:be.filter(Ge=>GD(Ge.event_date)!=="ended"))||[];o(Ue.slice(0,4)),N(Me.data||[]),d(Oe.data||[]),h(Se.data||[]),p(Qe.data||[]),x(Ae.data||[]);const Ye=Fe.data||[];A(Ye.filter(Ge=>Ge.placement==="top")),L(Ye.filter(Ge=>Ge.placement==="between"))}catch(he){console.error("Error loading dashboard:",he),re.error("Failed to load dashboard data")}finally{z(!1)}},H=async ne=>{var ce,je,be;if(ne.target_url.startsWith("/")){q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:ne.app_id,app_name:ne.name,user_agent:navigator.userAgent}).then(()=>{}),n(ne.target_url);return}const ie=window.open("about:blank","_blank");try{await q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:ne.app_id,app_name:ne.name,user_agent:navigator.userAgent});let{data:he}=await q.auth.getSession();(ce=he.session)!=null&&ce.access_token||(he=(await q.auth.refreshSession()).data);const ge=(je=he==null?void 0:he.session)==null?void 0:je.access_token;if(!ge){ie==null||ie.close(),re.error("Your session expired — please sign in again to launch this app.");return}const{data:ke,error:Te}=await q.functions.invoke("sso-launch",{body:{app_id:ne.app_id},headers:{Authorization:`Bearer ${ge}`}});if(Te)throw Te;ke!=null&&ke.redirect_url?ie&&!ie.closed?(ie.location.href=ke.redirect_url,(be=ie.focus)==null||be.call(ie)):window.location.assign(ke.redirect_url):(ie==null||ie.close(),re.error("Launch link unavailable"))}catch(he){ie==null||ie.close(),console.error("Error launching app:",he),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"},K=a.filter(ne=>{const ie=V[ne.name]||V[ne.app_id];return!ie||r(ie)}),Z=ne=>T.filter(ie=>ie.section_after===ne),Q=(M||((se=s==null?void 0:s.user_metadata)==null?void 0:se.name)||"there").split(" ")[0],le=Date.now()+7*24*60*60*1e3,ue=l.filter(ne=>new Date(ne.event_date).getTime()<=le).length;return e.jsxs(qs,{title:"Dashboard",children:[r("learn")&&e.jsx(rzs,{events:l,registrations:b,onNavigateToEvents:()=>n("/events")}),e.jsx(Q9s,{}),e.jsx(ezs,{}),e.jsx(tzs,{}),e.jsx($zs,{name:Q,eventsThisWeek:ue}),e.jsx(ozs,{}),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(Qzs,{})}),r("learn")&&e.jsx(tBs,{events:l,registrations:b})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 mb-8 lg:grid-cols-3",children:[e.jsx(N7t,{}),r("deals")&&e.jsx(sBs,{}),r("learn")&&e.jsx(Szs,{})]}),e.jsx(nBs,{}),S.length>0&&e.jsx("div",{className:"mb-8",children:e.jsx(eY,{banners:S})}),e.jsx(_zs,{}),R?e.jsx("div",{className:"mb-10 grid grid-cols-2 gap-4 md:grid-cols-4",children:[0,1,2,3].map(ne=>e.jsx("div",{className:"h-44 rounded-2xl bg-muted/40 animate-pulse"},ne))}):e.jsx(rBs,{videos:(r("learn")?m:[]).map(ne=>({id:ne.id,title:ne.title,image:ne.thumbnail_url,meta:ne.duration,onOpen:()=>n(`/academy/${ne.id}`)})),kits:(r("learn")?u:[]).map(ne=>({id:ne.id,title:ne.name,image:ne.featured_image_url,onOpen:()=>n(`/toolbox/${ne.id}`)})),templates:(r("marketing_studio")?c:[]).map(ne=>({id:ne.id,title:ne.name,image:ne.preview_image_url,onOpen:()=>n("/templates")})),services:f.map(ne=>({id:ne.id,title:ne.name,image:ne.preview_image_url,onOpen:()=>window.open(ne.signup_link_url,"_blank")}))}),Z("academy").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(eY,{banners:Z("academy")})}),r("listing_exchange")&&e.jsx("div",{className:"mb-10",children:e.jsx(kzs,{})}),K.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(U,{variant:"ghost",size:"sm",onClick:()=>n("/apps"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Oa,{className:"h-4 w-4"})]})]}),K.length===0?e.jsx(we,{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(u0,{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:K.map(ne=>{const ie=y.has(ne.id);return e.jsxs("div",{onClick:()=>H(ne),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:ne.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:ne.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:ne.description})]}),ie&&e.jsx(u0,{className:"h-5 w-5 text-primary fill-current flex-shrink-0"})]},ne.id)})})]}),Z("templates").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(eY,{banners:Z("templates")})}),Z("events").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(eY,{banners:Z("events")})}),Z("toolbox").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(eY,{banners:Z("toolbox")})})]})},iBs=[{key:"contacts",label:"Contacts",icon:ba,description:"View, add, and edit contacts"},{key:"pipeline",label:"Deal Pipeline",icon:EF,description:"View, add, and move deals"},{key:"client_portal",label:"Client Portals",icon:r1,description:"Manage client portals on deals"},{key:"videos",label:"Videos",icon:Wr,description:"View and upload videos"},{key:"listings",label:"Listings",icon:ra,description:"View, create, and edit listings"},{key:"scorecard",label:"Scorecard",icon:iy,description:"View and add transactions"},{key:"popbys",label:"Pop-bys",icon:ni,description:"View and log pop-bys"},{key:"digital_card",label:"Digital Card",icon:oy,description:"Create and edit digital business card"},{key:"guest_book",label:"Guest Book",icon:ig,description:"Manage open house guest books"},{key:"presentations",label:"Presentations",icon:hv,description:"Create and manage smart presentations"}];function oBs(){var L;const{user:s}=vs(),[t,n]=j.useState([]),[r,a]=j.useState(!0),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState({email:"",name:"",password:""}),[p,f]=j.useState("create"),[x,y]=j.useState(!1),[v,b]=j.useState(null);j.useEffect(()=>{s&&N()},[s]);const N=async()=>{if(s){a(!0);try{const{data:M,error:I}=await q.from("agent_assistant_assignments").select("id, assistant_id, permissions, created_at").eq("agent_id",s.id);if(I)throw I;if(M&&M.length>0){const R=M.map(H=>H.assistant_id),{data:z}=await q.from("profiles").select("id, name, email").in("id",R),$=M.map(H=>{const V=z==null?void 0:z.find(K=>K.id===H.assistant_id);return{...H,permissions:H.permissions,assistant_profile:V?{name:V.name||"",email:V.email||""}:void 0}});n($)}else n([])}catch(M){console.error("Error loading assistants:",M)}finally{a(!1)}}},S=async()=>{if(s){if(p==="link"){if(!h.email.trim()){re.error("Please enter the assistant's email");return}y(!0);try{const{data:{session:M}}=await q.auth.getSession();if(!M)throw new Error("Not authenticated");const{data:I,error:R}=await q.from("profiles").select("id, name, email").eq("email",h.email.trim().toLowerCase()).single();if(R||!I){re.error("No account found with that email. Try creating a new assistant instead.");return}const{data:z}=await q.from("agent_assistant_assignments").select("id").eq("agent_id",s.id).eq("assistant_id",I.id);if(z&&z.length>0){re.error("This assistant is already assigned to you");return}const $=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.access_token}`},body:JSON.stringify({userId:I.id,role:"assistant",action:"add",agentId:s.id})}),H=await $.json();if(!$.ok)throw new Error(H.error||"Failed to assign assistant role");const{error:V}=await q.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:I.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(`${I.name||I.email} linked as your assistant`),l(!1),m({email:"",name:"",password:""}),N()}catch(M){console.error("Error linking assistant:",M),re.error(M.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:M}}=await q.auth.getSession();if(!M)throw new Error("Not authenticated");const I=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.access_token}`},body:JSON.stringify({email:h.email.trim(),password:h.password,name:h.name.trim(),purpose:"assistant"})}),R=await I.json();if(!I.ok)throw new Error(R.error||"Failed to create assistant account");const z=R.userId||R.id;if(!z)throw new Error("No user ID returned");const $=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.access_token}`},body:JSON.stringify({userId:z,role:"assistant",action:"add",agentId:s.id})}),H=await $.json();if(!$.ok)throw new Error(H.error||"Failed to assign assistant role");const{error:V}=await q.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:z,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:""}),N()}catch(M){console.error("Error adding assistant:",M),re.error(M.message||"Failed to add assistant")}finally{y(!1)}}},A=async()=>{if(!(!d||!s))try{const{data:{session:M}}=await q.auth.getSession();if(!M)throw new Error("Not authenticated");const{error:I}=await q.from("agent_assistant_assignments").delete().eq("id",d.id);if(I)throw I;const{data:R}=await q.from("agent_assistant_assignments").select("id").eq("assistant_id",d.assistant_id);(!R||R.length===0)&&await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.access_token}`},body:JSON.stringify({userId:d.assistant_id,role:"assistant",action:"remove"})}),re.success("Assistant removed"),c(!1),u(null),N()}catch(M){console.error("Error removing assistant:",M),re.error(M.message||"Failed to remove assistant")}},T=async(M,I,R)=>{b(M);try{const z=t.find(V=>V.id===M);if(!z)return;const $={...z.permissions,[I]:R},{error:H}=await q.from("agent_assistant_assignments").update({permissions:$}).eq("id",M);if(H)throw H;n(V=>V.map(K=>K.id===M?{...K,permissions:$}:K))}catch(z){console.error("Error updating permissions:",z),re.error("Failed to update permissions")}finally{b(null)}};return r?e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Bn,{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(Et,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-5 w-5"}),"My Assistants"]}),e.jsx(Jn,{children:"Add assistants to help manage your Agent OS"})]}),e.jsxs(U,{size:"sm",onClick:()=>{f("create"),l(!0)},children:[e.jsx(an,{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(M=>{var I,R,z,$;return e.jsxs("div",{className:"border rounded-lg p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ea,{className:"h-10 w-10",children:e.jsx(Ta,{children:((R=(I=M.assistant_profile)==null?void 0:I.name)==null?void 0:R.split(" ").map(H=>H[0]).join("").toUpperCase())||"A"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((z=M.assistant_profile)==null?void 0:z.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(($=M.assistant_profile)==null?void 0:$.email)||""})]}),e.jsxs(Be,{variant:"secondary",className:"ml-2",children:[e.jsx(Im,{className:"h-3 w-3 mr-1"}),"Assistant"]})]}),e.jsx(U,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>{u(M),c(!0)},children:e.jsx(In,{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:iBs.map(H=>{const V=H.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:H.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:H.description})]})]}),e.jsx(wn,{checked:M.permissions[H.key]||!1,onCheckedChange:K=>T(M.id,H.key,K),disabled:v===M.id})]},H.key)})})]})]},M.id)})})})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Add Assistant"}),e.jsx(Pr,{children:p==="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(U,{variant:p==="create"?"default":"outline",size:"sm",onClick:()=>f("create"),children:[e.jsx(an,{className:"h-3 w-3 mr-1"}),"Create New"]}),e.jsxs(U,{variant:p==="link"?"default":"outline",size:"sm",onClick:()=>f("link"),children:[e.jsx(Rc,{className:"h-3 w-3 mr-1"}),"Link Existing"]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[p==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"assistant-name",children:"Name"}),e.jsx(xe,{id:"assistant-name",value:h.name,onChange:M=>m({...h,name:M.target.value}),placeholder:"Assistant's full name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"assistant-email",children:"Email"}),e.jsx(xe,{id:"assistant-email",type:"email",value:h.email,onChange:M=>m({...h,email:M.target.value}),placeholder:"assistant@email.com"})]}),p==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"assistant-password",children:"Temporary Password"}),e.jsx(xe,{id:"assistant-password",type:"password",value:h.password,onChange:M=>m({...h,password:M.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(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(U,{onClick:S,disabled:x,children:[x&&e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),p==="create"?"Create Assistant":"Link Assistant"]})]})]})}),e.jsx(Fl,{open:o,onOpenChange:c,children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Remove Assistant?"}),e.jsxs(Ll,{children:["This will remove ",(L=d==null?void 0:d.assistant_profile)==null?void 0:L.name,"'s access to your Agent OS. Their account will remain active but they won't be able to manage your data."]})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:A,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function Gy(s){this.content=s}Gy.prototype={constructor:Gy,find:function(s){for(var t=0;t>1}};Gy.from=function(s){if(s instanceof Gy)return s;var t=[];if(s)for(var n in s)t.push(n,s[n]);return new Gy(t)};function k7t(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){for(let l=0;a.text[l]==i.text[l];l++)n++;return n}if(a.content.size||i.content.size){let l=k7t(a.content,i.content,n+1);if(l!=null)return l}n+=a.nodeSize}}function S7t(s,t,n,r){for(let a=s.childCount,i=t.childCount;;){if(a==0||i==0)return a==i?null:{a:n,b:r};let l=s.child(--a),o=t.child(--i),c=l.nodeSize;if(l==o){n-=c,r-=c;continue}if(!l.sameMarkup(o))return{a:n,b:r};if(l.isText&&l.text!=o.text){let d=0,u=Math.min(l.text.length,o.text.length);for(;dt&&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 B1(r,a)}cutByIndex(t,n){return t==n?B1.empty:t==0&&n==this.content.length?this:new B1(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 B1(a,i)}addToStart(t){return new B1([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new B1(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?zoe(n+1,i):zoe(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 B1.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new B1(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return B1.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}};hm.none=[];class LCe extends Error{}class Si{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=A7t(this.content,t+this.openStart,n);return r&&new Si(r,this.openStart,this.openEnd)}removeBetween(t,n){return new Si(C7t(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 Si.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 Si(Ba.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 Si(t,r,a)}}Si.empty=new Si(Ba.empty,0,0);function C7t(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(C7t(i.content,t-a-1,n-a-1)))}function A7t(s,t,n,r){let{index:a,offset:i}=s.findIndex(t),l=s.maybeChild(a);if(i==t||l.isText)return r&&!r.canReplace(a,a,n)?null:s.cut(0,t).append(n).append(s.cut(t));let o=A7t(l.content,t-i-1,n,l);return o&&s.replaceChild(a,l.copy(o))}function lBs(s,t,n){if(n.openStart>s.depth)throw new LCe("Inserted content deeper than insertion position");if(s.depth-n.openStart!=t.depth-n.openEnd)throw new LCe("Inconsistent open depths");return E7t(s,t,n,0)}function E7t(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 IQ(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&&(GF(s.nodeAfter,r),i++));for(let o=i;oa&&h$e(s,t,a+1),l=r.depth>a&&h$e(n,r,a+1),o=[];return IQ(null,s,a,o),i&&l&&t.index(a)==n.index(a)?(T7t(i,l),GF(WF(i,M7t(s,t,n,r,a+1)),o)):(i&&GF(WF(i,ICe(s,t,a+1)),o),IQ(t,n,a,o),l&&GF(WF(l,ICe(n,r,a+1)),o)),IQ(r,null,a,o),new Ba(o)}function ICe(s,t,n){let r=[];if(IQ(null,s,n,r),s.depth>n){let a=h$e(s,t,n+1);GF(WF(a,ICe(s,t,n+1)),r)}return IQ(t,null,n,r),new Ba(r)}function cBs(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(Ba.from(a));return{start:a.resolveNoCache(s.openStart+n),end:a.resolveNoCache(a.content.size-s.openEnd-n)}}class vee{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 RCe(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 vee(n,r,i)}static resolveCached(t,n){let r=Gft.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()+")"),P7t(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=Ba.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=Ba.fromJSON(t,n.content),i=t.nodeType(n.type).create(n.attrs,a,r);return i.type.checkAttrs(i.attrs),i}};qM.prototype.text=void 0;class DCe extends qM{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):P7t(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 DCe(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new DCe(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 P7t(s,t){for(let n=s.length-1;n>=0;n--)t=s[n].type.name+"("+t+")";return t}class C7{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,n){let r=new mBs(t,n);if(r.next==null)return C7.empty;let a=L7t(r);r.next&&r.err("Unexpected trailing text");let i=bBs(vBs(a));return _Bs(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(` `)}}C7.empty=new C7(!0);class mBs{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 L7t(s){let t=[];do t.push(pBs(s));while(s.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function pBs(s){let t=[];do t.push(fBs(s));while(s.next&&s.next!=")"&&s.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function fBs(s){let t=yBs(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=gBs(s,t);else break;return t}function Wft(s){/\D/.test(s.next)&&s.err("Expected number, got '"+s.next+"'");let t=Number(s.next);return s.pos++,t}function gBs(s,t){let n=Wft(s),r=n;return s.eat(",")&&(s.next!="}"?r=Wft(s):r=-1),s.eat("}")||s.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:t}}function xBs(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 yBs(s){if(s.eat("(")){let t=L7t(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=xBs(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 vBs(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 C7(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:D7t(this.attrs,t)}create(t=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new qM(this,this.computeAttrs(t),Ba.from(n),hm.setFrom(r))}createChecked(t=null,n,r){return n=Ba.from(n),this.checkContent(n),new qM(this,this.computeAttrs(t),n,hm.setFrom(r))}createAndFill(t=null,n,r){if(t=this.computeAttrs(t),n=Ba.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(Ba.empty,!0);return i?new qM(this,t,n.append(i),hm.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 z7t(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 wBs(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 jBs{constructor(t,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?wBs(t,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class lPe{constructor(t,n,r,a){this.name=t,this.rank=n,this.schema=r,this.spec=a,this.attrs=F7t(t,a.attrs),this.excluded=null;let i=R7t(this.attrs);this.instance=i?new hm(this,i):null}create(t=null){return!t&&this.instance?this.instance:new hm(this,D7t(this.attrs,t))}static compile(t,n){let r=Object.create(null),a=0;return t.forEach((i,l)=>r[i]=new lPe(i,a++,n,l)),r}removeFromSet(t){for(var n=0;n-1}}let B7t=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=Gy.from(t.nodes),n.marks=Gy.from(t.marks||{}),this.nodes=Yft.compile(this.spec.nodes,this),this.marks=lPe.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]=C7.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?Zft(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==""?[]:Zft(this,l.split(" "))}this.nodeFromJSON=a=>qM.fromJSON(this,a),this.markFromJSON=a=>hm.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 Yft){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 DCe(r,r.defaultAttrs,t,hm.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 Zft(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 NBs(s){return s.tag!=null}function kBs(s){return s.style!=null}let RQ=class p$e{constructor(t,n){this.schema=t,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(a=>{if(NBs(a))this.tags.push(a);else if(kBs(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 Qft(this,n,!1);return r.addAll(t,hm.none,n.from,n.to),r.finish()}parseSlice(t,n={}){let r=new Qft(this,n,!0);return r.addAll(t,hm.none,n.from,n.to),Si.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=Jft(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=Jft(l)),l.node||l.ignore||l.mark||(l.node=a)})}return n}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new p$e(t,p$e.schemaRules(t)))}};const U7t={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},SBs={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},q7t={ol:!0,ul:!0},bee=1,f$e=2,DQ=4;function Xft(s,t,n){return t!=null?(t?bee:0)|(t==="full"?f$e:0):s&&s.whitespace=="pre"?bee|f$e:n&~DQ}class Boe{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=hm.none,this.match=i||(l&DQ?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(Ba.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&bee)){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=Ba.from(this.content);return!t&&this.match&&(n=n.append(this.match.fillBefore(Ba.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&&!U7t.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class Qft{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=Xft(null,n.preserveWhitespace,0)|(r?DQ:0);a?i=new Boe(a.type,a.attrs,hm.none,!0,n.topMatch||a.type.contentMatch,l):r?i=new Boe(null,null,hm.none,!0,null,l):i=new Boe(t.schema.topNodeType,null,hm.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&f$e?"full":this.localPreserveWS||(a.options&bee)>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):egt(d.type,t))?(c=d.addToSet(c),!1):!0),this.nodes.push(new Boe(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|=bee)}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 CBs(s){for(let t=s.firstChild,n=null;t;t=t.nextSibling){let r=t.nodeType==1?t.nodeName.toLowerCase():null;r&&q7t.hasOwnProperty(r)&&n?(n.appendChild(t),t=n):r=="li"?n=t:r&&(n=null)}}function ABs(s,t){return(s.matches||s.msMatchesSelector||s.webkitMatchesSelector||s.mozMatchesSelector).call(s,t)}function Jft(s){let t={};for(let n in s)t[n]=s[n];return t}function egt(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&&B5e(eFe(r),a(t,n),null,t.attrs)}static renderSpec(t,n,r=null,a){return B5e(t,n,r,a)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new x9(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let n=tgt(t.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(t){return tgt(t.marks)}}function tgt(s){let t={};for(let n in s){let r=s[n].spec.toDOM;r&&(t[n]=r)}return t}function eFe(s){return s.document||window.document}const sgt=new WeakMap;function EBs(s){let t=sgt.get(s);return t===void 0&&sgt.set(s,t=TBs(s)),t}function TBs(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{let{dom:p,contentDOM:f}=B5e(s,m,n,r);if(c.appendChild(p),f){if(o)throw new RangeError("Multiple content holes");o=f}}}return{dom:c,contentDOM:o}}const $7t=65535,V7t=Math.pow(2,16);function MBs(s,t){return s+t*V7t}function ngt(s){return s&$7t}function PBs(s){return(s-(s&$7t))/V7t}const H7t=1,G7t=2,U5e=4,W7t=8;class g$e{constructor(t,n,r){this.pos=t,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&W7t)>0}get deletedBefore(){return(this.delInfo&(H7t|U5e))>0}get deletedAfter(){return(this.delInfo&(G7t|U5e))>0}get deletedAcross(){return(this.delInfo&U5e)>0}}class Fw{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&Fw.empty)return Fw.empty}recover(t){let n=0,r=ngt(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,p=c+a+(m<0?0:u);if(r)return p;let f=t==(n<0?c:h)?null:MBs(o/3,t-c),x=t==c?G7t:t==h?H7t:U5e;return(n<0?t!=c:t!=h)&&(x|=W7t),new g$e(p,x,f)}a+=u-d}return r?t+a:new g$e(t+a,0,null)}touches(t,n){let r=0,a=ngt(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 _ee;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 yx.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 J6(n.pos,r.pos,this.mark)}merge(t){return t instanceof J6&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new J6(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 J6(n.from,n.to,t.markFromJSON(n.mark))}}p1.jsonID("addMark",J6);class g4 extends p1{constructor(t,n,r){super(),this.from=t,this.to=n,this.mark=r}apply(t){let n=t.slice(this.from,this.to),r=new Si(ZQe(n.content,a=>a.mark(this.mark.removeFromSet(a.marks)),t),n.openStart,n.openEnd);return yx.fromReplace(t,this.from,this.to,r)}invert(){return new J6(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))}}p1.jsonID("removeMark",g4);class eM extends p1{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return yx.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return yx.fromReplace(t,this.pos,this.pos+1,new Si(Ba.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 uy(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 uy(n.from,n.to,n.gapFrom,n.gapTo,Si.fromJSON(t,n.slice),n.insert,!!n.structure)}}p1.jsonID("replaceAround",uy);function x$e(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 LBs(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),p=Math.min(d+c.nodeSize,n),f=r.addToSet(h);for(let x=0;xs.step(c)),i.forEach(c=>s.step(c))}function IBs(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 lPe){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 XQe(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 RBs(s,t,n){return(t==0||s.canReplace(t,s.childCount))&&(n==s.childCount||s.canReplace(0,n))}function MG(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;f--)x||r.index(f)>0?(x=!0,u=Ba.from(r.node(f).copy(u)),h++):c--;let m=Ba.empty,p=0;for(let f=i,x=!1;f>n;f--)x||a.after(f+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=Ba.from(n[l].type.create(n[l].attrs,r))}let a=t.start,i=t.end;s.step(new uy(a,i,a,i,new Si(r,0,0),n.length,!0))}function BBs(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)&&UBs(s.doc,s.mapping.slice(i).map(o),r)){let d=null;if(r.schema.linebreakReplacement){let p=r.whitespace=="pre",f=!!r.contentMatch.matchType(r.schema.linebreakReplacement);p&&!f?d=!1:!p&&f&&(d=!0)}d===!1&&Y7t(s,l,o,i),XQe(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 uy(h,m,h+1,m-1,new Si(Ba.from(r.create(c,null,l.marks)),0,0),1,!0)),d===!0&&K7t(s,l,o,i),!1}})}function K7t(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 Y7t(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 UBs(s,t,n){let r=s.resolve(t),a=r.index();return r.parent.canReplaceWith(a,a+1,n)}function qBs(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 uy(t,t+i.nodeSize,t+1,t+i.nodeSize-1,new Si(Ba.from(l),0,0),1,!0))}function Fq(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 p=h.content.cutByIndex(m,h.childCount),f=r&&r[u+1];f&&(p=p.replaceChild(0,f.type.create(f.attrs)));let x=r&&r[u]||h;if(!h.canReplace(m+1,h.childCount)||!x.type.validContent(p))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 $Bs(s,t,n=1,r){let a=s.doc.resolve(t),i=Ba.empty,l=Ba.empty;for(let o=a.depth,c=a.depth-n,d=n-1;o>c;o--,d--){i=Ba.from(a.node(o).copy(i));let u=r&&r[d];l=Ba.from(u?u.type.create(u.attrs,l):a.node(o).copy(l))}s.step(new hx(t,t,new Si(i.append(l),n,n),!0))}function VP(s,t){let n=s.resolve(t),r=n.index();return Z7t(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function VBs(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&&Z7t(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 HBs(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);Y7t(s,u.node(),u.before(),o)}l.inlineContent&&XQe(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 hx(d,c.map(t+n,-1),Si.empty,!0)),r===!0){let u=s.doc.resolve(d);K7t(s,u.node(),u.before(),s.steps.length)}return s}function GBs(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 dPe(s,t,n=t,r=Si.empty){if(t==n&&!r.size)return null;let a=s.resolve(t),i=s.resolve(n);return Q7t(a,i,r)?new hx(t,n,r):new WBs(a,i,r).fit()}function Q7t(s,t,n){return!n.openStart&&!n.openEnd&&s.start()==t.start()&&s.parent.canReplace(s.index(),t.index(),n.content)}class WBs{constructor(t,n,r){this.$from=t,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=Ba.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=Ba.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 Si(i,l,o);return t>-1?new uy(r.pos,t,this.$to.pos,this.$to.end(),c,n):c.size||r.pos!=this.$to.pos?new hx(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=sFe(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(Ba.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,a=sFe(t,n);return!a.childCount||a.firstChild.isLeaf?!1:(this.unplaced=new Si(t,n+1,Math.max(r,a.size+n>=t.size-r?n+1:0)),!0)}dropNode(){let{content:t,openStart:n,openEnd:r}=this.unplaced,a=sFe(t,n);if(a.childCount<=1&&n>0){let i=t.size-n<=n+a.size;this.unplaced=new Si(wZ(t,n-1,1),n-1,i?n-1:r)}else this.unplaced=new Si(wZ(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(J7t(x.mark(m.allowedMarks(x.marks)),d==1?c:0,d==o.childCount?p:-1)))}let f=d==o.childCount;f||(p=-1),this.placed=jZ(this.placed,n,Ba.from(u)),this.frontier[n].match=h,f&&p<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=nFe(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=jZ(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=jZ(this.placed,this.depth,Ba.from(t.create(n,r))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(Ba.empty,!0);n.childCount&&(this.placed=jZ(this.placed,this.frontier.length,n))}}function wZ(s,t,n){return t==0?s.cutByIndex(n,s.childCount):s.replaceChild(0,s.firstChild.copy(wZ(s.firstChild.content,t-1,n)))}function jZ(s,t,n){return t==0?s.append(n):s.replaceChild(s.childCount-1,s.lastChild.copy(jZ(s.lastChild.content,t-1,n)))}function sFe(s,t){for(let n=0;n1&&(r=r.replaceChild(0,J7t(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(Ba.empty,!0)))),s.copy(r)}function nFe(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&&!KBs(n,i.content,l)?o:null}function KBs(s,t,n){for(let r=n;r0;m--,p--){let f=a.node(m).type.spec;if(f.defining||f.definingAsContext||f.isolating)break;l.indexOf(m)>-1?o=m:a.before(m)==p&&l.splice(1,0,-m)}let c=l.indexOf(o),d=[],u=r.openStart;for(let m=r.content,p=0;;p++){let f=m.firstChild;if(d.push(f),p==r.openStart)break;m=f.content}for(let m=u-1;m>=0;m--){let p=d[m],f=YBs(p.type);if(f&&!p.sameMarkup(a.node(Math.abs(o)-1)))u=m;else if(f||!p.type.isTextblock)break}for(let m=r.openStart;m>=0;m--){let p=(m+u+1)%(r.openStart+1),f=d[p];if(f)for(let x=0;x=0&&(s.replace(t,n,r),!(s.steps.length>h));m--){let p=l[m];p<0||(t=a.before(p),n=i.after(p))}}function e9t(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(Ba.empty,!0))}return s}function XBs(s,t,n,r){if(!r.isInline&&t==n&&s.doc.resolve(t).parent.content.size){let a=GBs(s.doc,t,r.type);a!=null&&(t=n=a)}s.replaceRange(t,n,new Si(Ba.from(r),0,0))}function QBs(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=t9t(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 t9t(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 zq extends p1{constructor(t,n,r){super(),this.pos=t,this.attr=n,this.value=r}apply(t){let n=t.nodeAt(this.pos);if(!n)return yx.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 yx.fromReplace(t,this.pos,this.pos+1,new Si(Ba.from(a),0,n.isLeaf?0:1))}getMap(){return Fw.empty}invert(t){return new zq(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 zq(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 zq(n.pos,n.attr,n.value)}}p1.jsonID("attr",zq);class wee extends p1{constructor(t,n){super(),this.attr=t,this.value=n}apply(t){let n=Object.create(null);for(let a in t.attrs)n[a]=t.attrs[a];n[this.attr]=this.value;let r=t.type.create(n,t.content,t.marks);return yx.ok(r)}getMap(){return Fw.empty}invert(t){return new wee(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 wee(n.attr,n.value)}}p1.jsonID("docAttr",wee);let WV=class extends Error{};WV=function s(t){let n=Error.call(this,t);return n.__proto__=s.prototype,n};WV.prototype=Object.create(Error.prototype);WV.prototype.constructor=WV;WV.prototype.name="TransformError";let JQe=class{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new _ee}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let n=this.maybeStep(t);if(n.failed)throw new WV(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=Si.empty){let a=dPe(this.doc,t,n,r);return a&&this.step(a),this}replaceWith(t,n,r){return this.replace(t,n,new Si(Ba.from(r),0,0))}delete(t,n){return this.replace(t,n,Si.empty)}insert(t,n){return this.replaceWith(t,t,n)}replaceRange(t,n,r){return ZBs(this,t,n,r),this}replaceRangeWith(t,n,r){return XBs(this,t,n,r),this}deleteRange(t,n){return QBs(this,t,n),this}lift(t,n){return DBs(this,t,n),this}join(t,n=1){return HBs(this,t,n),this}wrap(t,n){return zBs(this,t,n),this}setBlockType(t,n=t,r,a=null){return BBs(this,t,n,r,a),this}setNodeMarkup(t,n,r=null,a){return qBs(this,t,n,r,a),this}setNodeAttribute(t,n,r){return this.step(new zq(t,n,r)),this}setDocAttribute(t,n){return this.step(new wee(t,n)),this}addNodeMark(t,n){return this.step(new eM(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 hm)n.isInSet(r.marks)&&this.step(new A7(t,n));else{let a=r.marks,i,l=[];for(;i=n.isInSet(a);)l.push(new A7(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 $Bs(this,t,n,r),this}addMark(t,n,r){return LBs(this,t,n,r),this}removeMark(t,n,r){return IBs(this,t,n,r),this}clearIncompatible(t,n,r){return XQe(this,t,n,r),this}};const rFe=Object.create(null);class Ol{constructor(t,n,r){this.$anchor=t,this.$head=n,this.ranges=r||[new s9t(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?FB(t.node(0),t.node(i),t.before(i+1),t.index(i),n,r):FB(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 rN(t.node(0))}static atStart(t){return FB(t,t,0,0,1)||new rN(t)}static atEnd(t){return FB(t,t,t.content.size,t.childCount,-1)||new rN(t)}static fromJSON(t,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=rFe[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 rFe)throw new RangeError("Duplicate use of selection JSON ID "+t);return rFe[t]=n,n.prototype.jsonID=t,n}getBookmark(){return pl.between(this.$anchor,this.$head).getBookmark()}}Ol.prototype.visible=!0;class s9t{constructor(t,n){this.$from=t,this.$to=n}}let agt=!1;function igt(s){!agt&&!s.parent.inlineContent&&(agt=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+s.parent.type.name+")"))}class pl extends Ol{constructor(t,n=t){igt(t),igt(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 Ol.near(r);let a=t.resolve(n.map(this.anchor));return new pl(a.parent.inlineContent?a:r,r)}replace(t,n=Si.empty){if(super.replace(t,n),n==Si.empty){let r=this.$from.marksAcross(this.$to);r&&t.ensureMarks(r)}}eq(t){return t instanceof pl&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new uPe(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 pl(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=Ol.findFrom(n,r,!0)||Ol.findFrom(n,-r,!0);if(i)n=i.$head;else return Ol.near(n,r)}return t.parent.inlineContent||(a==0?t=n:(t=(Ol.findFrom(t,-r,!0)||Ol.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&&nl.isSelectable(o))return nl.create(s,n-(a<0?o.nodeSize:0))}else{let c=FB(s,o,n+a,a<0?o.childCount:0,a,i);if(c)return c}n+=o.nodeSize*a}return null}function ogt(s,t,n){let r=s.steps.length-1;if(r{l==null&&(l=u)}),s.setSelection(Ol.near(s.doc.resolve(l),n))}const lgt=1,Uoe=2,cgt=4;class eUs extends JQe{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|=Uoe,this}ensureMarks(t){return hm.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&Uoe)>0}addStep(t,n){super.addStep(t,n),this.updated=this.updated&~Uoe,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)||hm.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(Ol.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|=cgt,this}get scrolledIntoView(){return(this.updated&cgt)>0}}function dgt(s,t){return!t||!s?s:s.bind(t)}class NZ{constructor(t,n,r){this.name=t,this.init=dgt(n.init,r),this.apply=dgt(n.apply,r)}}const tUs=[new NZ("doc",{init(s){return s.doc||s.schema.topNodeType.createAndFill()},apply(s){return s.doc}}),new NZ("selection",{init(s,t){return s.selection||Ol.atStart(t.doc)},apply(s){return s.selection}}),new NZ("storedMarks",{init(s){return s.storedMarks||null},apply(s,t,n,r){return r.selection.$cursor?s.storedMarks:null}}),new NZ("scrollToSelection",{init(){return 0},apply(s,t){return s.scrolledIntoView?t+1:t}})];class aFe{constructor(t,n){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=tUs.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 NZ(r.key,r.spec.state,r))})}}class _U{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 aFe(t.schema,t.plugins),i=new _U(a);return a.fields.forEach(l=>{if(l.name=="doc")i.doc=qM.fromJSON(t.schema,n.doc);else if(l.name=="selection")i.selection=Ol.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 n9t(s,t,n){for(let r in s){let a=s[r];a instanceof Function?a=a.bind(t):r=="handleDOMEvents"&&(a=n9t(a,t,{})),n[r]=a}return n}class b0{constructor(t){this.spec=t,this.props={},t.props&&n9t(t.props,this,this.props),this.key=t.key?t.key.key:r9t("plugin")}getState(t){return t[this.key]}}const iFe=Object.create(null);function r9t(s){return s in iFe?s+"$"+ ++iFe[s]:(iFe[s]=0,s+"$")}class f1{constructor(t="key"){this.key=r9t(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}const Xy=function(s){for(var t=0;;t++)if(s=s.previousSibling,!s)return t},KV=function(s){let t=s.assignedSlot||s.parentNode;return t&&t.nodeType==11?t.host:t};let y$e=null;const wC=function(s,t,n){let r=y$e||(y$e=document.createRange());return r.setEnd(s,n??s.nodeValue.length),r.setStart(s,t||0),r},sUs=function(){y$e=null},E7=function(s,t,n,r){return n&&(ugt(s,t,n,r,-1)||ugt(s,t,n,r,1))},nUs=/^(img|br|input|textarea|hr)$/i;function ugt(s,t,n,r,a){for(var i;;){if(s==n&&t==r)return!0;if(t==(a<0?0:P2(s))){let l=s.parentNode;if(!l||l.nodeType!=1||mre(s)||nUs.test(s.nodeName)||s.contentEditable=="false")return!1;t=Xy(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?P2(s):0}else return!1}}function P2(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function rUs(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=P2(s)}else if(s.parentNode&&!mre(s))t=Xy(s),s=s.parentNode;else return null}}function aUs(s,t){for(;;){if(s.nodeType==3&&t2),N2=YV||(Q4?/Mac/.test(Q4.platform):!1),o9t=Q4?/Win/.test(Q4.platform):!1,gA=/Android \d/.test(HP),pre=!!hgt&&"webkitFontSmoothing"in hgt.documentElement.style,cUs=pre?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function dUs(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 Q3(s,t){return typeof s=="number"?s:s[t]}function uUs(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 mgt(s,t,n){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=KV(l);continue}let o=l,c=o==i.body,d=c?dUs(i):uUs(o),u=0,h=0;if(t.topd.bottom-Q3(r,"bottom")&&(h=t.bottom-t.top>d.bottom-d.top?t.top+Q3(a,"top")-d.top:t.bottom-d.bottom+Q3(a,"bottom")),t.leftd.right-Q3(r,"right")&&(u=t.right-d.right+Q3(a,"right")),u||h)if(c)i.defaultView.scrollBy(u,h);else{let p=o.scrollLeft,f=o.scrollTop;h&&(o.scrollTop+=h),u&&(o.scrollLeft+=u);let x=o.scrollLeft-p,y=o.scrollTop-f;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:KV(l)}}function hUs(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:l9t(s.dom)}}function l9t(s){let t=[],n=s.ownerDocument;for(let r=s;r&&(t.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),s!=n);r=KV(r));return t}function mUs({refDOM:s,refTop:t,stack:n}){let r=s?s.getBoundingClientRect().top:0;c9t(n,r==0?0:r-t)}function c9t(s,t){for(let n=0;n=o){l=Math.max(f.bottom,l),o=Math.min(f.top,o);let x=f.left>t.left?f.left-t.left:f.right=(f.left+f.right)/2?1:0));continue}}else f.top>t.top&&!c&&f.left<=t.left&&f.right>=t.left&&(c=u,d={left:Math.max(f.left,Math.min(f.right,t.left)),top:f.top});!n&&(t.left>=f.right&&t.top>=f.top||t.left>=f.left&&t.top>=f.bottom)&&(i=h+1)}}return!n&&c&&(n=c,a=d,r=0),n&&n.nodeType==3?fUs(n,a):!n||r&&n.nodeType==1?{node:s,offset:i}:d9t(n,a)}function fUs(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 tJe(s,t){return s.left>=t.left-1&&s.left<=t.right+1&&s.top>=t.top-1&&s.top<=t.bottom+1}function gUs(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 yUs(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 u9t(s,t,n){let r=s.childNodes.length;if(r&&n.topt.top&&a++}let d;pre&&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=yUs(s,r,a,t))}o==null&&(o=xUs(s,l,t));let c=s.docView.nearestDesc(l,!0);return{pos:o,inside:c?c.posAtStart-c.border:-1}}function pgt(s){return s.top=0&&a==r.nodeValue.length?(c--,u=1):n<0?c--:d++,tY(CT(wC(r,c,d),u),u<0)}if(!s.state.doc.resolve(t-(i||0)).parent.inlineContent){if(i==null&&a&&(n<0||a==P2(r))){let c=r.childNodes[a-1];if(c.nodeType==1)return oFe(c.getBoundingClientRect(),!1)}if(i==null&&a=0)}if(i==null&&a&&(n<0||a==P2(r))){let c=r.childNodes[a-1],d=c.nodeType==3?wC(c,P2(c)-(l?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return tY(CT(d,1),!1)}if(i==null&&a=0)}function tY(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 oFe(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 m9t(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 _Us(s,t,n){let r=t.selection,a=n=="up"?r.$from:r.$to;return m9t(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=h9t(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=wC(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 wUs=/[\u0590-\u08ac]/;function jUs(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?!wUs.test(r.parent.textContent)||!o.modify?n=="left"||n=="backward"?i:l:m9t(s,t,()=>{let{focusNode:c,focusOffset:d,anchorNode:u,anchorOffset:h}=s.domSelectionRange(),m=o.caretBidiLevel;o.modify("move",n,"character");let p=r.depth?s.docView.domAfterPos(r.before()):s.dom,{focusNode:f,focusOffset:x}=s.domSelectionRange(),y=f&&!p.contains(f.nodeType==1?f:f.parentNode)||c==f&&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 fgt=null,ggt=null,xgt=!1;function NUs(s,t,n){return fgt==t&&ggt==n?xgt:(fgt=t,ggt=n,xgt=n=="up"||n=="down"?_Us(s,t,n):jUs(s,t,n))}const iN=0,ygt=1,WD=2,J4=3;class fre{constructor(t,n,r,a){this.parent=t,this.children=n,this.dom=r,this.contentDOM=a,this.dirty=iN,r.pmViewDesc=this}matchesWidget(t){return!1}matchesMark(t){return!1}matchesNode(t,n,r){return!1}matchesHack(t){return!1}parseRule(){return null}stopEvent(t){return!1}get size(){let t=0;for(let n=0;nXy(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 f9t){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 p9t&&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?Xy(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=Xy(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;uf&&ln){let f=o;o=c,c=f}let p=document.createRange();p.setEnd(c.node,c.offset),p.setStart(o.node,o.offset),d.removeAllRanges(),d.addRange(p)}}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?WD:ygt,t==o&&n==c&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=J4:i.markDirty(t-o,n-o);return}else i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?WD:J4}r=l}this.dirty=WD}markParentsDirty(){let t=1;for(let n=this.parent;n;n=n.parent,t++){let r=t==1?WD:ygt;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.contentEditable="false",l.classList.add("ProseMirror-widget")}super(t,[],l,null),this.widget=n,this.widget=n,i=this}matchesWidget(t){return this.dirty==iN&&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 kUs extends fre{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 T7 extends fre{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=x9.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new T7(t,n,l.dom,l.contentDOM||l.dom,l)}parseRule(){return this.dirty&J4||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return this.dirty!=J4&&this.mark.eq(t)}markDirty(t,n){if(super.markDirty(t,n),this.dirty!=iN){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(i=j$e(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}=x9.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=y9t(u,r,n),d?c=new SUs(t,n,r,a,u,h||null,m,d,i,l+1):n.isText?new mPe(t,n,r,a,u,m,i):new VM(t,n,r,a,u,h||null,m,i,l+1)}parseRule(){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let n=this.children.length-1;n>=0;n--){let r=this.children[n];if(this.dom.contains(r.dom.parentNode)){t.contentElement=r.dom.parentNode;break}}t.contentElement||(t.getContent=()=>Ba.empty)}return t}matchesNode(t,n,r){return this.dirty==iN&&t.eq(this.node)&&OCe(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 AUs(this,l&&l.node,t);MUs(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?hm.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 p;c.findNodeMatch(d,u,h,m)||o&&t.state.selection.from>a&&t.state.selection.to-1&&c.updateNodeAt(d,u,h,p,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==WD)&&(l&&this.protectLocalComposition(t,l),g9t(this.contentDOM,this.children,t),YV&&PUs(this.dom))}localCompositionInfo(t,n){let{from:r,to:a}=t.state.selection;if(!(t.state.selection instanceof pl)||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=LUs(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 kUs(this,i,n,a);t.input.compositionNodes.push(l),this.children=j$e(this.children,r,r+a.length,t,l)}update(t,n,r,a){return this.dirty==J4||!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=iN}updateOuterDeco(t){if(OCe(t,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=x9t(this.dom,this.nodeDOM,w$e(this.outerDeco,this.node,n),w$e(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 vgt(s,t,n,r,a){y9t(r,t,s);let i=new VM(void 0,s,t,n,r,r,r,a,0);return i.contentDOM&&i.updateChildren(a,0),i}class mPe extends VM{constructor(t,n,r,a,i,l,o){super(t,n,r,a,i,null,l,o,0)}parseRule(){let t=this.nodeDOM.parentNode;for(;t&&t!=this.dom&&!t.pmIsDeco;)t=t.parentNode;return{skip:t||!0}}update(t,n,r,a){return this.dirty==J4||this.dirty!=iN&&!this.inParent()||!t.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=iN||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=iN,!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 mPe(this.parent,a,this.outerDeco,this.innerDeco,i,i,r)}markDirty(t,n){super.markDirty(t,n),this.dom!=this.nodeDOM&&(t==0||n==this.nodeDOM.nodeValue.length)&&(this.dirty=J4)}get domAtom(){return!1}isText(t){return this.node.text==t}}class f9t extends fre{parseRule(){return{ignore:!0}}matchesHack(t){return this.dirty==iN&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class SUs extends VM{constructor(t,n,r,a,i,l,o,c,d,u){super(t,n,r,a,i,l,o,d,u),this.spec=c}update(t,n,r,a){if(this.dirty==J4)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 g9t(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=T7.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 T7)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 TUs(s,t){return s.type.side-t.type.side}function MUs(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 f=i+m.nodeSize;if(m.isText){let y=f;l!y.inline):o.slice();r(m,x,t.forChild(i,m),p),i=f}}function PUs(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 LUs(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 j$e(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 sJe(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(hPe(n)){for(c=l;a&&!a.node;)a=a.parent;let h=a.node;if(a&&h.isAtom&&nl.isSelectable(h)&&a.parent&&!(h.isInline&&iUs(n.focusNode,n.focusOffset,a.dom))){let m=a.posBefore;d=new nl(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 p=0;p{(n.anchorNode!=r||n.anchorOffset!=a)&&(t.removeEventListener("selectionchange",s.input.hideSelectionGuard),setTimeout(()=>{(!v9t(s)||s.state.selection.visible)&&s.dom.classList.remove("ProseMirror-hideselection")},20))})}function RUs(s){let t=s.domSelection();if(!t)return;let n=s.cursorWrapper.dom,r=n.nodeName=="IMG";r?t.collapse(n.parentNode,Xy(n)+1):t.collapse(n,0),!r&&!s.state.selection.visible&&E_&&$M<=11&&(n.disabled=!0,n.disabled=!1)}function b9t(s,t){if(t instanceof nl){let n=s.docView.descAt(t.from);n!=s.lastSelectedViewDesc&&(Ngt(s),n&&n.selectNode(),s.lastSelectedViewDesc=n)}else Ngt(s)}function Ngt(s){s.lastSelectedViewDesc&&(s.lastSelectedViewDesc.parent&&s.lastSelectedViewDesc.deselectNode(),s.lastSelectedViewDesc=void 0)}function nJe(s,t,n,r){return s.someProp("createSelectionBetween",a=>a(s,t,n))||pl.between(t,n,r)}function kgt(s){return s.editable&&!s.hasFocus()?!1:_9t(s)}function _9t(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 DUs(s){let t=s.docView.domFromPos(s.state.selection.anchor,0),n=s.domSelectionRange();return E7(t.node,t.offset,n.anchorNode,n.anchorOffset)}function N$e(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&&Ol.findFrom(i,t)}function VT(s,t){return s.dispatch(s.state.tr.setSelection(t).scrollIntoView()),!0}function Sgt(s,t,n){let r=s.state.selection;if(r instanceof pl)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 VT(s,new pl(r.$anchor,l))}else if(r.empty){if(s.endOfTextblock(t>0?"forward":"backward")){let a=N$e(s.state,t);return a&&a instanceof nl?VT(s,a):!1}else if(!(N2&&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?nl.isSelectable(i)?VT(s,new nl(t<0?s.state.doc.resolve(a.pos-i.nodeSize):a)):pre?VT(s,new pl(s.state.doc.resolve(t<0?o:o+i.nodeSize))):!1:!1}}else return!1;else{if(r instanceof nl&&r.node.isInline)return VT(s,new pl(t>0?r.$to:r.$from));{let a=N$e(s.state,t);return a?VT(s,a):!1}}}function FCe(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function FQ(s,t){let n=s.pmViewDesc;return n&&n.size==0&&(t<0||s.nextSibling||s.nodeName!="BR")}function Wz(s,t){return t<0?OUs(s):FUs(s)}function OUs(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a,i,l=!1;for(aN&&n.nodeType==1&&r0){if(n.nodeType!=1)break;{let o=n.childNodes[r-1];if(FQ(o,-1))a=n,i=--r;else if(o.nodeType==3)n=o,r=n.nodeValue.length;else break}}else{if(w9t(n))break;{let o=n.previousSibling;for(;o&&FQ(o,-1);)a=n.parentNode,i=Xy(o),o=o.previousSibling;if(o)n=o,r=FCe(n);else{if(n=n.parentNode,n==s.dom)break;r=0}}}l?k$e(s,n,r):a&&k$e(s,a,i)}function FUs(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a=FCe(n),i,l;for(;;)if(r{s.state==a&&DA(s)},50)}function Cgt(s,t){let n=s.state.doc.resolve(t);if(!(av||o9t)&&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 Agt(s,t,n){let r=s.state.selection;if(r instanceof pl&&!r.empty||n.indexOf("s")>-1||N2&&n.indexOf("m")>-1)return!1;let{$from:a,$to:i}=r;if(!a.parent.inlineContent||s.endOfTextblock(t<0?"up":"down")){let l=N$e(s.state,t);if(l&&l instanceof nl)return VT(s,l)}if(!a.parent.inlineContent){let l=t<0?a:i,o=r instanceof rN?Ol.near(l,t):Ol.findFrom(l,t);return o?VT(s,o):!1}return!1}function Egt(s,t){if(!(s.state.selection instanceof pl))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 Tgt(s,t,n){s.domObserver.stop(),t.contentEditable=n,s.domObserver.start()}function UUs(s){if(!d1||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;Tgt(s,r,"true"),setTimeout(()=>Tgt(s,r,"false"),20)}return!1}function qUs(s){let t="";return s.ctrlKey&&(t+="c"),s.metaKey&&(t+="m"),s.altKey&&(t+="a"),s.shiftKey&&(t+="s"),t}function $Us(s,t){let n=t.keyCode,r=qUs(t);if(n==8||N2&&n==72&&r=="c")return Egt(s,-1)||Wz(s,-1);if(n==46&&!t.shiftKey||N2&&n==68&&r=="c")return Egt(s,1)||Wz(s,1);if(n==13||n==27)return!0;if(n==37||N2&&n==66&&r=="c"){let a=n==37?Cgt(s,s.state.selection.from)=="ltr"?-1:1:-1;return Sgt(s,a,r)||Wz(s,a)}else if(n==39||N2&&n==70&&r=="c"){let a=n==39?Cgt(s,s.state.selection.from)=="ltr"?1:-1:1;return Sgt(s,a,r)||Wz(s,a)}else{if(n==38||N2&&n==80&&r=="c")return Agt(s,-1,r)||Wz(s,-1);if(n==40||N2&&n==78&&r=="c")return UUs(s)||Agt(s,1,r)||Wz(s,1);if(r==(N2?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function rJe(s,t){s.someProp("transformCopied",p=>{t=p(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 p=r.firstChild;n.push(p.type.name,p.attrs!=p.type.defaultAttrs?p.attrs:null),r=p.content}let l=s.someProp("clipboardSerializer")||x9.fromSchema(s.state.schema),o=A9t(),c=o.createElement("div");c.appendChild(l.serializeFragment(r,{document:o}));let d=c.firstChild,u,h=0;for(;d&&d.nodeType==1&&(u=C9t[d.nodeName.toLowerCase()]);){for(let p=u.length-1;p>=0;p--){let f=o.createElement(u[p]);for(;c.firstChild;)f.appendChild(c.firstChild);c.appendChild(f),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",p=>p(t,s))||t.content.textBetween(0,t.content.size,` `);return{dom:c,text:m,slice:t}}function j9t(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 Si(Ba.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:p}=s.state,f=x9.fromSchema(p);l=document.createElement("div"),t.split(/(?:\r\n?|\n)+/).forEach(x=>{let y=l.appendChild(document.createElement("p"));x&&y.appendChild(f.serializeNode(p.text(x,m)))})}}else s.someProp("transformPastedHTML",h=>{n=h(n,s)}),l=WUs(n),pre&&KUs(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")||RQ.fromSchema(s.state.schema)).parseSlice(l,{preserveWhitespace:!!(c||u),context:a,ruleFromNode(m){return m.nodeName=="BR"&&!m.nextSibling&&m.parentNode&&!VUs.test(m.parentNode.nodeName)?{ignore:!0}:null}})),u)o=YUs(Mgt(o,+u[1],+u[2]),u[4]);else if(o=Si.maxOpen(HUs(o.content,a),!0),o.openStart||o.openEnd){let h=0,m=0;for(let p=o.content.firstChild;h{o=h(o,s,c)}),o}const VUs=/^(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 HUs(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&&k9t(c,i,o,l[l.length-1],0))l[l.length-1]=d;else{l.length&&(l[l.length-1]=S9t(l[l.length-1],i.length));let u=N9t(o,c);l.push(u),a=a.matchType(u.type),i=c}}),l)return Ba.from(l)}return s}function N9t(s,t,n=0){for(let r=t.length-1;r>=n;r--)s=t[r].create(null,Ba.from(s));return s}function k9t(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(Ba.empty,!0))),s.replaceChild(t<0?0:s.childCount-1,l.copy(o))}function Mgt(s,t,n){return tn})),cFe.createHTML(s)):s}function WUs(s){let t=/^(\s*]*>)*/.exec(s);t&&(s=s.slice(t[0].length));let n=A9t().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(s),a;if((a=r&&C9t[r[1].toLowerCase()])&&(s=a.map(i=>"<"+i+">").join("")+s+a.map(i=>"").reverse().join("")),n.innerHTML=GUs(s),a)for(let i=0;i=0;o-=2){let c=n.nodes[r[o]];if(!c||c.hasRequiredAttrs())break;a=Ba.from(c.create(r[o+1],a)),i++,l++}return new Si(a,i,l)}const bb={},_b={},ZUs={touchstart:!0,touchmove:!0};class XUs{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 QUs(s){for(let t in bb){let n=bb[t];s.dom.addEventListener(t,s.input.eventHandlers[t]=r=>{eqs(s,r)&&!aJe(s,r)&&(s.editable||!(r.type in _b))&&n(s,r)},ZUs[t]?{passive:!0}:void 0)}d1&&s.dom.addEventListener("input",()=>null),C$e(s)}function tM(s,t){s.input.lastSelectionOrigin=t,s.input.lastSelectionTime=Date.now()}function JUs(s){s.domObserver.stop();for(let t in s.input.eventHandlers)s.dom.removeEventListener(t,s.input.eventHandlers[t]);clearTimeout(s.input.composingTimeout),clearTimeout(s.input.lastIOSEnterFallbackTimeout)}function C$e(s){s.someProp("handleDOMEvents",t=>{for(let n in t)s.input.eventHandlers[n]||s.dom.addEventListener(n,s.input.eventHandlers[n]=r=>aJe(s,r))})}function aJe(s,t){return s.someProp("handleDOMEvents",n=>{let r=n[t.type];return r?r(s,t)||t.defaultPrevented:!1})}function eqs(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 tqs(s,t){!aJe(s,t)&&bb[t.type]&&(s.editable||!(t.type in _b))&&bb[t.type](s,t)}_b.keydown=(s,t)=>{let n=t;if(s.input.shiftKey=n.keyCode==16||n.shiftKey,!T9t(s,n)&&(s.input.lastKeyCode=n.keyCode,s.input.lastKeyCodeTime=Date.now(),!(gA&&av&&n.keyCode==13)))if(n.keyCode!=229&&s.domObserver.forceFlush(),YV&&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,TD(13,"Enter"))),s.input.lastIOSEnter=0)},200)}else s.someProp("handleKeyDown",r=>r(s,n))||$Us(s,n)?n.preventDefault():tM(s,"key")};_b.keyup=(s,t)=>{t.keyCode==16&&(s.input.shiftKey=!1)};_b.keypress=(s,t)=>{let n=t;if(T9t(s,n)||!n.charCode||n.ctrlKey&&!n.altKey||N2&&n.metaKey)return;if(s.someProp("handleKeyPress",a=>a(s,n))){n.preventDefault();return}let r=s.state.selection;if(!(r instanceof pl)||!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 pPe(s){return{left:s.clientX,top:s.clientY}}function sqs(s,t){let n=t.x-s.clientX,r=t.y-s.clientY;return n*n+r*r<100}function iJe(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 Bq(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 nqs(s,t){if(t==-1)return!1;let n=s.state.doc.resolve(t),r=n.nodeAfter;return r&&r.isAtom&&nl.isSelectable(r)?(Bq(s,new nl(n)),!0):!1}function rqs(s,t){if(t==-1)return!1;let n=s.state.selection,r,a;n instanceof nl&&(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(nl.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?(Bq(s,nl.create(s.state.doc,a)),!0):!1}function aqs(s,t,n,r,a){return iJe(s,"handleClickOn",t,n,r)||s.someProp("handleClick",i=>i(s,t,r))||(a?rqs(s,n):nqs(s,n))}function iqs(s,t,n,r){return iJe(s,"handleDoubleClickOn",t,n,r)||s.someProp("handleDoubleClick",a=>a(s,t,r))}function oqs(s,t,n,r){return iJe(s,"handleTripleClickOn",t,n,r)||s.someProp("handleTripleClick",a=>a(s,t,r))||lqs(s,n,r)}function lqs(s,t,n){if(n.button!=0)return!1;let r=s.state.doc;if(t==-1)return r.inlineContent?(Bq(s,pl.create(r,0,r.content.size)),!0):!1;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)Bq(s,pl.create(r,o+1,o+1+l.content.size));else if(nl.isSelectable(l))Bq(s,nl.create(r,o));else continue;return!0}}function oJe(s){return zCe(s)}const E9t=N2?"metaKey":"ctrlKey";bb.mousedown=(s,t)=>{let n=t;s.input.shiftKey=n.shiftKey;let r=oJe(s),a=Date.now(),i="singleClick";a-s.input.lastClick.time<500&&sqs(n,s.input.lastClick)&&!n[E9t]&&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};let l=s.posAtCoords(pPe(n));l&&(i=="singleClick"?(s.input.mouseDown&&s.input.mouseDown.done(),s.input.mouseDown=new cqs(s,l,n,!!r)):(i=="doubleClick"?iqs:oqs)(s,l.pos,l.inside,n)?n.preventDefault():tM(s,"pointer"))};class cqs{constructor(t,n,r,a){this.view=t,this.pos=n,this.event=r,this.flushed=a,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=t.state.doc,this.selectNode=!!r[E9t],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 nl&&d.from<=l&&d.to>l)&&(this.mightDrag={node:i,pos:l,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&aN&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),t.root.addEventListener("mouseup",this.up=this.up.bind(this)),t.root.addEventListener("mousemove",this.move=this.move.bind(this)),tM(t,"pointer")}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>DA(this.view)),this.view.input.mouseDown=null}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(pPe(t))),this.updateAllowDefault(t),this.allowDefault||!n?tM(this.view,"pointer"):aqs(this.view,n.pos,n.inside,t,this.selectNode)?t.preventDefault():t.button==0&&(this.flushed||d1&&this.mightDrag&&!this.mightDrag.node.isAtom||av&&!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)?(Bq(this.view,Ol.near(this.view.state.doc.resolve(n.pos))),t.preventDefault()):tM(this.view,"pointer")}move(t){this.updateAllowDefault(t),tM(this.view,"pointer"),t.buttons==0&&this.done()}updateAllowDefault(t){!this.allowDefault&&(Math.abs(this.event.x-t.clientX)>4||Math.abs(this.event.y-t.clientY)>4)&&(this.allowDefault=!0)}}bb.touchstart=s=>{s.input.lastTouch=Date.now(),oJe(s),tM(s,"pointer")};bb.touchmove=s=>{s.input.lastTouch=Date.now(),tM(s,"pointer")};bb.contextmenu=s=>oJe(s);function T9t(s,t){return s.composing?!0:d1&&Math.abs(t.timeStamp-s.input.compositionEndedAt)<500?(s.input.compositionEndedAt=-2e8,!0):!1}const dqs=gA?5e3:-1;_b.compositionstart=_b.compositionupdate=s=>{if(!s.composing){s.domObserver.flush();let{state:t}=s,n=t.selection.$to;if(t.selection instanceof pl&&(t.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||av&&o9t&&uqs(s)))s.markCursor=s.state.storedMarks||n.marks(),zCe(s,!0),s.markCursor=null;else if(zCe(s,!t.selection.empty),aN&&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}M9t(s,dqs)};function uqs(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"}_b.compositionend=(s,t)=>{s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=t.timeStamp,s.input.compositionPendingChanges=s.domObserver.pendingRecords().length?s.input.compositionID:0,s.input.compositionNode=null,s.input.badSafariComposition?s.domObserver.forceFlush():s.input.compositionPendingChanges&&Promise.resolve().then(()=>s.domObserver.flush()),s.input.compositionID++,M9t(s,20))};function M9t(s,t){clearTimeout(s.input.composingTimeout),t>-1&&(s.input.composingTimeout=setTimeout(()=>zCe(s),t))}function P9t(s){for(s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=mqs());s.input.compositionNodes.length>0;)s.input.compositionNodes.pop().markParentsDirty()}function hqs(s){let t=s.domSelectionRange();if(!t.focusNode)return null;let n=rUs(t.focusNode,t.focusOffset),r=aUs(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 mqs(){let s=document.createEvent("Event");return s.initEvent("event",!0,!0),s.timeStamp}function zCe(s,t=!1){if(!(gA&&s.domObserver.flushingSoon>=0)){if(s.domObserver.forceFlush(),P9t(s),t||s.docView&&s.docView.dirty){let n=sJe(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 pqs(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 jee=E_&&$M<15||YV&&cUs<604;bb.copy=_b.cut=(s,t)=>{let n=t,r=s.state.selection,a=n.type=="cut";if(r.empty)return;let i=jee?null:n.clipboardData,l=r.content(),{dom:o,text:c}=rJe(s,l);i?(n.preventDefault(),i.clearData(),i.setData("text/html",o.innerHTML),i.setData("text/plain",c)):pqs(s,o),a&&s.dispatch(s.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function fqs(s){return s.openStart==0&&s.openEnd==0&&s.content.childCount==1?s.content.firstChild:null}function gqs(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?Nee(s,r.value,null,a,t):Nee(s,r.textContent,r.innerHTML,a,t)},50)}function Nee(s,t,n,r,a){let i=j9t(s,t,n,r,s.state.selection.$from);if(s.someProp("handlePaste",c=>c(s,a,i||Si.empty)))return!0;if(!i)return!1;let l=fqs(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 L9t(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," "):""}_b.paste=(s,t)=>{let n=t;if(s.composing&&!gA)return;let r=jee?null:n.clipboardData,a=s.input.shiftKey&&s.input.lastKeyCode!=45;r&&Nee(s,L9t(r),r.getData("text/html"),a,n)?n.preventDefault():gqs(s,n)};class I9t{constructor(t,n,r){this.slice=t,this.move=n,this.node=r}}const xqs=N2?"altKey":"ctrlKey";function R9t(s,t){let n;return s.someProp("dragCopies",r=>{n=n||r(t)}),n!=null?!n:!t[xqs]}bb.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(pPe(n)),l;if(!(i&&i.pos>=a.from&&i.pos<=(a instanceof nl?a.to-1:a.to))){if(r&&r.mightDrag)l=nl.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=nl.create(s.state.doc,h.posBefore))}}let o=(l||s.state.selection).content(),{dom:c,text:d,slice:u}=rJe(s,o);(!n.dataTransfer.files.length||!av||i9t>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(jee?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",jee||n.dataTransfer.setData("text/plain",d),s.dragging=new I9t(u,R9t(s,n),l)};bb.dragend=s=>{let t=s.dragging;window.setTimeout(()=>{s.dragging==t&&(s.dragging=null)},50)};_b.dragover=_b.dragenter=(s,t)=>t.preventDefault();_b.drop=(s,t)=>{try{yqs(s,t,s.dragging)}finally{s.dragging=null}};function yqs(s,t,n){if(!t.dataTransfer)return;let r=s.posAtCoords(pPe(t));if(!r)return;let a=s.state.doc.resolve(r.pos),i=n&&n.slice;i?s.someProp("transformPasted",p=>{i=p(i,s,!1)}):i=j9t(s,L9t(t.dataTransfer),jee?null:t.dataTransfer.getData("text/html"),!1,a);let l=!!(n&&R9t(s,t));if(s.someProp("handleDrop",p=>p(s,t,i||Si.empty,l))){t.preventDefault();return}if(!i)return;t.preventDefault();let o=i?X7t(s.state.doc,a.pos,i):a.pos;o==null&&(o=a.pos);let c=s.state.tr;if(l){let{node:p}=n;p?p.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&&nl.isSelectable(i.content.firstChild)&&m.nodeAfter&&m.nodeAfter.sameMarkup(i.content.firstChild))c.setSelection(new nl(m));else{let p=c.mapping.map(o);c.mapping.maps[c.mapping.maps.length-1].forEach((f,x,y,v)=>p=v),c.setSelection(nJe(s,m,c.doc.resolve(p)))}s.focus(),s.dispatch(c.setMeta("uiEvent","drop"))}bb.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())&&DA(s)},20))};bb.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)};bb.beforeinput=(s,t)=>{if(av&&gA&&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,TD(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 _b)bb[s]=_b[s];function kee(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 BCe{constructor(t,n){this.toDOM=t,this.spec=n||KF,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 sb(i-r,i-r,this)}valid(){return!0}eq(t){return this==t||t instanceof BCe&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&kee(this.spec,t.spec))}destroy(t){this.spec.destroy&&this.spec.destroy(t)}}class HM{constructor(t,n){this.attrs=t,this.spec=n||KF}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 sb(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==Yv||t.maps.length==0?this:this.mapInner(t,n,0,0,r||KF)}mapInner(t,n,r,a,i){let l;for(let o=0;o{let d=c+r,u;if(u=O9t(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 HM){let d=Math.max(i,c.from)-i,u=Math.min(l,c.to)-i;da.map(t,n,KF));return n6.from(r)}forChild(t,n){if(n.isLeaf)return Jf.empty;let r=[];for(let a=0;an instanceof Jf)?t:t.reduce((n,r)=>n.concat(r instanceof Jf?r:r.members),[]))}}forEachSet(t){for(let n=0;n{let y=x-f-(p-m);for(let v=0;vb+u-h)continue;let N=o[v]+u-h;p>=N?o[v+1]=m<=N?-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),p=m-a,{index:f,offset:x}=r.content.findIndex(h),y=r.maybeChild(f);if(y&&x==h&&x+y.nodeSize==p){let v=o[d+2].mapInner(n,y,u+1,s[d]+i+1,l);v!=Yv?(o[d]=h,o[d+1]=p,o[d+2]=v):(o[d+1]=-2,c=!0)}else c=!0}if(c){let d=bqs(o,s,t,n,a,i,l),u=UCe(d,r,0,l);t=u.local;for(let h=0;hn&&l.to{let d=O9t(s,o,c+n);if(d){i=!0;let u=UCe(d,o,n+c+1,r);u!=Yv&&a.push(c,c+o.nodeSize,u)}});let l=D9t(i?F9t(s):s,-n).sort(YF);for(let o=0;o0;)t++;s.splice(t,0,n)}function dFe(s){let t=[];return s.someProp("decorations",n=>{let r=n(s.state);r&&r!=Yv&&t.push(r)}),s.cursorWrapper&&t.push(Jf.create(s.state.doc,[s.cursorWrapper.deco])),n6.from(t)}const _qs={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},wqs=E_&&$M<=11;class jqs{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 Nqs{constructor(t,n){this.view=t,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new jqs,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():d1&&t.composing&&r.some(a=>a.type=="childList"&&a.target.nodeName=="TR")?(t.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),wqs&&(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,_qs)),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(kgt(this.view)){if(this.suppressingSelectionUpdates)return DA(this.view);if(E_&&$M<=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&E7(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=KV(i))n.add(i);for(let i=t.anchorNode;i;i=KV(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)&&kgt(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)){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(aN&&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 p=m.parentNode;p&&p.nodeName=="LI"&&(!h||Cqs(t,h)!=p)&&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),kqs(t)),t.input.badSafariComposition&&(t.input.badSafariComposition=!1,Aqs(t,c)),this.handleDOMChange(i,l,o,c),t.docView&&t.docView.dirty?t.updateState(t.state):this.currentSelection.eq(r)||DA(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;ua;y--){let v=r.childNodes[y-1],b=v.pmViewDesc;if(v.nodeName=="BR"&&!b){i=y;break}if(!b||b.size)break}let h=s.state.doc,m=s.someProp("domParser")||RQ.fromSchema(s.state.schema),p=h.resolve(l),f=null,x=m.parse(r,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:a,to:i,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:d,ruleFromNode:Tqs,context:p});if(d&&d[0].pos!=null){let y=d[0].pos,v=d[1]&&d[1].pos;v==null&&(v=y),f={anchor:y+l,head:v+l}}return{doc:x,sel:f,from:l,to:o}}function Tqs(s){let t=s.pmViewDesc;if(t)return t.parseRule();if(s.nodeName=="BR"&&s.parentNode){if(d1&&/^(ul|ol)$/i.test(s.parentNode.nodeName)){let n=document.createElement("div");return n.appendChild(document.createElement("li")),{skip:n}}else if(s.parentNode.lastChild==s||d1&&/^(tr|table)$/i.test(s.parentNode.nodeName))return{ignore:!0}}else if(s.nodeName=="IMG"&&s.getAttribute("mark-placeholder"))return{ignore:!0};return null}const Mqs=/^(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 Pqs(s,t,n,r,a){let i=s.input.compositionPendingChanges||(s.composing?s.input.compositionID:0);if(s.input.compositionPendingChanges=0,t<0){let L=s.input.lastSelectionTime>Date.now()-50?s.input.lastSelectionOrigin:null,M=sJe(s,L);if(M&&!s.state.selection.eq(M)){if(av&&gA&&s.input.lastKeyCode===13&&Date.now()-100R(s,TD(13,"Enter"))))return;let I=s.state.tr.setSelection(M);L=="pointer"?I.setMeta("pointer",!0):L=="key"&&I.scrollIntoView(),i&&I.setMeta("composition",i),s.dispatch(I)}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=Eqs(s,t,n),u=s.state.doc,h=u.slice(d.from,d.to),m,p;s.input.lastKeyCode===8&&Date.now()-100Date.now()-225||gA)&&a.some(L=>L.nodeType==1&&!Mqs.test(L.nodeName))&&(!f||f.endA>=f.endB)&&s.someProp("handleKeyDown",L=>L(s,TD(13,"Enter")))){s.input.lastIOSEnter=0;return}if(!f)if(r&&c instanceof pl&&!c.empty&&c.$head.sameParent(c.$anchor)&&!s.composing&&!(d.sel&&d.sel.anchor!=d.sel.head))f={start:c.from,endA:c.to,endB:c.to};else{if(d.sel){let L=Ogt(s,s.state.doc,d.sel);if(L&&!L.eq(s.state.selection)){let M=s.state.tr.setSelection(L);i&&M.setMeta("composition",i),s.dispatch(M)}}return}s.state.selection.froms.state.selection.from&&f.start<=s.state.selection.from+2&&s.state.selection.from>=d.from?f.start=s.state.selection.from:f.endA=s.state.selection.to-2&&s.state.selection.to<=d.to&&(f.endB+=s.state.selection.to-f.endA,f.endA=s.state.selection.to)),E_&&$M<=11&&f.endB==f.start+1&&f.endA==f.start&&f.start>d.from&&d.doc.textBetween(f.start-d.from-1,f.start-d.from+1)=="  "&&(f.start--,f.endA--,f.endB--);let x=d.doc.resolveNoCache(f.start-d.from),y=d.doc.resolveNoCache(f.endB-d.from),v=u.resolve(f.start),b=x.sameParent(y)&&x.parent.inlineContent&&v.end()>=f.endA;if((YV&&s.input.lastIOSEnter>Date.now()-225&&(!b||a.some(L=>L.nodeName=="DIV"||L.nodeName=="P"))||!b&&x.posL(s,TD(13,"Enter")))){s.input.lastIOSEnter=0;return}if(s.state.selection.anchor>f.start&&Iqs(u,f.start,f.endA,x,y)&&s.someProp("handleKeyDown",L=>L(s,TD(8,"Backspace")))){gA&&av&&s.domObserver.suppressSelectionUpdates();return}av&&f.endB==f.start&&(s.input.lastChromeDelete=Date.now()),gA&&!b&&x.start()!=y.start()&&y.parentOffset==0&&x.depth==y.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==f.endA&&(f.endB-=2,y=d.doc.resolveNoCache(f.endB-d.from),setTimeout(()=>{s.someProp("handleKeyDown",function(L){return L(s,TD(13,"Enter"))})},20));let N=f.start,S=f.endA,A=L=>{let M=L||s.state.tr.replace(N,S,d.doc.slice(f.start-d.from,f.endB-d.from));if(d.sel){let I=Ogt(s,M.doc,d.sel);I&&!(av&&s.composing&&I.empty&&(f.start!=f.endB||s.input.lastChromeDeleteDA(s),20));let L=A(s.state.tr.delete(N,S)),M=u.resolve(f.start).marksAcross(u.resolve(f.endA));M&&L.ensureMarks(M),s.dispatch(L)}else if(f.endA==f.endB&&(T=Lqs(x.parent.content.cut(x.parentOffset,y.parentOffset),v.parent.content.cut(v.parentOffset,f.endA-v.start())))){let L=A(s.state.tr);T.type=="add"?L.addMark(N,S,T.mark):L.removeMark(N,S,T.mark),s.dispatch(L)}else if(x.parent.child(x.index()).isText&&x.index()==y.index()-(y.textOffset?0:1)){let L=x.parent.textBetween(x.parentOffset,y.parentOffset),M=()=>A(s.state.tr.insertText(L,N,S));s.someProp("handleTextInput",I=>I(s,N,S,L,M))||s.dispatch(M())}else s.dispatch(A());else s.dispatch(A())}function Ogt(s,t,n){return Math.max(n.anchor,n.head)>t.content.size?null:nJe(s,t.resolve(n.anchor),t.resolve(n.head))}function Lqs(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||uFe(l,!0,!1)0&&(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 Rqs(s,t,n,r,a){let i=s.findDiffStart(t,n);if(i==null)return null;let{a:l,b:o}=s.findDiffEnd(t,n+s.size,n+t.size);if(a=="end"){let c=Math.max(0,i-Math.min(l,o));r-=l+c-i}if(l=l?i-r:0;i-=c,i&&i=o?i-r:0;i-=c,i&&i=56320&&t<=57343&&n>=55296&&n<=56319}class z9t{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 XUs,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach($gt),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=Ugt(this),Bgt(this),this.nodeViews=qgt(this),this.docView=vgt(this.state.doc,zgt(this),dFe(this),this.dom,this),this.domObserver=new Nqs(this,(r,a,i,l)=>Pqs(this,r,a,i,l)),this.domObserver.start(),QUs(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&&C$e(this);let n=this._props;this._props=t,t.plugins&&(t.plugins.forEach($gt),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&&(P9t(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 p=qgt(this);Oqs(p,this.nodeViews)&&(this.nodeViews=p,i=!0)}(o||n.handleDOMEvents!=this._props.handleDOMEvents)&&C$e(this),this.editable=Ugt(this),Bgt(this);let c=dFe(this),d=zgt(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&&hUs(this);if(l){this.domObserver.stop();let p=h&&(E_||av)&&!this.composing&&!a.selection.empty&&!t.selection.empty&&Dqs(a.selection,t.selection);if(h){let f=av?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=hqs(this)),(i||!this.docView.update(t.doc,d,c,this))&&(this.docView.updateOuterDeco(d),this.docView.destroy(),this.docView=vgt(t.doc,d,c,this.dom,this)),f&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(p=!0)}p||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&DUs(this))?DA(this,p):(b9t(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&&mUs(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 nl){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&mgt(this,n.getBoundingClientRect(),t)}else mgt(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 vUs(this,t)}coordsAtPos(t,n=1){return h9t(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 NUs(this,n||this.state,t)}pasteHTML(t,n){return Nee(this,"",t,!1,n||new ClipboardEvent("paste"))}pasteText(t,n){return Nee(this,t,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(t){return rJe(this,t)}destroy(){this.docView&&(JUs(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],dFe(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,sUs())}get isDestroyed(){return this.docView==null}dispatchEvent(t){return tqs(this,t)}domSelectionRange(){let t=this.domSelection();return t?d1&&this.root.nodeType===11&&oUs(this.dom.ownerDocument)==this.dom&&Sqs(this,t)||t:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}z9t.prototype.dispatch=function(s){let t=this._props.dispatchTransaction;t?t.call(this,s):this.updateState(this.state.apply(s))};function zgt(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"),[sb.node(0,s.state.doc.content.size,t)]}function Bgt(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:sb.widget(s.state.selection.from,t,{raw:!0,marks:s.markCursor})}}else s.cursorWrapper=null}function Ugt(s){return!s.someProp("editable",t=>t(s.state)===!1)}function Dqs(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 qgt(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 Oqs(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 $gt(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 fP={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:"'"},qCe={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},Fqs=typeof navigator<"u"&&/Mac/.test(navigator.platform),zqs=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var Qy=0;Qy<10;Qy++)fP[48+Qy]=fP[96+Qy]=String(Qy);for(var Qy=1;Qy<=24;Qy++)fP[Qy+111]="F"+Qy;for(var Qy=65;Qy<=90;Qy++)fP[Qy]=String.fromCharCode(Qy+32),qCe[Qy]=String.fromCharCode(Qy);for(var hFe in fP)qCe.hasOwnProperty(hFe)||(qCe[hFe]=fP[hFe]);function Bqs(s){var t=Fqs&&s.metaKey&&s.shiftKey&&!s.ctrlKey&&!s.altKey||zqs&&s.shiftKey&&s.key&&s.key.length==1||s.key=="Unidentified",n=!t&&s.key||(s.shiftKey?qCe:fP)[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 Uqs=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),qqs=typeof navigator<"u"&&/Win/.test(navigator.platform);function $qs(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 B9t(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("backward",s):n.parentOffset>0)?null:n}const Wqs=(s,t,n)=>{let r=B9t(s,n);if(!r)return!1;let a=uJe(r);if(!a){let l=r.blockRange(),o=l&&MG(l);return o==null?!1:(t&&t(s.tr.lift(l,o).scrollIntoView()),!0)}let i=a.nodeBefore;if(V9t(s,a,t,-1))return!0;if(r.parent.content.size==0&&(ZV(i,"end")||nl.isSelectable(i)))for(let l=r.depth;;l--){let o=dPe(s.doc,r.before(l),r.after(l),Si.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},Kqs=(s,t,n)=>{let r=B9t(s,n);if(!r)return!1;let a=uJe(r);return a?U9t(s,a,t):!1},Yqs=(s,t,n)=>{let r=q9t(s,n);if(!r)return!1;let a=hJe(r);return a?U9t(s,a,t):!1};function U9t(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=dPe(s.doc,i,c,Si.empty);if(!d||d.from!=i||d instanceof hx&&d.slice.size>=c-i)return!1;if(n){let u=s.tr.step(d);u.setSelection(pl.create(u.doc,i)),n(u.scrollIntoView())}return!0}function ZV(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 Zqs=(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=uJe(r)}let l=i&&i.nodeBefore;return!l||!nl.isSelectable(l)?!1:(t&&t(s.tr.setSelection(nl.create(s.doc,i.pos-l.nodeSize)).scrollIntoView()),!0)};function uJe(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 q9t(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("forward",s):n.parentOffset{let r=q9t(s,n);if(!r)return!1;let a=hJe(r);if(!a)return!1;let i=a.nodeAfter;if(V9t(s,a,t,1))return!0;if(r.parent.content.size==0&&(ZV(i,"start")||nl.isSelectable(i))){let l=dPe(s.doc,r.before(),r.after(),Si.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 nl,a;if(r){if(n.node.isTextblock||!VP(s.doc,n.from))return!1;a=n.from}else if(a=cPe(s.doc,n.from,-1),a==null)return!1;if(t){let i=s.tr.join(a);r&&i.setSelection(nl.create(i.doc,a-s.doc.resolve(a).nodeBefore.nodeSize)),t(i.scrollIntoView())}return!0},e$s=(s,t)=>{let n=s.selection,r;if(n instanceof nl){if(n.node.isTextblock||!VP(s.doc,n.to))return!1;r=n.to}else if(r=cPe(s.doc,n.to,1),r==null)return!1;return t&&t(s.tr.join(r).scrollIntoView()),!0},t$s=(s,t)=>{let{$from:n,$to:r}=s.selection,a=n.blockRange(r),i=a&&MG(a);return i==null?!1:(t&&t(s.tr.lift(a,i).scrollIntoView()),!0)},s$s=(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 $9t(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=$9t(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(Ol.near(c.doc.resolve(o),1)),t(c.scrollIntoView())}return!0},r$s=(s,t)=>{let n=s.selection,{$from:r,$to:a}=n;if(n instanceof rN||r.parent.inlineContent||a.parent.inlineContent)return!1;let i=$9t(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(Fq(s.doc,i))return t&&t(s.tr.split(i).scrollIntoView()),!0}let r=n.blockRange(),a=r&&MG(r);return a==null?!1:(t&&t(s.tr.lift(r,a).scrollIntoView()),!0)},i$s=(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(nl.create(s.doc,a))),!0)};function o$s(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||VP(s.doc,t.pos))?!1:(n&&n(s.tr.join(t.pos).scrollIntoView()),!0)}function V9t(s,t,n,r){let a=t.nodeBefore,i=t.nodeAfter,l,o,c=a.type.spec.isolating||i.type.spec.isolating;if(!c&&o$s(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 p=t.pos+i.nodeSize,f=Ba.empty;for(let v=l.length-1;v>=0;v--)f=Ba.from(l[v].create(null,f));f=Ba.from(a.copy(f));let x=s.tr.step(new uy(t.pos-1,p,t.pos,p,new Si(f,1,0),l.length,!0)),y=x.doc.resolve(p+2*l.length);y.nodeAfter&&y.nodeAfter.type==a.type&&VP(x.doc,y.pos)&&x.join(y.pos),n(x.scrollIntoView())}return!0}let u=i.type.spec.isolating||r>0&&c?null:Ol.findFrom(t,1),h=u&&u.$from.blockRange(u.$to),m=h&&MG(h);if(m!=null&&m>=t.depth)return n&&n(s.tr.lift(h,m).scrollIntoView()),!0;if(d&&ZV(i,"start",!0)&&ZV(a,"end")){let p=a,f=[];for(;f.push(p),!p.isTextblock;)p=p.lastChild;let x=i,y=1;for(;!x.isTextblock;x=x.firstChild)y++;if(p.canReplace(p.childCount,p.childCount,x.content)){if(n){let v=Ba.empty;for(let N=f.length-1;N>=0;N--)v=Ba.from(f[N].copy(v));let b=s.tr.step(new uy(t.pos-f.length,t.pos+i.nodeSize,t.pos+y,t.pos+i.nodeSize-y,new Si(v,f.length,0),0,!0));n(b.scrollIntoView())}return!0}}return!1}function H9t(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(pl.create(t.doc,s<0?a.start(i):a.end(i)))),!0):!1}}const l$s=H9t(-1),c$s=H9t(1);function d$s(s,t=null){return function(n,r){let{$from:a,$to:i}=n.selection,l=a.blockRange(i),o=l&&QQe(l,s,t);return o?(r&&r(n.tr.wrap(l,o).scrollIntoView()),!0):!1}}function Vgt(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 RCe(c,c,t.depth),t.endIndex=0;u--)i=Ba.from(n[u].type.create(n[u].attrs,i));s.step(new uy(t.start-(r?2:0),t.end,t.start,t.end,new Si(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?f$s(t,n,s,i):g$s(t,n,i):!0:!1}}function f$s(s,t,n,r){let a=s.tr,i=r.end,l=r.$to.end(r.depth);ix;f--)p-=a.child(f).nodeSize,r.delete(p-1,p+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?Ba.empty:Ba.from(a))))return!1;let h=i.pos,m=h+l.nodeSize;return r.step(new uy(h-(o?1:0),m+(c?1:0),h+1,m-1,new Si((o?Ba.empty:Ba.from(a.copy(Ba.empty))).append(c?Ba.empty:Ba.from(a.copy(Ba.empty))),o?0:1,c?0:1),o?0:1)),t(r.scrollIntoView()),!0}function x$s(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=Ba.from(d?s.create():null),h=new Si(Ba.from(s.create(null,Ba.from(o.type.create(null,u)))),d?3:1,0),m=i.start,p=i.end;n(t.tr.step(new uy(m-(d?3:1),p,m,p,h,1,!0)).scrollIntoView())}return!0}}function fPe(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 gPe=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,p])=>[m,(...x)=>{const y=this.buildProps(d,n),v=p(...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:fPe({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}},y$s=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 xo(s,t,n){return s.config[t]===void 0&&s.parent?xo(s.parent,t,n):typeof s.config[t]=="function"?s.config[t].bind({...n,parent:s.parent?xo(s.parent,t,n):null}):s.config[t]}function xPe(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 G9t(s){const t=[],{nodeExtensions:n,markExtensions:r}=xPe(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=xo(l,"addGlobalAttributes",o);if(!c)return;c().forEach(u=>{u.types.forEach(h=>{Object.entries(u.attributes).forEach(([m,p])=>{t.push({type:h,name:m,attribute:{...i,...p}})})})})}),a.forEach(l=>{const o={name:l.name,options:l.options,storage:l.storage},c=xo(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 py(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 Dm(...s){return s.filter(t=>!!t).reduce((t,n)=>{const r={...t};return Object.entries(n).forEach(([a,i])=>{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(p=>p.trim());d.set(h,m)}),o.forEach(u=>{const[h,m]=u.split(":").map(p=>p.trim());d.set(h,m)}),r[a]=Array.from(d.entries()).map(([u,h])=>`${u}: ${h}`).join("; ")}else r[a]=i}),r},{})}function A$e(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)=>Dm(n,r),{})}function W9t(s){return typeof s=="function"}function Lc(s,t=void 0,...n){return W9t(s)?t?s.bind(t)(...n):s(...n):s}function v$s(s={}){return Object.keys(s).length===0&&s.constructor===Object}function b$s(s){return typeof s!="string"?s:s.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(s):s==="true"?!0:s==="false"?!1:s}function Hgt(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):b$s(n.getAttribute(l.name));return o==null?i:{...i,[l.name]:o}},{});return{...r,...a}}}}function Ggt(s){return Object.fromEntries(Object.entries(s).filter(([t,n])=>t==="attrs"&&v$s(n)?!1:n!=null))}function _$s(s,t){var n;const r=G9t(s),{nodeExtensions:a,markExtensions:i}=xPe(s),l=(n=a.find(d=>xo(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 N=xo(b,"extendNodeSchema",h);return{...v,...N?N(d):{}}},{}),p=Ggt({...m,content:Lc(xo(d,"content",h)),marks:Lc(xo(d,"marks",h)),group:Lc(xo(d,"group",h)),inline:Lc(xo(d,"inline",h)),atom:Lc(xo(d,"atom",h)),selectable:Lc(xo(d,"selectable",h)),draggable:Lc(xo(d,"draggable",h)),code:Lc(xo(d,"code",h)),whitespace:Lc(xo(d,"whitespace",h)),linebreakReplacement:Lc(xo(d,"linebreakReplacement",h)),defining:Lc(xo(d,"defining",h)),isolating:Lc(xo(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}]}))}),f=Lc(xo(d,"parseHTML",h));f&&(p.parseDOM=f.map(v=>Hgt(v,u)));const x=xo(d,"renderHTML",h);x&&(p.toDOM=v=>x({node:v,HTMLAttributes:A$e(v,u)}));const y=xo(d,"renderText",h);return y&&(p.toText=y),[d.name,p]})),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=xo(v,"extendMarkSchema",h);return{...y,...b?b(d):{}}},{}),p=Ggt({...m,inclusive:Lc(xo(d,"inclusive",h)),excludes:Lc(xo(d,"excludes",h)),group:Lc(xo(d,"group",h)),spanning:Lc(xo(d,"spanning",h)),code:Lc(xo(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}]}))}),f=Lc(xo(d,"parseHTML",h));f&&(p.parseDOM=f.map(y=>Hgt(y,u)));const x=xo(d,"renderHTML",h);return x&&(p.toDOM=y=>x({mark:y,HTMLAttributes:A$e(y,u)})),[d.name,p]}));return new B7t({topNode:l,nodes:o,marks:c})}function pFe(s,t){return t.nodes[s]||t.marks[s]||null}function Wgt(s,t){return Array.isArray(t)?t.some(n=>(typeof n=="string"?n:n.name)===s.name):t}function mJe(s,t){const n=x9.fromSchema(t).serializeFragment(s),a=document.implementation.createHTMLDocument().createElement("div");return a.appendChild(n),a.innerHTML}const w$s=(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 pJe(s){return Object.prototype.toString.call(s)==="[object RegExp]"}class yPe{constructor(t){this.find=t.find,this.handler=t.handler}}const j$s=(s,t)=>{if(pJe(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 qoe(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=w$s(d)+i;return l.forEach(m=>{if(u)return;const p=j$s(h,m.find);if(!p)return;const f=c.state.tr,x=fPe({state:c.state,transaction:f}),y={from:r-(p[0].length-i.length),to:a},{commands:v,chain:b,can:N}=new gPe({editor:n,state:x});m.handler({state:x,range:y,match:p,commands:v,chain:b,can:N})===null||!f.steps.length||(f.setMeta(o,{transform:f,from:r,to:a,text:i}),c.dispatch(f),u=!0)}),u}function N$s(s){const{editor:t,rules:n}=s,r=new b0({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=mJe(Ba.from(u),l.schema);const{from:h}=c,m=h+u.length;qoe({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 qoe({editor:t,from:i,to:l,text:o,rules:n,plugin:r})},handleDOMEvents:{compositionend:a=>(setTimeout(()=>{const{$cursor:i}=a.state.selection;i&&qoe({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?qoe({editor:t,from:l.pos,to:l.pos,text:` `,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function k$s(s){return Object.prototype.toString.call(s).slice(8,-1)}function $oe(s){return k$s(s)!=="Object"?!1:s.constructor===Object&&Object.getPrototypeOf(s)===Object.prototype}function vPe(s,t){const n={...s};return $oe(s)&&$oe(t)&&Object.keys(t).forEach(r=>{$oe(t[r])&&$oe(s[r])?n[r]=vPe(s[r],t[r]):n[r]=t[r]}),n}class gS{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=Lc(xo(this,"addOptions",{name:this.name}))),this.storage=Lc(xo(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new gS(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>vPe(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new gS(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=Lc(xo(n,"addOptions",{name:n.name})),n.storage=Lc(xo(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 S$s(s){return typeof s=="number"}class K9t{constructor(t){this.find=t.find,this.handler=t.handler}}const C$s=(s,t,n)=>{if(pJe(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 A$s(s){const{editor:t,state:n,from:r,to:a,rule:i,pasteEvent:l,dropEvent:o}=s,{commands:c,chain:d,can:u}=new gPe({editor:t,state:n}),h=[];return n.doc.nodesBetween(r,a,(p,f)=>{if(!p.isTextblock||p.type.spec.code)return;const x=Math.max(r,f),y=Math.min(a,f+p.content.size),v=p.textBetween(x-f,y-f,void 0,"");C$s(v,i.find,l).forEach(N=>{if(N.index===void 0)return;const S=x+N.index+1,A=S+N[0].length,T={from:n.tr.mapping.map(S),to:n.tr.mapping.map(A)},L=i.handler({state:n,range:T,match:N,commands:c,chain:d,can:u,pasteEvent:l,dropEvent:o});h.push(L)})}),h.every(p=>p!==null)}let Voe=null;const E$s=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 T$s(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:p,pasteEvt:f})=>{const x=u.tr,y=fPe({state:u,transaction:x});if(!(!A$s({editor:t,state:y,from:Math.max(h-1,0),to:m.b-1,rule:p,pasteEvent:f,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 b0({view(h){const m=f=>{var x;r=!((x=h.dom.parentElement)===null||x===void 0)&&x.contains(f.target)?h.dom.parentElement:null,r&&(Voe=t)},p=()=>{Voe&&(Voe=null)};return window.addEventListener("dragstart",m),window.addEventListener("dragend",p),{destroy(){window.removeEventListener("dragstart",m),window.removeEventListener("dragend",p)}}},props:{handleDOMEvents:{drop:(h,m)=>{if(i=r===h.dom.parentElement,o=m,!i){const p=Voe;p!=null&&p.isEditable&&setTimeout(()=>{const f=p.state.selection;f&&p.commands.deleteRange({from:f.from,to:f.to})},10)}return!1},paste:(h,m)=>{var p;const f=(p=m.clipboardData)===null||p===void 0?void 0:p.getData("text/html");return l=m,a=!!(f!=null&&f.includes("data-pm-slice")),!1}}},appendTransaction:(h,m,p)=>{const f=h[0],x=f.getMeta("uiEvent")==="paste"&&!a,y=f.getMeta("uiEvent")==="drop"&&!i,v=f.getMeta("applyPasteRules"),b=!!v;if(!x&&!y&&!b)return;if(b){let{text:A}=v;typeof A=="string"?A=A:A=mJe(Ba.from(A),p.schema);const{from:T}=v,L=T+A.length,M=E$s(A);return c({rule:u,state:p,from:T,to:{b:L},pasteEvt:M})}const N=m.doc.content.findDiffStart(p.doc.content),S=m.doc.content.findDiffEnd(p.doc.content);if(!(!S$s(N)||!S||N===S.b))return c({rule:u,state:p,from:N,to:S,pasteEvt:l})}}))}function M$s(s){const t=s.filter((n,r)=>s.indexOf(n)!==r);return Array.from(new Set(t))}class wU{constructor(t,n){this.splittableMarks=[],this.editor=n,this.extensions=wU.resolve(t),this.schema=_$s(this.extensions,n),this.setupExtensions()}static resolve(t){const n=wU.sort(wU.flatten(t)),r=M$s(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=xo(n,"addExtensions",r);return a?[n,...this.flatten(a())]:n}).flat(10)}static sort(t){return t.sort((r,a)=>{const i=xo(r,"priority")||100,l=xo(a,"priority")||100;return i>l?-1:i{const r={name:n.name,options:n.options,storage:n.storage,editor:this.editor,type:pFe(n.name,this.schema)},a=xo(n,"addCommands",r);return a?{...t,...a()}:t},{})}get plugins(){const{editor:t}=this,n=wU.sort([...this.extensions].reverse()),r=[],a=[],i=n.map(l=>{const o={name:l.name,options:l.options,storage:l.storage,editor:t,type:pFe(l.name,this.schema)},c=[],d=xo(l,"addKeyboardShortcuts",o);let u={};if(l.type==="mark"&&xo(l,"exitable",o)&&(u.ArrowRight=()=>gS.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=Hqs(u);c.push(h);const m=xo(l,"addInputRules",o);Wgt(l,t.options.enableInputRules)&&m&&r.push(...m());const p=xo(l,"addPasteRules",o);Wgt(l,t.options.enablePasteRules)&&p&&a.push(...p());const f=xo(l,"addProseMirrorPlugins",o);if(f){const x=f();c.push(...x)}return c}).flat();return[N$s({editor:t,rules:r}),...T$s({editor:t,rules:a}),...i]}get attributes(){return G9t(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:n}=xPe(this.extensions);return Object.fromEntries(n.filter(r=>!!xo(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:py(r.name,this.schema)},l=xo(r,"addNodeView",i);if(!l)return[];const o=(c,d,u,h,m)=>{const p=A$e(c,a);return l()({node:c,view:d,getPos:u,decorations:h,innerDecorations:m,editor:t,extension:r,HTMLAttributes:p})};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:pFe(t.name,this.schema)};t.type==="mark"&&(!((n=Lc(xo(t,"keepOnSplit",r)))!==null&&n!==void 0)||n)&&this.splittableMarks.push(t.name);const a=xo(t,"onBeforeCreate",r),i=xo(t,"onCreate",r),l=xo(t,"onUpdate",r),o=xo(t,"onSelectionUpdate",r),c=xo(t,"onTransaction",r),d=xo(t,"onFocus",r),u=xo(t,"onBlur",r),h=xo(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 wv{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=Lc(xo(this,"addOptions",{name:this.name}))),this.storage=Lc(xo(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new wv(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>vPe(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new wv({...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=Lc(xo(n,"addOptions",{name:n.name})),n.storage=Lc(xo(n,"addStorage",{name:n.name,options:n.options})),n}}function Y9t(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 p=l==null?void 0:l[c.type.name];if(p)return u&&(o+=p({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 Z9t(s){return Object.fromEntries(Object.entries(s.nodes).filter(([,t])=>t.spec.toText).map(([t,n])=>[t,n.spec.toText]))}const P$s=wv.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new b0({key:new f1("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=Z9t(n);return Y9t(r,{from:l,to:o},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),L$s=()=>({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),I$s=(s=!1)=>({commands:t})=>t.setContent("",s),R$s=()=>({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)),p=h.blockRange(m);if(!p)return;const f=MG(p);if(o.type.isTextblock){const{defaultType:x}=h.parent.contentMatchAt(h.index());t.setNodeMarkup(p.start,x)}(f||f===0)&&t.lift(p,f)})}),!0},D$s=s=>t=>s(t),O$s=()=>({state:s,dispatch:t})=>r$s(s,t),F$s=(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 pl(r.doc.resolve(Math.max(l-1,0)))),!0},z$s=()=>({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},B$s=s=>({tr:t,state:n,dispatch:r})=>{const a=py(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},U$s=s=>({tr:t,dispatch:n})=>{const{from:r,to:a}=s;return n&&t.delete(r,a),!0},q$s=()=>({state:s,dispatch:t})=>Gqs(s,t),$$s=()=>({commands:s})=>s.keyboardShortcut("Enter"),V$s=()=>({state:s,dispatch:t})=>n$s(s,t);function $Ce(s,t,n={strict:!0}){const r=Object.keys(t);return r.length?r.every(a=>n.strict?t[a]===s[a]:pJe(t[a])?t[a].test(s[a]):t[a]===s[a]):!0}function X9t(s,t,n={}){return s.find(r=>r.type===t&&$Ce(Object.fromEntries(Object.keys(n).map(a=>[a,r.attrs[a]])),n))}function Kgt(s,t,n={}){return!!X9t(s,t,n)}function fJe(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),!X9t([...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&&Kgt([...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=GP(s,r.schema),{doc:l,selection:o}=n,{$from:c,from:d,to:u}=o;if(a){const h=fJe(c,i,t);if(h&&h.from<=d&&h.to>=u){const m=pl.create(l,h.from,h.to);n.setSelection(m)}}return!0},G$s=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=()=>{(VCe()||Ygt())&&r.dom.focus(),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),W$s()&&!VCe()&&!Ygt()&&r.dom.focus({preventScroll:!0}))})};if(r.hasFocus()&&s===null||s===!1)return!0;if(i&&s===null&&!Q9t(n.state.selection))return l(),!0;const o=J9t(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},Y$s=(s,t)=>n=>s.every((r,a)=>t(r,{...n,index:a})),Z$s=(s,t)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},s,t),ezt=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&&ezt(r)}return s};function Hoe(s){const t=`${s}`,n=new window.DOMParser().parseFromString(t,"text/html").body;return ezt(n)}function See(s,t,n){if(s instanceof qM||s instanceof Ba)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 Ba.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),See("",t,n)}if(a){if(n.errorOnInvalidContent){let l=!1,o="";const c=new B7t({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?RQ.fromSchema(c).parseSlice(Hoe(s),n.parseOptions):RQ.fromSchema(c).parse(Hoe(s),n.parseOptions),n.errorOnInvalidContent&&l)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${o}`)})}const i=RQ.fromSchema(t);return n.slice?i.parseSlice(Hoe(s),n.parseOptions).content:i.parse(Hoe(s),n.parseOptions)}return See("",t,n)}function X$s(s,t,n){const r=s.steps.length-1;if(r{l===0&&(l=u)}),s.setSelection(Ol.near(s.doc.resolve(l),n))}const Q$s=s=>!("type"in s),J$s=(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{See(t,i.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(y){c(y)}try{o=See(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,p=!0;if((Q$s(o)?o:[o]).forEach(y=>{y.check(),m=m?y.isText&&y.marks.length===0:!1,p=p?y.isBlock:!1}),u===h&&p){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 Ba){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&&X$s(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},eVs=()=>({state:s,dispatch:t})=>Jqs(s,t),tVs=()=>({state:s,dispatch:t})=>e$s(s,t),sVs=()=>({state:s,dispatch:t})=>Wqs(s,t),nVs=()=>({state:s,dispatch:t})=>Xqs(s,t),rVs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=cPe(s.doc,s.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},aVs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=cPe(s.doc,s.selection.$from.pos,1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},iVs=()=>({state:s,dispatch:t})=>Kqs(s,t),oVs=()=>({state:s,dispatch:t})=>Yqs(s,t);function tzt(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function lVs(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=lVs(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 Cee(s,t,n={}){const{from:r,to:a,empty:i}=s.selection,l=t?py(t,s.schema):null,o=[];s.doc.nodesBetween(r,a,(h,m)=>{if(h.isText)return;const p=Math.max(r,m),f=Math.min(a,m+h.nodeSize);o.push({node:h,from:p,to:f})});const c=a-r,d=o.filter(h=>l?l.name===h.node.type.name:!0).filter(h=>$Ce(h.node.attrs,n,{strict:!1}));return i?!!d.length:d.reduce((h,m)=>h+m.to-m.from,0)>=c}const dVs=(s,t={})=>({state:n,dispatch:r})=>{const a=py(s,n.schema);return Cee(n,a,t)?t$s(n,r):!1},uVs=()=>({state:s,dispatch:t})=>a$s(s,t),hVs=s=>({state:t,dispatch:n})=>{const r=py(s,t.schema);return p$s(r)(t,n)},mVs=()=>({state:s,dispatch:t})=>s$s(s,t);function bPe(s,t){return t.nodes[s]?"node":t.marks[s]?"mark":null}function Zgt(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 pVs=(s,t)=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=bPe(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=py(s,r.schema)),o==="mark"&&(l=GP(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,Zgt(d.attrs,t)),l&&d.marks.length&&d.marks.forEach(h=>{l===h.type&&n.addMark(u,u+d.nodeSize,l.create(Zgt(h.attrs,t)))})})}),!0):!1},fVs=()=>({tr:s,dispatch:t})=>(t&&s.scrollIntoView(),!0),gVs=()=>({tr:s,dispatch:t})=>{if(t){const n=new rN(s.doc);s.setSelection(n)}return!0},xVs=()=>({state:s,dispatch:t})=>Zqs(s,t),yVs=()=>({state:s,dispatch:t})=>Qqs(s,t),vVs=()=>({state:s,dispatch:t})=>i$s(s,t),bVs=()=>({state:s,dispatch:t})=>c$s(s,t),_Vs=()=>({state:s,dispatch:t})=>l$s(s,t);function E$e(s,t,n={},r={}){return See(s,t,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}const wVs=(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=E$e(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 szt(s,t){const n=GP(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 jVs(s,t){const n=new JQe(s);return t.forEach(r=>{r.steps.forEach(a=>{n.step(a)})}),n}function NVs(s){for(let t=0;t{n(a)&&r.push({node:a,pos:i})}),r}function nzt(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 gJe(s){return t=>nzt(t.$from,s)}function SVs(s,t){const n={from:0,to:s.content.size};return Y9t(s,n,t)}function CVs(s,t){const n=py(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 rzt(s,t){const n=bPe(typeof t=="string"?t:t.name,s.schema);return n==="node"?CVs(s,t):n==="mark"?szt(s,t):{}}function AVs(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 EVs(s){const t=AVs(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 TVs(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}})})}),EVs(r)}function xJe(s,t,n){const r=[];return s===t?n.resolve(s).marks().forEach(a=>{const i=n.resolve(s),l=fJe(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 q5e(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 T$e(s,t,n={}){const{empty:r,ranges:a}=s.selection,i=t?GP(t,s.schema):null;if(r)return!!(s.storedMarks||s.selection.$from.marks()).filter(h=>i?i.name===h.type.name:!0).find(h=>$Ce(h.attrs,n,{strict:!1}));let l=0;const o=[];if(a.forEach(({$from:h,$to:m})=>{const p=h.pos,f=m.pos;s.doc.nodesBetween(p,f,(x,y)=>{if(!x.isText&&!x.marks.length)return;const v=Math.max(p,y),b=Math.min(f,y+x.nodeSize),N=b-v;l+=N,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=>$Ce(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 MVs(s,t,n={}){if(!t)return Cee(s,null,n)||T$e(s,null,n);const r=bPe(t,s.schema);return r==="node"?Cee(s,t,n):r==="mark"?T$e(s,t,n):!1}function Xgt(s,t){const{nodeExtensions:n}=xPe(t),r=n.find(l=>l.name===s);if(!r)return!1;const a={name:r.name,options:r.options,storage:r.storage},i=Lc(xo(r,"group",a));return typeof i!="string"?!1:i.split(" ").includes("list")}function yJe(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&&(yJe(i,{ignoreWhitespace:n,checkChildren:t})||(a=!1))}),a}return!1}function PVs(s){return s instanceof nl}function LVs(s,t,n){var r;const{selection:a}=t;let i=null;if(Q9t(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 p=!m||m.type.allowsMarkType(n),f=!!n.isInSet(u.marks)||!u.marks.some(x=>x.type.excludes(n));d=p&&f}return!d}),d})}const IVs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{const{selection:i}=n,{empty:l,ranges:o}=i,c=GP(s,r.schema);if(a)if(l){const d=szt(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,p)=>{const f=Math.max(p,u),x=Math.min(p+m.nodeSize,h);m.marks.find(v=>v.type===c)?m.marks.forEach(v=>{c===v.type&&n.addMark(f,x,c.create({...v.attrs,...t}))}):n.addMark(f,x,c.create(t))})});return LVs(r,n,c)},RVs=(s,t)=>({tr:n})=>(n.setMeta(s,t),!0),DVs=(s,t={})=>({state:n,dispatch:r,chain:a})=>{const i=py(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})=>Vgt(i,{...l,...t})(n)?!0:o.clearNodes()).command(({state:o})=>Vgt(i,{...l,...t})(o,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},OVs=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,a=YD(s,0,r.content.size),i=nl.create(r,a);t.setSelection(i)}return!0},FVs=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,{from:a,to:i}=typeof s=="number"?{from:s,to:s}:s,l=pl.atStart(r).from,o=pl.atEnd(r).to,c=YD(a,l,o),d=YD(i,l,o),u=pl.create(r,c,d);t.setSelection(u)}return!0},zVs=s=>({state:t,dispatch:n})=>{const r=py(s,t.schema);return x$s(r)(t,n)};function Qgt(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 BVs=({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=q5e(d,o.node().type.name,o.node().attrs);if(i instanceof nl&&i.node.isBlock)return!o.parentOffset||!Fq(l,o.pos)?!1:(r&&(s&&Qgt(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:NVs(o.node(-1).contentMatchAt(o.indexAfter(-1)));let p=h&&m?[{type:m,attrs:u}]:void 0,f=Fq(t.doc,t.mapping.map(o.pos),1,p);if(!p&&!f&&Fq(t.doc,t.mapping.map(o.pos),1,m?[{type:m}]:void 0)&&(f=!0,p=m?[{type:m,attrs:u}]:void 0),r){if(f&&(i instanceof pl&&t.deleteSelection(),t.split(t.mapping.map(o.pos),1,p),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&&Qgt(n,a.extensionManager.splittableMarks),t.scrollIntoView()}return f},UVs=(s,t={})=>({tr:n,state:r,dispatch:a,editor:i})=>{var l;const o=py(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=Ba.empty;const b=c.index(-1)?1:c.index(-2)?2:3;for(let M=c.depth-b;M>=c.depth-3;M-=1)v=Ba.from(c.node(M).copy(v));const N=c.indexAfter(-1){if(L>-1)return!1;M.isTextblock&&M.content.size===0&&(L=I+1)}),L>-1&&n.setSelection(pl.near(n.doc.resolve(L))),n.scrollIntoView()}return!0}const p=d.pos===c.end()?h.contentMatchAt(0).defaultType:null,f={...q5e(m,h.type.name,h.attrs),...t},x={...q5e(m,c.node().type.name,c.node().attrs),...t};n.delete(c.pos,d.pos);const y=p?[{type:o,attrs:f},{type:p,attrs:x}]:[{type:o,attrs:f}];if(!Fq(n.doc,c.pos,2))return!1;if(a){const{selection:v,storedMarks:b}=r,{splittableMarks:N}=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(T=>N.includes(T.type.name));n.ensureMarks(A)}return!0},fFe=(s,t)=>{const n=gJe(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)&&VP(s.doc,n.pos)&&s.join(n.pos),!0},gFe=(s,t)=>{const n=gJe(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)&&VP(s.doc,r)&&s.join(r),!0},qVs=(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,p=py(s,l.schema),f=py(t,l.schema),{selection:x,storedMarks:y}=l,{$from:v,$to:b}=x,N=v.blockRange(b),S=y||x.$to.parentOffset&&x.$from.marks();if(!N)return!1;const A=gJe(T=>Xgt(T.type.name,h))(x);if(N.depth>=1&&A&&N.depth-A.depth<=1){if(A.node.type===p)return d.liftListItem(f);if(Xgt(A.node.type.name,h)&&p.validContent(A.node.content)&&o)return c().command(()=>(i.setNodeMarkup(A.pos,p),!0)).command(()=>fFe(i,p)).command(()=>gFe(i,p)).run()}return!n||!S||!o?c().command(()=>u().wrapInList(p,r)?!0:d.clearNodes()).wrapInList(p,r).command(()=>fFe(i,p)).command(()=>gFe(i,p)).run():c().command(()=>{const T=u().wrapInList(p,r),L=S.filter(M=>m.includes(M.type.name));return i.ensureMarks(L),T?!0:d.clearNodes()}).wrapInList(p,r).command(()=>fFe(i,p)).command(()=>gFe(i,p)).run()},$Vs=(s,t={},n={})=>({state:r,commands:a})=>{const{extendEmptyMarkRange:i=!1}=n,l=GP(s,r.schema);return T$e(r,l,t)?a.unsetMark(l,{extendEmptyMarkRange:i}):a.setMark(l,t)},VVs=(s,t,n={})=>({state:r,commands:a})=>{const i=py(s,r.schema),l=py(t,r.schema),o=Cee(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})},HVs=(s,t={})=>({state:n,commands:r})=>{const a=py(s,n.schema);return Cee(n,a,t)?r.lift(a):r.wrapIn(a,t)},GVs=()=>({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},WVs=()=>({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},KVs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{var i;const{extendEmptyMarkRange:l=!1}=t,{selection:o}=n,c=GP(s,r.schema),{$from:d,empty:u,ranges:h}=o;if(!a)return!0;if(u&&l){let{from:m,to:p}=o;const f=(i=d.marks().find(y=>y.type===c))===null||i===void 0?void 0:i.attrs,x=fJe(d,c,f);x&&(m=x.from,p=x.to),n.removeMark(m,p,c)}else h.forEach(m=>{n.removeMark(m.$from.pos,m.$to.pos,c)});return n.removeStoredMark(c),!0},YVs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=bPe(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=py(s,r.schema)),o==="mark"&&(l=GP(s,r.schema)),a&&n.selection.ranges.forEach(c=>{const d=c.$from.pos,u=c.$to.pos;let h,m,p,f;n.selection.empty?r.doc.nodesBetween(d,u,(x,y)=>{i&&i===x.type&&(p=Math.max(y,d),f=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),N=Math.min(y+x.nodeSize,u);n.addMark(b,N,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(p,f,l.create({...x.attrs,...t}))}))}),!0):!1},ZVs=(s,t={})=>({state:n,dispatch:r})=>{const a=py(s,n.schema);return d$s(a,t)(n,r)},XVs=(s,t={})=>({state:n,dispatch:r})=>{const a=py(s,n.schema);return u$s(a,t)(n,r)};var QVs=Object.freeze({__proto__:null,blur:L$s,clearContent:I$s,clearNodes:R$s,command:D$s,createParagraphNear:O$s,cut:F$s,deleteCurrentNode:z$s,deleteNode:B$s,deleteRange:U$s,deleteSelection:q$s,enter:$$s,exitCode:V$s,extendMarkRange:H$s,first:G$s,focus:K$s,forEach:Y$s,insertContent:Z$s,insertContentAt:J$s,joinBackward:sVs,joinDown:tVs,joinForward:nVs,joinItemBackward:rVs,joinItemForward:aVs,joinTextblockBackward:iVs,joinTextblockForward:oVs,joinUp:eVs,keyboardShortcut:cVs,lift:dVs,liftEmptyBlock:uVs,liftListItem:hVs,newlineInCode:mVs,resetAttributes:pVs,scrollIntoView:fVs,selectAll:gVs,selectNodeBackward:xVs,selectNodeForward:yVs,selectParentNode:vVs,selectTextblockEnd:bVs,selectTextblockStart:_Vs,setContent:wVs,setMark:IVs,setMeta:RVs,setNode:DVs,setNodeSelection:OVs,setTextSelection:FVs,sinkListItem:zVs,splitBlock:BVs,splitListItem:UVs,toggleList:qVs,toggleMark:$Vs,toggleNode:VVs,toggleWrap:HVs,undoInputRule:GVs,unsetAllMarks:WVs,unsetMark:KVs,updateAttributes:YVs,wrapIn:ZVs,wrapInList:XVs});const JVs=wv.create({name:"commands",addCommands(){return{...QVs}}}),eHs=wv.create({name:"drop",addProseMirrorPlugins(){return[new b0({key:new f1("tiptapDrop"),props:{handleDrop:(s,t,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:t,slice:n,moved:r})}}})]}}),tHs=wv.create({name:"editable",addProseMirrorPlugins(){return[new b0({key:new f1("editable"),props:{editable:()=>this.editor.options.editable}})]}}),sHs=new f1("focusEvents"),nHs=wv.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:s}=this;return[new b0({key:sHs,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}}}})]}}),rHs=wv.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:p}=h,f=h.parent.isTextblock&&m>0?o.doc.resolve(m-1):h,x=f.parent.type.spec.isolating,y=h.pos-h.parentOffset,v=x&&f.parent.childCount===1?y===h.pos:Ol.atStart(d).from===m;return!u||!p.type.isTextblock||p.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 VCe()||tzt()?i:a},addProseMirrorPlugins(){return[new b0({key:new f1("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=Ol.atStart(t.doc).from,d=Ol.atEnd(t.doc).to;if(i||!(l===c&&o===d)||!yJe(n.doc))return;const m=n.tr,p=fPe({state:n,transaction:m}),{commands:f}=new gPe({editor:this.editor,state:p});if(f.clearNodes(),!!m.steps.length)return m}})]}}),aHs=wv.create({name:"paste",addProseMirrorPlugins(){return[new b0({key:new f1("tiptapPaste"),props:{handlePaste:(s,t,n)=>{this.editor.emit("paste",{editor:this.editor,event:t,slice:n})}}})]}}),iHs=wv.create({name:"tabindex",addProseMirrorPlugins(){return[new b0({key:new f1("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}});class MD{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 MD(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 MD(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 MD(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 MD(o,this.editor,a,a?n:null);a&&(c.actualDepth=this.depth+1),t.push(new MD(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 oHs=`.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 lHs(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 cHs extends y$s{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=lHs(oHs,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=W9t(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?[tHs,P$s.configure({blockSeparator:(n=(t=this.options.coreExtensionOptions)===null||t===void 0?void 0:t.clipboardTextSerializer)===null||n===void 0?void 0:n.blockSeparator}),JVs,nHs,rHs,iHs,eHs,aHs].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 wU(a,this)}createCommandManager(){this.commandManager=new gPe({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createView(){var t;let n;try{n=E$e(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=E$e(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}const r=J9t(n,this.options.autofocus);this.view=new z9t(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:_U.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 rzt(this.state,t)}isActive(t,n){const r=typeof t=="string"?t:null,a=typeof t=="string"?n:t;return MVs(this.state,r,a)}getJSON(){return this.state.doc.toJSON()}getHTML(){return mJe(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:n=` `,textSerializers:r={}}=t||{};return SVs(this.state.doc,{blockSeparator:n,textSerializers:{...Z9t(this.schema),...r}})}get isEmpty(){return yJe(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 MD(n,this)}get $doc(){return this.$pos(0)}}function XV(s){return new yPe({find:s.find,handler:({state:t,range:n,match:r})=>{const a=Lc(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(xJe(n.from,n.to,t.doc).filter(p=>p.mark.type.excluded.find(x=>x===s.type&&x!==p.mark.type)).filter(p=>p.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 azt(s){return new yPe({find:s.find,handler:({state:t,range:n,match:r})=>{const a=Lc(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 M$e(s){return new yPe({find:s.find,handler:({state:t,range:n,match:r})=>{const a=t.doc.resolve(n.from),i=Lc(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 Aee(s){return new yPe({find:s.find,handler:({state:t,range:n,match:r,chain:a})=>{const i=Lc(s.getAttributes,void 0,r)||{},l=t.tr.delete(n.from,n.to),c=l.doc.resolve(n.from).blockRange(),d=c&&QQe(c,s.type,i);if(!d)return null;if(l.wrap(c,d),s.keepMarks&&s.editor){const{selection:h,storedMarks:m}=t,{splittableMarks:p}=s.editor.extensionManager,f=m||h.$to.parentOffset&&h.$from.marks();if(f){const x=f.filter(y=>p.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&&VP(l.doc,n.from-1)&&(!s.joinPredicate||s.joinPredicate(r,u))&&l.join(n.from-1)}})}let fy=class P$e{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=Lc(xo(this,"addOptions",{name:this.name}))),this.storage=Lc(xo(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new P$e(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>vPe(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new P$e(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=Lc(xo(n,"addOptions",{name:n.name})),n.storage=Lc(xo(n,"addStorage",{name:n.name,options:n.options})),n}};function M7(s){return new K9t({find:s.find,handler:({state:t,range:n,match:r,pasteEvent:a})=>{const i=Lc(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(xJe(n.from,n.to,t.doc).filter(f=>f.mark.type.excluded.find(y=>y===s.type&&y!==f.mark.type)).filter(f=>f.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 dHs(s,t){const{selection:n}=s,{$from:r}=n;if(n instanceof nl){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 uHs(s){return new K9t({find:s.find,handler({match:t,chain:n,range:r,pasteEvent:a}){const i=Lc(s.getAttributes,void 0,t,a),l=Lc(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 hHs(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var izt={exports:{}},xFe={};/** * @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 Jgt;function mHs(){if(Jgt)return xFe;Jgt=1;var s=Dt;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 p=m(),f=r({inst:{value:p,getSnapshot:m}}),x=f[0].inst,y=f[1];return i(function(){x.value=p,x.getSnapshot=m,c(x)&&y({inst:x})},[h,p,m]),a(function(){return c(x)&&y({inst:x}),h(function(){c(x)&&y({inst:x})})},[h]),l(p),p}function c(h){var m=h.getSnapshot;h=h.value;try{var p=m();return!n(h,p)}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 xFe.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:u,xFe}izt.exports=mHs();var vJe=izt.exports;const pHs=(...s)=>t=>{s.forEach(n=>{typeof n=="function"?n(t):n&&(n.current=t)})},fHs=({contentComponent:s})=>{const t=vJe.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getServerSnapshot);return Dt.createElement(Dt.Fragment,null,Object.values(t))};function gHs(){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]:oZe.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 xHs extends Dt.Component{constructor(t){var n;super(t),this.editorContentRef=Dt.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=gHs(),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 Dt.createElement(Dt.Fragment,null,Dt.createElement("div",{ref:pHs(n,this.editorContentRef),...r}),(t==null?void 0:t.contentComponent)&&Dt.createElement(fHs,{contentComponent:t.contentComponent}))}}const yHs=j.forwardRef((s,t)=>{const n=Dt.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[s.editor]);return Dt.createElement(xHs,{key:n,innerRef:t,...s})}),_Pe=Dt.memo(yHs);var vHs=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},bHs=hHs(vHs),ozt={exports:{}},yFe={};/** * @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 ext;function _Hs(){if(ext)return yFe;ext=1;var s=Dt,t=vJe;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 yFe.useSyncExternalStoreWithSelector=function(d,u,h,m,p){var f=i(null);if(f.current===null){var x={hasValue:!1,value:null};f.current=x}else x=f.current;f=o(function(){function v(T){if(!b){if(b=!0,N=T,T=m(T),p!==void 0&&x.hasValue){var L=x.value;if(p(L,T))return S=L}return S=T}if(L=S,r(N,T))return L;var M=m(T);return p!==void 0&&p(L,M)?L:(N=T,S=M)}var b=!1,N,S,A=h===void 0?null:h;return[function(){return v(u())},A===null?void 0:function(){return v(A())}]},[u,h,m,p]);var y=a(d,f[0],f[1]);return l(function(){x.hasValue=!0,x.value=y},[y]),c(y),y},yFe}ozt.exports=_Hs();var wHs=ozt.exports;const jHs=typeof window<"u"?j.useLayoutEffect:j.useEffect;class NHs{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 kHs(s){var t;const[n]=j.useState(()=>new NHs(s.editor)),r=wHs.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,s.selector,(t=s.equalityFn)!==null&&t!==void 0?t:bHs);return jHs(()=>n.watch(s.editor),[s.editor,n]),j.useDebugValue(r),r}const SHs=!1,L$e=typeof window>"u",CHs=L$e||!!(typeof window<"u"&&window.next);class bJe{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(){if(this.options.current.immediatelyRender===void 0)return L$e||CHs?null:this.createEditor();if(this.options.current.immediatelyRender&&L$e&&SHs)throw new Error("Tiptap Error: SSR has been detected, and `immediatelyRender` has been set to `true` this is an unsupported configuration that may result in errors, explicitly set `immediatelyRender` to `false` to avoid hydration mismatches.");return this.options.current.immediatelyRender?this.createEditor():null}createEditor(){const t={...this.options.current,onBeforeCreate:(...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 cHs(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?bJe.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 wPe(s={},t=[]){const n=j.useRef(s);n.current=s;const[r]=j.useState(()=>new bJe(n)),a=vJe.useSyncExternalStore(r.subscribe,r.getEditor,r.getServerSnapshot);return j.useDebugValue(a),j.useEffect(r.onRender(t)),kHs({editor:a,selector:({transactionNumber:i})=>s.shouldRerenderOnTransaction===!1?null:s.immediatelyRender&&i===0?0:i+1}),a}const AHs=j.createContext({editor:null});AHs.Consumer;const EHs=j.createContext({onDragStart:void 0}),THs=()=>j.useContext(EHs);Dt.forwardRef((s,t)=>{const{onDragStart:n}=THs(),r=s.as||"div";return Dt.createElement(r,{...s,ref:t,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...s.style}})});const MHs=/^\s*>\s$/,PHs=fy.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:s}){return["blockquote",Dm(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[Aee({find:MHs,type:this.type})]}}),LHs=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,IHs=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,RHs=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,DHs=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,OHs=gS.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",Dm(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[XV({find:LHs,type:this.type}),XV({find:RHs,type:this.type})]},addPasteRules(){return[M7({find:IHs,type:this.type}),M7({find:DHs,type:this.type})]}}),FHs="listItem",txt="textStyle",sxt=/^\s*([-+*])\s$/,zHs=fy.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",Dm(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(FHs,this.editor.getAttributes(txt)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let s=Aee({find:sxt,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(s=Aee({find:sxt,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(txt),editor:this.editor})),[s]}}),BHs=/(^|[^`])`([^`]+)`(?!`)/,UHs=/(^|[^`])`([^`]+)`(?!`)/g,qHs=gS.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:s}){return["code",Dm(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[XV({find:BHs,type:this.type})]},addPasteRules(){return[M7({find:UHs,type:this.type})]}}),$Hs=/^```([a-z]+)?[\s\n]$/,VHs=/^~~~([a-z]+)?[\s\n]$/,HHs=fy.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",Dm(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(Ol.near(r.resolve(o))),!0)):s.commands.exitCode()}}},addInputRules(){return[M$e({find:$Hs,type:this.type,getAttributes:s=>({language:s[1]})}),M$e({find:VHs,type:this.type,getAttributes:s=>({language:s[1]})})]},addProseMirrorPlugins(){return[new b0({key:new f1("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(pl.near(l.doc.resolve(Math.max(0,l.selection.from-2)))),l.setMeta("paste",!0),s.dispatch(l),!0}}})]}}),GHs=fy.create({name:"doc",topNode:!0,content:"block+"});function WHs(s={}){return new b0({view(t){return new KHs(t,s)}})}class KHs{constructor(t,n){var r;this.editorView=t,this.cursorPos=null,this.element=null,this.timeout=-1,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.handlers.forEach(({name:t,handler:n})=>this.editorView.dom.removeEventListener(t,n))}update(t,n){this.cursorPos!=null&&n.doc!=t.state.doc&&(this.cursorPos>t.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(t){t!=this.cursorPos&&(this.cursorPos=t,t==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let t=this.editorView.state.doc.resolve(this.cursorPos),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 p=this.editorView.nodeDOM(this.cursorPos-(h?h.nodeSize:0));if(p){let f=p.getBoundingClientRect(),x=h?f.bottom:f.top;h&&m&&(x=(x+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let y=this.width/2*o;r={left:f.left,right:f.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,p=h.height/c.offsetHeight;d=h.left-c.scrollLeft*m,u=h.top-c.scrollTop*p}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)}dragover(t){if(!this.editorView.editable)return;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){let l=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let o=X7t(this.editorView.state.doc,l,this.editorView.dragging.slice);o!=null&&(l=o)}this.setCursor(l),this.scheduleRemoval(5e3)}}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(t){this.editorView.dom.contains(t.relatedTarget)||this.setCursor(null)}}const YHs=wv.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[WHs(this.options)]}});class eg extends Ol{constructor(t){super(t,t)}map(t,n){let r=t.resolve(n.map(this.head));return eg.valid(r)?new eg(r):Ol.near(r)}content(){return Si.empty}eq(t){return t instanceof eg&&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 eg(t.resolve(n.pos))}getBookmark(){return new _Je(this.anchor)}static valid(t){let n=t.parent;if(n.inlineContent||!ZHs(t)||!XHs(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&&eg.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(eg.valid(c))return c}for(;;){let l=n>0?i.firstChild:i.lastChild;if(!l){if(i.isAtom&&!i.isText&&!nl.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(eg.valid(o))return o}return null}}}eg.prototype.visible=!1;eg.findFrom=eg.findGapCursorFrom;Ol.jsonID("gapcursor",eg);class _Je{constructor(t){this.pos=t}map(t){return new _Je(t.map(this.pos))}resolve(t){let n=t.resolve(this.pos);return eg.valid(n)?new eg(n):Ol.near(n)}}function lzt(s){return s.isAtom||s.spec.isolating||s.spec.createGapCursor}function ZHs(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||lzt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function XHs(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||lzt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function QHs(){return new b0({props:{decorations:sGs,createSelectionBetween(s,t,n){return t.pos==n.pos&&eg.valid(n)?new eg(n):null},handleClick:eGs,handleKeyDown:JHs,handleDOMEvents:{beforeinput:tGs}}})}const JHs=dJe({ArrowLeft:Goe("horiz",-1),ArrowRight:Goe("horiz",1),ArrowUp:Goe("vert",-1),ArrowDown:Goe("vert",1)});function Goe(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 pl){if(!i.endOfTextblock(n)||o.depth==0)return!1;c=!1,o=r.doc.resolve(t>0?o.after():o.before())}let d=eg.findGapCursorFrom(o,t,c);return d?(a&&a(r.tr.setSelection(new eg(d))),!0):!1}}function eGs(s,t,n){if(!s||!s.editable)return!1;let r=s.state.doc.resolve(t);if(!eg.valid(r))return!1;let a=s.posAtCoords({left:n.clientX,top:n.clientY});return a&&a.inside>-1&&nl.isSelectable(s.state.doc.nodeAt(a.inside))?!1:(s.dispatch(s.state.tr.setSelection(new eg(r))),!0)}function tGs(s,t){if(t.inputType!="insertCompositionText"||!(s.state.selection instanceof eg))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=Ba.empty;for(let l=r.length-1;l>=0;l--)a=Ba.from(r[l].createAndFill(null,a));let i=s.state.tr.replace(n.pos,n.pos,new Si(a,0,0));return i.setSelection(pl.near(i.doc.resolve(n.pos+1))),s.dispatch(i),!1}function sGs(s){if(!(s.selection instanceof eg))return null;let t=document.createElement("div");return t.className="ProseMirror-gapcursor",Jf.create(s.doc,[sb.widget(s.selection.head,t,{key:"gapcursor"})])}const nGs=wv.create({name:"gapCursor",addProseMirrorPlugins(){return[QHs()]},extendNodeSchema(s){var t;const n={name:s.name,options:s.options,storage:s.storage};return{allowGapCursor:(t=Lc(xo(s,"allowGapCursor",n)))!==null&&t!==void 0?t:null}}}),rGs=fy.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",Dm(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()}}}),aGs=fy.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]}`,Dm(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=>M$e({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${s}})\\s$`),type:this.type,getAttributes:{level:s}}))}});var HCe=200,hy=function(){};hy.prototype.append=function(t){return t.length?(t=hy.from(t),!this.length&&t||t.length=n?hy.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,n))};hy.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)};hy.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)};hy.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};hy.from=function(t){return t instanceof hy?t:t&&t.length?new czt(t):hy.empty};var czt=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<=HCe)return new t(this.values.concat(a.flatten()))},t.prototype.leafPrepend=function(a){if(this.length+a.length<=HCe)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}(hy);hy.empty=new czt([]);var iGs=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}(hy);const oGs=500;class $k{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 aT(h.map));let p=h.step.map(a.slice(i)),f;p&&l.maybeStep(p).doc&&(f=l.mapping.maps[l.mapping.maps.length-1],d.push(new aT(f,void 0,void 0,d.length+u.length))),i--,f&&a.appendMap(f,i)}else l.maybeStep(h.step);if(h.selection)return o=a?h.selection.map(a.slice(i)):h.selection,c=new $k(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;ucGs&&(o=lGs(o,d),l-=d),new $k(o.append(i),l)}remapping(t,n){let r=new _ee;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 $k(this.items.append(t.map(n=>new aT(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 p=i.getMirror(--c);if(p==null)return;l=Math.min(l,p);let f=i.maps[p];if(m.step){let x=t.steps[p].invert(t.docs[p]),y=m.selection&&m.selection.map(i.slice(c+1,p));y&&o++,r.push(new aT(f,x,y))}else r.push(new aT(f))},a);let d=[];for(let m=n;moGs&&(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 aT(d.invert(),c,u),m,p=a.length-1;(m=a.length&&a[p].merge(h))?a[p]=m:a.push(h)}}else l.map&&r--},this.items.length,0),new $k(hy.from(a.reverse()),i)}}$k.empty=new $k(hy.empty,0);function lGs(s,t){let n;return s.forEach((r,a)=>{if(r.selection&&t--==0)return n=a,!1}),s.slice(n)}let aT=class dzt{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 dzt(n.getMap().invert(),n,this.selection)}}};class HT{constructor(t,n,r,a,i){this.done=t,this.undone=n,this.prevRanges=r,this.prevTime=a,this.prevComposition=i}}const cGs=20;function dGs(s,t,n,r){let a=n.getMeta(ZF),i;if(a)return a.historyState;n.getMeta(mGs)&&(s=new HT(s.done,s.undone,null,0,-1));let l=n.getMeta("appendedTransaction");if(n.steps.length==0)return s;if(l&&l.getMeta(ZF))return l.getMeta(ZF).redo?new HT(s.done.addTransform(n,void 0,r,$5e(t)),s.undone,nxt(n.mapping.maps),s.prevTime,s.prevComposition):new HT(s.done,s.undone.addTransform(n,void 0,r,$5e(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||!uGs(n,s.prevRanges)),d=l?vFe(s.prevRanges,n.mapping):nxt(n.mapping.maps);return new HT(s.done.addTransform(n,c?t.selection.getBookmark():void 0,r,$5e(t)),$k.empty,d,n.time,o??s.prevComposition)}else return(i=n.getMeta("rebased"))?new HT(s.done.rebased(n,i),s.undone.rebased(n,i),vFe(s.prevRanges,n.mapping),s.prevTime,s.prevComposition):new HT(s.done.addMaps(n.mapping.maps),s.undone.addMaps(n.mapping.maps),vFe(s.prevRanges,n.mapping),s.prevTime,s.prevComposition)}function uGs(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 nxt(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 vFe(s,t){if(!s)return null;let n=[];for(let r=0;r{let a=ZF.getState(n);if(!a||(s?a.undone:a.done).eventCount==0)return!1;if(r){let i=hGs(a,n,s);i&&r(t?i.scrollIntoView():i)}return!0}}const hzt=uzt(!1,!0),mzt=uzt(!0,!0),fGs=wv.create({name:"history",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:s,dispatch:t})=>hzt(s,t),redo:()=>({state:s,dispatch:t})=>mzt(s,t)}},addProseMirrorPlugins(){return[pGs(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()}}}),gGs=fy.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{}}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:s}){return["hr",Dm(this.options.HTMLAttributes,s)]},addCommands(){return{setHorizontalRule:()=>({chain:s,state:t})=>{if(!dHs(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}):PVs(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(pl.create(l.doc,d.pos+1)):d.nodeAfter.isBlock?l.setSelection(nl.create(l.doc,d.pos)):l.setSelection(pl.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(pl.create(l.doc,u+1)))}l.scrollIntoView()}return!0}).run()}}},addInputRules(){return[azt({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),xGs=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,yGs=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,vGs=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,bGs=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,_Gs=gS.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",Dm(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[XV({find:xGs,type:this.type}),XV({find:vGs,type:this.type})]},addPasteRules(){return[M7({find:yGs,type:this.type}),M7({find:bGs,type:this.type})]}}),wGs=fy.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:s}){return["li",Dm(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)}}}),jGs="listItem",axt="textStyle",ixt=/^(\d+)\.\s$/,NGs=fy.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",Dm(this.options.HTMLAttributes,n),0]:["ol",Dm(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(jGs,this.editor.getAttributes(axt)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let s=Aee({find:ixt,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=Aee({find:ixt,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(axt)}),joinPredicate:(t,n)=>n.childCount+n.attrs.start===+t[1],editor:this.editor})),[s]}}),kGs=fy.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:s}){return["p",Dm(this.options.HTMLAttributes,s),0]},addCommands(){return{setParagraph:()=>({commands:s})=>s.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),SGs=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,CGs=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,AGs=gS.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",Dm(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[XV({find:SGs,type:this.type})]},addPasteRules(){return[M7({find:CGs,type:this.type})]}}),EGs=fy.create({name:"text",group:"inline"}),jPe=wv.create({name:"starterKit",addExtensions(){const s=[];return this.options.bold!==!1&&s.push(OHs.configure(this.options.bold)),this.options.blockquote!==!1&&s.push(PHs.configure(this.options.blockquote)),this.options.bulletList!==!1&&s.push(zHs.configure(this.options.bulletList)),this.options.code!==!1&&s.push(qHs.configure(this.options.code)),this.options.codeBlock!==!1&&s.push(HHs.configure(this.options.codeBlock)),this.options.document!==!1&&s.push(GHs.configure(this.options.document)),this.options.dropcursor!==!1&&s.push(YHs.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&s.push(nGs.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&s.push(rGs.configure(this.options.hardBreak)),this.options.heading!==!1&&s.push(aGs.configure(this.options.heading)),this.options.history!==!1&&s.push(fGs.configure(this.options.history)),this.options.horizontalRule!==!1&&s.push(gGs.configure(this.options.horizontalRule)),this.options.italic!==!1&&s.push(_Gs.configure(this.options.italic)),this.options.listItem!==!1&&s.push(wGs.configure(this.options.listItem)),this.options.orderedList!==!1&&s.push(NGs.configure(this.options.orderedList)),this.options.paragraph!==!1&&s.push(kGs.configure(this.options.paragraph)),this.options.strike!==!1&&s.push(AGs.configure(this.options.strike)),this.options.text!==!1&&s.push(EGs.configure(this.options.text)),s}}),TGs="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",MGs="ελ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",I$e="numeric",R$e="ascii",D$e="alpha",zQ="asciinumeric",kZ="alphanumeric",O$e="domain",pzt="emoji",PGs="scheme",LGs="slashscheme",_Fe="whitespace";function IGs(s,t){return s in t||(t[s]=[]),t[s]}function ZD(s,t,n){t[I$e]&&(t[zQ]=!0,t[kZ]=!0),t[R$e]&&(t[zQ]=!0,t[D$e]=!0),t[zQ]&&(t[kZ]=!0),t[D$e]&&(t[kZ]=!0),t[kZ]&&(t[O$e]=!0),t[pzt]&&(t[O$e]=!0);for(const r in t){const a=IGs(r,n);a.indexOf(s)<0&&a.push(s)}}function RGs(s,t){const n={};for(const r in t)t[r].indexOf(s)>=0&&(n[r]=!0);return n}function f_(s=null){this.j={},this.jr=[],this.jd=null,this.t=s}f_.groups={};f_.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),Vf=(s,t,n,r,a)=>s.tr(t,n,r,a),oxt=(s,t,n,r,a)=>s.ts(t,n,r,a),Ga=(s,t,n,r,a)=>s.tt(t,n,r,a),pC="WORD",F$e="UWORD",fzt="ASCIINUMERICAL",gzt="ALPHANUMERICAL",Eee="LOCALHOST",z$e="TLD",B$e="UTLD",V5e="SCHEME",BB="SLASH_SCHEME",wJe="NUM",U$e="WS",jJe="NL",BQ="OPENBRACE",UQ="CLOSEBRACE",GCe="OPENBRACKET",WCe="CLOSEBRACKET",KCe="OPENPAREN",YCe="CLOSEPAREN",ZCe="OPENANGLEBRACKET",XCe="CLOSEANGLEBRACKET",QCe="FULLWIDTHLEFTPAREN",JCe="FULLWIDTHRIGHTPAREN",eAe="LEFTCORNERBRACKET",tAe="RIGHTCORNERBRACKET",sAe="LEFTWHITECORNERBRACKET",nAe="RIGHTWHITECORNERBRACKET",rAe="FULLWIDTHLESSTHAN",aAe="FULLWIDTHGREATERTHAN",iAe="AMPERSAND",oAe="APOSTROPHE",lAe="ASTERISK",GT="AT",cAe="BACKSLASH",dAe="BACKTICK",uAe="CARET",r6="COLON",NJe="COMMA",hAe="DOLLAR",S5="DOT",mAe="EQUALS",kJe="EXCLAMATION",p2="HYPHEN",qQ="PERCENT",pAe="PIPE",fAe="PLUS",gAe="POUND",$Q="QUERY",SJe="QUOTE",xzt="FULLWIDTHMIDDLEDOT",CJe="SEMI",C5="SLASH",VQ="TILDE",xAe="UNDERSCORE",yzt="EMOJI",yAe="SYM";var vzt=Object.freeze({__proto__:null,ALPHANUMERICAL:gzt,AMPERSAND:iAe,APOSTROPHE:oAe,ASCIINUMERICAL:fzt,ASTERISK:lAe,AT:GT,BACKSLASH:cAe,BACKTICK:dAe,CARET:uAe,CLOSEANGLEBRACKET:XCe,CLOSEBRACE:UQ,CLOSEBRACKET:WCe,CLOSEPAREN:YCe,COLON:r6,COMMA:NJe,DOLLAR:hAe,DOT:S5,EMOJI:yzt,EQUALS:mAe,EXCLAMATION:kJe,FULLWIDTHGREATERTHAN:aAe,FULLWIDTHLEFTPAREN:QCe,FULLWIDTHLESSTHAN:rAe,FULLWIDTHMIDDLEDOT:xzt,FULLWIDTHRIGHTPAREN:JCe,HYPHEN:p2,LEFTCORNERBRACKET:eAe,LEFTWHITECORNERBRACKET:sAe,LOCALHOST:Eee,NL:jJe,NUM:wJe,OPENANGLEBRACKET:ZCe,OPENBRACE:BQ,OPENBRACKET:GCe,OPENPAREN:KCe,PERCENT:qQ,PIPE:pAe,PLUS:fAe,POUND:gAe,QUERY:$Q,QUOTE:SJe,RIGHTCORNERBRACKET:tAe,RIGHTWHITECORNERBRACKET:nAe,SCHEME:V5e,SEMI:CJe,SLASH:C5,SLASH_SCHEME:BB,SYM:yAe,TILDE:VQ,TLD:z$e,UNDERSCORE:xAe,UTLD:B$e,UWORD:F$e,WORD:pC,WS:U$e});const J3=/[a-z]/,sY=new RegExp("\\p{L}","u"),wFe=new RegExp("\\p{Emoji}","u"),eC=/\d/,jFe=/\s/,lxt="\r",NFe=` `,DGs="️",OGs="‍",kFe="";let Woe=null,Koe=null;function FGs(s=[]){const t={};f_.groups=t;const n=new f_;Woe==null&&(Woe=cxt(TGs)),Koe==null&&(Koe=cxt(MGs)),Ga(n,"'",oAe),Ga(n,"{",BQ),Ga(n,"}",UQ),Ga(n,"[",GCe),Ga(n,"]",WCe),Ga(n,"(",KCe),Ga(n,")",YCe),Ga(n,"<",ZCe),Ga(n,">",XCe),Ga(n,"(",QCe),Ga(n,")",JCe),Ga(n,"「",eAe),Ga(n,"」",tAe),Ga(n,"『",sAe),Ga(n,"』",nAe),Ga(n,"<",rAe),Ga(n,">",aAe),Ga(n,"&",iAe),Ga(n,"*",lAe),Ga(n,"@",GT),Ga(n,"`",dAe),Ga(n,"^",uAe),Ga(n,":",r6),Ga(n,",",NJe),Ga(n,"$",hAe),Ga(n,".",S5),Ga(n,"=",mAe),Ga(n,"!",kJe),Ga(n,"-",p2),Ga(n,"%",qQ),Ga(n,"|",pAe),Ga(n,"+",fAe),Ga(n,"#",gAe),Ga(n,"?",$Q),Ga(n,'"',SJe),Ga(n,"/",C5),Ga(n,";",CJe),Ga(n,"~",VQ),Ga(n,"_",xAe),Ga(n,"\\",cAe),Ga(n,"・",xzt);const r=Vf(n,eC,wJe,{[I$e]:!0});Vf(r,eC,r);const a=Vf(r,J3,fzt,{[zQ]:!0}),i=Vf(r,sY,gzt,{[kZ]:!0}),l=Vf(n,J3,pC,{[R$e]:!0});Vf(l,eC,a),Vf(l,J3,l),Vf(a,eC,a),Vf(a,J3,a);const o=Vf(n,sY,F$e,{[D$e]:!0});Vf(o,J3),Vf(o,eC,i),Vf(o,sY,o),Vf(i,eC,i),Vf(i,J3),Vf(i,sY,i);const c=Ga(n,NFe,jJe,{[_Fe]:!0}),d=Ga(n,lxt,U$e,{[_Fe]:!0}),u=Vf(n,jFe,U$e,{[_Fe]:!0});Ga(n,kFe,u),Ga(d,NFe,c),Ga(d,kFe,u),Vf(d,jFe,u),Ga(u,lxt),Ga(u,NFe),Vf(u,jFe,u),Ga(u,kFe,u);const h=Vf(n,wFe,yzt,{[pzt]:!0});Ga(h,"#"),Vf(h,wFe,h),Ga(h,DGs,h);const m=Ga(h,OGs);Ga(m,"#"),Vf(m,wFe,h);const p=[[J3,l],[eC,a]],f=[[J3,null],[sY,o],[eC,i]];for(let x=0;xx[0]>y[0]?1:-1);for(let x=0;x=0?b[O$e]=!0:J3.test(y)?eC.test(y)?b[zQ]=!0:b[R$e]=!0:b[I$e]=!0,oxt(n,y,y,b)}return oxt(n,"localhost",Eee,{ascii:!0}),n.jd=new f_(yAe),{start:n,tokens:Object.assign({groups:t},vzt)}}function bzt(s,t){const n=zGs(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 zGs(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 iT(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 Tee={defaultProtocol:"http",events:null,format:dxt,formatHref:dxt,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function AJe(s,t=null){let n=Object.assign({},Tee);s&&(n=Object.assign(n,s instanceof AJe?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=Tee.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 NPe(s,t){class n extends _zt{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 uxt=NPe("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),hxt=NPe("text"),BGs=NPe("nl"),Yoe=NPe("url",{isLink:!0,toHref(s=Tee.defaultProtocol){return this.hasProtocol()?this.v:`${s}://${this.v}`},hasProtocol(){const s=this.tk;return s.length>=2&&s[0].t!==Eee&&s[1].t===r6}}),s2=s=>new f_(s);function UGs({groups:s}){const t=s.domain.concat([iAe,lAe,GT,cAe,dAe,uAe,hAe,mAe,p2,wJe,qQ,pAe,fAe,gAe,C5,yAe,VQ,xAe]),n=[oAe,r6,NJe,S5,kJe,qQ,$Q,SJe,CJe,ZCe,XCe,BQ,UQ,WCe,GCe,KCe,YCe,QCe,JCe,eAe,tAe,sAe,nAe,rAe,aAe],r=[iAe,oAe,lAe,cAe,dAe,uAe,hAe,mAe,p2,BQ,UQ,qQ,pAe,fAe,gAe,$Q,C5,yAe,VQ,xAe],a=s2(),i=Ga(a,VQ);Yc(i,r,i),Yc(i,s.domain,i);const l=s2(),o=s2(),c=s2();Yc(a,s.domain,l),Yc(a,s.scheme,o),Yc(a,s.slashscheme,c),Yc(l,r,i),Yc(l,s.domain,l);const d=Ga(l,GT);Ga(i,GT,d),Ga(o,GT,d),Ga(c,GT,d);const u=Ga(i,S5);Yc(u,r,i),Yc(u,s.domain,i);const h=s2();Yc(d,s.domain,h),Yc(h,s.domain,h);const m=Ga(h,S5);Yc(m,s.domain,h);const p=s2(uxt);Yc(m,s.tld,p),Yc(m,s.utld,p),Ga(d,Eee,p);const f=Ga(h,p2);Ga(f,p2,f),Yc(f,s.domain,h),Yc(p,s.domain,h),Ga(p,S5,m),Ga(p,p2,f);const x=Ga(p,r6);Yc(x,s.numeric,uxt);const y=Ga(l,p2),v=Ga(l,S5);Ga(y,p2,y),Yc(y,s.domain,l),Yc(v,r,i),Yc(v,s.domain,l);const b=s2(Yoe);Yc(v,s.tld,b),Yc(v,s.utld,b),Yc(b,s.domain,l),Yc(b,r,i),Ga(b,S5,v),Ga(b,p2,y),Ga(b,GT,d);const N=Ga(b,r6),S=s2(Yoe);Yc(N,s.numeric,S);const A=s2(Yoe),T=s2();Yc(A,t,A),Yc(A,n,T),Yc(T,t,A),Yc(T,n,T),Ga(b,C5,A),Ga(S,C5,A);const L=Ga(o,r6),M=Ga(c,r6),I=Ga(M,C5),R=Ga(I,C5);Yc(o,s.domain,l),Ga(o,S5,v),Ga(o,p2,y),Yc(c,s.domain,l),Ga(c,S5,v),Ga(c,p2,y),Yc(L,s.domain,A),Ga(L,C5,A),Ga(L,$Q,A),Yc(R,s.domain,A),Yc(R,t,A),Ga(R,C5,A);const z=[[BQ,UQ],[GCe,WCe],[KCe,YCe],[ZCe,XCe],[QCe,JCe],[eAe,tAe],[sAe,nAe],[rAe,aAe]];for(let $=0;$=0&&m++,a++,u++;if(m<0)a-=u,a0&&(i.push(SFe(hxt,t,l)),l=[]),a-=m,u-=m;const p=h.t,f=n.slice(a-u,a);i.push(SFe(p,t,f))}}return l.length>0&&i.push(SFe(hxt,t,l)),i}function SFe(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 $Gs=typeof console<"u"&&console&&console.warn||(()=>{}),VGs="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",tp={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function HGs(){return f_.groups={},tp.scanner=null,tp.parser=null,tp.tokenQueue=[],tp.pluginQueue=[],tp.customSchemes=[],tp.initialized=!1,tp}function mxt(s,t=!1){if(tp.initialized&&$Gs(`linkifyjs: already initialized - will not register custom scheme "${s}" ${VGs}`),!/^[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`);tp.customSchemes.push([s,t])}function GGs(){tp.scanner=FGs(tp.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=jVs(n.doc,[...t]);if(TVs(o).forEach(({newRange:d})=>{const u=kVs(r.doc,d,p=>p.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 p=r.doc.textBetween(d.from,d.to," "," ");if(!KGs.test(p))return;h=u[0],m=r.doc.textBetween(h.pos,d.to,void 0," ")}if(h&&m){const p=m.split(WGs).filter(Boolean);if(p.length<=0)return!1;const f=p[p.length-1],x=h.pos+m.lastIndexOf(f);if(!f)return!1;const y=EJe(f).map(v=>v.toObject(s.defaultProtocol));if(!ZGs(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=>{xJe(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 QGs(s){return new b0({key:new f1("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=rzt(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 JGs(s){return new b0({key:new f1("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=wzt(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 QL(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(YGs,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}const kPe=gS.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"){mxt(s);return}mxt(s.scheme,s.optionalSlashes)})},onDestroy(){HGs()},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)=>!!QL(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=>!!QL(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=>!!QL(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",Dm(this.options.HTMLAttributes,s),0]:["a",Dm(this.options.HTMLAttributes,{...s,href:""}),0]},addCommands(){return{setLink:s=>({chain:t})=>{const{href:n}=s;return this.options.isAllowedUri(n,{defaultValidate:r=>!!QL(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=>!!QL(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[M7({find:s=>{const t=[];if(s){const{protocols:n,defaultProtocol:r}=this.options,a=wzt(s).filter(i=>i.isLink&&this.options.isAllowedUri(i.value,{defaultValidate:l=>!!QL(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(XGs({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:a=>!!QL(a,t),protocols:t,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),this.options.openOnClick===!0&&s.push(QGs({type:this.type})),this.options.linkOnPaste&&s.push(JGs({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type})),s}}),SPe=wv.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")}}}),eWs=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}`)})},MJe=gS.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!1}},parseHTML(){return[{tag:"span",getAttrs:s=>s.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&eWs(s),{}):!1}]},renderHTML({HTMLAttributes:s}){return["span",Dm(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}}}}),tWs=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,jzt=fy.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",Dm(this.options.HTMLAttributes,s)]},addCommands(){return{setImage:s=>({commands:t})=>t.insertContent({type:this.name,attrs:s})}},addInputRules(){return[azt({find:tWs,type:this.type,getAttributes:s=>{const[,,t,n,r]=s;return{src:n,alt:t,title:r}}})]}});let q$e,$$e;if(typeof WeakMap<"u"){let s=new WeakMap;q$e=t=>s.get(t),$$e=(t,n)=>(s.set(t,n),n)}else{const s=[];let n=0;q$e=r=>{for(let a=0;a(n==10&&(n=0),s[n++]=r,s[n++]=a)}var tg=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-N});break}const S=a+N*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 rWs(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 iWs(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 jS(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 CPe(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=P7(t.$head)||oWs(t.$head);if(n)return n;throw new RangeError(`No cell found around position ${t.head}`)}function oWs(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 V$e(s){return s.parent.type.spec.tableRole=="row"&&!!s.nodeAfter}function lWs(s){return s.node(0).resolve(s.pos+s.nodeAfter.nodeSize)}function PJe(s,t){return s.depth==t.depth&&s.pos>=t.start(-1)&&s.pos<=t.end(-1)}function Nzt(s,t,n){const r=s.node(-1),a=tg.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 L7(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 kzt(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 s9t(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(V$e(r)&&V$e(a)&&PJe(r,a)){const i=this.$anchorCell.node(-1)!=r.node(-1);return i&&this.isRowSelection()?fC.rowSelection(r,a):i&&this.isColSelection()?fC.colSelection(r,a):new fC(r,a)}return pl.between(r,a)}content(){const t=this.$anchorCell.node(-1),n=tg.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=f.attrs;if(x>0&&(v=L7(v,0,x)),y>0&&(v=L7(v,v.colspan-y,y)),p.lefta.bottom){const v={...f.attrs,rowspan:Math.min(p.bottom,a.bottom)-Math.max(p.top,a.top)};p.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=tg.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 fC&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,n=t){const r=t.node(-1),a=tg.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(sb.node(r,r+n.nodeSize,{class:"selectedCell"}))}),Jf.create(s.doc,t)}function hWs({$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 mWs({$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 pWs(s,t,n){const r=(t||s).selection,a=(t||s).doc;let i,l;if(r instanceof nl&&(l=r.node.type.spec.tableRole)){if(l=="cell"||l=="header_cell")i=Rm.create(a,r.from);else if(l=="row"){const o=a.resolve(r.from+1);i=Rm.rowSelection(o,o)}else if(!n){const o=tg.get(r.node),c=r.from+1,d=c+o.map[o.width*o.height-1];i=Rm.create(a,c+1,d)}}else r instanceof pl&&hWs(r)?i=pl.create(a,r.from):r instanceof pl&&mWs(r)&&(i=pl.create(a,r.$from.start(),r.$from.end()));return i&&(t||(t=s.tr)).setSelection(i),t}const fWs=new f1("fix-tables");function Czt(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=gWs(s,a,i,n))};return t?t.doc!=s.doc&&Czt(t.doc,s.doc,0,r):s.doc.descendants(r),n}function gWs(s,t,n,r){const a=tg.get(t);if(!a.problems)return r;r||(r=s.tr);const i=[];for(let c=0;c0){let p="cell";u.firstChild&&(p=u.firstChild.type.spec.tableRole);const f=[];for(let y=0;y0?-1:0;cWs(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;_Ws(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=pxt(d)?c+1:u;i.replaceWith(h+r.tableStart,u+r.tableStart,o)}i.setSelection(new Rm(i.doc.resolve(c+r.tableStart))),t(i)}return!0}function gxt(s,t){const n=u1(s.schema);return CWs(({node:r})=>n[r.type.spec.tableRole])(s,t)}function CWs(s){return(t,n)=>{const r=t.selection;let a,i;if(r instanceof Rm){if(r.$anchorCell.pos!=r.$headCell.pos)return!1;a=r.$anchorCell.nodeAfter,i=r.$anchorCell.pos}else{var l;if(a=iWs(r.$from),!a)return!1;i=(l=P7(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=d3(t),h=t.tr;for(let p=0;p{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 EWs(s){return function(t,n){if(!jS(t))return!1;if(n){const r=u1(t.schema),a=d3(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 p=m+i.tableStart,f=l.doc.nodeAt(p);f&&l.setNodeMarkup(p,h,f.attrs)}),r(l)}return!0}}Mee("row",{useDeprecatedLogic:!0});Mee("column",{useDeprecatedLogic:!0});const TWs=Mee("cell",{useDeprecatedLogic:!0});function MWs(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 Zoe(s,t){const n=s.selection;if(!(n instanceof Rm))return!1;if(t){const r=s.tr,a=u1(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 Si(a,0,0))}),r.docChanged&&t(r)}return!0}function LWs(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(Ba.empty),n[a]r&&(m=m.type.createChecked(L7(m.attrs,m.attrs.colspan,u+m.attrs.colspan-r),m.content)),d.push(m),u+=m.attrs.colspan;for(let p=1;pa&&(h=h.type.create({...h.attrs,rowspan:Math.max(1,a-h.attrs.rowspan)},h.content)),c.push(h)}i.push(Ba.from(c))}n=i,t=a}return{width:s,height:t,rows:n}}function DWs(s,t,n,r,a,i,l){const o=s.doc.type.schema,c=u1(o);let d,u;if(a>t.width)for(let h=0,m=0;ht.height){const h=[];for(let f=0,x=(t.height-1)*t.width;f=t.width?!1:n.nodeAt(t.map[x+f]).type==c.header_cell;h.push(y?u||(u=c.header_cell.createAndFill()):d||(d=c.cell.createAndFill()))}const m=c.row.create(null,Ba.from(h)),p=[];for(let f=t.height;f{if(!a)return!1;const i=n.selection;if(i instanceof Rm)return H5e(n,r,Ol.near(i.$headCell,t));if(s!="horiz"&&!i.empty)return!1;const l=Mzt(a,s,t);if(l==null)return!1;if(s=="horiz")return H5e(n,r,Ol.near(n.doc.resolve(i.head+t),t));{const o=n.doc.resolve(l),c=Nzt(o,s,t);let d;return c?d=Ol.near(c,1):t<0?d=Ol.near(n.doc.resolve(o.before(-1)),-1):d=Ol.near(n.doc.resolve(o.after(-1)),1),H5e(n,r,d)}}}function Qoe(s,t){return(n,r,a)=>{if(!a)return!1;const i=n.selection;let l;if(i instanceof Rm)l=i;else{const c=Mzt(a,s,t);if(c==null)return!1;l=new Rm(n.doc.resolve(c))}const o=Nzt(l.$headCell,s,t);return o?H5e(n,r,new Rm(l.$anchorCell,o)):!1}}function FWs(s,t){const n=s.state.doc,r=P7(n.resolve(t));return r?(s.dispatch(s.state.tr.setSelection(new Rm(r))),!0):!1}function zWs(s,t,n){if(!jS(s.state))return!1;let r=LWs(n);const a=s.state.selection;if(a instanceof Rm){r||(r={width:1,height:1,rows:[Ba.from(H$e(u1(s.state.schema).cell,n))]});const i=a.$anchorCell.node(-1),l=a.$anchorCell.start(-1),o=tg.get(i).rectBetween(a.$anchorCell.pos-l,a.$headCell.pos-l);return r=RWs(r,o.right-o.left,o.bottom-o.top),_xt(s.state,s.dispatch,l,o,r),!0}else if(r){const i=CPe(s.state),l=i.start(-1);return _xt(s.state,s.dispatch,l,tg.get(i.node(-1)).findCell(i.pos-l),r),!0}else return!1}function BWs(s,t){var n;if(t.button!=0||t.ctrlKey||t.metaKey)return;const r=wxt(s,t.target);let a;if(t.shiftKey&&s.state.selection instanceof Rm)i(s.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&r&&(a=P7(s.state.selection.$anchor))!=null&&((n=CFe(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=CFe(s,d);const h=a6.getState(s.state)==null;if(!u||!PJe(c,u))if(h)u=c;else return;const m=new Rm(c,u);if(h||!s.state.selection.eq(m)){const p=s.state.tr.setSelection(m);h&&p.setMeta(a6,c.pos),s.dispatch(p)}}function l(){s.root.removeEventListener("mouseup",l),s.root.removeEventListener("dragstart",l),s.root.removeEventListener("mousemove",o),a6.getState(s.state)!=null&&s.dispatch(s.state.tr.setMeta(a6,-1))}function o(c){const d=c,u=a6.getState(s.state);let h;if(u!=null)h=s.state.doc.resolve(u);else if(wxt(s,d.target)!=r&&(h=CFe(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 Mzt(s,t,n){if(!(s.state.selection instanceof pl))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 wxt(s,t){for(;t&&t!=s.dom;t=t.parentNode)if(t.nodeName=="TD"||t.nodeName=="TH")return t;return null}function CFe(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&&P7(s.state.doc.resolve(r))||P7(s.state.doc.resolve(a))}var UWs=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")),G$e(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,G$e(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function G$e(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 $Ws(-1,!1)},apply(l,o){return o.apply(l)}},props:{attributes:l=>{const o=zw.getState(l);return o&&o.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(l,o)=>{VWs(l,o,s,a)},mouseleave:l=>{HWs(l)},mousedown:(l,o)=>{GWs(l,o,t,n)}},decorations:l=>{const o=zw.getState(l);if(o&&o.activeHandle>-1)return XWs(l,o.activeHandle)},nodeViews:{}}});return i}var $Ws=class G5e{constructor(t,n){this.activeHandle=t,this.dragging=n}apply(t){const n=this,r=t.getMeta(zw);if(r&&r.setHandle!=null)return new G5e(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new G5e(n.activeHandle,r.setDragging);if(n.activeHandle>-1&&t.docChanged){let a=t.mapping.map(n.activeHandle,-1);return V$e(t.doc.resolve(a))||(a=-1),new G5e(a,n.dragging)}return n}};function VWs(s,t,n,r){if(!s.editable)return;const a=zw.getState(s.state);if(a&&!a.dragging){const i=KWs(t.target);let l=-1;if(i){const{left:o,right:c}=i.getBoundingClientRect();t.clientX-o<=n?l=jxt(s,t,"left",n):c-t.clientX<=n&&(l=jxt(s,t,"right",n))}if(l!=a.activeHandle){if(!r&&l!==-1){const o=s.state.doc.resolve(l),c=o.node(-1),d=tg.get(c),u=o.start(-1);if(d.colCount(o.pos-u)+o.nodeAfter.attrs.colspan-1==d.width-1)return}Pzt(s,l)}}}function HWs(s){if(!s.editable)return;const t=zw.getState(s.state);t&&t.activeHandle>-1&&!t.dragging&&Pzt(s,-1)}function GWs(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=zw.getState(s.state);if(!l||l.activeHandle==-1||l.dragging)return!1;const o=s.state.doc.nodeAt(l.activeHandle),c=WWs(s,l.activeHandle,o.attrs);s.dispatch(s.state.tr.setMeta(zw,{setDragging:{startX:t.clientX,startWidth:c}}));function d(h){i.removeEventListener("mouseup",d),i.removeEventListener("mousemove",u);const m=zw.getState(s.state);m!=null&&m.dragging&&(YWs(s,m.activeHandle,Nxt(m.dragging,h,n)),s.dispatch(s.state.tr.setMeta(zw,{setDragging:null})))}function u(h){if(!h.which)return d(h);const m=zw.getState(s.state);if(m&&m.dragging){const p=Nxt(m.dragging,h,n);kxt(s,m.activeHandle,p,r)}}return kxt(s,l.activeHandle,c,r),i.addEventListener("mouseup",d),i.addEventListener("mousemove",u),t.preventDefault(),!0}function WWs(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 sKs(s,t,n,r,a){const i=tKs(s),l=[],o=[];for(let d=0;d{const{selection:t}=s.state;if(!nKs(t))return!1;let n=0;const r=nzt(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},rKs=fy.create({name:"table",addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:JWs,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}=eKs(s,this.options.cellMinWidth),i=["table",Dm(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=sKs(i.schema,s,t,n);if(a){const o=r.selection.from+1;r.replaceSelectionWith(l).scrollIntoView().setSelection(pl.near(r.doc.resolve(o)))}return!0},addColumnBefore:()=>({state:s,dispatch:t})=>xWs(s,t),addColumnAfter:()=>({state:s,dispatch:t})=>yWs(s,t),deleteColumn:()=>({state:s,dispatch:t})=>bWs(s,t),addRowBefore:()=>({state:s,dispatch:t})=>wWs(s,t),addRowAfter:()=>({state:s,dispatch:t})=>jWs(s,t),deleteRow:()=>({state:s,dispatch:t})=>kWs(s,t),deleteTable:()=>({state:s,dispatch:t})=>PWs(s,t),mergeCells:()=>({state:s,dispatch:t})=>fxt(s,t),splitCell:()=>({state:s,dispatch:t})=>gxt(s,t),toggleHeaderColumn:()=>({state:s,dispatch:t})=>Mee("column")(s,t),toggleHeaderRow:()=>({state:s,dispatch:t})=>Mee("row")(s,t),toggleHeaderCell:()=>({state:s,dispatch:t})=>TWs(s,t),mergeOrSplit:()=>({state:s,dispatch:t})=>fxt(s,t)?!0:gxt(s,t),setCellAttribute:(s,t)=>({state:n,dispatch:r})=>AWs(s,t)(n,r),goToNextCell:()=>({state:s,dispatch:t})=>yxt(1)(s,t),goToPreviousCell:()=>({state:s,dispatch:t})=>yxt(-1)(s,t),fixTables:()=>({state:s,dispatch:t})=>(t&&Azt(s),!0),setCellSelection:s=>({tr:t,dispatch:n})=>{if(n){const r=Rm.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:Joe,"Mod-Backspace":Joe,Delete:Joe,"Mod-Delete":Joe}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[qWs({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],QWs({allowTableNodeSelection:this.options.allowTableNodeSelection})]},extendNodeSchema(s){const t={name:s.name,options:s.options,storage:s.storage};return{tableRole:Lc(xo(s,"tableRole",t))}}}),aKs=fy.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:s}){return["tr",Dm(this.options.HTMLAttributes,s),0]}}),iKs=fy.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",Dm(this.options.HTMLAttributes,s),0]}}),oKs=fy.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",Dm(this.options.HTMLAttributes,s),0]}});function SN({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=wPe({extensions:[jPe,kPe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),SPe.configure({types:["heading","paragraph"]}),MJe,jzt.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}),rKs.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}),aKs.extend({addAttributes(){var x;return{...(x=this.parent)==null?void 0:x.call(this),style:{default:null}}}}),iKs.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}}}}),oKs.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 N of Array.from(v))if(N.type.startsWith("image/")){y.preventDefault();const S=N.getAsFile();if(!S)continue;const A=new FileReader;return A.onload=T=>{var M;const L=(M=T.target)==null?void 0:M.result;x.dispatch(x.state.tr.replaceSelectionWith(x.state.schema.nodes.image.create({src:L})))},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)},p=()=>{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(""))},f=()=>{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(U,{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(QU,{className:"h-4 w-4"})}),e.jsx(U,{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(AF,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleBold().run(),className:h.isActive("bold")?"bg-muted":"",title:"Bold",children:e.jsx(wA,{className:"h-4 w-4"})}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleItalic().run(),className:h.isActive("italic")?"bg-muted":"",title:"Italic",children:e.jsx(kA,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleBulletList().run(),className:h.isActive("bulletList")?"bg-muted":"",title:"Bullet List",children:e.jsx(m0,{className:"h-4 w-4"})}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleOrderedList().run(),className:h.isActive("orderedList")?"bg-muted":"",title:"Numbered List",children:e.jsx(sj,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(U,{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(_M,{className:"h-4 w-4"})}),e.jsx(U,{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(bM,{className:"h-4 w-4"})}),e.jsx(U,{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(wM,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:m,className:h.isActive("link")?"bg-muted":"",title:"Add Link",children:e.jsx(Rc,{className:"h-4 w-4"})}),h.isActive("link")&&e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:f,title:"Remove Link",children:e.jsx(Rc,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().undo().run(),disabled:!h.can().undo(),title:"Undo",children:e.jsx(RA,{className:"h-4 w-4"})}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().redo().run(),disabled:!h.can().redo(),title:"Redo",children:e.jsx(LA,{className:"h-4 w-4"})})]}),e.jsx(_Pe,{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(Ds,{className:"sm:max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Insert Link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"link-url",children:"URL"}),e.jsx(xe,{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(wn,{id:"link-new-tab",checked:d,onCheckedChange:u}),e.jsx(te,{htmlFor:"link-new-tab",children:"Open in new tab"})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(U,{type:"button",onClick:p,children:o?"Apply Link":"Remove Link"})]})]})})]}):null}var lKs=Object.defineProperty,cKs=(s,t,n)=>t in s?lKs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,Mp=(s,t,n)=>cKs(s,typeof t!="symbol"?t+"":t,n);const vAe={x:0,y:0,width:0,height:0,unit:"px"},Kz=(s,t,n)=>Math.min(Math.max(s,t),n),dKs=(...s)=>s.filter(t=>t&&typeof t=="string").join(" "),Axt=(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 uKs(s,t,n,r){const a=A5(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==="%"?WT(a,n,r):a}function hKs(s,t,n){const r=A5(s,t,n);return r.x=(t-r.width)/2,r.y=(n-r.height)/2,s.unit==="%"?WT(r,t,n):r}function WT(s,t,n){return s.unit==="%"?{...vAe,...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 A5(s,t,n){return s.unit?s.unit==="px"?{...vAe,...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}:{...vAe,...s,unit:"px"}}function Ext(s,t,n,r,a,i=0,l=0,o=r,c=a){const d={...s};let u=Math.min(i,r),h=Math.min(l,a),m=Math.min(o,r),p=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,p=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);const f=r-(d.x+d.width);f<0&&(d.x=Math.min(d.x,r-u),d.width+=f);const 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>p&&((n==="nw"||n=="ne")&&(d.y-=p-d.height),d.height=p),t){const y=d.width/d.height;if(yt){const v=Math.max(d.height*t,u);(n==="sw"||n=="nw")&&(d.x-=v-d.width),d.width=v}}return d}function mKs(s,t,n,r){const 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}const Yz={capture:!0,passive:!1};let pKs=0;const AT=class ik extends j.PureComponent{constructor(){super(...arguments),Mp(this,"docMoveBound",!1),Mp(this,"mouseDownOnCrop",!1),Mp(this,"dragStarted",!1),Mp(this,"evData",{startClientX:0,startClientY:0,startCropX:0,startCropY:0,clientX:0,clientY:0,isResize:!0}),Mp(this,"componentRef",j.createRef()),Mp(this,"mediaRef",j.createRef()),Mp(this,"resizeObserver"),Mp(this,"initChangeCalled",!1),Mp(this,"instanceId",`rc-${pKs++}`),Mp(this,"state",{cropIsActive:!1,newCropIsBeingDrawn:!1}),Mp(this,"onCropPointerDown",t=>{const{crop:n,disabled:r}=this.props,a=this.getBox();if(!n)return;const i=A5(n,a.width,a.height);if(r)return;t.cancelable&&t.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});const l=t.target.dataset.ord,o=!!l;let c=t.clientX,d=t.clientY,u=i.x,h=i.y;if(l){const m=t.clientX-a.x,p=t.clientY-a.y;let f=0,x=0;l==="ne"||l=="e"?(f=m-(i.x+i.width),x=p-i.y,u=i.x,h=i.y+i.height):l==="se"||l==="s"?(f=m-(i.x+i.width),x=p-(i.y+i.height),u=i.x,h=i.y):l==="sw"||l=="w"?(f=m-i.x,x=p-(i.y+i.height),u=i.x+i.width,h=i.y):(l==="nw"||l=="n")&&(f=m-i.x,x=p-i.y,u=i.x+i.width,h=i.y+i.height),c=u+a.x+f,d=h+a.y+x}this.evData={startClientX:c,startClientY:d,startCropX:u,startCropY:h,clientX:t.clientX,clientY:t.clientY,isResize:o,ord:l},this.mouseDownOnCrop=!0,this.setState({cropIsActive:!0})}),Mp(this,"onComponentPointerDown",t=>{const{crop:n,disabled:r,locked:a,keepSelection:i,onChange:l}=this.props,o=this.getBox();if(r||a||i&&n)return;t.cancelable&&t.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});const c=t.clientX-o.x,d=t.clientY-o.y,u={unit:"px",x:c,y:d,width:0,height:0};this.evData={startClientX:t.clientX,startClientY:t.clientY,startCropX:c,startCropY:d,clientX:t.clientX,clientY:t.clientY,isResize:!0},this.mouseDownOnCrop=!0,l(A5(u,o.width,o.height),WT(u,o.width,o.height)),this.setState({cropIsActive:!0,newCropIsBeingDrawn:!0})}),Mp(this,"onDocPointerMove",t=>{const{crop:n,disabled:r,onChange:a,onDragStart:i}=this.props,l=this.getBox();if(r||!n||!this.mouseDownOnCrop)return;t.cancelable&&t.preventDefault(),this.dragStarted||(this.dragStarted=!0,i&&i(t));const{evData:o}=this;o.clientX=t.clientX,o.clientY=t.clientY;let c;o.isResize?c=this.resizeCrop():c=this.dragCrop(),Axt(n,c)||a(A5(c,l.width,l.height),WT(c,l.width,l.height))}),Mp(this,"onComponentKeyDown",t=>{const{crop:n,disabled:r,onChange:a,onComplete:i}=this.props;if(r)return;const l=t.key;let o=!1;if(!n)return;const c=this.getBox(),d=this.makePixelCrop(c),u=(navigator.platform.match("Mac")?t.metaKey:t.ctrlKey)?ik.nudgeStepLarge:t.shiftKey?ik.nudgeStepMedium:ik.nudgeStep;if(l==="ArrowLeft"?(d.x-=u,o=!0):l==="ArrowRight"?(d.x+=u,o=!0):l==="ArrowUp"?(d.y-=u,o=!0):l==="ArrowDown"&&(d.y+=u,o=!0),o){t.cancelable&&t.preventDefault(),d.x=Kz(d.x,0,c.width-d.width),d.y=Kz(d.y,0,c.height-d.height);const h=A5(d,c.width,c.height),m=WT(d,c.width,c.height);a(h,m),i&&i(h,m)}}),Mp(this,"onHandlerKeyDown",(t,n)=>{const{aspect:r=0,crop:a,disabled:i,minWidth:l=0,minHeight:o=0,maxWidth:c,maxHeight:d,onChange:u,onComplete:h}=this.props,m=this.getBox();if(i||!a)return;if(t.key==="ArrowUp"||t.key==="ArrowDown"||t.key==="ArrowLeft"||t.key==="ArrowRight")t.stopPropagation(),t.preventDefault();else return;const p=(navigator.platform.match("Mac")?t.metaKey:t.ctrlKey)?ik.nudgeStepLarge:t.shiftKey?ik.nudgeStepMedium:ik.nudgeStep,f=A5(a,m.width,m.height),x=mKs(f,t.key,p,n),y=Ext(x,r,n,m.width,m.height,l,o,c,d);if(!Axt(a,y)){const v=WT(y,m.width,m.height);u(y,v),h&&h(y,v)}}),Mp(this,"onDocPointerDone",t=>{const{crop:n,disabled:r,onComplete:a,onDragEnd:i}=this.props,l=this.getBox();this.unbindDocMove(),!(r||!n)&&this.mouseDownOnCrop&&(this.mouseDownOnCrop=!1,this.dragStarted=!1,i&&i(t),a&&a(A5(n,l.width,l.height),WT(n,l.width,l.height)),this.setState({cropIsActive:!1,newCropIsBeingDrawn:!1}))}),Mp(this,"onDragFocus",()=>{var t;(t=this.componentRef.current)==null||t.scrollTo(0,0)})}get document(){return document}getBox(){const t=this.mediaRef.current;if(!t)return{x:0,y:0,width:0,height:0};const{x:n,y:r,width:a,height:i}=t.getBoundingClientRect();return{x:n,y:r,width:a,height:i}}componentDidUpdate(t){const{crop:n,onComplete:r}=this.props;if(r&&!t.crop&&n){const{width:a,height:i}=this.getBox();a&&i&&r(A5(n,a,i),WT(n,a,i))}}componentWillUnmount(){this.resizeObserver&&this.resizeObserver.disconnect(),this.unbindDocMove()}bindDocMove(){this.docMoveBound||(this.document.addEventListener("pointermove",this.onDocPointerMove,Yz),this.document.addEventListener("pointerup",this.onDocPointerDone,Yz),this.document.addEventListener("pointercancel",this.onDocPointerDone,Yz),this.docMoveBound=!0)}unbindDocMove(){this.docMoveBound&&(this.document.removeEventListener("pointermove",this.onDocPointerMove,Yz),this.document.removeEventListener("pointerup",this.onDocPointerDone,Yz),this.document.removeEventListener("pointercancel",this.onDocPointerDone,Yz),this.docMoveBound=!1)}getCropStyle(){const{crop:t}=this.props;if(t)return{top:`${t.y}${t.unit}`,left:`${t.x}${t.unit}`,width:`${t.width}${t.unit}`,height:`${t.height}${t.unit}`}}dragCrop(){const{evData:t}=this,n=this.getBox(),r=this.makePixelCrop(n),a=t.clientX-t.startClientX,i=t.clientY-t.startClientY;return r.x=Kz(t.startCropX+a,0,n.width-r.width),r.y=Kz(t.startCropY+i,0,n.height-r.height),r}getPointRegion(t,n,r,a){const{evData:i}=this,l=i.clientX-t.x,o=i.clientY-t.y;let c;a&&n?c=n==="nw"||n==="n"||n==="ne":c=o1?i?[i,i/n]:[l*n,l]:l?[l*n,l]:[i,i/n]}resizeCrop(){const{evData:t}=this,{aspect:n=0,maxWidth:r,maxHeight:a}=this.props,i=this.getBox(),[l,o]=this.resolveMinDimensions(i,n,this.props.minWidth,this.props.minHeight);let c=this.makePixelCrop(i);const d=this.getPointRegion(i,t.ord,l,o),u=t.ord||d;let h=t.clientX-t.startClientX,m=t.clientY-t.startClientY;(l&&u==="nw"||u==="w"||u==="sw")&&(h=Math.min(h,-l)),(o&&u==="nw"||u==="n"||u==="ne")&&(m=Math.min(m,-o));const p={unit:"px",x:0,y:0,width:0,height:0};d==="ne"?(p.x=t.startCropX,p.width=h,n?(p.height=p.width/n,p.y=t.startCropY-p.height):(p.height=Math.abs(m),p.y=t.startCropY-p.height)):d==="se"?(p.x=t.startCropX,p.y=t.startCropY,p.width=h,n?p.height=p.width/n:p.height=m):d==="sw"?(p.x=t.startCropX+h,p.y=t.startCropY,p.width=Math.abs(h),n?p.height=p.width/n:p.height=m):d==="nw"&&(p.x=t.startCropX+h,p.width=Math.abs(h),n?(p.height=p.width/n,p.y=t.startCropY-p.height):(p.height=Math.abs(m),p.y=t.startCropY+m));const f=Ext(p,n,d,i.width,i.height,l,o,r,a);return n||ik.xyOrds.indexOf(u)>-1?c=f:ik.xOrds.indexOf(u)>-1?(c.x=f.x,c.width=f.width):ik.yOrds.indexOf(u)>-1&&(c.y=f.y,c.height=f.height),c.x=Kz(c.x,0,i.width-c.width),c.y=Kz(c.y,0,i.height-c.height),c}renderCropSelection(){const{ariaLabels:t=ik.defaultProps.ariaLabels,disabled:n,locked:r,renderSelectionAddon:a,ruleOfThirds:i,crop:l}=this.props,o=this.getCropStyle();if(l)return Dt.createElement("div",{style:o,className:"ReactCrop__crop-selection",onPointerDown:this.onCropPointerDown,"aria-label":t.cropArea,tabIndex:0,onKeyDown:this.onComponentKeyDown,role:"group"},!n&&!r&&Dt.createElement("div",{className:"ReactCrop__drag-elements",onFocus:this.onDragFocus},Dt.createElement("div",{className:"ReactCrop__drag-bar ord-n","data-ord":"n"}),Dt.createElement("div",{className:"ReactCrop__drag-bar ord-e","data-ord":"e"}),Dt.createElement("div",{className:"ReactCrop__drag-bar ord-s","data-ord":"s"}),Dt.createElement("div",{className:"ReactCrop__drag-bar ord-w","data-ord":"w"}),Dt.createElement("div",{className:"ReactCrop__drag-handle ord-nw","data-ord":"nw",tabIndex:0,"aria-label":t.nwDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"nw"),role:"button"}),Dt.createElement("div",{className:"ReactCrop__drag-handle ord-n","data-ord":"n",tabIndex:0,"aria-label":t.nDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"n"),role:"button"}),Dt.createElement("div",{className:"ReactCrop__drag-handle ord-ne","data-ord":"ne",tabIndex:0,"aria-label":t.neDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"ne"),role:"button"}),Dt.createElement("div",{className:"ReactCrop__drag-handle ord-e","data-ord":"e",tabIndex:0,"aria-label":t.eDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"e"),role:"button"}),Dt.createElement("div",{className:"ReactCrop__drag-handle ord-se","data-ord":"se",tabIndex:0,"aria-label":t.seDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"se"),role:"button"}),Dt.createElement("div",{className:"ReactCrop__drag-handle ord-s","data-ord":"s",tabIndex:0,"aria-label":t.sDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"s"),role:"button"}),Dt.createElement("div",{className:"ReactCrop__drag-handle ord-sw","data-ord":"sw",tabIndex:0,"aria-label":t.swDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"sw"),role:"button"}),Dt.createElement("div",{className:"ReactCrop__drag-handle ord-w","data-ord":"w",tabIndex:0,"aria-label":t.wDragHandle,onKeyDown:c=>this.onHandlerKeyDown(c,"w"),role:"button"})),a&&Dt.createElement("div",{className:"ReactCrop__selection-addon",onPointerDown:c=>c.stopPropagation()},a(this.state)),i&&Dt.createElement(Dt.Fragment,null,Dt.createElement("div",{className:"ReactCrop__rule-of-thirds-hz"}),Dt.createElement("div",{className:"ReactCrop__rule-of-thirds-vt"})))}makePixelCrop(t){const n={...vAe,...this.props.crop||{}};return A5(n,t.width,t.height)}render(){const{aspect:t,children:n,circularCrop:r,className:a,crop:i,disabled:l,locked:o,style:c,ruleOfThirds:d}=this.props,{cropIsActive:u,newCropIsBeingDrawn:h}=this.state,m=i?this.renderCropSelection():null,p=dKs("ReactCrop",a,u&&"ReactCrop--active",l&&"ReactCrop--disabled",o&&"ReactCrop--locked",h&&"ReactCrop--new-crop",i&&t&&"ReactCrop--fixed-aspect",i&&r&&"ReactCrop--circular-crop",i&&d&&"ReactCrop--rule-of-thirds",!this.dragStarted&&i&&!i.width&&!i.height&&"ReactCrop--invisible-crop",r&&"ReactCrop--no-animate");return Dt.createElement("div",{ref:this.componentRef,className:p,style:c},Dt.createElement("div",{ref:this.mediaRef,className:"ReactCrop__child-wrapper",onPointerDown:this.onComponentPointerDown},n),i?Dt.createElement("svg",{className:"ReactCrop__crop-mask",width:"100%",height:"100%"},Dt.createElement("defs",null,Dt.createElement("mask",{id:`hole-${this.instanceId}`},Dt.createElement("rect",{width:"100%",height:"100%",fill:"white"}),r?Dt.createElement("ellipse",{cx:`${i.x+i.width/2}${i.unit}`,cy:`${i.y+i.height/2}${i.unit}`,rx:`${i.width/2}${i.unit}`,ry:`${i.height/2}${i.unit}`,fill:"black"}):Dt.createElement("rect",{x:`${i.x}${i.unit}`,y:`${i.y}${i.unit}`,width:`${i.width}${i.unit}`,height:`${i.height}${i.unit}`,fill:"black"}))),Dt.createElement("rect",{fill:"black",fillOpacity:.5,width:"100%",height:"100%",mask:`url(#hole-${this.instanceId})`})):void 0,m)}};Mp(AT,"xOrds",["e","w"]),Mp(AT,"yOrds",["n","s"]),Mp(AT,"xyOrds",["nw","ne","se","sw"]),Mp(AT,"nudgeStep",1),Mp(AT,"nudgeStepMedium",10),Mp(AT,"nudgeStepLarge",100),Mp(AT,"defaultProps",{ariaLabels:{cropArea:"Use the arrow keys to move the crop selection area",nwDragHandle:"Use the arrow keys to move the north west drag handle to change the crop selection area",nDragHandle:"Use the up and down arrow keys to move the north drag handle to change the crop selection area",neDragHandle:"Use the arrow keys to move the north east drag handle to change the crop selection area",eDragHandle:"Use the up and down arrow keys to move the east drag handle to change the crop selection area",seDragHandle:"Use the arrow keys to move the south east drag handle to change the crop selection area",sDragHandle:"Use the up and down arrow keys to move the south drag handle to change the crop selection area",swDragHandle:"Use the arrow keys to move the south west drag handle to change the crop selection area",wDragHandle:"Use the up and down arrow keys to move the west drag handle to change the crop selection area"}});let fKs=AT;function gKs(s,t,n){return hKs(uKs({unit:"%",width:90},n,s,t),s,t)}const LJe=({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,p]=j.useState(0),f=j.useCallback(v=>{const{width:b,height:N}=v.currentTarget;o(gKs(b,N,a))},[a]),x=j.useCallback(async()=>{const v=i.current;if(!v||!c)return;const b=document.createElement("canvas"),N=b.getContext("2d");if(!N)return;const S=v.naturalWidth/v.width,A=v.naturalHeight/v.height,T=400;b.width=T,b.height=T,N.imageSmoothingQuality="high";const L=c.x*S,M=c.y*A,I=c.width*S,R=c.height*A,z=m*Math.PI/180,$=b.width/2,H=b.height/2;return N.save(),N.translate($,H),N.rotate(z),N.scale(u,u),N.translate(-$,-H),N.drawImage(v,L,M,I,R,0,0,T,T),N.restore(),new Promise((V,K)=>{b.toBlob(Z=>{Z?V(Z):K(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(Ds,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Crop Your Photo"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"relative max-h-[400px] overflow-hidden rounded-lg bg-muted flex items-center justify-center",children:e.jsx(fKs,{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:f})})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Cq,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(rg,{value:[u],min:.5,max:3,step:.1,onValueChange:([v])=>h(v),className:"flex-1"}),e.jsx(OM,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(RF,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(rg,{value:[m],min:-180,max:180,step:1,onValueChange:([v])=>p(v),className:"flex-1"}),e.jsxs("span",{className:"text-sm text-muted-foreground w-12",children:[m,"°"]})]})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx(U,{onClick:y,children:"Save Photo"})]})]})})},Txt="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 xKs(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 yKs(){const{user:s}=vs(),{toast:t}=Ai(),[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,p]=j.useState(null),[f,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(),N=b;N&&(o(N.phone_e164||N.phone||""),h(!!N.sms_consent),d(!!N.sms_consent),p(N.sms_consent_at||null)),r(!1)})()},[s==null?void 0:s.id]);const y=async()=>{const b=xKs(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:N}=await q.from("profiles").update({phone_e164:b,sms_consent:!0,sms_consent_at:new Date().toISOString(),sms_consent_text:Txt,sms_consent_source:"profile_page",sms_opted_out_at:null}).eq("id",s.id);if(i(!1),N){t({title:"Error",description:N.message,variant:"destructive"});return}h(!0),p(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(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Ki,{className:"h-5 w-5"}),"Text Message (SMS) Alerts",u&&e.jsx(Be,{variant:"secondary",children:"Opted in"})]}),e.jsx(Jn,{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(Et,{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(te,{htmlFor:"sms-mobile",children:"Mobile Number (optional)"}),e.jsx(xe,{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(xi,{id:"sms-consent",checked:c,onCheckedChange:b=>d(b===!0),disabled:u,className:"mt-0.5"}),e.jsx(te,{htmlFor:"sms-consent",className:"text-sm font-normal leading-relaxed cursor-pointer",children:Txt})]})}),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"}),"."]}),f&&!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(U,{onClick:y,disabled:a||u&&!l,children:[a&&e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}),u?"Update Number":"Opt in to SMS"]}),u?e.jsx(U,{variant:"outline",onClick:v,disabled:a,children:"Opt out"}):e.jsx(U,{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 Mxt="#2a4c64",Pxt="#B8965A",Lxt="Inter",Ixt="Inter";function UB(s){if(typeof s!="string")return null;const t=s.trim();return t.length?t:null}function Kb(s,t=null){for(const[n,r]of s){const a=UB(r);if(a)return{value:a,source:n}}return{value:t,source:"default"}}function vKs(s){const t=s.agent??{},n=s.brokerage??{},r=s.legacy??{},a=!!n.lock_colors,i=!!n.lock_logo,l=(T,L,M)=>a?[["brokerage",L],["agent",T],["legacy",M]]:[["agent",T],["brokerage",L],["legacy",M]],o=Kb(l(t.brand_color,n.primary_color,r.brand_color),Mxt),c=Kb(l(t.accent_color,n.accent_color,r.accent_color),Pxt),d=Kb([["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=Kb(u),m=Kb([["brokerage",n.logo_url],["legacy",r.brokerage_logo_url]]),p=Kb([["agent",t.headshot_url],["legacy",r.avatar_url]]),f=Kb([["agent",t.tagline],["legacy",r.tagline||r.title]]),x=Kb([["agent",t.preferred_font],["brokerage",n.heading_font]],Lxt),y=Kb([["brokerage",n.body_font]],Ixt),v=Kb([["agent",t.license_number],["legacy",r.license_number]]),b=Kb([["agent",t.license_state],["legacy",r.license_state],["brokerage",n.license_state]]),N=Kb([["agent",t.website_url],["legacy",r.website_url]]),S=Kb([["brokerage",n.legal_name],["legacy",r.brokerage_name]]),A=Kb([["brokerage",n.compliance_line]]);return{agent_name:UB(r.name),brokerage_name:S.value,brand_color:o.value??Mxt,secondary_color:d.value,accent_color:c.value??Pxt,heading_font:x.value??Lxt,body_font:y.value??Ixt,logo_url:h.value,logo_dark_url:UB(n.logo_dark_url),brokerage_logo_url:m.value,icon_mark_url:UB(n.icon_mark_url),headshot_url:p.value,tagline:f.value,license_number:v.value,license_state:b.value,website_url:N.value,email:UB(r.email),phone:UB(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:p.source,tagline:f.source,heading_font:x.source,body_font:y.source,license_number:v.source,license_state:b.source,website_url:N.source,brokerage_name:S.source,compliance_line:A.source}}}function bKs(){const{user:s}=vs();return ct({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 _Ks(){const{user:s}=vs(),t=Qt();return yt({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 wKs(s){return ct({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 jKs(s){const{user:t}=vs(),n=Qt();return yt({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 NKs(){const{user:s}=vs();return ct({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(p=>p.is_active)??c[0]??{};let u=null,h=null;if(l.brokerage_id){const[p,f]=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=p.data??null,h=((m=f.data)==null?void 0:m.name)??null}return vKs({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 Lzt(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 kKs=["Inter","Playfair Display","Montserrat","Poppins","Lora","Work Sans"];function SKs(){const{user:s}=vs(),{toast:t}=Ai(),{data:n,isLoading:r}=bKs(),{data:a}=NKs(),i=_Ks(),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),p=(y,v)=>u(b=>({...b,[y]:v})),f=async y=>{if(s){c(!0);try{const v=await Lzt(s.id,y,"logo");p("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(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx($c,{className:"h-5 w-5"}),"Brand Kit"]}),e.jsx(Jn,{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(Et,{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(te,{className:"flex items-center gap-2",children:["Brand color",h&&e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Ql,{className:"h-3 w-3"})," Set by brokerage"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{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=>p("brand_color",y.target.value)}),e.jsx(xe,{value:d.brand_color,placeholder:(a==null?void 0:a.brand_color)||"#2a4c64",disabled:h,onChange:y=>p("brand_color",y.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Accent color"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{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=>p("accent_color",y.target.value)}),e.jsx(xe,{value:d.accent_color,placeholder:(a==null?void 0:a.accent_color)||"#B8965A",disabled:h,onChange:y=>p("accent_color",y.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{className:"flex items-center gap-2",children:["Personal / team logo",m&&e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Ql,{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])&&f(y.target.files[0])}}),e.jsxs(U,{type:"button",variant:"outline",disabled:o||m,onClick:()=>{var y;return(y=l.current)==null?void 0:y.click()},children:[o?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(qa,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Upload logo"})]}),d.logo_url&&e.jsx(U,{type:"button",variant:"ghost",onClick:()=>p("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(te,{htmlFor:"brand-tagline",children:"Tagline"}),e.jsx(xe,{id:"brand-tagline",value:d.tagline,placeholder:(a==null?void 0:a.tagline)||"Your positioning statement",onChange:y=>p("tagline",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"brand-font",children:"Preferred font"}),e.jsx(xe,{id:"brand-font",list:"brand-font-options",value:d.preferred_font,placeholder:(a==null?void 0:a.heading_font)||"Inter",onChange:y=>p("preferred_font",y.target.value)}),e.jsx("datalist",{id:"brand-font-options",children:kKs.map(y=>e.jsx("option",{value:y},y))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"brand-license",children:"License number"}),e.jsx(xe,{id:"brand-license",value:d.license_number,placeholder:(a==null?void 0:a.license_number)||"DRE #01234567",onChange:y=>p("license_number",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"brand-license-state",children:"License state"}),e.jsx(xe,{id:"brand-license-state",value:d.license_state,placeholder:(a==null?void 0:a.license_state)||"CA",onChange:y=>p("license_state",y.target.value)})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(te,{htmlFor:"brand-website",children:"Website"}),e.jsx(xe,{id:"brand-website",value:d.website_url,placeholder:(a==null?void 0:a.website_url)||"https://yoursite.com",onChange:y=>p("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(U,{onClick:x,disabled:i.isPending,children:[i.isPending?e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ho,{className:"mr-2 h-4 w-4"}),"Save brand kit"]})]})})]})}const AFe="id, name, address, notes, created_at, locked_style, share_token, share_enabled, share_headline, share_message, share_views";function Dgr(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 CKs(){var o,c,d;const{user:s}=vs(),t=Qt(),n=ct({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 Ogr(){return ct({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 Fgr(){const{user:s}=vs(),t=Qt(),n=ct({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(AFe).eq("user_id",s.id).order("created_at",{ascending:!1});if(c)throw c;return o??[]}}),r=yt({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(AFe).single();if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:["staging-projects"]})}),a=yt({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=yt({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=yt({mutationFn:async o=>{const{id:c,...d}=o,{data:u,error:h}=await q.from("staging_projects").update(d).eq("id",c).select(AFe).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 zgr(){return yt({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 Bgr(s){const{user:t}=vs(),n=Qt(),r=ct({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=yt({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=yt({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=yt({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 Ugr(){const s=Qt();return yt({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 qgr(s){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=n,r.readAsDataURL(s)})}function AKs(){try{return window.open("","_blank")}catch{return null}}function EKs(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 TKs(s){try{s&&!s.closed&&s.close()}catch{}}async function MKs(s,t){if(s instanceof Rne)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 PKs(){var i;const s=CKs(),[t,n]=j.useState(!1);if(s.isLoading||!s.legacyPlan)return null;const r=s.unlimited&&s.unlimitedReason==="plan",a=async()=>{if(t)return;const l=AKs();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");EKs(l,o.url)}catch(o){TKs(l);const c=await MKs(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(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(cn,{className:"h-5 w-5"}),"Staging Studio Subscription"]}),e.jsx(Jn,{children:"Manage the plan that powers your AI photo staging credits"})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(Be,{variant:r?"default":"secondary",children:[s.legacyPlan," plan"]}),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(U,{variant:"outline",size:"sm",onClick:a,disabled:t,children:[t?e.jsx(Et,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"}):e.jsx(oy,{className:"mr-1.5 h-3.5 w-3.5"}),"Manage billing"]}),e.jsx(U,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs(xr,{to:"/apps/staging-studio/credits",children:["Credits & history ",e.jsx(Sr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Cancel, update your card or change plans in the Stripe billing portal. Changes apply to your Staging Studio credits here automatically."})]})]})}const Rxt=["image/png","image/jpeg","image/jpg","image/svg+xml","image/webp"],LKs=5*1024*1024;function IKs({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 f=>{if(!Rxt.includes(f.type)){re.error("Please upload a PNG, JPG, SVG or WebP file");return}if(f.size>LKs){re.error("Please choose a logo under 5MB");return}d(!0);try{const x=(f.name.split(".").pop()||"png").toLowerCase(),y=`${s}/brokerage-logo-${Date.now()}.${x}`,{error:v}=await q.storage.from("card-logos").upload(y,f,{cacheControl:"3600",upsert:!0,contentType:f.type});if(v)throw v;const{data:b}=q.storage.from("card-logos").getPublicUrl(y),N=b.publicUrl;r&&await q.from("profiles").update({brokerage_logo_url:N}).eq("id",s),n(N),re.success("Brokerage logo uploaded")}catch(x){re.error((x==null?void 0:x.message)||"Upload failed")}finally{d(!1)}},p=async()=>{r&&await q.from("profiles").update({brokerage_logo_url:null}).eq("id",s),n(null)};return e.jsxs("div",{className:Mt("space-y-2",l),children:[e.jsx(te,{children:a}),e.jsxs("div",{onDragOver:f=>{f.preventDefault(),h(!0)},onDragLeave:()=>h(!1),onDrop:f=>{var y;f.preventDefault(),h(!1);const x=(y=f.dataTransfer.files)==null?void 0:y[0];x&&m(x)},onClick:()=>{var f;return!c&&((f=o.current)==null?void 0:f.click())},className:Mt("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(_i,{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(U,{type:"button",variant:"outline",size:"sm",disabled:c,onClick:f=>{var x;f.stopPropagation(),(x=o.current)==null||x.click()},children:[c?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(qa,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:t?"Replace":"Upload"})]}),t&&!c&&e.jsx(U,{type:"button",variant:"ghost",size:"icon",onClick:f=>{f.stopPropagation(),p()},children:e.jsx(In,{className:"h-4 w-4 text-muted-foreground"})})]})]}),e.jsx("input",{ref:o,type:"file",accept:Rxt.join(","),className:"hidden",onChange:f=>{var y;const x=(y=f.target.files)==null?void 0:y[0];x&&m(x),f.target.value=""}})]})}const RKs=()=>{const{user:s}=vs(),{toast:t}=Ai(),[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:p}=await q.functions.invoke("customer-portal",{headers:{Authorization:`Bearer ${h.access_token}`}});if(p)throw p;m!=null&&m.url&&window.open(m.url,"_blank")}catch(h){console.error("Error opening customer portal:",h),t({title:"Error",description:h.message||"Failed to open billing portal",variant:"destructive"})}finally{i(!1)}},u=()=>{if(l!=null&&l.isGrandfathered)return e.jsx(Be,{className:"bg-amber-500",children:"Grandfathered"});switch(l==null?void 0:l.status){case"active":return e.jsx(Be,{className:"bg-green-500",children:"Active"});case"trialing":return e.jsx(Be,{className:"bg-blue-500",children:"Trial"});case"past_due":return e.jsx(Be,{variant:"destructive",children:"Past Due"});case"canceled":return e.jsx(Be,{variant:"secondary",children:"Canceled"});default:return e.jsx(Be,{variant:"outline",children:"No Subscription"})}};return n?e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(oy,{className:"h-5 w-5"}),"Subscription"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Et,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(oy,{className:"h-5 w-5"}),"Subscription"]}),e.jsx(Jn,{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 account was upgraded from LevelUp 1.0. To update/manage your subscription please reach out to support."}):(l==null?void 0:l.status)==="active"||(l==null?void 0:l.status)==="trialing"?e.jsxs(e.Fragment,{children:[(l==null?void 0:l.status)==="trialing"&&(l==null?void 0:l.endDate)&&e.jsxs("p",{className:"text-sm text-muted-foreground mb-3",children:["Your trial ends on ",new Date(l.endDate).toLocaleDateString(),". After the trial, you'll be charged automatically."]}),e.jsxs(U,{onClick:d,variant:"outline",disabled:a,children:[a?e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Sr,{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."})]})]})},DKs=()=>{const{user:s}=vs(),t=Wn(),{toast:n}=Ai(),[r]=fc(),a=r.get("setup")==="true",i=r.get("reset")==="true",{isSupported:l,isSubscribed:o,isLoading:c,subscribe:d,unsubscribe:u}=C8t(),[h,m]=j.useState(!1),[p,f]=j.useState(""),[x,y]=j.useState(null),[v,b]=j.useState(!1),[N,S]=j.useState(!1),[A,T]=j.useState(""),[L,M]=j.useState({name:"",email:"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",brokerage_name:"",instagram_url:"",facebook_url:"",linkedin_url:"",email_signature:"",use_email_signature:!1}),[I,R]=j.useState(!1),[z,$]=j.useState(!1),[H,V]=j.useState(!1),[K,Z]=j.useState(!1),[Q,le]=j.useState(!1),[ue,se]=j.useState({newPassword:"",confirmPassword:""});j.useEffect(()=>{s&&ne()},[s]),j.useEffect(()=>{i&&s&&setTimeout(()=>{var he;(he=document.getElementById("change-password-section"))==null||he.scrollIntoView({behavior:"smooth",block:"center"})},500)},[i,s]);const ne=async()=>{var he,ge,ke,Te;if(!(s!=null&&s.id)){console.log("No user ID available yet");return}try{console.log("Loading profile for user:",s.id);const{data:Me,error:Oe}=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, email_signature, use_email_signature, brokerages(name)").eq("id",s.id).maybeSingle();if(Oe)throw console.error("Profile query error:",Oe),Oe;if(Me){console.log("Profile loaded successfully:",Me);const Qe=((he=Me.brokerages)==null?void 0:he.name)||"";R(!!Me.brokerage_id),M({name:Me.name||"",email:Me.email||"",phone:Me.phone||"",title:Me.title||"",bio:Me.bio||"",areas_served:Me.areas_served||"",years_experience:((ge=Me.years_experience)==null?void 0:ge.toString())||"",brokerage_name:Me.brokerage_id?Qe:Me.brokerage_name||"",instagram_url:Me.instagram_url||"",facebook_url:Me.facebook_url||"",linkedin_url:Me.linkedin_url||"",email_signature:Me.email_signature||"",use_email_signature:Me.use_email_signature||!1}),$(Me.digest_opt_out||!1),Z(Me.event_invite_opt_out||!1),y(Me.brokerage_logo_url||null)}else console.warn("No profile found for user"),M({name:((ke=s.user_metadata)==null?void 0:ke.name)||((Te=s.email)==null?void 0:Te.split("@")[0])||"",email:s.email||"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",brokerage_name:"",instagram_url:"",facebook_url:"",linkedin_url:"",email_signature:"",use_email_signature:!1});const{data:Se}=await q.storage.from("avatars").list(`${s.id}`);if(Se&&Se.length>0){const{data:Qe}=q.storage.from("avatars").getPublicUrl(`${s.id}/${Se[0].name}`);f(Qe.publicUrl)}}catch(Me){console.error("Error loading profile:",Me),n({title:"Error",description:Me.message||"Failed to load profile",variant:"destructive"})}},ie=he=>{var Te;const ge=(Te=he.target.files)==null?void 0:Te[0];if(!ge)return;const ke=new FileReader;ke.onloadend=()=>{T(ke.result),S(!0)},ke.readAsDataURL(ge),he.target.value=""},ce=async he=>{if(s){b(!0);try{const{data:ge}=await q.storage.from("avatars").list(`${s.id}`),ke=(ge??[]).filter(Ae=>/^avatar[.-]/i.test(Ae.name));ke.length>0&&await q.storage.from("avatars").remove(ke.map(Ae=>`${s.id}/${Ae.name}`));const Me=`${s.id}/avatar.jpg`,{error:Oe}=await q.storage.from("avatars").upload(Me,he,{upsert:!0,contentType:"image/jpeg"});if(Oe)throw Oe;const{data:Se}=q.storage.from("avatars").getPublicUrl(Me),Qe=Se.publicUrl;f(`${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(ge){console.error("Error uploading avatar:",ge),n({title:"Error",description:ge.message||"Failed to upload photo",variant:"destructive"})}finally{b(!1)}}},je=async()=>{if(!L.name.trim()||!L.email.trim()){n({title:"Error",description:"Name and email are required",variant:"destructive"});return}m(!0);try{const he=L.email.trim().toLowerCase(),ge=((s==null?void 0:s.email)||"").toLowerCase(),ke=!!he&&he!==ge;if(ke){const{data:Me,error:Oe}=await q.functions.invoke("update-own-email",{body:{newEmail:he}}),Se=Oe||(Me==null?void 0:Me.error);if(Se)throw new Error(typeof Se=="string"?Se:"Could not update your login email. Please try a different address.")}const{error:Te}=await q.from("profiles").update({name:L.name.trim(),email:he,phone:L.phone.trim()||null,title:L.title.trim()||null,bio:L.bio.trim()||null,areas_served:L.areas_served.trim()||null,years_experience:L.years_experience?parseInt(L.years_experience):null,...I?{}:{brokerage_name:L.brokerage_name.trim()||null},instagram_url:L.instagram_url.trim()||null,facebook_url:L.facebook_url.trim()||null,linkedin_url:L.linkedin_url.trim()||null,email_signature:L.email_signature||"",use_email_signature:L.use_email_signature}).eq("id",s==null?void 0:s.id);if(Te)throw Te;n({title:"Success",description:ke?"Profile updated. Your login email is now "+he:"Profile updated successfully"})}catch(he){console.error("Error updating profile:",he),n({title:"Error",description:he.message||"Failed to update profile",variant:"destructive"})}finally{m(!1)}},be=async()=>{if(!ue.newPassword){n({title:"Error",description:"Please enter a new password",variant:"destructive"});return}if(ue.newPassword.length<6){n({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}if(ue.newPassword!==ue.confirmPassword){n({title:"Error",description:"Passwords do not match",variant:"destructive"});return}m(!0);try{const{error:he}=await q.auth.updateUser({password:ue.newPassword});if(he)throw he;n({title:"Success",description:"Password updated successfully"}),se({newPassword:"",confirmPassword:""}),a&&setTimeout(()=>t("/dashboard"),1e3)}catch(he){console.error("Error updating password:",he),n({title:"Error",description:he.message||"Failed to update password",variant:"destructive"})}finally{m(!1)}};return e.jsx(qs,{title:a?"Complete Your Profile":i?"Reset Your Password":"Profile Settings",description:a?"Welcome! Please complete your profile setup":i?"Please set a new password for your account":"Manage your account information and password",children:e.jsxs("div",{className:"mx-auto max-w-4xl",children:[!a&&!i&&e.jsx("div",{className:"mb-6",children:e.jsxs(U,{variant:"outline",onClick:()=>{var he;(he=document.getElementById("change-password-section"))==null||he.scrollIntoView({behavior:"smooth",block:"center"})},className:"gap-2",children:[e.jsx(SA,{className:"h-4 w-4"}),"Change Password"]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"Profile Photo"}),e.jsx(Jn,{children:"Upload a professional photo for your profile"})]}),e.jsxs(Ie,{className:"flex items-center gap-6",children:[e.jsxs(Ea,{className:"h-24 w-24",children:[e.jsx(Ci,{src:p}),e.jsx(Ta,{className:"text-2xl",children:L.name.split(" ").map(he=>he[0]).join("").toUpperCase()||"U"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("input",{type:"file",id:"avatar-upload",accept:"image/*",className:"hidden",onChange:ie,disabled:v}),e.jsxs(U,{variant:"outline",onClick:()=>{var he;return(he=document.getElementById("avatar-upload"))==null?void 0:he.click()},disabled:v,children:[e.jsx(qa,{className:"mr-2 h-4 w-4"}),v?"Uploading...":"Upload Photo"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Upload an image and crop it to your liking."})]})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"Personal Information"}),e.jsx(Jn,{children:"Update your profile details"})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"name",children:"Name"}),e.jsx(xe,{id:"name",value:L.name,onChange:he=>M({...L,name:he.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"email",children:"Email"}),e.jsx(xe,{id:"email",type:"email",value:L.email,onChange:he=>M({...L,email:he.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(te,{htmlFor:"phone",children:"Phone Number"}),e.jsx(xe,{id:"phone",type:"tel",value:L.phone,onChange:he=>M({...L,phone:he.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(te,{htmlFor:"title",children:"Job Title"}),e.jsx(xe,{id:"title",value:L.title,onChange:he=>M({...L,title:he.target.value}),placeholder:"e.g., Broker Associate, Team Lead",maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"bio",children:"Bio"}),e.jsx(Fs,{id:"bio",value:L.bio,onChange:he=>M({...L,bio:he.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(te,{htmlFor:"areas_served",children:"Areas Served"}),e.jsx(xe,{id:"areas_served",value:L.areas_served,onChange:he=>M({...L,areas_served:he.target.value}),placeholder:"e.g., Downtown, Suburbs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"years_experience",children:"Years Experience"}),e.jsx(xe,{id:"years_experience",type:"number",min:"0",value:L.years_experience,onChange:he=>M({...L,years_experience:he.target.value}),placeholder:"e.g., 5"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"brokerage_name",children:["Brokerage ",I&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(managed)"})]}),e.jsx(xe,{id:"brokerage_name",value:L.brokerage_name,onChange:he=>M({...L,brokerage_name:he.target.value}),placeholder:"e.g., Keller Williams Realty",disabled:I,maxLength:150}),e.jsx("p",{className:"text-xs text-muted-foreground",children:I?"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(IKs,{userId:s.id,value:x,onChange:y,description:"PNG, JPG, SVG or WebP up to 5MB. Used on your agent website, marketing and email signatures."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Social Links"}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsx(xe,{value:L.linkedin_url,onChange:he=>M({...L,linkedin_url:he.target.value}),placeholder:"LinkedIn URL"}),e.jsx(xe,{value:L.instagram_url,onChange:he=>M({...L,instagram_url:he.target.value}),placeholder:"Instagram URL"}),e.jsx(xe,{value:L.facebook_url,onChange:he=>M({...L,facebook_url:he.target.value}),placeholder:"Facebook URL"})]})]}),e.jsxs(U,{onClick:je,disabled:h,children:[e.jsx(Ho,{className:"mr-2 h-4 w-4"}),"Save Changes"]})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Pg,{className:"h-5 w-5"}),"Email Signature"]}),e.jsx(Jn,{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:L.use_email_signature?"Your signature will be added to every email sent via Gmail":"Signature is currently disabled"})]}),e.jsx(wn,{checked:L.use_email_signature,onCheckedChange:he=>M({...L,use_email_signature:he})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Signature"}),e.jsx(SN,{content:L.email_signature,onChange:he=>M({...L,email_signature:he}),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(U,{onClick:je,disabled:h,children:[e.jsx(Ho,{className:"mr-2 h-4 w-4"}),"Save Signature"]})]})]}),e.jsx(SKs,{}),e.jsxs(we,{id:"change-password-section",children:[e.jsxs(Tt,{children:[e.jsx(It,{children:a?"Set Your Password":"Change Password"}),e.jsx(Jn,{children:a?"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(te,{htmlFor:"newPassword",children:"New Password"}),e.jsx(xe,{id:"newPassword",type:"password",value:ue.newPassword,onChange:he=>se({...ue,newPassword:he.target.value}),placeholder:"Min 6 characters"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"confirmPassword",children:"Confirm Password"}),e.jsx(xe,{id:"confirmPassword",type:"password",value:ue.confirmPassword,onChange:he=>se({...ue,confirmPassword:he.target.value}),placeholder:"Re-enter your new password"})]}),e.jsxs(U,{onClick:be,disabled:h,children:[e.jsx(Ho,{className:"mr-2 h-4 w-4"}),a?"Complete Setup":"Update Password"]}),a&&e.jsx(U,{variant:"outline",onClick:()=>t("/dashboard"),className:"ml-2",children:"Skip for Now"})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[o?e.jsx(bx,{className:"h-5 w-5"}):e.jsx(Zk,{className:"h-5 w-5"}),"Push Notifications"]}),e.jsx(Jn,{children:"Receive browser notifications when new content is added"})]}),e.jsx(Ie,{children:l?e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:o?"Notifications enabled":"Notifications disabled"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:o?"You'll receive notifications about new templates, videos, and events":"Enable to get notified about new content"})]}),e.jsx(wn,{checked:o,onCheckedChange:he=>{he?d():u()},disabled:c})]}):e.jsxs("div",{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{children:"Push notifications are not available in this browser."}),e.jsxs("p",{className:"text-xs space-y-1",children:[e.jsx("strong",{children:"Desktop:"})," Use Chrome, Firefox, or Edge.",e.jsx("br",{}),e.jsx("strong",{children:"Android:"})," Use Chrome or Firefox.",e.jsx("br",{}),e.jsx("strong",{children:"iPhone/iPad:"})," Push notifications on iOS ",e.jsx("em",{children:"only"})," work when this site is installed as an app from ",e.jsx("strong",{children:"Safari"}),". Open this site in Safari → tap the ",e.jsx("strong",{children:"Share"})," button → ",e.jsx("strong",{children:"Add to Home Screen"}),". Other browsers (Chrome, Firefox, etc.) on iOS do not support push notifications due to Apple restrictions."]})]})})]}),e.jsx(yKs,{}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[z?e.jsx(TM,{className:"h-5 w-5"}):e.jsx(ln,{className:"h-5 w-5"}),"Email Preferences"]}),e.jsx(Jn,{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:z?"You won't receive weekly digest emails":"Receive a weekly summary of new content, events, and your progress"})]}),e.jsx(wn,{checked:!z,onCheckedChange:async he=>{V(!0);try{const{error:ge}=await q.from("profiles").update({digest_opt_out:!he}).eq("id",s==null?void 0:s.id);if(ge)throw ge;$(!he),n({title:he?"Subscribed":"Unsubscribed",description:he?"You will now receive weekly digest emails":"You will no longer receive weekly digest emails"})}catch(ge){n({title:"Error",description:ge.message||"Failed to update preference",variant:"destructive"})}finally{V(!1)}},disabled:H})]}),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:K?"You won't receive event invite emails (weekly digest is unaffected)":"Get invited to LevelUp live trainings and special events"})]}),e.jsx(wn,{checked:!K,onCheckedChange:async he=>{le(!0);try{const{error:ge}=await q.from("profiles").update({event_invite_opt_out:!he}).eq("id",s==null?void 0:s.id);if(ge)throw ge;Z(!he),n({title:he?"Subscribed":"Unsubscribed",description:he?"You will now receive event invite emails":"You will no longer receive event invite emails"})}catch(ge){n({title:"Error",description:ge.message||"Failed to update preference",variant:"destructive"})}finally{le(!1)}},disabled:Q})]})]})]}),e.jsx(oBs,{}),e.jsx(RKs,{}),e.jsx(PKs,{})]}),e.jsx(LJe,{open:N,onClose:()=>S(!1),imageSrc:A,onCropComplete:ce,aspectRatio:1})]})})};var OKs="AspectRatio",Izt=j.forwardRef((s,t)=>{const{ratio:n=1/1,style:r,...a}=s;return e.jsx("div",{style:{position:"relative",width:"100%",paddingBottom:`${100/n}%`},"data-radix-aspect-ratio-wrapper":"",children:e.jsx(si.div,{...a,ref:t,style:{...r,position:"absolute",top:0,right:0,bottom:0,left:0}})})});Izt.displayName=OKs;var FKs=Izt;const zKs=FKs;function BKs(){const{user:s}=vs(),t=Qt(),[n,r]=j.useState(!1),[a,i]=j.useState(!1),{data:l,isLoading:o}=ct({queryKey:["calendar-token",s==null?void 0:s.id],queryFn:async()=>{const{data:f,error:x}=await q.from("profiles").select("calendar_token").eq("id",s==null?void 0:s.id).single();if(x)throw x;return f},enabled:!!s&&a}),c=yt({mutationFn:async()=>{const f=new Uint8Array(12);crypto.getRandomValues(f);const x=btoa(String.fromCharCode(...f)).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:f=>{re.error("Failed to generate calendar URL: "+f.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 f=d.replace("https://","webcal://"),x=`https://calendar.google.com/calendar/r?cid=${encodeURIComponent(f)}`;window.open(x,"_blank")}},p=()=>{if(d){const f=`https://outlook.live.com/calendar/0/addfromweb?url=${encodeURIComponent(d)}&name=Level%20Up%20Events`;window.open(f,"_blank")}};return e.jsxs(zs,{open:a,onOpenChange:i,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{variant:"outline",className:"gap-2",children:[e.jsx(pa,{className:"h-4 w-4"}),"Subscribe to Calendar"]})}),e.jsxs(Ds,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pa,{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(Et,{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(xe,{value:d,readOnly:!0,className:"text-xs font-mono"}),e.jsx(U,{variant:"outline",size:"icon",onClick:u,children:n?e.jsx(Xr,{className:"h-4 w-4 text-green-500"}):e.jsx(Pa,{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(U,{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(Sr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs(U,{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(Sr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs(U,{variant:"outline",className:"w-full justify-start gap-2",onClick:p,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(Sr,{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(U,{onClick:()=>c.mutate(),disabled:c.isPending,className:"w-full",children:c.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(pa,{className:"h-4 w-4 mr-2"}),"Generate Calendar URL"]})})]})})]})]})}const UKs={first_timer:Ua,regular:CA,dedicated:Eh,veteran:Al,streak_master:Xd,century:Al},qKs={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 Dxt(s){return s===1?e.jsx(Al,{className:"h-5 w-5 text-yellow-500"}):s===2?e.jsx(CA,{className:"h-5 w-5 text-gray-400"}):s===3?e.jsx(Eh,{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 Rzt({showUserStats:s=!0,compact:t=!1,brokerageId:n,title:r="Event Leaderboard"}){const{user:a}=vs(),{data:i,isLoading:l}=y7t(t?5:10,n),{data:o}=v7t(a==null?void 0:a.id),{data:c}=_7t(a==null?void 0:a.id),{data:d}=b7t(a==null?void 0:a.id);return l?e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Al,{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(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Al,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsxs(Ie,{children:[s&&o&&e.jsxs("div",{className:"mb-4 p-3 rounded-lg bg-primary/5 border border-primary/10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Your Stats"}),c&&e.jsxs(Be,{variant:"secondary",className:"text-xs",children:["Rank #",c]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold text-primary",children:o.total_points}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Points"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold",children:o.total_events_attended}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Events"})]}),e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Xd,{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=UKs[u.badge_type]||Ua;return e.jsxs(Be,{variant:"outline",className:`text-xs ${qKs[u.badge_type]||""}`,title:u.badge_description||"",children:[e.jsx(h,{className:"h-3 w-3 mr-1"}),u.badge_name]},u.id)}),d.length>4&&e.jsxs(Be,{variant:"outline",className:"text-xs",children:["+",d.length-4," more"]})]})]}),e.jsxs(oa,{defaultValue:"points",className:"w-full",children:[e.jsxs(la,{className:"w-full mb-3",children:[e.jsx(Kt,{value:"points",className:"flex-1",children:"By Points"}),e.jsx(Kt,{value:"events",className:"flex-1",children:"By Events"})]}),e.jsx(Zt,{value:"points",className:"mt-0",children:e.jsxs("div",{className:"space-y-2",children:[i==null?void 0:i.map((u,h)=>{var m,p,f;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:Dxt(h+1)}),e.jsx(Ea,{className:"h-8 w-8",children:e.jsx(Ta,{className:"text-xs",children:((p=(m=u.profile)==null?void 0:m.name)==null?void 0:p.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((f=u.profile)==null?void 0:f.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(Zt,{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,p,f;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:Dxt(h+1)}),e.jsx(Ea,{className:"h-8 w-8",children:e.jsx(Ta,{className:"text-xs",children:((p=(m=u.profile)==null?void 0:m.name)==null?void 0:p.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((f=u.profile)==null?void 0:f.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 $Ks(){const s=Wn(),{user:t,isAdmin:n}=vs(),r=Qt(),[a,i]=j.useState(!1),[l,o]=j.useState(!1),{data:c,isLoading:d}=ct({queryKey:["public-events"],queryFn:async()=>{const{data:T,error:L}=await q.from("events").select("*").order("event_date",{ascending:!0});if(L)throw L;return T}}),{data:u}=ct({queryKey:["my-registrations"],queryFn:async()=>{if(!t)return[];const{data:T,error:L}=await q.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",t.id);if(L)throw L;return T},enabled:!!t}),{data:h}=ct({queryKey:["event-registration-counts"],queryFn:async()=>{let T=[],L=0;const M=1e3;for(;;){const{data:R,error:z}=await q.from("event_registrations").select("event_id").range(L,L+M-1);if(z)throw z;if(!R||R.length===0||(T=T.concat(R),R.length{I[R.event_id]=(I[R.event_id]||0)+1}),I}}),m=yt({mutationFn:async T=>{await q.auth.refreshSession();const{data:L,error:M}=await q.functions.invoke("zoom-register",{body:{event_id:T}});if(M)throw M;if(L!=null&&L.error)throw new Error(L.error);return L},onSuccess:T=>{r.invalidateQueries({queryKey:["my-registrations"]}),r.invalidateQueries({queryKey:["event-registration-counts"]}),T!=null&&T.join_url?re.success("Successfully registered! You'll receive a Zoom confirmation email."):re.success("Successfully registered for the event!")},onError:T=>{re.error("Failed to register: "+T.message)}}),p=yt({mutationFn:async T=>{const{data:L,error:M}=await q.functions.invoke("zoom-unregister",{body:{event_id:T}});if(M)throw M;if(L!=null&&L.error)throw new Error(L.error);return L},onSuccess:()=>{r.invalidateQueries({queryKey:["my-registrations"]}),r.invalidateQueries({queryKey:["event-registration-counts"]}),re.success("Registration cancelled and removed from Zoom")},onError:T=>{re.error("Failed to cancel: "+T.message)}}),f=T=>u==null?void 0:u.some(L=>L.event_id===T),x=T=>{const L=u==null?void 0:u.find(M=>M.event_id===T);return L==null?void 0:L.zoom_join_url},y=T=>T.capacity?((h==null?void 0:h[T.id])||0)>=T.capacity:!1,v=(c==null?void 0:c.filter(T=>GD(T.event_date)!=="ended"))||[],b=(c==null?void 0:c.filter(T=>GD(T.event_date)==="ended"))||[],N=v.filter(T=>GD(T.event_date)==="live").length,S=v.filter(T=>f(T.id)).length,A=l?b:b.slice(0,6);return e.jsx(qs,{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:N>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(BKs,{}),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(qc,{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:pa},{label:"You're registered",value:S,icon:Xr},{label:"Live now",value:N,icon:mv},{label:"Past events",value:b.length,icon:Y2}].map(T=>e.jsxs("div",{className:"hub-glass rounded-xl px-3 py-2.5",children:[e.jsx("span",{className:"text-xl font-bold",children:T.value}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-1 text-[11px] hub-ink-muted",children:[e.jsx(T.icon,{className:"h-3 w-3"}),T.label]})]},T.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(T=>e.jsx("div",{className:"h-72 animate-pulse rounded-2xl border bg-muted/40"},T))}):v.length===0?e.jsx(we,{className:"rounded-2xl border-dashed py-12 text-center",children:e.jsxs(Ie,{className:"space-y-2",children:[e.jsx(pa,{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(T=>{const L=GD(T.event_date),M=GQe(T.event_date),I=L==="live",R=L==="starting_soon";return e.jsxs(we,{className:`group flex flex-col overflow-hidden rounded-2xl cursor-pointer transition-all hover:shadow-lg ${I?"border-red-500 ring-2 ring-red-500/20":R?"border-amber-500 ring-2 ring-amber-500/20":"hover:border-primary/50"}`,onClick:()=>s(`/events/${T.id}`),children:[M&&e.jsxs("div",{className:`${I?"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"})]}),I?e.jsxs(e.Fragment,{children:[e.jsx(mv,{className:"h-3.5 w-3.5"}),"LIVE NOW"]}):e.jsxs(e.Fragment,{children:[e.jsx(Yr,{className:"h-3.5 w-3.5"}),"STARTING SOON"]})]}),T.image_url&&e.jsxs(zKs,{ratio:16/9,className:"overflow-hidden relative bg-neutral-900",children:[e.jsx("img",{src:T.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:T.image_url,alt:T.title,className:"relative w-full h-full object-contain transition-transform group-hover:scale-[1.03]"})]}),e.jsxs(Tt,{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(pa,{className:"h-3 w-3"}),new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",timeZone:"America/New_York"}).format(new Date(T.event_date))]}),f(T.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(Xr,{className:"h-3 w-3"}),"Registered"]})]}),e.jsx(It,{className:"line-clamp-2 pt-1",children:T.title}),T.description&&e.jsx(Jn,{className:"line-clamp-2",children:T.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(pa,{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(T.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Yr,{className:"h-4 w-4"}),yee(new Date(T.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Bn,{className:"h-4 w-4"}),(h==null?void 0:h[T.id])||0," registered",T.capacity&&` / ${T.capacity} spots`]})]}),e.jsx(J3e,{className:"flex gap-2",onClick:z=>z.stopPropagation(),children:f(T.id)?e.jsxs(e.Fragment,{children:[e.jsxs(U,{variant:"outline",className:"flex-1",onClick:()=>p.mutate(T.id),disabled:p.isPending,children:[e.jsx(er,{className:"h-4 w-4 mr-2"}),"Cancel"]}),e.jsxs(U,{className:"flex-1",onClick:()=>window.open(x(T.id)||T.zoom_link,"_blank"),children:[e.jsx(Sr,{className:"h-4 w-4 mr-2"}),"Join Zoom"]})]}):e.jsx(U,{className:"w-full",onClick:()=>m.mutate(T.id),disabled:m.isPending||y(T),children:y(T)?"Event Full":e.jsxs(e.Fragment,{children:[e.jsx(Xr,{className:"h-4 w-4 mr-2"}),"Register"]})})})]},T.id)})}),b.length>0&&e.jsxs(we,{className:"rounded-2xl",children:[e.jsxs("button",{type:"button",onClick:()=>i(T=>!T),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(Y2,{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(rl,{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(T=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>s(`/events/${T.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(T.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(T.event_date))})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:T.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(T.event_date))})]}),e.jsx($h,{className:"h-4 w-4 shrink-0 text-muted-foreground"})]})},T.id))}),b.length>6&&e.jsx("div",{className:"border-t px-5 py-3",children:e.jsx(U,{variant:"ghost",size:"sm",className:"w-full",onClick:()=>o(T=>!T),children:l?"Show less":`Show all ${b.length}`})})]})]})]}),n&&e.jsx("div",{className:"lg:col-span-1",children:e.jsx(Rzt,{showUserStats:!0})})]})]})})}const EFe=[{value:"all",label:"All Roles",icon:Bn},{value:"newest",label:"Newest Members",icon:Yr},{value:"brokerage_manager",label:"Brokerage Managers",icon:fQ},{value:"admin",label:"Admins",icon:Im}];function VKs({open:s,onOpenChange:t,resourceType:n,resourceId:r,resourceTitle:a}){var Me,Oe;const{user:i,isAdmin:l,isBrokerageManager:o}=vs(),[c,d]=j.useState([]),[u,h]=j.useState([]),[m,p]=j.useState([]),[f,x]=j.useState([]),[y,v]=j.useState(""),[b,N]=j.useState(""),[S,A]=j.useState(""),[T,L]=j.useState(!1),[M,I]=j.useState(!1),[R,z]=j.useState("agents"),[$,H]=j.useState("all"),[V,K]=j.useState({}),Z=l||o;j.useEffect(()=>{s&&i&&(l?Q():le())},[s,i,l]),j.useEffect(()=>{s||(p([]),x([]),v(""),N(""),A(""),z("agents"),H("all"))},[s]);const Q=async()=>{if(i){L(!0);try{const{data:Se,error:Qe}=await q.from("brokerages").select("id, name").order("name");if(Qe)throw Qe;const Ae=1e3,Fe={};let Ne=0,$e=!0;for(;$e;){const{data:Ze,error:Ue}=await q.from("profiles").select("brokerage_id").range(Ne*Ae,(Ne+1)*Ae-1);if(Ue)throw Ue;Ze==null||Ze.forEach(Ye=>{Ye.brokerage_id&&(Fe[Ye.brokerage_id]=(Fe[Ye.brokerage_id]||0)+1)}),$e=(Ze==null?void 0:Ze.length)===Ae,Ne++}h((Se==null?void 0:Se.map(Ze=>({...Ze,agent_count:Fe[Ze.id]||0})))||[]);const Ve=[];for(Ne=0,$e=!0;$e;){const{data:Ze,error:Ue}=await q.from("profiles").select("id, name, email, brokerage_id, created_at, brokerages(name)").neq("id",i.id).order("name").range(Ne*Ae,(Ne+1)*Ae-1);if(Ue)throw Ue;Ze&&Ve.push(...Ze),$e=(Ze==null?void 0:Ze.length)===Ae,Ne++}const qe={};for(Ne=0,$e=!0;$e;){const{data:Ze,error:Ue}=await q.from("user_roles").select("user_id, role").range(Ne*Ae,(Ne+1)*Ae-1);if(Ue)throw Ue;Ze==null||Ze.forEach(Ye=>{qe[Ye.user_id]||(qe[Ye.user_id]=[]),qe[Ye.user_id].push(Ye.role)}),$e=(Ze==null?void 0:Ze.length)===Ae,Ne++}K(qe),d(Ve.map(Ze=>{var Ue;return{id:Ze.id,name:Ze.name,email:Ze.email,brokerage_name:((Ue=Ze.brokerages)==null?void 0:Ue.name)||"No Brokerage",roles:qe[Ze.id]||[],created_at:Ze.created_at}}))}catch(Se){console.error("Error loading data:",Se),re.error("Failed to load agents and brokerages")}finally{L(!1)}}},le=async()=>{if(i){L(!0);try{const{data:Se}=await q.from("profiles").select("brokerage_id").eq("id",i.id).single();if(!(Se!=null&&Se.brokerage_id)){re.error("You must be part of a brokerage to share resources"),t(!1);return}const{data:Qe,error:Ae}=await q.from("profiles").select("id, name, email").eq("brokerage_id",Se.brokerage_id).neq("id",i.id).order("name");if(Ae)throw Ae;d(Qe||[])}catch(Se){console.error("Error loading agents:",Se),re.error("Failed to load agents")}finally{L(!1)}}},ue=c.filter(Se=>{var Ae;const Qe=Se.name.toLowerCase().includes(y.toLowerCase())||Se.email.toLowerCase().includes(y.toLowerCase())||((Ae=Se.brokerage_name)==null?void 0:Ae.toLowerCase().includes(y.toLowerCase()));if(l&&$!=="all"&&$!=="newest"){const Fe=V[Se.id]||[];return Qe&&Fe.includes($)}return Qe}).sort((Se,Qe)=>$==="newest"?(Qe.created_at||"").localeCompare(Se.created_at||""):0),se=u.filter(Se=>Se.name.toLowerCase().includes(b.toLowerCase())),ne=()=>{m.length===ue.length?p([]):p(ue.map(Se=>Se.id))},ie=()=>{f.length===se.length?x([]):x(se.map(Se=>Se.id))},ce=Se=>{if(!Z){p([Se]);return}p(Qe=>Qe.includes(Se)?Qe.filter(Ae=>Ae!==Se):[...Qe,Se])},je=Se=>{x(Qe=>Qe.includes(Se)?Qe.filter(Ae=>Ae!==Se):[...Qe,Se])},be=async()=>{if(!(m.length>0||f.length>0)){re.error("Please select at least one agent or brokerage to share with");return}I(!0);try{const{data:Qe,error:Ae}=await q.functions.invoke("send-share-notification",{body:{recipientIds:m,brokerageIds:f,resourceType:n,resourceId:r,resourceTitle:a,message:S.trim()||void 0}});if(Ae)throw Ae;const Fe=(Qe==null?void 0:Qe.sharesCreated)||m.length;re.success(`Shared with ${Fe} agent${Fe!==1?"s":""}`),t(!1)}catch(Qe){console.error("Error sharing resource:",Qe),re.error("Failed to share resource")}finally{I(!1)}},he=Se=>Se.split(" ").map(Qe=>Qe[0]).join("").toUpperCase().slice(0,2),ge=Se=>{const Qe=V[Se]||[];return Qe.includes("admin")?e.jsx(Be,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:"Admin"}):Qe.includes("brokerage_manager")?e.jsx(Be,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:"Manager"}):null},ke=m.length+f.length,Te=$!=="all"&&$!=="newest"?ue.length:null;return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"sm:max-w-lg max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(Vs,{className:"flex-shrink-0",children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx($r,{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(oa,{value:R,onValueChange:z,className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(la,{className:"grid w-full grid-cols-2 flex-shrink-0",children:[e.jsxs(Kt,{value:"agents",className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4"}),e.jsx("span",{children:"Agents"}),m.length>0&&e.jsx(Be,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:m.length})]}),e.jsxs(Kt,{value:"brokerages",className:"flex items-center gap-2",children:[e.jsx(_i,{className:"h-4 w-4"}),e.jsx("span",{children:"Brokerages"}),f.length>0&&e.jsx(Be,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:f.length})]})]}),e.jsxs(Zt,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name, email, or brokerage...",value:y,onChange:Se=>v(Se.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:$,onValueChange:H,children:[e.jsxs(ws,{className:"w-[180px]",children:[e.jsx(K2,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(ks,{placeholder:"Filter by role"})]}),e.jsx(js,{children:EFe.map(Se=>e.jsx(et,{value:Se.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Se.icon,{className:"h-4 w-4"}),e.jsx("span",{children:Se.label})]})},Se.value))})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(U,{variant:"ghost",size:"sm",onClick:ne,className:"text-xs h-8",disabled:ue.length===0,children:[e.jsx(Bn,{className:"h-3.5 w-3.5 mr-1.5"}),m.length===ue.length&&ue.length>0?"Deselect All":"Select All"]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[Te!==null&&e.jsxs("span",{className:"text-primary font-medium",children:[Te," ",(Me=EFe.find(Se=>Se.value===$))==null?void 0:Me.label]}),e.jsxs("span",{className:"font-medium",children:[m.length," selected"]})]})]}),e.jsx(Gi,{className:"h-[300px] border rounded-lg",children:T?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(Et,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ue.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(Bn,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:$!=="all"?`No ${(Oe=EFe.find(Se=>Se.value===$))==null?void 0:Oe.label.toLowerCase()} found`:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:ue.map(Se=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${m.includes(Se.id)?"bg-accent":""}`,onClick:()=>ce(Se.id),children:[e.jsx(xi,{checked:m.includes(Se.id),onCheckedChange:()=>ce(Se.id),className:"flex-shrink-0"}),e.jsx(Ea,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(Ta,{className:"text-xs bg-primary/10 text-primary",children:he(Se.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:Se.name}),ge(Se.id)]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Se.email,Se.brokerage_name&&e.jsxs("span",{className:"ml-1 opacity-75",children:["• ",Se.brokerage_name]})]})]})]},Se.id))})})]}),e.jsxs(Zt,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search brokerages...",value:b,onChange:Se=>N(Se.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(U,{variant:"ghost",size:"sm",onClick:ie,className:"text-xs h-8",disabled:se.length===0,children:[e.jsx(_i,{className:"h-3.5 w-3.5 mr-1.5"}),f.length===se.length&&se.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[f.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(Gi,{className:"h-[250px] border rounded-lg",children:T?e.jsx("div",{className:"flex items-center justify-center h-[180px]",children:e.jsx(Et,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):se.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[180px] text-muted-foreground",children:[e.jsx(_i,{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:se.map(Se=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${f.includes(Se.id)?"bg-accent":""}`,onClick:()=>je(Se.id),children:[e.jsx(xi,{checked:f.includes(Se.id),onCheckedChange:()=>je(Se.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(_i,{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:Se.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Se.agent_count," agent",Se.agent_count!==1?"s":""]})]})]},Se.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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search agents...",value:y,onChange:Se=>v(Se.target.value),className:"pl-9"})]}),Z&&e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(U,{variant:"ghost",size:"sm",onClick:ne,className:"text-xs h-8",disabled:ue.length===0,children:[e.jsx(Bn,{className:"h-3.5 w-3.5 mr-1.5"}),m.length===ue.length&&ue.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[m.length," selected"]})]}),e.jsx(Gi,{className:"h-[300px] border rounded-lg",children:T?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(Et,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ue.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(Bn,{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:ue.map(Se=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${m.includes(Se.id)?"bg-accent":""}`,onClick:()=>ce(Se.id),children:[e.jsx(xi,{checked:m.includes(Se.id),onCheckedChange:()=>ce(Se.id),className:"flex-shrink-0"}),e.jsx(Ea,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(Ta,{className:"text-xs bg-primary/10 text-primary",children:he(Se.name)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:Se.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Se.email})]})]},Se.id))})})]}),e.jsxs("div",{className:"space-y-2 flex-shrink-0",children:[e.jsx(te,{htmlFor:"message",className:"text-sm font-medium",children:"Add a message (optional)"}),e.jsx(Fs,{id:"message",placeholder:"I thought you might find this useful...",value:S,onChange:Se=>A(Se.target.value),rows:2,className:"resize-none"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 flex-shrink-0",children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(U,{onClick:be,disabled:ke===0||M,children:M?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):e.jsxs(e.Fragment,{children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),"Share"]})})]})]})]})})}function PG({resourceType:s,resourceId:t,resourceTitle:n,variant:r="outline",size:a="sm",className:i=""}){const[l,o]=j.useState(!1),{user:c}=vs();return c?e.jsxs(e.Fragment,{children:[e.jsxs(U,{variant:r,size:a,onClick:()=>o(!0),className:i,children:[e.jsx(jd,{className:"h-4 w-4 mr-2"}),"Share"]}),e.jsx(VKs,{open:l,onOpenChange:o,resourceType:s,resourceId:t,resourceTitle:n})]}):null}function HKs(){const{eventId:s}=Di(),t=Wn(),{user:n}=vs(),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(0),[d,u]=j.useState(!0),[h,m]=j.useState(!1);j.useEffect(()=>{s&&p()},[s,n]);const p=async()=>{try{const{data:N,error:S}=await q.from("events").select("*").eq("id",s).single();if(S)throw S;a(N);const{count:A}=await q.from("event_registrations").select("*",{count:"exact",head:!0}).eq("event_id",s);if(c(A||0),n){const{data:T}=await q.from("event_registrations").select("id, zoom_join_url").eq("event_id",s).eq("user_id",n.id).maybeSingle();l(T)}}catch(N){console.error("Error loading event:",N),re.error("Failed to load event"),t("/events")}finally{u(!1)}},f=async()=>{if(!(!n||!r)){m(!0);try{const{error:N}=await q.auth.refreshSession();if(N){console.error("Session refresh failed:",N),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(T=>T+1)}}catch(N){console.error("Registration error:",N),re.error(i?"Failed to cancel registration":"Failed to register for event")}finally{m(!1)}}},x=N=>{var S,A,T;if(N.includes("iframe.mediadelivery.net")||N.includes("video.bunnycdn.com")){const L=N.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(L)return`https://iframe.mediadelivery.net/embed/${L[1]}/${L[2]}?autoplay=false&preload=true`}if(N.includes("youtube.com")||N.includes("youtu.be")){const L=N.includes("youtu.be")?(S=N.split("youtu.be/")[1])==null?void 0:S.split("?")[0]:(A=N.split("v=")[1])==null?void 0:A.split("&")[0];if(L)return`https://www.youtube.com/embed/${L}`}if(N.includes("vimeo.com")){const L=(T=N.split("vimeo.com/")[1])==null?void 0:T.split("?")[0];if(L)return`https://player.vimeo.com/video/${L}`}return N};if(d)return e.jsx(qs,{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(qs,{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(U,{onClick:()=>t("/events"),className:"mt-4",children:"Back to Events"})]})});const y=z4(new Date(r.event_date)),v=r.capacity&&o>=r.capacity,b=(i==null?void 0:i.zoom_join_url)||r.zoom_link;return e.jsx(qs,{title:r.title,children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs(U,{variant:"ghost",className:"mb-6 gap-2",onClick:()=>t("/events"),children:[e.jsx(Aa,{className:"h-4 w-4"}),"Back to Events"]}),r.image_url&&e.jsxs("div",{className:"relative aspect-video rounded-xl overflow-hidden mb-6",children:[e.jsx("img",{src:r.image_url,alt:r.title,className:"w-full h-full object-cover"}),y&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(Be,{variant:"secondary",className:"text-lg px-4 py-2",children:"Event Ended"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground",children:r.title}),e.jsx(PG,{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($h,{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(we,{children:e.jsxs(Ie,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(pa,{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:yee(new Date(r.event_date))})]})]}),r.capacity&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Bn,{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(Yo,{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(U,{className:"w-full gap-2",onClick:()=>window.open(b,"_blank"),children:[e.jsx(Sr,{className:"h-4 w-4"}),"Join Event"]}),e.jsxs(U,{variant:"outline",className:"w-full",onClick:f,disabled:h,children:[h?e.jsx(Et,{className:"h-4 w-4 animate-spin mr-2"}):null,"Cancel Registration"]})]}):e.jsx(U,{className:"w-full gap-2",onClick:f,disabled:h||(v??!1),children:h?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):v?"Event Full":"Register Now"})}),y&&i&&e.jsxs(U,{variant:"outline",className:"w-full gap-2",onClick:()=>window.open(r.zoom_link,"_blank"),children:[e.jsx(Sr,{className:"h-4 w-4"}),"View Recording"]})]})]})})})]})]})})}const GKs=[{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 WKs(){const{isAdmin:s}=vs(),t=GKs.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(BT,{to:n.to,end:n.end,className:({isActive:r})=>Mt("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 bAe=[{id:"market-listing",title:"Market a Listing",blurb:"Presentations, copy, pages and video",icon:ra,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:ln,color:"bg-emerald-500/15 text-emerald-600"},{id:"social-content",title:"Create Social Content",blurb:"Reels, posts and captions",icon:Th,color:"bg-rose-500/15 text-rose-600"},{id:"open-house",title:"Host an Open House",blurb:"Promote, sign in and follow up",icon:G2,color:"bg-sky-500/15 text-sky-600"},{id:"new-business",title:"Generate New Business",blurb:"Leads, expireds and by-owner sellers",icon:rc,color:"bg-amber-500/15 text-amber-600"},{id:"brand",title:"Build My Brand",blurb:"Your card, site, reviews and presence",icon:$c,color:"bg-teal-500/15 text-teal-600"}];bAe.reduce((s,t)=>({...s,[t.id]:t}),{});const KKs=[{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"}],Dzt=[{id:"scheduler",name:"LevelUp Scheduler",description:"Share your booking link, sync Google Calendar and let clients book you",icon:ch,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:Wr,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:oy,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:hv,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:Ur,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:ig,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:cn,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:ln,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:Gh,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:$r,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:Pg,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:iq,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:Q2,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:Gh,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:Cl,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:hv,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:cn,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:ra,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:gq,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"]}],Oxt=Dzt.reduce((s,t)=>({...s,[t.id]:t}),{}),YKs={agent_review:{goals:["brand","new-business"],categories:["brand","leads"],keywords:["reviews","get more reviews","testimonials","reputation"]},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"]}};function ZKs(s){return YKs[s]??{goals:[],categories:[],keywords:[]}}const IJe=[{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:ra,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:G2,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:Bn,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"}]}],I7=IJe.reduce((s,t)=>({...s,[t.id]:t}),{});function XKs({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:Mt("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 QKs({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"?{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:Mt("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:Mt("flex-shrink-0 w-12 h-12 rounded-xl flex items-center justify-center text-2xl",s.color),children:i?e.jsx(Ql,{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:Mt("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:Mt("flex-shrink-0 p-2 -m-1 rounded-lg transition-colors",t?"text-primary":"text-muted-foreground/40 hover:text-primary"),children:e.jsx(u0,{className:Mt("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 XF({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(QKs,{item:a,isFavorite:t(a),onOpen:n,onToggleFavorite:r},a.key))})}const JKs="bg-primary/10 text-primary";function gre(){const{user:s,isAdmin:t}=vs(),n=_S(),r=Wn(),{hasAccess:a}=Y6e(),{isFeatureEnabled:i}=qne(),[l,o]=j.useState([]),[c,d]=j.useState(!0),[u,h]=j.useState(new Set),[m,p]=j.useState(new Set),[f,x]=j.useState(!1),[y,v]=j.useState([]),[b,N]=j.useState(""),S=j.useCallback(async()=>{if(s!=null&&s.id)try{const[{data:K},{data:Z},{data:Q},{data:le},{data:ue},{data:se},{data:ne}]=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()]),ie=(K||[]).map(ge=>ge.tag);x((ue||[]).some(ge=>ge.is_active&&ge.mls_provider_id&&!ge.no_mls_mode)),h(new Set((Q||[]).map(ge=>ge.app_id))),p(new Set((le||[]).map(ge=>ge.tool_id)));const ce=(Z||[]).filter(ge=>ge.app_id==="newsletter_studio"?!1:!ge.required_tags||ge.required_tags.length===0?!0:ge.required_tags.some(ke=>ie.includes(ke)));o(ce.sort((ge,ke)=>ge.name==="LevelUp Members Portal"?-1:ke.name==="LevelUp Members Portal"?1:0));const je=new Set,be=[];for(const ge of se||[])if(!(!ge.app_id||je.has(ge.app_id))&&(je.add(ge.app_id),be.push({appId:ge.app_id,name:ge.app_name,at:ge.launched_at}),be.length>=8))break;v(be);const he=ne==null?void 0:ne.name;N(he?he.trim().split(" ")[0]:"")}catch(K){console.error("Error loading app catalog:",K),re.error("Failed to load apps")}finally{d(!1)}},[s==null?void 0:s.id]);j.useEffect(()=>{S()},[S]);const A=j.useMemo(()=>{const K=ue=>{if(!n.isRestricted)return null;const se=M_s(ue);return se&&!n.hasFeature(se)?se:null},Z=Dzt.filter(ue=>!(ue.adminOnly&&!t||ue.requiresLeadSiteMLS&&!f&&!t||ue.requiresWeeklyReels&&!a||ue.featureFlag&&!i(ue.featureFlag)&&!t)).map(ue=>({key:`tool:${ue.id}`,kind:"tool",id:ue.id,name:ue.name,description:ue.description,icon:ue.icon,color:ue.color,isNew:ue.isNew,beta:ue.beta,popular:ue.popular,goals:ue.goals,categories:ue.categories,keywords:ue.keywords,lockedFeature:K(ue.id),tool:ue})),Q={AgentReview:"marketing_studio",SigFlow:"marketing_studio",Staging_Studio:"marketing_studio",social_autopilot:"social",newsletter_studio:"newsletter"},le=l.map(ue=>{const se=ZKs(ue.app_id),ne=Q[ue.app_id];return{key:`app:${ue.app_id}`,kind:"app",id:ue.app_id,name:ue.name,description:ue.description,icon:ue.icon,color:JKs,goals:se.goals,categories:se.categories,keywords:se.keywords,lockedFeature:n.isRestricted&&ne&&!n.hasFeature(ne)?ne:null,tile:ue}});return[...Z,...le]},[l,t,f,a,i,n.isRestricted,n.features]),T=j.useCallback(K=>{var Z;return K.kind==="tool"?m.has(K.id):u.has(((Z=K.tile)==null?void 0:Z.id)??"")},[m,u]),L=j.useMemo(()=>A.filter(T),[A,T]),M=j.useMemo(()=>{const K=new Map(A.map(Z=>[Z.id,Z]));return y.map(Z=>K.get(Z.appId)).filter(Boolean)},[A,y]),I=j.useMemo(()=>A.filter(K=>K.kind==="app"),[A]),R=j.useCallback(async(K,Z)=>{try{await q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:K,app_name:Z,user_agent:navigator.userAgent})}catch{}},[s==null?void 0:s.id]),z=j.useCallback(async K=>{var Q;if(K.target_url.startsWith("/")){await R(K.app_id,K.name),r(K.target_url);return}try{const le=new URL(K.target_url);if(new Set([window.location.hostname,"dashboard.relevelup.com"]).has(le.hostname)){await R(K.app_id,K.name),r(le.pathname+le.search+le.hash);return}}catch{}const Z=window.open("about:blank","_blank");try{const{data:le,error:ue}=await q.auth.getSession();if(ue||!le.session){Z==null||Z.close(),re.error("Session expired. Please refresh the page and try again.");return}await R(K.app_id,K.name);const{data:se,error:ne}=await q.functions.invoke("sso-launch",{body:{app_id:K.app_id},headers:{Authorization:`Bearer ${le.session.access_token}`}});if(ne)throw ne;se!=null&&se.redirect_url?Z&&!Z.closed?(Z.location.href=se.redirect_url,(Q=Z.focus)==null||Q.call(Z)):window.location.assign(se.redirect_url):(Z==null||Z.close(),re.error("Launch link unavailable"))}catch(le){Z==null||Z.close(),console.error("Error launching app:",le),re.error("Failed to launch app. Please try again.")}},[R,r]),$=j.useCallback(K=>{if(K.lockedFeature){r(`/upgrade/${K.lockedFeature}`);return}if(K.kind==="app"&&K.tile){z(K.tile);return}K.tool&&(R(K.tool.id,K.tool.name),r(K.tool.path))},[z,R,r]),H=j.useCallback(async K=>{var ne;if(!(s!=null&&s.id))return;const Z=T(K),Q=K.kind==="tool"?"user_tool_favorites":"user_favorites",le=K.kind==="tool"?"tool_id":"app_id",ue=K.kind==="tool"?K.id:(ne=K.tile)==null?void 0:ne.id;if(!ue)return;const se=K.kind==="tool"?p:h;se(ie=>{const ce=new Set(ie);return Z?ce.delete(ue):ce.add(ue),ce});try{if(Z){const{error:ie}=await q.from(Q).delete().eq("user_id",s.id).eq(le,ue);if(ie)throw ie}else{const{error:ie}=await q.from(Q).insert({user_id:s.id,[le]:ue});if(ie)throw ie}}catch(ie){console.error("Error toggling favorite:",ie),re.error("Failed to update favorites"),se(ce=>{const je=new Set(ce);return Z?je.add(ue):je.delete(ue),je})}},[T,s==null?void 0:s.id]),V=j.useCallback((K,Z=A)=>{const Q=K.trim().toLowerCase();if(!Q)return Z;const le=Q.split(/\s+/);return Z.filter(ue=>{const se=[ue.name,ue.description,...ue.keywords,...ue.categories,...ue.goals].join(" ").toLowerCase();return le.every(ne=>se.includes(ne))||se.includes(Q)})},[A]);return{loading:c,items:A,favoriteItems:L,recentItems:M,connectedItems:I,recent:y,firstName:b,isFavorite:T,toggleFavorite:H,openItem:$,search:V,reload:S}}function TFe(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 APe(s){const t=I7[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 EPe(){const{user:s}=vs(),[t,n]=j.useState([]),[r,a]=j.useState(!0),i=j.useCallback(async()=>{if(s!=null&&s.id)try{const{data:m,error:p}=await q.from("workflow_runs").select("*").eq("user_id",s.id).order("last_activity_at",{ascending:!1});if(p)throw p;n((m||[]).map(TFe))}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,p)=>{var f;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:p.trim()||((f=I7[m])==null?void 0:f.title)||"Untitled"}).select("*").single();if(y)throw y;const v=TFe(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,p)=>{const f={...p,last_activity_at:new Date().toISOString()};n(y=>y.map(v=>v.id===m?TFe({...v,...f}):v));const{error:x}=await q.from("workflow_runs").update(f).eq("id",m);x&&(console.error("Error updating workflow run:",x),re.error("Could not save your progress"))},[]),c=j.useCallback(async(m,p,f)=>{const x={...m.step_state};f?x[p]=f:delete x[p];const y=I7[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,p)=>o(m.id,{run_name:p.trim()}),[o]),u=j.useCallback(m=>o(m.id,{status:"in_progress",completed_at:null}),[o]),h=j.useCallback(async m=>{n(f=>f.filter(x=>x.id!==m));const{error:p}=await q.from("workflow_runs").delete().eq("id",m);p&&(console.error("Error deleting workflow run:",p),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 eYs(){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 tYs(){const s=Wn(),{items:t,firstName:n,recentItems:r,favoriteItems:a,isFavorite:i,toggleFavorite:l,openItem:o,search:c}=gre(),{isAdmin:d}=vs(),{activeRuns:u}=EPe(),h=d?u:[],[m,p]=j.useState(""),f=j.useMemo(()=>m.trim()?c(m).slice(0,8):[],[m,c]),x=j.useMemo(()=>{const v=new Set(r.map(S=>S.id)),b=[],N=S=>{for(const A of S){if(b.length>=4)break;b.some(T=>T.key===A.key)||b.push(A)}};return N(a.filter(S=>!v.has(S.id))),N(t.filter(S=>S.isNew&&!v.has(S.id))),N(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:[eYs(),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(Fr,{className:"absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"}),e.jsx(xe,{value:m,onChange:v=>p(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:f.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”."]}):f.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:Mt("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:bAe.map(v=>e.jsx(XKs,{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(Yr,{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=I7[v.workflow_id],N=APe(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(N.touched+1,N.total)," of ",N.total]})]}),e.jsx(Oa,{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:`${N.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:Mt("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(cn,{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:Mt("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(U,{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(U,{variant:"ghost",size:"sm",onClick:()=>s("/apps/my-apps"),children:"View all"})]}),e.jsx(XF,{items:a.slice(0,6),isFavorite:i,onOpen:o,onToggleFavorite:l})]})]})}function Ozt({workflow:s,activeRun:t,onStart:n,onResume:r}){const a=s.icon,i=t?APe(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:Mt("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(zr,{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(U,{className:"w-full",onClick:()=>r(t),children:["Continue ",e.jsx(Oa,{className:"h-4 w-4 ml-1"})]})]}):e.jsx("div",{className:"mt-auto",children:e.jsxs(U,{className:"w-full",onClick:()=>n(s),children:["Start Workflow ",e.jsx(Oa,{className:"h-4 w-4 ml-1"})]})})]})}function Fzt({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(Ds,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{htmlFor:"workflow-run-name",children:s==null?void 0:s.namePrompt}),e.jsx(xe,{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(Mr,{children:[e.jsx(U,{variant:"outline",onClick:t,disabled:i,children:"Cancel"}),e.jsx(U,{onClick:o,disabled:i,children:i?"Starting…":"Start workflow"})]})]})})}function sYs(){const s=Wn(),[t,n]=fc(),{items:r,isFavorite:a,toggleFavorite:i,openItem:l,search:o}=gre(),{isAdmin:c}=vs(),{activeRuns:d,startRun:u}=EPe(),h=t.get("goal"),m=t.get("category")??null,[p,f]=j.useState(t.get("q")??""),[x,y]=j.useState(null);j.useEffect(()=>{f(t.get("q")??"")},[t]);const v=(T,L)=>{const M=new URLSearchParams(t);L?M.set(T,L):M.delete(T),n(M,{replace:!0})},b=()=>{const T=new URLSearchParams(t);T.delete("category"),T.delete("goal"),T.delete("q"),n(T,{replace:!0}),f("")},N=j.useMemo(()=>{let T=r;return h&&(T=T.filter(L=>L.goals.includes(h))),m&&(T=T.filter(L=>L.categories.includes(m))),p.trim()&&(T=o(p,T)),T},[r,h,m,p,o]),S=j.useMemo(()=>h||m||p.trim()?null:bAe.map(T=>({goal:T,apps:r.filter(L=>L.goals.includes(T.id))})).filter(T=>T.apps.length>0),[r,h,m,p]),A=h?bAe.find(T=>T.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(Fr,{className:"absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"}),e.jsx(xe,{value:p,onChange:T=>{f(T.target.value),v("q",T.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:Mt("px-4 py-2 rounded-full text-sm font-medium border transition-colors whitespace-nowrap",!m&&!h&&!p.trim()?"bg-primary text-primary-foreground border-primary":"bg-card text-muted-foreground border-border hover:text-foreground"),children:"All"}),KKs.map(T=>e.jsx("button",{type:"button",onClick:()=>v("category",m===T.id?null:T.id),className:Mt("px-4 py-2 rounded-full text-sm font-medium border transition-colors whitespace-nowrap",m===T.id?"bg-primary text-primary-foreground border-primary":"bg-card text-muted-foreground border-border hover:text-foreground"),children:T.label},T.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&&!p.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:IJe.map(T=>e.jsx(Ozt,{workflow:T,activeRun:d.find(L=>L.workflow_id===T.id),onStart:y,onResume:L=>s(`/apps/workflows/${L.id}`)},T.id))})]}),S?S.map(({goal:T,apps:L})=>e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:T.title}),e.jsx(XF,{items:L,isFavorite:a,onOpen:l,onToggleFavorite:i})]},T.id)):N.length>0?e.jsx(XF,{items:N,isFavorite:a,onOpen:l,onToggleFavorite:i}):e.jsxs("div",{className:"text-center py-16 bg-card border border-border rounded-2xl",children:[e.jsx(Fr,{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(Fzt,{workflow:x,onClose:()=>y(null),onStart:async(T,L)=>{const M=await u(T.id,L);y(null),M&&s(`/apps/workflows/${M.id}`)}})]})}function nYs(){const s=Wn(),{favoriteItems:t,recentItems:n,connectedItems:r,isFavorite:a,toggleFavorite:i,openItem:l}=gre(),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(u0,{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(U,{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(u0,{className:"h-4 w-4 text-primary"})," Favorites"]}),e.jsx(XF,{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(Yr,{className:"h-4 w-4 text-muted-foreground"})," Recently used"]}),e.jsx(XF,{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(Aw,{className:"h-4 w-4 text-muted-foreground"})," Activated for your account"]}),e.jsx(XF,{items:r,isFavorite:a,onOpen:l,onToggleFavorite:i})]})]})}function rYs(){const{connectedItems:s,isFavorite:t,toggleFavorite:n,openItem:r}=gre();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(ad,{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(XF,{items:s,isFavorite:t,onOpen:r,onToggleFavorite:n})]})}function aYs(){const s=Wn(),{activeRuns:t,completedRuns:n,startRun:r,reopenRun:a,deleteRun:i}=EPe(),[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=I7[c.workflow_id],u=APe(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(U,{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:IJe.map(c=>e.jsx(Ozt,{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(zr,{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=I7[c.workflow_id])==null?void 0:d.title})]}),e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>a(c),children:[e.jsx(Kg,{className:"h-4 w-4 mr-1"})," Reopen"]}),e.jsx(U,{variant:"ghost",size:"icon","aria-label":"Delete workflow",onClick:()=>i(c.id),children:e.jsx(In,{className:"h-4 w-4 text-muted-foreground"})})]},c.id)})})]}),e.jsx(Fzt,{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 iYs(){const{runId:s}=Di(),t=Wn(),{runs:n,loading:r,setStep:a,renameRun:i,reopenRun:l,deleteRun:o}=EPe(),{items:c,openItem:d}=gre(),[u,h]=j.useState(!1),[m,p]=j.useState(""),f=j.useMemo(()=>n.find(N=>N.id===s),[n,s]),x=f?I7[f.workflow_id]:void 0;if(r)return e.jsx("p",{className:"text-muted-foreground",children:"Loading…"});if(!f||!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(U,{className:"mt-4",onClick:()=>t("/apps/workflows"),children:"Back to workflows"})]});const y=APe(f),v=x.icon,b=N=>{if(!N)return;const S=c.find(T=>T.kind==="tool"&&T.id===N);if(S){d(S);return}const A=Oxt[N];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(Aa,{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:Mt("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(xe,{value:m,onChange:N=>p(N.target.value),autoFocus:!0,onKeyDown:N=>{N.key==="Enter"&&(i(f,m),h(!1))}}),e.jsx(U,{size:"sm",onClick:()=>{i(f,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:f.run_name}),e.jsx("button",{type:"button","aria-label":"Rename workflow",onClick:()=>{p(f.run_name),h(!0)},className:"text-muted-foreground hover:text-foreground",children:e.jsx(ri,{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}%`}})})]}),f.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(zr,{className:"h-4 w-4"})," Workflow complete"]}),e.jsx(U,{variant:"outline",size:"sm",onClick:()=>l(f),children:"Reopen"})]})]}),e.jsx("ol",{className:"space-y-3",children:x.steps.map((N,S)=>{const A=f.step_state[N.key],T=N.toolId?Oxt[N.toolId]:void 0,L=A==="done",M=A==="skipped";return e.jsx("li",{className:Mt("bg-card border rounded-2xl p-4 sm:p-5 transition-colors",L?"border-emerald-500/40":M?"border-border opacity-70":"border-border"),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:Mt("w-9 h-9 rounded-full flex items-center justify-center flex-shrink-0 text-sm font-semibold",L?"bg-emerald-500 text-white":M?"bg-muted text-muted-foreground":"bg-primary/10 text-primary"),children:L?e.jsx(Xr,{className:"h-4 w-4"}):S+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:Mt("font-medium text-foreground",(L||M)&&"line-through decoration-muted-foreground/40"),children:N.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:N.detail}),T&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Uses ",T.name]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-3",children:[T&&e.jsxs(U,{size:"sm",onClick:()=>b(N.toolId),children:["Open ",T.name," ",e.jsx(Sr,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsxs(U,{size:"sm",variant:L?"secondary":"outline",onClick:()=>a(f,N.key,L?null:"done"),children:[e.jsx(Xr,{className:"h-3.5 w-3.5 mr-1"}),L?"Done":"Mark done"]}),e.jsxs(U,{size:"sm",variant:"ghost",onClick:()=>a(f,N.key,M?null:"skipped"),children:[e.jsx(lQ,{className:"h-3.5 w-3.5 mr-1"}),M?"Un-skip":"Skip"]})]})]})]})},N.key)})}),e.jsx("div",{className:"pt-2",children:e.jsxs(U,{variant:"ghost",size:"sm",className:"text-muted-foreground",onClick:()=>{o(f.id),t("/apps/workflows")},children:[e.jsx(In,{className:"h-4 w-4 mr-1"})," Delete this workflow"]})})]})}const oYs=()=>{const{isAdmin:s}=vs();return e.jsx(qs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(WKs,{}),e.jsxs(tee,{children:[e.jsx(ns,{index:!0,element:e.jsx(tYs,{})}),e.jsx(ns,{path:"browse",element:e.jsx(sYs,{})}),e.jsx(ns,{path:"my-apps",element:e.jsx(nYs,{})}),e.jsx(ns,{path:"connected",element:e.jsx(rYs,{})}),s&&e.jsx(ns,{path:"workflows",element:e.jsx(aYs,{})}),s&&e.jsx(ns,{path:"workflows/:runId",element:e.jsx(iYs,{})}),e.jsx(ns,{path:"*",element:e.jsx(td,{to:"/apps",replace:!0})})]})]})})},lYs=()=>{var N;const s=Wn(),{isAdmin:t}=vs(),[n,r]=j.useState(""),[a,i]=j.useState("all"),[l,o]=j.useState("all"),[c,d]=j.useState("grid"),{data:u=[]}=ct({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=[]}=ct({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:p}=ct({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:T,error:L}=await q.from("template_links").select("*").order("sort_order");if(L)throw L;const M=async K=>{let Q=0;const le=[];for(;;){const{data:ue,error:se}=await K().range(Q,Q+1e3-1);if(se)throw se;if(!ue||ue.length===0||(le.push(...ue),ue.length<1e3))break;Q+=1e3}return le},I=await M(()=>q.from("template_likes").select("template_id")),R=await M(()=>q.from("template_comments").select("template_id")),z=new Map;I.forEach(K=>{z.set(K.template_id,(z.get(K.template_id)||0)+1)});const $=new Map;R.forEach(K=>{$.set(K.template_id,($.get(K.template_id)||0)+1)});const H=new Map;return t&&(await M(()=>q.from("content_engagement_logs").select("resource_id").eq("resource_type","template").eq("action_type","view"))).forEach(Z=>{H.set(Z.resource_id,(H.get(Z.resource_id)||0)+1)}),(S||[]).map(K=>({...K,links:(T||[]).filter(Z=>Z.template_id===K.id)||[],likesCount:z.get(K.id)||0,commentsCount:$.get(K.id)||0,viewsCount:H.get(K.id)||0}))}}),f=m.filter(S=>{var M;const A=S.name.toLowerCase().includes(n.toLowerCase())||((M=S.description)==null?void 0:M.toLowerCase().includes(n.toLowerCase())),T=a==="all"||S.category_id===a,L=l==="all"||S.type_id===l;return A&&T&&L}),x=()=>{r(""),i("all"),o("all")},y=n||a!=="all"||l!=="all",v=(N=[...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:N.id,b=S=>{s(`/templates/${S}`)};return e.jsx(qs,{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"})]}),!p&&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(Ua,{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(we,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer relative",onClick:()=>b(S.id),children:[e.jsxs("div",{className:"aspect-[3/2] relative overflow-hidden bg-muted",children:[S.id===v&&e.jsx(Be,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),S.preview_image_url?e.jsx("img",{src:S.preview_image_url,alt:S.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"})]}),e.jsxs(Ie,{className:"p-3",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 text-sm",children:S.name}),S.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:KJ(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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search templates...",value:n,onChange:S=>r(S.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:a,onValueChange:i,children:[e.jsx(ws,{className:"w-full sm:w-48",children:e.jsx(ks,{placeholder:"All Categories"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Categories"}),u.map(S=>e.jsx(et,{value:S.id,children:S.name},S.id))]})]}),e.jsxs(Ns,{value:l,onValueChange:o,children:[e.jsx(ws,{className:"w-full sm:w-48",children:e.jsx(ks,{placeholder:"All Types"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Types"}),h.map(S=>e.jsx(et,{value:S.id,children:S.name},S.id))]})]}),e.jsxs("div",{className:"flex gap-2",children:[y&&e.jsx(U,{variant:"outline",size:"sm",onClick:x,children:"Clear Filters"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(U,{variant:c==="grid"?"secondary":"outline",size:"icon",onClick:()=>d("grid"),className:"rounded-full",children:e.jsx(Hg,{className:"h-4 w-4"})}),e.jsx(U,{variant:c==="list"?"secondary":"outline",size:"icon",onClick:()=>d("list"),className:"rounded-full",children:e.jsx(m0,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[f.length," template",f.length!==1?"s":""," found"]}),p&&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(we,{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))}),!p&&f.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(U,{variant:"outline",onClick:x,children:"Clear Filters"})]}),!p&&f.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:f.map(S=>e.jsxs(we,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${c==="list"?"flex flex-row":""}`,onClick:()=>b(S.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${c==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[S.id===v&&e.jsx(Be,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),S.preview_image_url?e.jsx("img",{src:S.preview_image_url,alt:S.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"}),S.links.length>1&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Be,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm !text-secondary",children:[e.jsx(Rc,{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:KJ(S.description)}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[S.category&&e.jsx(Be,{variant:"secondary",className:"text-xs",children:S.category.name}),S.type&&e.jsx(Be,{variant:"outline",className:"text-xs",children:S.type.name})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground mb-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(wx,{className:"h-3.5 w-3.5"}),S.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(vu,{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(xa,{className:"h-3.5 w-3.5"}),S.viewsCount]})]}),e.jsxs(U,{size:"sm",className:"w-full gap-2",onClick:A=>{A.stopPropagation(),b(S.id)},children:[e.jsx(Sr,{className:"h-4 w-4"}),"View Template"]})]})]},S.id))})]})})},cYs=()=>{const{templateId:s}=Di(),t=Wn(),{user:n,isAdmin:r}=vs(),{toast:a}=Ai(),i=Qt(),{trackEngagement:l}=EG(),[o,c]=j.useState(""),{data:d,isLoading:u}=ct({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:T}=await q.from("template_links").select("*").eq("template_id",s).order("sort_order"),{data:L}=await q.from("template_guides").select("*").eq("template_id",s).order("sort_order");return{...S,links:T||[],guides:L||[]}},enabled:!!s}),{data:h=[]}=ct({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(T=>T.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=[]}=ct({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:p=[]}=ct({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 T=[...new Set(S.map(I=>I.user_id))],{data:L}=await q.from("profiles").select("id, name").in("id",T),M=new Map((L==null?void 0:L.map(I=>[I.id,I.name]))||[]);return S.map(I=>({...I,user_name:M.get(I.user_id)||"Unknown User"}))},enabled:!!s}),f=yt({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=yt({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=yt({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),N=S=>{S.preventDefault(),!(!o.trim()||!n)&&f.mutate(o.trim())};return u?e.jsx(qs,{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(qs,{title:d.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(U,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(xr,{to:"/templates",children:[e.jsx(Aa,{className:"h-4 w-4"}),"Back to Templates"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:d.name}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[d.category&&e.jsx(Be,{variant:"secondary",children:d.category.name}),d.type&&e.jsx(Be,{variant:"outline",children:d.type.name})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&e.jsx(U,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(xr,{to:`/admin/templates?edit=${d.id}`,children:[e.jsx(ri,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(PG,{resourceType:"template",resourceId:d.id,resourceTitle:d.name,size:"default",className:"rounded-full"}),e.jsxs(U,{variant:v?"default":"outline",className:"gap-2 rounded-full",onClick:()=>y.mutate(),disabled:!n||y.isPending,children:[e.jsx(wx,{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(we,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Rc,{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(U,{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(Sr,{className:"h-4 w-4 text-muted-foreground"})]},S.id))})]})}),d.video_url&&e.jsx(we,{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(we,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Ur,{className:"h-4 w-4"}),"Guide Files"]}),e.jsx("div",{className:"grid gap-2",children:d.guides.map(S=>e.jsxs(U,{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(Ur,{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(pi,{className:"h-4 w-4 text-muted-foreground"})]},S.id))})]})}),h.length>0&&e.jsx(we,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(dh,{className:"h-4 w-4"}),"Related Toolkits"]}),e.jsx("div",{className:"grid gap-2",children:h.map(S=>e.jsxs(U,{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(dh,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"font-medium",children:S.name})]},S.id))})]})}),e.jsx(hc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(vu,{className:"h-5 w-5"}),"Comments (",p.length,")"]}),n?e.jsxs("form",{onSubmit:N,className:"flex gap-2",children:[e.jsx(Fs,{placeholder:"Add a comment...",value:o,onChange:S=>c(S.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(U,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!o.trim()||f.isPending,children:e.jsx($r,{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:p.length===0?e.jsx(we,{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!"})})}):p.map(S=>e.jsx(we,{children:e.jsx(Ie,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ea,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Ta,{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:Nd(new Date(S.created_at),{addSuffix:!0})}),S.user_id===(n==null?void 0:n.id)&&e.jsx(U,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>x.mutate(S.id),children:e.jsx(In,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:S.content})]})]})})},S.id))})]})]})}):e.jsx(qs,{title:"Templates",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Rc,{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(U,{asChild:!0,className:"mt-4",children:e.jsx(xr,{to:"/templates",children:"Back to Templates"})})]})})},Fxt=({program:s,enrolled:t})=>{const{notOpenYet:n,closed:r,opensLabel:a}=aPe(s);return e.jsxs(we,{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(cn,{className:"h-10 w-10 text-primary/60"})}),e.jsxs("div",{className:"absolute left-3 top-3 flex gap-2",children:[s.is_featured&&e.jsx(Be,{className:"shadow-sm",children:"Featured"}),t&&e.jsxs(Be,{variant:"secondary",className:"shadow-sm",children:[e.jsx(zr,{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(Yr,{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(nc,{className:"h-3.5 w-3.5"}),"Starts ",Zd(s.kickoff_at)]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Bn,{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":gf(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 ",gee(s.duration_weeks)," — no subscription",s.charge_at?` · charged ${Zd(s.charge_at)}`:""]}):null]}),e.jsx(U,{asChild:!0,size:"sm",children:e.jsxs(xr,{to:t?`/programs/${s.slug}/workspace`:`/programs/${s.slug}`,children:[t?"Open program":n?"Preview details":"View details",e.jsx(Oa,{className:"ml-1.5 h-4 w-4"})]})})]})]})]})},dYs=()=>{const{data:s=[],isLoading:t}=u7t(),{data:n=[]}=VQe(),r=new Set(n.filter(l=>GV(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(qs,{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(Fxt,{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(we,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(cn,{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(Fxt,{program:l,enrolled:!1},l.id))})]})]})]})})},uYs=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},hYs=({url:s,headline:t,posterUrl:n})=>{const[r,a]=j.useState(!1),i=(s||"").trim();if(!i)return null;const l=uYs(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($h,{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 TPe="Collapsible",[mYs,zzt]=Up(TPe),[pYs,RJe]=mYs(TPe),Bzt=j.forwardRef((s,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:a,disabled:i,onOpenChange:l,...o}=s,[c,d]=Sx({prop:r,defaultProp:a??!1,onChange:l,caller:TPe});return e.jsx(pYs,{scope:n,disabled:i,contentId:jx(),open:c,onOpenToggle:j.useCallback(()=>d(u=>!u),[d]),children:e.jsx(si.div,{"data-state":zJe(c),"data-disabled":i?"":void 0,...o,ref:t})})});Bzt.displayName=TPe;var Uzt="CollapsibleTrigger",DJe=j.forwardRef((s,t)=>{const{__scopeCollapsible:n,...r}=s,a=RJe(Uzt,n);return e.jsx(si.button,{type:"button","aria-controls":a.contentId,"aria-expanded":a.open||!1,"data-state":zJe(a.open),"data-disabled":a.disabled?"":void 0,disabled:a.disabled,...r,ref:t,onClick:va(s.onClick,a.onOpenToggle)})});DJe.displayName=Uzt;var OJe="CollapsibleContent",FJe=j.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=RJe(OJe,s.__scopeCollapsible);return e.jsx(Xg,{present:n||a.open,children:({present:i})=>e.jsx(fYs,{...r,ref:t,present:i})})});FJe.displayName=OJe;var fYs=j.forwardRef((s,t)=>{const{__scopeCollapsible:n,present:r,children:a,...i}=s,l=RJe(OJe,n),[o,c]=j.useState(r),d=j.useRef(null),u=Uo(t,d),h=j.useRef(0),m=h.current,p=j.useRef(0),f=p.current,x=l.open||o,y=j.useRef(x),v=j.useRef(void 0);return j.useEffect(()=>{const b=requestAnimationFrame(()=>y.current=!1);return()=>cancelAnimationFrame(b)},[]),dg(()=>{const b=d.current;if(b){v.current=v.current||{transitionDuration:b.style.transitionDuration,animationName:b.style.animationName},b.style.transitionDuration="0s",b.style.animationName="none";const N=b.getBoundingClientRect();h.current=N.height,p.current=N.width,y.current||(b.style.transitionDuration=v.current.transitionDuration,b.style.animationName=v.current.animationName),c(r)}},[l.open,r]),e.jsx(si.div,{"data-state":zJe(l.open),"data-disabled":l.disabled?"":void 0,id:l.contentId,hidden:!x,...i,ref:u,style:{"--radix-collapsible-content-height":m?`${m}px`:void 0,"--radix-collapsible-content-width":f?`${f}px`:void 0,...s.style},children:x&&a})});function zJe(s){return s?"open":"closed"}var qzt=Bzt,gYs=DJe,xYs=FJe,NS="Accordion",yYs=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[BJe,vYs,bYs]=tG(NS),[MPe,$gr]=Up(NS,[bYs,zzt]),UJe=zzt(),$zt=Dt.forwardRef((s,t)=>{const{type:n,...r}=s,a=r,i=r;return e.jsx(BJe.Provider,{scope:s.__scopeAccordion,children:n==="multiple"?e.jsx(NYs,{...i,ref:t}):e.jsx(jYs,{...a,ref:t})})});$zt.displayName=NS;var[Vzt,_Ys]=MPe(NS),[Hzt,wYs]=MPe(NS,{collapsible:!1}),jYs=Dt.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},collapsible:i=!1,...l}=s,[o,c]=Sx({prop:n,defaultProp:r??"",onChange:a,caller:NS});return e.jsx(Vzt,{scope:s.__scopeAccordion,value:Dt.useMemo(()=>o?[o]:[],[o]),onItemOpen:c,onItemClose:Dt.useCallback(()=>i&&c(""),[i,c]),children:e.jsx(Hzt,{scope:s.__scopeAccordion,collapsible:i,children:e.jsx(Gzt,{...l,ref:t})})})}),NYs=Dt.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=Sx({prop:n,defaultProp:r??[],onChange:a,caller:NS}),c=Dt.useCallback(u=>o((h=[])=>[...h,u]),[o]),d=Dt.useCallback(u=>o((h=[])=>h.filter(m=>m!==u)),[o]);return e.jsx(Vzt,{scope:s.__scopeAccordion,value:l,onItemOpen:c,onItemClose:d,children:e.jsx(Hzt,{scope:s.__scopeAccordion,collapsible:!0,children:e.jsx(Gzt,{...i,ref:t})})})}),[kYs,PPe]=MPe(NS),Gzt=Dt.forwardRef((s,t)=>{const{__scopeAccordion:n,disabled:r,dir:a,orientation:i="vertical",...l}=s,o=Dt.useRef(null),c=Uo(o,t),d=vYs(n),h=xE(a)==="ltr",m=va(s.onKeyDown,p=>{var M;if(!yYs.includes(p.key))return;const f=p.target,x=d().filter(I=>{var R;return!((R=I.ref.current)!=null&&R.disabled)}),y=x.findIndex(I=>I.ref.current===f),v=x.length;if(y===-1)return;p.preventDefault();let b=y;const N=0,S=v-1,A=()=>{b=y+1,b>S&&(b=N)},T=()=>{b=y-1,b{const{__scopeAccordion:n,value:r,...a}=s,i=PPe(_Ae,n),l=_Ys(_Ae,n),o=UJe(n),c=jx(),d=r&&l.value.includes(r)||!1,u=i.disabled||s.disabled;return e.jsx(SYs,{scope:n,open:d,disabled:u,triggerId:c,children:e.jsx(qzt,{"data-orientation":i.orientation,"data-state":Jzt(d),...o,...a,ref:t,disabled:u,open:d,onOpenChange:h=>{h?l.onItemOpen(r):l.onItemClose(r)}})})});Wzt.displayName=_Ae;var Kzt="AccordionHeader",Yzt=Dt.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=PPe(NS,n),i=qJe(Kzt,n);return e.jsx(si.h3,{"data-orientation":a.orientation,"data-state":Jzt(i.open),"data-disabled":i.disabled?"":void 0,...r,ref:t})});Yzt.displayName=Kzt;var K$e="AccordionTrigger",Zzt=Dt.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=PPe(NS,n),i=qJe(K$e,n),l=wYs(K$e,n),o=UJe(n);return e.jsx(BJe.ItemSlot,{scope:n,children:e.jsx(gYs,{"aria-disabled":i.open&&!l.collapsible||void 0,"data-orientation":a.orientation,id:i.triggerId,...o,...r,ref:t})})});Zzt.displayName=K$e;var Xzt="AccordionContent",Qzt=Dt.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=PPe(NS,n),i=qJe(Xzt,n),l=UJe(n);return e.jsx(xYs,{role:"region","aria-labelledby":i.triggerId,"data-orientation":a.orientation,...l,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...s.style}})});Qzt.displayName=Xzt;function Jzt(s){return s?"open":"closed"}var CYs=$zt,AYs=Wzt,EYs=Yzt,eBt=Zzt,tBt=Qzt;const y9=CYs,WP=j.forwardRef(({className:s,...t},n)=>e.jsx(AYs,{ref:n,className:Mt("border-b",s),...t}));WP.displayName="AccordionItem";const KP=j.forwardRef(({className:s,children:t,...n},r)=>e.jsx(EYs,{className:"flex",children:e.jsxs(eBt,{ref:r,className:Mt("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(rl,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));KP.displayName=eBt.displayName;const YP=j.forwardRef(({className:s,children:t,...n},r)=>e.jsx(tBt,{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:Mt("pb-4 pt-0",s),children:t})}));YP.displayName=tBt.displayName;const TYs=({programId:s,opensLabel:t})=>{const{data:n,isLoading:r}=K9s(s),a=Y9s(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(A4,{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(U,{variant:i?"outline":"default",size:"sm",disabled:r||a.isPending,onClick:()=>a.mutate(!i),className:"shrink-0",children:[a.isPending?e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}):i?e.jsx(Xr,{className:"mr-2 h-4 w-4"}):e.jsx(A4,{className:"mr-2 h-4 w-4"}),i?"You're on the list":"Notify me"]})]})},MYs=()=>{const{slug:s}=Di(),{data:t,isLoading:n}=$Qe(s),{data:r}=h7t(t==null?void 0:t.id),{data:a}=HQe(t==null?void 0:t.id),i=GV(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(qs,{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(qs,{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(U,{asChild:!0,className:"mt-6",children:e.jsx(xr,{to:"/programs",children:"Back to Programs"})})]})});const p=typeof r=="number"&&r<=0&&!i,{notOpenYet:f,closed:x,opensLabel:y}=aPe(t),v=!i&&(p||x||f),b=i?"Open your program":f?`Enrollment opens ${Zd(t.enrollment_open_at)}`:p?"Cohort is full":x?"Enrollment closed":t.payment_mode==="delayed"?"Reserve my seat":"Enroll now",N=i?`/programs/${t.slug}/workspace`:`/programs/${t.slug}/enroll`;return e.jsxs(qs,{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(hYs,{url:t.promo_video_url,headline:t.promo_video_headline,posterUrl:t.hero_image_url||t.cover_image_url}):t.hero_image_url||t.cover_image_url?e.jsx("img",{src:t.hero_image_url||t.cover_image_url,alt:`${t.name} hero`,className:"h-56 w-full object-cover md:h-72"}):e.jsx("div",{className:"h-40 w-full bg-gradient-to-br from-primary/20 via-background to-accent/20 md:h-56"})}),e.jsxs("div",{className:"space-y-6 p-6 md:p-8",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Be,{variant:"secondary",children:[t.duration_weeks,"-week program"]}),typeof r=="number"&&!i&&e.jsx(Be,{variant:r<=10?"destructive":"outline",children:r>0?`${r} of ${t.capacity} seats left`:"Full"}),i&&e.jsxs(Be,{children:[e.jsx(zr,{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":gf(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 ",gee(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:Zd(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(oy,{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:[d$e(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:Zd(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(U,{asChild:!v,size:"lg",disabled:v,children:v?e.jsx("span",{children:b}):e.jsxs(xr,{to:N,children:[b,e.jsx(Oa,{className:"ml-2 h-4 w-4"})]})}),e.jsx(U,{asChild:!0,variant:"ghost",size:"lg",children:e.jsx(xr,{to:"/programs",children:"All programs"})})]}),f&&!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(nc,{className:"h-3.5 w-3.5"}),"Enrollment opens ",y]}),e.jsx(TYs,{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(zr,{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(we,{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(cn,{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(we,{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(zr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),S]},A))})]})}),u.length>0&&e.jsx(we,{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(Yr,{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(y9,{type:"single",collapsible:!0,className:"rounded-xl border border-border/60 px-4",children:h.map((S,A)=>e.jsxs(WP,{value:`faq-${A}`,children:[e.jsx(KP,{className:"text-left text-sm font-medium",children:S.q}),e.jsx(YP,{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(Wr,{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(U,{asChild:!v,size:"lg",disabled:v,children:v?e.jsx("span",{children:b}):e.jsxs(xr,{to:N,children:[b,e.jsx(Oa,{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(Bn,{className:"h-4 w-4"}),r," seats remaining"]})]}),!i&&(f?e.jsxs("p",{className:"mt-3 inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(nc,{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(nc,{className:"h-3.5 w-3.5"}),"Enrollment closes ",Zd(t.enrollment_close_at)]}):null)]})]})]})},ele=["Your business","Your content","Your goals","Reserve your seat"],PYs=()=>{const{slug:s}=Di(),t=Wn(),[n,r]=fc(),{user:a}=vs(),{data:i,isLoading:l}=$Qe(s),{data:o}=h7t(i==null?void 0:i.id),{data:c,refetch:d}=HQe(i==null?void 0:i.id),{data:u}=m7t(i==null?void 0:i.id),h=k9s(),m=S9s(),p=R9s(),f=D9s(),[x,y]=j.useState(0),[v,b]=j.useState(!1),[N,S]=j.useState(!1),[A,T]=j.useState(!1),[L,M]=j.useState(!1),[I,R]=j.useState(""),[z,$]=j.useState(null),H=j.useRef({}),[V,K]=j.useState({}),Z=j.useRef(!1),Q=(Ve,qe)=>{H.current={...H.current,[Ve]:qe},K(H.current)};j.useEffect(()=>{Z.current||(u?(H.current={...u},K(H.current),Z.current=!0):a&&(H.current={email:a.email,...H.current},K(H.current)))},[u,a]),j.useEffect(()=>{const Ve=c;!i||!(Ve!=null&&Ve.discount_code)||z||$({code:Ve.discount_code,discount_cents:Ve.discount_cents||0,amount_cents:Ve.amount_cents??i.price_cents,original_cents:i.price_cents})},[c,i,z]);const le=z?z.amount_cents:(i==null?void 0:i.price_cents)??0,ue=j.useMemo(()=>xee(i),[i]),se=Ve=>N9s(ue,Ve),ne=Ve=>$ft(ue,Ve)?e.jsx("span",{className:"text-destructive",children:" *"}):null,ie=(Ve,qe)=>{const Ze={...H.current.extra||{},[Ve]:qe};Q("extra",Ze)},ce=Ve=>ue.custom.filter((qe,Ze)=>Ze%3===Ve),je=Ve=>{const qe=ce(Ve);if(!qe.length)return null;const Ze=V.extra||{};return e.jsx("div",{className:"space-y-4",children:qe.map(Ue=>e.jsxs("div",{className:"space-y-2",children:[Ue.type==="checkbox"?e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(xi,{id:Ue.id,checked:!!Ze[Ue.id],onCheckedChange:Ye=>ie(Ue.id,!!Ye)}),e.jsxs(te,{htmlFor:Ue.id,className:"text-sm font-normal leading-relaxed",children:[Ue.label,Ue.required&&e.jsx("span",{className:"text-destructive",children:" *"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(te,{htmlFor:Ue.id,children:[Ue.label,Ue.required&&e.jsx("span",{className:"text-destructive",children:" *"})]}),Ue.type==="long_text"?e.jsx(Fs,{id:Ue.id,rows:3,value:Ze[Ue.id]||"",onChange:Ye=>ie(Ue.id,Ye.target.value)}):Ue.type==="select"?e.jsxs(Ns,{value:Ze[Ue.id]||"",onValueChange:Ye=>ie(Ue.id,Ye),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select"})}),e.jsx(js,{children:(Ue.options||[]).map(Ye=>e.jsx(et,{value:Ye,children:Ye},Ye))})]}):e.jsx(xe,{id:Ue.id,value:Ze[Ue.id]||"",onChange:Ye=>ie(Ue.id,Ye.target.value)})]}),Ue.help&&e.jsx("p",{className:"text-xs text-muted-foreground",children:Ue.help})]},Ue.id))})},be=Ve=>{const qe=H.current,Ze=He=>He==null||He===""||He===!1,Ue=qQe.find(He=>He.step===Ve&&$ft(ue,He.key)&&Ze(He.key==="timezone"?qe.timezone||(i==null?void 0:i.timezone):qe[He.key]));if(Ue)return Ue.label;const Ye=qe.extra||{},Ge=ce(Ve).find(He=>He.required&&Ze(Ye[He.id]));return Ge?Ge.label:null},he=()=>{if(x<=2){const Ve=be(x);if(Ve)return re.error(`Please answer: ${Ve}`)}y(Ve=>Ve+1)},ge=async()=>{if(!(!i||!I.trim()))try{let Ve=c==null?void 0:c.id;(!Ve||(c==null?void 0:c.status)==="canceled")&&(Ve=await m.mutateAsync(i.id));const qe=await p.mutateAsync({enrollmentId:Ve,code:I});$(qe),R(""),await d(),re.success(`Code applied — you save ${gf(qe.discount_cents,i.currency)}`)}catch(Ve){re.error(Ve.message||"That code could not be applied")}},ke=async()=>{if(!(c!=null&&c.id))return $(null);try{await f.mutateAsync(c.id),$(null),await d()}catch(Ve){re.error(Ve.message||"Could not remove the code")}},Te=n.get("setup"),Me=n.get("session_id"),Oe=j.useRef(!1);j.useEffect(()=>{Te!=="success"||!Me||!(c!=null&&c.id)||Oe.current||(Oe.current=!0,S(!0),(async()=>{const{data:Ve,error:qe}=await q.functions.invoke("program-enroll",{body:{action:"verify",enrollment_id:c.id,session_id:Me}});if(S(!1),qe||Ve!=null&&Ve.error||(Ve==null?void 0:Ve.success)===!1){re.error((Ve==null?void 0:Ve.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")})())},[Te,Me,c==null?void 0:c.id]),j.useEffect(()=>{Te==="cancelled"&&re.info("Checkout cancelled — your seat is held for a short while.")},[Te]);const Se=j.useMemo(()=>c&&["reserved","scheduled_for_charge","paid","completed"].includes(c.status),[c]),Qe=async()=>{if(i){if(!A||i.payment_mode!=="free"&&!L){re.error("Please confirm the checkboxes to continue");return}b(!0);try{let Ve=c==null?void 0:c.id;(!Ve||(c==null?void 0:c.status)==="canceled")&&(Ve=await m.mutateAsync(i.id)),await h.mutateAsync({...H.current,id:void 0,program_id:i.id,enrollment_id:Ve,created_at:void 0,updated_at:void 0,user_id:void 0});const{data:qe,error:Ze}=await q.functions.invoke("program-enroll",{body:{action:"setup",enrollment_id:Ve}});if(Ze||qe!=null&&qe.error)throw new Error((qe==null?void 0:qe.error)||(Ze==null?void 0:Ze.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(Ve){re.error(Ve.message||"Could not start enrollment")}finally{b(!1)}}};if(l)return e.jsx(qs,{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(qs,{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(U,{asChild:!0,className:"mt-6",children:e.jsx(xr,{to:"/programs",children:"Back to Programs"})})]})});if(GV(c)&&Se&&Te!=="success")return e.jsx(qs,{children:e.jsxs("div",{className:"mx-auto max-w-xl space-y-4 p-12 text-center",children:[e.jsx(zr,{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 ${Zd(c==null?void 0:c.charge_scheduled_at)||"the program start date"}.`}),e.jsx(U,{asChild:!0,size:"lg",children:e.jsx(xr,{to:`/programs/${i.slug}/workspace`,children:"Open your program workspace"})})]})});const Ae=typeof o=="number"&&o<=0,{notOpenYet:Fe,closed:Ne,opensLabel:$e}=aPe(i);return Fe||Ne?e.jsx(qs,{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:Fe?"Enrollment is not open yet":"Enrollment is closed"}),e.jsx("p",{className:"text-muted-foreground",children:Fe?`Enrollment for ${i.name} opens ${$e}. Come back then to reserve your seat.`:`Enrollment for ${i.name} has closed. Watch the Hub for the next cohort.`}),e.jsx(U,{asChild:!0,children:e.jsx(xr,{to:`/programs/${i.slug}`,children:"Back to program details"})})]})}):e.jsx(qs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-6 p-4 md:p-8",children:[e.jsx(U,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2",children:e.jsxs(xr,{to:`/programs/${i.slug}`,children:[e.jsx(Aa,{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?`${d$e(i.price_cents,i.currency,i.duration_weeks)}. Your card is saved today and charged once on ${Zd(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:ele[x]}),e.jsxs("span",{children:["Step ",x+1," of ",ele.length]})]}),e.jsx(ro,{value:(x+1)/ele.length*100})]}),N&&e.jsx(we,{className:"border-primary/40 bg-primary/5",children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4 text-sm",children:[e.jsx(Et,{className:"h-4 w-4 animate-spin text-primary"}),"Confirming your card with Stripe…"]})}),e.jsx(we,{children:e.jsxs(Ie,{className:"space-y-5 p-6",children:[x===0&&ue.intro&&e.jsx("p",{className:"rounded-lg border border-border/60 bg-muted/30 p-4 text-sm text-muted-foreground",children:ue.intro}),x===0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[se("full_name")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"full_name",children:["Full name",ne("full_name")]}),e.jsx(xe,{id:"full_name",value:V.full_name||"",onChange:Ve=>Q("full_name",Ve.target.value)})]}),se("phone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"phone",children:["Mobile number",ne("phone")]}),e.jsx(xe,{id:"phone",value:V.phone||"",onChange:Ve=>Q("phone",Ve.target.value)})]}),se("instagram_handle")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"instagram_handle",children:["Instagram handle",ne("instagram_handle")]}),e.jsx(xe,{id:"instagram_handle",placeholder:"@yourhandle",value:V.instagram_handle||"",onChange:Ve=>Q("instagram_handle",Ve.target.value)})]}),se("city")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"city",children:["Primary city / market",ne("city")]}),e.jsx(xe,{id:"city",value:V.city||"",onChange:Ve=>Q("city",Ve.target.value)})]})]}),se("service_areas")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"service_areas",children:["Neighborhoods or areas you serve",ne("service_areas")]}),e.jsx(Fs,{id:"service_areas",rows:2,value:V.service_areas||"",onChange:Ve=>Q("service_areas",Ve.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[se("years_experience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{children:["Years in real estate",ne("years_experience")]}),e.jsxs(Ns,{value:V.years_experience||"",onValueChange:Ve=>Q("years_experience",Ve),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select"})}),e.jsx(js,{children:["Less than 1","1-3","4-7","8-15","15+"].map(Ve=>e.jsx(et,{value:Ve,children:Ve},Ve))})]})]}),se("specialty")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"specialty",children:["Specialty or niche",ne("specialty")]}),e.jsx(xe,{id:"specialty",value:V.specialty||"",onChange:Ve=>Q("specialty",Ve.target.value)})]})]}),je(0)]}),x===1&&e.jsxs(e.Fragment,{children:[se("target_audience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"target_audience",children:["Who are you trying to reach?",ne("target_audience")]}),e.jsx(Fs,{id:"target_audience",rows:2,placeholder:"First-time buyers, move-up sellers, investors…",value:V.target_audience||"",onChange:Ve=>Q("target_audience",Ve.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[se("video_comfort")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{children:["How comfortable are you on camera?",ne("video_comfort")]}),e.jsxs(Ns,{value:V.video_comfort||"",onValueChange:Ve=>Q("video_comfort",Ve),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select"})}),e.jsx(js,{children:["Terrified","Nervous but willing","Getting comfortable","Very comfortable"].map(Ve=>e.jsx(et,{value:Ve,children:Ve},Ve))})]})]}),se("posting_frequency")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{children:["How often do you post today?",ne("posting_frequency")]}),e.jsxs(Ns,{value:V.posting_frequency||"",onValueChange:Ve=>Q("posting_frequency",Ve),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select"})}),e.jsx(js,{children:["Never","Rarely","Weekly","A few times a week","Daily"].map(Ve=>e.jsx(et,{value:Ve,children:Ve},Ve))})]})]})]}),se("content_style")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"content_style",children:["What content style feels like you?",ne("content_style")]}),e.jsx(Fs,{id:"content_style",rows:2,placeholder:"Educational, funny, behind-the-scenes, luxury-polished…",value:V.content_style||"",onChange:Ve=>Q("content_style",Ve.target.value)})]}),se("personal_interests")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"personal_interests",children:["Interests or hobbies we can weave in",ne("personal_interests")]}),e.jsx(Fs,{id:"personal_interests",rows:2,value:V.personal_interests||"",onChange:Ve=>Q("personal_interests",Ve.target.value)})]}),je(1)]}),x===2&&e.jsxs(e.Fragment,{children:[se("primary_goal")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"primary_goal",children:["Your #1 goal for this program",ne("primary_goal")]}),e.jsx(Fs,{id:"primary_goal",rows:3,value:V.primary_goal||"",onChange:Ve=>Q("primary_goal",Ve.target.value)})]}),se("topics_to_avoid")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"topics_to_avoid",children:["Anything you don't want to talk about",ne("topics_to_avoid")]}),e.jsx(Fs,{id:"topics_to_avoid",rows:2,value:V.topics_to_avoid||"",onChange:Ve=>Q("topics_to_avoid",Ve.target.value)})]}),se("timezone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{children:["Your time zone",ne("timezone")]}),e.jsxs(Ns,{value:V.timezone||i.timezone,onValueChange:Ve=>Q("timezone",Ve),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select"})}),e.jsx(js,{children:["America/New_York","America/Chicago","America/Denver","America/Phoenix","America/Los_Angeles","Pacific/Honolulu"].map(Ve=>e.jsx(et,{value:Ve,children:Ve.replace("America/","").replace("_"," ")},Ve))})]})]}),je(2),se("consent_public_profile")&&e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(xi,{id:"consent_public_profile",checked:!!V.consent_public_profile,onCheckedChange:Ve=>Q("consent_public_profile",!!Ve)}),e.jsx(te,{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":z?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-normal text-muted-foreground line-through",children:gf(z.original_cents,i.currency)}),gf(le,i.currency)]}):gf(i.price_cents,i.currency)})]}),i.payment_mode!=="free"&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:d$e(le,i.currency,i.duration_weeks)}),i.payment_mode!=="free"&&e.jsx("div",{className:"mt-3 border-t border-border/60 pt-3",children:z?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(Cf,{className:"h-3.5 w-3.5 text-primary"}),"Code ",e.jsx("span",{className:"font-mono font-semibold",children:z.code})," applied — you save ",gf(z.discount_cents,i.currency)]}),e.jsxs(U,{variant:"ghost",size:"sm",onClick:ke,disabled:f.isPending,children:[e.jsx(er,{className:"mr-1 h-3.5 w-3.5"})," Remove"]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"discount_code",className:"text-xs text-muted-foreground",children:"Have a discount code?"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{id:"discount_code",placeholder:"Enter code",className:"font-mono uppercase",value:I,onChange:Ve=>R(Ve.target.value.toUpperCase()),onKeyDown:Ve=>{Ve.key==="Enter"&&(Ve.preventDefault(),ge())}}),e.jsx(U,{variant:"outline",onClick:ge,disabled:!I.trim()||p.isPending||m.isPending,children:p.isPending||m.isPending?e.jsx(Et,{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(oy,{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:Zd(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(xi,{id:"terms",checked:A,onCheckedChange:Ve=>T(!!Ve)}),e.jsx(te,{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(xi,{id:"charge",checked:L,onCheckedChange:Ve=>M(!!Ve)}),e.jsx(te,{htmlFor:"charge",className:"text-sm font-normal leading-relaxed",children:i.payment_mode==="delayed"?`I authorize LevelUp to charge my saved card one time — ${gf(le,i.currency)} for the ${gee(i.duration_weeks)} — on ${Zd(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 — ${gf(le,i.currency)} for the ${gee(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(cg,{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(U,{variant:"ghost",onClick:()=>y(Ve=>Math.max(0,Ve-1)),disabled:x===0||v,children:[e.jsx(Aa,{className:"mr-1.5 h-4 w-4"})," Back"]}),xString(s).padStart(2,"0"),PFe=s=>s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",LYs=({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:${PFe(new Date)}`,`DTSTART:${PFe(d)}`,`DTEND:${PFe(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"})),p=document.createElement("a");p.href=m,p.download="program-kickoff.ics",p.click(),URL.revokeObjectURL(m)},c=[{label:"Days",value:i.days},{label:"Hours",value:MFe(i.hours)},{label:"Minutes",value:MFe(i.minutes)},{label:"Seconds",value:MFe(i.seconds)}];return e.jsxs(we,{className:"relative overflow-hidden border-primary/25",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-primary/15 via-background to-secondary/10"}),s.hero_image_url&&e.jsx("img",{src:s.hero_image_url,alt:"",className:"pointer-events-none absolute inset-0 h-full w-full object-cover opacity-10"}),e.jsxs(Ie,{className:"relative space-y-6 p-6 md:p-9",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Be,{className:"gap-1.5",children:[e.jsx(cn,{className:"h-3.5 w-3.5"})," Your seat is confirmed"]}),e.jsxs(Be,{variant:"outline",className:"gap-1.5",children:[e.jsx(Yr,{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(U,{onClick:o,size:"lg",children:[e.jsx(sv,{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(zr,{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))})]})]})},LFe=s=>s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",IYs=(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:${LFe(new Date)}`,`DTSTART:${LFe(n)}`,`DTEND:${LFe(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)},RYs={pdf:Ur,document:Qk,checklist:cy,template_link:ej,video:Gh,external:ad},DYs=()=>{var ce;const{slug:s}=Di(),[t]=fc(),{isAdmin:n}=vs(),r=n?t.get("as"):null,a=t.get("name")||"this member",i=n&&(t.get("preview")==="1"||!!r),{data:l,isLoading:o}=$Qe(s),{data:c}=HQe(l==null?void 0:l.id),{data:d,isLoading:u}=C9s(l==null?void 0:l.id,r),h=A9s(l==null?void 0:l.id),m=E9s(l==null?void 0:l.id),p=T9s(l==null?void 0:l.id),f=M9s(l==null?void 0:l.id),{data:x}=m7t(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),[N,S]=j.useState({title:"",instagram_url:""}),[A,T]=j.useState({}),[L,M]=j.useState(null),I=j.useMemo(()=>{if(!(l!=null&&l.kickoff_at))return 1;const je=Math.floor((Date.now()-new Date(l.kickoff_at).getTime())/864e5);return Math.min(Math.max(Math.floor(je/7)+1,1),l.duration_weeks)},[l]),R=new Set(((d==null?void 0:d.completions)||[]).map(je=>je.lesson_id)),z=(d==null?void 0:d.lessons)||[],$=z.length?Math.round(R.size/z.length*100):0,H=((d==null?void 0:d.videoLogs)||[]).filter(je=>je.week_number===I).length,V=((d==null?void 0:d.videoLogs)||[]).length,K=(l==null?void 0:l.weekly_video_goal)||3,Z=j.useMemo(()=>{const je=new Map;((d==null?void 0:d.videoLogs)||[]).forEach(he=>je.set(he.week_number,(je.get(he.week_number)||0)+1));let be=0;for(let he=I;he>=1;he--)if((je.get(he)||0)>=K)be++;else if(he!==I)break;return be},[d==null?void 0:d.videoLogs,I,K]);if(o||u)return e.jsx(qs,{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(qs,{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(U,{asChild:!0,className:"mt-6",children:e.jsx(xr,{to:"/programs",children:"Back to Programs"})})]})});if(!GV(c)&&!i)return e.jsx(qs,{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(U,{asChild:!0,size:"lg",children:e.jsx(xr,{to:`/programs/${l.slug}`,children:"View the program"})})]})});const Q=((d==null?void 0:d.events)||[]).filter(je=>new Date(je.starts_at)>=new Date),le=((d==null?void 0:d.events)||[]).filter(je=>new Date(je.starts_at)je.is_pinned),ne=[...(d==null?void 0:d.myResources)||[],...(d==null?void 0:d.resources)||[]].reduce((je,be)=>{const he=be.user_id?`Just for you · ${be.category}`:be.category;return(je[he]||(je[he]=[])).push(be),je},{}),ie=((d==null?void 0:d.progress)||[]).find(je=>je.week_number===I)||{};return e.jsx(qs,{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||!GV(c))&&e.jsx(we,{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(U,{variant:"outline",size:"sm",asChild:!0,children:e.jsx(xr,{to:"/admin/programs",children:"Back to Programs admin"})})]})}),e.jsxs("header",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Be,{variant:"secondary",children:["Week ",I," of ",l.duration_weeks]}),(c==null?void 0:c.status)==="scheduled_for_charge"&&c.charge_scheduled_at&&e.jsxs(Be,{variant:"outline",children:["Billing ",Zd(c.charge_scheduled_at)]}),(c==null?void 0:c.status)==="payment_failed"&&e.jsx(Be,{variant:"destructive",children:"Payment issue"})]}),e.jsx("p",{className:"neon-eyebrow font-semibold",children:"LevelUp Program"}),e.jsx("h1",{className:"neon-title w-fit text-4xl font-black uppercase tracking-tight md:text-5xl",children:l.name}),l.subtitle&&e.jsx("p",{className:"text-muted-foreground",children:l.subtitle})]}),y&&e.jsx(LYs,{program:l,intakeComplete:!!x}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(we,{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(Gu,{className:"h-3.5 w-3.5 text-primary"})," This week"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[H,e.jsxs("span",{className:"text-base font-normal text-muted-foreground",children:[" / ",K]})]}),e.jsx(ro,{value:Math.min(H/K*100,100),className:"h-1.5"})]})}),e.jsx(we,{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(Gh,{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(we,{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(Xd,{className:"h-3.5 w-3.5 text-primary"})," Streak"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[Z," wk"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"hitting your goal"})]})}),e.jsx(we,{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(rc,{className:"h-3.5 w-3.5 text-primary"})," Curriculum"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[$,"%"]}),e.jsx(ro,{value:$,className:"h-1.5"})]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(zs,{open:v,onOpenChange:b,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{children:[e.jsx(an,{className:"mr-1.5 h-4 w-4"})," Log a video"]})}),e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Log a posted video"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"v-title",children:"What was it about?"}),e.jsx(xe,{id:"v-title",value:N.title,onChange:je=>S(be=>({...be,title:je.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"v-url",children:"Instagram link (optional)"}),e.jsx(xe,{id:"v-url",placeholder:"https://instagram.com/reel/…",value:N.instagram_url,onChange:je=>S(be=>({...be,instagram_url:je.target.value}))})]})]}),e.jsx(Mr,{children:e.jsx(U,{onClick:async()=>{await m.mutateAsync({week_number:I,...N}),S({title:"",instagram_url:""}),b(!1)},children:"Log video"})})]})]}),((ce=Q[0])==null?void 0:ce.meeting_link)&&e.jsx(U,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:Q[0].meeting_link,target:"_blank",rel:"noreferrer",children:[e.jsx($h,{className:"mr-1.5 h-4 w-4"})," Join next session"]})})]}),ue.length>0&&e.jsx(we,{className:"border-primary/30 bg-primary/5",children:e.jsx(Ie,{className:"space-y-3 p-5",children:ue.map(je=>e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Th,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:je.title}),je.body&&e.jsx("p",{className:"text-sm text-muted-foreground",children:je.body})]})]},je.id))})}),e.jsxs(oa,{defaultValue:"roadmap",children:[e.jsxs(la,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(Kt,{value:"roadmap",children:"Roadmap"}),e.jsx(Kt,{value:"lessons",children:"Lessons"}),e.jsx(Kt,{value:"checkin",children:"Weekly check-in"}),e.jsx(Kt,{value:"events",children:"Sessions"}),e.jsx(Kt,{value:"resources",children:"Resources"}),e.jsx(Kt,{value:"profile",children:"Profile review"})]}),e.jsxs(Zt,{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(je=>{const be=je.release_at&&new Date(je.release_at)>new Date;return e.jsx(we,{className:be?"opacity-60":je.week_number===I?"border-primary/50":"",children:e.jsxs(Ie,{className:"space-y-2 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Be,{variant:"outline",children:["Week ",je.week_number]}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:je.phase}),je.week_number===I&&e.jsx(Be,{children:"Current"}),be&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Yr,{className:"h-3 w-3"})," Unlocks ",Zd(je.release_at)]})]}),e.jsx("h3",{className:"font-semibold",children:je.title}),je.learning_goal&&e.jsx("p",{className:"text-sm text-muted-foreground",children:je.learning_goal}),!be&&Array.isArray(je.tasks)&&je.tasks.length>0&&e.jsx("ul",{className:"mt-2 space-y-1.5",children:je.tasks.map((he,ge)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(zr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof he=="string"?he:he.label]},ge))})]})},je.id)})]}),e.jsxs(Zt,{value:"lessons",className:"mt-6 space-y-3",children:[z.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Lessons unlock as the program progresses."}),z.map(je=>{const be=p7t(je.video_url),he=L===je.id;return e.jsx(we,{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(xi,{checked:R.has(je.id),onCheckedChange:ge=>h.mutate({lessonId:je.id,done:!!ge}),"aria-label":`Mark ${je.title} complete`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium",children:je.title}),je.summary&&e.jsx("p",{className:"text-sm text-muted-foreground",children:je.summary}),je.action_assignment&&e.jsxs("p",{className:"mt-1 text-xs text-primary",children:["Action: ",je.action_assignment]})]}),je.duration_minutes&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Yr,{className:"h-3 w-3"})," ",je.duration_minutes," min"]}),e.jsxs("div",{className:"flex gap-2",children:[je.video_url&&(be||PQ(je.video_url))&&e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>M(he?null:je.id),children:[e.jsx($h,{className:"mr-1.5 h-3.5 w-3.5"})," ",he?"Close":"Watch"]}),je.video_url&&!be&&!PQ(je.video_url)&&e.jsx(U,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:je.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx($h,{className:"mr-1.5 h-3.5 w-3.5"})," Watch"]})}),je.worksheet_url&&e.jsx(U,{size:"sm",variant:"ghost",asChild:!0,children:e.jsxs("a",{href:je.worksheet_url,target:"_blank",rel:"noreferrer",children:[e.jsx(pi,{className:"mr-1.5 h-3.5 w-3.5"})," Worksheet"]})})]})]}),he&&be&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:be,title:je.title,className:"aspect-video w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0})}),he&&!be&&PQ(je.video_url)&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60 bg-black",children:e.jsx("video",{src:je.video_url,controls:!0,autoPlay:!0,className:"aspect-video w-full"})})]})},je.id)})]}),e.jsx(Zt,{value:"checkin",className:"mt-6",children:e.jsx(we,{children:e.jsxs(Ie,{className:"space-y-5 p-6",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold",children:["Week ",I," 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(([je,be])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:je,children:be}),e.jsx(xe,{id:je,type:"number",min:0,defaultValue:ie[je]??"",onChange:he=>T(ge=>({...ge,[je]:Number(he.target.value)}))})]},je))}),[["biggest_win","Biggest win"],["biggest_challenge","Biggest challenge"],["what_to_improve","What you’ll change next week"]].map(([je,be])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:je,children:be}),e.jsx(Fs,{id:je,rows:2,defaultValue:ie[je]??"",onChange:he=>T(ge=>({...ge,[je]:he.target.value}))})]},je)),e.jsx(U,{onClick:()=>p.mutate({week_number:I,goal_videos:K,...A}),children:"Save check-in"})]})})}),e.jsxs(Zt,{value:"events",className:"mt-6 space-y-4",children:[Q.length===0&&le.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sessions will be scheduled before kickoff."}),Q.map(je=>e.jsx(we,{className:"border-primary/30",children:e.jsxs(Ie,{className:"flex flex-wrap items-center gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Be,{variant:"secondary",className:"capitalize",children:String(je.event_kind).replace("_"," ")}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(nc,{className:"h-3 w-3"})," ",Zd(je.starts_at,!0)]})]}),e.jsx("p",{className:"mt-1.5 font-medium",children:je.title}),je.speaker&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["with ",je.speaker]}),je.description&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:je.description})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(U,{size:"sm",variant:"outline",onClick:()=>f.mutate({eventId:je.id,optIn:!0}),children:"Remind me"}),e.jsxs(U,{size:"sm",variant:"ghost",onClick:()=>IYs(je,l.name),children:[e.jsx(nc,{className:"mr-1.5 h-3.5 w-3.5"})," Add to calendar"]}),je.meeting_link&&e.jsx(U,{size:"sm",asChild:!0,children:e.jsxs("a",{href:je.meeting_link,target:"_blank",rel:"noreferrer",children:["Join ",e.jsx(Sr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})},je.id)),le.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"}),le.map(je=>e.jsx(we,{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:je.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Zd(je.starts_at,!0)})]}),je.replay_url?e.jsx(U,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:je.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx($h,{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"})]})},je.id))]})]}),e.jsxs(Zt,{value:"resources",className:"mt-6 space-y-8",children:[Object.keys(ne).length===0&&e.jsx(we,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center gap-2 p-12 text-center",children:[e.jsx(Ur,{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(ne).map(([je,be])=>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:je}),e.jsx("span",{className:"h-px flex-1 bg-border"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[be.length," item",be.length===1?"":"s"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:be.map(he=>{const ge=ure(he),ke=RYs[he.resource_kind]||Ur;return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>ge&&LQ(he),onKeyDown:Te=>{ge&&(Te.key==="Enter"||Te.key===" ")&&(Te.preventDefault(),LQ(he))},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(ke,{className:"h-5 w-5"})}),e.jsx(Be,{variant:"secondary",className:"capitalize",children:String(he.resource_kind).replace("_"," ")})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-semibold leading-snug",children:he.title}),he.description&&e.jsx("p",{className:"line-clamp-3 text-sm text-muted-foreground",children:he.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(Sr,{className:"h-3.5 w-3.5"})," Open"]}),he.file_path&&e.jsxs("button",{type:"button",onClick:Te=>{Te.stopPropagation(),LQ(he,"download")},className:"inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-primary",children:[e.jsx(pi,{className:"h-3.5 w-3.5"})," Download"]})]})]},he.id)})})]},je))]}),e.jsx(Zt,{value:"profile",className:"mt-6",children:e.jsx(we,{children:e.jsxs(Ie,{className:"space-y-4 p-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gm,{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(([je,be])=>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:je.replace(/_/g," ")}),e.jsxs("span",{className:"font-semibold",children:[be,"/10"]})]}),e.jsx(ro,{value:Number(be)*10,className:"h-1.5"})]},je))}),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((je,be)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Eh,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof je=="string"?je:je.label]},be))})]}),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(U,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:d.analysis.report_url,target:"_blank",rel:"noreferrer",children:[e.jsx(pi,{className:"mr-1.5 h-4 w-4"})," Download full report"]})})]})]})})})]})]})})})},Ya=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{className:"relative w-full overflow-auto",children:e.jsx("table",{ref:n,className:Mt("w-full caption-bottom text-sm",s),...t})}));Ya.displayName="Table";const Za=j.forwardRef(({className:s,...t},n)=>e.jsx("thead",{ref:n,className:Mt("[&_tr]:border-b",s),...t}));Za.displayName="TableHeader";const Xa=j.forwardRef(({className:s,...t},n)=>e.jsx("tbody",{ref:n,className:Mt("[&_tr:last-child]:border-0",s),...t}));Xa.displayName="TableBody";const OYs=j.forwardRef(({className:s,...t},n)=>e.jsx("tfoot",{ref:n,className:Mt("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",s),...t}));OYs.displayName="TableFooter";const gn=j.forwardRef(({className:s,...t},n)=>e.jsx("tr",{ref:n,className:Mt("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50",s),...t}));gn.displayName="TableRow";const Lt=j.forwardRef(({className:s,...t},n)=>e.jsx("th",{ref:n,className:Mt("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",s),...t}));Lt.displayName="TableHead";const gt=j.forwardRef(({className:s,...t},n)=>e.jsx("td",{ref:n,className:Mt("p-4 align-middle [&:has([role=checkbox])]:pr-0",s),...t}));gt.displayName="TableCell";const FYs=j.forwardRef(({className:s,...t},n)=>e.jsx("caption",{ref:n,className:Mt("mt-4 text-sm text-muted-foreground",s),...t}));FYs.displayName="TableCaption";const tle=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())}`},sle=s=>s?new Date(s).toISOString():null,IFe=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:tle(s.enrollment_open_at),enrollment_close_at:tle(s.enrollment_close_at),kickoff_at:tle(s.kickoff_at),charge_at:tle(s.charge_at),status:s.status||"draft",is_public:!!s.is_public,is_featured:!!s.is_featured,sort_order:s.sort_order??0}),zYs=({program:s,onSaved:t})=>{const[n,r]=j.useState(()=>IFe(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(IFe(s)),i(!1)},[s.id,s.updated_at]);const m=(y,v)=>{r(b=>({...b,[y]:v})),i(!0)},p=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",N=`programs/${s.id}/${v}-${Date.now()}.${b}`,{error:S}=await q.storage.from("event-images").upload(N,y,{cacheControl:"31536000",upsert:!0});if(S)throw S;const{data:A}=q.storage.from("event-images").getPublicUrl(N);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)}},f=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:sle(n.enrollment_open_at),enrollment_close_at:sle(n.enrollment_close_at),kickoff_at:sle(n.kickoff_at),charge_at:sle(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 N=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(te,{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:N?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:N,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(er,{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(ly,{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 L;const T=(L=A.target.files)==null?void 0:L[0];T&&p(T,y),A.target.value=""}}),e.jsxs(U,{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(Et,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(qa,{className:"mr-1.5 h-4 w-4"}),"Upload image"]}),e.jsx(xe,{placeholder:"…or paste an image URL",value:N,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(U,{variant:"ghost",onClick:()=>{r(IFe(s)),i(!1)},children:"Discard"}),e.jsxs(U,{onClick:f,disabled:l||!a,children:[l?e.jsx(Et,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Ho,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})]})]}),e.jsx(we,{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(te,{children:"Program name"}),e.jsx(xe,{value:n.name,onChange:y=>m("name",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Slug (public URL)"}),e.jsx(xe,{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(te,{children:"Subtitle"}),e.jsx(xe,{value:n.subtitle,onChange:y=>m("subtitle",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Tagline"}),e.jsx(xe,{value:n.tagline,onChange:y=>m("tagline",y.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Short description (cards & previews)"}),e.jsx(Fs,{rows:2,value:n.short_description,onChange:y=>m("short_description",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Full program description (sales page)"}),e.jsx(Fs,{rows:8,value:n.description,onChange:y=>m("description",y.target.value)})]})]})}),e.jsx(we,{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(te,{children:"Promo video URL (optional)"}),e.jsx(xe,{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(xe,{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(te,{children:"Accent color"}),e.jsx(xe,{placeholder:"#406E71",value:n.accent_color,onChange:y=>m("accent_color",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Sort order"}),e.jsx(xe,{type:"number",value:n.sort_order,onChange:y=>m("sort_order",Number(y.target.value))})]})]})]})}),e.jsx(we,{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(te,{children:"One-time price (USD)"}),e.jsx(xe,{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(te,{children:"Seats (capacity)"}),e.jsx(xe,{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(te,{children:"Billing mode"}),e.jsxs(Ns,{value:n.payment_mode,onValueChange:y=>m("payment_mode",y),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"delayed",children:"Save card, charge once later"}),e.jsx(et,{value:"immediate",children:"Charge once at checkout"}),e.jsx(et,{value:"free",children:"Free / included"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Charge date (one-time)"}),e.jsx(xe,{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(te,{children:"Payment grace days"}),e.jsx(xe,{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(te,{children:"Currency"}),e.jsx(xe,{value:n.currency,onChange:y=>m("currency",y.target.value)})]})]})]})}),e.jsx(we,{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(te,{children:"Enrollment opens"}),e.jsx(xe,{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(te,{children:"Enrollment closes"}),e.jsx(xe,{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(te,{children:"Kickoff"}),e.jsx(xe,{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(te,{children:"Length (weeks)"}),e.jsx(xe,{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(te,{children:"Videos per week goal"}),e.jsx(xe,{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(te,{children:"Timezone"}),e.jsx(xe,{value:n.timezone,onChange:y=>m("timezone",y.target.value)})]})]})]})}),e.jsx(we,{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(te,{children:"Status"}),e.jsxs(Ns,{value:n.status,onValueChange:y=>m("status",y),children:[e.jsx(ws,{className:"sm:max-w-xs",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"draft",children:"Draft (hidden)"}),e.jsx(et,{value:"published",children:"Published (members can enroll)"}),e.jsx(et,{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(wn,{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(wn,{checked:n.is_public,onCheckedChange:y=>m("is_public",y)})]})]})}),e.jsx("div",{className:"flex justify-end pb-4",children:e.jsxs(U,{onClick:f,disabled:l||!a,size:"lg",children:[l?e.jsx(Et,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Ho,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})})]})},zxt={title:"",description:"",category:"Personal",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},BYs=({programId:s,userId:t,memberName:n})=>{const{data:r=[],isLoading:a}=H9s(s,t),i=G9s(s,t),l=W9s(),[o,c]=j.useState(!1),[d,u]=j.useState({...zxt}),[h,m]=j.useState(!1),p=j.useRef(null),f=()=>{u({...zxt,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 N=b.name.split(".").pop()||"pdf",S=`programs/${s}/members/${t}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${N}`,{error:A}=await q.storage.from(TG).upload(S,b,{contentType:b.type||"application/pdf",upsert:!1});if(A)throw A;u(T=>({...T,file_path:S,url:"",title:T.title||b.name.replace(/\.[^.]+$/,""),resource_kind:b.type==="application/pdf"?"pdf":T.resource_kind})),re.success("File uploaded")}catch(N){re.error(N.message||"Upload failed")}finally{m(!1),p.current&&(p.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(Ql,{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(U,{size:"sm",onClick:f,disabled:!t,children:[e.jsx(an,{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(we,{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(we,{className:"border-border/60",children:e.jsxs(Ie,{className:"flex flex-wrap items-start justify-between gap-3 p-4",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:b.title}),e.jsx(Be,{variant:"secondary",children:b.category}),e.jsx(Be,{variant:"outline",className:"capitalize",children:b.resource_kind.replace("_"," ")}),b.status!=="published"&&e.jsx(Be,{variant:"outline",className:"capitalize",children:b.status})]}),b.description&&e.jsx("p",{className:"max-w-xl text-sm text-muted-foreground",children:b.description}),ure(b)&&e.jsxs("button",{type:"button",onClick:()=>LQ(b),className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Sr,{className:"h-3 w-3"})," Open"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>x(b),children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:async()=>{await Yi(`Remove "${b.title}"?`)&&l.mutate(b)},children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]})]})},b.id))}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Ds,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsx($s,{children:d.id?"Edit personal resource":"New personal resource"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Title"}),e.jsx(xe,{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(te,{children:"Description"}),e.jsx(Fs,{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(te,{children:"Category"}),e.jsx(xe,{value:d.category,onChange:b=>u({...d,category:b.target.value}),placeholder:"Personal"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Type"}),e.jsxs(Ns,{value:d.resource_kind,onValueChange:b=>u({...d,resource_kind:b}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:f7t.map(b=>e.jsx(et,{value:b.value,children:b.label},b.value))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"File"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(U,{type:"button",variant:"outline",size:"sm",disabled:h,onClick:()=>{var b;return(b=p.current)==null?void 0:b.click()},children:[h?e.jsx(Et,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(qa,{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:p,type:"file",hidden:!0,onChange:b=>{var N;return y((N=b.target.files)==null?void 0:N[0])}})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"…or link"}),e.jsx(xe,{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(te,{children:"Status"}),e.jsxs(Ns,{value:d.status,onValueChange:b=>u({...d,status:b}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"published",children:"Published"}),e.jsx(et,{value:"draft",children:"Draft"}),e.jsx(et,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Sort order"}),e.jsx(xe,{type:"number",value:d.sort_order,onChange:b=>u({...d,sort_order:b.target.value})})]})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(U,{onClick:v,disabled:i.isPending||h,children:[i.isPending&&e.jsx(Et,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save"]})]})]})})]})},UYs=({program:s,enrollment:t,open:n,onOpenChange:r,onUpdated:a})=>{var K,Z,Q,le,ue,se,ne,ie,ce,je;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,p]=j.useState(!1),[f,x]=j.useState(!1),y=j.useRef(null),{data:v,isLoading:b,refetch:N}=ct({queryKey:["admin-program-agent",s.id,i],enabled:n&&!!i,queryFn:async()=>{const[be,he,ge,ke,Te,Me,Oe,Se]=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:be.data||[],videos:he.data||[],completions:ge.data||[],badges:ke.data||[],intake:Te.data,attendance:Me.data||[],lessonCount:(Oe.data||[]).length,analysis:Se.data}}});j.useEffect(()=>{var be;h(((be=v==null?void 0:v.analysis)==null?void 0:be.member_notes)||"")},[(K=v==null?void 0:v.analysis)==null?void 0:K.id]);const S=j.useMemo(()=>{var ge;const be=xee(s),he=((ge=v==null?void 0:v.intake)==null?void 0:ge.extra)||{};return be.custom.map(ke=>({label:ke.label,value:typeof he[ke.id]=="boolean"?he[ke.id]?"Yes":"No":he[ke.id]||""})).filter(ke=>!!ke.value)},[s,v==null?void 0:v.intake]),A=async be=>i?q.from("program_profile_analyses").upsert({program_id:s.id,user_id:i,enrollment_id:(t==null?void 0:t.id)||null,...be},{onConflict:"program_id,user_id"}):{error:{message:"Missing agent"}},T=async be=>{if(be.type!=="application/pdf")return re.error("Please choose a PDF file");if(be.size>25*1024*1024)return re.error("PDF must be under 25MB");x(!0);try{const he=`programs/${s.id}/reviews/${i}-${Date.now()}.pdf`,{error:ge}=await q.storage.from("event-images").upload(he,be,{contentType:"application/pdf",upsert:!0});if(ge)throw ge;const{data:ke}=q.storage.from("event-images").getPublicUrl(he),{error:Te}=await A({report_url:ke.publicUrl,status:"ready",reviewed_at:new Date().toISOString()});if(Te)throw Te;re.success("Profile review uploaded"),await N()}catch(he){re.error(he.message||"Upload failed")}finally{x(!1)}},L=async()=>{const{error:be}=await A({report_url:null,status:"in_review"});if(be)return re.error(be.message);re.success("Review removed"),await N()},M=async()=>{p(!0);const{error:be}=await A({member_notes:u});if(p(!1),be)return re.error(be.message);re.success("Review notes saved"),await N()},I=async()=>{if(!t)return;d(!0);const{error:be}=await q.from("program_enrollments").update({admin_notes:l}).eq("id",t.id);if(d(!1),be)return re.error(be.message);re.success("Notes saved"),a()},R=((v==null?void 0:v.videos)||[]).filter(be=>be.posted).length,z=(s.weekly_video_goal||0)*(s.duration_weeks||0),$=v!=null&&v.lessonCount?Math.round(((v==null?void 0:v.completions.length)||0)/v.lessonCount*100):0,H=z?Math.min(100,Math.round(R/z*100)):0,V=((v==null?void 0:v.attendance)||[]).filter(be=>be.attended).length;return e.jsx(my,{open:n,onOpenChange:r,children:e.jsxs(g0,{className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(vv,{className:"mb-4",children:[e.jsxs(bv,{children:[((Z=t==null?void 0:t.profile)==null?void 0:Z.name)||"Agent"," · ",s.name]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(Q=t==null?void 0:t.profile)==null?void 0:Q.email}),i&&e.jsx(U,{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(((le=t==null?void 0:t.profile)==null?void 0:le.name)||((ue=t==null?void 0:t.profile)==null?void 0:ue.email)||"this member")}`,target:"_blank",rel:"noreferrer",children:[e.jsx(Sr,{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(we,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsx(Be,{className:"mt-1 capitalize",children:String(t.status).replace(/_/g," ")}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[gf(t.amount_cents,t.currency)," ·"," ",t.charged_at?`Charged ${Zd(t.charged_at)}`:`Charge ${Zd(t.charge_scheduled_at)||"not set"}`]})]})}),e.jsx(we,{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:Zd(t.last_activity_at,!0)||"No activity yet"}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Enrolled ",Zd(t.created_at)]})]})})]}),e.jsx(we,{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:[R," / ",z||"—"]})]}),e.jsx(ro,{value:H})]}),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(ro,{value:$})]}),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(we,{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(be=>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 ",be.week_number]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[be.videos_posted,"/",be.goal_videos||s.weekly_video_goal," posted ·"," ",be.stories_posted," stories"]})]}),be.biggest_win&&e.jsxs("p",{className:"mt-1 text-muted-foreground",children:["Win: ",be.biggest_win]}),be.biggest_challenge&&e.jsxs("p",{className:"text-muted-foreground",children:["Challenge: ",be.biggest_challenge]})]},be.id))})]})}),e.jsx(we,{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(be=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Wr,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:be.title||"Untitled video"}),e.jsxs("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:["Wk ",be.week_number," · ",Zd(be.posted_at)]}),be.instagram_url&&e.jsx("a",{href:be.instagram_url,target:"_blank",rel:"noreferrer",className:"shrink-0 text-muted-foreground hover:text-foreground","aria-label":"Open post",children:e.jsx(Sr,{className:"h-3.5 w-3.5"})})]},be.id))})]})}),(v==null?void 0:v.intake)&&e.jsx(we,{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(([,be])=>!!be).map(([be,he])=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[be,": "]}),he]},be)),S.map(({label:be,value:he})=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[be,": "]}),he]},be)),e.jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["Content-sharing consent: ",v.intake.consent_public_profile?"Yes":"No"]})]})}),e.jsx(we,{children:e.jsx(Ie,{className:"p-5",children:e.jsx(BYs,{programId:s.id,userId:i,memberName:(se=t==null?void 0:t.profile)==null?void 0:se.name})})}),e.jsx(we,{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."})]}),((ne=v==null?void 0:v.analysis)==null?void 0:ne.status)&&e.jsx(Be,{variant:"secondary",className:"capitalize",children:String(v.analysis.status).replace(/_/g," ")})]}),(ie=v==null?void 0:v.analysis)!=null&&ie.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(Ur,{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(Sr,{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:be=>{var ge;const he=(ge=be.target.files)==null?void 0:ge[0];he&&T(he),be.target.value=""}}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>{var be;return(be=y.current)==null?void 0:be.click()},disabled:f,children:[e.jsx(qa,{className:"mr-1.5 h-3.5 w-3.5"}),f?"Uploading…":(ce=v==null?void 0:v.analysis)!=null&&ce.report_url?"Replace PDF":"Upload PDF"]}),((je=v==null?void 0:v.analysis)==null?void 0:je.report_url)&&e.jsx(U,{size:"sm",variant:"ghost",onClick:L,children:"Remove"})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsx(te,{children:"Review summary shown to the agent (optional)"}),e.jsx(Fs,{rows:3,value:u,onChange:be=>h(be.target.value),placeholder:"Top 3 priorities, quick wins, what to fix first…"}),e.jsx("div",{className:"flex justify-end",children:e.jsx(U,{size:"sm",variant:"outline",onClick:M,disabled:m,children:"Save review notes"})})]})]})}),e.jsx(we,{children:e.jsxs(Ie,{className:"space-y-3 p-5",children:[e.jsx(te,{children:"Coach notes (internal)"}),e.jsx(Fs,{rows:4,value:l,onChange:be=>o(be.target.value)}),e.jsx("div",{className:"flex justify-end",children:e.jsx(U,{size:"sm",onClick:I,disabled:c,children:"Save notes"})})]})})]}):null]})})},Bxt={code:"",label:"",kind:"percent",percent_off:"20",amount_off:"",max_redemptions:"",starts_at:"",expires_at:"",is_active:!0},Uxt=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},qYs=({program:s})=>{const{data:t=[],isLoading:n}=P9s(s.id),r=L9s(s.id),a=I9s(),[i,l]=j.useState(!1),[o,c]=j.useState({...Bxt}),d=()=>{c({...Bxt}),l(!0)},u=f=>{c({id:f.id,code:f.code,label:f.label||"",kind:f.percent_off!=null?"percent":"amount",percent_off:f.percent_off!=null?String(f.percent_off):"",amount_off:f.amount_off_cents!=null?String(f.amount_off_cents/100):"",max_redemptions:f.max_redemptions!=null?String(f.max_redemptions):"",starts_at:Uxt(f.starts_at),expires_at:Uxt(f.expires_at),is_active:f.is_active}),l(!0)},h=j.useMemo(()=>{const f=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(f,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)},p=f=>{const x=f.percent_off!=null?Math.floor(s.price_cents*Number(f.percent_off)/100):f.amount_off_cents||0,y=Math.max(s.price_cents-Math.min(x,s.price_cents),0);return{off:f.percent_off!=null?`${Number(f.percent_off)}% off`:`${gf(f.amount_off_cents||0,s.currency)} off`,final:gf(y,s.currency)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(we,{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 ",gf(s.price_cents,s.currency)," charge."]})]}),e.jsxs(zs,{open:i,onOpenChange:l,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{onClick:d,children:[e.jsx(an,{className:"mr-1.5 h-4 w-4"})," New code"]})}),e.jsxs(Ds,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:o.id?"Edit discount code":"Create a discount code"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Code"}),e.jsx(xe,{placeholder:"FOUNDER50",value:o.code,onChange:f=>c({...o,code:f.target.value.toUpperCase()})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Internal label (optional)"}),e.jsx(xe,{placeholder:"Founding cohort",value:o.label,onChange:f=>c({...o,label:f.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Discount type"}),e.jsxs(Ns,{value:o.kind,onValueChange:f=>c({...o,kind:f}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"percent",children:"Percent off"}),e.jsx(et,{value:"amount",children:"Dollar amount off"})]})]})]}),o.kind==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Percent off"}),e.jsx(xe,{type:"number",min:1,max:100,value:o.percent_off,onChange:f=>c({...o,percent_off:f.target.value})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Amount off (USD)"}),e.jsx(xe,{type:"number",min:0,value:o.amount_off,onChange:f=>c({...o,amount_off:f.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Max redemptions (blank = unlimited)"}),e.jsx(xe,{type:"number",min:1,value:o.max_redemptions,onChange:f=>c({...o,max_redemptions:f.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Active from (optional)"}),e.jsx(xe,{type:"datetime-local",value:o.starts_at,onChange:f=>c({...o,starts_at:f.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Expires (optional)"}),e.jsx(xe,{type:"datetime-local",value:o.expires_at,onChange:f=>c({...o,expires_at:f.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(wn,{checked:o.is_active,onCheckedChange:f=>c({...o,is_active:f})})]}),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:[gf(s.price_cents,s.currency)," →"," ",e.jsx("span",{className:"font-semibold text-foreground",children:gf(h.final,s.currency)})," ","(",gf(h.discount,s.currency)," off) — charged one time."]})]})]}),e.jsx(Mr,{children:e.jsxs(U,{onClick:m,disabled:r.isPending,children:[r.isPending&&e.jsx(Et,{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(we,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Cf,{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(we,{children:e.jsx(Ie,{className:"overflow-x-auto p-0",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Code"}),e.jsx(Lt,{children:"Discount"}),e.jsx(Lt,{children:"Price after"}),e.jsx(Lt,{children:"Used"}),e.jsx(Lt,{children:"Window"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:t.map(f=>{const x=p(f);return e.jsxs(gn,{children:[e.jsxs(gt,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono font-semibold",children:f.code}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{navigator.clipboard.writeText(f.code),re.success("Code copied")},children:e.jsx(Pa,{className:"h-3.5 w-3.5"})})]}),f.label&&e.jsx("p",{className:"text-xs text-muted-foreground",children:f.label})]}),e.jsx(gt,{className:"whitespace-nowrap",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(PM,{className:"h-3.5 w-3.5 text-muted-foreground"}),x.off]})}),e.jsx(gt,{className:"font-medium",children:x.final}),e.jsxs(gt,{children:[f.times_redeemed,f.max_redemptions?` / ${f.max_redemptions}`:""]}),e.jsxs(gt,{className:"text-xs text-muted-foreground",children:[f.starts_at?`From ${Zd(f.starts_at)}`:"Anytime",f.expires_at?` · until ${Zd(f.expires_at)}`:""]}),e.jsx(gt,{children:e.jsx(Be,{variant:f.is_active?"default":"secondary",children:f.is_active?"Active":"Paused"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(U,{variant:"outline",size:"sm",onClick:()=>u(f),children:"Edit"}),e.jsx(U,{variant:"ghost",size:"icon",onClick:async()=>{await Yi(`Delete ${f.code}?`)&&a.mutate(f.id)},children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]})})]},f.id)})})]})})})]})},o5=({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(zr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}):e.jsx(tc,{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})]})]}),$Ys=({program:s})=>{var c,d;const{data:t,isLoading:n}=ct({queryKey:["admin-program-content-counts",s.id],queryFn:async()=>{const[u,h,m,p,f]=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:p.data||[],announcements:f.data||[]}}}),{notOpenYet:r,closed:a,opensLabel:i}=aPe(s),l=`/programs/${s.slug}`,o=[{icon:cn,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:hq,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:oy,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 ${gf(s.price_cents,s.currency)} charge runs on ${Zd(s.charge_at||s.kickoff_at)||"the charge date (not set)"}.`:`Stripe charges ${gf(s.price_cents,s.currency)} once at checkout.`},{icon:ln,title:"4 · Emails",body:"Confirmation right after enrollment, then payment receipt (or a payment-failed action email) when the one-time charge runs."},{icon:iq,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(we,{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(U,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:l,target:"_blank",rel:"noreferrer",children:["Sales page ",e.jsx(Sr,{className:"ml-1.5 h-3.5 w-3.5"})]})}),e.jsx(U,{asChild:!0,children:e.jsxs("a",{href:`${l}/workspace?preview=1`,target:"_blank",rel:"noreferrer",children:["Workspace preview ",e.jsx(Sr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})}),(s.status!=="published"||r||a)&&e.jsx(we,{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(tc,{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(we,{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(U,{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(Sr,{className:"ml-1 h-3 w-3"})]})})]})]},u.title))})]})}),e.jsx(we,{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(o5,{ok:!!s.cover_image_url,label:"Cover image",detail:s.cover_image_url?"Set":"Missing — cards look empty on the Programs page"}),e.jsx(o5,{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(o5,{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(o5,{ok:s.payment_mode==="free"||s.price_cents>0,label:"One-time price",detail:s.payment_mode==="free"?"Free / included":gf(s.price_cents,s.currency)}),e.jsx(o5,{ok:!!s.kickoff_at&&(s.payment_mode==="free"||!!s.charge_at),label:"Kickoff and charge dates",detail:`Kickoff ${Zd(s.kickoff_at)||"not set"} · charge ${Zd(s.charge_at)||"not set"}`}),e.jsx(o5,{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(o5,{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(o5,{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(o5,{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 ${Zd(t.events[0].starts_at)}`:""}`}),e.jsx(o5,{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(we,{children:e.jsx(Ie,{className:"grid gap-4 p-5 sm:grid-cols-2 lg:grid-cols-5",children:[{icon:nc,label:"Weeks",value:t.weeks.length},{icon:Ur,label:"Lessons",value:t.lessons.length},{icon:Ur,label:"Resources",value:t.resources.length},{icon:nc,label:"Events",value:t.events.length},{icon:Th,label:"Announcements",value:t.announcements.length}].map((u,h)=>e.jsxs("div",{className:"rounded-lg border border-border/60 p-4",children:[e.jsx(u.icon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("p",{className:"mt-2 text-2xl font-bold",children:u.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u.label})]},h))})}),e.jsx(Be,{variant:"outline",className:"text-xs",children:"Tip: preview in an incognito window as a test member to see the real enrollment flow end to end."})]})},VYs=["Step 1 · Your business","Step 2 · Your content","Step 3 · Your goals"],HYs={short_text:"Short answer",long_text:"Paragraph",select:"Dropdown",checkbox:"Yes / no checkbox"},GYs=({program:s,onSaved:t})=>{const[n,r]=j.useState(()=>xee(s)),[a,i]=j.useState(!1),[l,o]=j.useState(!1);j.useEffect(()=>{r(xee(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])],N=v?n.required:n.required.filter(S=>S!==y);c({hidden:b,required:N})},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)}),p=y=>c({custom:n.custom.filter(v=>v.id!==y)}),f=(y,v)=>{const b=[...n.custom],N=y+v;N<0||N>=b.length||([b[y],b[N]]=[b[N],b[y]],c({custom:b}))},x=async()=>{if(n.custom.find(N=>!N.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(U,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:`/programs/${s.slug}/enroll`,target:"_blank",rel:"noreferrer",children:[e.jsx(Sr,{className:"mr-1.5 h-3.5 w-3.5"})," Preview form"]})}),e.jsxs(U,{size:"sm",onClick:x,disabled:!a||l,children:[e.jsx(Ho,{className:"mr-1.5 h-3.5 w-3.5"}),l?"Saving…":"Save intake form"]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsx(It,{className:"text-sm",children:"Intro message"})}),e.jsx(Ie,{children:e.jsx(Fs,{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(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsx(It,{className:"text-sm",children:VYs[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"})]}),qQe.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(wn,{checked:b,onCheckedChange:N=>d(v.key,N),"aria-label":`Show ${v.label}`})}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(wn,{checked:n.required.includes(v.key),disabled:!b,onCheckedChange:N=>u(v.key,N),"aria-label":`Require ${v.label}`})})]},v.key)})]})]},y)),e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs(It,{className:"text-sm",children:["Custom questions"," ",e.jsx(Be,{variant:"secondary",className:"ml-1",children:n.custom.length})]}),e.jsxs(U,{size:"sm",variant:"outline",onClick:h,children:[e.jsx(an,{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:()=>f(v,-1),"aria-label":"Move up",children:e.jsx(kf,{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(te,{className:"text-xs",children:"Question"}),e.jsx(xe,{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(te,{className:"text-xs",children:"Answer type"}),e.jsxs(Ns,{value:y.type,onValueChange:b=>m(y.id,{type:b}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:Object.entries(HYs).map(([b,N])=>e.jsx(et,{value:b,children:N},b))})]})]})]}),e.jsx(U,{size:"icon",variant:"ghost",onClick:()=>p(y.id),"aria-label":"Delete question",children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]}),y.type==="select"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Options (one per line)"}),e.jsx(Fs,{rows:3,value:(y.options||[]).join(` `),onChange:b=>m(y.id,{options:b.target.value.split(` `).map(N=>N.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(te,{className:"text-xs",children:"Helper text (optional)"}),e.jsx(xe,{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(wn,{checked:!!y.required,onCheckedChange:b=>m(y.id,{required:b}),"aria-label":"Required"}),e.jsx("span",{className:"text-sm",children:"Required"})]})]})]},y.id))]})]})]})},ub=qzt,hb=DJe,mb=FJe,WYs=[og,Ur,Gu],KYs=["Business profile","Content style","Goals & consent"],YYs=({fieldKey:s})=>s.includes("phone")?e.jsx(ba,{className:"h-3.5 w-3.5"}):s.includes("email")?e.jsx(ln,{className:"h-3.5 w-3.5"}):s.includes("instagram")?e.jsx(gm,{className:"h-3.5 w-3.5"}):s.includes("city")||s.includes("area")?e.jsx(ni,{className:"h-3.5 w-3.5"}):s.includes("timezone")?e.jsx(Yr,{className:"h-3.5 w-3.5"}):s.includes("consent")?s.includes("true")?e.jsx(zr,{className:"h-3.5 w-3.5"}):e.jsx(ou,{className:"h-3.5 w-3.5"}):e.jsx(So,{className:"h-3.5 w-3.5"}),qxt=(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(zr,{className:"h-3.5 w-3.5"})," Yes"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 text-muted-foreground",children:[e.jsx(ou,{className:"h-3.5 w-3.5"})," No"]}):String(s),ZYs=({program:s})=>{const[t,n]=j.useState(""),[r,a]=j.useState(new Set),{data:i=[],isLoading:l}=ct({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=xee(s),c=qQe.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(p=>String(p).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(we,{className:"border-dashed",children:e.jsxs(Ie,{className:"p-12 text-center text-sm text-muted-foreground",children:[e.jsx(Ur,{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(Fr,{className:"absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{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),p=Zd(h.created_at,!0);return e.jsx(we,{className:"overflow-hidden",children:e.jsxs(ub,{open:m,onOpenChange:()=>u(h.id),children:[e.jsx(hb,{asChild:!0,children:e.jsxs(Tt,{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(So,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsxs(It,{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:p})]}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",children:e.jsx(rl,{className:`h-4 w-4 transition-transform ${m?"rotate-180":""}`})})]})]})}),e.jsx(mb,{children:e.jsxs(Ie,{className:"space-y-5 p-5",children:[[0,1,2].map(f=>{const x=c.filter(v=>v.step===f),y=WYs[f];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:KYs[f]})]}),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(YYs,{fieldKey:v.key}),v.label]}),e.jsx("p",{className:"text-sm font-medium",children:qxt(b,v.key)})]},v.key)})})]},f)}),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(Ur,{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(f=>{var y;const x=(y=h.extra)==null?void 0:y[f.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:f.label}),e.jsx("p",{className:"text-sm font-medium",children:qxt(x,f.id)})]},f.id)})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-2 text-xs text-muted-foreground",children:[e.jsx(pa,{className:"h-3.5 w-3.5"}),"Submitted ",p,h.timezone&&e.jsxs("span",{className:"ml-2",children:["· Timezone: ",h.timezone]})]})]})})]})},h.id)})})]})},XYs=[{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"}],QYs=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},$xt={title:"",description:"",event_kind:"mastermind",starts_at:"",duration_minutes:60,speaker:"",meeting_link:"",replay_url:"",is_published:!0},JYs=({programId:s})=>{const{data:t=[],isLoading:n}=O9s(s),r=F9s(s),a=z9s(),[i,l]=j.useState(!1),[o,c]=j.useState({...$xt}),d=()=>{c({...$xt}),l(!0)},u=y=>{c({id:y.id,title:y.title,description:y.description||"",event_kind:y.event_kind,starts_at:QYs(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(),p=t.filter(y=>new Date(y.starts_at).getTime()>=m),f=t.filter(y=>new Date(y.starts_at).getTime()e.jsx(we,{className:"border-border/60",children:e.jsxs(Ie,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:y.title}),e.jsx(Be,{variant:"secondary",className:"capitalize",children:y.event_kind.replace("_"," ")}),!y.is_published&&e.jsx(Be,{variant:"outline",children:"Hidden"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Zd(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(Sr,{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(Pa,{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(Wr,{className:"h-3 w-3"})," Replay"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{variant:"outline",size:"sm",onClick:()=>u(y),children:e.jsx(ri,{className:"h-3.5 w-3.5"})}),e.jsx(U,{variant:"outline",size:"sm",onClick:async()=>{await Yi(`Remove "${y.title}"?`)&&a.mutate(y.id)},children:e.jsx(In,{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(U,{onClick:d,children:[e.jsx(an,{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(we,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(ch,{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 (",p.length,")"]}),p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing upcoming."}):p.map(y=>e.jsx(x,{e:y},y.id))]}),f.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 (",f.length,") — add replay links so members can catch up"]}),f.map(y=>e.jsx(x,{e:y},y.id))]})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Ds,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:o.id?"Edit session":"Add a live session"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Title"}),e.jsx(xe,{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(te,{children:"Type"}),e.jsxs(Ns,{value:o.event_kind,onValueChange:y=>c({...o,event_kind:y}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:XYs.map(y=>e.jsx(et,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Host / speaker"}),e.jsx(xe,{value:o.speaker,onChange:y=>c({...o,speaker:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Starts (your local time)"}),e.jsx(xe,{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(te,{children:"Length (minutes)"}),e.jsx(xe,{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(te,{children:"Zoom / meeting link"}),e.jsx(xe,{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(te,{children:"Replay link (after the call)"}),e.jsx(xe,{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(te,{children:"What we'll cover"}),e.jsx(Fs,{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(wn,{checked:o.is_published,onCheckedChange:y=>c({...o,is_published:y})})]})]}),e.jsx(Mr,{children:e.jsxs(U,{onClick:h,disabled:r.isPending,children:[r.isPending&&e.jsx(Et,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save session":"Add session"]})})]})})]})},Vxt={title:"",summary:"",week_id:"none",duration_minutes:"",video_url:"",worksheet_url:"",action_assignment:"",status:"published",sort_order:0},eZs=({programId:s})=>{const{data:t,isLoading:n}=B9s(s),r=(t==null?void 0:t.lessons)||[],a=(t==null?void 0:t.weeks)||[],{data:i=[]}=g7t(s),l=U9s(s),o=q9s(),[c,d]=j.useState(!1),[u,h]=j.useState({...Vxt}),[m,p]=j.useState(!1),f=j.useRef(null),x=async A=>{if(f.current&&(f.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");p(!0);try{const T=A.name.split(".").pop()||"mp4",L=`lessons/${crypto.randomUUID()}.${T}`,{error:M}=await q.storage.from("program-assets").upload(L,A,{contentType:A.type,upsert:!1});if(M)throw M;const{data:I,error:R}=await q.storage.from("program-assets").createSignedUrl(L,60*60*24*365*5);if(R||!(I!=null&&I.signedUrl))throw R||new Error("Could not sign video URL");h(z=>({...z,video_url:I.signedUrl})),re.success("Video uploaded")}catch(T){re.error((T==null?void 0:T.message)||"Upload failed")}finally{p(!1)}}},y=()=>{h({...Vxt,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)},N=A=>{const T=a.find(L=>L.id===A);return T?`Week ${T.week_number}`:"Unassigned"},S=p7t(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(U,{onClick:y,children:[e.jsx(an,{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(we,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Gh,{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(we,{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(Be,{variant:"secondary",children:N(A.week_id)}),A.status!=="published"&&e.jsx(Be,{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(Sr,{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(Sr,{className:"h-3 w-3"})," Worksheet"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{variant:"outline",size:"sm",onClick:()=>v(A),children:e.jsx(ri,{className:"h-3.5 w-3.5"})}),e.jsx(U,{variant:"outline",size:"sm",onClick:async()=>{await Yi(`Remove "${A.title}"?`)&&o.mutate(A.id)},children:e.jsx(In,{className:"h-3.5 w-3.5"})})]})]})},A.id))}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Ds,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:u.id?"Edit video":"Add an on-demand video"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Title"}),e.jsx(xe,{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(te,{children:"Video link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{placeholder:"https://youtu.be/… , Vimeo or Loom URL",value:u.video_url,onChange:A=>h({...u,video_url:A.target.value})}),e.jsxs(U,{type:"button",variant:"outline",className:"shrink-0",disabled:m,onClick:()=>{var A;return(A=f.current)==null?void 0:A.click()},children:[m?e.jsx(Et,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(qa,{className:"mr-1.5 h-4 w-4"}),m?"Uploading…":"Upload"]}),e.jsx("input",{ref:f,type:"file",accept:"video/*",className:"hidden",onChange:A=>{var T;return x((T=A.target.files)==null?void 0:T[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&&!PQ(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&&PQ(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(te,{children:"Week"}),e.jsxs(Ns,{value:u.week_id,onValueChange:A=>h({...u,week_id:A}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"Unassigned (library)"}),a.map(A=>e.jsxs(et,{value:A.id,children:["Week ",A.week_number," — ",A.title]},A.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Length (minutes)"}),e.jsx(xe,{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(te,{children:"Status"}),e.jsxs(Ns,{value:u.status,onValueChange:A=>h({...u,status:A}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"published",children:"Published (visible)"}),e.jsx(et,{value:"draft",children:"Draft (hidden)"}),e.jsx(et,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Order"}),e.jsx(xe,{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(te,{children:"Summary"}),e.jsx(Fs,{rows:3,value:u.summary,onChange:A=>h({...u,summary:A.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Worksheet / download link"}),i.length>0&&e.jsxs(Ns,{value:"",onValueChange:A=>{const T=i.find(M=>M.id===A),L=T?ure(T):null;L?h({...u,worksheet_url:L}):re.error("That resource has no file or link yet")},children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Choose an uploaded program resource…"})}),e.jsx(js,{children:i.map(A=>e.jsx(et,{value:A.id,children:A.title},A.id))})]}),e.jsx(xe,{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(Sr,{className:"h-3 w-3"})," Preview worksheet"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Action assignment"}),e.jsx(Fs,{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(Mr,{children:e.jsxs(U,{onClick:b,disabled:l.isPending,children:[l.isPending&&e.jsx(Et,{className:"mr-1.5 h-4 w-4 animate-spin"}),u.id?"Save video":"Add video"]})})]})})]})},Hxt={title:"",description:"",category:"Resources",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},tZs=({programId:s})=>{const{data:t=[],isLoading:n}=g7t(s),r=$9s(s),a=V9s(),[i,l]=j.useState(!1),[o,c]=j.useState({...Hxt}),[d,u]=j.useState(!1),h=j.useRef(null),m=Array.from(new Set(t.map(v=>v.category))).filter(Boolean),p=()=>{c({...Hxt,sort_order:t.length}),l(!0)},f=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",N=`programs/${s}/resources/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${b}`,{error:S}=await q.storage.from(TG).upload(N,v,{contentType:v.type||"application/pdf",upsert:!1});if(S)throw S;c(A=>({...A,file_path:N,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(U,{onClick:p,children:[e.jsx(an,{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(we,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Ur,{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=ure(v);return e.jsx(we,{className:"border-border/60",children:e.jsxs(Ie,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:v.title}),e.jsx(Be,{variant:"secondary",children:v.category}),e.jsx(Be,{variant:"outline",className:"capitalize",children:v.resource_kind.replace("_"," ")}),v.status!=="published"&&e.jsx(Be,{variant:"outline",className:"capitalize",children:v.status})]}),v.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:v.description}),b&&e.jsxs("button",{type:"button",onClick:()=>LQ(v),className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Sr,{className:"h-3 w-3"})," Open"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>f(v),children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:async()=>{await Yi(`Remove "${v.title}"?`)&&a.mutate(v)},children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]})]})},v.id)})}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Ds,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsx($s,{children:o.id?"Edit resource":"Add resource"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Title"}),e.jsx(xe,{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(te,{children:"Description"}),e.jsx(Fs,{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(te,{children:"Category"}),e.jsx(xe,{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(te,{children:"Type"}),e.jsxs(Ns,{value:o.resource_kind,onValueChange:v=>c({...o,resource_kind:v}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:f7t.map(v=>e.jsx(et,{value:v.value,children:v.label},v.value))})]})]})]}),e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsx(te,{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(U,{variant:"ghost",size:"sm",onClick:()=>c({...o,file_path:""}),children:"Remove"})]}):e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>{var v;return(v=h.current)==null?void 0:v.click()},disabled:d,children:[d?e.jsx(Et,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(qa,{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(xe,{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(te,{children:"Status"}),e.jsxs(Ns,{value:o.status,onValueChange:v=>c({...o,status:v}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"published",children:"Published (visible)"}),e.jsx(et,{value:"draft",children:"Draft (hidden)"}),e.jsx(et,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Sort order"}),e.jsx(xe,{type:"number",value:o.sort_order,onChange:v=>c({...o,sort_order:v.target.value})})]})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(U,{onClick:y,disabled:r.isPending||d,children:[r.isPending&&e.jsx(Et,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save resource"]})]})]})})]})},sZs=({programId:s})=>{const{data:t=[],isLoading:n}=Z9s(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(we,{children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx(A4,{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(we,{children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx(Bn,{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(we,{children:e.jsx(Ie,{className:"flex items-center gap-3 p-4",children:e.jsxs(Be,{variant:"secondary",children:[t.filter(l=>l.notified_at).length," notified"]})})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(U,{variant:"outline",size:"sm",disabled:!a,onClick:()=>{navigator.clipboard.writeText(a),re.success("Emails copied")},children:[e.jsx(Pa,{className:"mr-2 h-4 w-4"})," Copy emails"]}),e.jsxs(U,{variant:"outline",size:"sm",disabled:!t.length,onClick:i,children:[e.jsx(pi,{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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Member"}),e.jsx(Lt,{children:"Email"}),e.jsx(Lt,{children:"Phone"}),e.jsx(Lt,{children:"Brokerage"}),e.jsx(Lt,{children:"Joined"})]})}),e.jsx(Xa,{children:t.map(l=>e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium",children:l.full_name||"—"}),e.jsx(gt,{children:l.email||"—"}),e.jsx(gt,{children:l.phone||"—"}),e.jsx(gt,{children:l.brokerage||"—"}),e.jsx(gt,{className:"text-muted-foreground",children:Zd(l.created_at)})]},l.id))})]})})]})},Gxt={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:""},nZs=()=>{const s=Qt(),[t,n]=j.useState(null),[r,a]=j.useState(!1),[i,l]=j.useState({...Gxt}),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,m]=j.useState(null),{data:p=[],isLoading:f}=ct({queryKey:["admin-programs"],queryFn:async()=>{const{data:M,error:I}=await q.from("programs").select("*").order("created_at",{ascending:!1});if(I)throw I;return M||[]}}),x=p.find(M=>M.id===t)||p[0]||null,{data:y=[]}=ct({queryKey:["admin-program-enrollments",x==null?void 0:x.id],enabled:!!(x!=null&&x.id),queryFn:async()=>{const{data:M,error:I}=await q.from("program_enrollments").select("*").eq("program_id",x.id).order("created_at",{ascending:!1});if(I)throw I;const R=(M||[]).map(H=>H.user_id),{data:z}=R.length?await q.from("profiles").select("id, name, email").in("id",R):{data:[]},$=new Map((z||[]).map(H=>[H.id,H]));return(M||[]).map(H=>({...H,profile:$.get(H.user_id)}))}}),{data:v=[]}=ct({queryKey:["admin-program-intakes",x==null?void 0:x.id],enabled:!!(x!=null&&x.id),queryFn:async()=>{const{data:M,error:I}=await q.from("program_intake_responses").select("*").eq("program_id",x.id);if(I)throw I;return M||[]}}),{data:b=[]}=ct({queryKey:["admin-program-audit",x==null?void 0:x.id],enabled:!!(x!=null&&x.id),queryFn:async()=>{const{data:M,error:I}=await q.from("program_audit_logs").select("*").eq("program_id",x.id).order("created_at",{ascending:!1}).limit(100);if(I)throw I;return M||[]}}),N=async()=>{c(!0);try{const M={...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:I}=await q.from("programs").insert(M);if(I)throw I;re.success("Program created"),a(!1),l({...Gxt}),s.invalidateQueries({queryKey:["admin-programs"]})}catch(M){re.error(M.message||"Could not create the program")}finally{c(!1)}},S=async M=>{if(!x)return;const{error:I}=await q.from("programs").update(M).eq("id",x.id);if(I)return re.error(I.message);s.invalidateQueries({queryKey:["admin-programs"]})},A=async(M,I)=>{const{error:R}=await q.from("program_enrollments").update(I).eq("id",M);if(R)return re.error(R.message);re.success("Enrollment updated"),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},T=async M=>{u(!0);const{data:I,error:R}=await q.functions.invoke("program-charge-due",{body:M?{enrollment_id:M}:{}});if(u(!1),R||I!=null&&I.error)return re.error((I==null?void 0:I.error)||(R==null?void 0:R.message));re.success(`Processed ${(I==null?void 0:I.processed)??0} charge(s)`),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},L=M=>M==="paid"||M==="completed"?"default":M==="payment_failed"?"destructive":"secondary";return e.jsx(qs,{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(U,{variant:"outline",onClick:()=>T(),disabled:d,children:[d?e.jsx(Et,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(oy,{className:"mr-1.5 h-4 w-4"}),"Run due charges"]}),e.jsxs(zs,{open:r,onOpenChange:a,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{children:[e.jsx(an,{className:"mr-1.5 h-4 w-4"})," New program"]})}),e.jsxs(Ds,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Create a program"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Name"}),e.jsx(xe,{value:i.name,onChange:M=>l({...i,name:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Slug (URL)"}),e.jsx(xe,{placeholder:"reel-estate-90",value:i.slug,onChange:M=>l({...i,slug:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Subtitle"}),e.jsx(xe,{value:i.subtitle,onChange:M=>l({...i,subtitle:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Description"}),e.jsx(Fs,{rows:4,value:i.description,onChange:M=>l({...i,description:M.target.value})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"One-time price (USD)"}),e.jsx(xe,{type:"number",value:i.price_cents/100,onChange:M=>l({...i,price_cents:Math.round(Number(M.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(te,{children:"Seats"}),e.jsx(xe,{type:"number",value:i.capacity,onChange:M=>l({...i,capacity:Number(M.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Weeks"}),e.jsx(xe,{type:"number",value:i.duration_weeks,onChange:M=>l({...i,duration_weeks:Number(M.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Videos per week"}),e.jsx(xe,{type:"number",value:i.weekly_video_goal,onChange:M=>l({...i,weekly_video_goal:Number(M.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Billing"}),e.jsxs(Ns,{value:i.payment_mode,onValueChange:M=>l({...i,payment_mode:M}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"delayed",children:"Save card, charge later"}),e.jsx(et,{value:"immediate",children:"Charge at checkout"}),e.jsx(et,{value:"free",children:"Free / included"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Kickoff"}),e.jsx(xe,{type:"datetime-local",value:i.kickoff_at,onChange:M=>l({...i,kickoff_at:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Charge date"}),e.jsx(xe,{type:"datetime-local",value:i.charge_at,onChange:M=>l({...i,charge_at:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Enrollment closes"}),e.jsx(xe,{type:"datetime-local",value:i.enrollment_close_at,onChange:M=>l({...i,enrollment_close_at:M.target.value})})]})]})]}),e.jsx(Mr,{children:e.jsxs(U,{onClick:N,disabled:o||!i.name,children:[o&&e.jsx(Et,{className:"mr-1.5 h-4 w-4 animate-spin"})," Create"]})})]})]})]})]}),f?e.jsx(xn,{className:"h-40 w-full rounded-xl"}):p.length===0?e.jsx(we,{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:p.map(M=>e.jsxs(U,{variant:(x==null?void 0:x.id)===M.id?"default":"outline",size:"sm",onClick:()=>n(M.id),children:[M.name,e.jsx(Be,{variant:"secondary",className:"ml-2 capitalize",children:M.status})]},M.id))}),x&&e.jsxs(oa,{defaultValue:"overview",children:[e.jsxs(la,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(Kt,{value:"overview",children:"Overview"}),e.jsx(Kt,{value:"details",children:"Details & pricing"}),e.jsx(Kt,{value:"sessions",children:"Live sessions"}),e.jsx(Kt,{value:"videos",children:"On-demand videos"}),e.jsx(Kt,{value:"resources",children:"Resources"}),e.jsx(Kt,{value:"intake-form",children:"Intake form"}),e.jsx(Kt,{value:"discounts",children:"Discount codes"}),e.jsx(Kt,{value:"experience",children:"Enrollee experience"}),e.jsx(Kt,{value:"interest",children:"Interest list"}),e.jsxs(Kt,{value:"enrollments",children:["Enrollments (",y.length,")"]}),e.jsxs(Kt,{value:"intake",children:["Intake (",v.length,")"]}),e.jsx(Kt,{value:"audit",children:"Audit"})]}),e.jsxs(Zt,{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(we,{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(M=>["reserved","scheduled_for_charge","paid","completed"].includes(M.status)).length,e.jsxs("span",{className:"text-base font-normal text-muted-foreground",children:[" / ",x.capacity]})]})]})}),e.jsx(we,{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(M=>M.status==="paid").length})]})}),e.jsx(we,{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(M=>M.status==="payment_failed").length})]})}),e.jsx(we,{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:gf(y.filter(M=>["scheduled_for_charge","paid","completed"].includes(M.status)).reduce((M,I)=>M+(I.amount_cents||0),0),x.currency)})]})})]}),e.jsx(we,{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(wn,{checked:x.status==="published",onCheckedChange:M=>S({status:M?"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(wn,{checked:x.is_featured,onCheckedChange:M=>S({is_featured:M})})]}),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:gf(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:Zd(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:Zd(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(Zt,{value:"details",className:"mt-6",children:e.jsx(zYs,{program:x,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(Zt,{value:"sessions",className:"mt-6",children:e.jsx(JYs,{programId:x.id})}),e.jsx(Zt,{value:"videos",className:"mt-6",children:e.jsx(eZs,{programId:x.id})}),e.jsx(Zt,{value:"resources",className:"mt-6",children:e.jsx(tZs,{programId:x.id})}),e.jsx(Zt,{value:"discounts",className:"mt-6",children:e.jsx(qYs,{program:x})}),e.jsx(Zt,{value:"intake-form",className:"mt-6",children:e.jsx(GYs,{program:x,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(Zt,{value:"experience",className:"mt-6",children:e.jsx($Ys,{program:x})}),e.jsx(Zt,{value:"interest",className:"mt-6",children:e.jsx(sZs,{programId:x.id})}),e.jsx(Zt,{value:"enrollments",className:"mt-6",children:e.jsx(we,{children:e.jsx(Ie,{className:"overflow-x-auto p-0",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Member"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{children:"Charge date"}),e.jsx(Lt,{children:"Amount"}),e.jsx(Lt,{children:"Access"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsxs(Xa,{children:[y.length===0&&e.jsx(gn,{children:e.jsxs(gt,{colSpan:6,className:"py-10 text-center text-sm text-muted-foreground",children:[e.jsx(Bn,{className:"mx-auto mb-2 h-5 w-5"}),"No enrollments yet"]})}),y.map(M=>{var I,R;return e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsxs("button",{type:"button",className:"text-left hover:underline",onClick:()=>m(M),children:[e.jsx("p",{className:"font-medium",children:((I=M.profile)==null?void 0:I.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(R=M.profile)==null?void 0:R.email})]})}),e.jsxs(gt,{children:[e.jsx(Be,{variant:L(M.status),className:"capitalize",children:String(M.status).replace(/_/g," ")}),M.last_payment_error&&e.jsx("p",{className:"mt-1 max-w-[200px] truncate text-xs text-destructive",children:M.last_payment_error})]}),e.jsx(gt,{className:"text-sm",children:Zd(M.charge_scheduled_at)||"—"}),e.jsx(gt,{className:"text-sm",children:gf(M.amount_cents,M.currency)}),e.jsx(gt,{children:e.jsx(wn,{checked:M.access_override,onCheckedChange:z=>A(M.id,{access_override:z})})}),e.jsxs(gt,{className:"space-x-2 text-right",children:[["scheduled_for_charge","payment_failed"].includes(M.status)&&e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>T(M.id),disabled:d,children:[e.jsx(no,{className:"mr-1.5 h-3.5 w-3.5"})," Charge now"]}),!["canceled","refunded"].includes(M.status)&&e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>A(M.id,{status:"canceled",canceled_at:new Date().toISOString()}),children:"Cancel"})]})]},M.id)})]})]})})})}),e.jsx(Zt,{value:"intake",className:"mt-6",children:e.jsx(ZYs,{program:x})}),e.jsx(Zt,{value:"audit",className:"mt-6",children:e.jsx(we,{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(M=>e.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-b border-border/40 py-2 last:border-0",children:[e.jsx(Be,{variant:"outline",className:"capitalize",children:String(M.action).replace(/_/g," ")}),e.jsx("span",{className:"text-muted-foreground",children:M.actor_label||"system"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:Zd(M.created_at,!0)})]},M.id))]})})})]}),x&&e.jsx(UYs,{program:x,enrollment:h,open:!!h,onOpenChange:M=>!M&&m(null),onUpdated:()=>s.invalidateQueries({queryKey:["admin-program-enrollments"]})})]})]})})},rZs=()=>{const{user:s}=vs(),[t,n]=j.useState(""),[r,a]=j.useState("all"),{data:i=[]}=ct({queryKey:["academy-categories"],queryFn:async()=>{const{data:m,error:p}=await q.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(p)throw p;return m}}),{data:l=[],isLoading:o}=ct({queryKey:["academy-videos"],queryFn:async()=>{const{data:m,error:p}=await q.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("is_published",!0).order("publish_date",{ascending:!1});if(p)throw p;const{data:f,error:x}=await q.from("academy_resources").select("*").order("sort_order");if(x)throw x;return m.map(v=>({...v,resources:(f==null?void 0:f.filter(b=>b.video_id===v.id))||[]}))}}),{data:c=[]}=ct({queryKey:["academy-video-likes"],queryFn:async()=>{const{data:m,error:p}=await q.from("academy_video_likes").select("video_id, user_id");if(p)throw p;return m}}),d=l.filter(m=>{var x;const p=t===""||m.title.toLowerCase().includes(t.toLowerCase())||((x=m.description)==null?void 0:x.toLowerCase().includes(t.toLowerCase())),f=r==="all"||m.category_id===r;return p&&f}),u=m=>c.filter(p=>p.video_id===m).length,h=m=>c.some(p=>p.video_id===m&&p.user_id===(s==null?void 0:s.id));return e.jsx(qs,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search videos...",value:t,onChange:m=>n(m.target.value),className:"pl-10"})]})}),e.jsx(oa,{value:r,onValueChange:a,children:e.jsxs(la,{className:"w-full justify-start flex-wrap h-auto gap-2 bg-transparent p-0",children:[e.jsx(Kt,{value:"all",className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:"All Videos"}),i.map(m=>e.jsx(Kt,{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(we,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Wr,{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(xr,{to:`/academy/${m.id}`,children:e.jsxs(we,{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(Wr,{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(lu,{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(Yr,{className:"h-3 w-3"}),m.duration]})]}),e.jsxs(Tt,{className:"pb-2",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsx(It,{className:"text-lg line-clamp-2",children:m.title})}),m.category&&e.jsx(Be,{variant:"secondary",className:"w-fit",children:m.category.name})]}),e.jsxs(Ie,{className:"pt-0",children:[m.description&&e.jsx(Jn,{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(wx,{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(Ur,{className:"h-4 w-4"}),m.resources.length]})]})]})]})},m.id))})]})})};function sBt({resourceType:s,resourceId:t}){const{data:n=[]}=ct({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($c,{className:"h-4 w-4"}),"Related Templates"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(r=>e.jsx(xr,{to:`/templates/${r.id}`,children:e.jsxs(Be,{variant:"secondary",className:"cursor-pointer hover:bg-secondary/80 transition-colors gap-1.5 px-3 py-1.5 text-xs font-medium rounded-full",children:[e.jsx($c,{className:"h-3 w-3"}),r.name]})},r.id))})]})}const aZs=(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},iZs=()=>{const{videoId:s}=Di();Wn();const{user:t,isAdmin:n}=vs(),{toast:r}=Ai(),a=Qt(),{trackEngagement:i}=EG(),[l,o]=j.useState(""),{data:c,isLoading:d}=ct({queryKey:["academy-video",s],queryFn:async()=>{const{data:N,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{...N,resources:A||[]}},enabled:!!s});j.useEffect(()=>{c&&i("academy_video",c.id,c.title,"view")},[c==null?void 0:c.id]);const{data:u=[]}=ct({queryKey:["academy-video-likes",s],queryFn:async()=>{const{data:N,error:S}=await q.from("academy_video_likes").select("*").eq("video_id",s);if(S)throw S;return N},enabled:!!s}),{data:h=[]}=ct({queryKey:["academy-video-comments",s],queryFn:async()=>{const{data:N,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(N.map(M=>M.user_id))],{data:T}=await q.from("profiles").select("id, name").in("id",A),L=new Map((T==null?void 0:T.map(M=>[M.id,M.name]))||[]);return N.map(M=>({...M,user_name:L.get(M.user_id)||"Unknown User"}))},enabled:!!s}),m=yt({mutationFn:async N=>{const{error:S}=await q.from("academy_video_comments").insert({video_id:s,user_id:t.id,content:N});if(S)throw S},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),o(""),r({title:"Comment added!"})},onError:N=>{r({title:"Error adding comment",description:N.message,variant:"destructive"})}}),p=yt({mutationFn:async N=>{const{error:S}=await q.from("academy_video_comments").delete().eq("id",N);if(S)throw S},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),r({title:"Comment deleted"})}}),f=yt({mutationFn:async()=>{const N=u.find(S=>S.user_id===(t==null?void 0:t.id));if(N){const{error:S}=await q.from("academy_video_likes").delete().eq("id",N.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(N=>N.user_id===(t==null?void 0:t.id)),y=N=>{switch(N==null?void 0:N.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=N=>N.split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),b=N=>{N.preventDefault(),!(!l.trim()||!t)&&m.mutate(l.trim())};return d?e.jsx(qs,{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(qs,{title:c.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(U,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(xr,{to:"/academy",children:[e.jsx(Aa,{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:aZs(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(Wr,{className:"h-16 w-16 opacity-50"}),e.jsx(U,{variant:"secondary",asChild:!0,children:e.jsxs("a",{href:c.video_url,target:"_blank",rel:"noopener noreferrer",className:"gap-2",children:[e.jsx(Sr,{className:"h-4 w-4"}),"Open Video"]})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:c.title}),c.category&&e.jsx(Be,{variant:"secondary",children:c.category.name})]}),e.jsxs("div",{className:"flex gap-2",children:[n&&e.jsx(U,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(xr,{to:`/admin/academy?edit=${c.id}`,children:[e.jsx(ri,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(PG,{resourceType:"academy_video",resourceId:c.id,resourceTitle:c.title}),e.jsxs(U,{variant:x?"default":"outline",className:"gap-2 w-fit",onClick:()=>f.mutate(),disabled:!t||f.isPending,children:[e.jsx(wx,{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(we,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Ur,{className:"h-4 w-4"}),"Resources"]}),e.jsx("div",{className:"grid gap-2",children:c.resources.map(N=>e.jsxs("a",{href:N.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(N.file_type)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:N.title}),e.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:N.file_type})]}),e.jsx(pi,{className:"h-4 w-4 text-muted-foreground"})]},N.id))})]})}),e.jsx(sBt,{resourceType:"academy_video",resourceId:c.id}),e.jsx(hc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(vu,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:b,className:"flex gap-2",children:[e.jsx(Fs,{placeholder:"Add a comment...",value:l,onChange:N=>o(N.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(U,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||m.isPending,children:e.jsx($r,{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(we,{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(N=>e.jsx(we,{children:e.jsx(Ie,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ea,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Ta,{className:"text-sm",children:v(N.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:N.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Nd(new Date(N.created_at),{addSuffix:!0})}),N.user_id===(t==null?void 0:t.id)&&e.jsx(U,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>p.mutate(N.id),children:e.jsx(In,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:N.content})]})]})})},N.id))})]})]})}):e.jsx(qs,{title:"Academy",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Wr,{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(U,{asChild:!0,className:"mt-4",children:e.jsx(xr,{to:"/academy",children:"Back to Academy"})})]})})},Zz="https://dashboard.relevelup.com",oZs=(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},lZs=[{icon:$h,title:"100+ Training Videos",desc:"On-demand LevelUp Academy content covering lead gen, listings, buyer conversion, marketing, and more."},{icon:Af,title:"Marketing Studio & Tools",desc:"AI-powered marketing tools, listing videos, landing pages, and social content — done for you."},{icon:Bn,title:"Coaching & Community",desc:"Live coaching sessions, private community, and a network of top-performing agents."},{icon:Al,title:"Business Scorecard",desc:"Track your deals, GCI, and pipeline in one dashboard built for real estate."}];function cZs(){var i;const{slug:s}=Di(),{data:t,isLoading:n,error:r}=ct({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"]');if(o&&o.setAttribute("content",l||"Free training preview from LevelUp Academy."),t.thumbnail_url){let c=document.querySelector('meta[property="og:image"]');c||(c=document.createElement("meta"),c.setAttribute("property","og:image"),document.head.appendChild(c)),c.setAttribute("content",t.thumbnail_url)}}},[t,s]);const a=j.useMemo(()=>t?oZs(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:Zz,children:e.jsx(U,{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(cn,{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:Zz,children:e.jsx(U,{variant:"ghost",className:"text-[#e8ecf1] hover:bg-white/5 hover:text-white",children:"Sign In"})})]})}),e.jsxs("section",{className:"relative z-10 max-w-6xl mx-auto px-6 pt-12 pb-16",children:[e.jsxs("div",{className:"text-center mb-8 space-y-4",children:[e.jsxs(Be,{className:"bg-[#406E71]/20 text-[#7ec0c3] border-[#406E71]/40 hover:bg-[#406E71]/30",children:[e.jsx($h,{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(pv,{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:Zz,className:"w-full sm:w-auto",children:e.jsxs(U,{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(Oa,{className:"w-4 h-4 ml-2"})]})}),e.jsx("a",{href:Zz,className:"w-full sm:w-auto",children:e.jsx(U,{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:lZs.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(zr,{className:"w-4 h-4 text-[#7ec0c3]"})," Trusted by top producers"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(zr,{className:"w-4 h-4 text-[#7ec0c3]"})," New training weekly"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(zr,{className:"w-4 h-4 text-[#7ec0c3]"})," Cancel anytime"]})]}),e.jsx("div",{className:"text-center",children:e.jsx("a",{href:Zz,children:e.jsxs(U,{size:"lg",className:"bg-[#406E71] hover:bg-[#4d8285] text-white h-12 px-10 shadow-lg",children:["Get Started at LevelUp",e.jsx(Oa,{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:Zz,className:"hover:text-[#7ec0c3]",children:"dashboard.relevelup.com"})]})]})}function dZs(){const s=Wn(),[t,n]=j.useState(""),{data:r,isLoading:a}=ct({queryKey:["resource-kits-published"],queryFn:async()=>{const{data:p,error:f}=await q.from("resource_kits").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(f)throw f;return p}}),{data:i}=ct({queryKey:["resource-kit-files-all"],queryFn:async()=>{const{data:p,error:f}=await q.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(f)throw f;return p}}),{data:l}=ct({queryKey:["resource-kit-likes-all"],queryFn:async()=>{const{data:p,error:f}=await q.from("resource_kit_likes").select("kit_id");if(f)throw f;return p}}),{data:o}=ct({queryKey:["resource-kit-comments-all"],queryFn:async()=>{const{data:p,error:f}=await q.from("resource_kit_comments").select("kit_id");if(f)throw f;return p}}),c=r==null?void 0:r.filter(p=>{var f;return p.name.toLowerCase().includes(t.toLowerCase())||((f=p.description)==null?void 0:f.toLowerCase().includes(t.toLowerCase()))}),d=p=>(i==null?void 0:i.filter(f=>f.kit_id===p))||[],u=p=>(l==null?void 0:l.filter(f=>f.kit_id===p).length)||0,h=p=>(o==null?void 0:o.filter(f=>f.kit_id===p).length)||0,m=p=>{s(`/toolbox/${p}`)};return e.jsx(qs,{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(Fr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search resource kits...",value:t,onChange:p=>n(p.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((p,f)=>e.jsx(we,{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"})]})},f))}):(c==null?void 0:c.length)===0?e.jsxs(we,{className:"p-12 text-center",children:[e.jsx(dh,{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(p=>{const f=d(p.id).length,x=u(p.id),y=h(p.id);return e.jsxs(we,{className:"group overflow-hidden cursor-pointer hover:shadow-lg transition-all duration-200",onClick:()=>m(p.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:p.featured_image_url?e.jsx("img",{src:p.featured_image_url,alt:p.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(dh,{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:p.name}),p.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:KJ(p.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(Ur,{className:"h-4 w-4"}),f," file",f!==1?"s":""]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(wx,{className:"h-3.5 w-3.5"}),x]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(vu,{className:"h-3.5 w-3.5"}),y]})]})]})]})]},p.id)})})]})})}const uZs=()=>{const{kitId:s}=Di(),{user:t,isAdmin:n}=vs(),{toast:r}=Ai(),a=Qt(),{trackEngagement:i}=EG(),[l,o]=j.useState(""),{data:c,isLoading:d}=ct({queryKey:["resource-kit-detail",s],queryFn:async()=>{const{data:N,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:T}=await q.from("resource_kit_links").select("*").eq("kit_id",s).order("sort_order");return{...N,files:A||[],links:T||[]}},enabled:!!s});j.useEffect(()=>{c&&i("toolbox",c.id,c.name,"view")},[c==null?void 0:c.id]);const{data:u=[]}=ct({queryKey:["resource-kit-likes",s],queryFn:async()=>{const{data:N,error:S}=await q.from("resource_kit_likes").select("*").eq("kit_id",s);if(S)throw S;return N},enabled:!!s}),{data:h=[]}=ct({queryKey:["resource-kit-comments",s],queryFn:async()=>{const{data:N,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(N.map(M=>M.user_id))],{data:T}=await q.from("profiles").select("id, name").in("id",A),L=new Map((T==null?void 0:T.map(M=>[M.id,M.name]))||[]);return N.map(M=>({...M,user_name:L.get(M.user_id)||"Unknown User"}))},enabled:!!s}),m=yt({mutationFn:async N=>{const{error:S}=await q.from("resource_kit_comments").insert({kit_id:s,user_id:t.id,content:N});if(S)throw S},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),o(""),r({title:"Comment added!"})},onError:N=>{r({title:"Error adding comment",description:N.message,variant:"destructive"})}}),p=yt({mutationFn:async N=>{const{error:S}=await q.from("resource_kit_comments").delete().eq("id",N);if(S)throw S},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),r({title:"Comment deleted"})}}),f=yt({mutationFn:async()=>{const N=u.find(S=>S.user_id===(t==null?void 0:t.id));if(N){const{error:S}=await q.from("resource_kit_likes").delete().eq("id",N.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(N=>N.user_id===(t==null?void 0:t.id)),y=N=>N.split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),v=N=>N?N<1024?N+" B":N<1024*1024?(N/1024).toFixed(1)+" KB":(N/(1024*1024)).toFixed(1)+" MB":"",b=N=>{N.preventDefault(),!(!l.trim()||!t)&&m.mutate(l.trim())};return d?e.jsx(qs,{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(qs,{title:c.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(U,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(xr,{to:"/toolbox",children:[e.jsx(Aa,{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(U,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(xr,{to:`/admin/toolbox?edit=${c.id}`,children:[e.jsx(ri,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(PG,{resourceType:"resource_kit",resourceId:c.id,resourceTitle:c.name,size:"default",className:"rounded-full"}),e.jsxs(U,{variant:x?"default":"outline",className:"gap-2 rounded-full",onClick:()=>f.mutate(),disabled:!t||f.isPending,children:[e.jsx(wx,{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(we,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Ur,{className:"h-4 w-4"}),"Included Resources (",c.files.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.files.map(N=>e.jsxs("a",{href:N.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(Ur,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:N.name}),N.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:v(N.file_size)})]})]}),e.jsx(pi,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},N.id))})]})}),c.links&&c.links.length>0&&e.jsx(we,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Sr,{className:"h-4 w-4"}),"Canva Templates (",c.links.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.links.map(N=>e.jsxs("a",{href:N.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(Sr,{className:"h-4 w-4 text-purple-600"})}),e.jsx("div",{className:"font-medium text-sm",children:N.title})]}),e.jsx("span",{className:"text-xs text-muted-foreground group-hover:text-primary transition-colors",children:"Open in Canva"})]},N.id))})]})}),e.jsx(sBt,{resourceType:"resource_kit",resourceId:c.id}),e.jsx(hc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(vu,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:b,className:"flex gap-2",children:[e.jsx(Fs,{placeholder:"Add a comment...",value:l,onChange:N=>o(N.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(U,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||m.isPending,children:e.jsx($r,{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(we,{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(N=>e.jsx(we,{children:e.jsx(Ie,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ea,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Ta,{className:"text-sm",children:y(N.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:N.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Nd(new Date(N.created_at),{addSuffix:!0})}),N.user_id===(t==null?void 0:t.id)&&e.jsx(U,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>p.mutate(N.id),children:e.jsx(In,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:N.content})]})]})})},N.id))})]})]})}):e.jsx(qs,{title:"Toolbox",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(dh,{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(U,{asChild:!0,className:"mt-4",children:e.jsx(xr,{to:"/toolbox",children:"Back to Toolbox"})})]})})},hZs=()=>{const s=Wn(),[t,n]=j.useState(""),[r,a]=j.useState("grid"),{data:i=[],isLoading:l}=ct({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:p}=await q.from("social_swag_likes").select("swag_id"),{data:f}=await q.from("social_swag_comments").select("swag_id"),x=new Map;p==null||p.forEach(b=>{x.set(b.swag_id,(x.get(b.swag_id)||0)+1)});const y=new Map;return f==null||f.forEach(b=>{y.set(b.swag_id,(y.get(b.swag_id)||0)+1)}),(d||[]).map(b=>({...b,links:(h||[]).filter(N=>N.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(qs,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{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(U,{variant:"outline",size:"sm",onClick:()=>n(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(U,{variant:r==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(Hg,{className:"h-4 w-4"})}),e.jsx(U,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(m0,{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(we,{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(U,{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(we,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${r==="list"?"flex flex-row":""}`,onClick:()=>c(d.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${r==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[d.preview_image_url?e.jsx("img",{src:d.preview_image_url,alt:d.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"}),d.links.length>1&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Be,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm",children:[e.jsx(Rc,{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(wx,{className:"h-3.5 w-3.5"}),d.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(vu,{className:"h-3.5 w-3.5"}),d.commentsCount]})]}),e.jsxs(U,{size:"sm",className:"w-full gap-2",onClick:u=>{u.stopPropagation(),c(d.id)},children:[e.jsx(Sr,{className:"h-4 w-4"}),"View Details"]})]})]},d.id))})]})})};var Ul=function(){return Ul=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)},p=function(){a&&i(a)};return e.jsx(HZs,{displayMonth:s.displayMonth,hideNext:u,hidePrevious:h,nextMonth:a,previousMonth:r,onPreviousClick:m,onNextClick:p})}function GZs(s){var t,n=Fm(),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:aBt,d;return a?d=e.jsx(c,{id:s.id,displayMonth:s.displayMonth}):l==="dropdown"?d=e.jsx(Wxt,{displayMonth:s.displayMonth,id:s.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(Wxt,{displayMonth:s.displayMonth,displayIndex:s.displayIndex,id:s.id}),e.jsx(Kxt,{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(Kxt,{displayMonth:s.displayMonth,id:s.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function WZs(s){var t=Fm(),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 KZs(s,t,n){for(var r=n?nE(new Date):c1(new Date,{locale:s,weekStartsOn:t}),a=[],i=0;i<7;i++){var l=jh(r,i);a.push(l)}return a}function YZs(){var s=Fm(),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=KZs(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 ZZs(){var s,t=Fm(),n=t.classNames,r=t.styles,a=t.components,i=(s=a==null?void 0:a.HeadRow)!==null&&s!==void 0?s:YZs;return e.jsx("thead",{style:r.head,className:n.head,children:e.jsx(i,{})})}function XZs(s){var t=Fm(),n=t.locale,r=t.formatters.formatDay;return e.jsx(e.Fragment,{children:r(s.date,{locale:n})})}var $Je=j.createContext(void 0);function QZs(s){if(!xre(s.initialProps)){var t={selected:void 0,modifiers:{disabled:[]}};return e.jsx($Je.Provider,{value:t,children:s.children})}return e.jsx(JZs,{initialProps:s.initialProps,children:s.children})}function JZs(s){var t=s.initialProps,n=s.children,r=t.selected,a=t.min,i=t.max,l=function(d,u,h){var m,p;(m=t.onDayClick)===null||m===void 0||m.call(t,d,u,h);var f=!!(u.selected&&a&&(r==null?void 0:r.length)===a);if(!f){var x=!!(!u.selected&&i&&(r==null?void 0:r.length)===i);if(!x){var y=r?nBt([],r):[];if(u.selected){var v=y.findIndex(function(b){return Hh(d,b)});y.splice(v,1)}else y.push(d);(p=t.onSelect)===null||p===void 0||p.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 Hh(m,d)});return!!(u&&!h)});var c={selected:r,onDayClick:l,modifiers:o};return e.jsx($Je.Provider,{value:c,children:n})}function VJe(){var s=j.useContext($Je);if(!s)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return s}function eXs(s,t){var n=t||{},r=n.from,a=n.to;return r&&a?Hh(a,s)&&Hh(r,s)?void 0:Hh(a,s)?{from:a,to:void 0}:Hh(r,s)?void 0:F4(r,s)?{from:s,to:a}:{from:r,to:s}:a?F4(s,a)?{from:a,to:s}:{from:s,to:a}:r?rS(s,r)?{from:s,to:r}:{from:r,to:s}:{from:s,to:void 0}}var HJe=j.createContext(void 0);function tXs(s){if(!yre(s.initialProps)){var t={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(HJe.Provider,{value:t,children:s.children})}return e.jsx(sXs,{initialProps:s.initialProps,children:s.children})}function sXs(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(p,f,x){var y,v;(y=t.onDayClick)===null||y===void 0||y.call(t,p,f,x);var b=eXs(p,r);(v=t.onSelect)===null||v===void 0||v.call(t,b,p,f,x)},u={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(u.range_start=[i],l?(u.range_end=[l],Hh(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:N5e(i,o-1),before:jh(i,o-1)}),i&&l&&u.disabled.push({after:i,before:jh(i,o-1)}),!i&&l&&u.disabled.push({after:N5e(l,o-1),before:jh(l,o-1)})),c){if(i&&!l&&(u.disabled.push({before:jh(i,-c+1)}),u.disabled.push({after:jh(i,c-1)})),i&&l){var h=nv(l,i)+1,m=c-h;u.disabled.push({before:N5e(i,m)}),u.disabled.push({after:jh(l,m)})}!i&&l&&(u.disabled.push({before:jh(l,-c+1)}),u.disabled.push({after:jh(l,c-1)}))}return e.jsx(HJe.Provider,{value:{selected:r,onDayClick:d,modifiers:u},children:n})}function GJe(){var s=j.useContext(HJe);if(!s)throw new Error("useSelectRange must be used within a SelectRangeProvider");return s}function W5e(s){return Array.isArray(s)?nBt([],s):s!==void 0?[s]:[]}function nXs(s){var t={};return Object.entries(s).forEach(function(n){var r=n[0],a=n[1];t[r]=W5e(a)}),t}var xS;(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"})(xS||(xS={}));var rXs=xS.Selected,tC=xS.Disabled,aXs=xS.Hidden,iXs=xS.Today,RFe=xS.RangeEnd,DFe=xS.RangeMiddle,OFe=xS.RangeStart,oXs=xS.Outside;function lXs(s,t,n){var r,a=(r={},r[rXs]=W5e(s.selected),r[tC]=W5e(s.disabled),r[aXs]=W5e(s.hidden),r[iXs]=[s.today],r[RFe]=[],r[DFe]=[],r[OFe]=[],r[oXs]=[],r);return s.fromDate&&a[tC].push({before:s.fromDate}),s.toDate&&a[tC].push({after:s.toDate}),xre(s)?a[tC]=a[tC].concat(t.modifiers[tC]):yre(s)&&(a[tC]=a[tC].concat(n.modifiers[tC]),a[OFe]=n.modifiers[OFe],a[DFe]=n.modifiers[DFe],a[RFe]=n.modifiers[RFe]),a}var lBt=j.createContext(void 0);function cXs(s){var t=Fm(),n=VJe(),r=GJe(),a=lXs(t,n,r),i=nXs(t.modifiers),l=Ul(Ul({},a),i);return e.jsx(lBt.Provider,{value:l,children:s.children})}function cBt(){var s=j.useContext(lBt);if(!s)throw new Error("useModifiers must be used within a ModifiersProvider");return s}function dXs(s){return!!(s&&typeof s=="object"&&"before"in s&&"after"in s)}function uXs(s){return!!(s&&typeof s=="object"&&"from"in s)}function hXs(s){return!!(s&&typeof s=="object"&&"after"in s)}function mXs(s){return!!(s&&typeof s=="object"&&"before"in s)}function pXs(s){return!!(s&&typeof s=="object"&&"dayOfWeek"in s)}function fXs(s,t){var n,r=t.from,a=t.to;if(r&&a){var i=nv(a,r)<0;i&&(n=[a,r],r=n[0],a=n[1]);var l=nv(s,r)>=0&&nv(a,s)>=0;return l}return a?Hh(a,s):r?Hh(r,s):!1}function gXs(s){return xXe(s)}function xXs(s){return Array.isArray(s)&&s.every(xXe)}function yXs(s,t){return t.some(function(n){if(typeof n=="boolean")return n;if(gXs(n))return Hh(s,n);if(xXs(n))return n.includes(s);if(uXs(n))return fXs(s,n);if(pXs(n))return n.dayOfWeek.includes(s.getDay());if(dXs(n)){var r=nv(n.before,s),a=nv(n.after,s),i=r>0,l=a<0,o=F4(n.before,n.after);return o?l&&i:i||l}return hXs(n)?nv(s,n.after)>0:mXs(n)?nv(n.before,s)>0:typeof n=="function"?n(s):!1})}function WJe(s,t,n){var r=Object.keys(t).reduce(function(i,l){var o=t[l];return yXs(s,o)&&i.push(l),i},[]),a={};return r.forEach(function(i){return a[i]=!0}),n&&!Kne(s,n)&&(a.outside=!0),a}function vXs(s,t){for(var n=Bh(s[0]),r=u_(s[s.length-1]),a,i,l=n;l<=r;){var o=WJe(l,t),c=!o.disabled&&!o.hidden;if(!c){l=jh(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),a||(a=l),l=jh(l,1)}return i||a}var bXs=365;function dBt(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:jh,week:qD,month:dy,year:YSs,startOfWeek:function(y){return a.ISOWeek?nE(y):c1(y,{locale:h,weekStartsOn:c})},endOfWeek:function(y){return a.ISOWeek?OIt(y):mMe(y,{locale:h,weekStartsOn:c})}},p=m[n](s,r==="after"?1:-1);r==="before"&&d?p=ZSs([d,p]):r==="after"&&u&&(p=XSs([u,p]));var f=!0;if(i){var x=WJe(p,i);f=!x.disabled&&!x.hidden}return f?p:o.count>bXs?o.lastFocused:dBt(p,{moveBy:n,direction:r,context:a,modifiers:i,retry:Ul(Ul({},o),{count:o.count+1})})}var uBt=j.createContext(void 0);function _Xs(s){var t=vre(),n=cBt(),r=j.useState(),a=r[0],i=r[1],l=j.useState(),o=l[0],c=l[1],d=vXs(t.displayMonths,n),u=a??(o&&t.isDateDisplayed(o))?o:d,h=function(){c(a),i(void 0)},m=function(y){i(y)},p=Fm(),f=function(y,v){if(a){var b=dBt(a,{moveBy:y,direction:v,context:p,modifiers:n});Hh(a,b)||(t.goToDate(b,a),m(b))}},x={focusedDay:a,focusTarget:u,blur:h,focus:m,focusDayAfter:function(){return f("day","after")},focusDayBefore:function(){return f("day","before")},focusWeekAfter:function(){return f("week","after")},focusWeekBefore:function(){return f("week","before")},focusMonthBefore:function(){return f("month","before")},focusMonthAfter:function(){return f("month","after")},focusYearBefore:function(){return f("year","before")},focusYearAfter:function(){return f("year","after")},focusStartOfWeek:function(){return f("startOfWeek","before")},focusEndOfWeek:function(){return f("endOfWeek","after")}};return e.jsx(uBt.Provider,{value:x,children:s.children})}function KJe(){var s=j.useContext(uBt);if(!s)throw new Error("useFocusContext must be used within a FocusProvider");return s}function wXs(s,t){var n=cBt(),r=WJe(s,n,t);return r}var YJe=j.createContext(void 0);function jXs(s){if(!LPe(s.initialProps)){var t={selected:void 0};return e.jsx(YJe.Provider,{value:t,children:s.children})}return e.jsx(NXs,{initialProps:s.initialProps,children:s.children})}function NXs(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(YJe.Provider,{value:a,children:n})}function hBt(){var s=j.useContext(YJe);if(!s)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return s}function kXs(s,t){var n=Fm(),r=hBt(),a=VJe(),i=GJe(),l=KJe(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,u=l.focusWeekBefore,h=l.blur,m=l.focus,p=l.focusMonthBefore,f=l.focusMonthAfter,x=l.focusYearBefore,y=l.focusYearAfter,v=l.focusStartOfWeek,b=l.focusEndOfWeek,N=function(Q){var le,ue,se,ne;LPe(n)?(le=r.onDayClick)===null||le===void 0||le.call(r,s,t,Q):xre(n)?(ue=a.onDayClick)===null||ue===void 0||ue.call(a,s,t,Q):yre(n)?(se=i.onDayClick)===null||se===void 0||se.call(i,s,t,Q):(ne=n.onDayClick)===null||ne===void 0||ne.call(n,s,t,Q)},S=function(Q){var le;m(s),(le=n.onDayFocus)===null||le===void 0||le.call(n,s,t,Q)},A=function(Q){var le;h(),(le=n.onDayBlur)===null||le===void 0||le.call(n,s,t,Q)},T=function(Q){var le;(le=n.onDayMouseEnter)===null||le===void 0||le.call(n,s,t,Q)},L=function(Q){var le;(le=n.onDayMouseLeave)===null||le===void 0||le.call(n,s,t,Q)},M=function(Q){var le;(le=n.onDayPointerEnter)===null||le===void 0||le.call(n,s,t,Q)},I=function(Q){var le;(le=n.onDayPointerLeave)===null||le===void 0||le.call(n,s,t,Q)},R=function(Q){var le;(le=n.onDayTouchCancel)===null||le===void 0||le.call(n,s,t,Q)},z=function(Q){var le;(le=n.onDayTouchEnd)===null||le===void 0||le.call(n,s,t,Q)},$=function(Q){var le;(le=n.onDayTouchMove)===null||le===void 0||le.call(n,s,t,Q)},H=function(Q){var le;(le=n.onDayTouchStart)===null||le===void 0||le.call(n,s,t,Q)},V=function(Q){var le;(le=n.onDayKeyUp)===null||le===void 0||le.call(n,s,t,Q)},K=function(Q){var le;switch(Q.key){case"ArrowLeft":Q.preventDefault(),Q.stopPropagation(),n.dir==="rtl"?o():c();break;case"ArrowRight":Q.preventDefault(),Q.stopPropagation(),n.dir==="rtl"?c():o();break;case"ArrowDown":Q.preventDefault(),Q.stopPropagation(),d();break;case"ArrowUp":Q.preventDefault(),Q.stopPropagation(),u();break;case"PageUp":Q.preventDefault(),Q.stopPropagation(),Q.shiftKey?x():p();break;case"PageDown":Q.preventDefault(),Q.stopPropagation(),Q.shiftKey?y():f();break;case"Home":Q.preventDefault(),Q.stopPropagation(),v();break;case"End":Q.preventDefault(),Q.stopPropagation(),b();break}(le=n.onDayKeyDown)===null||le===void 0||le.call(n,s,t,Q)},Z={onClick:N,onFocus:S,onBlur:A,onKeyDown:K,onKeyUp:V,onMouseEnter:T,onMouseLeave:L,onPointerEnter:M,onPointerLeave:I,onTouchCancel:R,onTouchEnd:z,onTouchMove:$,onTouchStart:H};return Z}function SXs(){var s=Fm(),t=hBt(),n=VJe(),r=GJe(),a=LPe(s)?t.selected:xre(s)?n.selected:yre(s)?r.selected:void 0;return a}function CXs(s){return Object.values(xS).includes(s)}function AXs(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(CXs(r)){var i=s.classNames["day_".concat(r)];i&&n.push(i)}}),n}function EXs(s,t){var n=Ul({},s.styles.day);return Object.keys(t).forEach(function(r){var a;n=Ul(Ul({},n),(a=s.modifiersStyles)===null||a===void 0?void 0:a[r])}),n}function TXs(s,t,n){var r,a,i,l=Fm(),o=KJe(),c=wXs(s,t),d=kXs(s,c),u=SXs(),h=!!(l.onDayClick||l.mode!=="default");j.useEffect(function(){var T;c.outside||o.focusedDay&&h&&Hh(o.focusedDay,s)&&((T=n.current)===null||T===void 0||T.focus())},[o.focusedDay,s,n,h,c.outside]);var m=AXs(l,c).join(" "),p=EXs(l,c),f=!!(c.outside&&!l.showOutsideDays||c.hidden),x=(i=(a=l.components)===null||a===void 0?void 0:a.DayContent)!==null&&i!==void 0?i:XZs,y=e.jsx(x,{date:s,displayMonth:t,activeModifiers:c}),v={style:p,className:m,children:y,role:"gridcell"},b=o.focusTarget&&Hh(o.focusTarget,s)&&!c.outside,N=o.focusedDay&&Hh(o.focusedDay,s),S=Ul(Ul(Ul({},v),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=N||b?0:-1,r)),d),A={isButton:h,isHidden:f,activeModifiers:c,selectedDays:u,buttonProps:S,divProps:v};return A}function MXs(s){var t=j.useRef(null),n=TXs(s.date,s.displayMonth,t);return n.isHidden?e.jsx("div",{role:"gridcell"}):n.isButton?e.jsx(wAe,Ul({name:"day",ref:t},n.buttonProps)):e.jsx("div",Ul({},n.divProps))}function PXs(s){var t=s.number,n=s.dates,r=Fm(),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(p){a(t,n,p)};return e.jsx(wAe,{name:"week-number","aria-label":h,className:l.weeknumber,style:i.weeknumber,onClick:m,children:u})}function LXs(s){var t,n,r=Fm(),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:MXs,d=(n=o==null?void 0:o.WeekNumber)!==null&&n!==void 0?n:PXs,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})},s4s(h))})]})}function Yxt(s,t,n){for(var r=n!=null&&n.ISOWeek?OIt(t):mMe(t,n),a=n!=null&&n.ISOWeek?nE(s):c1(s,n),i=nv(r,a),l=[],o=0;o<=i;o++)l.push(jh(a,o));var c=l.reduce(function(d,u){var h=n!=null&&n.ISOWeek?vXe(u):_Xe(u,n),m=d.find(function(p){return p.weekNumber===h});return m?(m.dates.push(u),d):(d.push({weekNumber:h,dates:[u]}),d)},[]);return c}function IXs(s,t){var n=Yxt(Bh(s),u_(s),t);if(t!=null&&t.useFixedWeeks){var r=r4s(s,t);if(r<6){var a=n[n.length-1],i=a.dates[a.dates.length-1],l=qD(i,6-r),o=Yxt(qD(i,1),l,t);n.push.apply(n,o)}}return n}function RXs(s){var t,n,r,a=Fm(),i=a.locale,l=a.classNames,o=a.styles,c=a.hideHead,d=a.fixedWeeks,u=a.components,h=a.weekStartsOn,m=a.firstWeekContainsDate,p=a.ISOWeek,f=IXs(s.displayMonth,{useFixedWeeks:!!d,ISOWeek:p,locale:i,weekStartsOn:h,firstWeekContainsDate:m}),x=(t=u==null?void 0:u.Head)!==null&&t!==void 0?t:ZZs,y=(n=u==null?void 0:u.Row)!==null&&n!==void 0?n:LXs,v=(r=u==null?void 0:u.Footer)!==null&&r!==void 0?r:WZs;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:f.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 DXs(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var OXs=DXs()?j.useLayoutEffect:j.useEffect,FFe=!1,FXs=0;function Zxt(){return"react-day-picker-".concat(++FXs)}function zXs(s){var t,n=s??(FFe?Zxt():null),r=j.useState(n),a=r[0],i=r[1];return OXs(function(){a===null&&i(Zxt())},[]),j.useEffect(function(){FFe===!1&&(FFe=!0)},[]),(t=s??a)!==null&&t!==void 0?t:void 0}function BXs(s){var t,n,r=Fm(),a=r.dir,i=r.classNames,l=r.styles,o=r.components,c=vre().displayMonths,d=zXs(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,p=s.displayIndex===0,f=s.displayIndex===c.length-1,x=!p&&!f;a==="rtl"&&(t=[p,f],f=t[0],p=t[1]),p&&(h.push(i.caption_start),m=Ul(Ul({},m),l.caption_start)),f&&(h.push(i.caption_end),m=Ul(Ul({},m),l.caption_end)),x&&(h.push(i.caption_between),m=Ul(Ul({},m),l.caption_between));var y=(n=o==null?void 0:o.Caption)!==null&&n!==void 0?n:GZs;return e.jsxs("div",{className:h.join(" "),style:m,children:[e.jsx(y,{id:d,displayMonth:s.displayMonth,displayIndex:s.displayIndex}),e.jsx(RXs,{id:u,"aria-labelledby":d,displayMonth:s.displayMonth})]},s.displayIndex)}function UXs(s){var t=Fm(),n=t.classNames,r=t.styles;return e.jsx("div",{className:n.months,style:r.months,children:s.children})}function qXs(s){var t,n,r=s.initialProps,a=Fm(),i=KJe(),l=vre(),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=Ul(Ul({},a.styles.root),a.style),m=Object.keys(r).filter(function(f){return f.startsWith("data-")}).reduce(function(f,x){var y;return Ul(Ul({},f),(y={},y[x]=r[x],y))},{}),p=(n=(t=r.components)===null||t===void 0?void 0:t.Months)!==null&&n!==void 0?n:UXs;return e.jsx("div",Ul({className:u.join(" "),style:h,dir:a.dir,id:a.id,nonce:r.nonce,title:r.title,lang:r.lang},m,{children:e.jsx(p,{children:l.displayMonths.map(function(f,x){return e.jsx(BXs,{displayIndex:x,displayMonth:f},x)})})}))}function $Xs(s){var t=s.children,n=mZs(s,["children"]);return e.jsx(PZs,{initialProps:n,children:e.jsx(qZs,{children:e.jsx(jXs,{initialProps:n,children:e.jsx(QZs,{initialProps:n,children:e.jsx(tXs,{initialProps:n,children:e.jsx(cXs,{children:e.jsx(_Xs,{children:t})})})})})})})}function VXs(s){return e.jsx($Xs,Ul({},s,{children:e.jsx(qXs,{initialProps:s})}))}function yj({className:s,classNames:t,showOutsideDays:n=!0,...r}){return e.jsx(VXs,{showOutsideDays:n,className:Mt("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:Mt(TV({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:Mt(TV({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(rd,{className:"h-4 w-4"}),IconRight:({...a})=>e.jsx(gi,{className:"h-4 w-4"})},...r})}yj.displayName="Calendar";var IPe="Popover",[mBt,Vgr]=Up(IPe,[o3]),bre=o3(),[HXs,ZP]=mBt(IPe),pBt=s=>{const{__scopePopover:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!1}=s,o=bre(t),c=j.useRef(null),[d,u]=j.useState(!1),[h,m]=Sx({prop:r,defaultProp:a??!1,onChange:i,caller:IPe});return e.jsx(Pne,{...o,children:e.jsx(HXs,{scope:t,contentId:jx(),triggerRef:c,open:h,onOpenChange:m,onOpenToggle:j.useCallback(()=>m(p=>!p),[m]),hasCustomAnchor:d,onCustomAnchorAdd:j.useCallback(()=>u(!0),[]),onCustomAnchorRemove:j.useCallback(()=>u(!1),[]),modal:l,children:n})})};pBt.displayName=IPe;var fBt="PopoverAnchor",GXs=j.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=ZP(fBt,n),i=bre(n),{onCustomAnchorAdd:l,onCustomAnchorRemove:o}=a;return j.useEffect(()=>(l(),()=>o()),[l,o]),e.jsx(lG,{...i,...r,ref:t})});GXs.displayName=fBt;var gBt="PopoverTrigger",xBt=j.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=ZP(gBt,n),i=bre(n),l=Uo(t,a.triggerRef),o=e.jsx(si.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":wBt(a.open),...r,ref:l,onClick:va(s.onClick,a.onOpenToggle)});return a.hasCustomAnchor?o:e.jsx(lG,{asChild:!0,...i,children:o})});xBt.displayName=gBt;var ZJe="PopoverPortal",[WXs,KXs]=mBt(ZJe,{forceMount:void 0}),yBt=s=>{const{__scopePopover:t,forceMount:n,children:r,container:a}=s,i=ZP(ZJe,t);return e.jsx(WXs,{scope:t,forceMount:n,children:e.jsx(Xg,{present:n||i.open,children:e.jsx(sG,{asChild:!0,container:a,children:r})})})};yBt.displayName=ZJe;var QV="PopoverContent",vBt=j.forwardRef((s,t)=>{const n=KXs(QV,s.__scopePopover),{forceMount:r=n.forceMount,...a}=s,i=ZP(QV,s.__scopePopover);return e.jsx(Xg,{present:r||i.open,children:i.modal?e.jsx(ZXs,{...a,ref:t}):e.jsx(XXs,{...a,ref:t})})});vBt.displayName=QV;var YXs=rP("PopoverContent.RemoveScroll"),ZXs=j.forwardRef((s,t)=>{const n=ZP(QV,s.__scopePopover),r=j.useRef(null),a=Uo(t,r),i=j.useRef(!1);return j.useEffect(()=>{const l=r.current;if(l)return j6e(l)},[]),e.jsx(Sne,{as:YXs,allowPinchZoom:!0,children:e.jsx(bBt,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:va(s.onCloseAutoFocus,l=>{var o;l.preventDefault(),i.current||(o=n.triggerRef.current)==null||o.focus()}),onPointerDownOutside:va(s.onPointerDownOutside,l=>{const o=l.detail.originalEvent,c=o.button===0&&o.ctrlKey===!0,d=o.button===2||c;i.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:va(s.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1})})})}),XXs=j.forwardRef((s,t)=>{const n=ZP(QV,s.__scopePopover),r=j.useRef(!1),a=j.useRef(!1);return e.jsx(bBt,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var l,o;(l=s.onCloseAutoFocus)==null||l.call(s,i),i.defaultPrevented||(r.current||(o=n.triggerRef.current)==null||o.focus(),i.preventDefault()),r.current=!1,a.current=!1},onInteractOutside:i=>{var c,d;(c=s.onInteractOutside)==null||c.call(s,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const l=i.target;((d=n.triggerRef.current)==null?void 0:d.contains(l))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&a.current&&i.preventDefault()}})}),bBt=j.forwardRef((s,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:i,disableOutsidePointerEvents:l,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onInteractOutside:u,...h}=s,m=ZP(QV,n),p=bre(n);return _6e(),e.jsx(kne,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(IP,{asChild:!0,disableOutsidePointerEvents:l,onInteractOutside:u,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onDismiss:()=>m.onOpenChange(!1),children:e.jsx(Lne,{"data-state":wBt(m.open),role:"dialog",id:m.contentId,...p,...h,ref:t,style:{...h.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)"}})})})}),_Bt="PopoverClose",QXs=j.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=ZP(_Bt,n);return e.jsx(si.button,{type:"button",...r,ref:t,onClick:va(s.onClick,()=>a.onOpenChange(!1))})});QXs.displayName=_Bt;var JXs="PopoverArrow",eQs=j.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=bre(n);return e.jsx(Ine,{...a,...r,ref:t})});eQs.displayName=JXs;function wBt(s){return s?"open":"closed"}var tQs=pBt,sQs=xBt,nQs=yBt,jBt=vBt;const md=tQs,pd=sQs,id=j.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(nQs,{children:e.jsx(jBt,{ref:a,align:t,sideOffset:n,className:Mt("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})}));id.displayName=jBt.displayName;async function Pee(s){if(s instanceof Rne)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 rQs=u9("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"}}),Lee=j.forwardRef(({className:s,variant:t,...n},r)=>e.jsx("div",{ref:r,role:"alert",className:Mt(rQs({variant:t}),s),...n}));Lee.displayName="Alert";const aQs=j.forwardRef(({className:s,...t},n)=>e.jsx("h5",{ref:n,className:Mt("mb-1 font-medium leading-none tracking-tight",s),...t}));aQs.displayName="AlertTitle";const Iee=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Mt("text-sm [&_p]:leading-relaxed",s),...t}));Iee.displayName="AlertDescription";function iQs({open:s,onOpenChange:t,imageUrl:n,imageId:r,defaultCaption:a="",swagItemId:i,reelId:l}){const o=Qt(),{user:c}=vs(),d=(c==null?void 0:c.id)??null,[u,h]=j.useState(a),[m,p]=j.useState([]),[f,x]=j.useState(null),[y,v]=j.useState("now"),[b,N]=j.useState(Zht(nmt(new Date),1)),[S,A]=j.useState("12"),[T,L]=j.useState("00"),[M,I]=j.useState("PM");j.useEffect(()=>{if(s){h(a),v("now"),p([]);const be=Zht(nmt(new Date),1);N(be);const he=be.getHours();A(String(he>12?he-12:he===0?12:he)),L("00"),I(he>=12?"PM":"AM")}},[s,a]);const R=()=>{if(!b)return null;let be=parseInt(S);const he=parseInt(T);return M==="PM"&&be!==12&&(be+=12),M==="AM"&&be===12&&(be=0),WIt(GIt(b,be),he)},{data:z,isLoading:$}=ct({queryKey:["social-accounts-for-post",d],queryFn:async()=>{const{data:{user:be}}=await q.auth.getUser();if(!be)return[];const{data:he,error:ge}=await q.from("social_accounts").select("*").eq("user_id",be.id).eq("is_active",!0).order("platform",{ascending:!0});if(ge)throw ge;return console.log("Fetched social accounts for posting:",he),he},enabled:s,staleTime:0}),H=yt({mutationFn:async({accountId:be,platform:he})=>{x(be);const{data:ge,error:ke}=await q.functions.invoke("social-post",{body:{platform:he,accountId:be,imageUrl:n,caption:u}});if(ke)throw new Error(await Pee(ke));if(ge!=null&&ge.error)throw new Error(ge.error);return ge},onSuccess:be=>{const he=be.platform==="facebook"?"Facebook":be.platform==="instagram"?"Instagram":be.platform==="linkedin"?"LinkedIn":"Google Business";re.success(`Posted to ${he}!`)},onError:be=>{re.error(`Failed to post: ${be.message}`)},onSettled:()=>{x(null)}}),V=yt({mutationFn:async({accountId:be,platform:he,scheduledFor:ge})=>{const{data:{user:ke}}=await q.auth.getUser();if(!ke)throw new Error("Not authenticated");const{error:Te}=await q.from("scheduled_posts").insert({user_id:ke.id,social_account_id:be,platform:he,image_url:n,caption:u,swag_item_id:i||null,reel_id:l||null,scheduled_for:ge.toISOString(),status:"scheduled"});if(Te)throw Te;return{platform:he}},onSuccess:be=>{const he=be.platform==="facebook"?"Facebook":be.platform==="instagram"?"Instagram":"LinkedIn";re.success(`Post scheduled for ${he}!`)},onError:be=>{re.error(`Failed to schedule: ${be.message}`)}}),K=async()=>{if(m.length===0){re.error("Please select at least one account");return}if(y==="schedule"){const be=R();if(!be||be<=new Date){re.error("Please select a future date and time");return}for(const he of m){const ge=z==null?void 0:z.find(ke=>ke.id===he);ge&&await V.mutateAsync({accountId:he,platform:ge.platform,scheduledFor:be})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),re.success(`${m.length} post(s) scheduled for ${Gs(be,"PPp")}`)}else for(const be of m){const he=z==null?void 0:z.find(ge=>ge.id===be);he&&await H.mutateAsync({accountId:be,platform:he.platform})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),h(""),p([]),t(!1)},Z=be=>{p(he=>he.includes(be)?he.filter(ge=>ge!==be):[...he,be])},Q=(z==null?void 0:z.filter(be=>be.platform==="facebook"))||[],le=(z==null?void 0:z.filter(be=>be.platform==="instagram"))||[],ue=(z==null?void 0:z.filter(be=>be.platform==="linkedin"))||[],se=(z==null?void 0:z.filter(be=>be.platform==="google_business"))||[],ne=((z==null?void 0:z.length)||0)>0,ie=H.isPending||V.isPending,ce=Array.from({length:12},(be,he)=>String(he+1)),je=["00","15","30","45"];return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{htmlFor:"caption",children:"Caption"}),e.jsx(Fs,{id:"caption",placeholder:"Write a caption for your post...",value:u,onChange:be=>h(be.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(te,{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:Mt("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:Mt("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(Yr,{className:"h-4 w-4"}),"Schedule for"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(md,{children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{variant:"outline",className:Mt("justify-start text-left font-normal flex-1",!b&&"text-muted-foreground"),children:[e.jsx(pa,{className:"mr-2 h-4 w-4"}),b?Gs(b,"PPP"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(id,{className:"w-auto p-0",align:"start",children:e.jsx(yj,{mode:"single",selected:b,onSelect:N,disabled:be=>bee.jsx(et,{value:be,children:be},be))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(Ns,{value:T,onValueChange:L,children:[e.jsx(ws,{className:"w-[70px]",children:e.jsx(ks,{})}),e.jsx(js,{children:je.map(be=>e.jsx(et,{value:be,children:be},be))})]}),e.jsxs(Ns,{value:M,onValueChange:be=>I(be),children:[e.jsx(ws,{className:"w-[70px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"AM",children:"AM"}),e.jsx(et,{value:"PM",children:"PM"})]})]})]})]}),b&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Post will be published on ",Gs(R()||new Date,"PPP 'at' p")]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(te,{children:"Post to"}),$&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Et,{className:"h-6 w-6 animate-spin"})}),!$&&!ne&&e.jsxs(Lee,{children:[e.jsx(Vo,{className:"h-4 w-4"}),e.jsxs(Iee,{className:"flex flex-col gap-2",children:[e.jsx("span",{children:"No social accounts connected yet."}),e.jsxs(xr,{to:"/social-connections",className:"inline-flex items-center gap-1.5 text-primary hover:underline font-medium",children:[e.jsx(qc,{className:"h-3.5 w-3.5"}),"Connect your Facebook, Instagram & LinkedIn"]})]})]}),Q.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(zp,{className:"h-4 w-4 text-blue-600"})," Facebook"]}),Q.map(be=>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(xi,{checked:m.includes(be.id),onCheckedChange:()=>Z(be.id),disabled:f===be.id}),e.jsxs(Ea,{className:"h-8 w-8",children:[e.jsx(Ci,{src:be.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(zp,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:be.page_name||be.platform_username}),f===be.id&&e.jsx(Et,{className:"h-4 w-4 animate-spin"})]},be.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(gm,{className:"h-4 w-4 text-pink-600"})," Instagram"]}),le.map(be=>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(xi,{checked:m.includes(be.id),onCheckedChange:()=>Z(be.id),disabled:f===be.id}),e.jsxs(Ea,{className:"h-8 w-8",children:[e.jsx(Ci,{src:be.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(gm,{className:"h-4 w-4"})})]}),e.jsxs("span",{className:"flex-1 text-sm font-medium",children:["@",be.platform_username]}),f===be.id&&e.jsx(Et,{className:"h-4 w-4 animate-spin"})]},be.id))]}),ue.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(Gg,{className:"h-4 w-4 text-blue-700"})," LinkedIn"]}),ue.map(be=>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(xi,{checked:m.includes(be.id),onCheckedChange:()=>Z(be.id),disabled:f===be.id}),e.jsxs(Ea,{className:"h-8 w-8",children:[e.jsx(Ci,{src:be.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(Gg,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:be.platform_username}),f===be.id&&e.jsx(Et,{className:"h-4 w-4 animate-spin"})]},be.id))]}),se.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(ni,{className:"h-4 w-4 text-red-600"})," Google Business"]}),se.map(be=>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(xi,{checked:m.includes(be.id),onCheckedChange:()=>Z(be.id),disabled:f===be.id}),e.jsxs(Ea,{className:"h-8 w-8",children:[e.jsx(Ci,{src:be.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(ni,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:be.page_name||be.platform_username}),f===be.id&&e.jsx(Et,{className:"h-4 w-4 animate-spin"})]},be.id))]})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{onClick:K,disabled:m.length===0||ie,className:"gap-2",children:[ie?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):y==="schedule"?e.jsx(pa,{className:"h-4 w-4"}):e.jsx($r,{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 oQs(){const{user:s}=vs(),t=(s==null?void 0:s.id)??null,n=Qt(),[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),[p,f]=j.useState("12"),[x,y]=j.useState("00"),[v,b]=j.useState("PM"),{data:N=[],isLoading:S}=ct({queryKey:["scheduled-posts",t],enabled:!!t,queryFn:async()=>{const{data:se,error:ne}=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(ne)throw ne;return se}}),A=N.filter(se=>{if(i!=="all"&&se.status!==i)return!1;if(r&&se.scheduled_for){const ne=new Date(se.scheduled_for);if(!Hh(ne,r))return!1}return!0}),T=N.filter(se=>se.scheduled_for).map(se=>vf(new Date(se.scheduled_for))),L=yt({mutationFn:async se=>{const{error:ne}=await q.from("scheduled_posts").update({caption:se.caption,scheduled_for:se.scheduled_for}).eq("id",se.id);if(ne)throw ne},onSuccess:()=>{re.success("Post updated!"),n.invalidateQueries({queryKey:["scheduled-posts",t]}),c(null)},onError:se=>{re.error(`Failed to update: ${se.message}`)}}),M=yt({mutationFn:async se=>{const{error:ne}=await q.from("scheduled_posts").update({status:"cancelled"}).eq("id",se);if(ne)throw ne},onSuccess:()=>{re.success("Post cancelled"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:se=>{re.error(`Failed to cancel: ${se.message}`)}}),I=yt({mutationFn:async se=>{const{error:ne}=await q.from("scheduled_posts").delete().eq("id",se);if(ne)throw ne},onSuccess:()=>{re.success("Post deleted"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:se=>{re.error(`Failed to delete: ${se.message}`)}}),R=yt({mutationFn:async se=>{const{data:ne,error:ie}=await q.functions.invoke("social-post",{body:{platform:se.platform,accountId:se.social_account_id,imageUrl:se.image_url,caption:se.caption}});if(ie)throw new Error(await Pee(ie));if(ne!=null&&ne.error)throw new Error(ne.error);return await q.from("scheduled_posts").update({status:"posted",posted_at:new Date().toISOString(),post_id:ne.postId}).eq("id",se.id),ne},onSuccess:se=>{const ne=se.platform==="facebook"?"Facebook":se.platform==="instagram"?"Instagram":"LinkedIn";re.success(`Posted to ${ne}!`),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:se=>{re.error(`Failed to post: ${se.message}`)}}),z=se=>{if(c(se),u(se.caption||""),se.scheduled_for){const ne=new Date(se.scheduled_for);m(ne);const ie=ne.getHours();f(String(ie>12?ie-12:ie===0?12:ie)),y(String(ne.getMinutes()).padStart(2,"0")),b(ie>=12?"PM":"AM")}},$=()=>{if(!o||!h)return;let se=parseInt(p);const ne=parseInt(x);v==="PM"&&se!==12&&(se+=12),v==="AM"&&se===12&&(se=0);const ie=WIt(GIt(h,se),ne);L.mutate({id:o.id,caption:d,scheduled_for:ie.toISOString()})},H=se=>{switch(se){case"facebook":return e.jsx(zp,{className:"h-4 w-4 text-blue-600"});case"instagram":return e.jsx(gm,{className:"h-4 w-4 text-pink-600"});case"linkedin":return e.jsx(Gg,{className:"h-4 w-4 text-blue-700"});default:return null}},V=se=>{switch(se){case"scheduled":return e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Yr,{className:"h-3 w-3"}),"Scheduled"]});case"posted":return e.jsxs(Be,{variant:"default",className:"gap-1 bg-green-600",children:[e.jsx(Yo,{className:"h-3 w-3"}),"Posted"]});case"failed":return e.jsxs(Be,{variant:"destructive",className:"gap-1",children:[e.jsx(ou,{className:"h-3 w-3"}),"Failed"]});case"cancelled":return e.jsxs(Be,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(Vo,{className:"h-3 w-3"}),"Cancelled"]});default:return e.jsx(Be,{variant:"outline",children:se})}},K=Array.from({length:12},(se,ne)=>String(ne+1)),Z=["00","15","30","45"],Q=N.filter(se=>se.status==="scheduled").length,le=N.filter(se=>se.status==="posted").length,ue=N.filter(se=>se.status==="scheduled"&&se.scheduled_for&&a4s(new Date(se.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(we,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:Q}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Scheduled"})]}),e.jsxs(we,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ue}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Upcoming"})]}),e.jsxs(we,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:le}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Posted"})]}),e.jsxs(we,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:N.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(we,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(nc,{className:"h-5 w-5"}),e.jsx("h3",{className:"font-semibold",children:"Calendar"})]}),e.jsx(yj,{mode:"single",selected:r,onSelect:a,className:Mt("pointer-events-auto"),modifiers:{hasPost:T},modifiersStyles:{hasPost:{fontWeight:"bold",backgroundColor:"hsl(var(--primary) / 0.1)",borderRadius:"50%"}}}),r&&e.jsx(U,{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(K2,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:["all","scheduled","posted","failed","cancelled"].map(se=>e.jsx(U,{variant:i===se?"default":"outline",size:"sm",onClick:()=>l(se),className:"capitalize",children:se},se))})]}),S&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Et,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),!S&&A.length===0&&e.jsxs(we,{className:"p-8 text-center",children:[e.jsx(pa,{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 ${Gs(r,"PPP")}`:"Schedule a post from Social Swag to get started!"})]}),e.jsx("div",{className:"space-y-4",children:A.map(se=>{var ne,ie;return e.jsx(we,{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:se.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:[H(se.platform),e.jsx("span",{className:"font-medium",children:((ne=se.social_accounts)==null?void 0:ne.page_name)||((ie=se.social_accounts)==null?void 0:ie.platform_username)||"Unknown"}),V(se.status)]}),e.jsxs("div",{className:"flex items-center gap-1",children:[se.status==="scheduled"&&e.jsxs(wN,{children:[e.jsxs(Bg,{children:[e.jsx(Ug,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>z(se),children:e.jsx(ri,{className:"h-4 w-4"})})}),e.jsx(ng,{children:"Edit post"})]}),e.jsxs(Bg,{children:[e.jsx(Ug,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>R.mutate(se),disabled:R.isPending,children:R.isPending?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx($r,{className:"h-4 w-4"})})}),e.jsx(ng,{children:"Post now"})]}),e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(In,{className:"h-4 w-4"})})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Cancel this scheduled post?"}),e.jsx(Ll,{children:"This will cancel the post. You can delete it entirely or keep it in your history."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Keep"}),e.jsx(_l,{onClick:()=>M.mutate(se.id),className:"bg-amber-600 hover:bg-amber-700",children:"Cancel Post"}),e.jsx(_l,{onClick:()=>I.mutate(se.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]}),(se.status==="posted"||se.status==="cancelled"||se.status==="failed")&&e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(In,{className:"h-4 w-4"})})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Delete this post?"}),e.jsx(Ll,{children:"This will permanently remove this post from your history."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>I.mutate(se.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]})]}),se.caption&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-2",children:se.caption}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Yr,{className:"h-3 w-3"}),se.status==="posted"&&se.posted_at?`Posted ${Gs(new Date(se.posted_at),"PPp")}`:se.scheduled_for?`Scheduled for ${Gs(new Date(se.scheduled_for),"PPp")}`:"Not scheduled"]}),se.status==="failed"&&se.error_message&&e.jsxs("p",{className:"text-xs text-destructive mt-2",children:["Error: ",se.error_message]})]})]})},se.id)})})]})]}),e.jsx(zs,{open:!!o,onOpenChange:se=>!se&&c(null),children:e.jsxs(Ds,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{children:"Caption"}),e.jsx(Fs,{value:d,onChange:se=>u(se.target.value),rows:3})]}),e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg",children:[e.jsx(te,{children:"Schedule for"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(md,{children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{variant:"outline",className:Mt("justify-start text-left font-normal flex-1",!h&&"text-muted-foreground"),children:[e.jsx(pa,{className:"mr-2 h-4 w-4"}),h?Gs(h,"PPP"):"Pick a date"]})}),e.jsx(id,{className:"w-auto p-0",align:"start",children:e.jsx(yj,{mode:"single",selected:h,onSelect:m,disabled:se=>see.jsx(et,{value:se,children:se},se))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(Ns,{value:x,onValueChange:y,children:[e.jsx(ws,{className:"w-[70px]",children:e.jsx(ks,{})}),e.jsx(js,{children:Z.map(se=>e.jsx(et,{value:se,children:se},se))})]}),e.jsxs(Ns,{value:v,onValueChange:se=>b(se),children:[e.jsx(ws,{className:"w-[70px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"AM",children:"AM"}),e.jsx(et,{value:"PM",children:"PM"})]})]})]})]})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>c(null),children:"Cancel"}),e.jsxs(U,{onClick:$,disabled:L.isPending,children:[L.isPending?e.jsx(Et,{className:"h-4 w-4 animate-spin mr-2"}):null,"Save Changes"]})]})]})})]})}function nle(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 NBt={exports:{}};/*! JSZip v3.10.1 - A JavaScript class for generating and reading zip files (c) 2009-2016 Stuart Knightley Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown. JSZip uses the library pako released under the MIT license : https://github.com/nodeca/pako/blob/main/LICENSE */(function(s,t){(function(n){s.exports=n()})(function(){return function n(r,a,i){function l(d,u){if(!a[d]){if(!r[d]){var h=typeof nle=="function"&≰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 p=a[d]={exports:{}};r[d][0].call(p.exports,function(f){var x=r[d][1][f];return l(x||f)},p,p.exports,n,r,a,i)}return a[d].exports}for(var o=typeof nle=="function"&&nle,c=0;c>2,p=(3&d)<<4|u>>4,f=1>6:64,x=2>4,u=(15&m)<<4|(p=o.indexOf(c.charAt(x++)))>>2,h=(3&p)<<6|(f=o.indexOf(c.charAt(x++))),b[y++]=d,p!==64&&(b[y++]=u),f!==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,p,f){this.compressedSize=u,this.uncompressedSize=h,this.crc32=m,this.compression=p,this.compressedContent=f}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 p=l,f=m+h;d^=-1;for(var x=m;x>>8^p[255&(d^u[x])];return-1^d}(0|c,o,o.length,0):function(d,u,h,m){var p=l,f=m+h;d^=-1;for(var x=m;x>>8^p[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(p,f){var x,y="";for(x=0;x>>=8;return y}function l(p,f,x,y,v,b){var N,S,A=p.file,T=p.compression,L=b!==d.utf8encode,M=o.transformTo("string",b(A.name)),I=o.transformTo("string",d.utf8encode(A.name)),R=A.comment,z=o.transformTo("string",b(R)),$=o.transformTo("string",d.utf8encode(R)),H=I.length!==A.name.length,V=$.length!==R.length,K="",Z="",Q="",le=A.dir,ue=A.date,se={crc32:0,compressedSize:0,uncompressedSize:0};f&&!x||(se.crc32=p.crc32,se.compressedSize=p.compressedSize,se.uncompressedSize=p.uncompressedSize);var ne=0;f&&(ne|=8),L||!H&&!V||(ne|=2048);var ie=0,ce=0;le&&(ie|=16),v==="UNIX"?(ce=798,ie|=function(be,he){var ge=be;return be||(ge=he?16893:33204),(65535&ge)<<16}(A.unixPermissions,le)):(ce=20,ie|=function(be){return 63&(be||0)}(A.dosPermissions)),N=ue.getUTCHours(),N<<=6,N|=ue.getUTCMinutes(),N<<=5,N|=ue.getUTCSeconds()/2,S=ue.getUTCFullYear()-1980,S<<=4,S|=ue.getUTCMonth()+1,S<<=5,S|=ue.getUTCDate(),H&&(Z=i(1,1)+i(u(M),4)+I,K+="up"+i(Z.length,2)+Z),V&&(Q=i(1,1)+i(u(z),4)+$,K+="uc"+i(Q.length,2)+Q);var je="";return je+=` \0`,je+=i(ne,2),je+=T.magic,je+=i(N,2),je+=i(S,2),je+=i(se.crc32,4),je+=i(se.compressedSize,4),je+=i(se.uncompressedSize,4),je+=i(M.length,2),je+=i(K.length,2),{fileRecord:h.LOCAL_FILE_HEADER+je+M+K,dirRecord:h.CENTRAL_FILE_HEADER+i(ce,2)+je+i(z.length,2)+"\0\0\0\0"+i(ie,4)+i(y,4)+M+K+z}}var o=n("../utils"),c=n("../stream/GenericWorker"),d=n("../utf8"),u=n("../crc32"),h=n("../signature");function m(p,f,x,y){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=f,this.zipPlatform=x,this.encodeFileName=y,this.streamFiles=p,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(p){var f=p.meta.percent||0,x=this.entriesCount,y=this._sources.length;this.accumulate?this.contentBuffer.push(p):(this.bytesWritten+=p.data.length,c.prototype.push.call(this,{data:p.data,meta:{currentFile:this.currentFile,percent:x?(f+100*(x-y-1))/x:100}}))},m.prototype.openedSource=function(p){this.currentSourceOffset=this.bytesWritten,this.currentFile=p.file.name;var f=this.streamFiles&&!p.file.dir;if(f){var x=l(p,f,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:x.fileRecord,meta:{percent:0}})}else this.accumulate=!0},m.prototype.closedSource=function(p){this.accumulate=!1;var f=this.streamFiles&&!p.file.dir,x=l(p,f,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(x.dirRecord),f)this.push({data:function(y){return h.DATA_DESCRIPTOR+i(y.crc32,4)+i(y.compressedSize,4)+i(y.uncompressedSize,4)}(p),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 p=this.bytesWritten,f=0;f=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(f,x){return new u.Promise(function(y,v){var b=[],N=f._internalType,S=f._outputType,A=f._mimeType;f.on("data",function(T,L){b.push(T),x&&x(L)}).on("error",function(T){b=[],v(T)}).on("end",function(){try{var T=function(L,M,I){switch(L){case"blob":return i.newBlob(i.transformTo("arraybuffer",M),I);case"base64":return c.encode(M);default:return i.transformTo(L,M)}}(S,function(L,M){var I,R=0,z=null,$=0;for(I=0;I"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(p){return l.nodebuffer?o.newBufferFrom(p,"utf-8"):function(f){var x,y,v,b,N,S=f.length,A=0;for(b=0;b>>6:(y<65536?x[N++]=224|y>>>12:(x[N++]=240|y>>>18,x[N++]=128|y>>>12&63),x[N++]=128|y>>>6&63),x[N++]=128|63&y);return x}(p)},a.utf8decode=function(p){return l.nodebuffer?i.transformTo("nodebuffer",p).toString("utf-8"):function(f){var x,y,v,b,N=f.length,S=new Array(2*N);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)}(p=i.transformTo(l.uint8array?"uint8array":"array",p))},i.inherits(h,c),h.prototype.processChunk=function(p){var f=i.transformTo(l.uint8array?"uint8array":"array",p.data);if(this.leftOver&&this.leftOver.length){if(l.uint8array){var x=f;(f=new Uint8Array(x.length+this.leftOver.length)).set(this.leftOver,0),f.set(x,this.leftOver.length)}else f=this.leftOver.concat(f);this.leftOver=null}var y=function(b,N){var S;for((N=N||b.length)>b.length&&(N=b.length),S=N-1;0<=S&&(192&b[S])==128;)S--;return S<0||S===0?N:S+d[b[S]]>N?S:N}(f),v=f;y!==f.length&&(l.uint8array?(v=f.subarray(0,y),this.leftOver=f.subarray(y,f.length)):(v=f.slice(0,y),this.leftOver=f.slice(y,f.length))),this.push({data:a.utf8decode(v),meta:p.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(p){this.push({data:a.utf8encode(p.data),meta:p.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),p==0&&(this.dosPermissions=63&this.externalFileAttributes),p==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var p=i(this.extraFields[1].value);this.uncompressedSize===l.MAX_VALUE_32BITS&&(this.uncompressedSize=p.readInt(8)),this.compressedSize===l.MAX_VALUE_32BITS&&(this.compressedSize=p.readInt(8)),this.localHeaderOffset===l.MAX_VALUE_32BITS&&(this.localHeaderOffset=p.readInt(8)),this.diskNumberStart===l.MAX_VALUE_32BITS&&(this.diskNumberStart=p.readInt(4))}},readExtraFields:function(p){var f,x,y,v=p.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});p.index+4>>6:(p<65536?m[y++]=224|p>>>12:(m[y++]=240|p>>>18,m[y++]=128|p>>>12&63),m[y++]=128|p>>>6&63),m[y++]=128|63&p);return m},a.buf2binstring=function(h){return u(h,h.length)},a.binstring2buf=function(h){for(var m=new i.Buf8(h.length),p=0,f=m.length;p>10&1023,b[f++]=56320|1023&x)}return u(b,f)},a.utf8border=function(h,m){var p;for((m=m||h.length)>h.length&&(m=h.length),p=m-1;0<=p&&(192&h[p])==128;)p--;return p<0||p===0?m:p+c[h[p]]>m?p: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,p=0,f=-2,x=-1,y=4,v=2,b=8,N=9,S=286,A=30,T=19,L=2*S+1,M=15,I=3,R=258,z=R+I+1,$=42,H=113,V=1,K=2,Z=3,Q=4;function le(Ae,Fe){return Ae.msg=u[Fe],Fe}function ue(Ae){return(Ae<<1)-(4Ae.avail_out&&(Ne=Ae.avail_out),Ne!==0&&(l.arraySet(Ae.output,Fe.pending_buf,Fe.pending_out,Ne,Ae.next_out),Ae.next_out+=Ne,Fe.pending_out+=Ne,Ae.total_out+=Ne,Ae.avail_out-=Ne,Fe.pending-=Ne,Fe.pending===0&&(Fe.pending_out=0))}function ie(Ae,Fe){o._tr_flush_block(Ae,0<=Ae.block_start?Ae.block_start:-1,Ae.strstart-Ae.block_start,Fe),Ae.block_start=Ae.strstart,ne(Ae.strm)}function ce(Ae,Fe){Ae.pending_buf[Ae.pending++]=Fe}function je(Ae,Fe){Ae.pending_buf[Ae.pending++]=Fe>>>8&255,Ae.pending_buf[Ae.pending++]=255&Fe}function be(Ae,Fe){var Ne,$e,Ve=Ae.max_chain_length,qe=Ae.strstart,Ze=Ae.prev_length,Ue=Ae.nice_match,Ye=Ae.strstart>Ae.w_size-z?Ae.strstart-(Ae.w_size-z):0,Ge=Ae.window,He=Ae.w_mask,tt=Ae.prev,pt=Ae.strstart+R,ft=Ge[qe+Ze-1],qt=Ge[qe+Ze];Ae.prev_length>=Ae.good_match&&(Ve>>=2),Ue>Ae.lookahead&&(Ue=Ae.lookahead);do if(Ge[(Ne=Fe)+Ze]===qt&&Ge[Ne+Ze-1]===ft&&Ge[Ne]===Ge[qe]&&Ge[++Ne]===Ge[qe+1]){qe+=2,Ne++;do;while(Ge[++qe]===Ge[++Ne]&&Ge[++qe]===Ge[++Ne]&&Ge[++qe]===Ge[++Ne]&&Ge[++qe]===Ge[++Ne]&&Ge[++qe]===Ge[++Ne]&&Ge[++qe]===Ge[++Ne]&&Ge[++qe]===Ge[++Ne]&&Ge[++qe]===Ge[++Ne]&&qeYe&&--Ve!=0);return Ze<=Ae.lookahead?Ze:Ae.lookahead}function he(Ae){var Fe,Ne,$e,Ve,qe,Ze,Ue,Ye,Ge,He,tt=Ae.w_size;do{if(Ve=Ae.window_size-Ae.lookahead-Ae.strstart,Ae.strstart>=tt+(tt-z)){for(l.arraySet(Ae.window,Ae.window,tt,tt,0),Ae.match_start-=tt,Ae.strstart-=tt,Ae.block_start-=tt,Fe=Ne=Ae.hash_size;$e=Ae.head[--Fe],Ae.head[Fe]=tt<=$e?$e-tt:0,--Ne;);for(Fe=Ne=tt;$e=Ae.prev[--Fe],Ae.prev[Fe]=tt<=$e?$e-tt:0,--Ne;);Ve+=tt}if(Ae.strm.avail_in===0)break;if(Ze=Ae.strm,Ue=Ae.window,Ye=Ae.strstart+Ae.lookahead,Ge=Ve,He=void 0,He=Ze.avail_in,Ge=I)for(qe=Ae.strstart-Ae.insert,Ae.ins_h=Ae.window[qe],Ae.ins_h=(Ae.ins_h<=I&&(Ae.ins_h=(Ae.ins_h<=I)if($e=o._tr_tally(Ae,Ae.strstart-Ae.match_start,Ae.match_length-I),Ae.lookahead-=Ae.match_length,Ae.match_length<=Ae.max_lazy_match&&Ae.lookahead>=I){for(Ae.match_length--;Ae.strstart++,Ae.ins_h=(Ae.ins_h<=I&&(Ae.ins_h=(Ae.ins_h<=I&&Ae.match_length<=Ae.prev_length){for(Ve=Ae.strstart+Ae.lookahead-I,$e=o._tr_tally(Ae,Ae.strstart-1-Ae.prev_match,Ae.prev_length-I),Ae.lookahead-=Ae.prev_length-1,Ae.prev_length-=2;++Ae.strstart<=Ve&&(Ae.ins_h=(Ae.ins_h<Ae.pending_buf_size-5&&(Ne=Ae.pending_buf_size-5);;){if(Ae.lookahead<=1){if(he(Ae),Ae.lookahead===0&&Fe===h)return V;if(Ae.lookahead===0)break}Ae.strstart+=Ae.lookahead,Ae.lookahead=0;var $e=Ae.block_start+Ne;if((Ae.strstart===0||Ae.strstart>=$e)&&(Ae.lookahead=Ae.strstart-$e,Ae.strstart=$e,ie(Ae,!1),Ae.strm.avail_out===0)||Ae.strstart-Ae.block_start>=Ae.w_size-z&&(ie(Ae,!1),Ae.strm.avail_out===0))return V}return Ae.insert=0,Fe===m?(ie(Ae,!0),Ae.strm.avail_out===0?Z:Q):(Ae.strstart>Ae.block_start&&(ie(Ae,!1),Ae.strm.avail_out),V)}),new Te(4,4,8,4,ge),new Te(4,5,16,8,ge),new Te(4,6,32,32,ge),new Te(4,4,16,16,ke),new Te(8,16,32,32,ke),new Te(8,16,128,128,ke),new Te(8,32,128,256,ke),new Te(32,128,258,1024,ke),new Te(32,258,258,4096,ke)],a.deflateInit=function(Ae,Fe){return Qe(Ae,Fe,b,15,8,0)},a.deflateInit2=Qe,a.deflateReset=Se,a.deflateResetKeep=Oe,a.deflateSetHeader=function(Ae,Fe){return Ae&&Ae.state?Ae.state.wrap!==2?f:(Ae.state.gzhead=Fe,p):f},a.deflate=function(Ae,Fe){var Ne,$e,Ve,qe;if(!Ae||!Ae.state||5>8&255),ce($e,$e.gzhead.time>>16&255),ce($e,$e.gzhead.time>>24&255),ce($e,$e.level===9?2:2<=$e.strategy||$e.level<2?4:0),ce($e,255&$e.gzhead.os),$e.gzhead.extra&&$e.gzhead.extra.length&&(ce($e,255&$e.gzhead.extra.length),ce($e,$e.gzhead.extra.length>>8&255)),$e.gzhead.hcrc&&(Ae.adler=d(Ae.adler,$e.pending_buf,$e.pending,0)),$e.gzindex=0,$e.status=69):(ce($e,0),ce($e,0),ce($e,0),ce($e,0),ce($e,0),ce($e,$e.level===9?2:2<=$e.strategy||$e.level<2?4:0),ce($e,3),$e.status=H);else{var Ze=b+($e.w_bits-8<<4)<<8;Ze|=(2<=$e.strategy||$e.level<2?0:$e.level<6?1:$e.level===6?2:3)<<6,$e.strstart!==0&&(Ze|=32),Ze+=31-Ze%31,$e.status=H,je($e,Ze),$e.strstart!==0&&(je($e,Ae.adler>>>16),je($e,65535&Ae.adler)),Ae.adler=1}if($e.status===69)if($e.gzhead.extra){for(Ve=$e.pending;$e.gzindex<(65535&$e.gzhead.extra.length)&&($e.pending!==$e.pending_buf_size||($e.gzhead.hcrc&&$e.pending>Ve&&(Ae.adler=d(Ae.adler,$e.pending_buf,$e.pending-Ve,Ve)),ne(Ae),Ve=$e.pending,$e.pending!==$e.pending_buf_size));)ce($e,255&$e.gzhead.extra[$e.gzindex]),$e.gzindex++;$e.gzhead.hcrc&&$e.pending>Ve&&(Ae.adler=d(Ae.adler,$e.pending_buf,$e.pending-Ve,Ve)),$e.gzindex===$e.gzhead.extra.length&&($e.gzindex=0,$e.status=73)}else $e.status=73;if($e.status===73)if($e.gzhead.name){Ve=$e.pending;do{if($e.pending===$e.pending_buf_size&&($e.gzhead.hcrc&&$e.pending>Ve&&(Ae.adler=d(Ae.adler,$e.pending_buf,$e.pending-Ve,Ve)),ne(Ae),Ve=$e.pending,$e.pending===$e.pending_buf_size)){qe=1;break}qe=$e.gzindex<$e.gzhead.name.length?255&$e.gzhead.name.charCodeAt($e.gzindex++):0,ce($e,qe)}while(qe!==0);$e.gzhead.hcrc&&$e.pending>Ve&&(Ae.adler=d(Ae.adler,$e.pending_buf,$e.pending-Ve,Ve)),qe===0&&($e.gzindex=0,$e.status=91)}else $e.status=91;if($e.status===91)if($e.gzhead.comment){Ve=$e.pending;do{if($e.pending===$e.pending_buf_size&&($e.gzhead.hcrc&&$e.pending>Ve&&(Ae.adler=d(Ae.adler,$e.pending_buf,$e.pending-Ve,Ve)),ne(Ae),Ve=$e.pending,$e.pending===$e.pending_buf_size)){qe=1;break}qe=$e.gzindex<$e.gzhead.comment.length?255&$e.gzhead.comment.charCodeAt($e.gzindex++):0,ce($e,qe)}while(qe!==0);$e.gzhead.hcrc&&$e.pending>Ve&&(Ae.adler=d(Ae.adler,$e.pending_buf,$e.pending-Ve,Ve)),qe===0&&($e.status=103)}else $e.status=103;if($e.status===103&&($e.gzhead.hcrc?($e.pending+2>$e.pending_buf_size&&ne(Ae),$e.pending+2<=$e.pending_buf_size&&(ce($e,255&Ae.adler),ce($e,Ae.adler>>8&255),Ae.adler=0,$e.status=H)):$e.status=H),$e.pending!==0){if(ne(Ae),Ae.avail_out===0)return $e.last_flush=-1,p}else if(Ae.avail_in===0&&ue(Fe)<=ue(Ne)&&Fe!==m)return le(Ae,-5);if($e.status===666&&Ae.avail_in!==0)return le(Ae,-5);if(Ae.avail_in!==0||$e.lookahead!==0||Fe!==h&&$e.status!==666){var Ue=$e.strategy===2?function(Ye,Ge){for(var He;;){if(Ye.lookahead===0&&(he(Ye),Ye.lookahead===0)){if(Ge===h)return V;break}if(Ye.match_length=0,He=o._tr_tally(Ye,0,Ye.window[Ye.strstart]),Ye.lookahead--,Ye.strstart++,He&&(ie(Ye,!1),Ye.strm.avail_out===0))return V}return Ye.insert=0,Ge===m?(ie(Ye,!0),Ye.strm.avail_out===0?Z:Q):Ye.last_lit&&(ie(Ye,!1),Ye.strm.avail_out===0)?V:K}($e,Fe):$e.strategy===3?function(Ye,Ge){for(var He,tt,pt,ft,qt=Ye.window;;){if(Ye.lookahead<=R){if(he(Ye),Ye.lookahead<=R&&Ge===h)return V;if(Ye.lookahead===0)break}if(Ye.match_length=0,Ye.lookahead>=I&&0Ye.lookahead&&(Ye.match_length=Ye.lookahead)}if(Ye.match_length>=I?(He=o._tr_tally(Ye,1,Ye.match_length-I),Ye.lookahead-=Ye.match_length,Ye.strstart+=Ye.match_length,Ye.match_length=0):(He=o._tr_tally(Ye,0,Ye.window[Ye.strstart]),Ye.lookahead--,Ye.strstart++),He&&(ie(Ye,!1),Ye.strm.avail_out===0))return V}return Ye.insert=0,Ge===m?(ie(Ye,!0),Ye.strm.avail_out===0?Z:Q):Ye.last_lit&&(ie(Ye,!1),Ye.strm.avail_out===0)?V:K}($e,Fe):i[$e.level].func($e,Fe);if(Ue!==Z&&Ue!==Q||($e.status=666),Ue===V||Ue===Z)return Ae.avail_out===0&&($e.last_flush=-1),p;if(Ue===K&&(Fe===1?o._tr_align($e):Fe!==5&&(o._tr_stored_block($e,0,0,!1),Fe===3&&(se($e.head),$e.lookahead===0&&($e.strstart=0,$e.block_start=0,$e.insert=0))),ne(Ae),Ae.avail_out===0))return $e.last_flush=-1,p}return Fe!==m?p:$e.wrap<=0?1:($e.wrap===2?(ce($e,255&Ae.adler),ce($e,Ae.adler>>8&255),ce($e,Ae.adler>>16&255),ce($e,Ae.adler>>24&255),ce($e,255&Ae.total_in),ce($e,Ae.total_in>>8&255),ce($e,Ae.total_in>>16&255),ce($e,Ae.total_in>>24&255)):(je($e,Ae.adler>>>16),je($e,65535&Ae.adler)),ne(Ae),0<$e.wrap&&($e.wrap=-$e.wrap),$e.pending!==0?p:1)},a.deflateEnd=function(Ae){var Fe;return Ae&&Ae.state?(Fe=Ae.state.status)!==$&&Fe!==69&&Fe!==73&&Fe!==91&&Fe!==103&&Fe!==H&&Fe!==666?le(Ae,f):(Ae.state=null,Fe===H?le(Ae,-3):p):f},a.deflateSetDictionary=function(Ae,Fe){var Ne,$e,Ve,qe,Ze,Ue,Ye,Ge,He=Fe.length;if(!Ae||!Ae.state||(qe=(Ne=Ae.state).wrap)===2||qe===1&&Ne.status!==$||Ne.lookahead)return f;for(qe===1&&(Ae.adler=c(Ae.adler,Fe,He,0)),Ne.wrap=0,He>=Ne.w_size&&(qe===0&&(se(Ne.head),Ne.strstart=0,Ne.block_start=0,Ne.insert=0),Ge=new l.Buf8(Ne.w_size),l.arraySet(Ge,Fe,He-Ne.w_size,Ne.w_size,0),Fe=Ge,He=Ne.w_size),Ze=Ae.avail_in,Ue=Ae.next_in,Ye=Ae.input,Ae.avail_in=He,Ae.next_in=0,Ae.input=Fe,he(Ne);Ne.lookahead>=I;){for($e=Ne.strstart,Ve=Ne.lookahead-(I-1);Ne.ins_h=(Ne.ins_h<>>=I=M>>>24,N-=I,(I=M>>>16&255)===0)K[u++]=65535&M;else{if(!(16&I)){if(!(64&I)){M=S[(65535&M)+(b&(1<>>=I,N-=I),N<15&&(b+=V[c++]<>>=I=M>>>24,N-=I,!(16&(I=M>>>16&255))){if(!(64&I)){M=A[(65535&M)+(b&(1<>>=I,N-=I,(I=u-h)>3,b&=(1<<(N-=R<<3))-1,i.next_in=c,i.next_out=u,i.avail_in=c>>24&255)+($>>>8&65280)+((65280&$)<<8)+((255&$)<<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 N($){var H;return $&&$.state?(H=$.state,$.total_in=$.total_out=H.total=0,$.msg="",H.wrap&&($.adler=1&H.wrap),H.mode=f,H.last=0,H.havedict=0,H.dmax=32768,H.head=null,H.hold=0,H.bits=0,H.lencode=H.lendyn=new i.Buf32(x),H.distcode=H.distdyn=new i.Buf32(y),H.sane=1,H.back=-1,m):p}function S($){var H;return $&&$.state?((H=$.state).wsize=0,H.whave=0,H.wnext=0,N($)):p}function A($,H){var V,K;return $&&$.state?(K=$.state,H<0?(V=0,H=-H):(V=1+(H>>4),H<48&&(H&=15)),H&&(H<8||15=Q.wsize?(i.arraySet(Q.window,H,V-Q.wsize,Q.wsize,0),Q.wnext=0,Q.whave=Q.wsize):(K<(Z=Q.wsize-Q.wnext)&&(Z=K),i.arraySet(Q.window,H,V-K,Z,Q.wnext),(K-=Z)?(i.arraySet(Q.window,H,V-K,K,0),Q.wnext=K,Q.whave=Q.wsize):(Q.wnext+=Z,Q.wnext===Q.wsize&&(Q.wnext=0),Q.whave>>8&255,V.check=o(V.check,qe,2,0),ie=ne=0,V.mode=2;break}if(V.flags=0,V.head&&(V.head.done=!1),!(1&V.wrap)||(((255&ne)<<8)+(ne>>8))%31){$.msg="incorrect header check",V.mode=30;break}if((15&ne)!=8){$.msg="unknown compression method",V.mode=30;break}if(ie-=4,Ae=8+(15&(ne>>>=4)),V.wbits===0)V.wbits=Ae;else if(Ae>V.wbits){$.msg="invalid window size",V.mode=30;break}V.dmax=1<>8&1),512&V.flags&&(qe[0]=255&ne,qe[1]=ne>>>8&255,V.check=o(V.check,qe,2,0)),ie=ne=0,V.mode=3;case 3:for(;ie<32;){if(ue===0)break e;ue--,ne+=K[Q++]<>>8&255,qe[2]=ne>>>16&255,qe[3]=ne>>>24&255,V.check=o(V.check,qe,4,0)),ie=ne=0,V.mode=4;case 4:for(;ie<16;){if(ue===0)break e;ue--,ne+=K[Q++]<>8),512&V.flags&&(qe[0]=255&ne,qe[1]=ne>>>8&255,V.check=o(V.check,qe,2,0)),ie=ne=0,V.mode=5;case 5:if(1024&V.flags){for(;ie<16;){if(ue===0)break e;ue--,ne+=K[Q++]<>>8&255,V.check=o(V.check,qe,2,0)),ie=ne=0}else V.head&&(V.head.extra=null);V.mode=6;case 6:if(1024&V.flags&&(ue<(be=V.length)&&(be=ue),be&&(V.head&&(Ae=V.head.extra_len-V.length,V.head.extra||(V.head.extra=new Array(V.head.extra_len)),i.arraySet(V.head.extra,K,Q,be,Ae)),512&V.flags&&(V.check=o(V.check,K,be,Q)),ue-=be,Q+=be,V.length-=be),V.length))break e;V.length=0,V.mode=7;case 7:if(2048&V.flags){if(ue===0)break e;for(be=0;Ae=K[Q+be++],V.head&&Ae&&V.length<65536&&(V.head.name+=String.fromCharCode(Ae)),Ae&&be>9&1,V.head.done=!0),$.adler=V.check=0,V.mode=12;break;case 10:for(;ie<32;){if(ue===0)break e;ue--,ne+=K[Q++]<>>=7&ie,ie-=7&ie,V.mode=27;break}for(;ie<3;){if(ue===0)break e;ue--,ne+=K[Q++]<>>=1)){case 0:V.mode=14;break;case 1:if(R(V),V.mode=20,H!==6)break;ne>>>=2,ie-=2;break e;case 2:V.mode=17;break;case 3:$.msg="invalid block type",V.mode=30}ne>>>=2,ie-=2;break;case 14:for(ne>>>=7&ie,ie-=7&ie;ie<32;){if(ue===0)break e;ue--,ne+=K[Q++]<>>16^65535)){$.msg="invalid stored block lengths",V.mode=30;break}if(V.length=65535&ne,ie=ne=0,V.mode=15,H===6)break e;case 15:V.mode=16;case 16:if(be=V.length){if(ue>>=5,ie-=5,V.ndist=1+(31&ne),ne>>>=5,ie-=5,V.ncode=4+(15&ne),ne>>>=4,ie-=4,286>>=3,ie-=3}for(;V.have<19;)V.lens[Ze[V.have++]]=0;if(V.lencode=V.lendyn,V.lenbits=7,Ne={bits:V.lenbits},Fe=d(0,V.lens,0,19,V.lencode,0,V.work,Ne),V.lenbits=Ne.bits,Fe){$.msg="invalid code lengths set",V.mode=30;break}V.have=0,V.mode=19;case 19:for(;V.have>>16&255,Me=65535&Ve,!((ke=Ve>>>24)<=ie);){if(ue===0)break e;ue--,ne+=K[Q++]<>>=ke,ie-=ke,V.lens[V.have++]=Me;else{if(Me===16){for($e=ke+2;ie<$e;){if(ue===0)break e;ue--,ne+=K[Q++]<>>=ke,ie-=ke,V.have===0){$.msg="invalid bit length repeat",V.mode=30;break}Ae=V.lens[V.have-1],be=3+(3&ne),ne>>>=2,ie-=2}else if(Me===17){for($e=ke+3;ie<$e;){if(ue===0)break e;ue--,ne+=K[Q++]<>>=ke)),ne>>>=3,ie-=3}else{for($e=ke+7;ie<$e;){if(ue===0)break e;ue--,ne+=K[Q++]<>>=ke)),ne>>>=7,ie-=7}if(V.have+be>V.nlen+V.ndist){$.msg="invalid bit length repeat",V.mode=30;break}for(;be--;)V.lens[V.have++]=Ae}}if(V.mode===30)break;if(V.lens[256]===0){$.msg="invalid code -- missing end-of-block",V.mode=30;break}if(V.lenbits=9,Ne={bits:V.lenbits},Fe=d(u,V.lens,0,V.nlen,V.lencode,0,V.work,Ne),V.lenbits=Ne.bits,Fe){$.msg="invalid literal/lengths set",V.mode=30;break}if(V.distbits=6,V.distcode=V.distdyn,Ne={bits:V.distbits},Fe=d(h,V.lens,V.nlen,V.ndist,V.distcode,0,V.work,Ne),V.distbits=Ne.bits,Fe){$.msg="invalid distances set",V.mode=30;break}if(V.mode=20,H===6)break e;case 20:V.mode=21;case 21:if(6<=ue&&258<=se){$.next_out=le,$.avail_out=se,$.next_in=Q,$.avail_in=ue,V.hold=ne,V.bits=ie,c($,je),le=$.next_out,Z=$.output,se=$.avail_out,Q=$.next_in,K=$.input,ue=$.avail_in,ne=V.hold,ie=V.bits,V.mode===12&&(V.back=-1);break}for(V.back=0;Te=(Ve=V.lencode[ne&(1<>>16&255,Me=65535&Ve,!((ke=Ve>>>24)<=ie);){if(ue===0)break e;ue--,ne+=K[Q++]<>Oe)])>>>16&255,Me=65535&Ve,!(Oe+(ke=Ve>>>24)<=ie);){if(ue===0)break e;ue--,ne+=K[Q++]<>>=Oe,ie-=Oe,V.back+=Oe}if(ne>>>=ke,ie-=ke,V.back+=ke,V.length=Me,Te===0){V.mode=26;break}if(32&Te){V.back=-1,V.mode=12;break}if(64&Te){$.msg="invalid literal/length code",V.mode=30;break}V.extra=15&Te,V.mode=22;case 22:if(V.extra){for($e=V.extra;ie<$e;){if(ue===0)break e;ue--,ne+=K[Q++]<>>=V.extra,ie-=V.extra,V.back+=V.extra}V.was=V.length,V.mode=23;case 23:for(;Te=(Ve=V.distcode[ne&(1<>>16&255,Me=65535&Ve,!((ke=Ve>>>24)<=ie);){if(ue===0)break e;ue--,ne+=K[Q++]<>Oe)])>>>16&255,Me=65535&Ve,!(Oe+(ke=Ve>>>24)<=ie);){if(ue===0)break e;ue--,ne+=K[Q++]<>>=Oe,ie-=Oe,V.back+=Oe}if(ne>>>=ke,ie-=ke,V.back+=ke,64&Te){$.msg="invalid distance code",V.mode=30;break}V.offset=Me,V.extra=15&Te,V.mode=24;case 24:if(V.extra){for($e=V.extra;ie<$e;){if(ue===0)break e;ue--,ne+=K[Q++]<>>=V.extra,ie-=V.extra,V.back+=V.extra}if(V.offset>V.dmax){$.msg="invalid distance too far back",V.mode=30;break}V.mode=25;case 25:if(se===0)break e;if(be=je-se,V.offset>be){if((be=V.offset-be)>V.whave&&V.sane){$.msg="invalid distance too far back",V.mode=30;break}he=be>V.wnext?(be-=V.wnext,V.wsize-be):V.wnext-be,be>V.length&&(be=V.length),ge=V.window}else ge=Z,he=le-V.offset,be=V.length;for(seL?(I=he[ge+y[H]],ie[ce+y[H]]):(I=96,0),b=1<<$-le,V=N=1<>le)+(N-=b)]=M<<24|I<<16|R|0,N!==0;);for(b=1<<$-1;ne&b;)b>>=1;if(b!==0?(ne&=b-1,ne+=b):ne=0,H++,--je[$]==0){if($===K)break;$=h[m+y[H]]}if(Z<$&&(ne&A)!==S){for(le===0&&(le=Z),T+=V,ue=1<<(Q=$-le);Q+le>>7)]}function ce(Ve,qe){Ve.pending_buf[Ve.pending++]=255&qe,Ve.pending_buf[Ve.pending++]=qe>>>8&255}function je(Ve,qe,Ze){Ve.bi_valid>v-Ze?(Ve.bi_buf|=qe<>v-Ve.bi_valid,Ve.bi_valid+=Ze-v):(Ve.bi_buf|=qe<>>=1,Ze<<=1,0<--qe;);return Ze>>>1}function ge(Ve,qe,Ze){var Ue,Ye,Ge=new Array(y+1),He=0;for(Ue=1;Ue<=y;Ue++)Ge[Ue]=He=He+Ze[Ue-1]<<1;for(Ye=0;Ye<=qe;Ye++){var tt=Ve[2*Ye+1];tt!==0&&(Ve[2*Ye]=he(Ge[tt]++,tt))}}function ke(Ve){var qe;for(qe=0;qe>1;1<=Ze;Ze--)Oe(Ve,Ge,Ze);for(Ye=pt;Ze=Ve.heap[1],Ve.heap[1]=Ve.heap[Ve.heap_len--],Oe(Ve,Ge,1),Ue=Ve.heap[1],Ve.heap[--Ve.heap_max]=Ze,Ve.heap[--Ve.heap_max]=Ue,Ge[2*Ye]=Ge[2*Ze]+Ge[2*Ue],Ve.depth[Ye]=(Ve.depth[Ze]>=Ve.depth[Ue]?Ve.depth[Ze]:Ve.depth[Ue])+1,Ge[2*Ze+1]=Ge[2*Ue+1]=Ye,Ve.heap[1]=Ye++,Oe(Ve,Ge,1),2<=Ve.heap_len;);Ve.heap[--Ve.heap_max]=Ve.heap[1],function(qt,Ut){var Wt,us,zt,bt,As,vt,Ws=Ut.dyn_tree,on=Ut.max_code,Ms=Ut.stat_desc.static_tree,dn=Ut.stat_desc.has_stree,rn=Ut.stat_desc.extra_bits,br=Ut.stat_desc.extra_base,Gn=Ut.stat_desc.max_length,On=0;for(bt=0;bt<=y;bt++)qt.bl_count[bt]=0;for(Ws[2*qt.heap[qt.heap_max]+1]=0,Wt=qt.heap_max+1;Wt>=7;Ye>>=1)if(1&ft&&tt.dyn_ltree[2*pt]!==0)return l;if(tt.dyn_ltree[18]!==0||tt.dyn_ltree[20]!==0||tt.dyn_ltree[26]!==0)return o;for(pt=32;pt>>3,(Ge=Ve.static_len+3+7>>>3)<=Ye&&(Ye=Ge)):Ye=Ge=Ze+5,Ze+4<=Ye&&qe!==-1?$e(Ve,qe,Ze,Ue):Ve.strategy===4||Ge===Ye?(je(Ve,2+(Ue?1:0),3),Se(Ve,z,$)):(je(Ve,4+(Ue?1:0),3),function(tt,pt,ft,qt){var Ut;for(je(tt,pt-257,5),je(tt,ft-1,5),je(tt,qt-4,4),Ut=0;Ut>>8&255,Ve.pending_buf[Ve.d_buf+2*Ve.last_lit+1]=255&qe,Ve.pending_buf[Ve.l_buf+Ve.last_lit]=255&Ze,Ve.last_lit++,qe===0?Ve.dyn_ltree[2*Ze]++:(Ve.matches++,qe--,Ve.dyn_ltree[2*(V[Ze]+h+1)]++,Ve.dyn_dtree[2*ie(qe)]++),Ve.last_lit===Ve.lit_bufsize-1},a._tr_align=function(Ve){je(Ve,2,3),be(Ve,N,z),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)}(Ve)}},{"../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,p={},f=!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",N,!1):l.attachEvent("onmessage",N),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),T=0;T"u"?i===void 0?this:i:self)}).call(this,typeof op<"u"?op:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(NBt);var lQs=NBt.exports;const kBt=od(lQs);function zFe(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 SBt=({embedded:s=!1,onCompose:t}={})=>{vs();const[n,r]=j.useState(null),[a,i]=j.useState(null),[l,o]=j.useState("all"),[c,d]=j.useState(new Set),[u,h]=j.useState(!1),[m,p]=j.useState(!1),[f,x]=j.useState("images"),[y,v]=j.useState(null),{data:b=[],isLoading:N}=ct({queryKey:["social-swag-2"],queryFn:async()=>{const{data:ne,error:ie}=await q.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(ie)throw ie;return ne}}),{data:S=[]}=ct({queryKey:["social-swag-2-months"],queryFn:async()=>{const{data:ne,error:ie}=await q.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(ie)throw ie;return ne}}),{data:A=[]}=ct({queryKey:["social-swag-2-reels"],queryFn:async()=>{const{data:ne,error:ie}=await q.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(ie)throw ie;return ne}}),{data:T=[]}=ct({queryKey:["my-social-accounts-count"],queryFn:async()=>{const{data:ne,error:ie}=await q.from("social_accounts").select("id, platform").eq("is_active",!0);if(ie)throw ie;return ne||[]}}),L=T.length>0,M=j.useMemo(()=>l==="all"?null:A.find(ne=>ne.month===l)||null,[l,A]),I=j.useMemo(()=>[...new Set(b.map(ie=>ie.month))].sort((ie,ce)=>ce.localeCompare(ie)),[b]);j.useEffect(()=>{I.length>0&&l==="all"&&o(I[0])},[I,l]);const R=ne=>{try{const ie=NXe(ne,"yyyy-MM",new Date);return Gs(ie,"MMMM yyyy")}catch{return ne}},z=j.useMemo(()=>l==="all"?b:b.filter(ne=>ne.month===l),[l,b]),$=j.useMemo(()=>{var ne;return l==="all"?null:((ne=S.find(ie=>ie.month===l))==null?void 0:ne.canva_link)||null},[l,S]),H=async ne=>{try{await navigator.clipboard.writeText(ne),re.success("Caption copied to clipboard!")}catch{re.error("Failed to copy caption")}},V=async(ne,ie)=>{try{const je=await(await fetch(ne)).blob(),be=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent),he=navigator.canShare&&navigator.canShare({files:[new File([je],"test.jpg",{type:"image/jpeg"})]});if(be&&he){const ge=new File([je],`social-swag-${ie}.jpg`,{type:"image/jpeg"});await navigator.share({files:[ge],title:"Social Swag Image"}),re.success("Image ready to save!")}else{const ge=window.URL.createObjectURL(je),ke=document.createElement("a");ke.href=ge,ke.download=`social-swag-${ie}.jpg`,document.body.appendChild(ke),ke.click(),document.body.removeChild(ke),window.URL.revokeObjectURL(ge),re.success("Image downloaded!")}}catch(ce){ce.name!=="AbortError"&&re.error("Failed to download image")}},K=ne=>{d(ie=>{const ce=new Set(ie);return ce.has(ne)?ce.delete(ne):ce.add(ne),ce})},Z=()=>{d(new Set(z.map(ne=>ne.id)))},Q=()=>{d(new Set),h(!1)},le=async()=>{const ne=z.filter(ie=>c.has(ie.id));if(ne.length===0){re.error("No images selected");return}p(!0),re.info(`Preparing ${ne.length} images for download...`);try{const ie=new kBt,ce=[...ne].sort((ke,Te)=>ke.sort_order-Te.sort_order);for(let ke=0;ke{u?K(ne.id):r(ne)},se=({children:ne})=>s?e.jsx(e.Fragment,{children:ne}):e.jsx(qs,{title:"Social Swag 2.0",children:ne});return e.jsx(se,{children:e.jsxs("div",{className:"space-y-8",children:[!s&&e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-primary via-primary/80 to-info p-8 text-primary-foreground",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmYiIGZpbGwtb3BhY2l0eT0iMC4xIj48cGF0aCBkPSJNMzYgMzRjMC0yIDItNCAyLTRzMiAyIDIgNC0yIDQtMiA0LTItMi0yLTR6Ii8+PC9nPjwvZz48L3N2Zz4=')] opacity-30"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-4",children:[e.jsxs(Be,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(cn,{className:"h-3 w-3 mr-1"}),"New content monthly"]}),e.jsxs(Be,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(pc,{className:"h-3 w-3 mr-1"}),b.length," images"]})]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-3",children:"Social Swag 📸"}),e.jsx("p",{className:"text-lg text-primary-foreground/90 max-w-2xl",children:"Ready-to-post social media images delivered to you monthly. Just download, copy the caption, and share with your audience!"})]})]}),e.jsxs(oa,{defaultValue:"gallery",className:"space-y-6",children:[!s&&e.jsxs(la,{className:"grid w-full max-w-md grid-cols-2",children:[e.jsxs(Kt,{value:"gallery",className:"gap-2",children:[e.jsx(pc,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(Kt,{value:"scheduled",className:"gap-2",children:[e.jsx(nc,{className:"h-4 w-4"}),"Scheduled"]})]}),e.jsxs(Zt,{value:"gallery",className:"space-y-6",children:[L?e.jsx(we,{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(U,{variant:"outline",size:"sm",asChild:!0,className:"gap-2",children:e.jsx(xr,{to:"/mission-control/integrations",children:"Manage Accounts"})})]})})}):e.jsx(we,{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(zp,{className:"h-5 w-5 text-blue-600"})}),e.jsx("div",{className:"p-2 rounded-full bg-pink-500/10",children:e.jsx(gm,{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(U,{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(xr,{to:"/social-connections",children:[e.jsx(ad,{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:I.map(ne=>e.jsx("button",{onClick:()=>o(ne),className:Mt("px-4 py-2 rounded-full text-sm font-medium transition-all",l===ne?"bg-primary text-primary-foreground shadow-sm":"bg-muted text-muted-foreground hover:text-foreground"),children:R(ne)},ne))}),l!=="all"&&($?e.jsxs("a",{href:$,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx("span",{className:"text-base",children:"🎨"}),"Edit ",R(l)," 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 ",R(l)," Images in Canva"]}))]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1 p-1 bg-muted rounded-full",children:[e.jsxs("button",{onClick:()=>{x("images"),Q()},className:Mt("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",f==="images"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(pc,{className:"h-4 w-4"}),"Images"]}),e.jsxs("button",{onClick:()=>{x("reels"),Q()},className:Mt("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",f==="reels"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(Gh,{className:"h-4 w-4"}),"Reels"]})]}),f==="images"&&e.jsx("div",{className:"flex flex-wrap items-center gap-3",children:u?e.jsxs(e.Fragment,{children:[e.jsxs(U,{variant:"outline",size:"sm",onClick:Z,className:"gap-2",children:["Select All (",z.length,")"]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:Q,className:"gap-2",children:[e.jsx(er,{className:"h-4 w-4"}),"Cancel"]}),c.size>0&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(U,{size:"sm",onClick:le,disabled:m,className:"gap-2",children:[e.jsx(pi,{className:"h-4 w-4"}),m?"Downloading...":`Download ${c.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(U,{variant:"outline",size:"sm",onClick:()=>h(!0),className:"gap-2",children:[e.jsx(Xr,{className:"h-4 w-4"}),"Select Images"]})})]}),N&&e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}),!N&&f==="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:z.map(ne=>{const ie=c.has(ne.id);return e.jsx(we,{className:Mt("group cursor-pointer overflow-hidden border-0 shadow-md hover:shadow-xl transition-all duration-300 rounded-2xl",u&&ie&&"ring-2 ring-primary ring-offset-2"),onClick:()=>ue(ne),children:e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden",children:[e.jsx("img",{src:zFe(ne.image_url,400,75),alt:"Social swag",className:"w-full h-full object-cover transition-transform duration-300 group-hover:scale-110",loading:"lazy",decoding:"async"}),ne.post_date&&!u&&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:Gs(new Date(ne.post_date+"T00:00:00"),"MMM d")})}),u&&e.jsx("div",{className:Mt("absolute top-2 right-2 w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all",ie?"bg-primary border-primary text-primary-foreground":"bg-white/80 border-muted-foreground/50"),children:ie&&e.jsx(Xr,{className:"h-4 w-4"})}),!u&&e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/40 transition-colors duration-300 flex items-center justify-center",children:e.jsx("span",{className:"text-white font-medium opacity-0 group-hover:opacity-100 transition-opacity duration-300 bg-primary px-4 py-2 rounded-full text-sm",children:"View Details"})})]})},ne.id)})}),z.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(pc,{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."})]})]}),!N&&f==="reels"&&e.jsx(e.Fragment,{children:M?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(we,{className:"group overflow-hidden rounded-2xl cursor-pointer transition-all duration-300 hover:shadow-xl hover:scale-[1.02]",onClick:()=>i(M),children:e.jsxs("div",{className:"relative aspect-[9/16] overflow-hidden",children:[e.jsx("img",{src:zFe(M.image_url,400,75),alt:"Reel preview",className:"w-full h-full object-cover transition-transform duration-300 group-hover:scale-105",loading:"lazy",decoding:"async"}),e.jsx("div",{className:"absolute top-2 left-2",children:e.jsxs(Be,{variant:"secondary",className:"bg-black/50 text-white border-0 backdrop-blur-sm text-xs",children:[e.jsx(Gh,{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(Gh,{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:!!n,onOpenChange:()=>r(null),children:e.jsx(Ds,{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:n&&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:zFe(n.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(pa,{className:"h-4 w-4"}),Gs(new Date(n.created_at),"MMMM d, yyyy")]}),n.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(pa,{className:"h-3.5 w-3.5"}),"Post on ",Gs(new Date(n.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:n.caption})})]}),e.jsxs("div",{className:"flex flex-col gap-3 mt-6",children:[e.jsxs(U,{onClick:()=>{if(t){t({mediaUrl:n.image_url,mediaType:"image",caption:n.caption,swagItemId:n.id}),r(null);return}v({imageUrl:n.image_url,imageId:n.id,caption:n.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($r,{className:"h-4 w-4"}),"Create Post"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(U,{variant:"outline",onClick:()=>H(n.caption),className:"flex-1 gap-2",children:[e.jsx(Pa,{className:"h-4 w-4"}),"Copy Caption"]}),e.jsxs(U,{variant:"outline",onClick:()=>V(n.image_url,n.id),className:"flex-1 gap-2",children:[e.jsx(pi,{className:"h-4 w-4"}),"Download"]})]})]})]})]})})})}),e.jsx(zs,{open:!!a,onOpenChange:()=>i(null),children:e.jsx(Ds,{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:a&&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:a.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(Gh,{className:"h-4 w-4"}),"Monthly Reel"]}),a.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:a.caption})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-6",children:[a.caption&&e.jsxs(U,{onClick:()=>H(a.caption||""),className:"flex-1 gap-2",children:[e.jsx(Pa,{className:"h-4 w-4"}),"Copy Caption"]}),a.canva_link&&e.jsxs(U,{variant:"outline",onClick:()=>window.open(a.canva_link,"_blank"),className:"flex-1 gap-2",children:[e.jsx(Sr,{className:"h-4 w-4"}),"Open in Canva"]})]})]})]})})})}),e.jsx(iQs,{open:!!y,onOpenChange:ne=>!ne&&v(null),imageUrl:(y==null?void 0:y.imageUrl)||"",imageId:(y==null?void 0:y.imageId)||"",defaultCaption:(y==null?void 0:y.caption)||"",swagItemId:y==null?void 0:y.imageId})]}),e.jsx(Zt,{value:"scheduled",children:e.jsx(oQs,{})})]})]})})},Xxt={facebook:{id:"facebook",label:"Facebook Page",icon:zp,dot:"bg-blue-500",chip:"bg-blue-500/10 text-blue-600 border-blue-500/20",captionLimit:63206,supportsVideo:!0,requiresMedia:!1},instagram:{id:"instagram",label:"Instagram",icon:gm,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:Gg,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:ni,dot:"bg-emerald-600",chip:"bg-emerald-600/10 text-emerald-700 border-emerald-600/20",captionLimit:1500,supportsVideo:!1,requiresMedia:!1}},OA=s=>Xxt[s]??Xxt.facebook,cQs=[{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}],Qxt="agent-uploads",dQs="social-studio",uQs=200*1024*1024,Jxt=s=>typeof s=="number"?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s):"";function hQs({onSelect:s}){const{user:t}=vs(),n=j.useRef(null),[r,a]=j.useState(!1),{data:i=[]}=ct({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=[]}=ct({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=[]}=ct({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>uQs){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=`${dQs}/${t.id}/${crypto.randomUUID()}.${h}`,{error:p}=await q.storage.from(Qxt).upload(m,d,{cacheControl:"3600",upsert:!1,contentType:d.type});if(p)throw p;const{data:f}=q.storage.from(Qxt).getPublicUrl(m),x=f.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(oa,{defaultValue:"upload",className:"space-y-4",children:[e.jsxs(la,{className:"grid grid-cols-3 w-full",children:[e.jsxs(Kt,{value:"upload",className:"gap-2",children:[e.jsx(qa,{className:"h-4 w-4"}),"Upload"]}),e.jsxs(Kt,{value:"swag",className:"gap-2",children:[e.jsx(cn,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(Kt,{value:"listings",className:"gap-2",children:[e.jsx(ra,{className:"h-4 w-4"}),"Listings"]})]}),e.jsxs(Zt,{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(we,{className:"border-dashed border-2",children:e.jsxs(Ie,{className:"p-6 flex flex-col items-center text-center gap-3",children:[e.jsx(pc,{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(U,{onClick:()=>{var d;return(d=n.current)==null?void 0:d.click()},disabled:r,className:"gap-2",children:[r?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(qa,{className:"h-4 w-4"}),r?"Uploading…":"Choose file"]})]})}),i.length>0&&e.jsx(Gi,{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(Be,{className:"absolute bottom-1 left-1 text-[10px]",children:"Video"})]},d.id))})})]}),e.jsx(Zt,{value:"swag",children:e.jsx(Gi,{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(Zt,{value:"listings",children:e.jsx(Gi,{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,p)=>Number(p.is_primary)-Number(m.is_primary)||m.sort_order-p.sort_order),h=[`${d.property_address??""}`.trim(),`${d.city}, ${d.state}`,Jxt(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(we,{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:Jxt(d.price)})]}),e.jsx(Be,{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,p)=>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"})},p))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No photos on this listing yet."})]})},d.id)})]})})})]})}function mQs({platform:s,accountName:t,avatarUrl:n,caption:r,mediaUrl:a,mediaType:i}){const l=OA(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(we,{className:"overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 border-b",children:[e.jsxs(Ea,{className:"h-9 w-9",children:[e.jsx(Ci,{src:n??void 0,alt:t}),e.jsx(Ta,{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(ko,{className:"h-5 w-5"}),e.jsx(vu,{className:"h-5 w-5"}),e.jsx($r,{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(wx,{className:"h-4 w-4"})," Like"]}),e.jsxs("span",{className:"flex items-center gap-1 text-xs",children:[e.jsx(vu,{className:"h-4 w-4"})," Comment"]}),e.jsxs("span",{className:"flex items-center gap-1 text-xs",children:[e.jsx(iQ,{className:"h-4 w-4"})," Share"]})]})]})]})}function CBt(){const{user:s}=vs();return ct({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 pQs(s){const{user:t}=vs();return ct({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 fQs(){const s=Qt();return()=>{s.invalidateQueries({queryKey:["studio-posts"]}),s.invalidateQueries({queryKey:["studio-accounts"]})}}const gQs="America/New_York",ABt="levelup.calendar.timezone";function QF(s){if(!s)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:s}),!0}catch{return!1}}function xQs(){try{const s=localStorage.getItem(ABt);if(QF(s))return s}catch{}return null}let K5e=xQs();function XP(){return K5e||_re()}function e0t(s){K5e=QF(s)?s:_re();try{localStorage.setItem(ABt,K5e)}catch{}return K5e}function _re(){const s=Intl.DateTimeFormat().resolvedOptions().timeZone;return QF(s)?s:gQs}function Ree(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 BFe(s,t=new Date){try{return new Intl.DateTimeFormat("en-US",{timeZone:s,hour:"numeric",minute:"2-digit"}).format(t)}catch{return""}}const EBt=[{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 yQs(){var r;let s=[];try{s=((r=Intl.supportedValuesOf)==null?void 0:r.call(Intl,"timeZone"))||[]}catch{s=[]}const t=EBt.map(a=>a.value),n=s.filter(a=>!t.includes(a));return[...t,...n]}function vQs(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 wre(){const{user:s}=vs(),t=Qt(),n=ct({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&&QF(n.data)&&e0t(n.data)},[n.data]);const r=QF(n.data)?n.data:XP()||_re(),a=yt({mutationFn:async i=>{if(!QF(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:vQs(s.email,s.id),timezone:i,is_active:!1});if(c)throw c}return e0t(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 TBt({open:s,onOpenChange:t}){const{timezone:n,update:r}=wre(),[a,i]=j.useState(n),[l,o]=j.useState("");j.useEffect(()=>{s&&(i(n),o(""))},[s,n]);const c=_re(),d=j.useMemo(()=>{const h=l.trim().toLowerCase();return h?yQs().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(Ds,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Ok,{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:["· ",BFe(a)," ",Ree(a)]})]})]}),c!==a&&e.jsxs(U,{type:"button",variant:"outline",size:"sm",className:"w-full justify-start gap-2",onClick:()=>i(c),children:[e.jsx(ni,{className:"h-4 w-4"}),"Use my device timezone (",c.replace(/_/g," "),")"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-sm font-medium",children:"Common timezones"}),e.jsx("div",{className:"grid gap-1.5",children:EBt.map(h=>e.jsxs("button",{type:"button",onClick:()=>i(h.value),className:Mt("flex items-center justify-between rounded-lg border px-3 py-2 text-left text-sm transition-colors",a===h.value?"border-primary bg-primary/5 font-medium":"hover:bg-muted/60"),children:[e.jsx("span",{children:h.label}),e.jsx(Be,{variant:"secondary",className:"text-[10px]",children:BFe(h.value)})]},h.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"tz-search",className:"text-sm font-medium",children:"Search all timezones"}),e.jsx(xe,{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:Mt("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:BFe(h)})]},h))})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(U,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{onClick:u,disabled:r.isPending||a===n,children:[r.isPending&&e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}),"Save timezone"]})]})]})})}const n4=s=>String(s).padStart(2,"0");function jre(s){return QF(s)?s:XP()}function XJe(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 t0t(s,t){const n=XJe(s,t);return Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second)-s.getTime()}function Y$e(s,t){const n=jre(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-t0t(new Date(u),n));return h=new Date(u-t0t(h,n)),h}function MBt(s,t){const n=jre(t),r=typeof s=="string"?new Date(s):s,a=XJe(r,n);return`${a.year}-${n4(a.month)}-${n4(a.day)}T${n4(a.hour)}:${n4(a.minute)}`}function bQs(s,t){const n=jre(t),r=typeof s=="string"?new Date(s):s,a=XJe(r,n);return`${a.year}-${a.month-1}-${a.day}`}function PBt(s,t,n){const r=typeof s=="string"?new Date(s):s;return new Intl.DateTimeFormat("en-US",{timeZone:jre(t),...n}).format(r)}function LBt(s,t){return PBt(s,t,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"})}function _Qs(s,t){return PBt(s,t,{hour:"numeric",minute:"2-digit"})}function wQs(s,t,n,r){const a=jre(n),i=r&&r.includes("T")?r.split("T")[0]:MBt(new Date,a).split("T")[0];let l=`${i}T${n4(s)}:${n4(t)}`;if(Y$e(l,a).getTime()<=Date.now()){const[o,c,d]=i.split("-").map(Number),u=new Date(Date.UTC(o,c-1,d+1));l=`${u.getUTCFullYear()}-${n4(u.getUTCMonth()+1)}-${n4(u.getUTCDate())}T${n4(s)}:${n4(t)}`}return l}const rle=s=>s.page_name||s.platform_username||OA(s.platform).label;function jQs({seed:s,editingPost:t,onSaved:n,onCancelEdit:r}){const{user:a}=vs(),{data:i=[],isLoading:l}=CBt(),{timezone:o}=wre(),[c,d]=j.useState(!1),u=he=>MBt(he,o),[h,m]=j.useState(""),[p,f]=j.useState(null),[x,y]=j.useState("text"),[v,b]=j.useState("manual"),[N,S]=j.useState([]),[A,T]=j.useState({}),[L,M]=j.useState(!1),[I,R]=j.useState(!1),[z,$]=j.useState(""),[H,V]=j.useState(null);j.useEffect(()=>{s&&(s.mediaUrl&&(f(s.mediaUrl),y(s.mediaType??"image")),s.caption!==void 0&&m(s.caption),s.source&&b(s.source),s.scheduledFor&&(R(!0),$(u(s.scheduledFor))))},[s]),j.useEffect(()=>{var ge;if(!t)return;m(t.caption??""),f(((ge=t.media_urls)==null?void 0:ge[0])??null),y(t.media_type),b(t.source??"manual"),S(t.social_post_targets.map(ke=>ke.social_account_id));const he={};t.social_post_targets.forEach(ke=>{ke.caption_override&&(he[ke.social_account_id]=ke.caption_override)}),T(he),M(Object.keys(he).length>0),t.scheduled_for&&(R(!0),$(u(new Date(t.scheduled_for))))},[t]);const K=j.useMemo(()=>i.filter(he=>N.includes(he.id)),[i,N]),Z=he=>{var ge;return L&&((ge=A[he])!=null&&ge.trim())?A[he]:h},Q=j.useMemo(()=>{const he=[];return K.forEach(ge=>{const ke=OA(ge.platform),Te=Z(ge.id);ke.requiresMedia&&!p&&he.push(`${ke.label} requires a photo or video.`),!ke.supportsVideo&&x==="video"&&he.push(`${ke.label} can't publish video from LevelUp yet.`),Te.length>ke.captionLimit&&he.push(`${ke.label} caption is over the ${ke.captionLimit.toLocaleString()} character limit.`)}),Array.from(new Set(he))},[K,p,x,h,A,L]),le=()=>{m(""),f(null),y("text"),b("manual"),S([]),T({}),M(!1),R(!1),$("")},ue=he=>{f(he.mediaUrl),y(he.mediaType),b(he.source),he.caption&&!h.trim()&&m(he.caption)},se=he=>S(ge=>ge.includes(he)?ge.filter(ke=>ke!==he):[...ge,he]),ne=async he=>{if(a!=null&&a.id){if(he!=="draft"&&N.length===0){re.error("Choose at least one account to post to.");return}if(he!=="draft"&&!h.trim()&&!p){re.error("Add a caption or media before publishing.");return}if(he==="schedule"&&!z){re.error("Pick a date and time to schedule.");return}if(he!=="draft"&&Q.length>0){re.error(Q[0]);return}V(he);try{const ge={user_id:a.id,caption:h.trim()||null,media_type:x,media_urls:p?[p]:[],source:v,status:he==="draft"?"draft":he==="schedule"?"scheduled":"publishing",scheduled_for:he==="schedule"?Y$e(z,o).toISOString():null,timezone:o};let ke=(t==null?void 0:t.id)??null;if(ke){const{error:Te}=await q.from("social_posts").update(ge).eq("id",ke);if(Te)throw Te;await q.from("social_post_targets").delete().eq("post_id",ke)}else{const{data:Te,error:Me}=await q.from("social_posts").insert(ge).select("id").single();if(Me)throw Me;ke=Te.id}if(N.length>0){const Te=K.map(Oe=>{var Se;return{post_id:ke,user_id:a.id,social_account_id:Oe.id,platform:Oe.platform,caption_override:L&&((Se=A[Oe.id])!=null&&Se.trim())?A[Oe.id].trim():null,status:"pending"}}),{error:Me}=await q.from("social_post_targets").insert(Te);if(Me)throw Me}if(he==="now"){const{data:Te,error:Me}=await q.functions.invoke("social-publish-post",{body:{post_id:ke}});if(Me)throw Me;const Oe=Te==null?void 0:Te.status;Oe==="failed"?re.error("Publishing failed. Check the Queue tab for details."):Oe==="partial"?re.warning("Some accounts failed. Check the Queue tab to retry."):re.success("Posted to your accounts.")}else re.success(he==="draft"?"Draft saved":"Post scheduled");t||le(),n==null||n()}catch(ge){console.error(ge),re.error((ge==null?void 0:ge.message)??"Something went wrong saving your post.")}finally{V(null)}}},ie=(he,ge)=>{R(!0),$(wQs(he,ge,o,z))},ce=Ree(o),je=_re(),be=je!==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(Lee,{children:e.jsxs(Iee,{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{children:"Editing a saved post."}),e.jsxs(U,{variant:"ghost",size:"sm",onClick:r,className:"gap-1",children:[e.jsx(er,{className:"h-4 w-4"})," Cancel"]})]})}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsx(It,{className:"text-base",children:"1. Choose your media"})}),e.jsxs(Ie,{className:"space-y-4",children:[p&&e.jsxs("div",{className:"relative w-full max-w-xs overflow-hidden rounded-lg border",children:[x==="video"?e.jsx("video",{src:p,className:"w-full",controls:!0,playsInline:!0}):e.jsx("img",{src:p,alt:"Selected media",className:"w-full object-cover"}),e.jsx(U,{variant:"secondary",size:"icon",className:"absolute top-2 right-2 h-8 w-8",onClick:()=>{f(null),y("text")},children:e.jsx(In,{className:"h-4 w-4"})})]}),e.jsx(hQs,{onSelect:ue})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsx(It,{className:"text-base",children:"2. Write your caption"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx(Fs,{value:h,onChange:he=>m(he.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(te,{htmlFor:"per-platform",className:"text-xs",children:"Customize per platform"}),e.jsx(wn,{id:"per-platform",checked:L,onCheckedChange:M})]})]}),L&&K.length>0&&e.jsxs(oa,{defaultValue:K[0].id,className:"pt-2",children:[e.jsx(la,{className:"flex-wrap h-auto",children:K.map(he=>e.jsx(Kt,{value:he.id,className:"text-xs",children:rle(he)},he.id))}),K.map(he=>e.jsx(Zt,{value:he.id,className:"pt-3",children:e.jsx(Fs,{rows:5,value:A[he.id]??"",placeholder:`Leave blank to use the main caption for ${OA(he.platform).label}`,onChange:ge=>T(ke=>({...ke,[he.id]:ge.target.value}))})},he.id))]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsx(It,{className:"text-base",children:"3. Pick your accounts"})}),e.jsxs(Ie,{className:"space-y-3",children:[l&&e.jsx(Et,{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(he=>{const ge=OA(he.platform),ke=ge.icon,Te=N.includes(he.id);return e.jsxs("button",{type:"button",onClick:()=>se(he.id),className:`flex items-center gap-3 rounded-lg border p-3 text-left transition ${Te?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsxs(Ea,{className:"h-9 w-9",children:[e.jsx(Ci,{src:he.profile_picture_url??void 0}),e.jsx(Ta,{children:rle(he).slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:rle(he)}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ke,{className:"h-3 w-3"})," ",ge.label]})]}),Te&&e.jsx(Xr,{className:"h-4 w-4 text-primary"})]},he.id)})})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsx(It,{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(te,{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(wn,{id:"schedule-toggle",checked:I,onCheckedChange:R})]}),I&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(xe,{type:"datetime-local",value:z,onChange:he=>$(he.target.value)}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Ok,{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"})]}),z&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Goes out ",e.jsx("span",{className:"font-medium text-foreground",children:LBt(Y$e(z,o),o)})]}),be&&e.jsxs("p",{className:"text-xs text-amber-600",children:["Your device is set to ",je.replace(/_/g," ")," — posts still go out on your ",ce||"saved"," schedule."]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:cQs.map(he=>e.jsx(U,{type:"button",variant:"outline",size:"sm",onClick:()=>ie(he.hour,he.minute),children:he.label},he.label))})]}),Q.length>0&&e.jsxs(Lee,{variant:"destructive",children:[e.jsx(tc,{className:"h-4 w-4"}),e.jsx(Iee,{children:e.jsx("ul",{className:"list-disc pl-4 space-y-1",children:Q.map(he=>e.jsx("li",{children:he},he))})})]}),e.jsx(hc,{}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(U,{variant:"outline",onClick:()=>ne("draft"),disabled:!!H,className:"gap-2",children:[H==="draft"?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4"}),"Save draft"]}),I?e.jsxs(U,{onClick:()=>ne("schedule"),disabled:!!H,className:"gap-2",children:[H==="schedule"?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(ch,{className:"h-4 w-4"}),"Schedule post"]}):e.jsxs(U,{onClick:()=>ne("now"),disabled:!!H,className:"gap-2",children:[H==="now"?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx($r,{className:"h-4 w-4"}),"Post now"]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Live preview"}),e.jsxs(Be,{variant:"secondary",children:[K.length," selected"]})]}),K.length===0?e.jsx(we,{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:K.map(he=>e.jsx(mQs,{platform:he.platform,accountName:rle(he),avatarUrl:he.profile_picture_url,caption:Z(he.id),mediaUrl:p,mediaType:x},he.id))})]}),e.jsx(TBt,{open:c,onOpenChange:d})]})}const NQs=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s0t={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 kQs({posts:s,onCreateAt:t,onOpenPost:n}){const{timezone:r}=wre(),a=Ree(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,p)=>{const f=new Date(h);return f.setDate(h.getDate()+p),f})},[i]),c=j.useMemo(()=>{const h=new Map;return s.forEach(m=>{const p=m.scheduled_for??m.published_at;if(!p)return;const f=bQs(p,r);h.set(f,[...h.get(f)??[],m])}),h},[s,r]),d=new Date,u=h=>h.toDateString()===d.toDateString();return e.jsx(we,{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(U,{variant:"outline",size:"sm",onClick:()=>l(new Date(d.getFullYear(),d.getMonth(),1)),children:"Today"}),e.jsx(U,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>l(new Date(i.getFullYear(),i.getMonth()-1,1)),children:e.jsx(rd,{className:"h-4 w-4"})}),e.jsx(U,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>l(new Date(i.getFullYear(),i.getMonth()+1,1)),children:e.jsx(gi,{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:NQs.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()}`,p=c.get(m)??[],f=h.getMonth()!==i.getMonth();return e.jsxs("div",{className:`group relative min-h-[104px] bg-background p-1.5 ${f?"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(an,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"mt-1 space-y-1",children:[p.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 ${s0t[x.status]??s0t.draft}`,children:[e.jsx("span",{className:"font-medium",children:_Qs(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 ${OA(b.platform).dot}`},b.id))})]},x.id)}),p.length>3&&e.jsxs(Be,{variant:"secondary",className:"text-[10px]",children:["+",p.length-3," more"]})]})]},m)})})]})})}const SQs=s=>{switch(s){case"published":case"success":return{label:"Published",variant:"default",icon:zr};case"partial":return{label:"Partly published",variant:"secondary",icon:tc};case"failed":return{label:"Failed",variant:"destructive",icon:tc};case"publishing":case"pending":return{label:"Publishing",variant:"secondary",icon:Et};case"scheduled":return{label:"Scheduled",variant:"outline",icon:ch};default:return{label:"Draft",variant:"outline",icon:ri}}};function n0t({posts:s,accounts:t,onEdit:n,onChanged:r,emptyLabel:a}){const[i,l]=j.useState(null),{timezone:o}=wre(),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:p}=await q.functions.invoke("social-publish-post",{body:{post_id:h.id}});if(p)throw p;const f=m==null?void 0:m.status;f==="failed"?re.error("Publishing failed. See the error details below."):f==="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(we,{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 p=h.status==="failed"&&!!((y=h.error_message)!=null&&y.startsWith("Missed its scheduled time"))?{label:"Didn't send",variant:"destructive",icon:tc}:SQs(h.status),f=p.icon,x=h.scheduled_for??h.published_at??h.created_at;return e.jsx(we,{children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex gap-4",children:[((v=h.media_urls)==null?void 0:v[0])&&(h.media_type==="video"?e.jsx("video",{src:h.media_urls[0],className:"h-20 w-20 rounded-lg object-cover shrink-0"}):e.jsx("img",{src:h.media_urls[0],alt:"",loading:"lazy",className:"h-20 w-20 rounded-lg object-cover shrink-0"})),e.jsxs("div",{className:"min-w-0 flex-1 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Be,{variant:p.variant,className:"gap-1",children:[e.jsx(f,{className:`h-3 w-3 ${p.label==="Publishing"?"animate-spin":""}`}),p.label]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:LBt(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 N=OA(b.platform),S=N.icon,A=c(b.social_account_id),T=b.status==="published",L=b.status==="failed";return e.jsxs("div",{className:`flex items-center gap-2 rounded-full border px-2.5 py-1 text-xs ${L?"border-destructive/30 bg-destructive/5 text-destructive":N.chip}`,children:[e.jsxs(Ea,{className:"h-4 w-4",children:[e.jsx(Ci,{src:(A==null?void 0:A.profile_picture_url)??void 0}),e.jsx(Ta,{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)||N.label}),T&&b.permalink&&e.jsx("a",{href:b.permalink,target:"_blank",rel:"noopener noreferrer","aria-label":"View post",children:e.jsx(Sr,{className:"h-3 w-3"})}),L&&e.jsx(tc,{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:[OA(b.platform).label,":"]})," ",b.error_message||"Publishing failed."]},b.id))})]}),e.jsxs("div",{className:"flex flex-col gap-2 shrink-0",children:[e.jsxs(U,{variant:"outline",size:"sm",className:"gap-1",onClick:()=>n(h),children:[e.jsx(ri,{className:"h-3.5 w-3.5"})," Edit"]}),h.status!=="published"&&e.jsxs(U,{size:"sm",className:"gap-1",disabled:i===h.id,onClick:()=>d(h),children:[i===h.id?e.jsx(Et,{className:"h-3.5 w-3.5 animate-spin"}):h.status==="failed"||h.status==="partial"?e.jsx(no,{className:"h-3.5 w-3.5"}):e.jsx($r,{className:"h-3.5 w-3.5"}),h.status==="failed"||h.status==="partial"?"Retry":"Post now"]}),e.jsxs(U,{variant:"ghost",size:"sm",className:"gap-1 text-muted-foreground",disabled:i===h.id,onClick:()=>u(h),children:[e.jsx(In,{className:"h-3.5 w-3.5"})," Delete"]})]})]})})},h.id)})})}const CQs=()=>{const[s,t]=j.useState("compose"),[n,r]=j.useState(null),[a,i]=j.useState(null),{data:l=[]}=CBt(),{data:o=[],isLoading:c}=pQs(),d=fQs(),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,p=(x,y=null)=>{r(x),i(y),t("compose")},f=x=>{p({mediaUrl:x.mediaUrl,mediaType:x.mediaType,caption:x.caption,source:"swag",sourceRef:x.swagItemId??x.reelId})};return e.jsx(qs,{title:"Social Studio",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(we,{className:"overflow-hidden border-none bg-gradient-to-br from-primary/10 via-background to-background",children:e.jsxs(Ie,{className:"p-6 flex flex-col gap-5 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(cn,{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(Ea,{className:"h-8 w-8 border-2 border-background",title:x.page_name??x.platform,children:[e.jsx(Ci,{src:x.profile_picture_url??void 0}),e.jsx(Ta,{className:"text-[10px]",children:OA(x.platform).label.slice(0,2)})]},x.id))}),e.jsx(U,{variant:"outline",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(xr,{to:"/social-connections",children:[e.jsx(R4,{className:"h-4 w-4"})," Manage accounts"]})})]}),e.jsxs(U,{className:"gap-2",onClick:()=>p(null),children:[e.jsx(sp,{className:"h-4 w-4"})," New post"]})]})]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:[{label:"Connected accounts",value:l.length,icon:L4},{label:"Scheduled & drafts",value:u.length,icon:nc},{label:"Published",value:h.filter(x=>x.status==="published").length,icon:zr}].map(({label:x,value:y,icon:v})=>e.jsx(we,{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(oa,{value:s,onValueChange:t,className:"space-y-6",children:[e.jsxs(la,{className:"flex-wrap h-auto",children:[e.jsxs(Kt,{value:"compose",className:"gap-2",children:[e.jsx(sp,{className:"h-4 w-4"}),"Compose"]}),e.jsxs(Kt,{value:"calendar",className:"gap-2",children:[e.jsx(nc,{className:"h-4 w-4"}),"Calendar"]}),e.jsxs(Kt,{value:"queue",className:"gap-2",children:[e.jsx($r,{className:"h-4 w-4"}),"Queue",u.length>0&&e.jsx(Be,{variant:"secondary",className:"ml-1",children:u.length})]}),e.jsxs(Kt,{value:"history",className:"gap-2",children:[e.jsx(zr,{className:"h-4 w-4"}),"History",m>0&&e.jsx(Be,{variant:"destructive",className:"ml-1",children:m})]}),e.jsxs(Kt,{value:"gallery",className:"gap-2",children:[e.jsx(cn,{className:"h-4 w-4"}),"Swag gallery"]})]}),e.jsx(Zt,{value:"compose",children:e.jsx(jQs,{seed:n,editingPost:a,onSaved:()=>{d(),i(null),r(null)},onCancelEdit:()=>{i(null),r(null)}})}),e.jsx(Zt,{value:"calendar",children:e.jsx(kQs,{posts:o,onCreateAt:x=>p({scheduledFor:x}),onOpenPost:x=>p(null,x)})}),e.jsx(Zt,{value:"queue",children:e.jsx(n0t,{posts:u,accounts:l,onEdit:x=>p(null,x),onChanged:d,emptyLabel:c?"Loading your posts…":"Nothing scheduled yet. Compose a post to get started."})}),e.jsx(Zt,{value:"history",children:e.jsx(n0t,{posts:h,accounts:l,onEdit:x=>p(null,x),onChanged:d,emptyLabel:"Your published posts will show up here."})}),e.jsx(Zt,{value:"gallery",children:e.jsx(SBt,{embedded:!0,onCompose:f})})]})]})})},AQs=[{id:"branding-bar",title:"Branding Bar Studio",description:"Drop in any image — get a branded version with your headshot, logo, and contact info.",icon:pc,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:ra,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:So,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:Cl,comingSoon:!0,color:"from-orange-500 to-red-500"},{id:"milestones",title:"Client Milestones",description:"Closing day, home anniversaries, birthdays, referral thank-yous.",icon:lg,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:$w,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:EA,comingSoon:!0,color:"from-amber-500 to-yellow-500"}];function EQs(){return e.jsx(qs,{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(Be,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(cn,{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(U,{variant:"outline",asChild:!0,children:e.jsxs(xr,{to:"/marketing-studio/brand-kit",children:[e.jsx($c,{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:AQs.map(s=>{const t=s.icon,n=e.jsxs(we,{className:`group relative overflow-hidden transition-all h-full ${s.comingSoon?"opacity-70":"hover:shadow-xl hover:-translate-y-0.5 cursor-pointer"}`,children:[e.jsx("div",{className:`absolute inset-x-0 top-0 h-1 bg-gradient-to-r ${s.color}`}),e.jsxs(Ie,{className:"p-5 space-y-3",children:[e.jsx("div",{className:`inline-flex h-10 w-10 items-center justify-center rounded-lg bg-gradient-to-br ${s.color} text-white shadow-md`,children:e.jsx(t,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold",children:s.title}),s.comingSoon&&e.jsx(Be,{variant:"outline",className:"text-[10px]",children:"Coming soon"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:s.description})]})]})]});return s.to&&!s.comingSoon?e.jsx(xr,{to:s.to,className:"block",children:n},s.id):e.jsx("div",{children:n},s.id)})})]})})}function Nre(){const s=Sa();return ct({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 TQs(){const{data:s,...t}=Nre();return{data:(s==null?void 0:s.find(n=>n.is_default))??(s==null?void 0:s[0])??null,...t}}function MQs(){const s=Sa(),t=Qt();return yt({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 PQs(){const s=Sa(),t=Qt();return yt({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 LQs(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 IQs({preset:s,onSaved:t,onCancel:n}){var x;const r=Sa(),a=MQs(),i=PQs(),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 ui(async()=>{const{supabase:b}=await Promise.resolve().then(()=>P1s);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 LQs(r,v,y);h(N=>({...N,[y==="headshot"?"headshot_url":"brokerage_logo_url"]:b}))}catch(b){re.error(b.message||"Upload failed")}finally{d(null)}}},p=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")}},f=async()=>{s!=null&&s.id&&await Yi("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(te,{children:"Preset name"}),e.jsx(xe,{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(wn,{checked:u.is_default,onCheckedChange:y=>h({...u,is_default:y})}),e.jsx(te,{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(te,{children:"Display name"}),e.jsx(xe,{value:u.display_name,onChange:y=>h({...u,display_name:y.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Phone"}),e.jsx(xe,{value:u.phone,onChange:y=>h({...u,phone:y.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Email"}),e.jsx(xe,{value:u.email,onChange:y=>h({...u,email:y.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{children:"License #"}),e.jsx(xe,{value:u.license_number,onChange:y=>h({...u,license_number:y.target.value})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(te,{children:"Tagline"}),e.jsx(xe,{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(te,{children:"Website"}),e.jsx(xe,{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(te,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Ea,{className:"h-16 w-16",children:[e.jsx(Ci,{src:u.headshot_url||void 0}),e.jsx(Ta,{children:((x=u.display_name)==null?void 0:x[0])??"A"})]}),e.jsxs(U,{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(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(qa,{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(te,{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(U,{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(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(qa,{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(te,{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(xe,{value:u.brand_color,onChange:y=>h({...u,brand_color:y.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(te,{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(xe,{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(U,{variant:"ghost",size:"sm",onClick:f,className:"text-destructive",children:[e.jsx(In,{className:"h-4 w-4 mr-1"})," Delete"]})}),e.jsxs("div",{className:"flex gap-2",children:[n&&e.jsx(U,{variant:"outline",onClick:n,children:"Cancel"}),e.jsxs(U,{onClick:p,disabled:a.isPending,children:[a.isPending&&e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}),"Save preset"]})]})]})]})}function RQs(){const{data:s,isLoading:t}=Nre(),[n,r]=j.useState(null);return e.jsx(qs,{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(xr,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(Aa,{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(U,{onClick:()=>r("new"),className:"w-full sm:w-auto",children:[e.jsx(an,{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(we,{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(U,{onClick:()=>r("new"),children:[e.jsx(an,{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(we,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-3",style:{background:`linear-gradient(90deg, ${a.brand_color}, ${a.accent_color})`}}),e.jsxs(Tt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(It,{className:"text-lg flex items-center gap-2",children:[a.name,a.is_default&&e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Ua,{className:"h-3 w-3"})," Default"]})]}),e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>r(a),children:e.jsx(ri,{className:"h-4 w-4"})})]}),e.jsx(Jn,{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(Ds,{className:"max-w-2xl max-h-[90vh] overflow-y-auto w-[calc(100vw-2rem)] sm:w-full",children:[e.jsx(Vs,{children:e.jsx($s,{children:n==="new"?"New brand preset":"Edit brand preset"})}),e.jsx(IQs,{preset:n==="new"?null:n,onSaved:()=>r(null),onCancel:()=>r(null)})]})})]})})}const Z$e=[{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"}],DQs=s=>Z$e.find(t=>t.id===s)??Z$e[0];function OQs(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 FQs({value:s,onChange:t,mediaType:n}){const r=Z$e.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:Mt("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(zQs,{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 zQs({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}})]})]})}const BQs=Math.PI/180;function UQs(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const XD=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},fi={_global:XD,version:"10.2.5",isBrowser:UQs(),isUnminified:/param/.test((function(s){}).toString()),dblClickWindow:400,getAngle(s){return fi.angleDeg?s*BQs:s},enableTrace:!1,pointerEventsEnabled:!0,autoDrawEnabled:!0,hitOnDragEnabled:!1,capturePointerEventsEnabled:!1,_mouseListenClick:!1,_touchListenClick:!1,_pointerListenClick:!1,_mouseInDblClickWindow:!1,_touchInDblClickWindow:!1,_pointerInDblClickWindow:!1,_mouseDblClickPointerId:null,_touchDblClickPointerId:null,_pointerDblClickPointerId:null,_renderBackend:"web",legacyTextRendering:!1,pixelRatio:typeof window<"u"&&window.devicePixelRatio||1,dragDistance:3,angleDeg:!0,showWarnings:!0,dragButtons:[0,1],isDragging(){return fi.DD.isDragging},isTransforming(){var s,t;return(t=(s=fi.Transformer)===null||s===void 0?void 0:s.isTransforming())!==null&&t!==void 0?t:!1},isDragReady(){return!!fi.DD.node},releaseCanvasOnDestroy:!0,document:XD.document,_injectGlobal(s){typeof XD.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),XD.Konva=s}},Lf=s=>{fi[s.prototype.getClassName()]=s};fi._injectGlobal(fi);const qQs=`Konva.js unsupported environment. Looks like you are trying to use Konva.js in Node.js environment. because "document" object is undefined. To use Konva.js in Node.js environment, you need to use the "canvas-backend" or "skia-backend" module. bash: npm install canvas js: import "konva/canvas-backend"; or bash: npm install skia-canvas js: import "konva/skia-backend"; `,r0t=()=>{if(typeof document>"u")throw new Error(qQs)};class Bw{constructor(t=[1,0,0,1,0,0]){this.dirty=!1,this.m=t&&t.slice()||[1,0,0,1,0,0]}reset(){this.m[0]=1,this.m[1]=0,this.m[2]=0,this.m[3]=1,this.m[4]=0,this.m[5]=0}copy(){return new Bw(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]}}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}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=(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=(t*r+n*a)/o}return c.rotation=sr._getRotation(c.rotation),c}}const $Qs="[object Array]",VQs="[object Number]",HQs="[object String]",GQs="[object Boolean]",WQs=Math.PI/180,KQs=180/Math.PI,nY="#",YQs="",ZQs="0",XQs="Konva warning: ",a0t="Konva error: ",QQs="rgb(",UFe={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,132,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,255,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,203],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[119,128,144],slategrey:[119,128,144],snow:[255,255,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],transparent:[255,255,255,0],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,5]},JQs=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let ale=[],rY=null;const eJs=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(s){setTimeout(s,16)},sr={_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)===$Qs},_isNumber(s){return Object.prototype.toString.call(s)===VQs&&!isNaN(s)&&isFinite(s)},_isString(s){return Object.prototype.toString.call(s)===HQs},_isBoolean(s){return Object.prototype.toString.call(s)===GQs},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){ale.push(s),ale.length===1&&eJs(function(){const t=ale;ale=[],t.forEach(function(n){n()})})},createCanvasElement(){r0t();const s=document.createElement("canvas");try{s.style=s.style||{}}catch{}return s},createImageElement(){return r0t(),document.createElement("img")},_isInDocument(s){for(;s=s.parentNode;)if(s==document)return!0;return!1},_urlToImage(s,t){const n=sr.createImageElement();n.onload=function(){t(n)},n.src=s},_rgbToHex(s,t,n){return((1<<24)+(s<<16)+(t<<8)+n).toString(16).slice(1)},_hexToRgb(s){s=s.replace(nY,YQs);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=ZQs+s;return nY+s},isCanvasFarblingActive(){if(rY!==null)return rY;if(typeof document>"u")return rY=!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 rY=r,this.releaseCanvas(s),rY},getHitColor(){const s=this.getRandomColor();return this.isCanvasFarblingActive()?this.getSnappedHexColor(s):s},getHitColorKey(s,t,n){return this.isCanvasFarblingActive()&&(s=Math.round(s/5)*5,t=Math.round(t/5)*5,n=Math.round(n/5)*5),nY+this._rgbToHex(s,t,n)},getSnappedHexColor(s){const t=this._hexToRgb(s);return nY+this._rgbToHex(Math.round(t.r/5)*5,Math.round(t.g/5)*5,Math.round(t.b/5)*5)},getRGB(s){let t;return s in UFe?(t=UFe[s],{r:t[0],g:t[1],b:t[2]}):s[0]===nY?this._hexToRgb(s.substring(1)):s.substr(0,4)===QQs?(t=JQs.exec(s.replace(/ /g,"")),{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10)}):{r:0,g:0,b:0}},colorToRGBA(s){return s=s||"black",sr._namedColorToRBA(s)||sr._hex3ColorToRGBA(s)||sr._hex4ColorToRGBA(s)||sr._hex6ColorToRGBA(s)||sr._hex8ColorToRGBA(s)||sr._rgbColorToRGBA(s)||sr._rgbaColorToRGBA(s)||sr._hslColorToRGBA(s)},_namedColorToRBA(s){const t=UFe[s.toLowerCase()];return t?{r:t[0],g:t[1],b:t[2],a:1}:null},_rgbColorToRGBA(s){if(s.indexOf("rgb(")===0){s=s.match(/rgb\(([^)]+)\)/)[1];const t=s.split(/ *, */).map(Number);return{r:t[0],g:t[1],b:t[2],a:1}}},_rgbaColorToRGBA(s){if(s.indexOf("rgba(")===0){s=s.match(/rgba\(([^)]+)\)/)[1];const t=s.split(/ *, */).map((n,r)=>n.slice(-1)==="%"?r===3?parseInt(n)/100:parseInt(n)/100*255:Number(n));return{r:t[0],g:t[1],b:t[2],a:t[3]}}},_hex8ColorToRGBA(s){if(s[0]==="#"&&s.length===9)return{r:parseInt(s.slice(1,3),16),g:parseInt(s.slice(3,5),16),b:parseInt(s.slice(5,7),16),a:parseInt(s.slice(7,9),16)/255}},_hex6ColorToRGBA(s){if(s[0]==="#"&&s.length===7)return{r:parseInt(s.slice(1,3),16),g:parseInt(s.slice(3,5),16),b:parseInt(s.slice(5,7),16),a:1}},_hex4ColorToRGBA(s){if(s[0]==="#"&&s.length===5)return{r:parseInt(s[1]+s[1],16),g:parseInt(s[2]+s[2],16),b:parseInt(s[3]+s[3],16),a:parseInt(s[4]+s[4],16)/255}},_hex3ColorToRGBA(s){if(s[0]==="#"&&s.length===4)return{r:parseInt(s[1]+s[1],16),g:parseInt(s[2]+s[2],16),b:parseInt(s[3]+s[3],16),a:1}},_hslColorToRGBA(s){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(s)){const[t,...n]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(s),r=Number(n[0])/360,a=Number(n[1])/100,i=Number(n[2])/100;let l,o,c;if(a===0)return c=i*255,{r:Math.round(c),g:Math.round(c),b:Math.round(c),a:1};i<.5?l=i*(1+a):l=i+a-i*a;const d=2*i-l,u=[0,0,0];for(let h=0;h<3;h++)o=r+1/3*-(h-1),o<0&&o++,o>1&&o--,6*o<1?c=d+(l-d)*6*o:2*o<1?c=l:3*o<2?c=d+(l-d)*(2/3-o)*6:c=d,u[h]=c*255;return{r:Math.round(u[0]),g:Math.round(u[1]),b:Math.round(u[2]),a:1}}},haveIntersection(s,t){return!(t.x>s.x+s.width||t.x+t.widths.y+s.height||t.y+t.height1?(l=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=sr.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=sr._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{t.width=0,t.height=0})},drawRoundedRectPath(s,t,n,r){let a=t<0?t:0,i=n<0?n:0;t=Math.abs(t),n=Math.abs(n);let l=0,o=0,c=0,d=0;typeof r=="number"?l=o=c=d=Math.min(r,t/2,n/2):(l=Math.min(r[0]||0,t/2,n/2),o=Math.min(r[1]||0,t/2,n/2),d=Math.min(r[2]||0,t/2,n/2),c=Math.min(r[3]||0,t/2,n/2)),s.moveTo(a+l,i),s.lineTo(a+t-o,i),s.arc(a+t-o,i+o,o,Math.PI*3/2,0,!1),s.lineTo(a+t,i+n-d),s.arc(a+t-d,i+n-d,d,0,Math.PI/2,!1),s.lineTo(a+c,i+n),s.arc(a+c,i+n-c,c,Math.PI/2,Math.PI,!1),s.lineTo(a,i+l),s.arc(a+l,i+l,l,Math.PI,Math.PI*3/2,!1)},drawRoundedPolygonPath(s,t,n,r,a){r=Math.abs(r);for(let i=0;itypeof u=="number"?Math.floor(u):u)),i+=sJs+d.join(i0t)+nJs)):(i+=o.property,t||(i+=lJs+o.val)),i+=iJs;return i}clearTrace(){this.traceArr=[]}_trace(t){let n=this.traceArr,r;n.push(t),r=n.length,r>=dJs&&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)}_applyLineCap(t){const n=t.attrs.lineCap;n&&this.setAttr("lineCap",n)}_applyOpacity(t){const n=t.getAbsoluteOpacity();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?this._context.setLineDash(t):"mozDash"in this._context?this._context.mozDash=t:"webkitLineDash"in this._context&&(this._context.webkitLineDash=t)}getLineDash(){return this._context.getLineDash()}setTransform(t,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=o0t.length,r=this.setAttr,a,i;const l=function(o){let c=t[o],d;t[o]=function(){return i=tJs(Array.prototype.slice.call(arguments,0)),d=c.apply(t,arguments),t._trace({method:o,args:i}),d}};for(a=0;a{t.dragStatus==="dragging"&&(s=!0)}),s},justDragged:!1,get node(){let s;return fu._dragElements.forEach(t=>{s=t.node}),s},_dragElements:new Map,_drag(s){const t=[];fu._dragElements.forEach((n,r)=>{const{node:a}=n,i=a.getStage();i.setPointersPositions(s),n.pointerId===void 0&&(n.pointerId=sr._getFirstPointerId(s));const l=i._changedPointerPositions.find(o=>o.id===n.pointerId);if(l){if(n.dragStatus!=="dragging"){const o=a.dragDistance();if(Math.max(Math.abs(l.x-n.startPointerPos.x),Math.abs(l.y-n.startPointerPos.y)){n.getStage()&&n.fire("dragmove",{type:"dragmove",target:n,evt:s},!0)})},_endDragBefore(s){const t=[];fu._dragElements.forEach(n=>{const{node:r}=n,a=r.getStage();if(s&&a.setPointersPositions(s),!a._changedPointerPositions.find(o=>o.id===n.pointerId))return;(n.dragStatus==="dragging"||n.dragStatus==="stopped")&&(fu.justDragged=!0,fi._mouseListenClick=!1,fi._touchListenClick=!1,fi._pointerListenClick=!1,n.dragStatus="stopped");const l=n.node.getLayer()||n.node instanceof fi.Stage&&n.node;l&&t.indexOf(l)===-1&&t.push(l)}),t.forEach(n=>{n.draw()})},_endDragAfter(s){fu._dragElements.forEach((t,n)=>{t.dragStatus==="stopped"&&t.node.fire("dragend",{type:"dragend",target:t.node,evt:s},!0),t.dragStatus!=="dragging"&&fu._dragElements.delete(n)})}};fi.isBrowser&&(window.addEventListener("mouseup",fu._endDragBefore,!0),window.addEventListener("touchend",fu._endDragBefore,!0),window.addEventListener("touchcancel",fu._endDragBefore,!0),window.addEventListener("mousemove",fu._drag),window.addEventListener("touchmove",fu._drag),window.addEventListener("mouseup",fu._endDragAfter,!1),window.addEventListener("touchend",fu._endDragAfter,!1),window.addEventListener("touchcancel",fu._endDragAfter,!1));function QP(s){return sr._isString(s)?'"'+s+'"':Object.prototype.toString.call(s)==="[object Number]"||sr._isBoolean(s)?s:Object.prototype.toString.call(s)}function IBt(s){return s>255?255:s<0?0:Math.round(s)}function oi(){if(fi.isUnminified)return function(s,t){return sr._isNumber(s)||sr.warn(QP(s)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),s}}function DPe(s){if(fi.isUnminified)return function(t,n){let r=sr._isNumber(t),a=sr._isArray(t)&&t.length==s;return!r&&!a&&sr.warn(QP(t)+' is a not valid value for "'+n+'" attribute. The value should be a number or Array('+s+")"),t}}function eet(){if(fi.isUnminified)return function(s,t){return sr._isNumber(s)||s==="auto"||sr.warn(QP(s)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),s}}function v9(){if(fi.isUnminified)return function(s,t){return sr._isString(s)||sr.warn(QP(s)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),s}}function RBt(){if(fi.isUnminified)return function(s,t){const n=sr._isString(s),r=Object.prototype.toString.call(s)==="[object CanvasGradient]"||s&&s.addColorStop;return n||r||sr.warn(QP(s)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.'),s}}function pJs(){if(fi.isUnminified)return function(s,t){const n=Int8Array?Object.getPrototypeOf(Int8Array):null;return n&&s instanceof n||(sr._isArray(s)?s.forEach(function(r){sr._isNumber(r)||sr.warn('"'+t+'" attribute has non numeric element '+r+". Make sure that all elements are numbers.")}):sr.warn(QP(s)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),s}}function kS(){if(fi.isUnminified)return function(s,t){return s===!0||s===!1||sr.warn(QP(s)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),s}}function fJs(s){if(fi.isUnminified)return function(t,n){return t==null||sr.isObject(t)||sr.warn(QP(t)+' is a not valid value for "'+n+'" attribute. The value should be an object with properties '+s),t}}const aY="get",iY="set",mn={addGetterSetter(s,t,n,r,a){mn.addGetter(s,t,n),mn.addSetter(s,t,r,a),mn.addOverloadedGetterSetter(s,t)},addGetter(s,t,n){const r=aY+sr._capitalize(t);s.prototype[r]=s.prototype[r]||function(){const a=this.attrs[t];return a===void 0?n:a}},addSetter(s,t,n,r){const a=iY+sr._capitalize(t);s.prototype[a]||mn.overWriteSetter(s,t,n,r)},overWriteSetter(s,t,n,r){const a=iY+sr._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=sr._capitalize,o=aY+l(t),c=iY+l(t);s.prototype[o]=function(){const u={};for(let h=0;h{this._setAttr(t+l(m),void 0)}),this._fireChangeEvent(t,h,u),a&&a.call(this),this},mn.addOverloadedGetterSetter(s,t)},addOverloadedGetterSetter(s,t){const n=sr._capitalize(t),r=iY+n,a=aY+n;s.prototype[t]=function(){return arguments.length?(this[r](arguments[0]),this):this[a]()}},addDeprecatedGetterSetter(s,t,n,r){sr.error("Adding deprecated "+t);const a=aY+sr._capitalize(t),i=t+" property is deprecated and will be removed soon. Look at Konva change log for more information.";s.prototype[a]=function(){sr.error(i);const l=this.attrs[t];return l===void 0?n:l},mn.addSetter(s,t,r,function(){sr.error(i)}),mn.addOverloadedGetterSetter(s,t)},backCompat(s,t){sr.each(t,function(n,r){const a=s.prototype[r],i=aY+sr._capitalize(n),l=iY+sr._capitalize(n);function o(){a.apply(this,arguments),sr.error('"'+n+'" method is deprecated and will be removed soon. Use ""'+r+'" instead.')}s.prototype[n]=o,s.prototype[i]=o,s.prototype[l]=o})},afterSetFilter(){this._filterUpToDate=!1}};function gJs(s){const t=/(\w+)\(([^)]+)\)/g;let n;for(;(n=t.exec(s))!==null;){const[,r,a]=n;switch(r){case"blur":{const i=parseFloat(a.replace("px",""));return function(l){this.blurRadius(i*.5);const o=fi.Filters;o&&o.Blur&&o.Blur.call(this,l)}}case"brightness":{const i=a.includes("%")?parseFloat(a)/100:parseFloat(a);return function(l){this.brightness(i);const o=fi.Filters;o&&o.Brightness&&o.Brightness.call(this,l)}}case"contrast":{const i=parseFloat(a);return function(l){const o=100*(Math.sqrt(i)-1);this.contrast(o);const c=fi.Filters;c&&c.Contrast&&c.Contrast.call(this,l)}}case"grayscale":return function(i){const l=fi.Filters;l&&l.Grayscale&&l.Grayscale.call(this,i)};case"sepia":return function(i){const l=fi.Filters;l&&l.Sepia&&l.Sepia.call(this,i)};case"invert":return function(i){const l=fi.Filters;l&&l.Invert&&l.Invert.call(this,i)};default:sr.warn(`CSS filter "${r}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}const Y5e="absoluteOpacity",c0t="allEventListeners",gC="absoluteTransform",d0t="absoluteScale",JL="canvas",xJs="Change",yJs="children",vJs="konva",X$e="listening",bJs="mouseenter",_Js="mouseleave",wJs="pointerenter",jJs="pointerleave",NJs="touchenter",kJs="touchleave",u0t="set",h0t="Shape",Z5e=" ",m0t="stage",ET="transform",SJs="Stage",Q$e="visible",CJs=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(Z5e);let AJs=1,bi=class SZ{constructor(t){this._id=AJs++,this.eventListeners={},this.attrs={},this.index=0,this._allEventListeners=null,this.parent=null,this._cache=new Map,this._attachedDepsListeners=new Map,this._lastPos=null,this._batchingTransformChange=!1,this._needClearTransformCache=!1,this._filterUpToDate=!1,this._isUnderCache=!1,this._dragEventId=null,this._shouldFireChangeEvents=!1,this.setAttrs(t),this._shouldFireChangeEvents=!0}hasChildren(){return!1}_clearCache(t){(t===ET||t===gC)&&this._cache.get(t)?this._cache.get(t).dirty=!0:t?this._cache.delete(t):this._cache.clear()}_getCache(t,n){let r=this._cache.get(t);return(r===void 0||(t===ET||t===gC)&&r.dirty===!0)&&(r=n.call(this),this._cache.set(t,r)),r}_calculate(t,n,r){if(!this._attachedDepsListeners.get(t)){const a=n.map(i=>i+"Change.konva").join(Z5e);this.on(a,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,r)}_getCanvasCache(){return this._cache.get(JL)}_clearSelfAndDescendantCache(t){this._clearCache(t),t===gC&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(JL)){const{scene:t,filter:n,hit:r}=this._cache.get(JL);sr.releaseCanvas(t._canvas,n._canvas,r._canvas),this._cache.delete(JL)}return this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(t){const n=t||{};let r={};(n.x===void 0||n.y===void 0||n.width===void 0||n.height===void 0)&&(r=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()||void 0}));let a=Math.ceil(n.width||r.width),i=Math.ceil(n.height||r.height),l=n.pixelRatio,o=n.x===void 0?Math.floor(r.x):n.x,c=n.y===void 0?Math.floor(r.y):n.y,d=n.offset||0,u=n.drawBorder||!1,h=n.hitCanvasPixelRatio||1;if(!a||!i){sr.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.");return}const m=Math.abs(Math.round(r.x)-o)>.5?1:0,p=Math.abs(Math.round(r.y)-c)>.5?1:0;a+=d*2+m,i+=d*2+p,o-=d,c-=d;const f=new i6({pixelRatio:l,width:a,height:i}),x=new i6({pixelRatio:l,width:0,height:0,willReadFrequently:!0}),y=new JJe({pixelRatio:h,width:a,height:i}),v=f.getContext(),b=y.getContext(),N=new i6({width:f.width/f.pixelRatio+Math.abs(o),height:f.height/f.pixelRatio+Math.abs(c),pixelRatio:f.pixelRatio}),S=N.getContext();return y.isCache=!0,f.isCache=!0,this._cache.delete(JL),this._filterUpToDate=!1,n.imageSmoothingEnabled===!1&&(f.getContext()._context.imageSmoothingEnabled=!1,x.getContext()._context.imageSmoothingEnabled=!1),v.save(),b.save(),S.save(),v.translate(-o,-c),b.translate(-o,-c),S.translate(-o,-c),N.x=o,N.y=c,this._isUnderCache=!0,this._clearSelfAndDescendantCache(Y5e),this._clearSelfAndDescendantCache(d0t),this.drawScene(f,this,N),this.drawHit(y,this),this._isUnderCache=!1,v.restore(),b.restore(),u&&(v.save(),v.beginPath(),v.rect(0,0,a,i),v.closePath(),v.setAttr("strokeStyle","red"),v.setAttr("lineWidth",5),v.stroke(),v.restore()),sr.releaseCanvas(N._canvas),this._cache.set(JL,{scene:f,filter:x,hit:y,x:o,y:c}),this._requestDraw(),this}isCached(){return this._cache.has(JL)}getClientRect(t){throw new Error('abstract "getClientRect" method call')}_transformedRect(t,n){const r=[{x:t.x,y:t.y},{x:t.x+t.width,y:t.y},{x:t.x+t.width,y:t.y+t.height},{x:t.x,y:t.y+t.height}];let a=1/0,i=1/0,l=-1/0,o=-1/0;const c=this.getAbsoluteTransform(n);return r.forEach(function(d){const u=c.point(d);a===void 0&&(a=l=u.x,i=o=u.y),a=Math.min(a,u.x),i=Math.min(i,u.y),l=Math.max(l,u.x),o=Math.max(o,u.y)}),{x:a,y:i,width:l-a,height:o-i}}_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){const n=this._getCanvasCache(),r=n.hit;t.save(),t.translate(n.x,n.y),t.drawImage(r._canvas,0,0,r.width/r.pixelRatio,r.height/r.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;m{this.isAncestorOf(t.node)&&fu._dragElements.delete(n)}),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(gC),this._clearSelfAndDescendantCache(Y5e),this._clearSelfAndDescendantCache(d0t),this._clearSelfAndDescendantCache(m0t),this._clearSelfAndDescendantCache(Q$e),this._clearSelfAndDescendantCache(X$e)}_remove(){this._clearCaches();const t=this.getParent();t&&t.children&&(t.children.splice(this.index,1),t._setChildrenIndices(),this.parent=null)}destroy(){return this.remove(),this.clearCache(),this}getAttr(t){const n="get"+sr._capitalize(t);return sr._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!==yJs&&(r=u0t+sr._capitalize(n),sr._isFunction(this[r])?this[r](t[n]):this._setAttr(n,t[n]))}),this}isListening(){return this._getCache(X$e,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(Q$e,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,n=!1){if(t)return this._isVisible(t)&&this._isListening(t);const r=this.getLayer();let a=!1;fu._dragElements.forEach(l=>{l.dragStatus==="dragging"&&(l.node.nodeType==="Stage"||l.node.getLayer()===r)&&(a=!0)});const i=!n&&!fi.hitOnDragEnabled&&(a||fi.isTransforming());return this.isListening()&&this.isVisible()&&!i}show(){return this.visible(!0),this}hide(){return this.visible(!1),this}getZIndex(){return this.index||0}getAbsoluteZIndex(){let t=this.getDepth(),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!==SJs&&d&&c(d.getChildren()),r}getDepth(){let t=0,n=this.parent;for(;n;)t++,n=n.parent;return t}_batchTransformChanges(t){this._batchingTransformChange=!0,t(),this._batchingTransformChange=!1,this._needClearTransformCache&&(this._clearCache(ET),this._clearSelfAndDescendantCache(gC)),this._needClearTransformCache=!1}setPosition(t){return this._batchTransformChanges(()=>{this.x(t.x),this.y(t.y)}),this}getPosition(){return{x:this.x(),y:this.y()}}getRelativePointerPosition(){const t=this.getStage();if(!t)return null;const n=t.getPointerPosition();if(!n)return null;const r=this.getAbsoluteTransform().copy();return r.invert(),r.point(n)}getAbsolutePosition(t){let n=!1,r=this.parent;for(;r;){if(r.isCached()){n=!0;break}r=r.parent}n&&!t&&(t=!0);const a=this.getAbsoluteTransform(t).getMatrix(),i=new Bw,l=this.offset();return i.m=a.slice(),i.translate(l.x,l.y),i.getTranslation()}setAbsolutePosition(t){const{x:n,y:r,...a}=this._clearTransform();this.attrs.x=n,this.attrs.y=r,this._clearCache(ET);const i=this._getAbsoluteTransform().copy();return i.invert(),i.translate(t.x,t.y),t={x:this.attrs.x+i.getTranslation().x,y:this.attrs.y+i.getTranslation().y},this._setTransform(a),this.setPosition({x:t.x,y:t.y}),this._clearCache(ET),this._clearSelfAndDescendantCache(gC),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}_eachAncestorReverse(t,n){let r=[],a=this.getParent(),i,l;if(!(n&&n._id===this._id)){for(r.unshift(this);a&&(!n||a._id!==n._id);)r.unshift(a),a=a.parent;for(i=r.length,l=0;l0?(this.parent.children.splice(t,1),this.parent.children.splice(t-1,0,this),this.parent._setChildrenIndices(),!0):!1}moveToBottom(){if(!this.parent)return sr.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 sr.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&sr.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(Y5e,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(){let t=this.getAttrs(),n,r,a,i,l;const o={attrs:{},className:this.getClassName()};for(n in t)r=t[n],l=sr.isObject(r)&&!sr._isPlainObject(r)&&!sr._isArray(r),!l&&(a=typeof this[n]=="function"&&this[n],delete t[n],i=a?a.call(this):null,t[n]=r,i!==r&&(o.attrs[n]=r));return sr._prepareToStringify(o)}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 a=t==null?void 0:t.callback;a&&delete t.callback,sr._urlToImage(this.toDataURL(t),function(i){n(i),a==null||a(i)})}catch(a){r(a)}})}toBlob(t){return new Promise((n,r)=>{try{const a=t==null?void 0:t.callback;a&&delete t.callback,this.toCanvas(t).toBlob(i=>{n(i),a==null||a(i)},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():fi.dragDistance}_off(t,n,r){let a=this.eventListeners[t],i,l,o;for(i=0;i=0)||this.isDragging())return;let a=!1;fu._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=fu._dragElements.get(this._id),r=n&&n.dragStatus==="dragging",a=n&&n.dragStatus==="ready";r?this.stopDrag():a&&fu._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 sr.haveIntersection(r,this.getClientRect())}static create(t,n){return sr._isString(t)&&(t=JSON.parse(t)),this._createNode(t,n)}static _createNode(t,n){let r=SZ.prototype.getClassName.call(t),a=t.children,i,l,o;n&&(t.attrs.container=n),fi[r]||(sr.warn('Can not find a node with class name "'+r+'". Fallback to "Shape".'),r="Shape");const c=fi[r];if(i=new c(t.attrs),a)for(l=a.length,o=0;o0}removeChildren(){return this.getChildren().forEach(t=>{t.parent=null,t.index=0,t.remove()}),this.children=[],this._requestDraw(),this}destroyChildren(){return this.getChildren().forEach(t=>{t.parent=null,t.index=0,t.destroy()}),this.children=[],this._requestDraw(),this}add(...t){if(t.length===0)return this;if(t.length>1){for(let 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;const r=this.getChildren();for(const a of r){if(n=t(a),n)return!0;if(a.hasChildren()&&(n=a._descendants(t),n))return!0}return!1}toObject(){const t=bi.prototype.toObject.call(this);return t.children=[],this.getChildren().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=bi.prototype.clone.call(this,t);return this.getChildren().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;super._clearSelfAndDescendantCache(t),!this.isCached()&&((n=this.children)===null||n===void 0||n.forEach(function(r){r._clearSelfAndDescendantCache(t)}))}_setChildrenIndices(){var t;(t=this.children)===null||t===void 0||t.forEach(function(n,r){n.index=r}),this._requestDraw()}drawScene(t,n,r){const a=this.getLayer(),i=t||a&&a.getCanvas(),l=i&&i.getContext(),o=this._getCanvasCache(),c=o&&o.scene,d=i&&i.isCache;if(!this.isVisible()&&!d)return this;if(c){l.save();const u=this.getAbsoluteTransform(n).getMatrix();l.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(l),l.restore()}else this._drawChildren("drawScene",i,n,r);return this}drawHit(t,n){if(!this.shouldDrawHit(n))return this;const r=this.getLayer(),a=t||r&&r.hitCanvas,i=a&&a.getContext(),l=this._getCanvasCache();if(l&&l.hit){i.save();const c=this.getAbsoluteTransform(n).getMatrix();i.transform(c[0],c[1],c[2],c[3],c[4],c[5]),this._drawCachedHitCanvas(i),i.restore()}else this._drawChildren("drawHit",a,n);return this}_drawChildren(t,n,r,a){var i;const l=n&&n.getContext(),o=this.clipWidth(),c=this.clipHeight(),d=this.clipFunc(),u=typeof o=="number"&&typeof c=="number"||d,h=r===this;if(u){l.save();const p=this.getAbsoluteTransform(r);let f=p.getMatrix();l.transform(f[0],f[1],f[2],f[3],f[4],f[5]),l.beginPath();let x;if(d)x=d.call(this,l,this);else{const y=this.clipX(),v=this.clipY();l.rect(y||0,v||0,o,c)}l.clip.apply(l,x),f=p.copy().invert().getMatrix(),l.transform(f[0],f[1],f[2],f[3],f[4],f[5])}const m=!h&&this.globalCompositeOperation()!=="source-over"&&t==="drawScene";m&&(l.save(),l._applyGlobalCompositeOperation(this)),(i=this.children)===null||i===void 0||i.forEach(function(p){p[t](n,r,a)}),m&&l.restore(),u&&l.restore()}getClientRect(t={}){var n;const r=t.skipTransform,a=t.relativeTo;let i,l,o,c,d={x:1/0,y:1/0,width:0,height:0};const u=this;(n=this.children)===null||n===void 0||n.forEach(function(p){if(!p.visible())return;const f=p.getClientRect({relativeTo:u,skipShadow:t.skipShadow,skipStroke:t.skipStroke});f.width===0&&f.height===0||(i===void 0?(i=f.x,l=f.y,o=f.x+f.width,c=f.y+f.height):(i=Math.min(i,f.x),l=Math.min(l,f.y),o=Math.max(o,f.x+f.width),c=Math.max(c,f.y+f.height)))});const h=this.find("Shape");let m=!1;for(let p=0;ps.indexOf("pointer")>=0?"pointer":s.indexOf("touch")>=0?"touch":"mouse",Xz=s=>{const t=MZ(s);if(t==="pointer")return fi.pointerEventsEnabled&&$Fe.pointer;if(t==="touch")return $Fe.touch;if(t==="mouse")return $Fe.mouse};function f0t(s={}){return(s.clipFunc||s.clipWidth||s.clipHeight)&&sr.warn("Stage does not support clipping. Please use clip for Layers or Groups."),s}const RJs="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);",GQ=[];let OPe=class extends rj{constructor(t){super(f0t(t)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),GQ.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{f0t(this.attrs)}),this._checkVisibility()}_validateAdd(t){const n=t.getType()==="Layer",r=t.getType()==="FastLayer";n||r||sr.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;const t=this.visible()?"":"none";this.content.style.display=t}setContainer(t){if(typeof t===TJs){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)),this}shouldDrawHit(){return!0}clear(){const t=this.children,n=t.length;for(let r=0;r-1&&GQ.splice(n,1),sr.releaseCanvas(this.bufferCanvas._canvas,this.bufferHitCanvas._canvas),this}getPointerPosition(){const t=this._pointerPositions[0]||this._changedPointerPositions[0];return t?{x:t.x,y:t.y}:(sr.warn(RJs),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 i6({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())}),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+p0t,this.content.style.height=n+p0t),this.bufferCanvas.setSize(t,n),this.bufferHitCanvas.setSize(t,n),this.children.forEach(r=>{r.setSize({width:t,height:n}),r.draw()})}add(t,...n){if(arguments.length>1){for(let a=0;aLJs&&sr.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(),fi.isBrowser&&this.content.appendChild(t.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(t){return OBt(t,this)}setPointerCapture(t){FBt(t,this)}releaseCapture(t){HQ(t)}getLayers(){return this.children}_bindContentEvents(){fi.isBrowser&&IJs.forEach(([t,n])=>{this.content.addEventListener(t,r=>{this[n](r)},{passive:!1})})}_pointerenter(t){this.setPointersPositions(t);const n=Xz(t.type);n&&this._fire(n.pointerenter,{evt:t,target:this,currentTarget:this})}_pointerover(t){this.setPointersPositions(t);const n=Xz(t.type);n&&this._fire(n.pointerover,{evt:t,target:this,currentTarget:this})}_getTargetShape(t){let n=this[t+"targetShape"];return n&&!n.getStage()&&(n=null),n}_pointerleave(t){const n=Xz(t.type),r=MZ(t.type);if(!n)return;this.setPointersPositions(t);const a=this._getTargetShape(r),i=!(fi.isDragging()||fi.isTransforming())||fi.hitOnDragEnabled;a&&i?(a._fireAndBubble(n.pointerout,{evt:t}),a._fireAndBubble(n.pointerleave,{evt:t}),this._fire(n.pointerleave,{evt:t,target:this,currentTarget:this}),this[r+"targetShape"]=null):i&&(this._fire(n.pointerleave,{evt:t,target:this,currentTarget:this}),this._fire(n.pointerout,{evt:t,target:this,currentTarget:this})),this.pointerPos=null,this._pointerPositions=[]}_pointerdown(t){const n=Xz(t.type),r=MZ(t.type);if(!n)return;this.setPointersPositions(t);let a=!1;this._changedPointerPositions.forEach(i=>{const l=this.getIntersection(i);if(fu.justDragged=!1,fi["_"+r+"ListenClick"]=!0,!l||!l.isListening()){this[r+"ClickStartShape"]=void 0;return}fi.capturePointerEventsEnabled&&l.setPointerCapture(i.id),this[r+"ClickStartShape"]=l,l._fireAndBubble(n.pointerdown,{evt:t,pointerId:i.id}),a=!0;const o=t.type.indexOf("touch")>=0;l.preventDefault()&&t.cancelable&&o&&t.preventDefault()}),a||this._fire(n.pointerdown,{evt:t,target:this,currentTarget:this,pointerId:this._pointerPositions[0].id})}_pointermove(t){const n=Xz(t.type),r=MZ(t.type);if(!n)return;const a=t.type.indexOf("touch")>=0||t.pointerType==="touch";if(fi.isDragging()&&fu.node.preventDefault()&&t.cancelable&&a&&t.preventDefault(),this.setPointersPositions(t),!(!(fi.isDragging()||fi.isTransforming())||fi.hitOnDragEnabled))return;const l={};let o=!1;const c=this._getTargetShape(r);this._changedPointerPositions.forEach(d=>{const u=qFe(d.id)||this.getIntersection(d),h=d.id,m={evt:t,pointerId:h},p=c!==u;if(p&&c&&(c._fireAndBubble(n.pointerout,{...m},u),c._fireAndBubble(n.pointerleave,{...m},u)),u){if(l[u._id])return;l[u._id]=!0}u&&u.isListening()?(o=!0,p&&(u._fireAndBubble(n.pointerover,{...m},c),u._fireAndBubble(n.pointerenter,{...m},c),this[r+"targetShape"]=u),u._fireAndBubble(n.pointermove,{...m})):c&&(this._fire(n.pointerover,{evt:t,target:this,currentTarget:this,pointerId:h}),this[r+"targetShape"]=null)}),o||this._fire(n.pointermove,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(t){const n=Xz(t.type),r=MZ(t.type);if(!n)return;this.setPointersPositions(t);const a=this[r+"ClickStartShape"],i=this[r+"ClickEndShape"],l={};let o=!1;this._changedPointerPositions.forEach(c=>{const d=qFe(c.id)||this.getIntersection(c);if(d){if(d.releaseCapture(c.id),l[d._id])return;l[d._id]=!0}const u=c.id,h={evt:t,pointerId:u};let m=!1;fi["_"+r+"InDblClickWindow"]?(m=!0,clearTimeout(this[r+"DblTimeout"])):fu.justDragged||(fi["_"+r+"InDblClickWindow"]=!0,clearTimeout(this[r+"DblTimeout"])),this[r+"DblTimeout"]=setTimeout(function(){fi["_"+r+"InDblClickWindow"]=!1},fi.dblClickWindow),d&&d.isListening()?(o=!0,this[r+"ClickEndShape"]=d,d._fireAndBubble(n.pointerup,{...h}),fi["_"+r+"ListenClick"]&&a&&a===d&&(d._fireAndBubble(n.pointerclick,{...h}),m&&i&&i===d&&d._fireAndBubble(n.pointerdblclick,{...h}))):(this[r+"ClickEndShape"]=null,o||(this._fire(n.pointerup,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),o=!0),fi["_"+r+"ListenClick"]&&this._fire(n.pointerclick,{evt:t,target:this,currentTarget:this,pointerId:u}),m&&this._fire(n.pointerdblclick,{evt:t,target:this,currentTarget:this,pointerId:u}))}),o||this._fire(n.pointerup,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),fi["_"+r+"ListenClick"]=!1,t.cancelable&&r!=="touch"&&r!=="pointer"&&t.preventDefault()}_contextmenu(t){this.setPointersPositions(t);const n=this.getIntersection(this.getPointerPosition());n&&n.isListening()?n._fireAndBubble(J$e,{evt:t}):this._fire(J$e,{evt:t,target:this,currentTarget:this})}_wheel(t){this.setPointersPositions(t);const n=this.getIntersection(this.getPointerPosition());n&&n.isListening()?n._fireAndBubble(eVe,{evt:t}):this._fire(eVe,{evt:t,target:this,currentTarget:this})}_pointercancel(t){this.setPointersPositions(t);const n=qFe(t.pointerId)||this.getIntersection(this.getPointerPosition());n&&n._fireAndBubble(jU,tet(t)),HQ(t.pointerId)}_lostpointercapture(t){HQ(t.pointerId)}setPointersPositions(t){const n=this._getContentPosition();let r=null,a=null;t=t||window.event,t.touches!==void 0?(this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(t.touches,i=>{this._pointerPositions.push({id:i.identifier,x:(i.clientX-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})})):(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:sr._getFirstPointerId(t)}],this._changedPointerPositions=[{x:r,y:a,id:sr._getFirstPointerId(t)}])}_setPointerPosition(t){sr.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'),this.setPointersPositions(t)}_getContentPosition(){if(!this.content||!this.content.getBoundingClientRect)return{top:0,left:0,scaleX:1,scaleY:1};const t=this.content.getBoundingClientRect();return{top:t.top,left:t.left,scaleX:t.width/this.content.clientWidth||1,scaleY:t.height/this.content.clientHeight||1}}_buildDOM(){if(this.bufferCanvas=new i6({width:this.width(),height:this.height()}),this.bufferHitCanvas=new JJe({pixelRatio:1,width:this.width(),height:this.height()}),!fi.isBrowser)return;const t=this.container();if(!t)throw"Stage has no container. A container is required.";t.innerHTML="",this.content=document.createElement("div"),this.content.style.position="relative",this.content.style.userSelect="none",this.content.className="konvajs-content",this.content.setAttribute("role","presentation"),t.appendChild(this.content),this._resizeDOM()}cache(){return sr.warn("Cache function is not allowed for stage. You may use cache only for layers, groups and shapes."),this}clearCache(){return this}batchDraw(){return this.getChildren().forEach(function(t){t.batchDraw()}),this}};OPe.prototype.nodeType=EJs;Lf(OPe);mn.addGetterSetter(OPe,"container");fi.isBrowser&&document.addEventListener("visibilitychange",()=>{GQ.forEach(s=>{s.batchDraw()})});const YBt="hasShadow",ZBt="shadowRGBA",XBt="patternImage",QBt="linearGradient",JBt="radialGradient";let ule;function VFe(){return ule||(ule=sr.createCanvasElement().getContext("2d"),ule)}const WQ={};function DJs(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function OJs(s){s.stroke()}function FJs(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function zJs(s){s.stroke()}function BJs(){this._clearCache(YBt)}function UJs(){this._clearCache(ZBt)}function qJs(){this._clearCache(XBt)}function $Js(){this._clearCache(QBt)}function VJs(){this._clearCache(JBt)}let Qa=class extends bi{constructor(t){super(t);let n,r=0;for(;n=sr.getHitColor(),!(n&&!(n in WQ));)if(r++,r>=1e4){sr.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=sr.getRandomColor();break}this.colorKey=n,WQ[n]=this}getContext(){return sr.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return sr.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(YBt,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(XBt,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const n=VFe().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(n&&n.setTransform){const r=new Bw;r.translate(this.fillPatternX(),this.fillPatternY()),r.rotate(fi.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(QBt,this.__getLinearGradient)}__getLinearGradient(){const t=this.fillLinearGradientColorStops();if(t){const n=VFe(),r=this.fillLinearGradientStartPoint(),a=this.fillLinearGradientEndPoint(),i=n.createLinearGradient(r.x,r.y,a.x,a.y);for(let l=0;lthis.fillEnabled()&&!!(this.fill()||this.fillPatternImage()||this.fillLinearGradientColorStops()||this.fillRadialGradientColorStops()))}hasStroke(){return this._calculate("hasStroke",["strokeEnabled","strokeWidth","stroke","strokeLinearGradientColorStops"],()=>this.strokeEnabled()&&this.strokeWidth()&&!!(this.stroke()||this.strokeLinearGradientColorStops()))}hasHitStroke(){const t=this.hitStrokeWidth();return t==="auto"?this.hasStroke():this.strokeEnabled()&&!!t}intersects(t){const n=this.getStage();if(!n)return!1;const r=n.bufferHitCanvas;return r.getContext().clear(),this.drawHit(r,void 0,!0),r.context.getImageData(Math.round(t.x),Math.round(t.y),1,1).data[3]>0}destroy(){return bi.prototype.destroy.call(this),delete WQ[this.colorKey],delete this.colorKey,this}_useBufferCanvas(t){var n;if(!((n=this.attrs.perfectDrawEnabled)!==null&&n!==void 0?n:!0))return!1;const a=t||this.hasFill(),i=this.hasStroke(),l=this.getAbsoluteOpacity()!==1;if(a&&i&&l)return!0;const o=this.hasShadow(),c=this.shadowForStrokeEnabled();return!!(a&&i&&o&&c)}setStrokeHitEnabled(t){sr.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),t?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return this.hitStrokeWidth()!==0}getSelfRect(){const t=this.size();return{x:this._centroid?-t.width/2:0,y:this._centroid?-t.height/2:0,width:t.width,height:t.height}}getClientRect(t={}){let n=!1,r=this.getParent();for(;r;){if(r.isCached()){n=!0;break}r=r.getParent()}const a=t.skipTransform,i=t.relativeTo||n&&this.getStage()||void 0,l=this.getSelfRect(),c=!t.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,d=l.width+c,u=l.height+c,h=!t.skipShadow&&this.hasShadow(),m=h?this.shadowOffsetX():0,p=h?this.shadowOffsetY():0,f=d+Math.abs(m),x=u+Math.abs(p),y=h&&this.shadowBlur()||0,v=f+y*2,b=x+y*2,N={width:v,height:b,x:-(c/2+y)+Math.min(m,0)+l.x,y:-(c/2+y)+Math.min(p,0)+l.y};return a?N:this._transformedRect(N,i)}drawScene(t,n,r){const a=this.getLayer(),i=t||a.getCanvas(),l=i.getContext(),o=this._getCanvasCache(),c=this.getSceneFunc(),d=this.hasShadow();let u;const h=!1,m=n===this;if(!this.isVisible()&&!m)return this;if(o){l.save();const p=this.getAbsoluteTransform(n).getMatrix();return l.transform(p[0],p[1],p[2],p[3],p[4],p[5]),this._drawCachedSceneCanvas(l),l.restore(),this}if(!c)return this;if(l.save(),this._useBufferCanvas()&&!h){u=this.getStage();const p=r||u.bufferCanvas,f=p.getContext();r?(f.save(),f.setTransform(1,0,0,1,0,0),f.clearRect(0,0,p.width,p.height),f.restore()):f.clear(),f.save(),f._applyLineJoin(this),f._applyMiterLimit(this);const x=this.getAbsoluteTransform(n).getMatrix();f.transform(x[0],x[1],x[2],x[3],x[4],x[5]),c.call(this,f,this),f.restore();const y=p.pixelRatio;d&&l._applyShadow(this),m||(l._applyOpacity(this),l._applyGlobalCompositeOperation(this)),l.drawImage(p._canvas,p.x||0,p.y||0,p.width/y,p.height/y)}else{if(l._applyLineJoin(this),l._applyMiterLimit(this),!m){const p=this.getAbsoluteTransform(n).getMatrix();l.transform(p[0],p[1],p[2],p[3],p[4],p[5]),l._applyOpacity(this),l._applyGlobalCompositeOperation(this)}d&&l._applyShadow(this),c.call(this,l,this)}return l.restore(),this}drawHit(t,n,r=!1){if(!this.shouldDrawHit(n,r))return this;const a=this.getLayer(),i=t||a.hitCanvas,l=i&&i.getContext(),o=this.hitFunc()||this.sceneFunc(),c=this._getCanvasCache(),d=c&&c.hit;if(this.colorKey||sr.warn("Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()"),d){l.save();const h=this.getAbsoluteTransform(n).getMatrix();return l.transform(h[0],h[1],h[2],h[3],h[4],h[5]),this._drawCachedHitCanvas(l),l.restore(),this}if(!o)return this;if(l.save(),l._applyLineJoin(this),l._applyMiterLimit(this),!(this===n)){const h=this.getAbsoluteTransform(n).getMatrix();l.transform(h[0],h[1],h[2],h[3],h[4],h[5])}return o.call(this,l,this),l.restore(),this}drawHitFromCache(t=0){const n=this._getCanvasCache(),r=this._getCachedSceneCanvas(),a=n.hit,i=a.getContext(),l=a.getWidth(),o=a.getHeight();i.clear(),i.drawImage(r._canvas,0,0,l,o);try{const c=i.getImageData(0,0,l,o),d=c.data,u=d.length,h=sr._hexToRgb(this.colorKey);for(let m=0;mt?(d[m]=h.r,d[m+1]=h.g,d[m+2]=h.b,d[m+3]=255):d[m+3]=0;i.putImageData(c,0,0)}catch(c){sr.error("Unable to draw hit graph from cached scene canvas. "+c.message)}return this}hasPointerCapture(t){return OBt(t,this)}setPointerCapture(t){FBt(t,this)}releaseCapture(t){HQ(t)}};Qa.prototype._fillFunc=DJs;Qa.prototype._strokeFunc=OJs;Qa.prototype._fillFuncHit=FJs;Qa.prototype._strokeFuncHit=zJs;Qa.prototype._centroid=!1;Qa.prototype.nodeType="Shape";Lf(Qa);Qa.prototype.eventListeners={};Qa.prototype.on("shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",BJs);Qa.prototype.on("shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",UJs);Qa.prototype.on("fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",qJs);Qa.prototype.on("fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",$Js);Qa.prototype.on("fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",VJs);mn.addGetterSetter(Qa,"stroke",void 0,RBt());mn.addGetterSetter(Qa,"strokeWidth",2,oi());mn.addGetterSetter(Qa,"fillAfterStrokeEnabled",!1);mn.addGetterSetter(Qa,"hitStrokeWidth","auto",eet());mn.addGetterSetter(Qa,"strokeHitEnabled",!0,kS());mn.addGetterSetter(Qa,"perfectDrawEnabled",!0,kS());mn.addGetterSetter(Qa,"shadowForStrokeEnabled",!0,kS());mn.addGetterSetter(Qa,"lineJoin");mn.addGetterSetter(Qa,"lineCap");mn.addGetterSetter(Qa,"miterLimit");mn.addGetterSetter(Qa,"sceneFunc");mn.addGetterSetter(Qa,"hitFunc");mn.addGetterSetter(Qa,"dash");mn.addGetterSetter(Qa,"dashOffset",0,oi());mn.addGetterSetter(Qa,"shadowColor",void 0,v9());mn.addGetterSetter(Qa,"shadowBlur",0,oi());mn.addGetterSetter(Qa,"shadowOpacity",1,oi());mn.addComponentsGetterSetter(Qa,"shadowOffset",["x","y"]);mn.addGetterSetter(Qa,"shadowOffsetX",0,oi());mn.addGetterSetter(Qa,"shadowOffsetY",0,oi());mn.addGetterSetter(Qa,"fillPatternImage");mn.addGetterSetter(Qa,"fill",void 0,RBt());mn.addGetterSetter(Qa,"fillPatternX",0,oi());mn.addGetterSetter(Qa,"fillPatternY",0,oi());mn.addGetterSetter(Qa,"fillLinearGradientColorStops");mn.addGetterSetter(Qa,"strokeLinearGradientColorStops");mn.addGetterSetter(Qa,"fillRadialGradientStartRadius",0);mn.addGetterSetter(Qa,"fillRadialGradientEndRadius",0);mn.addGetterSetter(Qa,"fillRadialGradientColorStops");mn.addGetterSetter(Qa,"fillPatternRepeat","repeat");mn.addGetterSetter(Qa,"fillEnabled",!0);mn.addGetterSetter(Qa,"strokeEnabled",!0);mn.addGetterSetter(Qa,"shadowEnabled",!0);mn.addGetterSetter(Qa,"dashEnabled",!0);mn.addGetterSetter(Qa,"strokeScaleEnabled",!0);mn.addGetterSetter(Qa,"fillPriority","color");mn.addComponentsGetterSetter(Qa,"fillPatternOffset",["x","y"]);mn.addGetterSetter(Qa,"fillPatternOffsetX",0,oi());mn.addGetterSetter(Qa,"fillPatternOffsetY",0,oi());mn.addComponentsGetterSetter(Qa,"fillPatternScale",["x","y"]);mn.addGetterSetter(Qa,"fillPatternScaleX",1,oi());mn.addGetterSetter(Qa,"fillPatternScaleY",1,oi());mn.addComponentsGetterSetter(Qa,"fillLinearGradientStartPoint",["x","y"]);mn.addComponentsGetterSetter(Qa,"strokeLinearGradientStartPoint",["x","y"]);mn.addGetterSetter(Qa,"fillLinearGradientStartPointX",0);mn.addGetterSetter(Qa,"strokeLinearGradientStartPointX",0);mn.addGetterSetter(Qa,"fillLinearGradientStartPointY",0);mn.addGetterSetter(Qa,"strokeLinearGradientStartPointY",0);mn.addComponentsGetterSetter(Qa,"fillLinearGradientEndPoint",["x","y"]);mn.addComponentsGetterSetter(Qa,"strokeLinearGradientEndPoint",["x","y"]);mn.addGetterSetter(Qa,"fillLinearGradientEndPointX",0);mn.addGetterSetter(Qa,"strokeLinearGradientEndPointX",0);mn.addGetterSetter(Qa,"fillLinearGradientEndPointY",0);mn.addGetterSetter(Qa,"strokeLinearGradientEndPointY",0);mn.addComponentsGetterSetter(Qa,"fillRadialGradientStartPoint",["x","y"]);mn.addGetterSetter(Qa,"fillRadialGradientStartPointX",0);mn.addGetterSetter(Qa,"fillRadialGradientStartPointY",0);mn.addComponentsGetterSetter(Qa,"fillRadialGradientEndPoint",["x","y"]);mn.addGetterSetter(Qa,"fillRadialGradientEndPointX",0);mn.addGetterSetter(Qa,"fillRadialGradientEndPointY",0);mn.addGetterSetter(Qa,"fillPatternRotation",0);mn.addGetterSetter(Qa,"fillRule",void 0,v9());mn.backCompat(Qa,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const HJs="beforeDraw",GJs="draw",eUt=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],WJs=eUt.length;let b9=class extends rj{constructor(t){super(t),this.canvas=new i6,this.hitCanvas=new JJe({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.draw(),this._waitingForDraw=!1})),this}getIntersection(t){if(!this.isListening()||!this.isVisible())return null;let n=1,r=!1;for(;;){for(let a=0;a0)return{antialiased:!0};return{}}drawScene(t,n,r){const a=this.getLayer(),i=t||a&&a.getCanvas();return this._fire(HJs,{node:this}),this.clearBeforeDraw()&&i.getContext().clear(),rj.prototype.drawScene.call(this,i,n,r),this._fire(GJs,{node:this}),this}drawHit(t,n){const r=this.getLayer(),a=t||r&&r.hitCanvas;return r&&r.clearBeforeDraw()&&r.getHitCanvas().getContext().clear(),rj.prototype.drawHit.call(this,a,n),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(t){sr.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)}getHitGraphEnabled(t){return sr.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 sr.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}};b9.prototype.nodeType="Layer";Lf(b9);mn.addGetterSetter(b9,"imageSmoothingEnabled",!0);mn.addGetterSetter(b9,"clearBeforeDraw",!0);mn.addGetterSetter(b9,"hitGraphEnabled",!0,kS());class set extends b9{constructor(t){super(t),this.listening(!1),sr.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}set.prototype.nodeType="FastLayer";Lf(set);let JV=class extends rj{_validateAdd(t){const n=t.getType();n!=="Group"&&n!=="Shape"&&sr.throw("You may only add groups and shapes to groups.")}};JV.prototype.nodeType="Group";Lf(JV);const HFe=function(){return XD.performance&&XD.performance.now?function(){return XD.performance.now()}:function(){return new Date().getTime()}}();class L2{constructor(t,n){this.id=L2.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:HFe(),frameRate:0},this.func=t,this.setLayers(n)}setLayers(t){let n=[];return t&&(n=Array.isArray(t)?t:[t]),this.layers=n,this}getLayers(){return this.layers}addLayer(t){const n=this.layers,r=n.length;for(let a=0;athis.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():t<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=t,this.update())}getTime(){return this._time}setPosition(t){this.prevPos=this._pos,this.propFunc(t),this._pos=t}getPosition(t){return t===void 0&&(t=this._time),this.func(t,this.begin,this._change,this.duration)}play(){this.state=g0t,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=x0t,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")}seek(t){this.pause(),this._time=t,this.update(),this.fire("onSeek")}reset(){this.pause(),this._time=0,this.update(),this.fire("onReset")}finish(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")}update(){this.setPosition(this.getPosition(this._time)),this.fire("onUpdate")}onEnterFrame(){const t=this.getTimer()-this._startTime;this.state===g0t?this.setTime(t):this.state===x0t&&this.setTime(this.duration-t)}pause(){this.state=YJs,this.fire("onPause")}getTimer(){return new Date().getTime()}}class Sm{constructor(t){const n=this,r=t.node,a=r._id,i=t.easing||KQ.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=ZJs++;const d=r.getLayer()||(r instanceof fi.Stage?r.getLayers():null);d||sr.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new L2(function(){n.tween.onEnterFrame()},d),this.tween=new XJs(c,function(u){n._tweenFunc(u)},i,0,1,o*1e3,l),this._addListeners(),Sm.attrs[a]||(Sm.attrs[a]={}),Sm.attrs[a][this._id]||(Sm.attrs[a][this._id]={}),Sm.tweens[a]||(Sm.tweens[a]={});for(c in t)KJs[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){const r=this.node,a=r._id;let i,l,o,c,d;const u=Sm.tweens[a][t];u&&delete Sm.attrs[a][u][t];let h=r.getAttr(t);if(sr._isArray(n))if(i=[],l=Math.max(n.length,h.length),t==="points"&&n.length!==h.length&&(n.length>h.length?(c=h,h=sr._prepareArrayForTween(h,n,r.closed())):(o=n,n=sr._prepareArrayForTween(n,h,r.closed()))),t.indexOf("fill")===0)for(let m=0;m{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{const t=this.node,n=Sm.attrs[t._id][this._id];n.points&&n.points.trueEnd&&t.setAttr("points",n.points.trueEnd),this.onFinish&&this.onFinish.call(this)},this.tween.onReset=()=>{const t=this.node,n=Sm.attrs[t._id][this._id];n.points&&n.points.trueStart&&t.points(n.points.trueStart),this.onReset&&this.onReset()},this.tween.onUpdate=()=>{this.onUpdate&&this.onUpdate.call(this)}}play(){return this.tween.play(),this}reverse(){return this.tween.reverse(),this}reset(){return this.tween.reset(),this}seek(t){return this.tween.seek(t*1e3),this}pause(){return this.tween.pause(),this}finish(){return this.tween.finish(),this}destroy(){const t=this.node._id,n=this._id,r=Sm.tweens[t];this.pause(),this.anim&&this.anim.stop();for(const a in r)delete Sm.tweens[t][a];delete Sm.attrs[t][n],Sm.tweens[t]&&(Object.keys(Sm.tweens[t]).length===0&&delete Sm.tweens[t],Object.keys(Sm.attrs[t]).length===0&&delete Sm.attrs[t])}}Sm.attrs={};Sm.tweens={};bi.prototype.to=function(s){const t=s.onFinish;s.node=this,s.onFinish=function(){this.destroy(),t&&t()},new Sm(s).play()};const KQ={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||a0?t:n),u=l*n,h=o*(o>0?t:n),m=c*(c>0?n:t);return{x:d,y:r?-1*m:h,width:u-d,height:m-h}}}yE.prototype._centroid=!0;yE.prototype.className="Arc";yE.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];Lf(yE);mn.addGetterSetter(yE,"innerRadius",0,oi());mn.addGetterSetter(yE,"outerRadius",0,oi());mn.addGetterSetter(yE,"angle",0,oi());mn.addGetterSetter(yE,"clockwise",!1,kS());function tVe(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=l*o/(o+c),u=l*c/(o+c),h=n-d*(a-s),m=r-d*(i-t),p=n+u*(a-s),f=r+u*(i-t);return[h,m,p,f]}function v0t(s,t){const n=s.length,r=[];for(let a=2;a=0){const c=Math.sqrt(o);n.push((-i+c)/(2*a)),n.push((-i-c)/(2*a))}}}return n.filter(r=>r>0&&r<1).flatMap(r=>t.map(a=>{const i=1-r;return i*i*i*a[0]+3*i*i*r*a[1]+3*i*r*r*a[2]+r*r*r*a[3]}))}let vE=class extends Qa{constructor(t){super(t),this.on("pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva",function(){this._clearCache("tensionPoints")})}_sceneFunc(t){const n=this.points(),r=n.length,a=this.tension(),i=this.closed(),l=this.bezier();if(!r)return;let o=0;if(t.beginPath(),t.moveTo(n[0],n[1]),a!==0&&r>4){const c=this.getTensionPoints(),d=c.length;for(o=i?0:4,i||t.quadraticCurveTo(c[0],c[1],c[2],c[3]);o{let r,a;const l=n/2;r=0;for(let o=0;o<20;o++)a=l*JJs[20][o]+l,r+=een[20][o]*sen(s,t,a);return l*r},_0t=(s,t,n)=>{n===void 0&&(n=1);const r=s[0]-2*s[1]+s[2],a=t[0]-2*t[1]+t[2],i=2*s[1]-2*s[0],l=2*t[1]-2*t[0],o=4*(r*r+a*a),c=4*(r*i+a*l),d=i*i+l*l;if(o===0)return n*Math.sqrt(Math.pow(s[2]-s[0],2)+Math.pow(t[2]-t[0],2));const u=c/(2*o),h=d/o,m=n+u,p=h-u*u,f=m*m+p>0?Math.sqrt(m*m+p):0,x=u*u+p>0?Math.sqrt(u*u+p):0,y=u+Math.sqrt(u*u+p)!==0?p*Math.log(Math.abs((m+f)/(u+x))):0;return Math.sqrt(o)/2*(m*f-u*x+y)};function sen(s,t,n){const r=sVe(1,n,s),a=sVe(1,n,t),i=r*r+a*a;return Math.sqrt(i)}const sVe=(s,t,n)=>{const r=n.length-1;let a,i;if(r===0)return 0;if(s===0){i=0;for(let l=0;l<=r;l++)i+=ten[r][l]*Math.pow(1-t,r-l)*Math.pow(t,l)*n[l];return i}else{a=new Array(r);for(let l=0;l{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};let I2=class Jb extends Qa{constructor(t){super(t),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=Jb.parsePathData(this.data()),this.pathLength=Jb.getPathLength(this.dataArray)}_sceneFunc(t){const n=this.dataArray;t.beginPath();let r=!1;for(let a=0;au?d:u,y=d>u?1:d/u,v=d>u?u/d:1;t.translate(o,c),t.rotate(p),t.scale(y,v),t.arc(0,0,x,h,h+m,1-f),t.scale(1/y,1/v),t.rotate(-p),t.translate(-o,-c);break;case"z":r=!0,t.closePath();break}}!r&&!this.hasFill()?t.strokeShape(this):t.fillStrokeShape(this)}getSelfRect(){let t=[];this.dataArray.forEach(function(c){if(c.command==="A"){const d=c.points[4],u=c.points[5],h=c.points[4]+u;let m=Math.PI/180;if(Math.abs(d-h)h;p-=m){const f=Jb.getPointOnEllipticalArc(c.points[0],c.points[1],c.points[2],c.points[3],p,0);t.push(f.x,f.y)}else for(let p=d+m;pn[a].pathLength;)t-=n[a].pathLength,++a;if(a===i)return r=n[a-1].points.slice(-2),{x:r[0],y:r[1]};if(t<.01)return n[a].command==="M"?(r=n[a].points.slice(0,2),{x:r[0],y:r[1]}):{x:n[a].start.x,y:n[a].start.y};const l=n[a],o=l.points;switch(l.command){case"L":return Jb.getPointOnLine(t,l.start.x,l.start.y,o[0],o[1]);case"C":return Jb.getPointOnCubicBezier(w0t(t,Jb.getPathLength(n),x=>b0t([l.start.x,o[0],o[2],o[4]],[l.start.y,o[1],o[3],o[5]],x)),l.start.x,l.start.y,o[0],o[1],o[2],o[3],o[4],o[5]);case"Q":return Jb.getPointOnQuadraticBezier(w0t(t,Jb.getPathLength(n),x=>_0t([l.start.x,o[0],o[2]],[l.start.y,o[1],o[3]],x)),l.start.x,l.start.y,o[0],o[1],o[2],o[3]);case"A":const c=o[0],d=o[1],u=o[2],h=o[3],m=o[5],p=o[6];let f=o[4];return f+=m*t/l.pathLength,Jb.getPointOnEllipticalArc(c,d,u,h,f,p)}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))*(a=0&&(x+=2,x>=7&&(x-=7));continue}if(x>=0){if(x===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(b)){f.push(parseInt(b[0],10)),f.push(parseInt(b[1],10)),f.push(parseFloat(b.slice(2))),x+=3,x>=7&&(x-=7);continue}if(b==="11"||b==="10"||b==="01"){f.push(parseInt(b[0],10)),f.push(parseInt(b[1],10)),x+=2,x>=7&&(x-=7);continue}if(b==="0"||b==="1"){f.push(parseInt(b,10)),x+=1,x>=7&&(x-=7);continue}}else if(x===4){if(/^[01]\d+(?:\.\d+)?$/.test(b)){f.push(parseInt(b[0],10)),f.push(parseFloat(b.slice(1))),x+=2,x>=7&&(x-=7);continue}if(b==="0"||b==="1"){f.push(parseInt(b,10)),x+=1,x>=7&&(x-=7);continue}}const N=parseFloat(b);isNaN(N)?f.push(0):f.push(N),x+=1,x>=7&&(x-=7)}else{const N=parseFloat(b);isNaN(N)?f.push(0):f.push(N)}}for(;f.length>0&&!isNaN(f[0]);){let y="",v=[];const b=o,N=c;let S,A,T,L,M,I,R,z,$,H;switch(p){case"l":o+=f.shift(),c+=f.shift(),y="L",v.push(o,c);break;case"L":o=f.shift(),c=f.shift(),v.push(o,c);break;case"m":const V=f.shift(),K=f.shift();if(o+=V,c+=K,y="M",i.length>2&&i[i.length-1].command==="z"){for(let Z=i.length-2;Z>=0;Z--)if(i[Z].command==="M"){o=i[Z].points[0]+V,c=i[Z].points[1]+K;break}}v.push(o,c),p="l";break;case"M":o=f.shift(),c=f.shift(),y="M",v.push(o,c),p="L";break;case"h":o+=f.shift(),y="L",v.push(o,c);break;case"H":o=f.shift(),y="L",v.push(o,c);break;case"v":c+=f.shift(),y="L",v.push(o,c);break;case"V":c=f.shift(),y="L",v.push(o,c);break;case"C":v.push(f.shift(),f.shift(),f.shift(),f.shift()),o=f.shift(),c=f.shift(),v.push(o,c);break;case"c":v.push(o+f.shift(),c+f.shift(),o+f.shift(),c+f.shift()),o+=f.shift(),c+=f.shift(),y="C",v.push(o,c);break;case"S":A=o,T=c,S=i[i.length-1],S.command==="C"&&(A=o+(o-S.points[2]),T=c+(c-S.points[3])),v.push(A,T,f.shift(),f.shift()),o=f.shift(),c=f.shift(),y="C",v.push(o,c);break;case"s":A=o,T=c,S=i[i.length-1],S.command==="C"&&(A=o+(o-S.points[2]),T=c+(c-S.points[3])),v.push(A,T,o+f.shift(),c+f.shift()),o+=f.shift(),c+=f.shift(),y="C",v.push(o,c);break;case"Q":v.push(f.shift(),f.shift()),o=f.shift(),c=f.shift(),v.push(o,c);break;case"q":v.push(o+f.shift(),c+f.shift()),o+=f.shift(),c+=f.shift(),y="Q",v.push(o,c);break;case"T":A=o,T=c,S=i[i.length-1],S.command==="Q"&&(A=o+(o-S.points[0]),T=c+(c-S.points[1])),o=f.shift(),c=f.shift(),y="Q",v.push(A,T,o,c);break;case"t":A=o,T=c,S=i[i.length-1],S.command==="Q"&&(A=o+(o-S.points[0]),T=c+(c-S.points[1])),o+=f.shift(),c+=f.shift(),y="Q",v.push(A,T,o,c);break;case"A":L=f.shift(),M=f.shift(),I=f.shift(),R=f.shift(),z=f.shift(),$=o,H=c,o=f.shift(),c=f.shift(),y="A",v=this.convertEndpointToCenterParameterization($,H,o,c,R,z,L,M,I);break;case"a":L=f.shift(),M=f.shift(),I=f.shift(),R=f.shift(),z=f.shift(),$=o,H=c,o+=f.shift(),c+=f.shift(),y="A",v=this.convertEndpointToCenterParameterization($,H,o,c,R,z,L,M,I);break}i.push({command:y||p,points:v,start:{x:b,y:N},pathLength:this.calcLength(b,N,y||p,v)})}(p==="z"||p==="Z")&&i.push({command:"z",points:[],start:void 0,pathLength:0})}return i}static calcLength(t,n,r,a){let i,l,o,c;const d=Jb;switch(r){case"L":return d.getLineLength(t,n,a[0],a[1]);case"C":return b0t([t,a[0],a[2],a[4]],[n,a[1],a[3],a[5]],1);case"Q":return _0t([t,a[0],a[2]],[n,a[1],a[3]],1);case"A":i=0;const u=a[4],h=a[5],m=a[4]+h;let p=Math.PI/180;if(Math.abs(u-m)m;c-=p)o=d.getPointOnEllipticalArc(a[0],a[1],a[2],a[3],c,0),i+=d.getLineLength(l.x,l.y,o.x,o.y),l=o;else for(c=u+p;c1&&(o*=Math.sqrt(p),c*=Math.sqrt(p));let f=Math.sqrt((o*o*(c*c)-o*o*(m*m)-c*c*(h*h))/(o*o*(m*m)+c*c*(h*h)));i===l&&(f*=-1),isNaN(f)&&(f=0);const x=f*o*m/c,y=f*-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,N=function(R){return Math.sqrt(R[0]*R[0]+R[1]*R[1])},S=function(R,z){return(R[0]*z[0]+R[1]*z[1])/(N(R)*N(z))},A=function(R,z){return(R[0]*z[1]=1&&(I=0),l===0&&I>0&&(I=I-2*Math.PI),l===1&&I<0&&(I=I+2*Math.PI),[v,b,o,c,T,I,u,l]}};I2.prototype.className="Path";I2.prototype._attrsAffectingSize=["data"];Lf(I2);mn.addGetterSetter(I2,"data");class _9 extends vE{_sceneFunc(t){super._sceneFunc(t);const n=Math.PI*2,r=this.points();let a=r;const i=this.tension()!==0&&r.length>4;i&&(a=this.getTensionPoints());const l=this.pointerLength(),o=r.length;let c,d;if(i){const m=[a[a.length-4],a[a.length-3],a[a.length-2],a[a.length-1],r[o-2],r[o-1]],p=I2.calcLength(a[a.length-4],a[a.length-3],"C",m),f=I2.getPointOnQuadraticBezier(Math.min(1,1-l/p),m[0],m[1],m[2],m[3],m[4],m[5]);c=r[o-2]-f.x,d=r[o-1]-f.y}else c=r[o-2]-r[o-4],d=r[o-1]-r[o-3];const u=(Math.atan2(d,c)+n)%n,h=this.pointerWidth();this.pointerAtEnding()&&(t.save(),t.beginPath(),t.translate(r[o-2],r[o-1]),t.rotate(u),t.moveTo(0,0),t.lineTo(-l,h/2),t.lineTo(-l,-h/2),t.closePath(),t.restore(),this.__fillStroke(t)),this.pointerAtBeginning()&&(t.save(),t.beginPath(),t.translate(r[0],r[1]),i?(c=(a[0]+a[2])/2-r[0],d=(a[1]+a[3])/2-r[1]):(c=r[2]-r[0],d=r[3]-r[1]),t.rotate((Math.atan2(-d,-c)+n)%n),t.moveTo(0,0),t.lineTo(-l,h/2),t.lineTo(-l,-h/2),t.closePath(),t.restore(),this.__fillStroke(t))}__fillStroke(t){const n=this.dashEnabled();n&&(this.attrs.dashEnabled=!1,t.setLineDash([])),t.fillStrokeShape(this),n&&(this.attrs.dashEnabled=!0)}getSelfRect(){const t=super.getSelfRect(),n=this.pointerWidth()/2;return{x:t.x,y:t.y-n,width:t.width,height:t.height+n*2}}}_9.prototype.className="Arrow";Lf(_9);mn.addGetterSetter(_9,"pointerLength",10,oi());mn.addGetterSetter(_9,"pointerWidth",10,oi());mn.addGetterSetter(_9,"pointerAtBeginning",!1);mn.addGetterSetter(_9,"pointerAtEnding",!0);class LG extends Qa{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.attrs.radius||0,0,Math.PI*2,!1),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(t){this.radius()!==t/2&&this.radius(t/2)}setHeight(t){this.radius()!==t/2&&this.radius(t/2)}}LG.prototype._centroid=!0;LG.prototype.className="Circle";LG.prototype._attrsAffectingSize=["radius"];Lf(LG);mn.addGetterSetter(LG,"radius",0,oi());class JP extends Qa{_sceneFunc(t){const n=this.radiusX(),r=this.radiusY();t.beginPath(),t.save(),n!==r&&t.scale(1,r/n),t.arc(0,0,n,0,Math.PI*2,!1),t.restore(),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.radiusX()*2}getHeight(){return this.radiusY()*2}setWidth(t){this.radiusX(t/2)}setHeight(t){this.radiusY(t/2)}}JP.prototype.className="Ellipse";JP.prototype._centroid=!0;JP.prototype._attrsAffectingSize=["radiusX","radiusY"];Lf(JP);mn.addComponentsGetterSetter(JP,"radius",["x","y"]);mn.addGetterSetter(JP,"radiusX",0,oi());mn.addGetterSetter(JP,"radiusY",0,oi());let SS=class tUt extends Qa{constructor(t){super(t),this._loadListener=()=>{this._requestDraw()},this.on("imageChange.konva",n=>{this._removeImageLoad(n.oldVal),this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){const t=this.image();t&&t.complete||t&&t.readyState===4||t&&t.addEventListener&&t.addEventListener("load",this._loadListener)}_removeImageLoad(t){t&&t.removeEventListener&&t.removeEventListener("load",this._loadListener)}destroy(){return this._removeImageLoad(this.image()),super.destroy(),this}_useBufferCanvas(){const t=!!this.cornerRadius(),n=this.hasShadow();return t&&n?!0:super._useBufferCanvas(!0)}_sceneFunc(t){const n=this.getWidth(),r=this.getHeight(),a=this.cornerRadius(),i=this.attrs.image;let l;if(i){const o=this.attrs.cropWidth,c=this.attrs.cropHeight;o&&c?l=[i,this.cropX(),this.cropY(),o,c,0,0,n,r]:l=[i,0,0,n,r]}(this.hasFill()||this.hasStroke()||a)&&(t.beginPath(),a?sr.drawRoundedRectPath(t,n,r,a):t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)),i&&(a&&t.clip(),t.drawImage.apply(t,l))}_hitFunc(t){const n=this.width(),r=this.height(),a=this.cornerRadius();t.beginPath(),a?sr.drawRoundedRectPath(t,n,r,a):t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)}getWidth(){var t,n,r;return(r=(t=this.attrs.width)!==null&&t!==void 0?t:(n=this.image())===null||n===void 0?void 0:n.width)!==null&&r!==void 0?r:0}getHeight(){var t,n,r;return(r=(t=this.attrs.height)!==null&&t!==void 0?t:(n=this.image())===null||n===void 0?void 0:n.height)!==null&&r!==void 0?r:0}static fromURL(t,n,r=null){const a=sr.createImageElement();a.onload=function(){const i=new tUt({image:a});n(i)},a.onerror=r,a.crossOrigin="Anonymous",a.src=t}};SS.prototype.className="Image";SS.prototype._attrsAffectingSize=["image"];Lf(SS);mn.addGetterSetter(SS,"cornerRadius",0,DPe(4));mn.addGetterSetter(SS,"image");mn.addComponentsGetterSetter(SS,"crop",["x","y","width","height"]);mn.addGetterSetter(SS,"cropX",0,oi());mn.addGetterSetter(SS,"cropY",0,oi());mn.addGetterSetter(SS,"cropWidth",0,oi());mn.addGetterSetter(SS,"cropHeight",0,oi());const sUt=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],nen="Change.konva",ren="none",nVe="up",rVe="right",aVe="down",iVe="left",aen=sUt.length;let net=class extends JV{constructor(t){super(t),this.on("add.konva",function(n){this._addListeners(n.child),this._sync()})}getText(){return this.find("Text")[0]}getTag(){return this.find("Tag")[0]}_addListeners(t){let n=this,r;const a=function(){n._sync()};for(r=0;r{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)}}eL.prototype.className="RegularPolygon";eL.prototype._centroid=!0;eL.prototype._attrsAffectingSize=["radius"];Lf(eL);mn.addGetterSetter(eL,"radius",0,oi());mn.addGetterSetter(eL,"sides",0,oi());mn.addGetterSetter(eL,"cornerRadius",0,DPe(4));const j0t=Math.PI*2;class j9 extends Qa{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.innerRadius(),0,j0t,!1),t.moveTo(this.outerRadius(),0),t.arc(0,0,this.outerRadius(),j0t,0,!0),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(t){this.outerRadius(t/2)}setHeight(t){this.outerRadius(t/2)}}j9.prototype.className="Ring";j9.prototype._centroid=!0;j9.prototype._attrsAffectingSize=["innerRadius","outerRadius"];Lf(j9);mn.addGetterSetter(j9,"innerRadius",0,oi());mn.addGetterSetter(j9,"outerRadius",0,oi());class u3 extends Qa{constructor(t){super(t),this._updated=!0,this.anim=new L2(()=>{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())})}_sceneFunc(t){const n=this.animation(),r=this.frameIndex(),a=r*4,i=this.animations()[n],l=this.frameOffsets(),o=i[a+0],c=i[a+1],d=i[a+2],u=i[a+3],h=this.image();if((this.hasFill()||this.hasStroke())&&(t.beginPath(),t.rect(0,0,d,u),t.closePath(),t.fillStrokeShape(this)),h)if(l){const m=l[n],p=r*2;t.drawImage(h,o,c,d,u,m[p+0],m[p+1],d,u)}else t.drawImage(h,o,c,d,u,0,0,d,u)}_hitFunc(t){const n=this.animation(),r=this.frameIndex(),a=r*4,i=this.animations()[n],l=this.frameOffsets(),o=i[a+2],c=i[a+3];if(t.beginPath(),l){const d=l[n],u=r*2;t.rect(d[u+0],d[u+1],o,c)}else t.rect(0,0,o,c);t.closePath(),t.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){const t=this;this.interval=setInterval(function(){t._updateIndex()},1e3/this.frameRate())}start(){if(this.isRunning())return;const t=this.getLayer();this.anim.setLayers(t),this._setInterval(),this.anim.start()}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){const t=this.frameIndex(),n=this.animation(),r=this.animations(),a=r[n],i=a.length/4;t{if(new RegExp("\\p{Emoji}","u").test(n)){const i=a[r+1];i&&new RegExp("\\p{Emoji_Modifier}|\\u200D","u").test(i)?(t.push(n+i),a[r+1]=""):t.push(n)}else new RegExp("\\p{Regional_Indicator}{2}","u").test(n+(a[r+1]||""))?t.push(n+a[r+1]):r>0&&new RegExp("\\p{Mn}|\\p{Me}|\\p{Mc}","u").test(n)?t[t.length-1]+=n:n&&t.push(n);return t},[])}const Qz="auto",ien="center",nUt="inherit",oY="justify",oen="Change.konva",rUt="2d",N0t="-",aUt="left",len="text",cen="Text",den="top",uen="bottom",k0t="middle",iUt="normal",hen="px ",hle=" ",men="right",S0t="rtl",pen="word",fen="char",C0t="none",GFe="…",oUt=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],gen=oUt.length;let lY=null;function xen(){if(lY!==null)return lY;lY=!1;try{const s=document.createElement("canvas");s.width=10,s.height=10;const t=s.getContext(rUt);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){lY=!0;break}}}catch{}return lY}function yen(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 mle;function WFe(){return mle||(mle=sr.createCanvasElement().getContext(rUt),mle)}function ven(s){s.fillText(this._partialText,this._partialTextX,this._partialTextY)}function ben(s){s.setAttr("miterLimit",2),s.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function _en(s){return s=s||{},!s.fillLinearGradientColorStops&&!s.fillRadialGradientColorStops&&!s.fillPatternImage&&(s.fill=s.fill||"black"),s}let Om=class extends Qa{constructor(t){super(_en(t)),this._partialTextX=0,this._partialTextY=0;for(let n=0;nie+TT(ce.text).length,0),ne=Q+se;x({char:le,index:ne,x:M,y:T+I,lineIndex:A,column:Q,isLastInLine:H,width:this.measureSize(le).width,context:t})}t.fillStrokeShape(this),x&&t.restore(),M+=this.measureSize(le).width+f}}else f!==0&&t.setAttr("letterSpacing",`${f}px`),this._partialTextX=M,this._partialTextY=T+I,this._partialText=z,t.fillStrokeShape(this);if(S){t.save(),t.beginPath();const K=fi.legacyTextRendering?0:-Math.round(o/4),Z=V;t.moveTo(Z,T+I+K);const Q=m===oY&&!H?p-l*2:$;t.lineTo(Z+Math.round(Q),T+I+K),t.lineWidth=o/15;const le=this._getLinearGradient();t.strokeStyle=le||y,t.stroke(),t.restore()}t.restore(),i>1&&(T+=c)}}_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=sr._isString(t)?t:t==null?"":t+"";return this._setAttr(len,n),this}getWidth(){return this.attrs.width===Qz||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===Qz||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return sr.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 p=WFe(),f=this.fontSize(),x;p.save(),p.font=this._getContextFont(),x=p.measureText(t),p.restore();const y=f/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:f}}_getContextFont(){return this.fontStyle()+hle+this.fontVariant()+hle+(this.fontSize()+hen)+yen(this.fontFamily())}_addTextLine(t){this.align()===oY&&(t=t.trim());const r=this._getTextWidth(t);return this.textArr.push({text:t,width:r,lastInParagraph:!1})}_getTextWidth(t){const n=this.letterSpacing(),r=t.length;return WFe().measureText(t).width+n*r}_setTextData(){let t=this.text().split(` `),n=+this.fontSize(),r=0,a=this.lineHeight()*n,i=this.attrs.width,l=this.attrs.height,o=i!==Qz&&i!==void 0,c=l!==Qz&&l!==void 0,d=this.padding(),u=i-d*2,h=l-d*2,m=0,p=this.wrap(),f=p!==C0t,x=p!==fen&&f,y=this.ellipsis();this.textArr=[],WFe().font=this._getContextFont();const v=y?this._getTextWidth(GFe):0;for(let b=0,N=t.length;bu)for(;S.length>0;){let T=0,L=TT(S).length,M="",I=0;for(;T>>1,z=TT(S),$=z.slice(0,R+1).join(""),H=this._getTextWidth($);(y&&c&&m+a>h?H+v:H)<=u?(T=R+1,M=$,I=H):L=R}if(M){if(x){const $=TT(S),H=TT(M),V=$[H.length],K=V===hle||V===N0t;let Z;if(K&&I<=u)Z=H.length;else{const Q=H.lastIndexOf(hle),le=H.lastIndexOf(N0t);Z=Math.max(Q,le)+1}Z>0&&(T=Z,M=$.slice(0,T).join(""),I=this._getTextWidth(M))}if(M=M.trimRight(),this._addTextLine(M),r=Math.max(r,I),m+=a,this._shouldHandleEllipsis(m)){this._tryToAddEllipsisToLastLine();break}if(S=TT(S).slice(T).join("").trimLeft(),S.length>0&&(A=this._getTextWidth(S),A<=u)){this._addTextLine(S),m+=a,r=Math.max(r,A);break}}else break}else this._addTextLine(S),m+=a,r=Math.max(r,A),this._shouldHandleEllipsis(m)&&bh)break}this.textHeight=n,this.textWidth=r}_shouldHandleEllipsis(t){const n=+this.fontSize(),r=this.lineHeight()*n,a=this.attrs.height,i=a!==Qz&&a!==void 0,l=this.padding(),o=a-l*2;return!(this.wrap()!==C0t)||i&&t+r>o}_tryToAddEllipsisToLastLine(){const t=this.attrs.width,n=t!==Qz&&t!==void 0,r=this.padding(),a=t-r*2,i=this.ellipsis(),l=this.textArr[this.textArr.length-1];!l||!i||(n&&(this._getTextWidth(l.text+GFe)n?null:I2.getPointAtLengthOfDataArray(t,this.dataArray)}_readDataAttribute(){this.dataArray=I2.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;rthis.pathLength&&v-this.pathLength<=d?this.pathLength:v);if(!b)return;const N=I2.getLineLength(f.x,f.y,b.x,b.y);let S=0;if(c)try{S=c(n[p-1].char,x)*this.fontSize()}catch{S=0}f.x+=S,b.x+=S,this.textWidth+=S;const A=I2.getPointOnLine(S+N/2,f.x,f.y,b.x,b.y),T=Math.atan2(b.y-f.y,b.x-f.x);this.glyphInfo.push({transposeX:A.x,transposeY:A.y,text:t[p],rotation:T,p0:f,p1:b,width:N}),m+=y}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};const t=[];this.glyphInfo.forEach(function(d){t.push(d.p0.x),t.push(d.p0.y),t.push(d.p1.x),t.push(d.p1.y)});let n=t[0]||0,r=t[0]||0,a=t[1]||0,i=t[1]||0,l,o;for(let d=0;ds+`.${uUt}`).join(" "),A0t="nodesRect",Nen=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],ken={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},Sen="ontouchstart"in fi._global;function Cen(s,t,n){if(s==="rotater")return n;t+=sr.degToRad(ken[s]||0);const r=(sr.radToDeg(t)%360+360)%360;return sr._inRange(r,315+22.5,360)||sr._inRange(r,0,22.5)?"ns-resize":sr._inRange(r,45-22.5,45+22.5)?"nesw-resize":sr._inRange(r,90-22.5,90+22.5)?"ew-resize":sr._inRange(r,135-22.5,135+22.5)?"nwse-resize":sr._inRange(r,180-22.5,180+22.5)?"ns-resize":sr._inRange(r,225-22.5,225+22.5)?"nesw-resize":sr._inRange(r,270-22.5,270+22.5)?"ew-resize":sr._inRange(r,315-22.5,315+22.5)?"nwse-resize":(sr.error("Transformer has unknown angle for cursor detection: "+r),"pointer")}const jAe=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"],E0t=1e8;function Aen(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 hUt(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 Een(s,t){const n=Aen(s);return hUt(s,t,n)}function Ten(s,t,n){let r=t;for(let a=0;aa.isAncestorOf(this)?(sr.error("Konva.Transformer cannot be an a child of the node you are trying to attach"),!1):!0);return this._nodes=t=n,t.length===1&&this.useSingleNodeRotation()?this.rotation(t[0].getAbsoluteRotation()):this.rotation(0),this._nodes.forEach(a=>{const i=()=>{this.nodes().length===1&&this.useSingleNodeRotation()&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),!this._transforming&&!this.isDragging()&&this.update()};if(a._attrsAffectingSize.length){const l=a._attrsAffectingSize.map(o=>o+"Change."+this._getEventNamespace()).join(" ");a.on(l,i)}a.on(Nen.map(l=>l+`.${this._getEventNamespace()}`).join(" "),i),a.on(`absoluteTransformChange.${this._getEventNamespace()}`,i),this._proxyDrag(a)}),this._resetTransformCache(),!!this.findOne(".top-left")&&this.update(),this}_proxyDrag(t){let n;t.on(`dragstart.${this._getEventNamespace()}`,r=>{n=t.getAbsolutePosition(),!this.isDragging()&&t!==this.findOne(".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(){this._nodes&&this._nodes.forEach(t=>{t.off("."+this._getEventNamespace())}),this._nodes=[],this._resetTransformCache()}_resetTransformCache(){this._clearCache(A0t),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(A0t,this.__getNodeRect)}__getNodeShape(t,n=this.rotation(),r){const a=t.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),i=t.getAbsoluteScale(r),l=t.getAbsolutePosition(r),o=a.x*i.x-t.offsetX()*i.x,c=a.y*i.y-t.offsetY()*i.y,d=(fi.getAngle(t.getAbsoluteRotation())+Math.PI*2)%(Math.PI*2),u={x:l.x+o*Math.cos(d)+c*Math.sin(-d),y:l.y+c*Math.cos(d)+o*Math.sin(d),width:a.width*i.x,height:a.height*i.y,rotation:d};return hUt(u,-fi.getAngle(n),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-E0t,y:-E0t,width:0,height:0,rotation:0};const n=[];this.nodes().map(d=>{const u=d.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),h=[{x:u.x,y:u.y},{x:u.x+u.width,y:u.y},{x:u.x+u.width,y:u.y+u.height},{x:u.x,y:u.y+u.height}],m=d.getAbsoluteTransform();h.forEach(function(p){const f=m.point(p);n.push(f)})});const r=new Bw;r.rotate(-fi.getAngle(this.rotation()));let a=1/0,i=1/0,l=-1/0,o=-1/0;n.forEach(function(d){const u=r.point(d);a===void 0&&(a=l=u.x,i=o=u.y),a=Math.min(a,u.x),i=Math.min(i,u.y),l=Math.max(l,u.x),o=Math.max(o,u.y)}),r.invert();const c=r.point({x:a,y:i});return{x:c.x,y:c.y,width:l-a,height:o-i,rotation:fi.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(),jAe.forEach(t=>{this._createAnchor(t)}),this._createAnchor("rotater"),this._elementsCreated=!0}_createAnchor(t){const n=new kre({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:t+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:Sen?10:"auto"}),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",()=>{const a=fi.getAngle(this.rotation()),i=this.rotateAnchorCursor(),l=Cen(t,a,i);n.getStage().content&&(n.getStage().content.style.cursor=l),this._cursorChange=!0}),n.on("mouseout",()=>{n.getStage().content&&(n.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(n)}_createBack(){const t=new Qa({name:"back",width:0,height:0,sceneFunc(n,r){const a=r.getParent(),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=a.rotateAnchorAngle(),d=a.rotateAnchorOffset(),u=sr.degToRad(c),h=Math.sin(u),m=-Math.cos(u),p=l/2,f=o/2;let x=1/0;m<0?x=Math.min(x,-f/m):m>0&&(x=Math.min(x,(o-f)/m)),h<0?x=Math.min(x,-p/h):h>0&&(x=Math.min(x,(l-p)/h));const y=p+h*x,v=f+m*x,b=sr._sign(o),N=y+h*d*b,S=v+m*d*b;n.moveTo(y,v),n.lineTo(N,S)}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.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){if(this._transforming)return;this._movingAnchorName=t.target.name().split(" ")[0];const n=this._getNodeRect(),r=n.width,a=n.height,i=Math.sqrt(Math.pow(r,2)+Math.pow(a,2));this.sin=Math.abs(a/i),this.cos=Math.abs(r/i),typeof window<"u"&&(window.addEventListener("mousemove",this._handleMouseMove),window.addEventListener("touchmove",this._handleMouseMove),window.addEventListener("mouseup",this._handleMouseUp,!0),window.addEventListener("touchend",this._handleMouseUp,!0)),this._transforming=!0;const l=t.target.getAbsolutePosition(),o=t.target.getStage().getPointerPosition();this._anchorDragOffset={x:o.x-l.x,y:o.y-l.y},oVe++,this._fire("transformstart",{evt:t.evt,target:this.getNode()}),this._nodes.forEach(c=>{c._fire("transformstart",{evt:t.evt,target:c})})}_handleMouseMove(t){let n,r,a;const i=this.findOne("."+this._movingAnchorName),l=i.getStage();l.setPointersPositions(t);const o=l.getPointerPosition();let c={x:o.x-this._anchorDragOffset.x,y:o.y-this._anchorDragOffset.y};const d=i.getAbsolutePosition();this.anchorDragBoundFunc()&&(c=this.anchorDragBoundFunc()(d,c,t)),i.setAbsolutePosition(c);const u=i.getAbsolutePosition();if(d.x===u.x&&d.y===u.y)return;if(this._movingAnchorName==="rotater"){const b=this._getNodeRect();n=i.x()-b.width/2,r=-i.y()+b.height/2;const N=fi.getAngle(this.rotateAnchorAngle());let S=Math.atan2(-r,n)+Math.PI/2-N;b.height<0&&(S-=Math.PI);const T=fi.getAngle(this.rotation())+S,L=fi.getAngle(this.rotationSnapTolerance()),I=Ten(this.rotationSnaps(),T,L)-b.rotation,R=Een(b,I);this._fitNodesInto(R,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 p=this.centeredScaling()||t.altKey;if(this._movingAnchorName==="top-left"){if(m){const b=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};a=Math.sqrt(Math.pow(b.x-i.x(),2)+Math.pow(b.y-i.y(),2));const N=this.findOne(".top-left").x()>b.x?-1:1,S=this.findOne(".top-left").y()>b.y?-1:1;n=a*this.cos*N,r=a*this.sin*S,this.findOne(".top-left").x(b.x-n),this.findOne(".top-left").y(b.y-r)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(i.y());else if(this._movingAnchorName==="top-right"){if(m){const b=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};a=Math.sqrt(Math.pow(i.x()-b.x,2)+Math.pow(b.y-i.y(),2));const N=this.findOne(".top-right").x()b.y?-1:1;n=a*this.cos*N,r=a*this.sin*S,this.findOne(".top-right").x(b.x+n),this.findOne(".top-right").y(b.y-r)}var f=i.position();this.findOne(".top-left").y(f.y),this.findOne(".bottom-right").x(f.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(i.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(i.x());else if(this._movingAnchorName==="bottom-left"){if(m){const b=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};a=Math.sqrt(Math.pow(b.x-i.x(),2)+Math.pow(i.y()-b.y,2));const N=b.x{var i;a._fire("transformend",{evt:t,target:a}),(i=a.getLayer())===null||i===void 0||i.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(t,n){const r=this._getNodeRect(),a=1;if(sr._inRange(t.width,-this.padding()*2-a,a)){this.update();return}if(sr._inRange(t.height,-this.padding()*2-a,a)){this.update();return}const i=new Bw;if(i.rotate(fi.getAngle(this.rotation())),this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("left")>=0){const m=i.point({x:-this.padding()*2,y:0});t.x+=m.x,t.y+=m.y,t.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=m.x,this._anchorDragOffset.y-=m.y}else if(this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("right")>=0){const m=i.point({x:this.padding()*2,y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=m.x,this._anchorDragOffset.y-=m.y,t.width+=this.padding()*2}if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("top")>=0){const m=i.point({x:0,y:-this.padding()*2});t.x+=m.x,t.y+=m.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=m.x,this._anchorDragOffset.y-=m.y,t.height+=this.padding()*2}else if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const m=i.point({x:0,y:this.padding()*2});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=m.x,this._anchorDragOffset.y-=m.y,t.height+=this.padding()*2}if(this.boundBoxFunc()){const m=this.boundBoxFunc()(r,t);m?t=m:sr.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const l=1e7,o=new Bw;o.translate(r.x,r.y),o.rotate(r.rotation),o.scale(r.width/l,r.height/l);const c=new Bw,d=t.width/l,u=t.height/l;this.flipEnabled()===!1?(c.translate(t.x,t.y),c.rotate(t.rotation),c.translate(t.width<0?t.width:0,t.height<0?t.height:0),c.scale(Math.abs(d),Math.abs(u))):(c.translate(t.x,t.y),c.rotate(t.rotation),c.scale(d,u));const h=c.multiply(o.invert());this._nodes.forEach(m=>{var p;if(!m.getStage())return;const f=m.getParent().getAbsoluteTransform(),x=m.getTransform().copy();x.translate(m.offsetX(),m.offsetY());const y=new Bw;y.multiply(f.copy().invert()).multiply(h).multiply(f).multiply(x);const v=y.decompose();m.setAttrs(v),(p=m.getLayer())===null||p===void 0||p.batchDraw()}),this.rotation(sr._getRotation(t.rotation)),this._nodes.forEach(m=>{this._fire("transform",{evt:n,target:m}),m._fire("transform",{evt:n,target:m})}),this._resetTransformCache(),this.update(),this.getLayer().batchDraw()}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(t,n){this.findOne(t).setAttrs(n)}update(){var t;const n=this._getNodeRect();this.rotation(sr._getRotation(n.rotation));const r=n.width,a=n.height,i=this.enabledAnchors(),l=this.resizeEnabled(),o=this.padding(),c=this.anchorSize(),d=this.find("._anchor");d.forEach(T=>{T.setAttrs({width:c,height:c,offsetX:c/2,offsetY:c/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:c/2+o,offsetY:c/2+o,visible:l&&i.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:r/2,y:0,offsetY:c/2+o,visible:l&&i.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:r,y:0,offsetX:c/2-o,offsetY:c/2+o,visible:l&&i.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:a/2,offsetX:c/2+o,visible:l&&i.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:r,y:a/2,offsetX:c/2-o,visible:l&&i.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:a,offsetX:c/2+o,offsetY:c/2-o,visible:l&&i.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:r/2,y:a,offsetY:c/2-o,visible:l&&i.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:r,y:a,offsetX:c/2-o,offsetY:c/2-o,visible:l&&i.indexOf("bottom-right")>=0});const u=this.rotateAnchorAngle(),h=this.rotateAnchorOffset(),m=sr.degToRad(u),p=Math.sin(m),f=-Math.cos(m),x=r/2,y=a/2;let v=1/0;f<0?v=Math.min(v,-y/f):f>0&&(v=Math.min(v,(a-y)/f)),p<0?v=Math.min(v,-x/p):p>0&&(v=Math.min(v,(r-x)/p));const b=x+p*v,N=y+f*v,S=sr._sign(a);this._batchChangeChild(".rotater",{x:b+p*h*S,y:N+f*h*S-o*f,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:r,height:a,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),draggable:this.nodes().some(T=>T.draggable()),x:0,y:0});const A=this.anchorStyleFunc();A&&d.forEach(T=>{A(T)}),(t=this.getLayer())===null||t===void 0||t.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();const t=this.findOne("."+this._movingAnchorName);t&&t.stopDrag()}}destroy(){return this.getStage()&&this._cursorChange&&this.getStage().content&&(this.getStage().content.style.cursor=""),JV.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}add(...t){return this._elementsCreated?(sr.error("You cannot add external nodes to the Transformer. Use tr.nodes([node]) instead."),this):super.add(...t)}toObject(){return bi.prototype.toObject.call(this)}clone(t){return bi.prototype.clone.call(this,t)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}};Fd.isTransforming=()=>oVe>0;function Men(s){return s instanceof Array||sr.warn("enabledAnchors value should be an array"),s instanceof Array&&s.forEach(function(t){jAe.indexOf(t)===-1&&sr.warn("Unknown anchor name: "+t+". Available names are: "+jAe.join(", "))}),s||[]}Fd.prototype.className="Transformer";Lf(Fd);mn.addGetterSetter(Fd,"enabledAnchors",jAe,Men);mn.addGetterSetter(Fd,"flipEnabled",!0,kS());mn.addGetterSetter(Fd,"resizeEnabled",!0);mn.addGetterSetter(Fd,"anchorSize",10,oi());mn.addGetterSetter(Fd,"rotateEnabled",!0);mn.addGetterSetter(Fd,"rotateLineVisible",!0);mn.addGetterSetter(Fd,"rotationSnaps",[]);mn.addGetterSetter(Fd,"rotateAnchorOffset",50,oi());mn.addGetterSetter(Fd,"rotateAnchorAngle",0,oi());mn.addGetterSetter(Fd,"rotateAnchorCursor","crosshair");mn.addGetterSetter(Fd,"rotationSnapTolerance",5,oi());mn.addGetterSetter(Fd,"borderEnabled",!0);mn.addGetterSetter(Fd,"anchorStroke","rgb(0, 161, 255)");mn.addGetterSetter(Fd,"anchorStrokeWidth",1,oi());mn.addGetterSetter(Fd,"anchorFill","white");mn.addGetterSetter(Fd,"anchorCornerRadius",0,oi());mn.addGetterSetter(Fd,"borderStroke","rgb(0, 161, 255)");mn.addGetterSetter(Fd,"borderStrokeWidth",1,oi());mn.addGetterSetter(Fd,"borderDash");mn.addGetterSetter(Fd,"keepRatio",!0);mn.addGetterSetter(Fd,"shiftBehavior","default");mn.addGetterSetter(Fd,"centeredScaling",!1);mn.addGetterSetter(Fd,"ignoreStroke",!1);mn.addGetterSetter(Fd,"padding",0,oi());mn.addGetterSetter(Fd,"nodes");mn.addGetterSetter(Fd,"node");mn.addGetterSetter(Fd,"boundBoxFunc");mn.addGetterSetter(Fd,"anchorDragBoundFunc");mn.addGetterSetter(Fd,"anchorStyleFunc");mn.addGetterSetter(Fd,"shouldOverdrawWholeArea",!1);mn.addGetterSetter(Fd,"useSingleNodeRotation",!0);mn.backCompat(Fd,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class bE extends Qa{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.radius(),0,fi.getAngle(this.angle()),this.clockwise()),t.lineTo(0,0),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(t){this.radius(t/2)}setHeight(t){this.radius(t/2)}}bE.prototype.className="Wedge";bE.prototype._centroid=!0;bE.prototype._attrsAffectingSize=["radius"];Lf(bE);mn.addGetterSetter(bE,"radius",0,oi());mn.addGetterSetter(bE,"angle",0,oi());mn.addGetterSetter(bE,"clockwise",!1);mn.backCompat(bE,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function T0t(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const Pen=[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],Len=[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 Ien(s,t){const n=s.data,r=s.width,a=s.height;let i,l,o,c,d,u,h,m,p,f,x,y,v,b,N,S,A,T,L,M;const I=t+t+1,R=r-1,z=a-1,$=t+1,H=$*($+1)/2,V=new T0t,K=Pen[t],Z=Len[t];let Q=null,le=V,ue=null,se=null;for(let ne=1;ne>Z,L!==0?(L=255/L,n[l]=(c*K>>Z)*L,n[l+1]=(d*K>>Z)*L,n[l+2]=(u*K>>Z)*L):n[l]=n[l+1]=n[l+2]=0,c-=m,d-=p,u-=f,h-=x,m-=ue.r,p-=ue.g,f-=ue.b,x-=ue.a,i=o+((i=ie+t+1)>Z,L>0?(L=255/L,n[i]=(c*K>>Z)*L,n[i+1]=(d*K>>Z)*L,n[i+2]=(u*K>>Z)*L):n[i]=n[i+1]=n[i+2]=0,c-=m,d-=p,u-=f,h-=x,m-=ue.r,p-=ue.g,f-=ue.b,x-=ue.a,i=ne+((i=ce+$)0&&Ien(t,n)};mn.addGetterSetter(bi,"blurRadius",0,oi(),mn.afterSetFilter);const Den=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};mn.addGetterSetter(bi,"contrast",0,oi(),mn.afterSetFilter);const zen=function(s){var t,n,r,a,i,l,o,c,d;const u=s.data,h=s.width,m=s.height,p=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)),f=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=p*10,N=f*255,S=y*Math.PI/180,A=Math.cos(S),T=Math.sin(S),L=128/1020*b,M=new Uint8ClampedArray(u),I=new Float32Array(h*m);for(let V=0,K=0;KV<0?0:V>255?255:V;for(let V=1;Va&&(a=i),c=t[N+1],co&&(o=c),h=t[N+2],hu&&(u=h);a===r&&(a=255,r=0),o===l&&(o=255,l=0),u===d&&(u=255,d=0);let p,f,x,y,v,b;if(m>0)p=a+m*(255-a),f=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 N=(a+r)*.5;p=a+m*(a-N),f=r+m*(r-N);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 N=0;Nd?m:d;const p=l,f=i,x=360/f*Math.PI/180;for(let y=0;yd?m:d;const p=l,f=i,x=0;let y,v;for(u=0;ut&&(S=N,A=0,T=-1),a=0;a=0&&p=0&&f=0&&p=0&&f=255*4?255:0}return l}function Jen(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&&p=0&&f=n))for(let N=x;N=r)continue;const S=(n*N+b)*4;d+=l[S+0],u+=l[S+1],h+=l[S+2],m+=l[S+3],v+=1}d=d/v,u=u/v,h=h/v,m=m/v;for(let b=p;b=n))for(let N=x;N=r)continue;const S=(n*N+b)*4;l[S+0]=d,l[S+1]=u,l[S+2]=h,l[S+3]=m}}};mn.addGetterSetter(bi,"pixelSize",8,oi(),mn.afterSetFilter);const ntn=function(s){const t=Math.round(this.levels()*254)+1,n=s.data,r=n.length,a=255/t;for(let i=0;i255?255:s<0?0:Math.round(s)});mn.addGetterSetter(bi,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});mn.addGetterSetter(bi,"blue",0,IBt,mn.afterSetFilter);const atn=function(s){const t=s.data,n=t.length,r=this.red(),a=this.green(),i=this.blue(),l=this.alpha();for(let o=0;o255?255:s<0?0:Math.round(s)});mn.addGetterSetter(bi,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});mn.addGetterSetter(bi,"blue",0,IBt,mn.afterSetFilter);mn.addGetterSetter(bi,"alpha",1,function(s){return this._filterUpToDate=!1,s>1?1:s<0?0:s});const itn=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},ltn=function(s){const t=this.threshold()*255,n=s.data,r=n.length;for(let a=0;aYn||lt[Os]!==At[Yn]){var Ir=` `+lt[Os].replace(" at new "," at ");return ee.displayName&&Ir.includes("")&&(Ir=Ir.replace("",ee.displayName)),Ir}while(1<=Os&&0<=Yn);break}}}finally{Zr=!1,Error.prepareStackTrace=Re}return(ee=ee?ee.displayName||ee.name:"")?qr(ee):""}var ha=Object.prototype.hasOwnProperty,Fa=[],Fo=-1;function Xo(ee){return{current:ee}}function Vi(ee){0>Fo||(ee.current=Fa[Fo],Fa[Fo]=null,Fo--)}function Ja(ee,oe){Fo++,Fa[Fo]=ee.current,ee.current=oe}var Co={},Go=Xo(Co),hi=Xo(!1),Qo=Co;function Ao(ee,oe){var Re=ee.type.contextTypes;if(!Re)return Co;var nt=ee.stateNode;if(nt&&nt.__reactInternalMemoizedUnmaskedChildContext===oe)return nt.__reactInternalMemoizedMaskedChildContext;var lt={},At;for(At in Re)lt[At]=oe[At];return nt&&(ee=ee.stateNode,ee.__reactInternalMemoizedUnmaskedChildContext=oe,ee.__reactInternalMemoizedMaskedChildContext=lt),lt}function _a(ee){return ee=ee.childContextTypes,ee!=null}function ir(){Vi(hi),Vi(Go)}function li(ee,oe,Re){if(Go.current!==Co)throw Error(l(168));Ja(Go,oe),Ja(hi,Re)}function Eo(ee,oe,Re){var nt=ee.stateNode;if(oe=oe.childContextTypes,typeof nt.getChildContext!="function")return Re;nt=nt.getChildContext();for(var lt in nt)if(!(lt in oe))throw Error(l(108,M(ee)||"Unknown",lt));return i({},Re,nt)}function gl(ee){return ee=(ee=ee.stateNode)&&ee.__reactInternalMemoizedMergedChildContext||Co,Qo=Go.current,Ja(Go,ee),Ja(hi,hi.current),!0}function ds(ee,oe,Re){var nt=ee.stateNode;if(!nt)throw Error(l(169));Re?(ee=Eo(ee,oe,Qo),nt.__reactInternalMemoizedMergedChildContext=ee,Vi(hi),Vi(Go),Ja(Go,ee)):Vi(hi),Ja(hi,Re)}var Gr=Math.clz32?Math.clz32:Wi,ji=Math.log,ya=Math.LN2;function Wi(ee){return ee>>>=0,ee===0?32:31-(ji(ee)/ya|0)|0}var wi=64,di=4194304;function Dc(ee){switch(ee&-ee){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 ee&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return ee&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return ee}}function fd(ee,oe){var Re=ee.pendingLanes;if(Re===0)return 0;var nt=0,lt=ee.suspendedLanes,At=ee.pingedLanes,Os=Re&268435455;if(Os!==0){var Yn=Os&~lt;Yn!==0?nt=Dc(Yn):(At&=Os,At!==0&&(nt=Dc(At)))}else Os=Re&~lt,Os!==0?nt=Dc(Os):At!==0&&(nt=Dc(At));if(nt===0)return 0;if(oe!==0&&oe!==nt&&!(oe<)&&(lt=nt&-nt,At=oe&-oe,lt>=At||lt===16&&(At&4194240)!==0))return oe;if(nt&4&&(nt|=Re&16),oe=ee.entangledLanes,oe!==0)for(ee=ee.entanglements,oe&=nt;0Re;Re++)oe.push(ee);return oe}function fg(ee,oe,Re){ee.pendingLanes|=oe,oe!==536870912&&(ee.suspendedLanes=0,ee.pingedLanes=0),ee=ee.eventTimes,oe=31-Gr(oe),ee[oe]=Re}function Lh(ee,oe){var Re=ee.pendingLanes&~oe;ee.pendingLanes=oe,ee.suspendedLanes=0,ee.pingedLanes=0,ee.expiredLanes&=oe,ee.mutableReadLanes&=oe,ee.entangledLanes&=oe,oe=ee.entanglements;var nt=ee.eventTimes;for(ee=ee.expirationTimes;0>=Os,lt-=Os,eu=1<<32-Gr(oe)+lt|Re<Bl?(wp=ho,ho=null):wp=ho.sibling;var dd=Ei(Er,ho,$n[Bl],Fi);if(dd===null){ho===null&&(ho=wp);break}ee&&ho&&dd.alternate===null&&oe(Er,ho),Cn=At(dd,Cn,Bl),cl===null?Qi=dd:cl.sibling=dd,cl=dd,ho=wp}if(Bl===$n.length)return Re(Er,ho),Sn&&qm(Er,Bl),Qi;if(ho===null){for(;Bl<$n.length;Bl++)ho=Gl(Er,$n[Bl],Fi),ho!==null&&(Cn=At(ho,Cn,Bl),cl===null?Qi=ho:cl.sibling=ho,cl=ho);return Sn&&qm(Er,Bl),Qi}for(ho=nt(Er,ho);Bl<$n.length;Bl++)wp=fh(ho,Er,Bl,$n[Bl],Fi),wp!==null&&(ee&&wp.alternate!==null&&ho.delete(wp.key===null?Bl:wp.key),Cn=At(wp,Cn,Bl),cl===null?Qi=wp:cl.sibling=wp,cl=wp);return ee&&ho.forEach(function(qb){return oe(Er,qb)}),Sn&&qm(Er,Bl),Qi}function wg(Er,Cn,$n,Fi){var Qi=T($n);if(typeof Qi!="function")throw Error(l(150));if($n=Qi.call($n),$n==null)throw Error(l(151));for(var cl=Qi=null,ho=Cn,Bl=Cn=0,wp=null,dd=$n.next();ho!==null&&!dd.done;Bl++,dd=$n.next()){ho.index>Bl?(wp=ho,ho=null):wp=ho.sibling;var qb=Ei(Er,ho,dd.value,Fi);if(qb===null){ho===null&&(ho=wp);break}ee&&ho&&qb.alternate===null&&oe(Er,ho),Cn=At(qb,Cn,Bl),cl===null?Qi=qb:cl.sibling=qb,cl=qb,ho=wp}if(dd.done)return Re(Er,ho),Sn&&qm(Er,Bl),Qi;if(ho===null){for(;!dd.done;Bl++,dd=$n.next())dd=Gl(Er,dd.value,Fi),dd!==null&&(Cn=At(dd,Cn,Bl),cl===null?Qi=dd:cl.sibling=dd,cl=dd);return Sn&&qm(Er,Bl),Qi}for(ho=nt(Er,ho);!dd.done;Bl++,dd=$n.next())dd=fh(ho,Er,Bl,dd.value,Fi),dd!==null&&(ee&&dd.alternate!==null&&ho.delete(dd.key===null?Bl:dd.key),Cn=At(dd,Cn,Bl),cl===null?Qi=dd:cl.sibling=dd,cl=dd);return ee&&ho.forEach(function(jL){return oe(Er,jL)}),Sn&&qm(Er,Bl),Qi}function Ry(Er,Cn,$n,Fi){if(typeof $n=="object"&&$n!==null&&$n.type===u&&$n.key===null&&($n=$n.props.children),typeof $n=="object"&&$n!==null){switch($n.$$typeof){case c:e:{for(var Qi=$n.key,cl=Cn;cl!==null;){if(cl.key===Qi){if(Qi=$n.type,Qi===u){if(cl.tag===7){Re(Er,cl.sibling),Cn=lt(cl,$n.props.children),Cn.return=Er,Er=Cn;break e}}else if(cl.elementType===Qi||typeof Qi=="object"&&Qi!==null&&Qi.$$typeof===N&&S0(Qi)===cl.type){Re(Er,cl.sibling),Cn=lt(cl,$n.props),Cn.ref=$m(Er,cl,$n),Cn.return=Er,Er=Cn;break e}Re(Er,cl);break}else oe(Er,cl);cl=cl.sibling}$n.type===u?(Cn=Us($n.props.children,Er.mode,Fi,$n.key),Cn.return=Er,Er=Cn):(Fi=Wc($n.type,$n.key,$n.props,null,Er.mode,Fi),Fi.ref=$m(Er,Cn,$n),Fi.return=Er,Er=Fi)}return Os(Er);case d:e:{for(cl=$n.key;Cn!==null;){if(Cn.key===cl)if(Cn.tag===4&&Cn.stateNode.containerInfo===$n.containerInfo&&Cn.stateNode.implementation===$n.implementation){Re(Er,Cn.sibling),Cn=lt(Cn,$n.children||[]),Cn.return=Er,Er=Cn;break e}else{Re(Er,Cn);break}else oe(Er,Cn);Cn=Cn.sibling}Cn=D3($n,Er.mode,Fi),Cn.return=Er,Er=Cn}return Os(Er);case N:return cl=$n._init,Ry(Er,Cn,cl($n._payload),Fi)}if(K($n))return Wl(Er,Cn,$n,Fi);if(T($n))return wg(Er,Cn,$n,Fi);k0(Er,$n)}return typeof $n=="string"&&$n!==""||typeof $n=="number"?($n=""+$n,Cn!==null&&Cn.tag===6?(Re(Er,Cn.sibling),Cn=lt(Cn,$n),Cn.return=Er,Er=Cn):(Re(Er,Cn),Cn=WS($n,Er.mode,Fi),Cn.return=Er,Er=Cn),Os(Er)):Re(Er,Cn)}return Ry}var Ac=Xu(!0),Ab=Xu(!1),Mx=Xo(null),wy=null,wu=null,Kp=null;function jy(){Kp=wu=wy=null}function Sv(ee,oe,Re){Me?(Ja(Mx,oe._currentValue),oe._currentValue=Re):(Ja(Mx,oe._currentValue2),oe._currentValue2=Re)}function Bd(ee){var oe=Mx.current;Vi(Mx),Me?ee._currentValue=oe:ee._currentValue2=oe}function tu(ee,oe,Re){for(;ee!==null;){var nt=ee.alternate;if((ee.childLanes&oe)!==oe?(ee.childLanes|=oe,nt!==null&&(nt.childLanes|=oe)):nt!==null&&(nt.childLanes&oe)!==oe&&(nt.childLanes|=oe),ee===Re)break;ee=ee.return}}function uh(ee,oe){wy=ee,Kp=wu=null,ee=ee.dependencies,ee!==null&&ee.firstContext!==null&&(ee.lanes&oe&&(Of=!0),ee.firstContext=null)}function fp(ee){var oe=Me?ee._currentValue:ee._currentValue2;if(Kp!==ee)if(ee={context:ee,memoizedValue:oe,next:null},wu===null){if(wy===null)throw Error(l(308));wu=ee,wy.dependencies={lanes:0,firstContext:ee}}else wu=wu.next=ee;return oe}var xg=null;function Hl(ee){xg===null?xg=[ee]:xg.push(ee)}function Ia(ee,oe,Re,nt){var lt=oe.interleaved;return lt===null?(Re.next=Re,Hl(oe)):(Re.next=lt.next,lt.next=Re),oe.interleaved=Re,Hr(ee,nt)}function Hr(ee,oe){ee.lanes|=oe;var Re=ee.alternate;for(Re!==null&&(Re.lanes|=oe),Re=ee,ee=ee.return;ee!==null;)ee.childLanes|=oe,Re=ee.alternate,Re!==null&&(Re.childLanes|=oe),Re=ee,ee=ee.return;return Re.tag===3?Re.stateNode:null}var bc=!1;function Da(ee){ee.updateQueue={baseState:ee.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function gp(ee,oe){ee=ee.updateQueue,oe.updateQueue===ee&&(oe.updateQueue={baseState:ee.baseState,firstBaseUpdate:ee.firstBaseUpdate,lastBaseUpdate:ee.lastBaseUpdate,shared:ee.shared,effects:ee.effects})}function Ud(ee,oe){return{eventTime:ee,lane:oe,tag:0,payload:null,callback:null,next:null}}function fa(ee,oe,Re){var nt=ee.updateQueue;if(nt===null)return null;if(nt=nt.shared,To&2){var lt=nt.pending;return lt===null?oe.next=oe:(oe.next=lt.next,lt.next=oe),nt.pending=oe,Hr(ee,Re)}return lt=nt.interleaved,lt===null?(oe.next=oe,Hl(nt)):(oe.next=lt.next,lt.next=oe),nt.interleaved=oe,Hr(ee,Re)}function Px(ee,oe,Re){if(oe=oe.updateQueue,oe!==null&&(oe=oe.shared,(Re&4194240)!==0)){var nt=oe.lanes;nt&=ee.pendingLanes,Re|=nt,oe.lanes=Re,by(ee,Re)}}function C0(ee,oe){var Re=ee.updateQueue,nt=ee.alternate;if(nt!==null&&(nt=nt.updateQueue,Re===nt)){var lt=null,At=null;if(Re=Re.firstBaseUpdate,Re!==null){do{var Os={eventTime:Re.eventTime,lane:Re.lane,tag:Re.tag,payload:Re.payload,callback:Re.callback,next:null};At===null?lt=At=Os:At=At.next=Os,Re=Re.next}while(Re!==null);At===null?lt=At=oe:At=At.next=oe}else lt=At=oe;Re={baseState:nt.baseState,firstBaseUpdate:lt,lastBaseUpdate:At,shared:nt.shared,effects:nt.effects},ee.updateQueue=Re;return}ee=Re.lastBaseUpdate,ee===null?Re.firstBaseUpdate=oe:ee.next=oe,Re.lastBaseUpdate=oe}function Jg(ee,oe,Re,nt){var lt=ee.updateQueue;bc=!1;var At=lt.firstBaseUpdate,Os=lt.lastBaseUpdate,Yn=lt.shared.pending;if(Yn!==null){lt.shared.pending=null;var Ir=Yn,za=Ir.next;Ir.next=null,Os===null?At=za:Os.next=za,Os=Ir;var Zi=ee.alternate;Zi!==null&&(Zi=Zi.updateQueue,Yn=Zi.lastBaseUpdate,Yn!==Os&&(Yn===null?Zi.firstBaseUpdate=za:Yn.next=za,Zi.lastBaseUpdate=Ir))}if(At!==null){var Gl=lt.baseState;Os=0,Zi=za=Ir=null,Yn=At;do{var Ei=Yn.lane,fh=Yn.eventTime;if((nt&Ei)===Ei){Zi!==null&&(Zi=Zi.next={eventTime:fh,lane:0,tag:Yn.tag,payload:Yn.payload,callback:Yn.callback,next:null});e:{var Wl=ee,wg=Yn;switch(Ei=oe,fh=Re,wg.tag){case 1:if(Wl=wg.payload,typeof Wl=="function"){Gl=Wl.call(fh,Gl,Ei);break e}Gl=Wl;break e;case 3:Wl.flags=Wl.flags&-65537|128;case 0:if(Wl=wg.payload,Ei=typeof Wl=="function"?Wl.call(fh,Gl,Ei):Wl,Ei==null)break e;Gl=i({},Gl,Ei);break e;case 2:bc=!0}}Yn.callback!==null&&Yn.lane!==0&&(ee.flags|=64,Ei=lt.effects,Ei===null?lt.effects=[Yn]:Ei.push(Yn))}else fh={eventTime:fh,lane:Ei,tag:Yn.tag,payload:Yn.payload,callback:Yn.callback,next:null},Zi===null?(za=Zi=fh,Ir=Gl):Zi=Zi.next=fh,Os|=Ei;if(Yn=Yn.next,Yn===null){if(Yn=lt.shared.pending,Yn===null)break;Ei=Yn,Yn=Ei.next,Ei.next=null,lt.lastBaseUpdate=Ei,lt.shared.pending=null}}while(!0);if(Zi===null&&(Ir=Gl),lt.baseState=Ir,lt.firstBaseUpdate=za,lt.lastBaseUpdate=Zi,oe=lt.shared.interleaved,oe!==null){lt=oe;do Os|=lt.lane,lt=lt.next;while(lt!==oe)}else At===null&&(lt.shared.lanes=0);j1|=Os,ee.lanes=Os,ee.memoizedState=Gl}}function Ny(ee,oe,Re){if(ee=oe.effects,oe.effects=null,ee!==null)for(oe=0;oeRe?Re:4,ee(!0);var nt=Eb.transition;Eb.transition={};try{ee(!1),oe()}finally{qo=Re,Eb.transition=nt}}function IS(){return eh().memoizedState}function S3(ee,oe,Re){var nt=Py(ee);if(Re={lane:nt,action:Re,hasEagerState:!1,eagerState:null,next:null},C3(ee))ME(oe,Re);else if(Re=Ia(ee,oe,Re,nt),Re!==null){var lt=sh();_g(Re,ee,nt,lt),Qc(Re,oe,nt)}}function xL(ee,oe,Re){var nt=Py(ee),lt={lane:nt,action:Re,hasEagerState:!1,eagerState:null,next:null};if(C3(ee))ME(oe,lt);else{var At=ee.alternate;if(ee.lanes===0&&(At===null||At.lanes===0)&&(At=oe.lastRenderedReducer,At!==null))try{var Os=oe.lastRenderedState,Yn=At(Os,Re);if(lt.hasEagerState=!0,lt.eagerState=Yn,mp(Yn,Os)){var Ir=oe.interleaved;Ir===null?(lt.next=lt,Hl(oe)):(lt.next=Ir.next,Ir.next=lt),oe.interleaved=lt;return}}catch{}finally{}Re=Ia(ee,oe,lt,nt),Re!==null&&(lt=sh(),_g(Re,ee,nt,lt),Qc(Re,oe,nt))}}function C3(ee){var oe=ee.alternate;return ee===_c||oe!==null&&oe===_c}function ME(ee,oe){Cd=ju=!0;var Re=ee.pending;Re===null?oe.next=oe:(oe.next=Re.next,Re.next=oe),ee.pending=oe}function Qc(ee,oe,Re){if(Re&4194240){var nt=oe.lanes;nt&=ee.pendingLanes,Re|=nt,oe.lanes=Re,by(ee,Re)}}var K_={readContext:fp,useCallback:sm,useContext:sm,useEffect:sm,useImperativeHandle:sm,useInsertionEffect:sm,useLayoutEffect:sm,useMemo:sm,useReducer:sm,useRef:sm,useState:sm,useDebugValue:sm,useDeferredValue:sm,useTransition:sm,useMutableSource:sm,useSyncExternalStore:sm,useId:sm,unstable_isNewReconciler:!1},A3={readContext:fp,useCallback:function(ee,oe){return Rx().memoizedState=[ee,oe===void 0?null:oe],ee},useContext:fp,useEffect:_1,useImperativeHandle:function(ee,oe,Re){return Re=Re!=null?Re.concat([ee]):null,Pb(4194308,4,W_.bind(null,oe,ee),Re)},useLayoutEffect:function(ee,oe){return Pb(4194308,4,ee,oe)},useInsertionEffect:function(ee,oe){return Pb(4,2,ee,oe)},useMemo:function(ee,oe){var Re=Rx();return oe=oe===void 0?null:oe,ee=ee(),Re.memoizedState=[ee,oe],ee},useReducer:function(ee,oe,Re){var nt=Rx();return oe=Re!==void 0?Re(oe):oe,nt.memoizedState=nt.baseState=oe,ee={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:ee,lastRenderedState:oe},nt.queue=ee,ee=ee.dispatch=S3.bind(null,_c,ee),[nt.memoizedState,ee]},useRef:function(ee){var oe=Rx();return ee={current:ee},oe.memoizedState=ee},useState:Xp,useDebugValue:DN,useDeferredValue:function(ee){return Rx().memoizedState=ee},useTransition:function(){var ee=Xp(!1),oe=ee[0];return ee=_o.bind(null,ee[1]),Rx().memoizedState=ee,[oe,ee]},useMutableSource:function(){},useSyncExternalStore:function(ee,oe,Re){var nt=_c,lt=Rx();if(Sn){if(Re===void 0)throw Error(l(407));Re=Re()}else{if(Re=oe(),cd===null)throw Error(l(349));Ju&30||IN(nt,oe,Re)}lt.memoizedState=Re;var At={value:Re,getSnapshot:oe};return lt.queue=At,_1(Mb.bind(null,nt,At,ee),[ee]),nt.flags|=2048,nm(9,Tb.bind(null,nt,At,Re,oe),void 0,null),Re},useId:function(){var ee=Rx(),oe=cd.identifierPrefix;if(Sn){var Re=Wp,nt=eu;Re=(nt&~(1<<32-Gr(nt)-1)).toString(32)+Re,oe=":"+oe+"R"+Re,Re=Ix++,0M0&&(oe.flags|=128,nt=!0,En(lt,!1),oe.lanes=4194304)}else{if(!nt)if(ee=Lx(At),ee!==null){if(oe.flags|=128,nt=!0,ee=ee.updateQueue,ee!==null&&(oe.updateQueue=ee,oe.flags|=4),En(lt,!0),lt.tail===null&<.tailMode==="hidden"&&!At.alternate&&!Sn)return Xn(oe),null}else 2*Vl()-lt.renderingStartTime>M0&&Re!==1073741824&&(oe.flags|=128,nt=!0,En(lt,!1),oe.lanes=4194304);lt.isBackwards?(At.sibling=oe.child,oe.child=At):(ee=lt.last,ee!==null?ee.sibling=At:oe.child=At,lt.last=At)}return lt.tail!==null?(oe=lt.tail,lt.rendering=oe,lt.tail=oe.sibling,lt.renderingStartTime=Vl(),oe.sibling=null,ee=Xc.current,Ja(Xc,nt?ee&1|2:ee&1),oe):(Xn(oe),null);case 22:case 23:return C1(),Re=oe.memoizedState!==null,ee!==null&&ee.memoizedState!==null!==Re&&(oe.flags|=8192),Re&&oe.mode&1?Hm&1073741824&&(Xn(oe),Oe&&oe.subtreeFlags&6&&(oe.flags|=8192)):Xn(oe),null;case 24:return null;case 25:return null}throw Error(l(156,oe.tag))}function Fn(ee,oe){switch(Yt(oe),oe.tag){case 1:return _a(oe.type)&&ir(),ee=oe.flags,ee&65536?(oe.flags=ee&-65537|128,oe):null;case 3:return Zp(),Vi(hi),Vi(Go),tm(),ee=oe.flags,ee&65536&&!(ee&128)?(oe.flags=ee&-65537|128,oe):null;case 5:return b1(oe),null;case 13:if(Vi(Xc),ee=oe.memoizedState,ee!==null&&ee.dehydrated!==null){if(oe.alternate===null)throw Error(l(340));Va()}return ee=oe.flags,ee&65536?(oe.flags=ee&-65537|128,oe):null;case 19:return Vi(Xc),null;case 4:return Zp(),null;case 10:return Bd(oe.type._context),null;case 22:case 23:return C1(),null;case 24:return null;default:return null}}var rr=!1,Tr=!1,vr=typeof WeakSet=="function"?WeakSet:Set,qn=null;function Vr(ee,oe){var Re=ee.ref;if(Re!==null)if(typeof Re=="function")try{Re(null)}catch(nt){Oi(ee,oe,nt)}else Re.current=null}function wa(ee,oe,Re){try{Re()}catch(nt){Oi(ee,oe,nt)}}var ga=!1;function Xi(ee,oe){for(ue(ee.containerInfo),qn=oe;qn!==null;)if(ee=qn,oe=ee.child,(ee.subtreeFlags&1028)!==0&&oe!==null)oe.return=ee,qn=oe;else for(;qn!==null;){ee=qn;try{var Re=ee.alternate;if(ee.flags&1024)switch(ee.tag){case 0:case 11:case 15:break;case 1:if(Re!==null){var nt=Re.memoizedProps,lt=Re.memoizedState,At=ee.stateNode,Os=At.getSnapshotBeforeUpdate(ee.elementType===ee.type?nt:E0(ee.type,nt),lt);At.__reactInternalSnapshotBeforeUpdate=Os}break;case 3:Oe&&Gn(ee.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(l(163))}}catch(Yn){Oi(ee,ee.return,Yn)}if(oe=ee.sibling,oe!==null){oe.return=ee.return,qn=oe;break}qn=ee.return}return Re=ga,ga=!1,Re}function Mi(ee,oe,Re){var nt=oe.updateQueue;if(nt=nt!==null?nt.lastEffect:null,nt!==null){var lt=nt=nt.next;do{if((lt.tag&ee)===ee){var At=lt.destroy;lt.destroy=void 0,At!==void 0&&wa(oe,Re,At)}lt=lt.next}while(lt!==nt)}}function yl(ee,oe){if(oe=oe.updateQueue,oe=oe!==null?oe.lastEffect:null,oe!==null){var Re=oe=oe.next;do{if((Re.tag&ee)===ee){var nt=Re.create;Re.destroy=nt()}Re=Re.next}while(Re!==oe)}}function Ui(ee){var oe=ee.ref;if(oe!==null){var Re=ee.stateNode;switch(ee.tag){case 5:ee=Z(Re);break;default:ee=Re}typeof oe=="function"?oe(ee):oe.current=ee}}function ic(ee){var oe=ee.alternate;oe!==null&&(ee.alternate=null,ic(oe)),ee.child=null,ee.deletions=null,ee.sibling=null,ee.tag===5&&(oe=ee.stateNode,oe!==null&&$e(oe)),ee.stateNode=null,ee.return=null,ee.dependencies=null,ee.memoizedProps=null,ee.memoizedState=null,ee.pendingProps=null,ee.stateNode=null,ee.updateQueue=null}function cu(ee){return ee.tag===5||ee.tag===3||ee.tag===4}function vl(ee){e:for(;;){for(;ee.sibling===null;){if(ee.return===null||cu(ee.return))return null;ee=ee.return}for(ee.sibling.return=ee.return,ee=ee.sibling;ee.tag!==5&&ee.tag!==6&&ee.tag!==18;){if(ee.flags&2||ee.child===null||ee.tag===4)continue e;ee.child.return=ee,ee=ee.child}if(!(ee.flags&2))return ee.stateNode}}function Hi(ee,oe,Re){var nt=ee.tag;if(nt===5||nt===6)ee=ee.stateNode,oe?As(Re,ee,oe):Ut(Re,ee);else if(nt!==4&&(ee=ee.child,ee!==null))for(Hi(ee,oe,Re),ee=ee.sibling;ee!==null;)Hi(ee,oe,Re),ee=ee.sibling}function ci(ee,oe,Re){var nt=ee.tag;if(nt===5||nt===6)ee=ee.stateNode,oe?bt(Re,ee,oe):qt(Re,ee);else if(nt!==4&&(ee=ee.child,ee!==null))for(ci(ee,oe,Re),ee=ee.sibling;ee!==null;)ci(ee,oe,Re),ee=ee.sibling}var wl=null,vo=!1;function ul(ee,oe,Re){for(Re=Re.child;Re!==null;)su(ee,oe,Re),Re=Re.sibling}function su(ee,oe,Re){if(zi&&typeof zi.onCommitFiberUnmount=="function")try{zi.onCommitFiberUnmount(_u,Re)}catch{}switch(Re.tag){case 5:Tr||Vr(Re,oe);case 6:if(Oe){var nt=wl,lt=vo;wl=null,ul(ee,oe,Re),wl=nt,vo=lt,wl!==null&&(vo?Ws(wl,Re.stateNode):vt(wl,Re.stateNode))}else ul(ee,oe,Re);break;case 18:Oe&&wl!==null&&(vo?Xs(wl,Re.stateNode):Ht(wl,Re.stateNode));break;case 4:Oe?(nt=wl,lt=vo,wl=Re.stateNode.containerInfo,vo=!0,ul(ee,oe,Re),wl=nt,vo=lt):(Se&&(nt=Re.stateNode.containerInfo,lt=Rr(nt),_r(nt,lt)),ul(ee,oe,Re));break;case 0:case 11:case 14:case 15:if(!Tr&&(nt=Re.updateQueue,nt!==null&&(nt=nt.lastEffect,nt!==null))){lt=nt=nt.next;do{var At=lt,Os=At.destroy;At=At.tag,Os!==void 0&&(At&2||At&4)&&wa(Re,oe,Os),lt=lt.next}while(lt!==nt)}ul(ee,oe,Re);break;case 1:if(!Tr&&(Vr(Re,oe),nt=Re.stateNode,typeof nt.componentWillUnmount=="function"))try{nt.props=Re.memoizedProps,nt.state=Re.memoizedState,nt.componentWillUnmount()}catch(Yn){Oi(Re,oe,Yn)}ul(ee,oe,Re);break;case 21:ul(ee,oe,Re);break;case 22:Re.mode&1?(Tr=(nt=Tr)||Re.memoizedState!==null,ul(ee,oe,Re),Tr=nt):ul(ee,oe,Re);break;default:ul(ee,oe,Re)}}function vm(ee){var oe=ee.updateQueue;if(oe!==null){ee.updateQueue=null;var Re=ee.stateNode;Re===null&&(Re=ee.stateNode=new vr),oe.forEach(function(nt){var lt=GS.bind(null,ee,nt);Re.has(nt)||(Re.add(nt),nt.then(lt,lt))})}}function nu(ee,oe){var Re=oe.deletions;if(Re!==null)for(var nt=0;nt";case hh:return":has("+(du(ee)||"")+")";case xp:return'[role="'+ee.value+'"]';case Ih:return'"'+ee.value+'"';case xd:return'[data-testname="'+ee.value+'"]';default:throw Error(l(365))}}function zf(ee,oe){var Re=[];ee=[ee,0];for(var nt=0;ntlt&&(lt=Os),nt&=~At}if(nt=lt,nt=Vl()-nt,nt=(120>nt?120:480>nt?480:1080>nt?1080:1920>nt?1920:3e3>nt?3e3:4320>nt?4320:1960*vp(nt/1960))-nt,10ee?16:ee,sx===null)var nt=!1;else{if(ee=sx,sx=null,J_=0,To&6)throw Error(l(331));var lt=To;for(To|=4,qn=ee.current;qn!==null;){var At=qn,Os=At.child;if(qn.flags&16){var Yn=At.deletions;if(Yn!==null){for(var Ir=0;IrVl()-qj?P0(ee,0):N1|=Re),qf(ee,oe)}function I3(ee,oe){oe===0&&(ee.mode&1?(oe=di,di<<=1,!(di&130023424)&&(di=4194304)):oe=1);var Re=sh();ee=Hr(ee,oe),ee!==null&&(fg(ee,oe,Re),qf(ee,Re))}function LE(ee){var oe=ee.memoizedState,Re=0;oe!==null&&(Re=oe.retryLane),I3(ee,Re)}function GS(ee,oe){var Re=0;switch(ee.tag){case 13:var nt=ee.stateNode,lt=ee.memoizedState;lt!==null&&(Re=lt.retryLane);break;case 19:nt=ee.stateNode;break;default:throw Error(l(314))}nt!==null&&nt.delete(oe),I3(ee,Re)}var IE;IE=function(ee,oe,Re){if(ee!==null)if(ee.memoizedProps!==oe.pendingProps||hi.current)Of=!0;else{if(!(ee.lanes&Re)&&!(oe.flags&128))return Of=!1,ht(ee,oe,Re);Of=!!(ee.flags&131072)}else Of=!1,Sn&&oe.flags&1048576&&ym(oe,_y,oe.index);switch(oe.lanes=0,oe.tag){case 2:var nt=oe.type;Ee(ee,oe),ee=oe.pendingProps;var lt=Ao(oe,Go.current);uh(oe,Re),lt=Tj(null,oe,nt,ee,lt,Re);var At=V_();return oe.flags|=1,typeof lt=="object"&<!==null&&typeof lt.render=="function"&<.$$typeof===void 0?(oe.tag=1,oe.memoizedState=null,oe.updateQueue=null,_a(nt)?(At=!0,gl(oe)):At=!1,oe.memoizedState=lt.state!==null&<.state!==void 0?lt.state:null,Da(oe),lt.updater=Y_,oe.stateNode=lt,lt._reactInternals=oe,bg(oe,nt,ee,Re),oe=Fj(null,oe,nt,!0,At,Re)):(oe.tag=0,Sn&&At&&at(oe),Qp(null,oe,lt,Re),oe=oe.child),oe;case 16:nt=oe.elementType;e:{switch(Ee(ee,oe),ee=oe.pendingProps,lt=nt._init,nt=lt(nt._payload),oe.type=nt,lt=oe.tag=or(nt),ee=E0(nt,ee),lt){case 0:oe=FS(null,oe,nt,ee,Re);break e;case 1:oe=zS(null,oe,nt,ee,Re);break e;case 11:oe=T3(null,oe,nt,ee,Re);break e;case 14:oe=Av(null,oe,nt,E0(nt.type,ee),Re);break e}throw Error(l(306,nt,""))}return oe;case 0:return nt=oe.type,lt=oe.pendingProps,lt=oe.elementType===nt?lt:E0(nt,lt),FS(ee,oe,nt,lt,Re);case 1:return nt=oe.type,lt=oe.pendingProps,lt=oe.elementType===nt?lt:E0(nt,lt),zS(ee,oe,nt,lt,Re);case 3:e:{if(zj(oe),ee===null)throw Error(l(387));nt=oe.pendingProps,At=oe.memoizedState,lt=At.element,gp(ee,oe),Jg(oe,nt,null,Re);var Os=oe.memoizedState;if(nt=Os.element,Qe&&At.isDehydrated)if(At={element:nt,isDehydrated:!1,cache:Os.cache,pendingSuspenseBoundaries:Os.pendingSuspenseBoundaries,transitions:Os.transitions},oe.updateQueue.baseState=At,oe.memoizedState=At,oe.flags&256){lt=Pu(Error(l(423)),oe),oe=Z_(ee,oe,nt,Re,lt);break e}else if(nt!==lt){lt=Pu(Error(l(424)),oe),oe=Z_(ee,oe,nt,Re,lt);break e}else for(Qe&&(Zs=ot(oe.stateNode.containerInfo),Bs=oe,Sn=!0,kt=null,Dr=!1),Re=Ab(oe,null,nt,Re),oe.child=Re;Re;)Re.flags=Re.flags&-3|4096,Re=Re.sibling;else{if(Va(),nt===lt){oe=ze(ee,oe,Re);break e}Qp(ee,oe,nt,Re)}oe=oe.child}return oe;case 5:return v1(oe),ee===null&&Or(oe),nt=oe.type,lt=oe.pendingProps,At=ee!==null?ee.memoizedProps:null,Os=lt.children,be(nt,lt)?Os=null:At!==null&&be(nt,At)&&(oe.flags|=32),OS(ee,oe),Qp(ee,oe,Os,Re),oe.child;case 6:return ee===null&&Or(oe),null;case 13:return PE(ee,oe,Re);case 4:return Sd(oe,oe.stateNode.containerInfo),nt=oe.pendingProps,ee===null?oe.child=Ac(oe,null,nt,Re):Qp(ee,oe,nt,Re),oe.child;case 11:return nt=oe.type,lt=oe.pendingProps,lt=oe.elementType===nt?lt:E0(nt,lt),T3(ee,oe,nt,lt,Re);case 7:return Qp(ee,oe,oe.pendingProps,Re),oe.child;case 8:return Qp(ee,oe,oe.pendingProps.children,Re),oe.child;case 12:return Qp(ee,oe,oe.pendingProps.children,Re),oe.child;case 10:e:{if(nt=oe.type._context,lt=oe.pendingProps,At=oe.memoizedProps,Os=lt.value,Sv(oe,nt,Os),At!==null)if(mp(At.value,Os)){if(At.children===lt.children&&!hi.current){oe=ze(ee,oe,Re);break e}}else for(At=oe.child,At!==null&&(At.return=oe);At!==null;){var Yn=At.dependencies;if(Yn!==null){Os=At.child;for(var Ir=Yn.firstContext;Ir!==null;){if(Ir.context===nt){if(At.tag===1){Ir=Ud(-1,Re&-Re),Ir.tag=2;var za=At.updateQueue;if(za!==null){za=za.shared;var Zi=za.pending;Zi===null?Ir.next=Ir:(Ir.next=Zi.next,Zi.next=Ir),za.pending=Ir}}At.lanes|=Re,Ir=At.alternate,Ir!==null&&(Ir.lanes|=Re),tu(At.return,Re,oe),Yn.lanes|=Re;break}Ir=Ir.next}}else if(At.tag===10)Os=At.type===oe.type?null:At.child;else if(At.tag===18){if(Os=At.return,Os===null)throw Error(l(341));Os.lanes|=Re,Yn=Os.alternate,Yn!==null&&(Yn.lanes|=Re),tu(Os,Re,oe),Os=At.sibling}else Os=At.child;if(Os!==null)Os.return=At;else for(Os=At;Os!==null;){if(Os===oe){Os=null;break}if(At=Os.sibling,At!==null){At.return=Os.return,Os=At;break}Os=Os.return}At=Os}Qp(ee,oe,lt.children,Re),oe=oe.child}return oe;case 9:return lt=oe.type,nt=oe.pendingProps.children,uh(oe,Re),lt=fp(lt),nt=nt(lt),oe.flags|=1,Qp(ee,oe,nt,Re),oe.child;case 14:return nt=oe.type,lt=E0(nt,oe.pendingProps),lt=E0(nt.type,lt),Av(ee,oe,nt,lt,Re);case 15:return Dj(ee,oe,oe.type,oe.pendingProps,Re);case 17:return nt=oe.type,lt=oe.pendingProps,lt=oe.elementType===nt?lt:E0(nt,lt),Ee(ee,oe),oe.tag=1,_a(nt)?(ee=!0,gl(oe)):ee=!1,uh(oe,Re),Rb(oe,nt,lt),bg(oe,nt,lt,Re),Fj(null,oe,nt,!0,ee,Re);case 19:return Q_(ee,oe,Re);case 22:return Oj(ee,oe,Re)}throw Error(l(156,oe.tag))};function RE(ee,oe){return Ex(ee,oe)}function qN(ee,oe,Re,nt){this.tag=ee,this.key=Re,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=oe,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=nt,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function _p(ee,oe,Re,nt){return new qN(ee,oe,Re,nt)}function lr(ee){return ee=ee.prototype,!(!ee||!ee.isReactComponent)}function or(ee){if(typeof ee=="function")return lr(ee)?1:0;if(ee!=null){if(ee=ee.$$typeof,ee===x)return 11;if(ee===b)return 14}return 2}function Iy(ee,oe){var Re=ee.alternate;return Re===null?(Re=_p(ee.tag,oe,ee.key,ee.mode),Re.elementType=ee.elementType,Re.type=ee.type,Re.stateNode=ee.stateNode,Re.alternate=ee,ee.alternate=Re):(Re.pendingProps=oe,Re.type=ee.type,Re.flags=0,Re.subtreeFlags=0,Re.deletions=null),Re.flags=ee.flags&14680064,Re.childLanes=ee.childLanes,Re.lanes=ee.lanes,Re.child=ee.child,Re.memoizedProps=ee.memoizedProps,Re.memoizedState=ee.memoizedState,Re.updateQueue=ee.updateQueue,oe=ee.dependencies,Re.dependencies=oe===null?null:{lanes:oe.lanes,firstContext:oe.firstContext},Re.sibling=ee.sibling,Re.index=ee.index,Re.ref=ee.ref,Re}function Wc(ee,oe,Re,nt,lt,At){var Os=2;if(nt=ee,typeof ee=="function")lr(ee)&&(Os=1);else if(typeof ee=="string")Os=5;else e:switch(ee){case u:return Us(Re.children,lt,At,oe);case h:Os=8,lt|=8;break;case m:return ee=_p(12,Re,oe,lt|2),ee.elementType=m,ee.lanes=At,ee;case y:return ee=_p(13,Re,oe,lt),ee.elementType=y,ee.lanes=At,ee;case v:return ee=_p(19,Re,oe,lt),ee.elementType=v,ee.lanes=At,ee;case S:return R3(Re,lt,At,oe);default:if(typeof ee=="object"&&ee!==null)switch(ee.$$typeof){case p:Os=10;break e;case f:Os=9;break e;case x:Os=11;break e;case b:Os=14;break e;case N:Os=16,nt=null;break e}throw Error(l(130,ee==null?ee:typeof ee,""))}return oe=_p(Os,Re,oe,lt),oe.elementType=ee,oe.type=nt,oe.lanes=At,oe}function Us(ee,oe,Re,nt){return ee=_p(7,ee,nt,oe),ee.lanes=Re,ee}function R3(ee,oe,Re,nt){return ee=_p(22,ee,nt,oe),ee.elementType=S,ee.lanes=Re,ee.stateNode={isHidden:!1},ee}function WS(ee,oe,Re){return ee=_p(6,ee,null,oe),ee.lanes=Re,ee}function D3(ee,oe,Re){return oe=_p(4,ee.children!==null?ee.children:[],ee.key,oe),oe.lanes=Re,oe.stateNode={containerInfo:ee.containerInfo,pendingChildren:null,implementation:ee.implementation},oe}function DE(ee,oe,Re,nt,lt){this.tag=oe,this.containerInfo=ee,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Te,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Hp(0),this.expirationTimes=Hp(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Hp(0),this.identifierPrefix=nt,this.onRecoverableError=lt,Qe&&(this.mutableSourceEagerHydrationData=null)}function bL(ee,oe,Re,nt,lt,At,Os,Yn,Ir){return ee=new DE(ee,oe,Re,Yn,Ir),oe===1?(oe=1,At===!0&&(oe|=8)):oe=0,At=_p(3,null,null,oe),ee.current=At,At.stateNode=ee,At.memoizedState={element:nt,isDehydrated:Re,cache:null,transitions:null,pendingSuspenseBoundaries:null},Da(At),ee}function _L(ee){if(!ee)return Co;ee=ee._reactInternals;e:{if(I(ee)!==ee||ee.tag!==1)throw Error(l(170));var oe=ee;do{switch(oe.tag){case 3:oe=oe.stateNode.context;break e;case 1:if(_a(oe.type)){oe=oe.stateNode.__reactInternalMemoizedMergedChildContext;break e}}oe=oe.return}while(oe!==null);throw Error(l(171))}if(ee.tag===1){var Re=ee.type;if(_a(Re))return Eo(ee,Re,oe)}return oe}function $N(ee){var oe=ee._reactInternals;if(oe===void 0)throw typeof ee.render=="function"?Error(l(188)):(ee=Object.keys(ee).join(","),Error(l(268,ee)));return ee=$(oe),ee===null?null:ee.stateNode}function wL(ee,oe){if(ee=ee.memoizedState,ee!==null&&ee.dehydrated!==null){var Re=ee.retryLane;ee.retryLane=Re!==0&&Re=za&&At>=Gl&<<=Zi&&Os<=Ei){ee.splice(oe,1);break}else if(nt!==za||Re.width!==Ir.width||EiOs){if(!(At!==Gl||Re.height!==Ir.height||Zilt)){za>nt&&(Ir.width+=za-nt,Ir.x=nt),ZiAt&&(Ir.height+=Gl-At,Ir.y=At),EiRe&&(Re=Os)),Os ")+` No matching component was found for: `)+ee.join(" > ")}return null},n.getPublicRootInstance=function(ee){if(ee=ee.current,!ee.child)return null;switch(ee.child.tag){case 5:return Z(ee.child.stateNode);default:return ee.child.stateNode}},n.injectIntoDevTools=function(ee){if(ee={bundleType:ee.bundleType,version:ee.version,rendererPackageName:ee.rendererPackageName,rendererConfig:ee.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:o.ReactCurrentDispatcher,findHostInstanceByFiber:Y9,findFiberByHostInstance:ee.findFiberByHostInstance||FE,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")ee=!1;else{var oe=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(oe.isDisabled||!oe.supportsFiber)ee=!0;else{try{_u=oe.inject(ee),zi=oe}catch{}ee=!!oe.checkDCE}}return ee},n.isAlreadyRendering=function(){return!1},n.observeVisibleRects=function(ee,oe,Re,nt){if(!Ze)throw Error(l(363));ee=Bf(ee,oe);var lt=ft(ee,Re,nt).disconnect;return{disconnect:function(){lt()}}},n.registerMutableSourceForHydration=function(ee,oe){var Re=oe._getVersion;Re=Re(oe._source),ee.mutableSourceEagerHydrationData==null?ee.mutableSourceEagerHydrationData=[oe,Re]:ee.mutableSourceEagerHydrationData.push(oe,Re)},n.runWithPriority=function(ee,oe){var Re=qo;try{return qo=ee,oe()}finally{qo=Re}},n.shouldError=function(){return null},n.shouldSuspend=function(){return!1},n.updateContainer=function(ee,oe,Re,nt){var lt=oe.current,At=sh(),Os=Py(lt);return Re=_L(Re),oe.context===null?oe.context=Re:oe.pendingContext=Re,oe=Ud(At,Os),oe.payload={element:ee},nt=nt===void 0?null:nt,nt!==null&&(oe.callback=nt),ee=fa(lt,oe,Os),ee!==null&&(_g(ee,lt,Os,At),Px(ee,lt,Os)),Os},n};mUt.exports=ctn;var dtn=mUt.exports;const utn=od(dtn);var pUt={exports:{}},N9={};/** * @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. */N9.ConcurrentRoot=1;N9.ContinuousEventPriority=4;N9.DefaultEventPriority=16;N9.DiscreteEventPriority=1;N9.IdleEventPriority=536870912;N9.LegacyRoot=0;pUt.exports=N9;var fUt=pUt.exports;const M0t={children:!0,ref:!0,key:!0,style:!0,forwardedRef:!0,unstable_applyCache:!0,unstable_applyDrawHitFromCache:!0};let P0t=!1,L0t=!1;const ret=".react-konva-event",htn=`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 `,mtn=`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 `,ptn={};function FPe(s,t,n=ptn){if(!P0t&&"zIndex"in t&&(console.warn(mtn),P0t=!0),!L0t&&t.draggable){var r=t.x!==void 0||t.y!==void 0,a=t.onDragEnd||t.onDragMove;r&&!a&&(console.warn(htn),L0t=!0)}for(var i in n)if(!M0t[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 p={};for(var i in t)if(!M0t[i]){var l=i.slice(0,2)==="on",f=n[i]!==t[i];if(l&&f){var c=i.substr(2).toLowerCase();c.substr(0,7)==="content"&&(c="content"+c.substr(7,1).toUpperCase()+c.substr(8)),t[i]&&(p[c]=t[i])}!l&&(t[i]!==n[i]||u&&t[i]!==s.getAttr(i))&&(m=!0,h[i]=t[i])}m&&(s.setAttrs(h),sL(s));for(var c in p)s.on(c+ret,p[c])}function sL(s){if(!fi.autoDrawEnabled){var t=s.getLayer()||s.getStage();t&&t.batchDraw()}}const gUt={},ftn={};R7.Node.prototype._applyProps=FPe;function gtn(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),sL(s)}function xtn(s,t,n){let r=R7[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=R7.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 FPe(c,i),c}function ytn(s,t,n){console.error(`Text components are not supported for now in ReactKonva. Your text is: "${s}"`)}function vtn(s,t,n){return!1}function btn(s){return s}function _tn(){return null}function wtn(){return null}function jtn(s,t,n,r){return ftn}function Ntn(){}function ktn(s){}function Stn(s,t){return!1}function Ctn(){return gUt}function Atn(){return gUt}const Etn=setTimeout,Ttn=clearTimeout,Mtn=-1;function Ptn(s,t){return!1}const Ltn=!1,Itn=!0,Rtn=!0;function Dtn(s,t){t.parent===s?t.moveToTop():s.add(t),sL(s)}function Otn(s,t){t.parent===s?t.moveToTop():s.add(t),sL(s)}function xUt(s,t,n){t._remove(),s.add(t),t.setZIndex(n.getZIndex()),sL(s)}function Ftn(s,t,n){xUt(s,t,n)}function ztn(s,t){t.destroy(),t.off(ret),sL(s)}function Btn(s,t){t.destroy(),t.off(ret),sL(s)}function Utn(s,t,n){console.error(`Text components are not yet supported in ReactKonva. You text is: "${n}"`)}function qtn(s,t,n){}function $tn(s,t,n,r,a){FPe(s,a,r)}function Vtn(s){s.hide(),sL(s)}function Htn(s){}function Gtn(s,t){(t.visible==null||t.visible)&&s.show()}function Wtn(s,t){}function Ktn(s){}function Ytn(){}const Ztn=()=>fUt.DefaultEventPriority,Xtn=Object.freeze(Object.defineProperty({__proto__:null,appendChild:Dtn,appendChildToContainer:Otn,appendInitialChild:gtn,cancelTimeout:Ttn,clearContainer:Ktn,commitMount:qtn,commitTextUpdate:Utn,commitUpdate:$tn,createInstance:xtn,createTextInstance:ytn,detachDeletedInstance:Ytn,finalizeInitialChildren:vtn,getChildHostContext:Atn,getCurrentEventPriority:Ztn,getPublicInstance:btn,getRootHostContext:Ctn,hideInstance:Vtn,hideTextInstance:Htn,idlePriority:mX.unstable_IdlePriority,insertBefore:xUt,insertInContainerBefore:Ftn,isPrimaryRenderer:Ltn,noTimeout:Mtn,now:mX.unstable_now,prepareForCommit:_tn,preparePortalMount:wtn,prepareUpdate:jtn,removeChild:ztn,removeChildFromContainer:Btn,resetAfterCommit:Ntn,resetTextContent:ktn,run:mX.unstable_runWithPriority,scheduleTimeout:Etn,shouldDeprioritizeSubtree:Stn,shouldSetTextContent:Ptn,supportsMutation:Rtn,unhideInstance:Gtn,unhideTextInstance:Wtn,warnsIfNotActing:Itn},Symbol.toStringTag,{value:"Module"}));var Qtn=Object.defineProperty,Jtn=Object.defineProperties,esn=Object.getOwnPropertyDescriptors,I0t=Object.getOwnPropertySymbols,tsn=Object.prototype.hasOwnProperty,ssn=Object.prototype.propertyIsEnumerable,R0t=(s,t,n)=>t in s?Qtn(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,D0t=(s,t)=>{for(var n in t||(t={}))tsn.call(t,n)&&R0t(s,n,t[n]);if(I0t)for(var n of I0t(t))ssn.call(t,n)&&R0t(s,n,t[n]);return s},nsn=(s,t)=>Jtn(s,esn(t)),O0t,F0t;typeof window<"u"&&((O0t=window.document)!=null&&O0t.createElement||((F0t=window.navigator)==null?void 0:F0t.product)==="ReactNative")?j.useLayoutEffect:j.useEffect;function yUt(s,t,n){if(!s)return;if(n(s)===!0)return s;let r=s.child;for(;r;){const a=yUt(r,t,n);if(a)return a;r=r.sibling}}function vUt(s){try{return Object.defineProperties(s,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch{return s}}const z0t=console.error;console.error=function(){const s=[...arguments].join("");if(s!=null&&s.startsWith("Warning:")&&s.includes("useContext")){console.error=z0t;return}return z0t.apply(this,arguments)};const aet=vUt(j.createContext(null));class bUt extends j.Component{render(){return j.createElement(aet.Provider,{value:this._reactInternals},this.props.children)}}function rsn(){const s=j.useContext(aet);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=yUt(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 asn(){const s=rsn(),[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!==aet&&!t.has(a)&&t.set(a,j.useContext(vUt(a)))}n=n.return}return t}function isn(){const s=asn();return j.useMemo(()=>Array.from(s.keys()).reduce((t,n)=>r=>j.createElement(t,null,j.createElement(n.Provider,nsn(D0t({},r),{value:s.get(n)}))),t=>j.createElement(bUt,D0t({},t))),[s])}function osn(s){const t=Dt.useRef({});return Dt.useLayoutEffect(()=>{t.current=s}),Dt.useLayoutEffect(()=>()=>{t.current={}},[]),t.current}const lsn=s=>{const t=Dt.useRef(null),n=Dt.useRef(null),r=Dt.useRef(null),a=osn(s),i=isn(),l=o=>{const{forwardedRef:c}=s;c&&(typeof c=="function"?c(o):c.current=o)};return Dt.useLayoutEffect(()=>(n.current=new R7.Stage({width:s.width,height:s.height,container:t.current}),l(n.current),r.current=PZ.createContainer(n.current,fUt.LegacyRoot,!1,null),PZ.updateContainer(Dt.createElement(i,{},s.children),r.current),()=>{R7.isBrowser&&(l(null),PZ.updateContainer(null,r.current,null),n.current.destroy())}),[]),Dt.useLayoutEffect(()=>{l(n.current),FPe(n.current,s,a),PZ.updateContainer(Dt.createElement(i,{},s.children),r.current,null)}),Dt.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})},csn="Layer",sM="Group",_5="Rect",NU="Image",Jz="Text",exr="Transformer",PZ=utn(Xtn);PZ.injectIntoDevTools({findHostInstanceByFiber:()=>null,bundleType:0,version:Dt.version,rendererPackageName:"react-konva"});const dsn=Dt.forwardRef((s,t)=>Dt.createElement(bUt,{},Dt.createElement(lsn,{...s,forwardedRef:t})));function usn({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),p=(t==null?void 0:t.headshot_url)??"",f=(t==null?void 0:t.brokerage_logo_url)??"";j.useEffect(()=>{if(!s){c(null);return}const H=new window.Image;H.crossOrigin="anonymous",H.onload=()=>c(H),H.onerror=()=>c(null),H.src=s},[s]),j.useEffect(()=>{if(!p){u(null);return}const H=new window.Image;H.crossOrigin="anonymous",H.onload=()=>u(H),H.onerror=()=>u(null),H.src=p},[p]),j.useEffect(()=>{if(!f){m(null);return}const H=new window.Image;H.crossOrigin="anonymous",H.onload=()=>m(H),H.onerror=()=>m(null),H.src=f},[f]);const x=DQs(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]),N=y*b,S=v*b,A=(r==null?void 0:r.brand_color)??(t==null?void 0:t.brand_color)??"#0f172a",T=(r==null?void 0:r.accent_color)??(t==null?void 0:t.accent_color)??"#3b82f6",L=(r==null?void 0:r.display_name)??(t==null?void 0:t.display_name)??"",M=(r==null?void 0:r.phone)??(t==null?void 0:t.phone)??"",I=(r==null?void 0:r.email)??(t==null?void 0:t.email)??"",R=(r==null?void 0:r.tagline)??(t==null?void 0:t.tagline)??"",z=new Set((r==null?void 0:r.hidden_fields)??(t==null?void 0:t.hidden_fields)??[]),$=H=>x.fields.includes(H)&&!z.has(H);return e.jsx("div",{className:"border rounded-lg overflow-hidden bg-muted/40 inline-block",children:e.jsx(dsn,{ref:H=>{l.current=H,i&&(i.current=H)},width:N,height:S,scaleX:b,scaleY:b,children:e.jsxs(csn,{children:[o&&e.jsx(NU,{image:o,width:y,height:v,listening:!1}),!o&&e.jsx(_5,{x:0,y:0,width:y,height:v,fill:"#e2e8f0"}),e.jsx(hsn,{style:x,canvasW:y,canvasH:v,brandColor:A,accentColor:T,name:L,phone:M,email:I,tagline:R,headshot:d,logo:h,hidden:z,has:$})]})})})}function hsn({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,p=m*.18,f=s.textColor==="light"?"#ffffff":s.textColor==="dark"?"#0f172a":s.background==="dark"||s.background==="gradient"?"#ffffff":OQs(r),x=f==="#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(sM,{children:[e.jsx(_5,{x:0,y,width:t,height:m,fill:r}),e.jsx(_5,{x:0,y:s.position==="bottom"?y:m-4,width:t,height:4,fill:a}),e.jsx(fle,{x:p,y:y+p,width:t-p*2,height:m-p*2,textColor:f,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,N=n-v-n*.025;return e.jsxs(sM,{children:[e.jsx(_5,{x:b,y:N,width:y,height:v,fill:r,cornerRadius:v*.12,opacity:.92}),e.jsx(_5,{x:b,y:N+v-4,width:y,height:4,fill:a,cornerRadius:2}),e.jsx(fle,{x:b+p,y:N+p,width:y-p*2,height:v-p*2,textColor:f,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(sM,{children:[e.jsx(_5,{x:t-y,y:0,width:y,height:n,fill:r}),e.jsx(_5,{x:t-y,y:0,width:4,height:n,fill:a}),e.jsx(fle,{x:t-y+v,y:n*.08,width:y-v*2,height:n*.84,textColor:f,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(sM,{children:[e.jsx(_5,{x:0,y:0,width:t,height:m,fill:"#0a0a0a"}),e.jsx(_5,{x:0,y:n-m,width:t,height:m,fill:"#0a0a0a"}),e.jsx(_5,{x:0,y:n-m,width:t,height:3,fill:a}),e.jsx(fle,{x:p,y:n-m+p,width:t-p*2,height:m-p*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(NU,{image:u,x:t-p-m*.7,y:p,height:m-p*2,width:m*.7})]}):null}function fle({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:p,vertical:f,railWidth:x}){if(f){const H=x??n,V=Math.min(n,H*.7),K=Math.max(14,H*.13),Z=Math.max(11,H*.085),Q=H*.08,le=H*.35;let ue=t;const se=ue;ue+=V+Q;const ne=ue,ie=l.length>12?2:1;ue+=K*1.15*ie+Q*.5;const ce=ue;m("phone")&&o&&(ue+=Z*1.3+Q*.4);const je=ue;m("email")&&c&&(ue+=Z*1.3+Q*.4);const be=ue+Q*.5;return e.jsxs(sM,{children:[m("headshot")&&u&&e.jsx(sM,{clipFunc:p?he=>{he.beginPath(),he.arc(s+n/2,se+V/2,V/2,0,Math.PI*2),he.closePath()}:void 0,children:e.jsx(NU,{image:u,x:s+(n-V)/2,y:se,width:V,height:V})}),m("name")&&l&&e.jsx(Jz,{text:l,x:s,y:ne,width:n,align:"center",fontSize:K,fontStyle:"bold",fill:a}),m("phone")&&o&&e.jsx(Jz,{text:o,x:s,y:ce,width:n,align:"center",fontSize:Z,fill:i}),m("email")&&c&&e.jsx(Jz,{text:c,x:s,y:je,width:n,align:"center",fontSize:Z,fill:i,ellipsis:!0,wrap:"none"}),m("logo")&&h&&e.jsx(NU,{image:h,x:s,y:be,width:n,height:le})]})}const y=r*.95,v=u&&m("headshot")?s+y+r*.18:s,b=n-(v-s)-(h&&m("logo")?r*1.6:0),N=Math.max(20,r*.34),S=Math.max(13,r*.22),A=r*.06,T=m("tagline")&&d?1:0,L=m("phone")&&o?1:0,M=m("email")&&c?1:0,I=1+T+(L||M?1:0),R=I*N+(I-1)*A;let $=t+(r-R)/2;return e.jsxs(sM,{children:[m("headshot")&&u&&e.jsx(sM,{clipFunc:p?H=>{H.beginPath(),H.arc(s+y/2,t+y/2,y/2,0,Math.PI*2),H.closePath()}:void 0,children:e.jsx(NU,{image:u,x:s,y:t+(r-y)/2,width:y,height:y})}),m("name")&&l&&e.jsx(Jz,{text:l,x:v,y:$,width:b,fontSize:N,fontStyle:"bold",fill:a,ellipsis:!0,wrap:"none"}),($+=N+A,null),m("tagline")&&d&&e.jsxs(e.Fragment,{children:[e.jsx(Jz,{text:d,x:v,y:$,width:b,fontSize:S*1.1,fontStyle:"italic",fill:i,ellipsis:!0,wrap:"none"}),($+=S*1.1+A,null)]}),L||M?e.jsx(Jz,{text:[o,c].filter(Boolean).join(" • "),x:v,y:$,width:b,fontSize:S,fill:i,ellipsis:!0,wrap:"none"}):null,m("logo")&&h&&e.jsx(NU,{image:h,x:s+n-r*1.4,y:t+(r-r*.8)/2,width:r*1.4,height:r*.8})]})}function msn(){const{data:s}=Nre(),t=(s==null?void 0:s.find($=>$.is_default))??(s==null?void 0:s[0])??null,[n,r]=j.useState(void 0),a=(s==null?void 0:s.find($=>$.id===n))??t,[i,l]=j.useState([]),[o,c]=j.useState(0),[d,u]=j.useState("minimal-stripe"),[h,m]=j.useState({}),[p,f]=j.useState(!1),x=j.useRef(null),[y,v]=j.useState(780),b=j.useRef(null),N=$=>{if(b.current&&(b.current.disconnect(),b.current=null),!$)return;const H=()=>{const K=$.clientWidth;K>0&&v(Math.min(780,K-16))};H();const V=new ResizeObserver(H);V.observe($),b.current=V};j.useEffect(()=>()=>{var $;($=b.current)==null||$.disconnect()},[]);const S=j.useRef(null),A=$=>{if(!$)return;const H=[];Array.from($).forEach(V=>{V.type.startsWith("image/")&&H.push({id:crypto.randomUUID(),url:URL.createObjectURL(V),file:V,name:V.name})}),l(V=>[...V,...H])},T=$=>{l(H=>{const V=H.find(K=>K.id===$);return V&&URL.revokeObjectURL(V.url),H.filter(K=>K.id!==$)}),c(0)},L=typeof navigator<"u"&&/iPad|iPhone|iPod/.test(navigator.userAgent),M=$=>{var le;const[H,V]=$.split(","),K=((le=H.match(/:(.*?);/))==null?void 0:le[1])??"image/jpeg",Z=atob(V),Q=new Uint8Array(Z.length);for(let ue=0;ue{var $;if(S.current){f(!0);try{const H=S.current,V=H.toDataURL({pixelRatio:1/(H.scaleX()||1),mimeType:"image/jpeg",quality:.95}),Z=`${(($=i[o])==null?void 0:$.name.replace(/\.[^.]+$/,""))||"branded"}-branded.jpg`,Q=M(V),le=URL.createObjectURL(Q);if(L)window.open(le,"_blank")||(window.location.href=le),re.success('Long-press the image and tap "Save to Photos"');else{const ue=document.createElement("a");ue.href=le,ue.download=Z,document.body.appendChild(ue),ue.click(),ue.remove(),re.success("Image exported")}setTimeout(()=>URL.revokeObjectURL(le),6e4)}catch(H){re.error(H.message||"Export failed")}finally{f(!1)}}},R=async()=>{if(i.length){f(!0);try{const $=new kBt,H=i.length,V=o;for(let Q=0;QsetTimeout(ie,600)),!S.current)continue;const le=S.current,se=le.toDataURL({pixelRatio:1/(le.scaleX()||1),mimeType:"image/jpeg",quality:.95}).split(",")[1],ne=i[Q].name.replace(/\.[^.]+$/,"")||`image-${Q+1}`;$.file(`${ne}-branded.jpg`,se,{base64:!0})}c(V);const K=await $.generateAsync({type:"blob"}),Z=document.createElement("a");Z.href=URL.createObjectURL(K),Z.download=`branded-images-${Date.now()}.zip`,Z.click(),URL.revokeObjectURL(Z.href),re.success(`${H} images exported`)}catch($){re.error($.message||"Batch export failed")}finally{f(!1)}}},z=i[o];return e.jsx(qs,{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(xr,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(Aa,{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(U,{variant:"outline",asChild:!0,className:"w-full sm:w-auto",children:e.jsxs(xr,{to:"/marketing-studio/brand-kit",children:[e.jsx($c,{className:"h-4 w-4 mr-1"})," Brand Kit"]})})]}),!a&&e.jsx(we,{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(U,{asChild:!0,className:"w-full sm:w-auto",children:e.jsx(xr,{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(we,{className:"overflow-hidden",children:e.jsxs(Ie,{className:"p-4",children:[z?e.jsx("div",{ref:N,className:"flex justify-center bg-muted/30 rounded p-2 overflow-hidden",children:e.jsx(usn,{imageUrl:z.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 $;return($=x.current)==null?void 0:$.click()},onDragOver:$=>$.preventDefault(),onDrop:$=>{$.preventDefault(),A($.dataTransfer.files)},children:[e.jsx(pc,{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(U,{type:"button",children:[e.jsx(qa,{className:"h-4 w-4 mr-1"})," Choose images"]})]}),e.jsx("input",{ref:x,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:$=>A($.target.files)})]})}),i.length>0&&e.jsx(we,{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(($,H)=>e.jsxs("div",{className:"relative group flex-shrink-0",children:[e.jsx("button",{onClick:()=>c(H),className:`block h-16 w-16 rounded overflow-hidden border-2 transition-all ${H===o?"border-primary":"border-transparent hover:border-muted-foreground/30"}`,children:e.jsx("img",{src:$.url,alt:"",className:"h-full w-full object-cover"})}),e.jsx("button",{onClick:()=>T($.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(er,{className:"h-3 w-3"})})]},$.id)),e.jsx("button",{onClick:()=>{var $;return($=x.current)==null?void 0:$.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(an,{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(U,{variant:"outline",onClick:()=>{i.forEach($=>URL.revokeObjectURL($.url)),l([])},children:"Clear all"}),e.jsxs(U,{onClick:I,disabled:p||!z,children:[p?e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(pi,{className:"h-4 w-4 mr-1"}),"Download this image"]}),i.length>1&&e.jsxs(U,{onClick:R,disabled:p,children:[p?e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(pi,{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(we,{className:"overflow-hidden",children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{className:"text-base",children:"Brand preset"})}),e.jsx(Ie,{children:e.jsxs(Ns,{value:(a==null?void 0:a.id)??"",onValueChange:r,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Choose preset"})}),e.jsx(js,{children:s==null?void 0:s.map($=>e.jsxs(et,{value:$.id,children:[$.name," ",$.is_default?"(default)":""]},$.id))})]})})]}),e.jsxs(we,{className:"overflow-hidden",children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{className:"text-base",children:"Bar style"})}),e.jsx(Ie,{children:e.jsx(FQs,{value:d,onChange:u,mediaType:"image"})})]}),e.jsxs(we,{className:"overflow-hidden",children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{className:"text-base",children:"Tweak this design"})}),e.jsx(Ie,{children:e.jsxs(oa,{defaultValue:"text",children:[e.jsxs(la,{className:"grid grid-cols-2 w-full",children:[e.jsx(Kt,{value:"text",children:"Text"}),e.jsx(Kt,{value:"colors",children:"Colors"})]}),e.jsxs(Zt,{value:"text",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Display name"}),e.jsx(xe,{value:h.display_name??(a==null?void 0:a.display_name)??"",onChange:$=>m({...h,display_name:$.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Phone"}),e.jsx(xe,{value:h.phone??(a==null?void 0:a.phone)??"",onChange:$=>m({...h,phone:$.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Email"}),e.jsx(xe,{value:h.email??(a==null?void 0:a.email)??"",onChange:$=>m({...h,email:$.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Tagline"}),e.jsx(xe,{value:h.tagline??(a==null?void 0:a.tagline)??"",onChange:$=>m({...h,tagline:$.target.value})})]})]}),e.jsxs(Zt,{value:"colors",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(te,{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:$=>m({...h,brand_color:$.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(xe,{value:h.brand_color??(a==null?void 0:a.brand_color)??"#0f172a",onChange:$=>m({...h,brand_color:$.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(te,{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:$=>m({...h,accent_color:$.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(xe,{value:h.accent_color??(a==null?void 0:a.accent_color)??"#3b82f6",onChange:$=>m({...h,accent_color:$.target.value})})]})]}),e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>m({}),children:"Reset to preset"})]})]})})]})]})]})]})})}function psn(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 fsn=(()=>{let s=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(s+=1,`u${t()}${s}`)})();function GM(s){const t=[];for(let n=0,r=s.length;nrw||s.height>rw)&&(s.width>rw&&s.height>rw?s.width>s.height?(s.height*=rw/s.width,s.width=rw):(s.width*=rw/s.height,s.height=rw):s.width>rw?(s.height*=rw/s.width,s.width=rw):(s.width*=rw/s.height,s.height=rw))}function kAe(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 bsn(s){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(s)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function _sn(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),bsn(a)}const T_=(s,t)=>{if(s instanceof t)return!0;const n=Object.getPrototypeOf(s);return n===null?!1:n.constructor.name===t.name||T_(n,t)};function wsn(s){const t=s.getPropertyValue("content");return`${s.cssText} content: '${t.replace(/'|"/g,"")}';`}function jsn(s,t){return _Ut(t).map(n=>{const r=s.getPropertyValue(n),a=s.getPropertyPriority(n);return`${n}: ${r}${a?" !important":""};`}).join(" ")}function Nsn(s,t,n,r){const a=`.${s}:${t}`,i=n.cssText?wsn(n):jsn(n,r);return document.createTextNode(`${a}{${i}}`)}function B0t(s,t,n,r){const a=window.getComputedStyle(s,n),i=a.getPropertyValue("content");if(i===""||i==="none")return;const l=fsn();try{t.className=`${t.className} ${l}`}catch{return}const o=document.createElement("style");o.appendChild(Nsn(l,n,a,r)),t.appendChild(o)}function ksn(s,t,n){B0t(s,t,":before",n),B0t(s,t,":after",n)}const U0t="application/font-woff",q0t="image/jpeg",Ssn={woff:U0t,woff2:U0t,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:q0t,jpeg:q0t,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function Csn(s){const t=/\.([^./]*?)$/g.exec(s);return t?t[1]:""}function iet(s){const t=Csn(s).toLowerCase();return Ssn[t]||""}function Asn(s){return s.split(/,/)[1]}function lVe(s){return s.search(/^(data:)/)!==-1}function Esn(s,t){return`data:${t};base64,${s}`}async function jUt(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 YFe={};function Tsn(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 oet(s,t,n){const r=Tsn(s,t,n.includeQueryParams);if(YFe[r]!=null)return YFe[r];n.cacheBust&&(s+=(/\?/.test(s)?"&":"?")+new Date().getTime());let a;try{const i=await jUt(s,n.fetchRequestInit,({res:l,result:o})=>(t||(t=l.headers.get("Content-Type")||""),Asn(o)));a=Esn(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 YFe[r]=a,a}async function Msn(s){const t=s.toDataURL();return t==="data:,"?s.cloneNode(!1):kAe(t)}async function Psn(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 kAe(o)}const n=s.poster,r=iet(n),a=await oet(n,r,t);return kAe(a)}async function Lsn(s,t){var n;try{if(!((n=s==null?void 0:s.contentDocument)===null||n===void 0)&&n.body)return await zPe(s.contentDocument.body,t,!0)}catch{}return s.cloneNode(!1)}async function Isn(s,t){return T_(s,HTMLCanvasElement)?Msn(s):T_(s,HTMLVideoElement)?Psn(s,t):T_(s,HTMLIFrameElement)?Lsn(s,t):s.cloneNode(NUt(s))}const Rsn=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SLOT",NUt=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SVG";async function Dsn(s,t,n){var r,a;if(NUt(t))return t;let i=[];return Rsn(s)&&s.assignedNodes?i=GM(s.assignedNodes()):T_(s,HTMLIFrameElement)&&(!((r=s.contentDocument)===null||r===void 0)&&r.body)?i=GM(s.contentDocument.body.childNodes):i=GM(((a=s.shadowRoot)!==null&&a!==void 0?a:s).childNodes),i.length===0||T_(s,HTMLVideoElement)||await i.reduce((l,o)=>l.then(()=>zPe(o,n)).then(c=>{c&&t.appendChild(c)}),Promise.resolve()),t}function Osn(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):_Ut(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`),T_(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 Fsn(s,t){T_(s,HTMLTextAreaElement)&&(t.innerHTML=s.value),T_(s,HTMLInputElement)&&t.setAttribute("value",s.value)}function zsn(s,t){if(T_(s,HTMLSelectElement)){const n=t,r=Array.from(n.children).find(a=>s.value===a.getAttribute("value"));r&&r.setAttribute("selected","")}}function Bsn(s,t,n){return T_(t,Element)&&(Osn(s,t,n),ksn(s,t,n),Fsn(s,t),zsn(s,t)),t}async function Usn(s,t){const n=s.querySelectorAll?s.querySelectorAll("use"):[];if(n.length===0)return s;const r={};for(let i=0;iIsn(r,t)).then(r=>Dsn(s,r,t)).then(r=>Bsn(s,r,t)).then(r=>Usn(r,t))}const kUt=/url\((['"]?)([^'"]+?)\1\)/g,qsn=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,$sn=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function Vsn(s){const t=s.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function Hsn(s){const t=[];return s.replace(kUt,(n,r,a)=>(t.push(a),n)),t.filter(n=>!lVe(n))}async function Gsn(s,t,n,r,a){try{const i=n?psn(t,n):t,l=iet(t);let o;return a||(o=await oet(i,l,r)),s.replace(Vsn(t),`$1${o}$3`)}catch{}return s}function Wsn(s,{preferredFontFormat:t}){return t?s.replace($sn,n=>{for(;;){const[r,,a]=qsn.exec(n)||[];if(!a)return"";if(a===t)return`src: ${r};`}}):s}function SUt(s){return s.search(kUt)!==-1}async function CUt(s,t,n){if(!SUt(s))return s;const r=Wsn(s,n);return Hsn(r).reduce((i,l)=>i.then(o=>Gsn(o,l,t,n)),Promise.resolve(r))}async function tB(s,t,n){var r;const a=(r=t.style)===null||r===void 0?void 0:r.getPropertyValue(s);if(a){const i=await CUt(a,null,n);return t.style.setProperty(s,i,t.style.getPropertyPriority(s)),!0}return!1}async function Ksn(s,t){await tB("background",s,t)||await tB("background-image",s,t),await tB("mask",s,t)||await tB("-webkit-mask",s,t)||await tB("mask-image",s,t)||await tB("-webkit-mask-image",s,t)}async function Ysn(s,t){const n=T_(s,HTMLImageElement);if(!(n&&!lVe(s.src))&&!(T_(s,SVGImageElement)&&!lVe(s.href.baseVal)))return;const r=n?s.src:s.href.baseVal,a=await oet(r,iet(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 Zsn(s,t){const r=GM(s.childNodes).map(a=>AUt(a,t));await Promise.all(r).then(()=>s)}async function AUt(s,t){T_(s,Element)&&(await Ksn(s,t),await Ysn(s,t),await Zsn(s,t))}function Xsn(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 $0t={};async function V0t(s){let t=$0t[s];if(t!=null)return t;const r=await(await fetch(s)).text();return t={url:s,cssText:r},$0t[s]=t,t}async function H0t(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),jUt(o,t.fetchRequestInit,({result:c})=>(n=n.replace(l,`url(${c})`),[l,c]))});return Promise.all(i).then(()=>n)}function G0t(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 Qsn(s,t){const n=[],r=[];return s.forEach(a=>{if("cssRules"in a)try{GM(a.cssRules||[]).forEach((i,l)=>{if(i.type===CSSRule.IMPORT_RULE){let o=l+1;const c=i.href,d=V0t(c).then(u=>H0t(u,t)).then(u=>G0t(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(V0t(a.href).then(o=>H0t(o,t)).then(o=>G0t(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{GM(a.cssRules||[]).forEach(i=>{n.push(i)})}catch(i){console.error(`Error while reading CSS rules from ${a.href}`,i)}}),n))}function Jsn(s){return s.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>SUt(t.style.getPropertyValue("src")))}async function enn(s,t){if(s.ownerDocument==null)throw new Error("Provided element is not within a Document");const n=GM(s.ownerDocument.styleSheets),r=await Qsn(n,t);return Jsn(r)}function EUt(s){return s.trim().replace(/["']/g,"")}function tnn(s){const t=new Set;function n(r){(r.style.fontFamily||getComputedStyle(r).fontFamily).split(",").forEach(i=>{t.add(EUt(i))}),Array.from(r.children).forEach(i=>{i instanceof HTMLElement&&n(i)})}return n(s),t}async function snn(s,t){const n=await enn(s,t),r=tnn(s);return(await Promise.all(n.filter(i=>r.has(EUt(i.style.fontFamily))).map(i=>{const l=i.parentStyleSheet?i.parentStyleSheet.href:null;return CUt(i.cssText,l,t)}))).join(` `)}async function nnn(s,t){const n=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await snn(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 TUt(s,t={}){const{width:n,height:r}=wUt(s,t),a=await zPe(s,t,!0);return await nnn(a,t),await AUt(a,t),Xsn(a,t),await _sn(a,n,r)}async function MUt(s,t={}){const{width:n,height:r}=wUt(s,t),a=await TUt(s,t),i=await kAe(a),l=document.createElement("canvas"),o=l.getContext("2d"),c=t.pixelRatio||ysn(),d=t.canvasWidth||n,u=t.canvasHeight||r;return l.width=d*c,l.height=u*c,t.skipAutoScale||vsn(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 eH(s,t={}){return(await MUt(s,t)).toDataURL()}const PUt=Object.freeze(Object.defineProperty({__proto__:null,toCanvas:MUt,toPng:eH,toSvg:TUt},Symbol.toStringTag,{value:"Module"})),tH=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),BPe={"just-listed":"JUST LISTED","just-sold":"JUST SOLD","open-house":"OPEN HOUSE","price-drop":"PRICE DROP"},nM={"instagram-square":{width:1080,height:1080},"instagram-story":{width:1080,height:1920},"facebook-post":{width:1200,height:630}},rnn=({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})]})]}),cet=Dt.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=BPe[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:tH(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.028,color:"#C9A84C",marginBottom:l.w*.01},children:["Sold for ",tH(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(rnn,{branding:r,dim:l})]})]})]})});cet.displayName="LuxuryDarkTemplate";const ann=({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})]})]}),det=Dt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var p;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=(p=s.photos)==null?void 0:p[a],d=BPe[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:tH(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(ann,{branding:r,dim:l,accentColor:m})]})]})});det.displayName="ModernCleanTemplate";const inn=({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})]})]}),uet=Dt.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=BPe[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:tH(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(inn,{branding:r,dim:l})]})]})]})});uet.displayName="BoldColorfulTemplate";const onn=({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})]})]}),het=Dt.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=BPe[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:tH(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.02,color:"#8B7355",marginBottom:l.w*.01},children:["Sold: ",tH(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(onn,{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"}})]})]})})});het.displayName="EditorialTemplate";const lnn=[{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:"📉"}],W0t=[{value:"instagram-square",label:"IG Post",dimensions:"1080×1080",icon:e.jsx(gm,{className:"h-4 w-4"})},{value:"instagram-story",label:"IG Story",dimensions:"1080×1920",icon:e.jsx(gm,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook",dimensions:"1200×630",icon:e.jsx(zp,{className:"h-4 w-4"})}],cnn=[{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:"📰"}],K0t={"luxury-dark":cet,"modern-clean":det,"bold-colorful":uet,editorial:het},ZFe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s);function dnn(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;oke.is_default))??(s==null?void 0:s[0])??null,[n,r]=j.useState(void 0),a=(s==null?void 0:s.find(ke=>ke.id===n))??t,i=Sa(),[l,o]=j.useState("mine"),[c,d]=j.useState(""),[u,h]=j.useState("address"),[m,p]=j.useState(!1),[f,x]=j.useState([]),[y,v]=j.useState(null),[b,N]=j.useState(0),[S,A]=j.useState("just-listed"),[T,L]=j.useState(["instagram-square"]),[M,I]=j.useState("luxury-dark"),[R,z]=j.useState(!0),[$,H]=j.useState(!1),[V,K]=j.useState([]),[Z,Q]=j.useState("search"),le=j.useRef({}),{data:ue=[],isLoading:se}=ct({queryKey:["marketing-studio-my-listings",i],enabled:!!i,queryFn:async()=>{const{data:ke,error:Te}=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(Te)throw Te;return(ke||[]).map(Me=>{const Oe=(Me.listing_photos||[]).slice().sort((Qe,Ae)=>(Ae.is_primary?1:0)-(Qe.is_primary?1:0)||(Qe.sort_order??0)-(Ae.sort_order??0)).map(Qe=>Qe.photo_url).filter(Boolean),Se=String(Me.status||"");return{mlsNumber:Me.id,address:Me.property_address||"",city:Me.city||"",state:Me.state||"",zip:"",price:Number(Me.price||0),status:Se,bedrooms:Number(Me.bedrooms||0),bathrooms:Number(Me.bathrooms||0),sqft:Number(Me.square_footage||0),lotSize:"",yearBuilt:Me.year_built??null,propertyType:Me.property_type||"",description:Me.description||"",photos:Oe,listDate:Me.created_at,soldDate:Se.toLowerCase().includes("sold")?Me.created_at:null,soldPrice:null,agent:{name:"",office:""}}})}}),ne=j.useMemo(()=>!R||!a?{enabled:!1}:{enabled:!0,agentName:a.display_name||"",brokerage:a.tagline||"",agentPhotoUrl:a.headshot_url||void 0},[R,a]),ie=async()=>{if(c.trim()){p(!0),x([]);try{const{data:ke,error:Te}=await q.functions.invoke("repliers-mls-search",{body:{searchType:u,query:c.trim()}});if(Te)throw Te;if(ke!=null&&ke.error)throw new Error(ke.error);x((ke==null?void 0:ke.listings)||[]),((ke==null?void 0:ke.listings)||[]).length===0&&re.info("No listings found. Try a different search.")}catch(ke){re.error(ke.message||"Search failed")}finally{p(!1)}}},ce=ke=>{var Te;v(ke),N(0),Q("customize"),ke.soldDate||(Te=ke.status)!=null&&Te.toLowerCase().includes("sold")?A("just-sold"):A("just-listed")},je=ke=>L(Te=>Te.includes(ke)?Te.filter(Me=>Me!==ke):[...Te,ke]),be=y?{listing:y,postType:S,format:"instagram-square",branding:ne,selectedPhotoIndex:b}:null,he=j.useCallback(async()=>{if(!(!y||T.length===0)){H(!0),K([]),Q("generate");try{await new Promise(Te=>setTimeout(Te,600));const ke=[];for(const Te of T){const Me=`${M}-${Te}`,Oe=le.current[Me];if(!Oe)continue;const Se=nM[Te],Qe=await eH(Oe,{width:Se.width,height:Se.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});ke.push({format:Te,url:Qe})}K(ke),re.success(`Generated ${ke.length} design${ke.length>1?"s":""}!`)}catch(ke){re.error(ke.message||"Generation failed")}finally{H(!1)}}},[y,T,M]),ge=(ke,Te)=>{const Me=`${((y==null?void 0:y.address)||"listing").replace(/\s+/g,"-")}-${S}-${Te}.png`;try{const Oe=dnn(ke),Se=URL.createObjectURL(Oe);if(unn)window.open(Se,"_blank"),re.message("Long-press the image to save to Photos");else{const Qe=document.createElement("a");Qe.href=Se,Qe.download=Me,document.body.appendChild(Qe),Qe.click(),document.body.removeChild(Qe)}setTimeout(()=>URL.revokeObjectURL(Se),6e4)}catch{const Oe=document.createElement("a");Oe.href=ke,Oe.download=Me,Oe.click()}};return j.useEffect(()=>{!n&&t&&r(t.id)},[t,n]),e.jsx(qs,{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(U,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs(xr,{to:"/marketing-studio",children:[e.jsx(Aa,{className:"h-4 w-4 mr-1"})," Marketing Studio"]})})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Be,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(cn,{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(te,{className:"text-xs text-muted-foreground",children:"Brand preset"}),e.jsxs(Ns,{value:n,onValueChange:r,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Default"})}),e.jsx(js,{children:s.map(ke=>e.jsxs(et,{value:ke.id,children:[ke.name,ke.is_default?" (default)":""]},ke.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:()=>Q("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${Z==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"}`,children:[e.jsx(Fr,{className:"h-3.5 w-3.5"})," 1. Find listing"]}),e.jsx(gi,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{onClick:()=>y&&Q("customize"),disabled:!y,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${Z==="customize"?"bg-primary text-primary-foreground":y?"bg-muted text-muted-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(cn,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(gi,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${Z==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(pi,{className:"h-3.5 w-3.5"})," 3. Download"]})]}),Z==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(oa,{value:l,onValueChange:ke=>o(ke),children:e.jsxs(la,{className:"grid grid-cols-2 w-full sm:w-auto",children:[e.jsxs(Kt,{value:"mine",children:[e.jsx(ra,{className:"h-4 w-4 mr-1.5"})," My Listings"]}),e.jsxs(Kt,{value:"mls",children:[e.jsx(Fr,{className:"h-4 w-4 mr-1.5"})," MLS Search"]})]})}),l==="mine"&&e.jsx("div",{className:"space-y-3",children:se?e.jsx(we,{children:e.jsx(Ie,{className:"py-12 flex items-center justify-center",children:e.jsx(Et,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):ue.length===0?e.jsx(we,{children:e.jsxs(Ie,{className:"py-10 text-center space-y-2",children:[e.jsx(ra,{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(U,{variant:"outline",size:"sm",asChild:!0,className:"mt-2",children:e.jsx(xr,{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:[ue.length," listing",ue.length!==1?"s":""," from your Listing Exchange"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:ue.map((ke,Te)=>{var Me;return e.jsx(we,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>ce(ke),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:(Me=ke.photos)!=null&&Me[0]?e.jsx("img",{src:ke.photos[0],alt:ke.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(ra,{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:ke.price>0?ZFe(ke.price):"—"}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:ke.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[ke.city,ke.state?`, ${ke.state}`:""]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[ke.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(C4,{className:"h-3 w-3"})," ",ke.bedrooms]}),ke.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(d0,{className:"h-3 w-3"})," ",ke.bathrooms]}),ke.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(PF,{className:"h-3 w-3"})," ",ke.sqft.toLocaleString()]})]}),ke.status&&e.jsx("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:e.jsx(Be,{variant:"outline",className:"text-[10px]",children:ke.status})})]})]})})},ke.mlsNumber||Te)})})]})}),l==="mls"&&e.jsxs(e.Fragment,{children:[e.jsxs(we,{className:"overflow-hidden",children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2 text-base md:text-lg",children:[e.jsx(Fr,{className:"h-5 w-5 text-primary"})," Search MLS"]}),e.jsxs(Jn,{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(oa,{value:u,onValueChange:ke=>h(ke),children:e.jsxs(la,{children:[e.jsxs(Kt,{value:"address",children:[e.jsx(ni,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Kt,{value:"mls",children:[e.jsx(Cf,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(xe,{value:c,onChange:ke=>d(ke.target.value),placeholder:u==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:ke=>ke.key==="Enter"&&ie()}),e.jsxs(U,{onClick:ie,disabled:m||!c.trim(),className:"sm:w-auto w-full",children:[m?e.jsx(Et,{className:"h-4 w-4 animate-spin mr-1.5"}):e.jsx(Fr,{className:"h-4 w-4 mr-1.5"})," Search"]})]})]})]}),f.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[f.length," listing",f.length!==1?"s":""," found"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:f.map((ke,Te)=>{var Me;return e.jsx(we,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>ce(ke),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:(Me=ke.photos)!=null&&Me[0]?e.jsx("img",{src:ke.photos[0],alt:ke.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(ra,{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:ZFe(ke.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:ke.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[ke.city,", ",ke.state," ",ke.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[ke.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(C4,{className:"h-3 w-3"})," ",ke.bedrooms]}),ke.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(d0,{className:"h-3 w-3"})," ",ke.bathrooms]}),ke.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(PF,{className:"h-3 w-3"})," ",ke.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[ke.mlsNumber&&e.jsx(Be,{variant:"outline",className:"text-[10px]",children:ke.mlsNumber}),ke.status&&e.jsx(Be,{variant:"outline",className:"text-[10px]",children:ke.status})]})]})]})})},ke.mlsNumber||Te)})})]})]})]}),Z==="customize"&&y&&be&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 md:gap-6",children:[e.jsxs(we,{className:"lg:col-span-1 overflow-hidden min-w-0",children:[e.jsx(Tt,{className:"pb-3",children:e.jsx(It,{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(U,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>N(ke=>Math.max(0,ke-1)),disabled:b===0,children:e.jsx(rd,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[b+1," of ",y.photos.length]}),e.jsx(U,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>N(ke=>Math.min(y.photos.length-1,ke+1)),disabled:b===y.photos.length-1,children:e.jsx(gi,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:ZFe(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(U,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{Q("search"),v(null)},children:[e.jsx(Kg,{className:"h-3.5 w-3.5 mr-1.5"})," Choose different listing"]})]})]}),e.jsxs(we,{className:"lg:col-span-2 overflow-hidden min-w-0",children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx(cn,{className:"h-5 w-5 text-primary"})," Customize"]}),e.jsx(Jn,{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(te,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx($c,{className:"h-4 w-4"})," Template style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:cnn.map(ke=>e.jsxs("button",{onClick:()=>I(ke.value),className:`flex flex-col items-center gap-1 px-2 py-3 rounded-lg border-2 transition-all text-center ${M===ke.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:ke.preview}),e.jsx("span",{className:"text-sm font-medium",children:ke.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:ke.description})]},ke.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-sm font-medium",children:"Post type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:lnn.map(ke=>e.jsxs("button",{onClick:()=>A(ke.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===ke.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:ke.icon})," ",e.jsx("span",{className:"truncate",children:ke.label})]},ke.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-sm font-medium",children:"Output formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:W0t.map(ke=>e.jsxs("button",{onClick:()=>je(ke.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${T.includes(ke.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[ke.icon,e.jsxs("div",{className:"text-left min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:ke.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:ke.dimensions})]})]},ke.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(te,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(So,{className:"h-4 w-4"})," Show my branding"]}),e.jsx(wn,{checked:R,onCheckedChange:z})]}),R&&!a&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["No brand preset yet. ",e.jsx(xr,{to:"/marketing-studio/brand-kit",className:"underline",children:"Create one"})," to add your headshot and name."]}),R&&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(te,{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*(nM[T[0]||"instagram-square"].height/nM[T[0]||"instagram-square"].width)},children:(()=>{const ke=K0t[M],Te=T[0]||"instagram-square";return e.jsx(ke,{...be,format:Te})})()})})]}),e.jsx(U,{onClick:he,disabled:T.length===0||$,size:"lg",className:"w-full gap-2",children:$?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-5 w-5 animate-spin"})," Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(cn,{className:"h-5 w-5"})," Generate ",T.length," design",T.length>1?"s":""]})})]})]})]}),Z==="generate"&&e.jsxs("div",{className:"space-y-4",children:[$&&e.jsx(we,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(Et,{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(U,{variant:"outline",size:"sm",onClick:()=>Q("customize"),children:[e.jsx(Kg,{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((ke,Te)=>{const Me=W0t.find(Oe=>Oe.value===ke.format);return e.jsxs(we,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:ke.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:[Me==null?void 0:Me.icon,e.jsx("span",{className:"text-sm font-medium",children:Me==null?void 0:Me.label})]}),e.jsx(Be,{variant:"outline",className:"text-[10px]",children:Me==null?void 0:Me.dimensions})]}),e.jsxs(U,{size:"sm",className:"w-full gap-1.5",onClick:()=>ge(ke.url,ke.format),children:[e.jsx(pi,{className:"h-3.5 w-3.5"})," Download"]})]})]},Te)})})]})]}),Z==="generate"&&y&&be&&e.jsx("div",{style:{position:"fixed",left:"-99999px",top:0,pointerEvents:"none"},"aria-hidden":!0,children:T.map(ke=>{const Te=K0t[M],Me=nM[ke];return e.jsx("div",{style:{width:Me.width,height:Me.height},children:e.jsx(Te,{ref:Oe=>{le.current[`${M}-${ke}`]=Oe},...be,format:ke})},`${M}-${ke}`)})})]})})}var LUt="Toggle",met=j.forwardRef((s,t)=>{const{pressed:n,defaultPressed:r,onPressedChange:a,...i}=s,[l,o]=Sx({prop:n,onChange:a,defaultProp:r??!1,caller:LUt});return e.jsx(si.button,{type:"button","aria-pressed":l,"data-state":l?"on":"off","data-disabled":s.disabled?"":void 0,...i,ref:t,onClick:va(s.onClick,()=>{s.disabled||o(!l)})})});met.displayName=LUt;var IUt=met,nL="ToggleGroup",[RUt,txr]=Up(nL,[DP]),DUt=DP(),pet=Dt.forwardRef((s,t)=>{const{type:n,...r}=s;if(n==="single"){const a=r;return e.jsx(mnn,{...a,ref:t})}if(n==="multiple"){const a=r;return e.jsx(pnn,{...a,ref:t})}throw new Error(`Missing prop \`type\` expected on \`${nL}\``)});pet.displayName=nL;var[OUt,FUt]=RUt(nL),mnn=Dt.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=Sx({prop:n,defaultProp:r??"",onChange:a,caller:nL});return e.jsx(OUt,{scope:s.__scopeToggleGroup,type:"single",value:Dt.useMemo(()=>l?[l]:[],[l]),onItemActivate:o,onItemDeactivate:Dt.useCallback(()=>o(""),[o]),children:e.jsx(zUt,{...i,ref:t})})}),pnn=Dt.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=Sx({prop:n,defaultProp:r??[],onChange:a,caller:nL}),c=Dt.useCallback(u=>o((h=[])=>[...h,u]),[o]),d=Dt.useCallback(u=>o((h=[])=>h.filter(m=>m!==u)),[o]);return e.jsx(OUt,{scope:s.__scopeToggleGroup,type:"multiple",value:l,onItemActivate:c,onItemDeactivate:d,children:e.jsx(zUt,{...i,ref:t})})});pet.displayName=nL;var[fnn,gnn]=RUt(nL),zUt=Dt.forwardRef((s,t)=>{const{__scopeToggleGroup:n,disabled:r=!1,rovingFocus:a=!0,orientation:i,dir:l,loop:o=!0,...c}=s,d=DUt(n),u=xE(l),h={role:"group",dir:u,...c};return e.jsx(fnn,{scope:n,rovingFocus:a,disabled:r,children:a?e.jsx(V6e,{asChild:!0,...d,orientation:i,dir:u,loop:o,children:e.jsx(si.div,{...h,ref:t})}):e.jsx(si.div,{...h,ref:t})})}),SAe="ToggleGroupItem",BUt=Dt.forwardRef((s,t)=>{const n=FUt(SAe,s.__scopeToggleGroup),r=gnn(SAe,s.__scopeToggleGroup),a=DUt(s.__scopeToggleGroup),i=n.value.includes(s.value),l=r.disabled||s.disabled,o={...s,pressed:i,disabled:l},c=Dt.useRef(null);return r.rovingFocus?e.jsx(H6e,{asChild:!0,...a,focusable:!l,active:i,ref:c,children:e.jsx(Y0t,{...o,ref:t})}):e.jsx(Y0t,{...o,ref:t})});BUt.displayName=SAe;var Y0t=Dt.forwardRef((s,t)=>{const{__scopeToggleGroup:n,value:r,...a}=s,i=FUt(SAe,n),l={role:"radio","aria-checked":s.pressed,"aria-pressed":void 0},o=i.type==="single"?l:void 0;return e.jsx(met,{...o,...a,ref:t,onPressedChange:c=>{c?i.onItemActivate(r):i.onItemDeactivate(r)}})}),UUt=pet,qUt=BUt;const $Ut=u9("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"}}),xnn=j.forwardRef(({className:s,variant:t,size:n,...r},a)=>e.jsx(IUt,{ref:a,className:Mt($Ut({variant:t,size:n,className:s})),...r}));xnn.displayName=IUt.displayName;const VUt=j.createContext({size:"default",variant:"default"}),Uq=j.forwardRef(({className:s,variant:t,size:n,children:r,...a},i)=>e.jsx(UUt,{ref:i,className:Mt("flex items-center justify-center gap-1",s),...a,children:e.jsx(VUt.Provider,{value:{variant:t,size:n},children:r})}));Uq.displayName=UUt.displayName;const JF=j.forwardRef(({className:s,children:t,variant:n,size:r,...a},i)=>{const l=j.useContext(VUt);return e.jsx(qUt,{ref:i,className:Mt($Ut({variant:l.variant||n,size:l.size||r}),s),...a,children:t})});JF.displayName=qUt.displayName;const ynn=[{id:"meet",label:"Meet Your Agent",icon:So,description:"Polished intro card with your headshot, story, and contact."},{id:"testimonial",label:"Testimonial",icon:tS,description:"Turn a Zillow / Google review into a branded graphic."},{id:"milestone",label:"Milestone",icon:Al,description:"Celebrate homes sold, awards, anniversaries, achievements."},{id:"tip",label:"Pro Tip",icon:eS,description:"Drop a value-bomb tip — buyer/seller advice, market insight."},{id:"quote",label:"Quote / Mantra",icon:Th,description:"Personal philosophy, mantra, or rallying call."}],XFe={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"}},vnn=[{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."}],Z0t={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 bnn(){const{data:s}=TQs(),{data:t}=Nre(),[n,r]=j.useState(void 0),a=j.useMemo(()=>(t==null?void 0:t.find(f=>f.id===n))??s??null,[t,n,s]),[i,l]=j.useState({template:"meet",style:"editorial",aspect:"portrait",rating:5,...Z0t.meet}),o=f=>l(x=>({...x,...f})),c=f=>l(x=>({...x,template:f,...Z0t[f]})),d=j.useRef(null),[u,h]=j.useState(!1),m=async()=>{if(!d.current)return;h(!0);const f=d.current,x=f.style.transform;try{f.style.transform="none",await new Promise(b=>requestAnimationFrame(()=>b(null)));const y=await eH(f,{cacheBust:!0,pixelRatio:2,width:f.offsetWidth,height:f.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{f.style.transform=x,h(!1)}},p=XFe[i.aspect];return e.jsx(qs,{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(xr,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(Aa,{className:"h-3 w-3"})," Back to Marketing Studio"]}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(cn,{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(U,{variant:"outline",asChild:!0,children:e.jsxs(xr,{to:"/marketing-studio/brand-kit",children:[e.jsx($c,{className:"h-4 w-4 mr-1"})," Brand Kit"]})}),e.jsxs(U,{onClick:m,disabled:u,children:[e.jsx(pi,{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(we,{children:e.jsxs(Ie,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Template"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:ynn.map(f=>{const x=f.icon,y=i.template===f.id;return e.jsxs("button",{onClick:()=>c(f.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:f.label})]},f.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Style"}),e.jsx(Uq,{type:"single",value:i.style,onValueChange:f=>f&&o({style:f}),className:"grid grid-cols-2 gap-1",children:vnn.map(f=>e.jsx(JF,{value:f.id,className:"text-xs h-9",children:f.label},f.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Format"}),e.jsx(Uq,{type:"single",value:i.aspect,onValueChange:f=>f&&o({aspect:f}),className:"grid grid-cols-3 gap-1",children:Object.keys(XFe).map(f=>e.jsx(JF,{value:f,className:"text-xs h-9",children:XFe[f].label},f))})]}),t&&t.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Brand preset"}),e.jsxs(Ns,{value:n??(s==null?void 0:s.id)??"",onValueChange:r,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Choose preset"})}),e.jsx(js,{children:t.map(f=>e.jsx(et,{value:f.id,children:f.name},f.id))})]})]})]})}),e.jsx(we,{children:e.jsxs(Ie,{className:"p-4 space-y-3",children:[e.jsx(te,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Content"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"headline",className:"text-xs",children:"Headline"}),e.jsx(Fs,{id:"headline",value:i.headline,onChange:f=>o({headline:f.target.value}),rows:2})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"subline",className:"text-xs",children:"Subline"}),e.jsx(xe,{id:"subline",value:i.subline,onChange:f=>o({subline:f.target.value})})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"body",className:"text-xs",children:"Body"}),e.jsx(Fs,{id:"body",value:i.body,onChange:f=>o({body:f.target.value}),rows:4})]}),(i.template==="testimonial"||i.template==="quote")&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"attribution",className:"text-xs",children:"Attribution"}),e.jsx(xe,{id:"attribution",value:i.attribution,onChange:f=>o({attribution:f.target.value}),placeholder:"— Client name / Source"})]}),i.template==="testimonial"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Rating"}),e.jsx(Uq,{type:"single",value:String(i.rating),onValueChange:f=>f&&o({rating:Number(f)}),className:"grid grid-cols-5 gap-1",children:[1,2,3,4,5].map(f=>e.jsxs(JF,{value:String(f),className:"text-xs h-9",children:[f,"★"]},f))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"badge",className:"text-xs",children:"Eyebrow tag"}),e.jsx(xe,{id:"badge",value:i.badgeText,onChange:f=>o({badgeText:f.target.value})})]})]})})]}),e.jsx(_nn,{aspect:p,canvasRef:d,children:e.jsx(wnn,{form:i,preset:a,width:p.w,height:p.h})})]})]})})}function _nn({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 wnn({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)||"",p={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(jnn,{...p}):s.style==="bold"?e.jsx(Nnn,{...p}):s.style==="luxury"?e.jsx(Snn,{...p}):e.jsx(knn,{...p})}function HUt({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 UPe({rating:s,color:t}){return e.jsx("div",{style:{display:"flex",gap:4},children:Array.from({length:5}).map((n,r)=>e.jsx(Ua,{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:p?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(UPe,{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(HUt,{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 Nnn(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%, ${Cnn(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(UPe,{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(HUt,{name:l,phone:o,email:c,website:d,color:"#fff"})]})]})}function knn(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(UPe,{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 Snn(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(UPe,{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 Cnn(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 Ann=()=>{const{swagId:s}=Di(),{user:t}=vs(),{toast:n}=Ai(),r=Qt(),{trackEngagement:a}=EG(),[i,l]=j.useState(""),{data:o,isLoading:c}=ct({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:N}=await q.from("social_swag_links").select("*").eq("swag_id",s).order("sort_order");return{...v,links:N||[]}},enabled:!!s});j.useEffect(()=>{o&&a("social_swag",o.id,o.title,"view")},[o==null?void 0:o.id]);const{data:d=[]}=ct({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=[]}=ct({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 N=[...new Set(v.map(T=>T.user_id))],{data:S}=await q.from("profiles").select("id, name").in("id",N),A=new Map((S==null?void 0:S.map(T=>[T.id,T.name]))||[]);return v.map(T=>({...T,user_name:A.get(T.user_id)||"Unknown User"}))},enabled:!!s}),h=yt({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=yt({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"})}}),p=yt({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]})}}),f=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(qs,{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(qs,{title:o.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(U,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(xr,{to:"/social-swag",children:[e.jsx(Aa,{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(PG,{resourceType:"social_swag",resourceId:o.id,resourceTitle:o.title}),e.jsxs(U,{variant:f?"default":"outline",className:"gap-2 w-fit",onClick:()=>p.mutate(),disabled:!t||p.isPending,children:[e.jsx(wx,{className:`h-4 w-4 ${f?"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(we,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Rc,{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(U,{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(Sr,{className:"h-4 w-4 text-muted-foreground"})]},v.id))})]})}),e.jsx(hc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(vu,{className:"h-5 w-5"}),"Comments (",u.length,")"]}),t?e.jsxs("form",{onSubmit:y,className:"flex gap-2",children:[e.jsx(Fs,{placeholder:"Add a comment...",value:i,onChange:v=>l(v.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(U,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!i.trim()||h.isPending,children:e.jsx($r,{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(we,{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(we,{children:e.jsx(Ie,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ea,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Ta,{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:Nd(new Date(v.created_at),{addSuffix:!0})}),v.user_id===(t==null?void 0:t.id)&&e.jsx(U,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>m.mutate(v.id),children:e.jsx(In,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:v.content})]})]})})},v.id))})]})]})}):e.jsx(qs,{title:"Social Swag",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Rc,{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(U,{asChild:!0,className:"mt-4",children:e.jsx(xr,{to:"/social-swag",children:"Back to Social Swag"})})]})})},Enn=({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(p=>p[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(U,{variant:n==="all"?"secondary":"ghost",className:"w-full justify-start",onClick:()=>r("all"),children:[e.jsx(CM,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsxs(ub,{open:i,onOpenChange:l,children:[e.jsx(hb,{asChild:!0,children:e.jsxs(U,{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(rl,{className:"h-4 w-4"}):e.jsx(gi,{className:"h-4 w-4"})]})}),e.jsx(mb,{className:"space-y-1 pl-2",children:s.map(m=>e.jsxs(U,{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(ub,{open:o,onOpenChange:c,children:[e.jsx(hb,{asChild:!0,children:e.jsxs(U,{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(Ql,{className:"h-3 w-3"}),"Your Groups"]}),o?e.jsx(rl,{className:"h-4 w-4"}):e.jsx(gi,{className:"h-4 w-4"})]})}),e.jsx(mb,{className:"space-y-1 pl-2",children:t.map(m=>e.jsxs(U,{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(ub,{open:d,onOpenChange:u,children:[e.jsx(hb,{asChild:!0,children:e.jsxs(U,{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(Bn,{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(rl,{className:"h-4 w-4"}):e.jsx(gi,{className:"h-4 w-4"})]})}),e.jsx(mb,{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(Ea,{className:"h-7 w-7",children:[e.jsx(Ci,{src:m.avatarUrl}),e.jsx(Ta,{className:"text-xs",children:h(m.name)})]}),e.jsx(Nf,{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))})]})]})})})},Tnn=({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(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsxs(U,{variant:"outline",className:"flex-1 justify-between",children:[e.jsx("span",{className:"truncate",children:c()}),e.jsx(rl,{className:"h-4 w-4 ml-2 shrink-0"})]})}),e.jsxs(Eu,{className:"w-56 bg-background border",children:[e.jsxs(La,{onClick:()=>r("all"),children:[e.jsx(CM,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsx(l1,{}),e.jsx(DV,{className:"text-xs text-muted-foreground",children:"Categories"}),s.map(d=>e.jsxs(La,{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(l1,{}),e.jsxs(DV,{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ql,{className:"h-3 w-3"}),"Your Groups"]}),t.map(d=>e.jsxs(La,{onClick:()=>r(`group:${d.id}`),children:[e.jsx("span",{className:"mr-2",children:d.icon||"🔒"}),d.name]},d.id))]})]})]}),e.jsxs(my,{open:i,onOpenChange:l,children:[e.jsx($ne,{asChild:!0,children:e.jsxs(U,{variant:"outline",size:"icon",className:"relative",children:[e.jsx(Bn,{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(g0,{children:[e.jsx(vv,{children:e.jsxs(bv,{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-5 w-5"}),"Online Now (",a.length,")"]})}),e.jsx(Gi,{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(Ea,{className:"h-10 w-10",children:[e.jsx(Ci,{src:d.avatarUrl}),e.jsx(Ta,{children:o(d.name)})]}),e.jsx(Nf,{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 QFe,qPe="HoverCard",[GUt,sxr]=Up(qPe,[o3]),$Pe=o3(),[Mnn,fet]=GUt(qPe),WUt=s=>{const{__scopeHoverCard:t,children:n,open:r,defaultOpen:a,onOpenChange:i,openDelay:l=700,closeDelay:o=300}=s,c=$Pe(t),d=j.useRef(0),u=j.useRef(0),h=j.useRef(!1),m=j.useRef(!1),[p,f]=Sx({prop:r,defaultProp:a??!1,onChange:i,caller:qPe}),x=j.useCallback(()=>{clearTimeout(u.current),d.current=window.setTimeout(()=>f(!0),l)},[l,f]),y=j.useCallback(()=>{clearTimeout(d.current),!h.current&&!m.current&&(u.current=window.setTimeout(()=>f(!1),o))},[o,f]),v=j.useCallback(()=>f(!1),[f]);return j.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(u.current)},[]),e.jsx(Mnn,{scope:t,open:p,onOpenChange:f,onOpen:x,onClose:y,onDismiss:v,hasSelectionRef:h,isPointerDownOnContentRef:m,children:e.jsx(Pne,{...c,children:n})})};WUt.displayName=qPe;var KUt="HoverCardTrigger",YUt=j.forwardRef((s,t)=>{const{__scopeHoverCard:n,...r}=s,a=fet(KUt,n),i=$Pe(n);return e.jsx(lG,{asChild:!0,...i,children:e.jsx(si.a,{"data-state":a.open?"open":"closed",...r,ref:t,onPointerEnter:va(s.onPointerEnter,AAe(a.onOpen)),onPointerLeave:va(s.onPointerLeave,AAe(a.onClose)),onFocus:va(s.onFocus,a.onOpen),onBlur:va(s.onBlur,a.onClose),onTouchStart:va(s.onTouchStart,l=>l.preventDefault())})})});YUt.displayName=KUt;var Pnn="HoverCardPortal",[nxr,Lnn]=GUt(Pnn,{forceMount:void 0}),CAe="HoverCardContent",ZUt=j.forwardRef((s,t)=>{const n=Lnn(CAe,s.__scopeHoverCard),{forceMount:r=n.forceMount,...a}=s,i=fet(CAe,s.__scopeHoverCard);return e.jsx(Xg,{present:r||i.open,children:e.jsx(Inn,{"data-state":i.open?"open":"closed",...a,onPointerEnter:va(s.onPointerEnter,AAe(i.onOpen)),onPointerLeave:va(s.onPointerLeave,AAe(i.onClose)),ref:t})})});ZUt.displayName=CAe;var Inn=j.forwardRef((s,t)=>{const{__scopeHoverCard:n,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,...o}=s,c=fet(CAe,n),d=$Pe(n),u=j.useRef(null),h=Uo(t,u),[m,p]=j.useState(!1);return j.useEffect(()=>{if(m){const f=document.body;return QFe=f.style.userSelect||f.style.webkitUserSelect,f.style.userSelect="none",f.style.webkitUserSelect="none",()=>{f.style.userSelect=QFe,f.style.webkitUserSelect=QFe}}},[m]),j.useEffect(()=>{if(u.current){const f=()=>{p(!1),c.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var y;((y=document.getSelection())==null?void 0:y.toString())!==""&&(c.hasSelectionRef.current=!0)})};return document.addEventListener("pointerup",f),()=>{document.removeEventListener("pointerup",f),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!1}}},[c.isPointerDownOnContentRef,c.hasSelectionRef]),j.useEffect(()=>{u.current&&Onn(u.current).forEach(x=>x.setAttribute("tabindex","-1"))}),e.jsx(IP,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:l,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:va(i,f=>{f.preventDefault()}),onDismiss:c.onDismiss,children:e.jsx(Lne,{...d,...o,onPointerDown:va(o.onPointerDown,f=>{f.currentTarget.contains(f.target)&&p(!0),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!0}),ref:h,style:{...o.style,userSelect:m?"text":void 0,WebkitUserSelect:m?"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)"}})})}),Rnn="HoverCardArrow",Dnn=j.forwardRef((s,t)=>{const{__scopeHoverCard:n,...r}=s,a=$Pe(n);return e.jsx(Ine,{...a,...r,ref:t})});Dnn.displayName=Rnn;function AAe(s){return t=>t.pointerType==="touch"?void 0:s()}function Onn(s){const t=[],n=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;n.nextNode();)t.push(n.currentNode);return t}var Fnn=WUt,znn=YUt,XUt=ZUt;const Bnn=Fnn,Unn=znn,QUt=j.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(XUt,{ref:a,align:t,sideOffset:n,className:Mt("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}));QUt.displayName=XUt.displayName;const qnn=[{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"}],$nn=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2),JUt=({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(Bnn,{openDelay:200,closeDelay:100,children:[e.jsx(Unn,{asChild:!0,children:e.jsx("div",{className:"cursor-pointer",children:t})}),e.jsx(QUt,{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=qnn.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(Ea,{className:"h-6 w-6",children:[e.jsx(Ci,{src:l.user_avatar||void 0}),e.jsx(Ta,{className:"text-[10px]",children:$nn(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 Vnn({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(Ds,{className:"max-w-[95vw] max-h-[95vh] w-auto h-auto p-0 border-none bg-black/95 overflow-hidden",children:[e.jsx(U,{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(er,{className:"h-6 w-6"})}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(U,{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(rd,{className:"h-8 w-8"})}),e.jsx(U,{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(gi,{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(U,{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(Cq,{className:"h-5 w-5"}):e.jsx(OM,{className:"h-5 w-5"})}),e.jsx("div",{className:Mt("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:Mt("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,p)=>e.jsx("button",{onClick:()=>{i(p),o(!1)},className:Mt("w-12 h-12 rounded overflow-hidden flex-shrink-0 border-2 transition-all",a===p?"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"})},p))})]})})}const gle=[{type:"like",emoji:"👍",label:"Like"},{type:"love",emoji:"❤️",label:"Love"}],Hnn=({commentId:s,reactions:t,currentUserId:n})=>{var d,u;const r=Qt(),[a,i]=j.useState(!1),l=t.find(h=>h.user_id===n),o=yt({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(JUt,{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=gle.find(p=>p.type===h))==null?void 0:m.emoji},h)})}),e.jsx("span",{children:t.length})]})}),n&&e.jsxs(md,{open:a,onOpenChange:i,children:[e.jsx(pd,{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=gle.find(h=>h.type===l.reaction_type))==null?void 0:d.emoji," ",(u=gle.find(h=>h.type===l.reaction_type))==null?void 0:u.label]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ko,{className:"h-3 w-3"}),"Like"]})})}),e.jsx(id,{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:gle.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 get({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(xr,{to:u?`/templates/${d}`:`/profile?user=${d}`,className:Mt("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 EAe({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,p]=j.useState(!1),[f,x]=j.useState("user"),[y,v]=j.useState(""),[b,N]=j.useState(null),[S,A]=j.useState(0),[T,L]=j.useState({top:0,left:0,width:0}),M=j.useRef(new Map),I=j.useRef(new Map),R=ie=>{if(c==="plain"){const he=[];return M.current.forEach((ke,Te)=>{ie.includes(`@${Te}`)&&he.push(ke)}),[...new Set(he)]}const ce=/@\[([^\]]+)\]\(([^)]+)\)/g,je=[];let be;for(;(be=ce.exec(ie))!==null;)je.push(be[2]);return[...new Set(je)]},z=ie=>{if(c==="plain"){const he=[];return I.current.forEach((ke,Te)=>{ie.includes(`#${Te}`)&&he.push(ke)}),[...new Set(he)]}const ce=/#\[([^\]]+)\]\(([^)]+)\)/g,je=[];let be;for(;(be=ce.exec(ie))!==null;)je.push(be[2]);return[...new Set(je)]};j.useEffect(()=>{if(i){const ie=R(s);i(ie)}if(l){const ie=z(s);l(ie)}},[s,i,l,c]);const{data:$=[],isLoading:H}=ct({queryKey:["mention-users",y],queryFn:async()=>{const ie=q.from("profiles").select("id, name").limit(8),ce=y.length>=1?ie.ilike("name",`%${y}%`):ie.order("name"),{data:je,error:be}=await ce;if(be)throw be;const he=je.map(ke=>ke.id),ge=await UPt(he);return je.map(ke=>({id:ke.id,name:ke.name||"Unknown",avatar_url:ge.get(ke.id)}))},enabled:m&&f==="user",staleTime:3e4}),{data:V=[],isLoading:K}=ct({queryKey:["mention-templates",y],queryFn:async()=>{let ie=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&&(ie=ie.ilike("name",`%${y}%`));const{data:ce,error:je}=await ie;if(je)throw je;return ce||[]},enabled:m&&f==="template"&&d,staleTime:3e4}),Z=f==="user"?H:K,Q=f==="user"?$:V,le=ie=>ie.split(" ").map(ce=>ce[0]).join("").toUpperCase().slice(0,2),ue=ie=>{const ce=ie.target.value,je=ie.target.selectionStart;t(ce);const be=ce.substring(0,je),he=be.lastIndexOf("@"),ge=d?be.lastIndexOf("#"):-1;let ke=-1,Te="user";if(he>ge?(ke=he,Te="user"):ge>he&&d&&(ke=ge,Te="template"),ke!==-1){const Me=be.substring(ke+1),Oe=Me.includes(" "),Se=Me.includes(` `);if(!Oe&&!Se&&Me.length<=30){N(ke),v(Me),x(Te),p(!0),A(0);return}}p(!1),N(null)},se=ie=>{if(b===null)return;const ce=s.substring(0,b),je=s.substring(b+y.length+1),be=f==="user"?"@":"#",he=c==="plain"?`${be}${ie.name} `:`${be}[${ie.name}](${ie.id}) `;c==="plain"&&(f==="user"?M.current.set(ie.name,ie.id):I.current.set(ie.name,ie.id));const ge=ce+he+je;t(ge),p(!1),N(null),v(""),setTimeout(()=>{if(u.current){const ke=ce.length+he.length;u.current.focus(),u.current.setSelectionRange(ke,ke)}},0)},ne=ie=>{if(!(!m||Q.length===0))switch(ie.key){case"ArrowDown":ie.preventDefault(),A(ce=>(ce+1)%Q.length);break;case"ArrowUp":ie.preventDefault(),A(ce=>(ce-1+Q.length)%Q.length);break;case"Enter":Q[S]&&(ie.preventDefault(),se(Q[S]));break;case"Escape":ie.preventDefault(),p(!1);break;case"Tab":Q[S]&&(ie.preventDefault(),se(Q[S]));break}};return j.useEffect(()=>{const ie=ce=>{h.current&&!h.current.contains(ce.target)&&u.current&&!u.current.contains(ce.target)&&p(!1)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[]),j.useEffect(()=>{if(!m)return;const ie=()=>{const ce=u.current;if(!ce)return;const je=ce.getBoundingClientRect();L({top:je.bottom+4,left:je.left,width:je.width})};return ie(),window.addEventListener("resize",ie),window.addEventListener("scroll",ie,!0),()=>{window.removeEventListener("resize",ie),window.removeEventListener("scroll",ie,!0)}},[m,s]),e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fs,{ref:u,value:s,onChange:ue,onKeyDown:ie=>{ne(ie),ie.defaultPrevented||o==null||o(ie)},placeholder:n,className:Mt("resize-none",r),style:{minHeight:a}}),m&&tv.createPortal(e.jsxs("div",{ref:h,className:"fixed z-[1000] max-h-[220px] overflow-hidden rounded-lg border bg-popover shadow-lg",style:{top:T.top,left:T.left,width:T.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:f==="user"?"👤 Mention a person":"📋 Link a template"}),Z?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"Searching..."}):Q.length===0?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:y.length<1?`Type to search ${f==="user"?"people":"templates"}...`:`No ${f==="user"?"users":"templates"} found`}):e.jsx("ul",{className:"py-1 max-h-[180px] overflow-y-auto",children:Q.map((ie,ce)=>e.jsx("li",{className:Mt("flex items-center gap-2 px-3 py-2 cursor-pointer transition-colors",ce===S?"bg-accent":"hover:bg-accent/50"),onClick:()=>se(ie),onMouseEnter:()=>A(ce),children:f==="user"?e.jsxs(e.Fragment,{children:[e.jsxs(Ea,{className:"h-6 w-6",children:[e.jsx(Ci,{src:ie.avatar_url}),e.jsx(Ta,{className:"text-xs",children:le(ie.name)})]}),e.jsx("span",{className:"text-sm font-medium truncate",children:ie.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:ie.preview_image_url?e.jsx("img",{src:ie.preview_image_url,alt:"",className:"w-full h-full object-cover"}):e.jsx($c,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate",children:ie.name})]})},ie.id))})]}),document.body)]})}function Gnn(s){const t=/#\[([^\]]+)\]\(([^)]+)\)/g,n=[];let r;for(;(r=t.exec(s))!==null;)n.push(r[2]);return[...new Set(n)]}const X0t=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2);function eqt({comment:s,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l=0}){const o=Qt(),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,p]=j.useState([]),f=yt({mutationFn:async({content:b,parentCommentId:N})=>{const{data:S,error:A}=await q.from("community_comments").insert({post_id:t,user_id:n,content:b,parent_comment_id:N}).select("id").single();if(A)throw A;const T=m;if(T.length>0&&S){const L=T.filter(M=>M!==n).map(M=>({comment_id:S.id,mentioned_user_id:M,mentioned_by_user_id:n}));L.length>0&&await q.from("community_comment_mentions").insert(L)}},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),h(""),p([]),d(!1)}}),x=yt({mutationFn:async b=>{const{error:N}=await q.from("community_comments").delete().eq("id",b);if(N)throw N},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),y=()=>{u.trim()&&f.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(Ea,{className:"h-8 w-8 shrink-0",children:[e.jsx(Ci,{src:s.user_avatar||void 0}),e.jsx(Ta,{className:"text-xs",children:X0t(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(get,{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:Nd(new Date(s.created_at),{addSuffix:!0})}),e.jsx(Hnn,{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(uq,{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(Ea,{className:"h-6 w-6 shrink-0 mt-1",children:[e.jsx(Ci,{src:r||void 0}),e.jsx(Ta,{className:"text-xs",children:X0t((a==null?void 0:a.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2 items-start",children:[e.jsx(EAe,{placeholder:`Reply to ${s.user_name}...`,value:u,onChange:h,onMentionsChange:p,mentionFormat:"plain",className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(U,{size:"sm",variant:"ghost",onClick:y,disabled:!u.trim()||f.isPending,className:"h-8 px-2 mt-0.5",children:e.jsx($r,{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(eqt,{comment:b,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l+1},b.id))})]})}const xle=[{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"}],Wnn=()=>{const{user:s,isBrokerageManager:t,managedBrokerages:n,isAdmin:r}=vs(),{avatarUrl:a}=BPt(s==null?void 0:s.id),{onlineUsers:i}=SMt(),{toast:l}=Ai(),o=Qt(),c=j.useRef(null),[d,u]=j.useState("all"),[h,m]=j.useState(""),[p,f]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState([]),[N,S]=j.useState([]),[A,T]=j.useState(""),[L,M]=j.useState(!1),[I,R]=j.useState(null),[z,$]=j.useState(""),[H,V]=j.useState(new Set),[K,Z]=j.useState({}),[Q,le]=j.useState({}),[ue,se]=j.useState([]),[ne,ie]=j.useState([]),[ce,je]=j.useState({open:!1,images:[],index:0});j.useEffect(()=>{if(d.startsWith("group:")){const ft=d.replace("group:","");y(ft),f("")}else d!=="all"?(f(d),y("")):(f(""),y(""))},[d]);const{data:be=[]}=ct({queryKey:["community-categories"],queryFn:async()=>{const{data:ft,error:qt}=await q.from("community_categories").select("*").order("sort_order");if(qt)throw qt;return ft}}),{data:he=[]}=ct({queryKey:["community-private-groups"],queryFn:async()=>{const{data:ft,error:qt}=await q.from("community_private_groups").select("id, name, description, icon, brokerage_id, sort_order").order("sort_order");if(qt)throw qt;return ft}}),ge=20,{data:ke,isLoading:Te,hasNextPage:Me,fetchNextPage:Oe,isFetchingNextPage:Se}=Bxs({queryKey:["community-posts",d],initialPageParam:0,queryFn:async({pageParam:ft})=>{var mt;const qt=ft*ge,Ut=qt+ge;let Wt=q.from("community_posts").select("*").order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1}).range(qt,Ut);if(d.startsWith("group:")){const Nt=d.replace("group:","");Wt=Wt.eq("private_group_id",Nt)}else d==="all"||(Wt=Wt.eq("category_id",d).is("private_group_id",null));const{data:us,error:zt}=await Wt;if(zt)throw zt;const bt=((us==null?void 0:us.length)||0)>ge,As=(us||[]).slice(0,ge);if(As.length===0)return{posts:[],hasMore:!1,nextPage:ft+1};const vt=As.map(Nt=>Nt.id),Ws=[...new Set(As.filter(Nt=>Nt.category_id).map(Nt=>Nt.category_id))].filter(Boolean),[on,Ms,dn,rn,br]=await Promise.all([Ws.length?q.from("community_categories").select("*").in("id",Ws):Promise.resolve({data:[]}),q.from("community_post_media").select("*").in("post_id",vt).order("sort_order"),q.from("community_reactions").select("*").in("post_id",vt),q.from("community_comments").select("*").in("post_id",vt).order("created_at",{ascending:!0}),q.from("community_post_resources").select("*").in("post_id",vt)]),Gn=on==null?void 0:on.data,On=Ms==null?void 0:Ms.data,Rr=dn==null?void 0:dn.data,cr=rn==null?void 0:rn.data,Hs=br==null?void 0:br.data,_r=(cr||[]).map(Nt=>Nt.id),[nn,Zn]=await Promise.all([_r.length?q.from("community_comment_reactions").select("*").in("comment_id",_r):Promise.resolve({data:[]}),(()=>{const Nt=(Hs||[]).filter(Pt=>Pt.resource_type==="template").map(Pt=>Pt.resource_id);return Nt.length===0?Promise.resolve({data:[]}):q.from("canva_templates").select("id, name, preview_image_url").in("id",Nt)})()]),es=(nn==null?void 0:nn.data)||[],ar=(Zn==null?void 0:Zn.data)||[],Hn=new Map(ar.map(Nt=>[Nt.id,{name:Nt.name,preview_image_url:Nt.preview_image_url}])),kn=Array.from(new Set([...As.map(Nt=>Nt.user_id),...(Rr||[]).map(Nt=>Nt.user_id),...(cr||[]).map(Nt=>Nt.user_id),...es.map(Nt=>Nt.user_id)])),[Un,sn]=await Promise.all([kn.length?q.from("profiles").select("id, name").in("id",kn):Promise.resolve({data:[]}),UPt(kn)]),un=new Map(((mt=Un==null?void 0:Un.data)==null?void 0:mt.map(Nt=>[Nt.id,Nt.name]))||[]),Ar=new Map((Gn||[]).map(Nt=>[Nt.id,Nt])),fs=Nt=>{const Pt=new Map,ts=[];return Nt.forEach(ls=>{Pt.set(ls.id,{...ls,user_name:un.get(ls.user_id)||"Unknown User",user_avatar:sn.get(ls.user_id),reactions:es.filter(Is=>Is.comment_id===ls.id).map(Is=>({...Is,user_name:un.get(Is.user_id)||"Unknown User",user_avatar:sn.get(Is.user_id)})),replies:[]})}),Nt.forEach(ls=>{const Is=Pt.get(ls.id);if(ls.parent_comment_id&&Pt.has(ls.parent_comment_id)){const ps=Pt.get(ls.parent_comment_id);ps.replies=ps.replies||[],ps.replies.push(Is)}else ts.push(Is)}),ts};return{posts:As.map(Nt=>{const Pt=(Hs||[]).filter(ts=>ts.post_id===Nt.id).map(ts=>{let ls="",Is=null;if(ts.resource_type==="template"){const ps=Hn.get(ts.resource_id);ls=(ps==null?void 0:ps.name)||"Unknown Template",Is=(ps==null?void 0:ps.preview_image_url)||null}return{id:ts.id,resource_type:ts.resource_type,resource_id:ts.resource_id,resource_name:ls,resource_preview_url:Is}});return{...Nt,user_name:un.get(Nt.user_id)||"Unknown User",user_avatar:sn.get(Nt.user_id),category:Nt.category_id?Ar.get(Nt.category_id):null,media:(On||[]).filter(ts=>ts.post_id===Nt.id),reactions:((Rr||[]).filter(ts=>ts.post_id===Nt.id)||[]).map(ts=>({...ts,user_name:un.get(ts.user_id)||"Unknown User",user_avatar:sn.get(ts.user_id)})),comments:fs((cr||[]).filter(ts=>ts.post_id===Nt.id)),resources:Pt}}),hasMore:bt,nextPage:ft+1}},getNextPageParam:ft=>ft.hasMore?ft.nextPage:void 0}),Qe=j.useMemo(()=>(ke==null?void 0:ke.pages.flatMap(ft=>ft.posts))??[],[ke]),Ae=yt({mutationFn:async()=>{M(!0);const{data:ft,error:qt}=await q.from("community_posts").insert({user_id:s.id,category_id:x?null:p||null,private_group_id:x||null,content:h,link_url:A||null}).select().single();if(qt)throw qt;for(let Wt=0;Wt0){const Wt=ue.filter(us=>us!==s.id).map(us=>({post_id:ft.id,mentioned_user_id:us,mentioned_by_user_id:s.id}));Wt.length>0&&await q.from("community_post_mentions").insert(Wt)}const Ut=Gnn(h);if(Ut.length>0){const Wt=Ut.map(us=>({post_id:ft.id,resource_type:"template",resource_id:us}));await q.from("community_post_resources").insert(Wt)}return ft},onSuccess:async ft=>{var qt;o.invalidateQueries({queryKey:["community-posts"]}),m(""),se([]),ie([]),f(""),y(""),b([]),S([]),T(""),l({title:"Post created!"});try{const Ut=((qt=s==null?void 0:s.user_metadata)==null?void 0:qt.name)||"Someone",Wt=h.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),us=Wt.length>50?Wt.substring(0,50)+"...":Wt;await q.functions.invoke("send-push-notification",{body:{title:"New Community Post",body:`${Ut}: ${us}`,url:"/community"}})}catch(Ut){console.error("Failed to send push notification:",Ut)}},onError:ft=>{l({title:"Error creating post",description:ft.message,variant:"destructive"})},onSettled:()=>M(!1)}),Fe=yt({mutationFn:async({postId:ft,content:qt})=>{const{error:Ut}=await q.from("community_posts").update({content:qt}).eq("id",ft);if(Ut)throw Ut},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),R(null),$(""),l({title:"Post updated!"})}}),Ne=yt({mutationFn:async ft=>{const{error:qt}=await q.from("community_posts").delete().eq("id",ft);if(qt)throw qt},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:"Post deleted"})}}),$e=yt({mutationFn:async({postId:ft,isPinned:qt})=>{const{error:Ut}=await q.from("community_posts").update({is_pinned:!qt,pinned_at:qt?null:new Date().toISOString(),pinned_by:qt?null:s==null?void 0:s.id}).eq("id",ft);if(Ut)throw Ut},onSuccess:(ft,{isPinned:qt})=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:qt?"Post unpinned":"Post pinned to top"})}}),Ve=yt({mutationFn:async({postId:ft,reactionType:qt})=>{var Wt;const Ut=(Wt=Qe.find(us=>us.id===ft))==null?void 0:Wt.reactions.find(us=>us.user_id===(s==null?void 0:s.id));Ut?Ut.reaction_type===qt?await q.from("community_reactions").delete().eq("id",Ut.id):await q.from("community_reactions").update({reaction_type:qt}).eq("id",Ut.id):await q.from("community_reactions").insert({post_id:ft,user_id:s.id,reaction_type:qt})},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),qe=yt({mutationFn:async({postId:ft,content:qt})=>{const{data:Ut,error:Wt}=await q.from("community_comments").insert({post_id:ft,user_id:s.id,content:qt}).select("id").single();if(Wt)throw Wt;const us=Q[ft]||[];if(us.length>0&&Ut){const zt=us.filter(bt=>bt!==s.id).map(bt=>({comment_id:Ut.id,mentioned_user_id:bt,mentioned_by_user_id:s.id}));zt.length>0&&await q.from("community_comment_mentions").insert(zt)}},onSuccess:(ft,{postId:qt})=>{o.invalidateQueries({queryKey:["community-posts"]}),Z(Ut=>({...Ut,[qt]:""})),le(Ut=>({...Ut,[qt]:[]}))}});yt({mutationFn:async ft=>{const{error:qt}=await q.from("community_comments").delete().eq("id",ft);if(qt)throw qt},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})});const Ze=ft=>{const qt=Array.from(ft.target.files||[]);if(qt.length+v.length>10){l({title:"Maximum 10 files allowed",variant:"destructive"});return}b(Ut=>[...Ut,...qt]),qt.forEach(Ut=>{const Wt=new FileReader;Wt.onloadend=()=>{S(us=>[...us,Wt.result])},Wt.readAsDataURL(Ut)})},Ue=ft=>{b(qt=>qt.filter((Ut,Wt)=>Wt!==ft)),S(qt=>qt.filter((Ut,Wt)=>Wt!==ft))},Ye=ft=>ft.split(" ").map(qt=>qt[0]).join("").toUpperCase().slice(0,2),Ge=ft=>{const qt={};return ft.forEach(Ut=>{qt[Ut.reaction_type]=(qt[Ut.reaction_type]||0)+1}),qt},He=ft=>{var qt;return(qt=ft.find(Ut=>Ut.user_id===(s==null?void 0:s.id)))==null?void 0:qt.reaction_type},tt=ft=>ft.reduce((qt,Ut)=>qt+1+(Ut.replies?tt(Ut.replies):0),0),pt=ft=>{if(r)return!0;if(!t||!ft.private_group_id)return!1;const qt=he.find(Ut=>Ut.id===ft.private_group_id);return qt!=null&&qt.brokerage_id?n.some(Ut=>Ut.id===qt.brokerage_id):!1};return e.jsx(qs,{title:"Community",children:e.jsxs("div",{className:"flex gap-6 w-full isolate z-0",children:[e.jsx(Enn,{categories:be,privateGroups:he,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(Tnn,{categories:be,privateGroups:he,selectedFilter:d,onFilterChange:u,onlineUsers:i}),e.jsx(we,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(Ea,{className:"h-10 w-10",children:[e.jsx(Ci,{src:a||void 0}),e.jsx(Ta,{children:s!=null&&s.email?Ye(s.email.split("@")[0]):"U"})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsx(EAe,{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:se,onTemplatesChange:ie,mentionFormat:"encoded",minHeight:"80px",enableTemplateMentions:r}),N.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:N.map((ft,qt)=>{var Ut;return e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden bg-muted",children:[(Ut=v[qt])!=null&&Ut.type.startsWith("video/")?e.jsx("video",{src:ft,className:"w-full h-full object-cover"}):e.jsx("img",{src:ft,alt:"",className:"w-full h-full object-cover"}),e.jsx(U,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>Ue(qt),children:e.jsx(er,{className:"h-3 w-3"})})]},qt)})}),A&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rc,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:A,onChange:ft=>T(ft.target.value),placeholder:"https://...",className:"flex-1"}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>T(""),children:e.jsx(er,{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:Ze,accept:"image/*,video/*",multiple:!0,className:"hidden"}),e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>{var ft;return(ft=c.current)==null?void 0:ft.click()},children:[e.jsx(pc,{className:"h-4 w-4 mr-1"}),"Photo"]}),e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>{var ft;return(ft=c.current)==null?void 0:ft.click()},children:[e.jsx(Wr,{className:"h-4 w-4 mr-1"}),"Video"]}),e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>T("https://"),children:[e.jsx(Rc,{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:[he.length>0?e.jsxs(Ns,{value:x||p||"none",onValueChange:ft=>{ft==="none"?(f(""),y("")):ft.startsWith("group:")?(y(ft.replace("group:","")),f("")):(f(ft),y(""))},children:[e.jsx(ws,{className:"w-[130px] sm:w-[160px] h-8 text-xs sm:text-sm",children:e.jsx(ks,{placeholder:"Select..."})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"No category"}),be.map(ft=>e.jsxs(et,{value:ft.id,children:[ft.icon," ",ft.name]},ft.id)),he.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"}),he.map(ft=>e.jsxs(et,{value:`group:${ft.id}`,children:[ft.icon||"🔒"," ",ft.name]},ft.id))]})]})]}):e.jsxs(Ns,{value:p,onValueChange:f,children:[e.jsx(ws,{className:"w-[110px] sm:w-[140px] h-8 text-xs sm:text-sm",children:e.jsx(ks,{placeholder:"Category"})}),e.jsx(js,{children:be.map(ft=>e.jsxs(et,{value:ft.id,children:[ft.icon," ",ft.name]},ft.id))})]}),e.jsxs(U,{size:"sm",onClick:()=>Ae.mutate(),disabled:!h.trim()||L,children:[e.jsx($r,{className:"h-4 w-4 mr-1"}),"Post"]})]})]})]})]})})}),Te?e.jsx("div",{className:"space-y-4",children:[...Array(3)].map((ft,qt)=>e.jsx(we,{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"})]})]})})},qt))}):Qe.length===0?e.jsx(we,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(vu,{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:[Qe.map(ft=>{var qt,Ut,Wt,us;return e.jsx(we,{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(Ea,{className:"h-10 w-10",children:[e.jsx(Ci,{src:ft.user_avatar||void 0}),e.jsx(Ta,{children:Ye(ft.user_name||"U")})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold break-words",children:ft.user_name}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("span",{children:Nd(new Date(ft.created_at),{addSuffix:!0})}),ft.category&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs(Be,{variant:"secondary",className:"text-xs",children:[ft.category.icon," ",ft.category.name]})]})]})]})]}),(ft.user_id===(s==null?void 0:s.id)||pt(ft))&&e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Z1,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",children:[pt(ft)&&ft.private_group_id&&e.jsx(La,{onClick:()=>$e.mutate({postId:ft.id,isPinned:ft.is_pinned}),children:ft.is_pinned?e.jsxs(e.Fragment,{children:[e.jsx(nQ,{className:"h-4 w-4 mr-2"}),"Unpin Post"]}):e.jsxs(e.Fragment,{children:[e.jsx(MA,{className:"h-4 w-4 mr-2"}),"Pin to Top"]})}),ft.user_id===(s==null?void 0:s.id)&&e.jsxs(La,{onClick:()=>{R(ft),$(ft.content)},children:[e.jsx(ri,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(La,{className:"text-destructive",onClick:()=>Ne.mutate(ft.id),children:[e.jsx(In,{className:"h-4 w-4 mr-2"}),ft.user_id!==(s==null?void 0:s.id)?"Remove (Moderate)":"Delete"]})]})]})]}),ft.is_pinned&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-sm text-primary",children:[e.jsx(MA,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Pinned"})]}),e.jsx("div",{className:"mb-3",children:e.jsx(get,{content:ft.content})}),ft.media.length>0&&e.jsx("div",{className:`grid gap-2 mb-3 ${ft.media.length===1?"grid-cols-1":ft.media.length===2?"grid-cols-2":ft.media.length===3?"grid-cols-3":"grid-cols-2"}`,children:ft.media.slice(0,4).map((zt,bt)=>{const As=bt===3&&ft.media.length>4,vt=ft.media.length-4;return e.jsxs("div",{className:`relative rounded-lg overflow-hidden bg-muted cursor-pointer group ${ft.media.length===1?"max-h-[500px]":ft.media.length===2?"aspect-[4/3]":"aspect-square"}`,onClick:()=>je({open:!0,images:ft.media.map(Ws=>({url:Ws.media_url,type:Ws.media_type==="video"?"video":"image"})),index:bt}),children:[zt.media_type==="video"?e.jsx("video",{src:zt.media_url,className:"w-full h-full object-cover transition-transform group-hover:scale-105"}):e.jsx("img",{src:zt.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:["+",vt]})})]},zt.id)})}),ft.link_url&&e.jsxs("a",{href:ft.link_url,target:"_blank",rel:"noopener noreferrer",className:"block rounded-lg border hover:bg-muted transition-colors mb-3 overflow-hidden",children:[ft.link_image&&e.jsx("div",{className:"aspect-video bg-muted",children:e.jsx("img",{src:ft.link_image,alt:ft.link_title||"Link preview",className:"w-full h-full object-cover",onError:zt=>{zt.currentTarget.style.display="none"}})}),e.jsx("div",{className:"p-3",children:ft.link_title?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium text-foreground line-clamp-2",children:ft.link_title}),ft.link_description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mt-1",children:ft.link_description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 truncate",children:new URL(ft.link_url).hostname})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm text-primary",children:[e.jsx(Rc,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:ft.link_url})]})})]}),ft.reactions.length>0&&e.jsx(JUt,{reactions:ft.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(Ge(ft.reactions)).slice(0,3).map(([zt])=>{var bt;return e.jsx("span",{className:"text-base",children:(bt=xle.find(As=>As.type===zt))==null?void 0:bt.emoji},zt)})}),e.jsx("span",{children:ft.reactions.length})]})}),e.jsxs("div",{className:"flex items-center gap-1 border-t border-b py-1 my-2",children:[e.jsxs(md,{children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{variant:"ghost",size:"sm",className:"flex-1",children:[He(ft.reactions)?e.jsx("span",{className:"mr-1",children:(qt=xle.find(zt=>zt.type===He(ft.reactions)))==null?void 0:qt.emoji}):e.jsx(wx,{className:"h-4 w-4 mr-1"}),He(ft.reactions)?(Ut=xle.find(zt=>zt.type===He(ft.reactions)))==null?void 0:Ut.label:"Like"]})}),e.jsx(id,{className:"w-auto p-2",side:"top",children:e.jsx("div",{className:"flex gap-1",children:xle.map(zt=>e.jsx("button",{onClick:()=>Ve.mutate({postId:ft.id,reactionType:zt.type}),className:"text-2xl hover:scale-125 transition-transform p-1",title:zt.label,children:zt.emoji},zt.type))})})]}),e.jsxs(U,{variant:"ghost",size:"sm",className:"flex-1",onClick:()=>V(zt=>{const bt=new Set(zt);return bt.has(ft.id)?bt.delete(ft.id):bt.add(ft.id),bt}),children:[e.jsx(vu,{className:"h-4 w-4 mr-1"}),(()=>{const zt=tt(ft.comments);return zt>0?`Comment (${zt})`:"Comment"})()]})]}),H.has(ft.id)&&e.jsxs("div",{className:"space-y-3 mt-3",children:[ft.comments.map(zt=>e.jsx(eqt,{comment:zt,postId:ft.id,currentUserId:s==null?void 0:s.id,currentUserAvatar:a,currentUserEmail:s==null?void 0:s.email,canModerate:pt(ft)},zt.id)),s&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ea,{className:"h-8 w-8",children:[e.jsx(Ci,{src:a||void 0}),e.jsx(Ta,{className:"text-xs",children:Ye(((Wt=s.email)==null?void 0:Wt.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsx(EAe,{placeholder:"Write a comment... (use @ to mention)",value:K[ft.id]||"",onChange:zt=>Z(bt=>({...bt,[ft.id]:zt})),onMentionsChange:zt=>le(bt=>({...bt,[ft.id]:zt})),mentionFormat:"plain",onKeyDown:zt=>{var bt;zt.defaultPrevented||zt.key==="Enter"&&!zt.shiftKey&&((bt=K[ft.id])!=null&&bt.trim())&&(zt.preventDefault(),qe.mutate({postId:ft.id,content:K[ft.id]}))},className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>{var zt;(zt=K[ft.id])!=null&&zt.trim()&&qe.mutate({postId:ft.id,content:K[ft.id]})},disabled:!((us=K[ft.id])!=null&&us.trim()),className:"h-8 px-2 mt-0.5",children:e.jsx($r,{className:"h-4 w-4"})})]})]})]})]})},ft.id)}),Me&&e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx(U,{variant:"outline",onClick:()=>Oe(),disabled:Se,children:Se?"Loading…":"Load more posts"})})]}),e.jsx(zs,{open:!!I,onOpenChange:()=>R(null),children:e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Edit Post"})}),e.jsx(Fs,{value:z,onChange:ft=>$(ft.target.value),className:"min-h-[120px]"}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(U,{variant:"outline",onClick:()=>R(null),children:"Cancel"}),e.jsx(U,{onClick:()=>{I&&Fe.mutate({postId:I.id,content:z})},disabled:!z.trim(),children:"Save Changes"})]})]})}),e.jsx(Vnn,{images:ce.images,initialIndex:ce.index,open:ce.open,onOpenChange:ft=>je(qt=>({...qt,open:ft}))})]})]})})},Knn=50*1024*1024;function tqt({value:s,onChange:t,disabled:n}){const{user:r}=vs(),a=j.useRef(null),[i,l]=j.useState(!1),o=async d=>{if(!d||!r)return;const u=[];l(!0);try{for(const h of Array.from(d)){if(!h.type.startsWith("image/")&&!h.type.startsWith("video/")){re.error(`${h.name}: only images and videos allowed`);continue}if(h.size>Knn){re.error(`${h.name}: must be under 50MB`);continue}const m=h.name.split(".").pop()||"bin",p=`${r.id}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${m}`,{error:f}=await q.storage.from("support-attachments").upload(p,h,{contentType:h.type,upsert:!1});if(f){re.error(`${h.name}: ${f.message}`);continue}u.push({path:p,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(FX,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(kM,{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(er,{className:"h-3 w-3"})})]},d.path))}),e.jsxs(U,{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(Et,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(MM,{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 sqt({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(Et,{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 sB={open:{label:"Open",icon:Yr,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:vu,color:"bg-blue-500"},resolved:{label:"Resolved",icon:Yo,color:"bg-green-500"},closed:{label:"Closed",icon:ou,color:"bg-muted-foreground"}},Q0t={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function Ynn(){const{user:s}=vs(),t=Qt(),[n,r]=j.useState(null),[a,i]=j.useState(""),[l,o]=j.useState([]),{data:c=[],isLoading:d}=ct({queryKey:["support-tickets"],queryFn:async()=>{const{data:p,error:f}=await q.from("support_tickets").select("*").eq("user_id",s==null?void 0:s.id).order("created_at",{ascending:!1});if(f)throw f;return p},enabled:!!s}),{data:u=[]}=ct({queryKey:["ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:p,error:f}=await q.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if(f)throw f;return p},enabled:!!n}),h=yt({mutationFn:async({content:p,attachments:f})=>{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:p,is_admin_reply:!1,attachments:f});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 p=sB[n.status].icon;return e.jsx(qs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>r(null),children:e.jsx(Aa,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:n.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Be,{variant:"secondary",children:Q0t[n.category]}),e.jsxs(Be,{className:sB[n.status].color,children:[e.jsx(p,{className:"h-3 w-3 mr-1"}),sB[n.status].label]})]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(Jn,{children:["Created on ",Gs(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(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-lg",children:"Conversation"})}),e.jsxs(Ie,{children:[e.jsx(Gi,{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(f=>{var x;return e.jsxs("div",{className:`p-4 rounded-lg ${f.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:f.is_admin_reply?"Support Team":((x=f.profiles)==null?void 0:x.name)||"You"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Gs(new Date(f.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:f.content}),f.attachments&&f.attachments.length>0&&e.jsx(sqt,{attachments:f.attachments})]},f.id)})})}),n.status!=="closed"&&e.jsxs(e.Fragment,{children:[e.jsx(hc,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Fs,{placeholder:"Type your reply...",value:a,onChange:f=>i(f.target.value),className:"min-h-[80px]"}),e.jsx(U,{onClick:m,disabled:!a.trim()&&l.length===0||h.isPending,className:"self-end",children:e.jsx($r,{className:"h-4 w-4"})})]}),e.jsx(tqt,{value:l,onChange:o,disabled:h.isPending})]})]})]})]})]})})}return e.jsx(qs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(we,{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(MC,{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(fqe,{trigger:e.jsxs(U,{size:"lg",className:"gap-2",children:[e.jsx(an,{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(ba,{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(fqe,{trigger:e.jsxs(U,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(an,{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(we,{className:"border-dashed",children:e.jsxs(Ie,{className:"text-center py-12",children:[e.jsx(vu,{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(p=>{const f=sB[p.status].icon;return e.jsx(we,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(p),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:p.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Be,{variant:"outline",className:"text-xs",children:Q0t[p.category]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Gs(new Date(p.created_at),"MMM d, yyyy")})]})]}),e.jsxs(Be,{className:sB[p.status].color,children:[e.jsx(f,{className:"h-3 w-3 mr-1"}),sB[p.status].label]})]})})},p.id)})})]})})}function Znn({open:s,onOpenChange:t}){return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Vs,{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(pa,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx($s,{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 Xnn({open:s,onOpenChange:t}){const{brokerageId:n}=vs(),[r,a]=j.useState(""),[i,l]=j.useState([]),[o,c]=j.useState(!1),{data:d,isLoading:u}=ct({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])},p=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)}},f=x=>{x||(l([]),a("")),t(x)};return e.jsx(zs,{open:s,onOpenChange:f,children:e.jsxs(Ds,{className:"max-w-md",children:[e.jsx(Vs,{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($r,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx($s,{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(Fr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{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(Et,{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(Bn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No agents found"})]}):e.jsx(Gi,{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(xi,{checked:i.includes(x.id),onCheckedChange:()=>m(x.id)}),e.jsx(Ea,{className:"h-8 w-8",children:e.jsx(Ta,{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(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsx(U,{onClick:p,disabled:i.length===0||o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),"Send Link"]})})]})]})})}function Qnn(){const[s,t]=j.useState(!1),[n,r]=j.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(we,{className:"mb-8",children:[e.jsx(Tt,{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(Bn,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(It,{children:"Agent Onboarding"}),e.jsx(Jn,{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(U,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(pa,{className:"h-4 w-4"}),"Schedule Agent Onboarding"]}),e.jsxs(U,{variant:"outline",onClick:()=>r(!0),className:"flex items-center gap-2",children:[e.jsx($r,{className:"h-4 w-4"}),"Send New Agent Onboarding Link"]})]})})]}),e.jsx(Znn,{open:s,onOpenChange:t}),e.jsx(Xnn,{open:n,onOpenChange:r})]})}function Jnn({open:s,onOpenChange:t}){return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Vs,{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(pv,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx($s,{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 ern(){const[s,t]=j.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(we,{className:"mb-8",children:[e.jsx(Tt,{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(pv,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(It,{children:"Launch or ReLaunch Meeting"}),e.jsx(Jn,{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(U,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(pv,{className:"h-4 w-4"}),"Schedule Launch Meeting"]})})]}),e.jsx(Jnn,{open:s,onOpenChange:t})]})}function trn(){const s=Wn(),[t,n]=j.useState(""),[r,a]=j.useState(null),{data:i,isLoading:l}=ct({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}=ct({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}=ct({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}=ct({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}=ct({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)),p=x=>{const y=(c==null?void 0:c.filter(N=>N.resource_id===x).length)||0,v=(d==null?void 0:d.filter(N=>N.resource_id===x).length)||0,b=(u==null?void 0:u.filter(N=>N.resource_id===x).length)||0;return{pdfCount:y,videoCount:v,linkCount:b}},f=x=>{s(`/brokerage-resources/${x}`)};return e.jsx(qs,{title:"Brokerage Resources",description:"Access exclusive resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Qnn,{}),e.jsx(ern,{}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search resources...",value:t,onChange:x=>n(x.target.value),className:"pl-10"})]}),m&&m.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Be,{variant:r===null?"default":"outline",className:"cursor-pointer",onClick:()=>a(null),children:"All"}),m.map(x=>e.jsx(Be,{variant:r===x.id?"default":"outline",className:"cursor-pointer",onClick:()=>a(x.id),children:x.name},x.id))]}),!l&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(h==null?void 0:h.length)||0," resource",(h==null?void 0:h.length)!==1?"s":""," available"]}),l?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:[...Array(6)].map((x,y)=>e.jsxs(we,{children:[e.jsx(xn,{className:"h-40 w-full"}),e.jsx(Tt,{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(we,{className:"p-12 text-center",children:[e.jsx(og,{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}=p(x.id),N=o==null?void 0:o.find(S=>S.id===x.category_id);return e.jsxs(we,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>f(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(og,{className:"h-16 w-16 text-muted-foreground"})}),e.jsx(Tt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(It,{className:"text-lg line-clamp-1",children:x.title}),N&&e.jsx(Be,{variant:"secondary",className:"shrink-0 text-xs",children:N.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(Ur,{className:"h-4 w-4"}),y]}),v>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Wr,{className:"h-4 w-4"}),v]}),b>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Rc,{className:"h-4 w-4"}),b]})]})]})]},x.id)})})]})})}const srn=()=>{const{resourceId:s}=Di(),{data:t,isLoading:n}=ct({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(qs,{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(qs,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(U,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(xr,{to:"/brokerage-resources",children:[e.jsx(Aa,{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(we,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Wr,{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(we,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Ur,{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(Ur,{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(pi,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})}),t.links&&t.links.length>0&&e.jsx(we,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Sr,{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(Sr,{className:"h-4 w-4 text-primary"})}),e.jsx("div",{className:"font-medium text-sm",children:a.title})]}),e.jsx(Sr,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})})]})}):e.jsx(qs,{title:"Brokerage Resources",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(og,{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(U,{asChild:!0,className:"mt-4",children:e.jsx(xr,{to:"/brokerage-resources",children:"Back to Resources"})})]})})};function nrn(){const{onlineUsers:s,totalOnline:t}=SMt(),{user:n}=vs();return e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4"}),"Online Now"]}),e.jsxs(Be,{variant:"secondary",className:"bg-green-100 text-green-700",children:[e.jsx(Nf,{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(Gi,{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(Ea,{className:"h-9 w-9",children:[e.jsx(Ci,{src:r.avatarUrl,alt:r.name}),e.jsx(Ta,{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 ",Nd(new Date(r.onlineSince),{addSuffix:!1})]})]})]},r.id)})})})})]})}const J0t={users:{label:"Users & Access",sections:[{title:"Member Broadcasts",description:"Email a filtered group of members (paste HTML or write it)",icon:Th,path:"/admin/broadcasts",color:"bg-rose-500/10 text-rose-600"},{title:"Members",description:"Manage users, roles, and brokerage assignments",icon:Bn,path:"/admin/members",color:"bg-blue-500/10 text-blue-600"},{title:"Partnerships",description:"Manage partnership packages, rosters, and upgrade requests",icon:Ro,path:"/admin/partnerships",color:"bg-indigo-500/10 text-indigo-600"},{title:"Invite Codes",description:"Create and manage signup invite codes",icon:BF,path:"/admin/invite-codes",color:"bg-amber-500/10 text-amber-600"},{title:"Subscriptions",description:"Track and manage user subscriptions",icon:oy,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:TX,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:Cf,path:"/admin/discounts",color:"bg-red-500/10 text-red-600"},{title:"Referral Program",description:"Track brokerage referrals and discounts",icon:jd,path:"/admin/referrals",color:"bg-teal-500/10 text-teal-600"},{title:"Teams",description:"Manage agent teams across all brokerages",icon:Bn,path:"/admin/members?tab=teams",color:"bg-violet-500/10 text-violet-600"},{title:"Prospector",description:"Send free trial invites and track conversions",icon:Gu,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:zl,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:Al,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:Q2,path:"/admin/blog",color:"bg-amber-500/10 text-amber-600"},{title:"Manage Templates",description:"Upload and organize Canva templates",icon:$c,path:"/admin/templates",color:"bg-pink-500/10 text-pink-600"},{title:"Manage Programs",description:"Cohorts, enrollments and delayed billing",icon:Kh,path:"/admin/programs",color:"bg-emerald-500/10 text-emerald-600"},{title:"Manage Academy",description:"Upload videos and training content",icon:Kh,path:"/admin/academy",color:"bg-indigo-500/10 text-indigo-600"},{title:"Manage Toolbox",description:"Create and manage resource kits",icon:O4,path:"/admin/toolbox",color:"bg-orange-500/10 text-orange-600"},{title:"Social Swag",description:"Manage social media content and links",icon:cn,path:"/admin/social-swag",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Social Swag 2.0",description:"New monthly social media images",icon:cn,path:"/admin/social-swag-2",color:"bg-cyan-500/10 text-cyan-600"},{title:"Newsletters",description:"Manage monthly newsletter templates",icon:Q2,path:"/admin/newsletters",color:"bg-violet-500/10 text-violet-600"},{title:"Newsletter Graphics",description:"Upload branded graphics agents drop into newsletters & emails",icon:Q2,path:"/admin/newsletter-graphics",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Manage Events",description:"Create and publish events with Zoom integration",icon:nc,path:"/admin/events",color:"bg-green-500/10 text-green-600"},{title:"LevelUp Live",description:"Public streaming pages, invite links, and live leads",icon:mv,path:"/admin/live",color:"bg-red-500/10 text-red-600"},{title:"Additional Services",description:"Manage additional service offerings",icon:og,path:"/admin/additional-services",color:"bg-lime-500/10 text-lime-600"},{title:"Brokerage Resources",description:"Manage resources for brokerage managers",icon:og,path:"/admin/brokerage-resources",color:"bg-slate-500/10 text-slate-600"},{title:"Agent Email Templates",description:"Manage curated email templates for agents",icon:ln,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:Th,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:EF,path:"/admin/dashboard-management",color:"bg-teal-500/10 text-teal-600"},{title:"Manage Apps",description:"Configure app tiles and access requirements",icon:Aw,path:"/admin/apps",color:"bg-purple-500/10 text-purple-600"},{title:"Email Templates",description:"Customize system email templates",icon:ln,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:Th,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:T4,path:"/admin/onboarding-checklist",color:"bg-emerald-500/10 text-emerald-600"},{title:"Marketplace",description:"Manage store categories, products, and orders",icon:D4,path:"/admin/marketplace",color:"bg-gradient-to-br from-orange-500/20 to-amber-500/10 text-orange-600"},{title:"Reward Store",description:"Manage reward items agents can redeem with points",icon:Ro,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:Al,path:"/admin/agent-points",color:"bg-amber-500/10 text-amber-600"},{title:"Integrations",description:"Connect Canva, Facebook & Instagram for platform-level features",icon:ad,path:"/admin/integrations",color:"bg-blue-500/10 text-blue-600"},{title:"Agent Cards",description:"Manage digital business cards for agents",icon:Bn,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:Th,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:Ki,path:"/admin/community",color:"bg-cyan-500/10 text-cyan-600"},{title:"Support Tickets",description:"View and respond to agent support requests",icon:sq,path:"/admin/support-tickets",color:"bg-rose-500/10 text-rose-600"},{title:"Wishlist",description:"Review and manage community feature requests",icon:eS,path:"/admin/wishlist",color:"bg-yellow-500/10 text-yellow-600"},{title:"Membership Reviews",description:"View member feedback and ratings",icon:Ua,path:"/admin/membership-reviews",color:"bg-amber-500/10 text-amber-600"},{title:"Weekly Digest",description:"Configure automated weekly email digests",icon:ln,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:Cl,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:ig,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:hv,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:Kh,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:ko,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:ra,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:zl,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:zl,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:hv,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:Ur,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:cn,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:pc,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:Gh,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:ig,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:pc,path:"/admin/beta/social-post-generator",color:"bg-gradient-to-br from-fuchsia-500/20 to-pink-500/10 text-fuchsia-600"},{title:"Postcard Direct Mail",description:"Upload monthly postcard designs and manage agent direct mail via Postalytics",icon:ln,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:SM,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:fl,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:PX,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:Ro,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:rc,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:Ur,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:Ur,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:Ur,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:yu,path:"/admin/mls-fee-tracker",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]}};function eyt(){const s=Wn();return console.log("[AdminDashboard] render"),e.jsx(qs,{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(oa,{defaultValue:"users",className:"w-full",children:[e.jsx(la,{className:"w-full justify-start flex-wrap h-auto gap-1 bg-muted/50 p-1 overflow-x-auto",children:Object.entries(J0t).map(([t,n])=>e.jsx(Kt,{value:t,className:"data-[state=active]:bg-background",children:n.label},t))}),Object.entries(J0t).map(([t,n])=>e.jsx(Zt,{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(we,{className:"cursor-pointer hover:shadow-md transition-all hover:border-primary/50 group",onClick:()=>s(r.path),children:[e.jsxs(Tt,{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(It,{className:"text-base",children:r.title})]}),e.jsx(Ie,{className:"pt-0",children:e.jsx(Jn,{className:"text-sm",children:r.description})})]},r.path))})},t))]}),e.jsx(nrn,{})]})})}const rrn=()=>{const{isAdmin:s}=vs(),t=Wn(),[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 Yi("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")}},p=x=>{d(x),o(!0)},f=()=>{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(U,{variant:"ghost",size:"sm",onClick:()=>t("/dashboard"),children:[e.jsx(Aa,{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(al,{asChild:!0,children:e.jsxs(U,{onClick:f,children:[e.jsx(an,{className:"mr-2 h-4 w-4"}),"Add App"]})}),e.jsxs(Ds,{className:"max-w-2xl",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{htmlFor:"name",children:"App Name"}),e.jsx(xe,{id:"name",name:"name",defaultValue:c==null?void 0:c.name,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"app_id",children:"App ID"}),e.jsx(xe,{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(te,{htmlFor:"description",children:"Description"}),e.jsx(Fs,{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(te,{htmlFor:"icon",children:"Icon (emoji)"}),e.jsx(xe,{id:"icon",name:"icon",defaultValue:c==null?void 0:c.icon,placeholder:"🚀",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"target_url",children:"Target URL"}),e.jsx(xe,{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(te,{htmlFor:"required_tags",children:"Required Tags (comma-separated)"}),e.jsx(xe,{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(U,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(U,{type:"submit",children:c?"Update":"Create"})]})]})]})]})]})})}),e.jsx("div",{className:"container mx-auto px-4 py-8",children:e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"Application Tiles"}),e.jsx(Jn,{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(U,{onClick:f,children:[e.jsx(an,{className:"mr-2 h-4 w-4"}),"Create First App"]})]}):e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Icon"}),e.jsx(Lt,{children:"Name"}),e.jsx(Lt,{children:"App ID"}),e.jsx(Lt,{children:"Target URL"}),e.jsx(Lt,{children:"Tags"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:n.map(x=>e.jsxs(gn,{children:[e.jsx(gt,{className:"text-2xl",children:x.icon}),e.jsx(gt,{className:"font-medium",children:x.name}),e.jsx(gt,{className:"font-mono text-sm",children:x.app_id}),e.jsx(gt,{className:"text-sm text-muted-foreground max-w-xs truncate",children:x.target_url}),e.jsx(gt,{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(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>p(x),children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>m(x.id),children:e.jsx(In,{className:"h-4 w-4"})})]})})]},x.id))})]})})]})})]})};function Xh({title:s,description:t,children:n}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(xr,{to:"/admin",children:e.jsxs(U,{variant:"ghost",size:"sm",className:"gap-2 text-muted-foreground hover:text-foreground",children:[e.jsx(Aa,{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 tyt=({expiresAt:s,className:t})=>{const n=new Date().getTime(),r=new Date(s).getTime(),a=Math.ceil((r-n)/(1e3*60*60*24));return a<=0?e.jsxs(Be,{variant:"destructive",className:Mt("gap-1",t),children:[e.jsx(tc,{className:"h-3 w-3"}),"Trial Expired"]}):a<=1?e.jsxs(Be,{variant:"destructive",className:Mt("gap-1",t),children:[e.jsx(Yr,{className:"h-3 w-3"}),"Trial: <1 day left"]}):a<=3?e.jsxs(Be,{className:Mt("gap-1 bg-amber-500 hover:bg-amber-600",t),children:[e.jsx(Yr,{className:"h-3 w-3"}),"Trial: ",a," days left"]}):e.jsxs(Be,{variant:"secondary",className:Mt("gap-1",t),children:[e.jsx(Yr,{className:"h-3 w-3"}),"Trial: ",a," days left"]})},nqt=({open:s,onOpenChange:t,brokerages:n,fixedBrokerageId:r,onSuccess:a})=>{const{toast:i}=Ai(),l=j.useRef(null),[o,c]=j.useState([]),[d,u]=j.useState(""),[h,m]=j.useState(!1),[p,f]=j.useState("upload"),[x,y]=j.useState(null),v=()=>{c([]),u(""),f("upload"),y(null),l.current&&(l.current.value="")},b=()=>{v(),t(!1)},N=M=>{const I=M.split(` `).map(V=>V.trim()).filter(V=>V);if(I.length===0)return[];const R=I[0].toLowerCase(),$=R.includes("first")||R.includes("last")||R.includes("email")||R.includes("name")||R.includes("phone")||R.includes("sms")||R.includes("consent")?I.slice(1):I,H=[];for(const V of $){const Z=(V.includes(" ")?V.split(" "):V.split(",")).map(Q=>Q.trim().replace(/^["']|["']$/g,""));if(Z.length>=2){let Q="",le="",ue="",se="",ne;if(Z.length===2){const je=Z[0].split(" ");Q=je[0]||"",le=je.slice(1).join(" ")||"",ue=Z[1]}else if(Z.length===3)Q=Z[0],le=Z[1],ue=Z[2];else if(Z.length===4)Q=Z[0],le=Z[1],ue=Z[2],se=Z[3];else if(Z.length>=5){Q=Z[0],le=Z[1],ue=Z[2],se=Z[3];const je=Z[4].toLowerCase();ne=je==="true"||je==="yes"||je==="1"||je==="y"}const ce=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ue);H.push({firstName:Q.trim(),lastName:le.trim(),email:ue.trim().toLowerCase(),phone:se.trim()||void 0,smsConsent:ne,isValid:ce&&Q.trim().length>0,error:ce?Q.trim()?void 0:"Missing name":"Invalid email"})}}return H},S=M=>{var z;const I=(z=M.target.files)==null?void 0:z[0];if(!I)return;const R=new FileReader;R.onload=$=>{var K;const H=(K=$.target)==null?void 0:K.result,V=N(H);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),f("preview")},R.readAsText(I)},A=async()=>{const M=o.filter(R=>R.isValid);if(M.length===0){i({title:"No valid users",description:"There are no valid users to import.",variant:"destructive"});return}const I=r||d||null;m(!0);try{const{data:{session:R}}=await q.auth.getSession(),z=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-create-users",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${R==null?void 0:R.access_token}`},body:JSON.stringify({users:M.map(H=>({firstName:H.firstName,lastName:H.lastName,email:H.email,phone:H.phone,smsConsent:H.smsConsent})),brokerageId:I})}),$=await z.json();if(!z.ok)throw new Error($.error||"Failed to import users");y($),f("result"),$.created>0&&a(),i({title:"Import Complete",description:`${$.created} user(s) created successfully.${$.failed>0?` ${$.failed} failed.`:""}`})}catch(R){console.error("Import error:",R),i({title:"Import Failed",description:R.message||"Failed to import users",variant:"destructive"})}finally{m(!1)}},T=o.filter(M=>M.isValid).length,L=o.filter(M=>!M.isValid).length;return e.jsx(zs,{open:s,onOpenChange:b,children:e.jsxs(Ds,{className:"max-w-2xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Qk,{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."})]}),p==="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(qa,{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(U,{onClick:()=>{var M;return(M=l.current)==null?void 0:M.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."})]})]}),p==="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(te,{children:"Assign to Brokerage (optional)"}),e.jsxs(Ns,{value:d||"none",onValueChange:M=>u(M==="none"?"":M),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select a brokerage..."})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"No brokerage"}),n.map(M=>e.jsx(et,{value:M.id,children:M.name},M.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(zr,{className:"h-4 w-4 text-green-500"}),e.jsxs("span",{children:[T," valid"]})]}),L>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Vo,{className:"h-4 w-4"}),e.jsxs("span",{children:[L," invalid"]})]})]}),e.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{className:"bg-muted/30",children:[e.jsx(Lt,{children:"First Name"}),e.jsx(Lt,{children:"Last Name"}),e.jsx(Lt,{children:"Email"}),e.jsx(Lt,{children:"Phone"}),e.jsx(Lt,{children:"SMS"}),e.jsx(Lt,{children:"Status"})]})}),e.jsx(Xa,{children:o.slice(0,100).map((M,I)=>e.jsxs(gn,{children:[e.jsx(gt,{children:M.firstName}),e.jsx(gt,{children:M.lastName}),e.jsx(gt,{children:M.email}),e.jsx(gt,{className:"text-muted-foreground",children:M.phone||"-"}),e.jsx(gt,{className:"text-muted-foreground",children:M.smsConsent===!0?"✓":M.smsConsent===!1?"✗":"-"}),e.jsx(gt,{children:M.isValid?e.jsx(Be,{variant:"default",className:"bg-green-500/10 text-green-600",children:"Valid"}):e.jsx(Be,{variant:"destructive",children:M.error||"Invalid"})})]},I))})]}),o.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",o.length," users"]})]})]}),p==="result"&&x&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx(zr,{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((M,I)=>e.jsxs("li",{children:["• ",M]},I)),x.errors.length>10&&e.jsxs("li",{children:["...and ",x.errors.length-10," more"]})]})]})]}),e.jsxs(Mr,{children:[p==="upload"&&e.jsx(U,{variant:"outline",onClick:b,children:"Cancel"}),p==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(U,{variant:"outline",onClick:v,children:"Back"}),e.jsx(U,{onClick:A,disabled:h||T===0,children:h?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${T} Agent${T!==1?"s":""}`})]}),p==="result"&&e.jsx(U,{onClick:b,children:"Done"})]})]})})};function Sh({sortKey:s,currentSortKey:t,currentDirection:n,onSort:r,children:a,className:i,...l}){const o=t===s;return e.jsx(Lt,{className:Mt("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(cp,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(ag,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(xx,{className:"h-3.5 w-3.5 shrink-0 opacity-40"})]})})}function Sre(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 p=u(h),f=u(m);if(p==null&&f==null)return 0;if(p==null)return 1;if(f==null)return-1;let x;return typeof p=="string"&&typeof f=="string"?x=p.localeCompare(f,void 0,{sensitivity:"base"}):x=p-f,a==="asc"?x:-x})},[n,a]);return{sortKey:n,sortDirection:a,handleSort:l,sortData:o}}const arn=[{type:"custom",title:"Great job!",message:"Keep up the amazing work!",icon:Ua},{type:"custom",title:"You're on fire!",message:"Your dedication is inspiring!",icon:Al},{type:"custom",title:"Congratulations!",message:"You earned this celebration!",icon:Wg}];function rqt({open:s,onOpenChange:t,userId:n,userName:r}){const[a,i]=j.useState("custom"),[l,o]=j.useState(""),[c,d]=j.useState(""),u=DCs(),h=p=>{i(p.type),o(p.title),d(p.message)},m=async p=>{if(p.preventDefault(),!l.trim()){ka({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}),ka({title:"Celebration sent! 🎉",description:`${r} will see confetti on their next visit!`}),t(!1),o(""),d(""),i("custom")}catch{ka({title:"Error",description:"Failed to send celebration",variant:"destructive"})}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Wg,{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(te,{className:"text-sm text-muted-foreground mb-2 block",children:"Quick presets:"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:arn.map((p,f)=>e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>h(p),className:"text-xs",children:[e.jsx(p.icon,{className:"h-3 w-3 mr-1"}),p.title]},f))})]}),e.jsxs("form",{onSubmit:m,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{htmlFor:"type",children:"Celebration Type"}),e.jsxs(Ns,{value:a,onValueChange:p=>i(p),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"custom",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ua,{className:"h-4 w-4"})," Custom"]})}),e.jsx(et,{value:"points_earned",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Al,{className:"h-4 w-4"})," Points Earned"]})}),e.jsx(et,{value:"listing_created",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ra,{className:"h-4 w-4"})," Listing Created"]})}),e.jsx(et,{value:"deal_closed",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yu,{className:"h-4 w-4"})," Deal Closed"]})})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"title",children:"Title *"}),e.jsx(xe,{id:"title",value:l,onChange:p=>o(p.target.value),placeholder:"e.g., Congratulations!",maxLength:100})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"message",children:"Message (optional)"}),e.jsx(Fs,{id:"message",value:c,onChange:p=>d(p.target.value),placeholder:"Add a personal message...",rows:3,maxLength:500})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{type:"submit",disabled:u.isPending,children:[e.jsx(Wg,{className:"h-4 w-4 mr-2"}),u.isPending?"Sending...":"Send Celebration"]})]})]})]})})}const JFe={points_earned:{label:"Points Earned",icon:Al,color:"bg-yellow-500"},listing_created:{label:"Listing Created",icon:ra,color:"bg-blue-500"},deal_closed:{label:"Deal Closed",icon:yu,color:"bg-green-500"},custom:{label:"Custom",icon:cn,color:"bg-purple-500"}};function irn(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),[a,i]=j.useState("all"),{data:l=[],isLoading:o}=ct({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:p}=await q.from("profiles").select("id, name, email").in("id",m),f=new Map((p==null?void 0:p.map(x=>[x.id,x]))||[]);return u.map(x=>{var y,v,b;return{...x,user_name:((y=f.get(x.user_id))==null?void 0:y.name)||"Unknown",user_email:((v=f.get(x.user_id))==null?void 0:v.email)||"",creator_name:x.created_by?((b=f.get(x.created_by))==null?void 0:b.name)||"System":"Auto-triggered"}})}}),c=l.filter(u=>{var f,x;const h=((f=u.user_name)==null?void 0:f.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,p=a==="all"||a==="seen"&&u.seen_at||a==="unseen"&&!u.seen_at;return h&&m&&p}),d={total:l.length,seen:l.filter(u=>u.seen_at).length,unseen:l.filter(u=>!u.seen_at).length,byType:Object.keys(JFe).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(Et,{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(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{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(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{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(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{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(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{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(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Wg,{className:"h-5 w-5"}),"Celebration History"]}),e.jsx(Jn,{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(Fr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by agent name, email, or title...",value:s,onChange:u=>t(u.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:n,onValueChange:r,children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{placeholder:"Filter by type"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Types"}),Object.entries(JFe).map(([u,h])=>e.jsx(et,{value:u,children:h.label},u))]})]}),e.jsxs(Ns,{value:a,onValueChange:i,children:[e.jsx(ws,{className:"w-[140px]",children:e.jsx(ks,{placeholder:"Status"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Status"}),e.jsx(et,{value:"seen",children:"Seen"}),e.jsx(et,{value:"unseen",children:"Pending"})]})]})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Type"}),e.jsx(Lt,{children:"Agent"}),e.jsx(Lt,{children:"Title"}),e.jsx(Lt,{children:"Points"}),e.jsx(Lt,{children:"Created By"}),e.jsx(Lt,{children:"Created"}),e.jsx(Lt,{children:"Status"})]})}),e.jsx(Xa,{children:c.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No celebrations found"})}):c.map(u=>{const h=JFe[u.celebration_type],m=h.icon;return e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(m,{className:"h-3 w-3"}),h.label]})}),e.jsx(gt,{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(gt,{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(gt,{children:u.points_amount?e.jsxs(Be,{variant:"secondary",children:["+",u.points_amount]}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(gt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:u.creator_name})}),e.jsx(gt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:Gs(new Date(u.created_at),"MMM d, yyyy h:mm a")})}),e.jsx(gt,{children:u.seen_at?e.jsx(Be,{variant:"outline",className:"bg-green-50 text-green-700 border-green-200",children:"Seen"}):e.jsx(Be,{variant:"outline",className:"bg-orange-50 text-orange-700 border-orange-200",children:"Pending"})})]},u.id)})})]})}),c.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground text-right",children:["Showing ",c.length," of ",l.length," celebrations"]})]})]})]})}const orn=()=>{const{user:s}=vs(),{toast:t}=Ai(),[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,p]=j.useState("new"),[f,x]=j.useState(new Set),y=j.useCallback(async()=>{try{i(!0);const{data:H,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:K,error:Z}=await q.from("trial_email_exports").select("user_id");if(Z)throw Z;const Q=new Set((K||[]).map(ue=>ue.user_id)),le=(H||[]).map(ue=>({...ue,converted_from_trial_at:ue.converted_from_trial_at??null,already_exported:Q.has(ue.id)}));le.sort((ue,se)=>new Date(se.created_at).getTime()-new Date(ue.created_at).getTime()),r(le)}catch(H){console.error("Error loading trial users:",H),t({title:"Error",description:"Failed to load trial users",variant:"destructive"})}finally{i(!1)}},[t]);j.useEffect(()=>{y()},[y]);const v=H=>H.trial_started_at?"ghl":"stripe",b=H=>H.trial_expires_at?H.trial_expires_at:H.subscription_end_date?H.subscription_end_date:null,N=H=>H.converted_from_trial_at!==null,S=H=>{if(N(H))return!1;const V=b(H);return V?new Date(V).getTime()<=Date.now():!1},A=n.filter(H=>!(c!=="all"&&v(H)!==c||u==="active"&&(S(H)||N(H))||u==="expired"&&!S(H)||u==="converted"&&!N(H)||m==="new"&&H.already_exported||m==="exported"&&!H.already_exported)),T=()=>{f.size===A.length?x(new Set):x(new Set(A.map(H=>H.id)))},L=H=>{const V=new Set(f);V.has(H)?V.delete(H):V.add(H),x(V)},M=async()=>{if(f.size===0){t({title:"No users selected",description:"Select users to export",variant:"destructive"});return}o(!0);try{const H=n.filter(ne=>f.has(ne.id)),V="First Name,Last Name,Email,Phone,Trial Type,Status,Signup Date,Expiry Date",K=H.map(ne=>{const ie=(ne.name||"").split(" "),ce=ie[0]||"",je=ie.slice(1).join(" ")||"",be=v(ne)==="stripe"?"Credit Card Trial":"Free Trial (No CC)",he=N(ne)?"Converted":S(ne)?"Expired":"Active",ge=ne.created_at?new Date(ne.created_at).toLocaleDateString():"",ke=b(ne)?new Date(b(ne)).toLocaleDateString():"";return`"${ce}","${je}","${ne.email}","${ne.phone||""}","${be}","${he}","${ge}","${ke}"`}),Z=[V,...K].join(` `),Q=new Blob([Z],{type:"text/csv"}),le=URL.createObjectURL(Q),ue=document.createElement("a");ue.href=le,ue.download=`trial-users-${new Date().toISOString().split("T")[0]}.csv`,ue.click(),URL.revokeObjectURL(le);const se=H.filter(ne=>!ne.already_exported).map(ne=>({user_id:ne.id,exported_by:s.id}));if(se.length>0){const{error:ne}=await q.from("trial_email_exports").upsert(se,{onConflict:"user_id"});ne&&console.error("Error marking exports:",ne)}t({title:"Export complete",description:`Downloaded ${H.length} trial user(s). ${se.length} newly marked as exported.`}),x(new Set),y()}catch(H){console.error("Export error:",H),t({title:"Error",description:"Failed to export",variant:"destructive"})}finally{o(!1)}},I=n.filter(H=>!H.already_exported).length,R=n.filter(H=>H.already_exported).length,z=n.filter(H=>N(H)).length,$=n.filter(H=>!S(H)&&!N(H)).length;return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Et,{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(we,{children:e.jsxs(Tt,{className:"pb-2",children:[e.jsx(Jn,{children:"Total"}),e.jsx(It,{className:"text-2xl",children:n.length})]})}),e.jsx(we,{children:e.jsxs(Tt,{className:"pb-2",children:[e.jsx(Jn,{children:"New (Not Exported)"}),e.jsx(It,{className:"text-2xl text-green-600",children:I})]})}),e.jsx(we,{children:e.jsxs(Tt,{className:"pb-2",children:[e.jsx(Jn,{children:"Active Trials"}),e.jsx(It,{className:"text-2xl",children:$})]})}),e.jsx(we,{children:e.jsxs(Tt,{className:"pb-2",children:[e.jsx(Jn,{children:"Converted 🎉"}),e.jsx(It,{className:"text-2xl text-primary",children:z})]})}),e.jsx(we,{children:e.jsxs(Tt,{className:"pb-2",children:[e.jsx(Jn,{children:"Already Exported"}),e.jsx(It,{className:"text-2xl text-muted-foreground",children:R})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(Ns,{value:m,onValueChange:H=>p(H),children:[e.jsx(ws,{className:"w-[160px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Users"}),e.jsx(et,{value:"new",children:"New Only"}),e.jsx(et,{value:"exported",children:"Already Exported"})]})]}),e.jsxs(Ns,{value:c,onValueChange:H=>d(H),children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Trial Types"}),e.jsx(et,{value:"stripe",children:"Credit Card Trial"}),e.jsx(et,{value:"ghl",children:"Free Trial (No CC)"})]})]}),e.jsxs(Ns,{value:u,onValueChange:H=>h(H),children:[e.jsx(ws,{className:"w-[160px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Statuses"}),e.jsx(et,{value:"active",children:"Active Trial"}),e.jsx(et,{value:"expired",children:"Expired"}),e.jsx(et,{value:"converted",children:"Converted ✓"})]})]}),e.jsx("div",{className:"ml-auto",children:e.jsxs(U,{onClick:M,disabled:l||f.size===0,children:[l?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(pi,{className:"h-4 w-4 mr-2"}),"Export Selected (",f.size,")"]})})]}),e.jsx("div",{className:"border rounded-lg",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Lt,{className:"w-[40px]",children:e.jsx(xi,{checked:A.length>0&&f.size===A.length,onCheckedChange:T})}),e.jsx(Lt,{children:"Name"}),e.jsx(Lt,{children:"Email"}),e.jsx(Lt,{children:"Trial Type"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{children:"Signup Date"}),e.jsx(Lt,{children:"Last Login"}),e.jsx(Lt,{children:"Expires / Renews"}),e.jsx(Lt,{children:"Exported"})]})}),e.jsx(Xa,{children:A.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No trial users match the current filters"})}):A.map(H=>{const V=v(H),K=N(H),Z=S(H),Q=b(H);return e.jsxs(gn,{className:`hover:bg-muted/30 ${K?"bg-primary/5":""}`,children:[e.jsx(gt,{children:e.jsx(xi,{checked:f.has(H.id),onCheckedChange:()=>L(H.id)})}),e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[H.name,K&&e.jsx(rc,{className:"h-3.5 w-3.5 text-primary"})]})}),e.jsx(gt,{className:"text-muted-foreground",children:H.email}),e.jsx(gt,{children:V==="stripe"?e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(oy,{className:"h-3 w-3"}),"Credit Card"]}):e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(ln,{className:"h-3 w-3"}),"Free (No CC)"]})}),e.jsx(gt,{children:K?e.jsxs(Be,{className:"bg-primary/10 text-primary hover:bg-primary/20 gap-1",children:[e.jsx(rc,{className:"h-3 w-3"}),"Converted"]}):Z?e.jsx(Be,{variant:"destructive",children:"Expired"}):e.jsx(Be,{className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active Trial"})}),e.jsx(gt,{className:"text-sm",children:H.created_at?new Date(H.created_at).toLocaleDateString():"—"}),e.jsx(gt,{className:"text-sm",children:H.last_login?e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:new Date(H.last_login).toLocaleDateString()}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(H.last_login).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}):e.jsx("span",{className:"text-muted-foreground",children:"Never"})}),e.jsx(gt,{className:"text-sm",children:K&&Q?e.jsxs("span",{className:"text-muted-foreground",children:["Renews ",new Date(Q).toLocaleDateString()]}):Q?new Date(Q).toLocaleDateString():"—"}),e.jsx(gt,{children:H.already_exported?e.jsx(zr,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Be,{variant:"outline",className:"text-green-600 border-green-300",children:"New"})})]},H.id)})})]})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",A.length," of ",n.length," trial users · ",z," converted to paid"]})]})},lrn=s=>s==null?'""':`"${String(s).replace(/"/g,'""')}"`,crn=()=>{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=>[Gs(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(lrn).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(Et,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx(we,{children:e.jsxs(Ie,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(In,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{children:"No deletion records yet"})]})}):e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsx(It,{className:"text-lg",children:"User Deletion History"}),e.jsxs(U,{variant:"outline",size:"sm",onClick:a,children:[e.jsx(pi,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]}),e.jsx(Ie,{children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Date"}),e.jsx(Lt,{children:"User"}),e.jsx(Lt,{children:"Email"}),e.jsx(Lt,{children:"Brokerage"}),e.jsx(Lt,{children:"Type"}),e.jsx(Lt,{children:"Deleted By"})]})}),e.jsx(Xa,{children:s.map(i=>e.jsxs(gn,{children:[e.jsx(gt,{className:"whitespace-nowrap text-sm",children:Gs(new Date(i.created_at),"MMM d, yyyy h:mm a")}),e.jsx(gt,{className:"font-medium",children:i.deleted_user_name||"—"}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:i.deleted_user_email||"—"}),e.jsx(gt,{children:i.brokerage_name||"—"}),e.jsx(gt,{children:e.jsx(Be,{variant:i.deletion_type==="deleted"?"destructive":"secondary",children:i.deletion_type==="deleted"?"Account Deleted":"Removed"})}),e.jsx(gt,{className:"text-sm",children:i.deleted_by_name||i.deleted_by_email||"—"})]},i.id))})]})})]})},_E=s=>{const{user:t}=vs(),n=Qt(),r=ct({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:p}=await h;if(p)throw p;return m||[]},enabled:!!t}),a=h=>ct({queryKey:["team-members",h],queryFn:async()=>{const{data:m,error:p}=await q.from("team_members").select("*").eq("team_id",h).order("role",{ascending:!0});if(p)throw p;const f=(m||[]).map(v=>v.user_id),{data:x}=await q.from("profiles").select("id, name, email, avatar_url").in("id",f),y=new Map((x||[]).map(v=>[v.id,v]));return(m||[]).map(v=>({...v,profile:y.get(v.user_id)||null}))},enabled:!!h}),i=yt({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:p,error:f}=await q.from("teams").insert(m).select().single();if(f)throw f;return p},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),re.success("Team created!")},onError:h=>{re.error("Failed to create team: "+h.message)}}),l=yt({mutationFn:async({id:h,...m})=>{const{data:p,error:f}=await q.from("teams").update(m).eq("id",h).select().single();if(f)throw f;return p},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),re.success("Team updated")},onError:h=>{re.error("Failed to update team: "+h.message)}}),o=yt({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=yt({mutationFn:async h=>{const{data:m,error:p}=await q.from("team_members").insert({team_id:h.team_id,user_id:h.user_id,role:h.role||"team_member"}).select().single();if(p)throw p.message.includes("duplicate")||p.message.includes("unique")?new Error("This agent is already on this team."):p;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=yt({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=yt({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}},xet=s=>{const t=Qt(),n=ct({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=yt({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=yt({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=yt({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}},drn=s=>{const t=Qt(),n=ct({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=yt({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}},urn=({pond:s,teamId:t})=>{const{useTeamMembers:n}=_E(),{data:r=[],isLoading:a}=n(t),{assignedUserIds:i,isLoading:l,setAssigned:o}=drn(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(Bn,{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(xi,{checked:d,onCheckedChange:m=>o.mutate({user_id:c.user_id,assigned:!!m})}),e.jsx("span",{className:"truncate",children:((u=c.profile)==null?void 0:u.name)||((h=c.profile)==null?void 0:h.email)||"Unknown"}),c.role==="team_leader"&&e.jsx(Be,{variant:"secondary",className:"ml-auto text-[10px]",children:"Leader"})]},c.id)})})]})},aqt=({teamId:s})=>{const{ponds:t,isLoading:n,createPond:r,updatePond:a,deletePond:i}=xet(s),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,p]=j.useState(null),[f,x]=j.useState(null),y=async()=>{c.trim()&&(await r.mutateAsync({name:c.trim(),description:u.trim()}),d(""),h(""),o(!1))};return e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-start justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(It,{className:"text-lg",children:"Lead Ponds"}),e.jsx(Jn,{children:"Create multiple ponds (by area, source, or specialty) and assign which agents can see each one."})]}),e.jsxs(U,{size:"sm",onClick:()=>o(!0),children:[e.jsx(an,{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(cb,{className:"h-4 w-4 text-primary"}),e.jsx("p",{className:"font-medium",children:v.name}),v.is_default&&e.jsx(Be,{variant:"secondary",className:"text-[10px]",children:"Default"})]}),v.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:v.description}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-2 text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:[v.available_count," available"]}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[v.claimed_count," claimed"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(U,{size:"sm",variant:"ghost",onClick:()=>x(f===v.id?null:v.id),children:[e.jsx(Bn,{className:"mr-1 h-3.5 w-3.5"}),f===v.id?"Hide agents":"Assign agents"]}),e.jsx(U,{size:"icon",variant:"ghost",onClick:()=>p(v),children:e.jsx(ri,{className:"h-3.5 w-3.5"})}),e.jsx(U,{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(In,{className:"h-3.5 w-3.5 text-destructive"})})]})]}),f===v.id&&e.jsx(urn,{pond:v,teamId:s})]},v.id))]}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{children:"Pond name"}),e.jsx(xe,{value:c,onChange:v=>d(v.target.value),placeholder:"e.g. Northland Buyers"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Description (optional)"}),e.jsx(xe,{value:u,onChange:v=>h(v.target.value),placeholder:"What kind of leads go in this pond?"})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(U,{onClick:y,disabled:!c.trim()||r.isPending,children:"Create Pond"})]})]})}),e.jsx(zs,{open:!!m,onOpenChange:v=>!v&&p(null),children:e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Edit Pond"})}),m&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Pond name"}),e.jsx(xe,{value:m.name,onChange:v=>p({...m,name:v.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Description"}),e.jsx(xe,{value:m.description||"",onChange:v=>p({...m,description:v.target.value})})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>p(null),children:"Cancel"}),e.jsx(U,{onClick:async()=>{m&&(await a.mutateAsync({id:m.id,name:m.name,description:m.description||""}),p(null))},disabled:a.isPending,children:"Save"})]})]})})]})},hrn=(s,t=!0)=>ct({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}),mrn=()=>{const{user:s}=vs();return ct({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})},iqt=(s,t)=>{const{user:n}=vs(),r=Qt(),a=ct({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=yt({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=yt({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=yt({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}},prn=(s,t,n=100)=>ct({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}),frn=()=>{const s=Qt();return yt({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 oqt({open:s,onOpenChange:t,contactIds:n,contactNames:r=[],onComplete:a}){var A;const{user:i}=vs(),{data:l}=Sj(),{useTeamMembers:o}=_E(),{data:c=[]}=o((l==null?void 0:l.teamId)||""),d=frn(),[u,h]=j.useState(null),[m,p]=j.useState(""),[f,x]=j.useState(!1),y=c.filter(T=>T.user_id!==(i==null?void 0:i.id)),v=async()=>{if(u){x(!0);try{for(const T of n)await d.mutateAsync({contactId:T,toUserId:u,notes:m||void 0});t(!1),h(null),p(""),a==null||a()}catch{}finally{x(!1)}}},b=y.find(T=>T.user_id===u),N=n.length>1,S=r.length>0?N?`${r.length} contacts`:r[0]:N?`${n.length} contacts`:"this contact";return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(S4,{className:"h-5 w-5"}),"Transfer ",S]}),e.jsxs(Pr,{children:["Select a team member to transfer ",N?"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(te,{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(T=>{var L,M,I;return e.jsxs("button",{onClick:()=>h(T.user_id),className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${u===T.user_id?"bg-primary/10 border border-primary/30":"hover:bg-accent border border-transparent"}`,children:[e.jsxs(Ea,{className:"h-8 w-8",children:[e.jsx(Ci,{src:((L=T.profile)==null?void 0:L.avatar_url)||""}),e.jsx(Ta,{className:"text-xs",children:(((M=T.profile)==null?void 0:M.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:((I=T.profile)==null?void 0:I.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:T.role.replace("_"," ")})]})]},T.user_id)})})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"transfer-notes",className:"text-sm font-medium",children:"Notes (optional)"}),e.jsx(Fs,{id:"transfer-notes",value:m,onChange:T=>p(T.target.value),placeholder:"Reason for transfer...",className:"mt-1",rows:2})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{onClick:v,disabled:!u||f,children:[f?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(S4,{className:"h-4 w-4 mr-2"}),"Transfer",b?` to ${(A=b.profile)==null?void 0:A.name}`:""]})]})]})})}const yet=()=>{const s=Wn(),{data:t,isLoading:n}=mrn(),{data:r}=Sj(),[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",p=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]),f=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,N,S;return(v.first_name+" "+(v.last_name||"")).toLowerCase().includes(y)||((b=v.email)==null?void 0:b.toLowerCase().includes(y))||((N=v.phone)==null?void 0:N.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(we,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Bn,{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(we,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name, email, phone, or agent...",value:a,onChange:x=>i(x.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:l,onValueChange:o,children:[e.jsx(ws,{className:"w-[200px]",children:e.jsx(ks,{placeholder:"Filter by agent"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Team Members"}),p.map(x=>e.jsx(et,{value:x.id,children:x.name},x.id))]})]})]})})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[f.length," contact",f.length!==1?"s":""," from ",p.length," teammate",p.length!==1?"s":""]}),e.jsx(we,{children:e.jsx(Ie,{className:"p-0 overflow-x-auto",children:e.jsxs(Ya,{className:"min-w-[800px]",children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Name"}),e.jsx(Lt,{children:"Agent"}),e.jsx(Lt,{children:"Contact Info"}),e.jsx(Lt,{children:"Address"}),e.jsx(Lt,{children:"Lead Source"}),e.jsx(Lt,{children:"Date Added"}),m&&e.jsx(Lt,{className:"w-[80px]",children:"Actions"})]})}),e.jsx(Xa,{children:f.length===0?e.jsx(gn,{children:e.jsx(gt,{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"})}):f.map(x=>e.jsxs(gn,{className:`hover:bg-accent/50 ${m?"cursor-pointer":""}`,onClick:m?()=>s(`/mission-control/contacts/${x.id}`):void 0,children:[e.jsx(gt,{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(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ea,{className:"h-6 w-6",children:[e.jsx(Ci,{src:x.owner_avatar_url||""}),e.jsx(Ta,{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(gt,{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(ln,{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(ba,{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(gt,{children:x.address?e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(ni,{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(gt,{children:x.lead_source?e.jsx(Be,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:x.lead_source}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(gt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:Gs(new Date(x.created_at),"MMM d, yyyy")})}),m&&e.jsx(gt,{children:e.jsx(U,{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(S4,{className:"h-4 w-4"})})})]},x.id))})]})})}),e.jsx(oqt,{open:!!c,onOpenChange:x=>{x||d(null)},contactIds:c?[c]:[],contactNames:u?[u]:[],onComplete:()=>d(null)})]})},grn=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)},xrn=({leadPondId:s})=>{const{data:t,isLoading:n,error:r}=hrn(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(zF,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground"}):e.jsx(Lm,{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:grn(a.occurred_at)})]})]},i))})},yrn=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)):"",vrn=s=>{var n;const t=((n=s.contact_name)==null?void 0:n.trim())||"A lead";switch(s.event_type){case"claimed":return{icon:XU,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:Kg,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:cb,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"]})}}},syt=({teamId:s,pondId:t})=>{const{data:n,isLoading:r}=prn(s,t),[a,i]=j.useState(!1),l=n||[],o=a?l:l.slice(0,8);return e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs(It,{className:"flex items-center gap-2 text-sm",children:[e.jsx(Y2,{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=vrn(c),h=u.icon;return e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(Ea,{className:"h-6 w-6 shrink-0",children:[e.jsx(Ci,{src:c.actor_avatar_url||""}),e.jsx(Ta,{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:yrn(c.occurred_at)}),c.pond_name&&e.jsx(Be,{variant:"secondary",className:"text-[9px]",children:c.pond_name})]}),c.notes&&e.jsx("p",{className:"whitespace-pre-wrap text-[11px] text-muted-foreground",children:c.notes})]})]},`${c.lead_pond_id}-${c.event_type}-${d}`)})}),l.length>8&&e.jsxs(U,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>i(c=>!c),children:[a?e.jsx(dv,{className:"mr-1 h-3 w-3"}):e.jsx(rl,{className:"mr-1 h-3 w-3"}),a?"Show less":`Show all ${l.length} events`]})]})})]})},brn=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric"}).format(new Date(s)):null,_rn=({item:s,isClaimer:t,onReturn:n,returning:r})=>{var o,c,d;const[a,i]=j.useState(!1),l=brn(s.last_activity_at);return e.jsx(we,{children:e.jsxs(Ie,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("p",{className:"text-sm font-medium",children:[(o=s.contact)==null?void 0:o.first_name," ",((c=s.contact)==null?void 0:c.last_name)||""]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Be,{variant:"secondary",className:"text-xs",children:["Claimed by ",((d=s.claimer)==null?void 0:d.name)||"Unknown"]}),e.jsxs(Be,{variant:"outline",className:"text-[10px]",children:[s.touch_count||0," follow-up",(s.touch_count||0)===1?"":"s"]}),e.jsxs("span",{className:"flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(Yr,{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(xa,{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(U,{size:"sm",variant:"outline",onClick:n,disabled:r,children:[e.jsx(Kg,{className:"mr-1 h-3 w-3"}),"Return"]})]}),s.can_view_activity&&e.jsxs("div",{className:"border-t pt-2",children:[e.jsxs(U,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>i(u=>!u),children:[a?e.jsx(dv,{className:"mr-1 h-3 w-3"}):e.jsx(rl,{className:"mr-1 h-3 w-3"}),a?"Hide notes & activity":"View notes & activity"]}),a&&e.jsx(xrn,{leadPondId:s.id})]})]})})},vet=({teamId:s})=>{const{user:t}=vs(),[n,r]=j.useState(null),{ponds:a,isLoading:i}=xet(s),l=a.filter(f=>f.has_access),{leadPondItems:o,isLoading:c,claimLead:d,returnLead:u}=iqt(s,n),h=l.length>1?e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(U,{size:"sm",variant:n===null?"default":"outline",onClick:()=>r(null),children:"All Ponds"}),l.map(f=>e.jsxs(U,{size:"sm",variant:n===f.id?"default":"outline",onClick:()=>r(f.id),children:[e.jsx(cb,{className:"mr-1 h-3 w-3"}),f.name,e.jsx(Be,{variant:"secondary",className:"ml-2 text-[10px]",children:f.available_count})]},f.id))]}):null;if(console.log("[LeadPondView] render — teamId:",s,"itemCount:",o.length,"loading:",c),c)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(f=>e.jsx(xn,{className:"h-20 w-full"},f))});if(o.length===0)return e.jsxs("div",{className:"space-y-4",children:[h,e.jsx(we,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(cb,{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(syt,{teamId:s,pondId:n})]});const m=o.filter(f=>f.status==="available"),p=o.filter(f=>f.status==="claimed");return e.jsxs("div",{className:"space-y-6",children:[h,e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Available (",m.length,")"]}),m.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:m.map(f=>{var x,y,v,b,N,S,A,T,L,M,I;return e.jsx(we,{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:[((x=f.contact)==null?void 0:x.first_name)||"Unnamed"," ",((y=f.contact)==null?void 0:y.last_name)||""]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1",children:[((v=f.contact)==null?void 0:v.email)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ln,{className:"h-3 w-3"})," ",f.contact.email]}),((b=f.contact)==null?void 0:b.phone)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ba,{className:"h-3 w-3"})," ",f.contact.phone]}),((N=f.contact)==null?void 0:N.address)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ni,{className:"h-3 w-3"})," ",f.contact.address]})]}),f.pond_name&&n===null&&l.length>1&&e.jsxs(Be,{variant:"secondary",className:"text-[10px]",children:[e.jsx(cb,{className:"mr-1 h-2.5 w-2.5"})," ",f.pond_name]}),((S=f.contact)==null?void 0:S.lead_source)&&e.jsxs(Be,{variant:"outline",className:"text-[10px]",children:["Source: ",f.contact.lead_source]}),(f.notes||((A=f.contact)==null?void 0:A.notes))&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-start gap-1 max-w-xl",children:[e.jsx(zF,{className:"h-3 w-3 mt-0.5 shrink-0"}),e.jsx("span",{className:"whitespace-pre-wrap",children:f.notes||((T=f.contact)==null?void 0:T.notes)})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-0.5",children:[e.jsxs(Ea,{className:"h-4 w-4",children:[e.jsx(Ci,{src:((L=f.contributor)==null?void 0:L.avatar_url)||""}),e.jsx(Ta,{className:"text-[8px]",children:(((M=f.contributor)==null?void 0:M.name)||"?").charAt(0)})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["from ",((I=f.contributor)==null?void 0:I.name)||"Unknown"]})]})]}),e.jsxs(U,{size:"sm",className:"shrink-0",onClick:()=>d.mutate(f.id),disabled:d.isPending,children:[e.jsx(XU,{className:"mr-1 h-3 w-3"}),"Claim"]})]})},f.id)})})]}),p.length>0&&e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Claimed (",p.length,")"]}),e.jsx("div",{className:"space-y-2",children:p.map(f=>e.jsx(_rn,{item:f,isClaimer:f.claimed_by===(t==null?void 0:t.id),onReturn:()=>u.mutate(f.id),returning:u.isPending},f.id))})]}),e.jsx(syt,{teamId:s,pondId:n})]})},lqt=({teamId:s})=>{const{useTeamMembers:t}=_E(),{data:n=[]}=t(s),r=n.map(p=>p.user_id),a=new Map(n.map(p=>[p.user_id,p.profile])),{data:i=[],isLoading:l}=ct({queryKey:["team-shared-presentations",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:p,error:f}=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(f)throw f;return p||[]},enabled:r.length>0}),{data:o=[],isLoading:c}=ct({queryKey:["team-shared-open-houses",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:p,error:f}=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(f)throw f;return p||[]},enabled:r.length>0}),{data:d=[],isLoading:u}=ct({queryKey:["team-shared-videos",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:p,error:f}=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(f)throw f;return p||[]},enabled:r.length>0});if(l||c||u)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(p=>e.jsx(xn,{className:"h-20 w-full"},p))});const m=p=>{const f=a.get(p);return{name:(f==null?void 0:f.name)||"Unknown",avatar:(f==null?void 0:f.avatar_url)||"",initials:((f==null?void 0:f.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(we,{children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx(hv,{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(we,{children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx(ra,{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(we,{children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx(Wr,{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(oa,{defaultValue:"presentations",className:"space-y-4",children:[e.jsxs(la,{children:[e.jsxs(Kt,{value:"presentations",children:["Presentations (",i.length,")"]}),e.jsxs(Kt,{value:"guest-books",children:["Guest Books (",o.length,")"]}),e.jsxs(Kt,{value:"videos",children:["Videos (",d.length,")"]})]}),e.jsx(Zt,{value:"presentations",className:"space-y-2",children:i.length===0?e.jsx(e7e,{icon:e.jsx(hv,{className:"h-10 w-10"}),label:"No presentations yet"}):i.map(p=>{const f=m(p.owner_user_id);return e.jsx(we,{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(Ea,{className:"h-8 w-8 shrink-0",children:[e.jsx(Ci,{src:f.avatar}),e.jsx(Ta,{className:"text-xs",children:f.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:p.title||"Untitled"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[f.name," · ",Gs(new Date(p.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(Be,{variant:p.status==="published"?"default":"secondary",className:"text-xs capitalize",children:p.status}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(xa,{className:"h-3 w-3"}),p.view_count||0]})]})]})},p.id)})}),e.jsx(Zt,{value:"guest-books",className:"space-y-2",children:o.length===0?e.jsx(e7e,{icon:e.jsx(ra,{className:"h-10 w-10"}),label:"No guest books yet"}):o.map(p=>{const f=m(p.agent_id);return e.jsx(we,{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(Ea,{className:"h-8 w-8 shrink-0",children:[e.jsx(Ci,{src:f.avatar}),e.jsx(Ta,{className:"text-xs",children:f.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:p.property_address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[f.name," · ",Gs(new Date(p.event_date),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[p.is_active?e.jsx(Be,{className:"text-xs",children:"Active"}):e.jsx(Be,{variant:"secondary",className:"text-xs",children:"Inactive"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Bn,{className:"h-3 w-3"}),p.visitor_count||0]})]})]})},p.id)})}),e.jsx(Zt,{value:"videos",className:"space-y-2",children:d.length===0?e.jsx(e7e,{icon:e.jsx(Wr,{className:"h-10 w-10"}),label:"No videos yet"}):d.map(p=>{const f=m(p.owner_user_id);return e.jsx(we,{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(Ea,{className:"h-8 w-8 shrink-0",children:[e.jsx(Ci,{src:f.avatar}),e.jsx(Ta,{className:"text-xs",children:f.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:p.title||p.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[f.name," · ",Gs(new Date(p.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(Be,{variant:"secondary",className:"text-xs capitalize",children:p.touch_type}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(xa,{className:"h-3 w-3"}),p.view_count||0]})]})]})},p.id)})})]})]})},e7e=({icon:s,label:t})=>e.jsx(we,{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})]})}),cqt=({team:s,brokerageAgents:t,onBack:n,onUpdate:r,onAddMember:a,onRemoveMember:i,onUpdateRole:l,onDeleteTeam:o,isUpdating:c,isAddingMember:d})=>{var L,M;const{useTeamMembers:u}=_E(),{data:h=[],isLoading:m}=u(s.id),[p,f]=j.useState(!1),[x,y]=j.useState(""),[v,b]=j.useState("team_member"),{data:N}=ct({queryKey:["agents-on-other-teams",s.id],queryFn:async()=>{const{data:I}=await q.from("team_members").select("user_id, team_id, teams:team_id(name)").neq("team_id",s.id),R=new Map;return(I||[]).forEach(z=>{var H;const $=R.get(z.user_id)||[];$.push(((H=z.teams)==null?void 0:H.name)||"another team"),R.set(z.user_id,$)}),R}}),S=new Set(h.map(I=>I.user_id)),A=t.filter(I=>!S.has(I.id)),T=async()=>{x&&(await a(x,v),y(""),b("team_member"),f(!1))};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(U,{variant:"ghost",onClick:n,className:"mb-2",children:"← Back to Teams"}),e.jsxs(oa,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(la,{children:[e.jsx(Kt,{value:"members",children:"Members"}),e.jsxs(Kt,{value:"contacts",children:[e.jsx(SF,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),s.lead_pond_enabled&&e.jsxs(Kt,{value:"lead-pond",children:[e.jsx(cb,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),s.shared_assets_enabled&&e.jsxs(Kt,{value:"shared-assets",children:[e.jsx(r1,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),e.jsx(Kt,{value:"settings",children:"Settings"})]}),e.jsxs(Zt,{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:p,onOpenChange:f,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{size:"sm",children:[e.jsx(zl,{className:"mr-2 h-4 w-4"}),"Add Member"]})}),e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{children:"Agent"}),e.jsxs(md,{children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[x&&(((L=A.find(I=>I.id===x))==null?void 0:L.name)||((M=A.find(I=>I.id===x))==null?void 0:M.email))||"Select an agent",e.jsx(Jw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(id,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(pj,{children:[e.jsx(fj,{placeholder:"Search agents..."}),e.jsxs(gj,{children:[e.jsx(xj,{children:"No agents found."}),e.jsx(I_,{children:A.map(I=>{const R=N==null?void 0:N.get(I.id);return e.jsxs(e1,{value:I.name||I.email||I.id,onSelect:()=>y(I.id),children:[e.jsx(Xr,{className:Mt("mr-2 h-4 w-4",x===I.id?"opacity-100":"opacity-0")}),I.name||I.email,R!=null&&R.length?e.jsxs("span",{className:"text-xs text-muted-foreground ml-1",children:["(also on ",R.join(", "),")"]}):null]},I.id)})})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Role"}),e.jsxs(Ns,{value:v,onValueChange:b,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"team_leader",children:"Team Leader"}),e.jsx(et,{value:"team_member",children:"Team Member"})]})]})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsx(U,{onClick:T,disabled:!x||d,children:d?"Adding...":"Add to Team"})]})]})]})]}),m?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(I=>e.jsx(xn,{className:"h-16 w-full"},I))}):h.length===0?e.jsx(we,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(Bn,{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(I=>{var R,z,$,H,V;return e.jsx(we,{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(Ea,{className:"h-10 w-10",children:[e.jsx(Ci,{src:((R=I.profile)==null?void 0:R.avatar_url)||""}),e.jsx(Ta,{children:(((z=I.profile)==null?void 0:z.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:(($=I.profile)==null?void 0:$.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(H=I.profile)==null?void 0:H.email})]}),I.role==="team_leader"?e.jsxs(Be,{className:"bg-[hsl(var(--chart-4)/0.1)] text-[hsl(var(--chart-4))] border-[hsl(var(--chart-4))]",children:[e.jsx(h0,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(Be,{variant:"secondary",children:"Member"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ns,{value:I.role,onValueChange:K=>l(I.id,K),children:[e.jsx(ws,{className:"w-[140px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"team_leader",children:"Team Leader"}),e.jsx(et,{value:"team_member",children:"Team Member"})]})]}),e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"text-muted-foreground hover:text-destructive",children:e.jsx(Nq,{className:"h-4 w-4"})})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Remove Member?"}),e.jsxs(Ll,{children:["Remove ",((V=I.profile)==null?void 0:V.name)||"this member"," from ",s.name,"?"]})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>i(I.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})]})]})]})},I.id)})})]}),e.jsx(Zt,{value:"contacts",className:"space-y-4",children:e.jsx(yet,{})}),s.lead_pond_enabled&&e.jsx(Zt,{value:"lead-pond",className:"space-y-4",children:e.jsx(vet,{teamId:s.id})}),s.shared_assets_enabled&&e.jsx(Zt,{value:"shared-assets",className:"space-y-4",children:e.jsx(lqt,{teamId:s.id})}),e.jsxs(Zt,{value:"settings",className:"space-y-4",children:[e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-lg",children:"Team Settings"}),e.jsx(Jn,{children:"Configure how this team operates."})]}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Team Name"}),e.jsx(xe,{defaultValue:s.name,onBlur:I=>{I.target.value!==s.name&&r({name:I.target.value})}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Description"}),e.jsx(Fs,{defaultValue:s.description||"",onBlur:I=>{I.target.value!==(s.description||"")&&r({description:I.target.value||null})},rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Contact Visibility"}),e.jsxs(Ns,{defaultValue:s.contact_visibility,onValueChange:I=>r({contact_visibility:I}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"private",children:"Private — Members keep their contacts private"}),e.jsx(et,{value:"leader_only",children:"Leader Only — Only team leaders can see member contacts"}),e.jsx(et,{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(te,{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(wn,{checked:s.lead_pond_enabled,onCheckedChange:I=>r({lead_pond_enabled:I})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(te,{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(wn,{checked:s.shared_assets_enabled,onCheckedChange:I=>r({shared_assets_enabled:I})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(te,{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(wn,{checked:s.shared_videos_enabled??!1,onCheckedChange:I=>r({shared_videos_enabled:I})})]})]})]}),s.lead_pond_enabled&&e.jsx(aqt,{teamId:s.id}),e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsxs(U,{variant:"destructive",size:"sm",children:[e.jsx(In,{className:"mr-2 h-4 w-4"}),"Delete Team"]})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Delete Team?"}),e.jsxs(Ll,{children:['This will permanently delete "',s.name,'" and remove all team members. This cannot be undone.']})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>{o(),n()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Team"})]})]})]})]})]})]})},dqt=({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,p]=j.useState(""),[f,x]=j.useState(""),[y,v]=j.useState(""),[b,N]=j.useState([]),S=()=>{d(1),h(""),p(""),x(""),v(""),N([])},A=I=>{I||S(),t(I)},T=async()=>{const I=f&&f!=="none"?f:o||null;await n({name:u.trim(),description:m.trim()||void 0,brokerage_id:I,leaderId:y||void 0,memberIds:b.length>0?b:void 0}),S()},L=I=>{I!==y&&N(R=>R.includes(I)?R.filter(z=>z!==I):[...R,I])},M=a.filter(I=>I.id!==y);return e.jsx(zs,{open:s,onOpenChange:A,children:e.jsxs(Ds,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Vs,{children:[e.jsx($s,{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:Mt("h-1.5 flex-1 rounded-full transition-colors","bg-primary")}),e.jsx("div",{className:Mt("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(te,{htmlFor:"team-name",children:"Team Name *"}),e.jsx(xe,{id:"team-name",value:u,onChange:I=>h(I.target.value),placeholder:"e.g., Downtown Squad",autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"team-desc",children:"Description"}),e.jsx(Fs,{id:"team-desc",value:m,onChange:I=>p(I.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(te,{children:"Brokerage"}),e.jsxs(Ns,{value:f,onValueChange:x,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"No brokerage (independent team)"})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"No brokerage (independent)"}),l.map(I=>e.jsx(et,{value:I.id,children:I.name},I.id))]})]})]})]}):e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{className:"flex items-center gap-1.5",children:[e.jsx(h0,{className:"h-3.5 w-3.5 text-[hsl(var(--chart-4))]"}),"Team Leader"]}),e.jsxs(Ns,{value:y,onValueChange:I=>{v(I),N(R=>R.filter(z=>z!==I))},children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select a team leader (optional)"})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"No leader for now"}),a.map(I=>e.jsx(et,{value:I.id,children:I.name||I.email||"Unknown"},I.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{className:"flex items-center gap-1.5",children:[e.jsx(zl,{className:"h-3.5 w-3.5"}),"Initial Members",b.length>0&&e.jsxs(Be,{variant:"secondary",className:"ml-1 text-xs",children:[b.length," selected"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Click agents to add them. You can always add more later."}),e.jsx("div",{className:"border rounded-lg max-h-[240px] overflow-y-auto divide-y",children:M.length===0?e.jsxs("div",{className:"p-4 text-center text-sm text-muted-foreground",children:[e.jsx(Bn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No agents available"]}):M.map(I=>{const R=b.includes(I.id);return e.jsxs("button",{type:"button",className:Mt("w-full flex items-center gap-3 p-3 text-left transition-colors hover:bg-accent/50",R&&"bg-primary/5"),onClick:()=>L(I.id),children:[e.jsxs(Ea,{className:"h-8 w-8",children:[e.jsx(Ci,{src:I.avatar_url||""}),e.jsx(Ta,{className:"text-xs",children:(I.name||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:I.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:I.email})]}),e.jsx("div",{className:Mt("h-5 w-5 rounded-full border-2 flex items-center justify-center transition-colors shrink-0",R?"bg-primary border-primary text-primary-foreground":"border-muted-foreground/30"),children:R&&e.jsx(Xr,{className:"h-3 w-3"})})]},I.id)})})]})]})}),e.jsx(Mr,{className:"gap-2 sm:gap-0",children:c===1?e.jsxs(e.Fragment,{children:[e.jsx(U,{variant:"outline",onClick:()=>A(!1),children:"Cancel"}),e.jsxs(U,{onClick:()=>d(2),disabled:!u.trim(),children:["Next",e.jsx(Oa,{className:"ml-2 h-4 w-4"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(U,{variant:"outline",onClick:()=>d(1),children:[e.jsx(Aa,{className:"mr-2 h-4 w-4"}),"Back"]}),e.jsx(U,{onClick:T,disabled:r,children:r?"Creating…":"Create Team"})]})})]})})},wrn=()=>{const{teams:s,isLoading:t,createTeam:n,updateTeam:r,deleteTeam:a,addMember:i,removeMember:l,updateMemberRole:o}=_E(),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,p]=j.useState(""),{data:f}=ct({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:A,error:T}=await q.from("brokerages").select("id, name").order("name");if(T)throw T;return A||[]}}),{data:x}=ct({queryKey:["admin-team-member-info",s.map(A=>A.id).join(",")],queryFn:async()=>{var I;if(s.length===0)return{};const{data:A}=await q.from("team_members").select("team_id, user_id, role").in("team_id",s.map(R=>R.id));if(!A)return{};const T=A.filter(R=>R.role==="team_leader").map(R=>R.user_id);let L={};if(T.length>0){const{data:R}=await q.from("profiles").select("id, name").in("id",T);R&&(L=Object.fromEntries(R.map(z=>[z.id,{name:z.name}])))}const M={};for(const R of s){const z=A.filter(H=>H.team_id===R.id),$=z.find(H=>H.role==="team_leader");M[R.id]={count:z.length,leaderName:$&&((I=L[$.user_id])==null?void 0:I.name)||null}}return M},enabled:s.length>0}),y=(u==null?void 0:u.brokerage_id)||null,{data:v}=ct({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:T,error:L}=await A;if(L)throw L;return T||[]},enabled:!!u}),b=Object.fromEntries((f||[]).map(A=>[A.id,A.name])),N=async A=>{const T=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:T.id,user_id:A.leaderId,role:"team_leader"}),A.memberIds)for(const L of A.memberIds)await i.mutateAsync({team_id:T.id,user_id:L,role:"team_member"});d(!1)};if(u)return e.jsx(cqt,{team:u,brokerageAgents:v||[],onBack:()=>h(null),onUpdate:A=>r.mutateAsync({id:u.id,...A}).then(T=>h(T)),onAddMember:(A,T)=>i.mutateAsync({team_id:u.id,user_id:A,role:T}),onRemoveMember:A=>l.mutateAsync({team_id:u.id,member_id:A}),onUpdateRole:(A,T)=>o.mutateAsync({team_id:u.id,member_id:A,role:T}),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(Fr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search teams...",value:m,onChange:A=>p(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(U,{size:"sm",onClick:()=>d(!0),children:[e.jsx(an,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(dqt,{open:c,onOpenChange:d,onCreateTeam:N,isCreating:n.isPending,brokerageAgents:[],isAdmin:!0,allBrokerages:f,activeBrokerageId:null}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Lt,{className:"font-semibold",children:"Team Name"}),e.jsx(Lt,{className:"font-semibold",children:"Brokerage"}),e.jsx(Lt,{className:"font-semibold",children:"Leader"}),e.jsx(Lt,{className:"font-semibold",children:"Members"}),e.jsx(Lt,{className:"font-semibold",children:"Visibility"}),e.jsx(Lt,{className:"w-[100px]"})]})}),e.jsx(Xa,{children:t?e.jsx(e.Fragment,{children:[1,2,3].map(A=>e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsx(xn,{className:"h-4 w-32"})}),e.jsx(gt,{children:e.jsx(xn,{className:"h-4 w-24"})}),e.jsx(gt,{children:e.jsx(xn,{className:"h-4 w-28"})}),e.jsx(gt,{children:e.jsx(xn,{className:"h-4 w-12"})}),e.jsx(gt,{children:e.jsx(xn,{className:"h-4 w-20"})}),e.jsx(gt,{children:e.jsx(xn,{className:"h-4 w-16"})})]},A))}):S.length===0?e.jsx(gn,{children:e.jsx(gt,{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 T=x==null?void 0:x[A.id];return e.jsxs(gn,{className:"hover:bg-muted/30",children:[e.jsxs(gt,{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(gt,{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(gt,{children:T!=null&&T.leaderName?e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(h0,{className:"h-3 w-3 text-[hsl(var(--chart-4))]"}),T.leaderName]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No leader"})}),e.jsx(gt,{children:e.jsxs(Be,{variant:"secondary",className:"text-xs",children:[e.jsx(Bn,{className:"h-3 w-3 mr-1"}),(T==null?void 0:T.count)??0]})}),e.jsx(gt,{children:e.jsxs("span",{className:"text-xs text-muted-foreground capitalize flex items-center gap-1",children:[e.jsx(Im,{className:"h-3 w-3"}),A.contact_visibility.replace("_"," ")]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>h(A),title:"Edit team",children:e.jsx(ri,{className:"h-3.5 w-3.5"})}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:async()=>{await Yi(`Delete team "${A.name}"? This cannot be undone.`)&&a.mutate(A.id)},title:"Delete team",children:e.jsx(In,{className:"h-3.5 w-3.5"})})]})})]},A.id)})})]})})]})};function nyt(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 jrn({open:s,onOpenChange:t,recipients:n}){const{toast:r}=Ai(),[a,i]=j.useState([]),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,p]=j.useState(""),[f,x]=j.useState(!1),[y,v]=j.useState(!1),b=j.useMemo(()=>a.find(T=>T.id===c)||null,[a,c]);j.useEffect(()=>{s&&(o(!0),(async()=>{const T=new Date().toISOString(),{data:L,error:M}=await q.from("events").select("id,title,description,event_date,zoom_link,image_url,is_published").gte("event_date",T).order("event_date",{ascending:!0}).limit(50);M?r({title:"Could not load events",description:M.message,variant:"destructive"}):i(L||[]),o(!1)})())},[s,r]);const N=j.useMemo(()=>n.filter(T=>T.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(T.email)),[n]),S=()=>{if(!b){r({title:"Pick an event first",variant:"destructive"});return}if(N.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:T}}=await q.auth.getSession(),L=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${T==null?void 0:T.access_token}`},body:JSON.stringify({event_id:b.id,recipients:N.map($=>({email:$.email,name:$.name,user_id:$.id})),custom_subject:u.trim()||void 0,custom_intro:m.trim()||void 0})}),M=await L.json().catch(()=>({}));if(!L.ok)throw new Error((M==null?void 0:M.error)||"Failed to send event invite");const I=(M==null?void 0:M.sent)??0,R=(M==null?void 0:M.failed)??0,z=(M==null?void 0:M.already_invited)??0;r({title:"Invites sent",description:`Sent: ${I}${z?` · Skipped (already invited): ${z}`:""}${R?` · Failed: ${R}`:""}`}),t(!1),p(""),h(""),d("")}catch(T){const L=T instanceof Error?T.message:"Send failed";r({title:"Send failed",description:L,variant:"destructive"})}finally{x(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5 text-primary"}),"Send Event Invite"]}),e.jsxs(Pr,{children:["Send a beautiful event invitation to ",N.length," selected member",N.length===1?"":"s",".",n.length!==N.length&&e.jsxs("span",{className:"block text-amber-600 mt-1",children:[n.length-N.length," skipped (missing or invalid email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{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(Et,{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(Ns,{value:c,onValueChange:d,children:[e.jsx(ws,{id:"event-select",children:e.jsx(ks,{placeholder:"Pick an upcoming event..."})}),e.jsx(js,{children:a.map(T=>e.jsx(et,{value:T.id,children:e.jsxs("div",{className:"flex flex-col text-left",children:[e.jsx("span",{className:"font-medium",children:T.title}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[nyt(T.event_date),!T.is_published&&" · (Draft)"]})]})},T.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(pa,{className:"h-4 w-4 text-primary"}),b.title]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:nyt(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(te,{htmlFor:"subject",children:"Subject line (optional)"}),e.jsx(xe,{id:"subject",placeholder:b?`You're invited: ${b.title}`:"You're invited to...",value:u,onChange:T=>h(T.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(te,{htmlFor:"intro",children:"Personal message (optional)"}),e.jsx(Fs,{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:T=>p(T.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 (",N.length,")"]}),e.jsxs("div",{className:"flex flex-wrap gap-1 max-h-24 overflow-y-auto",children:[N.slice(0,30).map(T=>e.jsx(Be,{variant:"secondary",className:"text-xs font-normal",children:T.name||T.email},T.id)),N.length>30&&e.jsxs(Be,{variant:"outline",className:"text-xs",children:["+",N.length-30," more"]})]})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),disabled:f,children:"Cancel"}),e.jsx(U,{onClick:S,disabled:f||!c||N.length===0,children:f?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx($r,{className:"h-4 w-4 mr-2"})," Send to ",N.length]})})]})]})}),e.jsx(Fl,{open:y,onOpenChange:v,children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Send event invite?"}),e.jsx(Ll,{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:[N.length," member",N.length===1?"":"s"]}),"?"]}):null})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsxs(_l,{onClick:A,children:[e.jsx($r,{className:"h-4 w-4 mr-2"})," Send"]})]})]})})]})}const Nrn=()=>{var Dr;const s=Wn(),{user:t,isAdmin:n}=vs(),{startImpersonation:r,isLoading:a}=$6e(),{toast:i}=Ai(),[l,o]=j.useState([]),[c,d]=j.useState([]),[u,h]=j.useState([]),[m,p]=j.useState({}),[f,x]=j.useState(!0);j.useState({});const[y,v]=j.useState(!1),[b,N]=j.useState({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),[S,A]=j.useState(!1),[T,L]=j.useState(""),[M,I]=j.useState(1),[R,z]=j.useState(50),[$,H]=j.useState("all"),[V,K]=j.useState("all"),[Z,Q]=j.useState("all"),[le,ue]=j.useState("all"),[se,ne]=j.useState("all"),[ie,ce]=j.useState(!1),[je,be]=j.useState(!1),[he,ge]=j.useState(!1),[ke,Te]=j.useState(null),[Me,Oe]=j.useState(null),[Se,Qe]=j.useState(!1),[Ae,Fe]=j.useState({name:"",email:"",brokerage_id:"",phone:""}),[Ne,$e]=j.useState(null),[Ve,qe]=j.useState(!1),[Ze,Ue]=j.useState(""),[Ye,Ge]=j.useState(!1),[He,tt]=j.useState(!1),[pt,ft]=j.useState(null),[qt,Ut]=j.useState(""),[Wt,us]=j.useState(!1),[zt,bt]=j.useState(!1),[As,vt]=j.useState(null),[Ws,on]=j.useState(!1),[Ms,dn]=j.useState(!1),[rn,br]=j.useState(null),[Gn,On]=j.useState(""),[Rr,cr]=j.useState(!1),[Hs,_r]=j.useState({email:"",name:"",password:"",phone:""}),[nn,Zn]=j.useState(!1),[es,ar]=j.useState(null),[Hn,kn]=j.useState([]),[Un,sn]=j.useState("none"),[un,Ar]=j.useState(!1),[fs,ot]=j.useState(""),[mt,Nt]=j.useState(!1),[Pt,ts]=j.useState(!1),[ls,Is]=j.useState(""),[ps,Ht]=j.useState(new Set),[Xs,Rs]=j.useState(!1),[zn,Qr]=j.useState(!1),[ma,qr]=j.useState(null),[Zr,Jr]=j.useState(!1),[ha,Fa]=j.useState(null),[Fo,Xo]=j.useState([]),[Vi,Ja]=j.useState([]),[Co,Go]=j.useState(!1),[hi,Qo]=j.useState({});j.useEffect(()=>{!t||!n||(_a(),ir())},[t,n]);const Ao=async()=>{try{const{data:kt,error:Es}=await q.from("brokerage_manager_assignments").select("user_id, brokerage_id");if(Es)throw Es;const bn={};for(const Br of kt??[])bn[Br.brokerage_id]||(bn[Br.brokerage_id]=[]),bn[Br.brokerage_id].push(Br.user_id);p(bn)}catch(kt){console.error("Error loading brokerage manager assignments:",kt)}},_a=async()=>{try{x(!0);const{data:kt,error:Es}=await q.functions.invoke("get-user-details");if(Es)throw Es;const bn=kt.users||[];o(bn),h(kt.brokerages||[]),await Ao();const Br=bn.filter(Or=>Or.roles.includes("assistant"));if(Br.length>0){const Or=Br.map(Ra=>Ra.id),{data:Ma}=await q.from("agent_assistant_assignments").select("agent_id, assistant_id").in("assistant_id",Or);if(Ma&&Ma.length>0){const Ra=[...new Set(Ma.map(mi=>mi.agent_id))],{data:nr}=await q.from("profiles").select("id, name, email").in("id",Ra),Va={};for(const mi of Ma){const ol=nr==null?void 0:nr.find(vc=>vc.id===mi.agent_id);ol&&(Va[mi.assistant_id]={agent_name:ol.name||"",agent_email:ol.email||""})}Qo(Va)}}}catch(kt){console.error("Error loading members:",kt),i({title:"Error",description:"Failed to load members",variant:"destructive"})}finally{x(!1)}},ir=async()=>{try{const{data:kt,error:Es}=await q.from("app_tiles").select("id, name, icon, app_id, required_tags").order("name");if(Es)throw Es;d(kt||[])}catch(kt){console.error("Error loading apps:",kt),i({title:"Error",description:"Failed to load apps",variant:"destructive"})}},li=async kt=>{if(!Ae.name.trim()||!Ae.email.trim()){i({title:"Error",description:"Name and email are required",variant:"destructive"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Ae.email)){i({title:"Error",description:"Please enter a valid email address",variant:"destructive"});return}try{const{error:bn}=await q.from("profiles").update({name:Ae.name.trim(),email:Ae.email.trim(),brokerage_id:Ae.brokerage_id||null,phone:Ae.phone.trim()||null}).eq("id",kt);if(bn)throw bn;i({title:"Success",description:"Member details updated successfully"}),Te(null),_a()}catch(bn){console.error("Error updating member:",bn),i({title:"Error",description:bn.message||"Failed to update member",variant:"destructive"})}},Eo=async kt=>{try{const{data:{session:Es}}=await q.auth.getSession(),bn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Es==null?void 0:Es.access_token}`},body:JSON.stringify({userId:kt})}),Br=await bn.json();if(!bn.ok)throw new Error(Br.error||"Failed to resend welcome email");i({title:"Success",description:"Welcome email sent successfully"})}catch(Es){console.error("Error resending welcome email:",Es),i({title:"Error",description:Es.message||"Failed to resend welcome email",variant:"destructive"})}},gl=async(kt,Es)=>{try{const{error:bn}=await q.functions.invoke("send-password-reset",{body:{email:kt,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(bn)throw bn;i({title:"Password Reset Sent",description:`Password reset email sent to ${Es}`})}catch(bn){console.error("Error sending password reset:",bn),i({title:"Error",description:bn.message||"Failed to send password reset email",variant:"destructive"})}},ds=async(kt,Es)=>{if(await Yi(`Are you sure you want to delete ${Es}? This action cannot be undone.`))try{const{data:{session:bn}}=await q.auth.getSession(),Br=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${bn==null?void 0:bn.access_token}`},body:JSON.stringify({userId:kt})}),Or=await Br.json();if(!Br.ok)throw new Error(Or.error||"Failed to delete user");i({title:"Success",description:"User deleted successfully"}),_a()}catch(bn){console.error("Error deleting user:",bn),i({title:"Error",description:bn.message||"Failed to delete user",variant:"destructive"})}},Gr=async()=>{if(!b.email||!b.name||!b.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}if(b.role==="brokerage_manager"&&!b.brokerage_id){i({title:"Error",description:"Please select a brokerage for this manager",variant:"destructive"});return}v(!0);try{const{data:{session:kt}}=await q.auth.getSession(),Es=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${kt==null?void 0:kt.access_token}`},body:JSON.stringify(b)}),bn=await Es.json();if(!Es.ok)throw new Error(bn.error||"Failed to create user");if(b.role&&b.role!=="user"&&bn.userId){const Br=b.role==="brokerage_manager"?b.brokerage_id:void 0;await ji(bn.userId,b.role,"add",Br)}i({title:"Success",description:`User ${b.email} created successfully`}),N({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),A(!1),_a()}catch(kt){console.error("Error creating user:",kt),i({title:"Error",description:kt.message||"Failed to create user",variant:"destructive"})}finally{v(!1)}},ji=async(kt,Es,bn,Br)=>{try{const{data:{session:Or}}=await q.auth.getSession(),Ma={userId:kt,role:Es,action:bn};if(Es==="brokerage_manager"){if(!Br){i({title:"Error",description:"Please choose a brokerage for this manager assignment",variant:"destructive"});return}Ma.brokerageId=Br}const Ra=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Or==null?void 0:Or.access_token}`},body:JSON.stringify(Ma)}),nr=await Ra.json();if(!Ra.ok)throw new Error(nr.error||"Failed to manage user role");i({title:"Success",description:`Role ${bn==="add"?"added":"removed"} successfully`}),_a()}catch(Or){console.error("Error managing user role:",Or),i({title:"Error",description:Or.message||"Failed to manage user role",variant:"destructive"})}},ya=(kt,Es)=>Es.length===0?!0:Es.some(bn=>kt.includes(bn)),Wi=async(kt,Es,bn)=>{const Br=`${kt}-${Es.id}`;$e(Br);try{if(bn){const Or=l.find(Ra=>Ra.id===kt),Ma=Es.required_tags.filter(Ra=>Or==null?void 0:Or.tags.includes(Ra));for(const Ra of Ma){const{error:nr}=await q.from("user_tags").delete().eq("user_id",kt).eq("tag",Ra);if(nr)throw nr}i({title:"Access Removed",description:`Removed access to ${Es.name}`})}else if(Es.required_tags.length>0){const{error:Or}=await q.from("user_tags").insert({user_id:kt,tag:Es.required_tags[0]});if(Or)throw Or;i({title:"Access Granted",description:`Granted access to ${Es.name}`})}await _a()}catch(Or){console.error("Error toggling access:",Or),i({title:"Error",description:Or.message||"Failed to update access",variant:"destructive"})}finally{$e(null)}},wi=async()=>{const kt=Ze.trim();if(!kt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(kt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}if(u.find(bn=>bn.name.toLowerCase()===kt.toLowerCase())){i({title:"Error",description:"A brokerage with this name already exists",variant:"destructive"});return}Ge(!0);try{const{error:bn}=await q.from("brokerages").insert({name:kt});if(bn)throw bn;i({title:"Success",description:`Brokerage "${kt}" created successfully`}),Ue(""),qe(!1),_a()}catch(bn){console.error("Error creating brokerage:",bn),i({title:"Error",description:bn.message||"Failed to create brokerage",variant:"destructive"})}finally{Ge(!1)}},di=kt=>{ft(kt),Ut(kt.name),tt(!0)},Dc=()=>{ft(null),Ut(""),tt(!1)},fd=async()=>{if(!pt)return;const kt=qt.trim();if(!kt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(kt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}us(!0);try{const{error:Es}=await q.from("brokerages").update({name:kt}).eq("id",pt.id);if(Es)throw Es;i({title:"Success",description:"Brokerage updated successfully"}),Dc(),_a()}catch(Es){console.error("Error updating brokerage:",Es),i({title:"Error",description:Es.message||"Failed to update brokerage",variant:"destructive"})}finally{us(!1)}},Vp=async(kt,Es)=>{var bn;if(!Es||typeof Es!="string"){i({title:"Error",description:"Please select a brokerage first",variant:"destructive"});return}try{const Br={userId:kt,role:"brokerage_manager",action:"add",brokerageId:Es};console.debug("[assignManagerToBrokerage] payload",Br);const{data:{session:Or}}=await q.auth.getSession(),Ma=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Or==null?void 0:Or.access_token}`},body:JSON.stringify(Br)}),Ra=await Ma.json();if(!Ma.ok&&!((bn=Ra.error)!=null&&bn.includes("duplicate")))throw new Error(Ra.error||"Failed to add role");i({title:"Success",description:"Manager assigned to brokerage"}),await _a()}catch(Br){console.error("Error assigning manager:",Br),i({title:"Error",description:Br.message||"Failed to assign manager",variant:"destructive"})}},vy=kt=>{vt(kt),bt(!0)},Jo=async()=>{if(As){on(!0);try{const kt=l.filter(Br=>Br.brokerage_id===As.id),{data:{session:Es}}=await q.auth.getSession();for(const Br of kt){const Or=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Es==null?void 0:Es.access_token}`},body:JSON.stringify({userId:Br.id})});if(!Or.ok){const Ma=await Or.json();console.error(`Failed to delete user ${Br.email}:`,Ma.error)}}const{error:bn}=await q.from("brokerages").delete().eq("id",As.id);if(bn)throw bn;i({title:"Success",description:`Brokerage "${As.name}" and ${kt.length} member(s) deleted`}),bt(!1),vt(null),_a()}catch(kt){console.error("Error deleting brokerage:",kt),i({title:"Error",description:kt.message||"Failed to delete brokerage",variant:"destructive"})}finally{on(!1)}}},il=kt=>{br(kt),On(""),dn(!0)},Hp=()=>{br(null),On(""),dn(!1)},fg=async kt=>{try{const{error:Es}=await q.from("profiles").update({brokerage_id:null}).eq("id",kt);if(Es)throw Es;i({title:"Success",description:"User removed from brokerage"}),_a()}catch(Es){console.error("Error removing user from brokerage:",Es),i({title:"Error",description:Es.message||"Failed to remove user",variant:"destructive"})}},Lh=async(kt,Es)=>{try{const{error:bn}=await q.from("profiles").update({brokerage_id:Es}).eq("id",kt);if(bn)throw bn;i({title:"Success",description:"User added to brokerage"}),_a()}catch(bn){console.error("Error adding user to brokerage:",bn),i({title:"Error",description:bn.message||"Failed to add user",variant:"destructive"})}};j.useEffect(()=>{(async()=>{var Es;if(!(rn!=null&&rn.id)){ar(null),kn([]),sn("none");return}try{const{data:bn}=await q.from("partnership_programs").select("id, name, enabled").eq("brokerage_id",rn.id).maybeSingle();if(!bn||!bn.enabled){ar(null),kn([]),sn("none");return}const{data:Br}=await q.from("partnership_packages").select("id, name, description, sort_order").eq("program_id",bn.id).order("sort_order",{ascending:!0});ar({id:bn.id,name:bn.name}),kn(Br||[]),sn(((Es=Br==null?void 0:Br[0])==null?void 0:Es.id)||"none")}catch(bn){console.error("Error loading partnership packages:",bn)}})()},[rn==null?void 0:rn.id]);const by=async()=>{if(!rn||!Hs.email||!Hs.name||!Hs.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}Zn(!0);try{const{data:{session:kt}}=await q.auth.getSession(),Es=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${kt==null?void 0:kt.access_token}`},body:JSON.stringify({...Hs,brokerage_id:rn.id,role:"user",partnershipPackageId:es&&Un!=="none"?Un:void 0})}),bn=await Es.json();if(!Es.ok)throw new Error(bn.error||"Failed to create agent");i({title:"Success",description:`Agent ${Hs.email} created successfully`}),_r({email:"",name:"",password:"",phone:""}),cr(!1),_a()}catch(kt){console.error("Error creating agent:",kt),i({title:"Error",description:kt.message||"Failed to create agent",variant:"destructive"})}finally{Zn(!1)}},qo=kt=>l.filter(Es=>Es.brokerage_id===kt),bo=kt=>{const Es=qo(kt);if(!Gn)return Es;const bn=Gn.toLowerCase();return Es.filter(Br=>Br.name.toLowerCase().includes(bn)||Br.email.toLowerCase().includes(bn))},Ex=kt=>l.filter(Es=>Es.brokerage_id!==kt),dp=l.filter(kt=>{var bn;if(T){const Br=T.toLowerCase();if(!(kt.name.toLowerCase().includes(Br)||kt.email.toLowerCase().includes(Br)||((bn=kt.brokerage_name)==null?void 0:bn.toLowerCase().includes(Br))))return!1}if($==="claimed"&&!kt.claimed||$==="unclaimed"&&kt.claimed||V!=="all"&&!kt.roles.includes(V))return!1;const Es=kt.is_trial||kt.subscription_status==="trialing";if(Z==="trial"&&!Es||Z==="non-trial"&&Es||le==="none"&&kt.brokerage_id||le!=="all"&&le!=="none"&&kt.brokerage_id!==le)return!1;if(se!=="all"){if(!kt.created_at)return!1;const Br=parseInt(se,10),Or=Date.now()-Br*24*60*60*1e3;if(new Date(kt.created_at).getTime(){var Es;return((Es=kt.name)==null?void 0:Es.toLowerCase())||""},brokerage:kt=>{var Es;return((Es=kt.brokerage_name)==null?void 0:Es.toLowerCase())||""},status:kt=>kt.claimed?"active":"pending",role:kt=>kt.roles[0]||"",last_login:kt=>kt.last_sign_in_at?new Date(kt.last_sign_in_at).getTime():null,created_at:kt=>kt.created_at?new Date(kt.created_at).getTime():null}),Mu=Jd.length,kv=R===0,_u=kv?1:Math.ceil(Mu/R),zi=kv?0:(M-1)*R,zm=kv?Mu:zi+R,Qh=Jd.slice(zi,zm),mp=kt=>{L(kt),I(1)},If=kt=>{z(kt),I(1)},Jh=(kt,Es)=>{kt(Es),I(1)},Bm=async(kt,Es)=>{be(!0);try{const bn=l.find(Ra=>Ra.id===kt);if(!bn)return;const Br=bn.trial_expires_at?new Date(bn.trial_expires_at):new Date,Or=new Date(Br.getTime()+Es*24*60*60*1e3),{error:Ma}=await q.from("profiles").update({trial_expires_at:Or.toISOString()}).eq("id",kt);if(Ma)throw Ma;i({title:"Trial Extended",description:`Trial extended by ${Es} days`}),_a()}catch(bn){console.error("Error extending trial:",bn),i({title:"Error",description:bn.message||"Failed to extend trial",variant:"destructive"})}finally{be(!1)}},j0=async kt=>{ge(!0);try{const{error:Es}=await q.from("profiles").update({is_trial:!1,trial_expires_at:null,trial_started_at:null,trial_claimed_at:null}).eq("id",kt);if(Es)throw Es;i({title:"Account Converted",description:"User has been converted to a full account"}),_a(),_y()}catch(Es){console.error("Error converting trial:",Es),i({title:"Error",description:Es.message||"Failed to convert account",variant:"destructive"})}finally{ge(!1)}},[N0,pp]=j.useState(!1),Um=async(kt,Es)=>{if(await Yi(`Revert this user to a ${Es}-day free trial? This will clear their paid/grandfathered status. Any active Stripe subscription will need to be cancelled separately.`)){pp(!0);try{const bn=new Date,Br=new Date(bn.getTime()+Es*24*60*60*1e3),{error:Or}=await q.from("profiles").update({is_trial:!0,trial_started_at:bn.toISOString(),trial_expires_at:Br.toISOString(),trial_claimed_at:bn.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",kt);if(Or)throw Or;i({title:"Reverted to Trial",description:`User is now on a ${Es}-day free trial.`}),_a()}catch(bn){console.error("Error reverting to trial:",bn),i({title:"Error",description:bn.message||"Failed to revert to trial",variant:"destructive"})}finally{pp(!1)}}},Tx=async kt=>{Go(!0);try{const{data:Es}=await q.from("agent_assistant_assignments").select("id, assistant_id, permissions").eq("agent_id",kt);if(Es&&Es.length>0){const Br=Es.map(Ma=>Ma.assistant_id),{data:Or}=await q.from("profiles").select("id, name, email").in("id",Br);Xo(Es.map(Ma=>{const Ra=Or==null?void 0:Or.find(nr=>nr.id===Ma.assistant_id);return{id:Ma.id,assistant_id:Ma.assistant_id,assistant_name:(Ra==null?void 0:Ra.name)||"Unknown",assistant_email:(Ra==null?void 0:Ra.email)||"",permissions:Ma.permissions||{}}}))}else Xo([]);const{data:bn}=await q.from("agent_assistant_assignments").select("id, agent_id, permissions").eq("assistant_id",kt);if(bn&&bn.length>0){const Br=bn.map(Ma=>Ma.agent_id),{data:Or}=await q.from("profiles").select("id, name, email").in("id",Br);Ja(bn.map(Ma=>{const Ra=Or==null?void 0:Or.find(nr=>nr.id===Ma.agent_id);return{id:Ma.id,agent_id:Ma.agent_id,agent_name:(Ra==null?void 0:Ra.name)||"Unknown",agent_email:(Ra==null?void 0:Ra.email)||"",permissions:Ma.permissions||{}}}))}else Ja([])}catch(Es){console.error("Error loading assistant data:",Es)}finally{Go(!1)}},Qg=kt=>{Oe(kt),Fe({name:kt.name,email:kt.email,brokerage_id:kt.brokerage_id||"",phone:kt.phone||""}),Qe(!0),Tx(kt.id)},_y=()=>{Oe(null),Qe(!1),Fe({name:"",email:"",brokerage_id:"",phone:""})},zd=async()=>{Me&&(await li(Me.id),_y())},ld=kt=>{Ht(Es=>{const bn=new Set(Es);return bn.has(kt)?bn.delete(kt):bn.add(kt),bn})},Gp=()=>{if(ps.size===Qh.length&&Qh.every(kt=>ps.has(kt.id))){const kt=new Set(ps);Qh.forEach(Es=>kt.delete(Es.id)),Ht(kt)}else{const kt=new Set(ps);Qh.forEach(Es=>kt.add(Es.id)),Ht(kt)}},eu=()=>{Ht(new Set)},Wp=async()=>{if(ps.size===0)return;Rs(!0);let kt=0,Es=0;try{const{data:{session:bn}}=await q.auth.getSession();for(const Br of ps)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${bn==null?void 0:bn.access_token}`},body:JSON.stringify({userId:Br,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"})})).ok?kt++:Es++}catch{Es++}i({title:"Bulk Email Complete",description:`Sent ${kt} emails${Es>0?`, ${Es} failed`:""}`}),eu()}catch(bn){i({title:"Error",description:bn.message||"Failed to send emails",variant:"destructive"})}finally{Rs(!1)}},qm=async()=>{if(ps.size===0)return;Rs(!0);let kt=0,Es=0;try{const{data:{session:bn}}=await q.auth.getSession();for(const Br of ps)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${bn==null?void 0:bn.access_token}`},body:JSON.stringify({userId:Br})})).ok?kt++:Es++}catch{Es++}i({title:"Bulk Password Reset Complete",description:`Sent ${kt} reset emails${Es>0?`, ${Es} failed`:""}`}),eu()}catch(bn){i({title:"Error",description:bn.message||"Failed to send password reset emails",variant:"destructive"})}finally{Rs(!1)}},ym=async()=>{if(ps.size===0)return;const kt=l.filter(Or=>ps.has(Or.id)).map(Or=>Or.name).slice(0,5).join(", "),Es=ps.size>5?` and ${ps.size-5} more`:"";if(!await Yi(`Are you sure you want to delete ${ps.size} users (${kt}${Es})? This action cannot be undone.`))return;Rs(!0);let bn=0,Br=0;try{const{data:{session:Or}}=await q.auth.getSession();for(const Ma of ps)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Or==null?void 0:Or.access_token}`},body:JSON.stringify({userId:Ma})})).ok?bn++:Br++}catch{Br++}i({title:"Bulk Delete Complete",description:`Deleted ${bn} users${Br>0?`, ${Br} failed`:""}`}),eu(),_a()}catch(Or){i({title:"Error",description:Or.message||"Failed to delete users",variant:"destructive"})}finally{Rs(!1)}},at=async()=>{Qr(!0);try{const{data:{session:kt}}=await q.auth.getSession(),Es=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-phone-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${kt==null?void 0:kt.access_token}`}});if(!Es.ok){const Br=await Es.json();throw new Error(Br.error||"Failed to sync phones")}const bn=await Es.json();i({title:"Phone Sync Complete",description:`Pulled ${bn.summary.pulledFromGHL} from GHL, pushed ${bn.summary.pushedToGHL} to GHL, ${bn.summary.alreadySynced} already synced`}),_a()}catch(kt){i({title:"Error",description:kt.message||"Failed to sync phones with GHL",variant:"destructive"})}finally{Qr(!1)}},Yt=async(kt,Es)=>{qr(kt);try{const{data:{session:bn}}=await q.auth.getSession(),{data:Br}=await q.from("profiles").select("phone").eq("id",kt).single(),Or=(Br==null?void 0:Br.phone)||"",Ma=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-tag-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${bn==null?void 0:bn.access_token}`},body:JSON.stringify({email:Es,action:"update",phone:Or||void 0})});if(!Ma.ok){const nr=await Ma.json();throw new Error(nr.error||"Failed to sync with GHL")}const Ra=await fetch(`https://services.leadconnectorhq.com/contacts/lookup?locationId=&email=${encodeURIComponent(Es)}`,{method:"GET",headers:{"Content-Type":"application/json"}});i({title:"Phone Synced",description:Or?`Phone ${Or} synced to GHL`:"Sync attempted - run bulk sync to pull phone from GHL"}),_a()}catch(bn){i({title:"Error",description:bn.message||"Failed to sync phone",variant:"destructive"})}finally{qr(null)}},Bs=async kt=>{await r(kt)},Zs=()=>{if(ps.size===0){i({title:"No members selected",description:"Please select members to export",variant:"destructive"});return}const kt=l.filter(nr=>ps.has(nr.id)),Es=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],bn=kt.map(nr=>[nr.name,nr.email,nr.phone||"",nr.brokerage_name||"",nr.roles.join("; "),nr.claimed?"Claimed":"Unclaimed",new Date(nr.created_at).toLocaleDateString()]),Br=[Es.join(","),...bn.map(nr=>nr.map(Va=>`"${(Va||"").replace(/"/g,'""')}"`).join(","))].join(` `),Or=new Blob([Br],{type:"text/csv"}),Ma=URL.createObjectURL(Or),Ra=document.createElement("a");Ra.href=Ma,Ra.download=`members-export-${new Date().toISOString().split("T")[0]}.csv`,Ra.click(),URL.revokeObjectURL(Ma),i({title:"Export complete",description:`Exported ${kt.length} member(s)`})},Sn=()=>{if(dp.length===0){i({title:"No members to export",description:"Adjust filters to include at least one member",variant:"destructive"});return}const kt=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],Es=dp.map(nr=>[nr.name,nr.email,nr.phone||"",nr.brokerage_name||"",nr.roles.join("; "),nr.claimed?"Claimed":"Unclaimed",nr.created_at?new Date(nr.created_at).toLocaleDateString():""]),bn=[kt.join(","),...Es.map(nr=>nr.map(Va=>`"${(Va||"").replace(/"/g,'""')}"`).join(","))].join(` `),Br=new Blob([bn],{type:"text/csv"}),Or=URL.createObjectURL(Br),Ma=document.createElement("a"),Ra=se!=="all"?`-last-${se}days`:"";Ma.href=Or,Ma.download=`members-export${Ra}-${new Date().toISOString().split("T")[0]}.csv`,Ma.click(),URL.revokeObjectURL(Or),i({title:"Export complete",description:`Exported ${dp.length} member(s)`})};return f?e.jsx(qs,{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(qs,{title:"Members",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{title:"Member Management",description:"Manage users, roles, and permissions",children:e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>s("/admin/unassigned-members"),className:"gap-2",children:[e.jsx(tc,{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(U,{size:"sm",variant:"outline",onClick:at,disabled:zn,children:[zn?e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(ba,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:zn?"Syncing...":"Sync Phones with GHL"}),e.jsx("span",{className:"sm:hidden",children:zn?"Syncing...":"Sync GHL"})]}),e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>Ar(!0),children:[e.jsx(Qk,{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:S,onOpenChange:A,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{size:"sm",children:[e.jsx(zl,{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(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{htmlFor:"name",children:"Name"}),e.jsx(xe,{id:"name",placeholder:"John Doe",value:b.name,onChange:kt=>N({...b,name:kt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"email",children:"Email"}),e.jsx(xe,{id:"email",type:"email",placeholder:"john@example.com",value:b.email,onChange:kt=>N({...b,email:kt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"password",children:"Password"}),e.jsx(xe,{id:"password",type:"password",placeholder:"Min 6 characters",value:b.password,onChange:kt=>N({...b,password:kt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(xe,{id:"phone",type:"tel",placeholder:"555-123-4567",value:b.phone,onChange:kt=>N({...b,phone:kt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"brokerage",children:["Brokerage",b.role==="brokerage_manager"?" (required)":""]}),e.jsxs(Ns,{value:b.brokerage_id||"none",onValueChange:kt=>N({...b,brokerage_id:kt==="none"?"":kt}),children:[e.jsx(ws,{id:"brokerage",children:e.jsx(ks,{placeholder:b.role==="brokerage_manager"?"Select brokerage":"Select brokerage (optional)"})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"None"}),u.map(kt=>e.jsx(et,{value:kt.id,children:kt.name},kt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"role",children:"Role"}),e.jsxs(Ns,{value:b.role,onValueChange:kt=>N({...b,role:kt}),children:[e.jsx(ws,{id:"role",children:e.jsx(ks,{placeholder:"Select role"})}),e.jsxs(js,{children:[e.jsx(et,{value:"user",children:"User"}),e.jsx(et,{value:"moderator",children:"Moderator"}),e.jsx(et,{value:"brokerage_manager",children:"Brokerage Manager"}),e.jsx(et,{value:"admin",children:"Admin"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"trial_days",children:"Trial Period (optional)"}),e.jsxs(Ns,{value:b.trial_days||"none",onValueChange:kt=>N({...b,trial_days:kt==="none"?"":kt}),children:[e.jsx(ws,{id:"trial_days",children:e.jsx(ks,{placeholder:"No trial (full access)"})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"No trial (full access)"}),e.jsx(et,{value:"7",children:"7-day trial"}),e.jsx(et,{value:"30",children:"30-day trial"}),e.jsx(et,{value:"60",children:"60-day trial"}),e.jsx(et,{value:"90",children:"90-day trial"}),e.jsx(et,{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(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>A(!1),children:"Cancel"}),e.jsx(U,{onClick:Gr,disabled:y,children:y?"Creating...":"Create User"})]})]})]})]})]}),e.jsxs(oa,{defaultValue:new URLSearchParams(window.location.search).get("tab")||"members",className:"space-y-6",children:[e.jsxs(la,{children:[e.jsx(Kt,{value:"members",children:"Members"}),e.jsx(Kt,{value:"brokerages",children:"Brokerages"}),e.jsx(Kt,{value:"teams",children:"Teams"}),e.jsx(Kt,{value:"trials",children:"Trial Users"}),e.jsx(Kt,{value:"access",children:"Access Matrix"}),e.jsx(Kt,{value:"celebrations",children:"Celebrations"}),e.jsx(Kt,{value:"deletions",children:"Deletion Log"})]}),e.jsxs(Zt,{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(Fr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search members...",value:T,onChange:kt=>mp(kt.target.value),className:"pl-10 h-9"})]}),e.jsxs(Ns,{value:$,onValueChange:kt=>Jh(H,kt),children:[e.jsx(ws,{className:"w-[130px] h-9",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Status"}),e.jsx(et,{value:"claimed",children:"Active"}),e.jsx(et,{value:"unclaimed",children:"Pending"})]})]}),e.jsxs(Ns,{value:V,onValueChange:kt=>Jh(K,kt),children:[e.jsx(ws,{className:"w-[130px] h-9",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Roles"}),e.jsx(et,{value:"admin",children:"Admin"}),e.jsx(et,{value:"brokerage_manager",children:"Manager"}),e.jsx(et,{value:"assistant",children:"Assistant"}),e.jsx(et,{value:"user",children:"User"})]})]}),e.jsxs(Ns,{value:Z,onValueChange:kt=>Jh(Q,kt),children:[e.jsx(ws,{className:"w-[130px] h-9",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Users"}),e.jsx(et,{value:"trial",children:"Trial Only"}),e.jsx(et,{value:"non-trial",children:"Full Only"})]})]}),e.jsxs(Ns,{value:le,onValueChange:kt=>Jh(ue,kt),children:[e.jsx(ws,{className:"w-[150px] h-9",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Brokerages"}),e.jsx(et,{value:"none",children:"No Brokerage"}),u.map(kt=>e.jsx(et,{value:kt.id,children:kt.name},kt.id))]})]}),e.jsxs(Ns,{value:se,onValueChange:kt=>Jh(ne,kt),children:[e.jsx(ws,{className:"w-[150px] h-9",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"Any Join Date"}),e.jsx(et,{value:"30",children:"Joined Last 30 Days"}),e.jsx(et,{value:"60",children:"Joined Last 60 Days"}),e.jsx(et,{value:"90",children:"Joined Last 90 Days"})]})]}),e.jsxs(U,{size:"sm",variant:"outline",className:"h-9",onClick:Sn,title:"Export currently filtered members to CSV",children:[e.jsx(pi,{className:"h-4 w-4 mr-1"}),"Export Filtered"]}),(T||$!=="all"||V!=="all"||Z!=="all"||le!=="all"||se!=="all")&&e.jsxs(U,{variant:"ghost",size:"sm",className:"h-9",onClick:()=>{L(""),H("all"),K("all"),Q("all"),ue("all"),ne("all"),I(1)},children:[e.jsx(er,{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:kv?`Showing all ${Mu} members`:`Showing ${zi+1}-${Math.min(zm,Mu)} of ${Mu} members`}),e.jsxs(Ns,{value:R.toString(),onValueChange:kt=>If(Number(kt)),children:[e.jsx(ws,{className:"h-9 w-[110px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"50",children:"50 / page"}),e.jsx(et,{value:"100",children:"100 / page"}),e.jsx(et,{value:"250",children:"250 / page"}),e.jsx(et,{value:"0",children:"All"})]})]})]})]}),ps.size>0&&e.jsxs("div",{className:"flex flex-col gap-2 p-3 bg-primary/10 border border-primary/20 rounded-lg",children:[Qh.length>0&&Qh.every(kt=>ps.has(kt.id))&&Jd.length>ps.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 ",ps.size," on this page are selected."]}),e.jsxs(U,{size:"sm",variant:"link",className:"h-auto p-0 text-primary",onClick:()=>Ht(new Set(Jd.map(kt=>kt.id))),children:["Select all ",Jd.length," filtered members"]})]}),Jd.length>0&&ps.size===Jd.length&&e.jsxs("div",{className:"px-1 text-sm text-muted-foreground",children:["All ",Jd.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(t4,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm font-medium",children:[ps.size," selected"]})]}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(U,{size:"sm",variant:"outline",onClick:Wp,disabled:Xs,children:[Xs?e.jsx(Et,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(ln,{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(U,{size:"sm",variant:"outline",onClick:qm,disabled:Xs,children:[Xs?e.jsx(Et,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(C_,{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(U,{size:"sm",variant:"outline",onClick:()=>ce(!0),disabled:Xs,className:"bg-primary/5 border-primary/30 text-primary hover:bg-primary/10",children:[e.jsx(Xk,{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(U,{size:"sm",variant:"outline",onClick:Zs,children:[e.jsx(pi,{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(U,{size:"sm",variant:"destructive",onClick:ym,disabled:Xs,children:[Xs?e.jsx(Et,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(In,{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(U,{size:"sm",variant:"ghost",onClick:eu,disabled:Xs,children:e.jsx(er,{className:"h-4 w-4"})})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Lt,{className:"w-[50px]",children:e.jsx(xi,{checked:Qh.length>0&&Qh.every(kt=>ps.has(kt.id)),onCheckedChange:Gp,"aria-label":"Select all on page"})}),e.jsx(Sh,{sortKey:"name",currentSortKey:up,currentDirection:gg,onSort:Vl,children:"Name"}),e.jsx(Sh,{sortKey:"brokerage",currentSortKey:up,currentDirection:gg,onSort:Vl,children:"Brokerage"}),e.jsx(Sh,{sortKey:"status",currentSortKey:up,currentDirection:gg,onSort:Vl,children:"Status"}),e.jsx(Sh,{sortKey:"role",currentSortKey:up,currentDirection:gg,onSort:Vl,children:"Role"}),e.jsx(Sh,{sortKey:"last_login",currentSortKey:up,currentDirection:gg,onSort:Vl,children:"Last Login"}),e.jsx(Sh,{sortKey:"created_at",currentSortKey:up,currentDirection:gg,onSort:Vl,children:"Member Since"}),e.jsx(Lt,{className:"w-[100px]"})]})}),e.jsx(Xa,{children:Qh.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:8,className:"text-center py-12 text-muted-foreground",children:"No members found"})}):Qh.map(kt=>e.jsxs(gn,{className:`hover:bg-muted/30 ${ps.has(kt.id)?"bg-primary/5":""}`,children:[e.jsx(gt,{children:e.jsx(xi,{checked:ps.has(kt.id),onCheckedChange:()=>ld(kt.id),"aria-label":`Select ${kt.name}`})}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("button",{onClick:()=>Qg(kt),className:"text-primary hover:underline font-medium text-left",children:kt.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:kt.email})]})}),e.jsx(gt,{className:"text-muted-foreground",children:kt.brokerage_name||"—"}),e.jsx(gt,{children:e.jsx("div",{className:"flex flex-col",children:(()=>{const Es=kt.trial_expires_at||kt.subscription_end_date;if((kt.is_trial||kt.subscription_status==="trialing")&&Es){const Br=Math.ceil((new Date(Es).getTime()-Date.now())/864e5),Or=Br<=0,Ma=Br<=3;return e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Be,{variant:"outline",className:Mt("w-fit",Or?"border-destructive text-destructive":Ma?"border-amber-500 text-amber-600":"border-violet-300 text-violet-700 bg-violet-50"),children:Or?"Trial Expired":`Trial · ${Br}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 Ra="https://dashboard.relevelup.com/upgrade";try{await navigator.clipboard.writeText(Ra),i({title:"Upgrade link copied",description:Ra})}catch{window.prompt("Copy this upgrade link:",Ra)}},children:e.jsx(Pa,{className:"h-3.5 w-3.5"})})]})}return e.jsx(Be,{variant:kt.claimed?"default":"secondary",className:kt.claimed?"bg-primary text-primary-foreground w-fit":"w-fit",children:kt.claimed?"Active":"Pending"})})()})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex flex-col",children:[kt.roles.length>0?e.jsx("span",{className:"text-sm capitalize",children:kt.roles[0]}):e.jsx("span",{className:"text-muted-foreground",children:"—"}),kt.roles.includes("assistant")&&hi[kt.id]&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["→ ",hi[kt.id].agent_name||hi[kt.id].agent_email]})]})}),e.jsx(gt,{className:"text-muted-foreground",children:kt.last_sign_in_at?new Date(kt.last_sign_in_at).toLocaleDateString():"—"}),e.jsx(gt,{className:"text-muted-foreground",children:kt.created_at?new Date(kt.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"—"}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsx(U,{size:"icon",variant:"ghost",className:"h-8 w-8 text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",onClick:()=>{Fa(kt),Jr(!0)},title:"Send celebration",children:e.jsx(Wg,{className:"h-4 w-4"})}),e.jsx(U,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Qg(kt),title:"Edit member",children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Yt(kt.id,kt.email),disabled:ma===kt.id,title:"Sync phone with GHL",children:ma===kt.id?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(ba,{className:"h-4 w-4"})}),e.jsx(U,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Eo(kt.id),title:"Resend welcome email",children:e.jsx(ln,{className:"h-4 w-4"})}),e.jsx(U,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>gl(kt.email,kt.name),title:"Send password reset",children:e.jsx(SA,{className:"h-4 w-4"})}),e.jsx(U,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>Bs(kt.id),disabled:a||kt.id===(t==null?void 0:t.id),title:kt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${kt.name}`,children:a?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(EM,{className:"h-4 w-4"})}),e.jsx(U,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>ds(kt.id,kt.name),title:"Delete user",children:e.jsx(In,{className:"h-4 w-4"})})]})})]},kt.id))})]})}),_u>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 ",M," of ",_u]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(U,{variant:"outline",size:"sm",onClick:()=>I(1),disabled:M===1,children:"First"}),e.jsx(U,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>I(kt=>Math.max(1,kt-1)),disabled:M===1,children:e.jsx(rd,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,_u)},(kt,Es)=>{let bn;return _u<=5||M<=3?bn=Es+1:M>=_u-2?bn=_u-4+Es:bn=M-2+Es,e.jsx(U,{variant:M===bn?"default":"outline",size:"sm",className:"h-8 w-8 p-0",onClick:()=>I(bn),children:bn},bn)})}),e.jsx(U,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>I(kt=>Math.min(_u,kt+1)),disabled:M===_u,children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx(U,{variant:"outline",size:"sm",onClick:()=>I(_u),disabled:M===_u,children:"Last"})]})]})]}),e.jsx(zs,{open:Se,onOpenChange:Qe,children:e.jsxs(Ds,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Edit Member"}),e.jsx(Pr,{children:"Update member details, roles, and app access"})]}),Me&&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(te,{htmlFor:"edit-name",children:"Name"}),e.jsx(xe,{id:"edit-name",value:Ae.name,onChange:kt=>Fe({...Ae,name:kt.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"edit-email",children:"Email"}),e.jsx(xe,{id:"edit-email",type:"email",value:Ae.email,onChange:kt=>Fe({...Ae,email:kt.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(te,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(xe,{id:"edit-phone",type:"tel",value:Ae.phone,onChange:kt=>Fe({...Ae,phone:kt.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"edit-brokerage",children:"Brokerage"}),e.jsxs(Ns,{value:Ae.brokerage_id||"none",onValueChange:kt=>Fe({...Ae,brokerage_id:kt==="none"?"":kt}),children:[e.jsx(ws,{id:"edit-brokerage",children:e.jsx(ks,{placeholder:"Select brokerage"})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"None"}),u.map(kt=>e.jsx(et,{value:kt.id,children:kt.name},kt.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:[Me.roles.map(kt=>e.jsxs(Be,{variant:"default",className:"gap-1",children:[e.jsx(Im,{className:"h-3 w-3"}),kt,kt==="brokerage_manager"?e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(manage in Brokerages tab)"}):e.jsx("button",{onClick:()=>ji(Me.id,kt,"remove"),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove role",children:e.jsx(er,{className:"h-3 w-3"})})]},kt)),Me.roles.length===0&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"No roles assigned"})]}),e.jsxs(Ns,{onValueChange:kt=>ji(Me.id,kt,"add"),children:[e.jsx(ws,{className:"w-[200px]",children:e.jsx(ks,{placeholder:"Add role..."})}),e.jsxs(js,{children:[!Me.roles.includes("admin")&&e.jsx(et,{value:"admin",children:"Admin"}),!Me.roles.includes("user")&&e.jsx(et,{value:"user",children:"User"})]})]}),!Me.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"})]}),(Fo.length>0||Vi.length>0||Me.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(Bn,{className:"h-4 w-4"}),"Assistant Relationships"]}),Co?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Et,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):e.jsxs("div",{className:"space-y-3",children:[Fo.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:"}),Fo.map(kt=>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:kt.assistant_name}),e.jsx(Be,{variant:"outline",className:"text-xs",children:"Assistant"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:kt.assistant_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(kt.permissions).filter(([,Es])=>Es).map(([Es])=>e.jsx(Be,{variant:"secondary",className:"text-[10px] capitalize",children:Es},Es))})]},kt.id))]}),Vi.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:"}),Vi.map(kt=>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:kt.agent_name}),e.jsx(Be,{variant:"outline",className:"text-xs",children:"Agent"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:kt.agent_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(kt.permissions).filter(([,Es])=>Es).map(([Es])=>e.jsx(Be,{variant:"secondary",className:"text-[10px] capitalize",children:Es},Es))})]},kt.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(kt=>{const Es=ya(Me.tags,kt.required_tags),bn=`${Me.id}-${kt.id}`,Br=Ne===bn,Or=kt.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:kt.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:kt.name}),Or&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Available to all members"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:Br?e.jsx(Et,{className:"h-4 w-4 animate-spin text-muted-foreground"}):Or?e.jsx(Be,{variant:"secondary",className:"text-xs",children:"Always On"}):e.jsx(wn,{checked:Es,onCheckedChange:()=>Wi(Me.id,kt,Es)})})]},kt.id)})})]}),(Me.is_trial||Me.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(Yr,{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:[Me.trial_expires_at&&e.jsx(tyt,{expiresAt:Me.trial_expires_at}),!Me.trial_expires_at&&Me.subscription_status==="trialing"&&Me.subscription_end_date&&e.jsx(tyt,{expiresAt:Me.subscription_end_date})]}),(Me.trial_expires_at||Me.subscription_end_date)&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Expires: ",new Date(Me.trial_expires_at||Me.subscription_end_date).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>Bm(Me.id,7),disabled:je,children:[e.jsx(sv,{className:"h-4 w-4 mr-1"}),"+7 Days"]}),e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>Bm(Me.id,14),disabled:je,children:[e.jsx(sv,{className:"h-4 w-4 mr-1"}),"+14 Days"]}),e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>Bm(Me.id,30),disabled:je,children:[e.jsx(sv,{className:"h-4 w-4 mr-1"}),"+30 Days"]}),e.jsxs(U,{size:"sm",variant:"default",onClick:()=>j0(Me.id),disabled:he,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(tN,{className:"h-4 w-4 mr-1"}),"Convert to Full Account"]})]}),Me.trial_started_at&&e.jsxs("div",{className:"mt-3 text-xs text-muted-foreground",children:["Trial started: ",new Date(Me.trial_started_at).toLocaleDateString(),Me.trial_claimed_at&&e.jsxs("span",{children:[" • Claimed: ",new Date(Me.trial_claimed_at).toLocaleDateString()]})]})]})]}),!(Me.is_trial||Me.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(Yr,{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(kt=>e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>Um(Me.id,kt),disabled:N0,children:[e.jsx(sv,{className:"h-4 w-4 mr-1"}),kt,"-day trial"]},kt))})]})]}),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:[Me.email_confirmed_at&&e.jsxs("div",{children:["Claimed: ",new Date(Me.email_confirmed_at).toLocaleString()]}),Me.last_sign_in_at&&e.jsxs("div",{children:["Last login: ",new Date(Me.last_sign_in_at).toLocaleString()]}),e.jsxs("div",{children:["Created: ",new Date(Me.created_at).toLocaleString()]})]})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:_y,children:"Cancel"}),e.jsx(U,{onClick:zd,children:"Save Changes"})]})]})}),e.jsxs(Zt,{value:"access",children:[c.length===0?e.jsx(we,{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(U,{onClick:()=>s("/admin/apps"),children:"Configure Apps"})]})}):e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Member Access Matrix"}),e.jsx(Jn,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search agents by name or email...",value:T,onChange:kt=>{L(kt.target.value),I(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(kt=>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:kt.icon}),e.jsx("span",{className:"text-sm",children:kt.name})]})},kt.id))]})}),e.jsxs("tbody",{children:[Qh.map(kt=>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:kt.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:kt.email})]})}),c.map(Es=>{const bn=ya(kt.tags,Es.required_tags),Br=`${kt.id}-${Es.id}`,Or=Ne===Br;return e.jsx("td",{className:"p-4 text-center",children:e.jsx("div",{className:"flex items-center justify-center",children:Or?e.jsx(Et,{className:"h-5 w-5 animate-spin text-muted-foreground"}):e.jsx(wn,{checked:bn,onCheckedChange:()=>Wi(kt.id,Es,bn),disabled:Es.required_tags.length===0})})},Es.id)})]},kt.id)),Qh.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"})})]})]})}),_u>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 ",zi+1,"-",Math.min(zm,Mu)," of ",Mu," • Page ",M," of ",_u]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(U,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>I(kt=>Math.max(1,kt-1)),disabled:M===1,children:e.jsx(rd,{className:"h-4 w-4"})}),e.jsx(U,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>I(kt=>Math.min(_u,kt+1)),disabled:M===_u,children:e.jsx(gi,{className:"h-4 w-4"})})]})]})]})]}),e.jsx("div",{className:"mt-6",children:e.jsx(U,{variant:"outline",onClick:()=>s("/admin/apps"),children:"Manage Apps"})})]}),e.jsxs(Zt,{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(Fr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search brokerages...",value:fs,onChange:kt=>ot(kt.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[u.filter(kt=>kt.name.toLowerCase().includes(fs.toLowerCase())).length," of ",u.length," brokerages"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>{const kt=[];for(const Ra of u){const nr=m[Ra.id]??[];for(const Va of nr){const mi=l.find(ol=>ol.id===Va);if(mi){const ol=(mi.name||"").trim().split(/\s+/),vc=ol[0]||"",ao=ol.slice(1).join(" ")||"";kt.push({firstName:vc,lastName:ao,email:mi.email,brokerageName:Ra.name})}}}if(kt.length===0){i({title:"No managers found to export"});return}const bn=[["First Name","Last Name","Email","Brokerage Name"].join(","),...kt.map(Ra=>[Ra.firstName,Ra.lastName,Ra.email,Ra.brokerageName].map(nr=>`"${(nr||"").replace(/"/g,'""')}"`).join(","))].join(` `),Br=new Blob([bn],{type:"text/csv"}),Or=URL.createObjectURL(Br),Ma=document.createElement("a");Ma.href=Or,Ma.download=`brokerage-managers-${new Date().toISOString().slice(0,10)}.csv`,Ma.click(),URL.revokeObjectURL(Or),i({title:`Exported ${kt.length} managers`})},children:[e.jsx(pi,{className:"mr-2 h-4 w-4"}),"Export Managers"]}),e.jsxs(zs,{open:Ve,onOpenChange:qe,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{size:"sm",children:[e.jsx(_i,{className:"mr-2 h-4 w-4"}),"Add Brokerage"]})}),e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(xe,{id:"brokerage-name",placeholder:"Enter brokerage name",value:Ze,onChange:kt=>Ue(kt.target.value),maxLength:100})]})}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>qe(!1),children:"Cancel"}),e.jsx(U,{onClick:wi,disabled:Ye,children:Ye?"Creating...":"Create Brokerage"})]})]})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Lt,{className:"font-semibold",children:"Brokerage Name"}),e.jsx(Lt,{className:"font-semibold",children:"Manager(s)"}),e.jsx(Lt,{className:"font-semibold",children:"Agents"}),e.jsx(Lt,{className:"w-[150px]"})]})}),e.jsx(Xa,{children:(()=>{const kt=u.filter(Es=>Es.name.toLowerCase().includes(fs.toLowerCase()));return kt.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:4,className:"text-center py-12 text-muted-foreground",children:fs?"No brokerages match your search":"No brokerages found"})}):kt.map(Es=>{const bn=l.filter(Ra=>Ra.brokerage_id===Es.id),Or=(m[Es.id]??[]).map(Ra=>l.find(nr=>nr.id===Ra)).filter(Boolean),Ma=bn.length;return e.jsxs(gn,{className:"hover:bg-muted/30",children:[e.jsx(gt,{children:e.jsx("button",{onClick:()=>di(Es),className:"text-primary hover:underline font-medium",children:Es.name})}),e.jsx(gt,{children:Or.length>0?e.jsx("div",{className:"flex flex-wrap gap-1",children:Or.map(Ra=>e.jsx(Be,{variant:"secondary",className:"text-xs",children:Ra.name},Ra.id))}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"No manager"})}),e.jsxs(gt,{children:[Ma," member",Ma!==1?"s":""]}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsxs(U,{size:"sm",variant:"outline",className:"h-8",onClick:()=>il(Es),children:[e.jsx(Bn,{className:"h-4 w-4 mr-1"}),"Manage"]}),e.jsx(U,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>di(Es),title:"Edit brokerage",children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>vy(Es),title:"Delete brokerage",children:e.jsx(In,{className:"h-4 w-4"})})]})})]},Es.id)})})()})]})}),e.jsx(zs,{open:He,onOpenChange:tt,children:e.jsxs(Ds,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Edit Brokerage"}),e.jsx(Pr,{children:"Update brokerage details and manage managers"})]}),pt&&e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"edit-brokerage-name",children:"Brokerage Name"}),e.jsx(xe,{id:"edit-brokerage-name",value:qt,onChange:kt=>Ut(kt.target.value),maxLength:100})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(te,{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 Es=(m[pt.id]??[]).map(bn=>l.find(Br=>Br.id===bn)).filter(Boolean);return Es.length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No managers assigned"}):Es.map(bn=>e.jsxs(Be,{variant:"default",className:"gap-1",children:[e.jsx(Im,{className:"h-3 w-3"}),bn.name,e.jsx("button",{onClick:()=>ji(bn.id,"brokerage_manager","remove",pt.id),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove manager from this brokerage",children:e.jsx(er,{className:"h-3 w-3"})})]},bn.id))})()}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-sm text-muted-foreground",children:"Assign manager from existing members:"}),e.jsxs(md,{open:mt,onOpenChange:Nt,children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{variant:"outline",role:"combobox","aria-expanded":mt,className:"w-full justify-between",children:["Search for a member...",e.jsx(Fr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(id,{className:"w-full p-0",align:"start",children:e.jsxs(pj,{children:[e.jsx(fj,{placeholder:"Search by name or email..."}),e.jsxs(gj,{className:"max-h-[200px]",children:[e.jsx(xj,{children:"No members found."}),e.jsx(I_,{children:(()=>{const kt=new Set(m[pt.id]??[]);return l.filter(Es=>!kt.has(Es.id)&&(n||Es.brokerage_id===pt.id)).map(Es=>e.jsxs(e1,{value:`${Es.name} ${Es.email}`,onSelect:()=>{Vp(Es.id,pt.id),Nt(!1)},children:[Es.name," (",Es.email,")"]},Es.id))})()})]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Members in this Brokerage"}),e.jsx("div",{className:"max-h-32 overflow-y-auto border rounded p-2",children:l.filter(kt=>kt.brokerage_id===pt.id).length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No members"}):l.filter(kt=>kt.brokerage_id===pt.id).map(kt=>e.jsxs("div",{className:"text-sm py-1 flex items-center justify-between",children:[e.jsx("span",{children:kt.name}),kt.roles.includes("brokerage_manager")&&e.jsx(Be,{variant:"outline",className:"text-xs",children:"Manager"})]},kt.id))})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:Dc,children:"Cancel"}),e.jsx(U,{onClick:fd,disabled:Wt,children:Wt?"Saving...":"Save Changes"})]})]})}),e.jsx(zs,{open:zt,onOpenChange:bt,children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{className:"text-destructive",children:"Delete Brokerage"}),e.jsxs(Pr,{children:['Are you sure you want to delete "',As==null?void 0:As.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 "',As==null?void 0:As.name,'"']}),e.jsxs("li",{children:["All ",l.filter(kt=>kt.brokerage_id===(As==null?void 0:As.id)).length," member(s) assigned to this brokerage"]}),e.jsx("li",{children:"All their data, roles, and access"})]})]})}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>bt(!1),children:"Cancel"}),e.jsx(U,{variant:"destructive",onClick:Jo,disabled:Ws,children:Ws?"Deleting...":"Yes, Delete Brokerage"})]})]})}),e.jsx(zs,{open:Ms,onOpenChange:dn,children:e.jsxs(Ds,{className:"max-w-4xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(_i,{className:"h-5 w-5"}),"Manage ",rn==null?void 0:rn.name]}),e.jsx(Pr,{children:"Add, remove, or manage users in this brokerage"})]}),rn&&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(Fr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search members...",value:Gn,onChange:kt=>On(kt.target.value),className:"pl-10 h-9"})]}),e.jsxs(zs,{open:Rr,onOpenChange:cr,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{size:"sm",children:[e.jsx(zl,{className:"h-4 w-4 mr-1"}),"Add New Agent"]})}),e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Add New Agent"}),e.jsxs(Pr,{children:["Create a new agent for ",rn.name]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"agent-name",children:"Name"}),e.jsx(xe,{id:"agent-name",placeholder:"John Doe",value:Hs.name,onChange:kt=>_r({...Hs,name:kt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"agent-email",children:"Email"}),e.jsx(xe,{id:"agent-email",type:"email",placeholder:"john@example.com",value:Hs.email,onChange:kt=>_r({...Hs,email:kt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"agent-password",children:"Password"}),e.jsx(xe,{id:"agent-password",type:"password",placeholder:"Min 6 characters",value:Hs.password,onChange:kt=>_r({...Hs,password:kt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"agent-phone",children:"Phone (optional)"}),e.jsx(xe,{id:"agent-phone",type:"tel",placeholder:"555-123-4567",value:Hs.phone,onChange:kt=>_r({...Hs,phone:kt.target.value})})]}),es&&Hn.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"agent-package",children:[es.name," Package"]}),e.jsxs(Ns,{value:Un,onValueChange:sn,children:[e.jsx(ws,{id:"agent-package",children:e.jsx(ks,{placeholder:"Select a package"})}),e.jsxs(js,{children:[Hn.map(kt=>e.jsx(et,{value:kt.id,children:kt.name},kt.id)),e.jsx(et,{value:"none",children:"No package (full access)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Un==="none"?"Agent gets unrestricted access; welcome email has no package block.":((Dr=Hn.find(kt=>kt.id===Un))==null?void 0:Dr.description)||"Entitlements and the welcome email reflect this package."})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>cr(!1),children:"Cancel"}),e.jsx(U,{onClick:by,disabled:nn,children:nn?"Creating...":"Create Agent"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(te,{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Add existing user:"}),e.jsxs(md,{open:Pt,onOpenChange:ts,children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{variant:"outline",role:"combobox","aria-expanded":Pt,className:"w-[300px] justify-between",children:["Select a user to add...",e.jsx(Fr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(id,{className:"w-[300px] p-0",align:"start",children:e.jsxs(pj,{children:[e.jsx(fj,{placeholder:"Search users...",value:ls,onValueChange:Is}),e.jsxs(gj,{children:[e.jsx(xj,{children:"No users found."}),e.jsx(I_,{children:Ex(rn.id).filter(kt=>ls===""||kt.name.toLowerCase().includes(ls.toLowerCase())||kt.email.toLowerCase().includes(ls.toLowerCase())).map(kt=>e.jsxs(e1,{value:`${kt.name} ${kt.email}`,onSelect:()=>{Lh(kt.id,rn.id),ts(!1),Is("")},children:[kt.name," (",kt.email,")"]},kt.id))})]})]})})]})]}),e.jsx("div",{className:"flex-1 overflow-auto border rounded-lg",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Lt,{className:"font-semibold",children:"Name"}),e.jsx(Lt,{className:"font-semibold",children:"Email"}),e.jsx(Lt,{className:"font-semibold",children:"Status"}),e.jsx(Lt,{className:"font-semibold",children:"Role"}),e.jsx(Lt,{className:"w-[120px]"})]})}),e.jsx(Xa,{children:bo(rn.id).length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:Gn?"No matching members found":"No members in this brokerage"})}):bo(rn.id).map(kt=>e.jsxs(gn,{className:"hover:bg-muted/30",children:[e.jsx(gt,{className:"font-medium",children:kt.name}),e.jsx(gt,{className:"text-muted-foreground",children:kt.email}),e.jsx(gt,{children:kt.claimed?e.jsx(Be,{variant:"default",className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active"}):e.jsx(Be,{variant:"secondary",children:"Pending"})}),e.jsx(gt,{children:kt.roles.includes("brokerage_manager")?e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(Im,{className:"h-3 w-3"}),"Manager"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"Agent"})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[!kt.claimed&&e.jsx(U,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Eo(kt.id),title:"Resend welcome email",children:e.jsx(ln,{className:"h-4 w-4"})}),e.jsx(U,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>fg(kt.id),title:"Remove from brokerage",children:e.jsx(er,{className:"h-4 w-4"})}),e.jsx(U,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>Bs(kt.id),disabled:a||kt.id===(t==null?void 0:t.id),title:kt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${kt.name}`,children:a?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(EM,{className:"h-4 w-4"})}),e.jsx(U,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>ds(kt.id,kt.name),title:"Delete user",children:e.jsx(In,{className:"h-4 w-4"})})]})})]},kt.id))})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[qo(rn.id).length," total member",qo(rn.id).length!==1?"s":""," •",qo(rn.id).filter(kt=>kt.roles.includes("brokerage_manager")).length," manager",qo(rn.id).filter(kt=>kt.roles.includes("brokerage_manager")).length!==1?"s":""]})]}),e.jsx(Mr,{children:e.jsx(U,{variant:"outline",onClick:Hp,children:"Close"})})]})})]}),e.jsx(Zt,{value:"teams",children:e.jsx(wrn,{})}),e.jsx(Zt,{value:"trials",children:e.jsx(orn,{})}),e.jsx(Zt,{value:"celebrations",children:e.jsx(irn,{})}),e.jsx(Zt,{value:"deletions",children:e.jsx(crn,{})})]})]}),e.jsx(nqt,{open:un,onOpenChange:Ar,brokerages:u,onSuccess:_a}),ha&&e.jsx(rqt,{open:Zr,onOpenChange:kt=>{Jr(kt),kt||Fa(null)},userId:ha.id,userName:ha.name}),e.jsx(jrn,{open:ie,onOpenChange:ce,recipients:l.filter(kt=>ps.has(kt.id)).map(kt=>({id:kt.id,name:kt.name,email:kt.email}))})]})};function krn(){const{toast:s}=Ai(),t=Qt(),[n,r]=j.useState(""),[a,i]=j.useState(new Set),[l,o]=j.useState({}),[c,d]=j.useState({}),[u,h]=j.useState(""),[m,p]=j.useState(!1),{data:f=[],isLoading:x}=ct({queryKey:["unassigned-members"],queryFn:async()=>{const{data:M,error:I}=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(I)throw I;return M||[]}}),{data:y=[]}=ct({queryKey:["brokerages-all"],queryFn:async()=>{const{data:M,error:I}=await q.from("brokerages").select("id, name").order("name");if(I)throw I;return M||[]}}),v=j.useMemo(()=>{const M=n.toLowerCase().trim();return M?f.filter(I=>(I.name||"").toLowerCase().includes(M)||(I.email||"").toLowerCase().includes(M)||(I.phone||"").toLowerCase().includes(M)):f},[f,n]),b=j.useMemo(()=>{var I;const M=new Map;for(const R of f){const z=(I=(R.email||"").split("@")[1])==null?void 0:I.toLowerCase();z&&(["gmail.com","yahoo.com","hotmail.com","outlook.com","icloud.com","aol.com","me.com","comcast.net"].includes(z)||M.set(z,(M.get(z)||0)+1))}return Array.from(M.entries()).sort((R,z)=>z[1]-R[1]).slice(0,10)},[f]),N=M=>{i(I=>{const R=new Set(I);return R.has(M)?R.delete(M):R.add(M),R})},S=()=>{a.size===v.length?i(new Set):i(new Set(v.map(M=>M.id)))},A=async(M,I)=>{if(I){d(R=>({...R,[M]:!0}));try{const{data:R,error:z}=await q.functions.invoke("assign-brokerage",{body:{userId:M,brokerageId:I}});if(z)throw z;if(R!=null&&R.error)throw new Error(R.error);s({title:"Assigned",description:"Member added to brokerage."}),t.invalidateQueries({queryKey:["unassigned-members"]}),i($=>{const H=new Set($);return H.delete(M),H})}catch(R){s({title:"Failed",description:R.message,variant:"destructive"})}finally{d(R=>({...R,[M]:!1}))}}},T=async()=>{if(!u||a.size===0)return;p(!0);let M=0,I=0;for(const R of a)try{const{data:z,error:$}=await q.functions.invoke("assign-brokerage",{body:{userId:R,brokerageId:u}});if($||z!=null&&z.error)throw new Error(($==null?void 0:$.message)||z.error);M++}catch{I++}p(!1),s({title:`Assigned ${M}${I?`, ${I} failed`:""}`,description:"Bulk assignment complete.",variant:I?"destructive":"default"}),i(new Set),h(""),t.invalidateQueries({queryKey:["unassigned-members"]})},L=(M,I)=>{const R={...l};for(const z of f)(z.email||"").toLowerCase().endsWith(`@${M}`)&&(R[z.id]=I);o(R),s({title:"Suggestions applied",description:`Pre-filled brokerage for @${M}`})};return e.jsx(qs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{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(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsxs(It,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4"})," Orphan members"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-3xl font-bold",children:f.length})})]}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsxs(It,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(_i,{className:"h-4 w-4"})," Selected"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-3xl font-bold",children:a.size})})]}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsxs(It,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(cn,{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(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Domain suggestions"})}),e.jsx(Ie,{children:e.jsx("div",{className:"flex flex-wrap gap-2",children:b.map(([M,I])=>{const R=y.find(z=>z.name.toLowerCase().replace(/[^a-z0-9]/g,"").includes(M.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:["@",M]}),e.jsx(Be,{variant:"secondary",children:I}),e.jsxs(Ns,{onValueChange:z=>L(M,z),defaultValue:R==null?void 0:R.id,children:[e.jsx(ws,{className:"h-8 w-[220px]",children:e.jsx(ks,{placeholder:"Apply brokerage…"})}),e.jsx(js,{children:y.map(z=>e.jsx(et,{value:z.id,children:z.name},z.id))})]})]},M)})})})]}),e.jsxs(we,{children:[e.jsxs(Tt,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:n,onChange:M=>r(M.target.value),placeholder:"Search name, email, phone…",className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ns,{value:u,onValueChange:h,children:[e.jsx(ws,{className:"w-[240px]",children:e.jsx(ks,{placeholder:"Bulk assign to brokerage…"})}),e.jsx(js,{children:y.map(M=>e.jsx(et,{value:M.id,children:M.name},M.id))})]}),e.jsxs(U,{onClick:T,disabled:!u||a.size===0||m,children:[m&&e.jsx(Et,{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(Et,{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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{className:"w-10",children:e.jsx(xi,{checked:a.size===v.length&&v.length>0,onCheckedChange:S})}),e.jsx(Lt,{children:"Name"}),e.jsx(Lt,{children:"Email"}),e.jsx(Lt,{children:"Signed up"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{children:"Assign to brokerage"}),e.jsx(Lt,{className:"w-24"})]})}),e.jsx(Xa,{children:v.map(M=>{const I=l[M.id]||"";return e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsx(xi,{checked:a.has(M.id),onCheckedChange:()=>N(M.id)})}),e.jsx(gt,{className:"font-medium",children:M.name||"—"}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:M.email}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Nd(new Date(M.created_at),{addSuffix:!0})}),e.jsx(gt,{children:e.jsx(Be,{variant:"outline",children:M.subscription_status||"none"})}),e.jsx(gt,{children:e.jsxs(Ns,{value:I,onValueChange:R=>o(z=>({...z,[M.id]:R})),children:[e.jsx(ws,{className:"h-9 w-[240px]",children:e.jsx(ks,{placeholder:"Pick brokerage…"})}),e.jsx(js,{children:y.map(R=>e.jsx(et,{value:R.id,children:R.name},R.id))})]})}),e.jsx(gt,{children:e.jsx(U,{size:"sm",disabled:!I||c[M.id],onClick:()=>A(M.id,I),children:c[M.id]?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):"Assign"})})]},M.id)})})]})})})]})]})})}const Srn=()=>{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,p]=j.useState("");j.useEffect(()=>{f()},[]);const f=async()=>{const{data:A,error:T}=await q.from("invite_codes").select("*").order("created_at",{ascending:!1});T?(re.error("Failed to load invite codes"),console.error(T)):t(A||[]),r(!1)},x=async A=>{if(A.preventDefault(),!l.trim()){re.error("Please enter a code");return}i(!0);const{error:T}=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});T?T.code==="23505"?re.error("This code already exists"):(re.error("Failed to create invite code"),console.error(T)):(re.success("Invite code created"),o(""),d(""),h(""),p(""),f()),i(!1)},y=async(A,T)=>{const{error:L}=await q.from("invite_codes").update({is_active:!T}).eq("id",A);L?re.error("Failed to update code"):t(s.map(M=>M.id===A?{...M,is_active:!T}:M))},v=async A=>{const{error:T}=await q.from("invite_codes").delete().eq("id",A);T?re.error("Failed to delete code"):(re.success("Code deleted"),t(s.filter(L=>L.id!==A)))},b="https://dashboard.relevelup.com",N=A=>{const T=`${b}/join?code=${A}`;navigator.clipboard.writeText(T),re.success("Link copied to clipboard")},S=`${b}/join`;return e.jsx(qs,{title:"Invite Codes",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{title:"Invite Codes",description:"Manage signup invite codes"}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"Create New Code"}),e.jsxs(Jn,{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(te,{htmlFor:"code",children:"Code"}),e.jsx(xe,{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(te,{htmlFor:"description",children:"Description (optional)"}),e.jsx(xe,{id:"description",placeholder:"For marketing campaign",value:c,onChange:A=>d(A.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"maxUses",children:"Max Uses"}),e.jsx(xe,{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(te,{htmlFor:"trialDays",children:"Trial Days"}),e.jsx(xe,{id:"trialDays",type:"number",placeholder:"None",value:m,onChange:A=>p(A.target.value),className:"w-28"})]}),e.jsxs(U,{type:"submit",disabled:a,children:[a?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(an,{className:"h-4 w-4 mr-2"}),"Create"]})]})})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{children:"Active Codes"})}),e.jsx(Ie,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Et,{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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Code"}),e.jsx(Lt,{children:"Description"}),e.jsx(Lt,{children:"Uses"}),e.jsx(Lt,{children:"Trial"}),e.jsx(Lt,{children:"Created"}),e.jsx(Lt,{children:"Active"}),e.jsx(Lt,{className:"w-24",children:"Actions"})]})}),e.jsx(Xa,{children:s.map(A=>e.jsxs(gn,{children:[e.jsx(gt,{className:"font-mono font-medium",children:A.code}),e.jsx(gt,{className:"text-muted-foreground",children:A.description||"—"}),e.jsxs(gt,{children:[A.uses_count,A.max_uses&&` / ${A.max_uses}`]}),e.jsx(gt,{children:A.trial_days?e.jsxs("span",{className:"text-amber-600 dark:text-amber-400 font-medium",children:[A.trial_days," days"]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{className:"text-muted-foreground",children:Gs(new Date(A.created_at),"MMM d, yyyy")}),e.jsx(gt,{children:e.jsx(wn,{checked:A.is_active,onCheckedChange:()=>y(A.id,A.is_active)})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>N(A.code),title:"Copy invite link",children:e.jsx(Pa,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>v(A.id),className:"text-destructive hover:text-destructive",title:"Delete code",children:e.jsx(In,{className:"h-4 w-4"})})]})})]},A.id))})]})})]})]})})},xA=q;function rxr(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 Crn(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").slice(0,70)}const Arn="https://dashboard.relevelup.com";function axr(s,t){const r=`${typeof window<"u"&&window.location.hostname==="localhost"?window.location.origin:Arn}/live/${s}`;return t?`${r}?i=${t}`:r}function ixr(){const s=Qt(),t=ct({queryKey:["live-events"],queryFn:async()=>{const{data:i,error:l}=await xA.from("live_events").select("*").order("starts_at",{ascending:!1});if(l)throw l;return i||[]}}),n=yt({mutationFn:async i=>{var d;const{data:l}=await q.auth.getUser(),{data:o,error:c}=await xA.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=yt({mutationFn:async({id:i,...l})=>{const{error:o}=await xA.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=yt({mutationFn:async i=>{const{error:l}=await xA.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 oxr(s){return ct({queryKey:["live-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await xA.from("live_events").select("*").eq("id",s).maybeSingle();if(n)throw n;return t}})}function lxr(s){return ct({queryKey:["live-registrations",s],enabled:!!s,refetchInterval:2e4,queryFn:async()=>{const{data:t,error:n}=await xA.from("live_registrations").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function cxr(s){const t=Qt(),n=ct({queryKey:["live-invites",s],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await xA.from("live_invites").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(l)throw l;return i||[]}}),r=yt({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 xA.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=yt({mutationFn:async i=>{const{error:l}=await xA.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 Cre=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}},IG=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}}},Ern=async(s,t)=>await Cre("new_templates")?IG({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}),Trn=async(s,t)=>IG({title:"New Academy Video",body:`New video added: ${s}`,url:`/academy/${t}`}),Mrn=async(s,t)=>await Cre("new_events")?IG({title:"New Event",body:`New event: ${s}`,url:`/events/${t}`}):(console.log("New event notifications are disabled"),{success:!1,skipped:!0}),Prn=async(s,t)=>await Cre("new_toolbox")?IG({title:"New Resource Kit",body:`New resource kit available: ${s}`,url:`/toolbox/${t}`}):(console.log("New toolbox notifications are disabled"),{success:!1,skipped:!0}),cVe=async(s,t)=>await Cre("new_social_swag")?IG({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}),Lrn=async(s,t)=>await Cre("new_newsletters")?IG({title:"New Newsletter",body:`New newsletter available: ${s}`,url:`/newsletters/${t}`}):(console.log("New newsletter notifications are disabled"),{success:!1,skipped:!0}),t7e=400;function Irn(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 Rrn(){const s=[];let t=0;const n=1e3;for(;;){const{data:r,error:a}=await q.from("profiles").select("id, name, email, event_invite_opt_out").not("email","is",null).neq("email","").eq("event_invite_opt_out",!1).order("created_at",{ascending:!1}).range(t,t+n-1);if(a)throw a;if(!r||r.length===0)break;for(const i of r)i.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i.email)&&s.push({id:i.id,name:i.name||"",email:i.email});if(r.length{if(!s||!n)return;let Z=!1;return(async()=>{h(!0);try{const[Q,le,ue]=await Promise.all([Rrn(),ryt("event_registrations",n.id),ryt("event_attendees",n.id)]);if(Z)return;p(Q),x(le),v(ue)}catch(Q){Z||r({title:"Could not load audience",description:Q instanceof Error?Q.message:"Unknown error",variant:"destructive"})}finally{Z||h(!1)}})(),()=>{Z=!0}},[s,n,r]),j.useEffect(()=>{s||(A(null),d(""),o(""),i("not_registered"))},[s]);const R=j.useMemo(()=>a==="all"?m:a==="not_registered"?m.filter(Z=>!f.has(Z.id)):m.filter(Z=>f.has(Z.id)&&!y.has(Z.id)),[a,m,f,y]),z={all:m.length,not_registered:m.filter(Z=>!f.has(Z.id)).length,registered_never_attended:m.filter(Z=>f.has(Z.id)&&!y.has(Z.id)).length},$=async(Z,Q=!1)=>{const{data:{session:le}}=await q.auth.getSession(),ue=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${le==null?void 0:le.access_token}`},body:JSON.stringify({event_id:n.id,recipients:Z.map(ne=>({email:ne.email,name:ne.name,user_id:ne.id})),custom_subject:l.trim()||void 0,custom_intro:c.trim()||void 0,force_resend:Q||void 0})}),se=await ue.json().catch(()=>({}));if(!ue.ok)throw new Error((se==null?void 0:se.error)||`HTTP ${ue.status}`);return{sent:(se==null?void 0:se.sent)??0,failed:(se==null?void 0:se.failed)??0,alreadyInvited:(se==null?void 0:se.already_invited)??0}},H=async()=>{var Z;if(n){I(!0);try{const{data:{session:Q}}=await q.auth.getSession(),le=Q==null?void 0:Q.user;if(!(le!=null&&le.email))throw new Error("No signed-in email found");const ue=await $([{id:le.id,name:((Z=le.user_metadata)==null?void 0:Z.name)||"",email:le.email}],!0);r({title:"Test sent",description:`Sent to ${le.email} · Sent: ${ue.sent} · Failed: ${ue.failed}`})}catch(Q){r({title:"Test failed",description:Q instanceof Error?Q.message:"Unknown error",variant:"destructive"})}finally{I(!1)}}},V=async()=>{if(!(!n||R.length===0)){L(!1),N(!0),A({done:0,total:R.length,sent:0,failed:0});try{let Z=0,Q=0,le=0;for(let ue=0;ue!b&&t(Z),children:e.jsxs(Ds,{className:"max-w-2xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(cn,{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(ch,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-foreground",children:n.title}),e.jsx("span",{children:"·"}),e.jsx("span",{children:Irn(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(te,{className:"flex items-center gap-2",children:[e.jsx(Bn,{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(Et,{className:"h-4 w-4 animate-spin"})," Loading members..."]}):e.jsxs(y_,{value:a,onValueChange:Z=>i(Z),className:"space-y-2",children:[e.jsxs("label",{htmlFor:"aud-not-reg",className:"flex items-start gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/40 transition",children:[e.jsx(Fh,{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:z.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(Fh,{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:z.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(Fh,{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:z.registered_never_attended.toLocaleString()})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"ev-inv-subject",children:"Subject line (optional)"}),e.jsx(xe,{id:"ev-inv-subject",placeholder:n?`You're invited: ${n.title}`:"You're invited to...",value:l,onChange:Z=>o(Z.target.value),disabled:b}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank for the default."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"ev-inv-intro",children:"Personal message (optional)"}),e.jsx(Fs,{id:"ev-inv-intro",placeholder:"e.g. Our Wednesday live training this week is on lead conversion. Grab your seat — it's a game-changer.",value:c,onChange:Z=>d(Z.target.value),rows:4,disabled:b}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Appears at the top of the email above the event details."})]}),S&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Sending ",S.done.toLocaleString()," / ",S.total.toLocaleString()]}),e.jsxs("span",{className:"font-medium",children:["✓ ",S.sent.toLocaleString(),S.failed>0&&e.jsxs("span",{className:"text-destructive",children:[" · ✗ ",S.failed.toLocaleString()]})]})]}),e.jsx(ro,{value:K})]})]}),e.jsxs(Mr,{className:"gap-2 sm:gap-2",children:[e.jsx(U,{variant:"outline",onClick:H,disabled:b||M||u,children:M?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"})," Sending test..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ln,{className:"h-4 w-4 mr-2"})," Send test to me"]})}),e.jsx(U,{variant:"ghost",onClick:()=>t(!1),disabled:b,children:"Cancel"}),e.jsx(U,{onClick:()=>L(!0),disabled:b||u||R.length===0,children:b?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx($r,{className:"h-4 w-4 mr-2"})," Send to ",R.length.toLocaleString()]})})]})]})}),e.jsx(Fl,{open:T,onOpenChange:L,children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Send event invite?"}),e.jsxs(Ll,{children:["This will send a branded invite to"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[R.length.toLocaleString()," member",R.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(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsxs(_l,{onClick:V,children:[e.jsx($r,{className:"h-4 w-4 mr-2"})," Send now"]})]})]})})]})}const yle={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 Orn(){const s=Wn(),t=Qt(),[n,r]=j.useState(!1),[a,i]=j.useState(null),[l,o]=j.useState(yle),[c,d]=j.useState(null),[u,h]=j.useState(null),[m,p]=j.useState(!1),f=j.useRef(null),[x,y]=j.useState(!1),[v,b]=j.useState(null),[N,S]=j.useState(!1),[A,T]=j.useState(null),[L,M]=j.useState(null),[I,R]=j.useState(!0),[z,$]=j.useState(""),[H,V]=j.useState(!1),[K,Z]=j.useState(null),{data:Q,isLoading:le}=ct({queryKey:["admin-events"],queryFn:async()=>{const{data:He,error:tt}=await q.from("events").select("*").order("event_date",{ascending:!0});if(tt)throw tt;return He}}),{data:ue}=ct({queryKey:["event-registrations-count"],queryFn:async()=>{let He=[],tt=0;const pt=1e3;for(;;){const{data:qt,error:Ut}=await q.from("event_registrations").select("event_id").range(tt,tt+pt-1);if(Ut)throw Ut;if(!qt||qt.length===0||(He=He.concat(qt),qt.length{ft[qt.event_id]=(ft[qt.event_id]||0)+1}),ft}}),{data:se,isLoading:ne}=ct({queryKey:["event-registrations-details",v==null?void 0:v.id],queryFn:async()=>{if(!v)return[];const{data:He,error:tt}=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(tt)throw tt;if(!He||He.length===0)return[];const pt=He.map(Ut=>Ut.user_id).filter(Boolean);let ft=[];if(pt.length>0){const{data:Ut,error:Wt}=await q.from("profiles").select("id, name, email").in("id",pt);if(Wt)throw Wt;ft=Ut||[]}const qt=new Map((ft==null?void 0:ft.map(Ut=>[Ut.id,Ut]))||[]);return He.map(Ut=>({...Ut,profiles:Ut.user_id&&qt.get(Ut.user_id)||null}))},enabled:!!v}),{data:ie,isLoading:ce}=ct({queryKey:["event-attendees-details",v==null?void 0:v.id],queryFn:async()=>{if(!v)return[];const{data:He,error:tt}=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(tt)throw tt;if(!He||He.length===0)return[];const pt=He.map(us=>us.user_id).filter(Boolean);let ft=[];if(pt.length>0){const{data:us,error:zt}=await q.from("profiles").select("id, name, email").in("id",pt);if(zt)throw zt;ft=us||[]}const{data:qt}=await q.from("agent_points").select("user_id").eq("event_id",v.id),Ut=new Set((qt==null?void 0:qt.map(us=>us.user_id))||[]),Wt=new Map((ft==null?void 0:ft.map(us=>[us.id,us]))||[]);return He.map(us=>({...us,profiles:us.user_id&&Wt.get(us.user_id)||null,points_awarded:us.user_id?Ut.has(us.user_id):!1}))},enabled:!!v}),je=He=>{b(He),y(!0)},be=yt({mutationFn:async He=>{const{data:{session:tt}}=await q.auth.getSession();if(!tt)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 ${tt.access_token}`},body:JSON.stringify({event_id:He})}),ft=await pt.json();if(!pt.ok){const qt=new Error(ft.error||"Failed to sync");throw qt.scopeError=!!ft.scope_error,qt.details=ft.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,qt}return ft},onSuccess:He=>{if(t.invalidateQueries({queryKey:["event-registrations-details",v==null?void 0:v.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),He!=null&&He.scope_error||(He==null?void 0:He.success)===!1){re.error("Zoom needs one more authorization step",{description:He!=null&&He.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.":(He==null?void 0:He.message)||"Zoom registration sync could not complete.",duration:2e4});return}re.success(He.message)},onError:He=>{re.error("Failed to sync Zoom registrations",{description:He.scopeError&&He.details||He.message,duration:He.scopeError?2e4:5e3})}}),he=yt({mutationFn:async He=>{const{data:{session:tt}}=await q.auth.getSession();if(!tt)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 ${tt.access_token}`},body:JSON.stringify({event_id:He})}),ft=await pt.json();if(!pt.ok)throw new Error(ft.error||"Failed to sync attendees");return ft},onSuccess:He=>{if(t.invalidateQueries({queryKey:["event-attendees-details",v==null?void 0:v.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]}),He!=null&&He.scope_error||(He==null?void 0:He.success)===!1){re.error((He==null?void 0:He.message)||"Zoom sync failed",{description:He!=null&&He.scope_error?"Zoom must be re-authorized after adding the missing report scope.":void 0,duration:15e3});return}He!=null&&He.message?re.success(He.message):re.success(`Synced ${He.synced||0} attendees. ${He.points_awarded||0} points awarded!`)},onError:He=>{re.error("Failed to sync attendees: "+He.message)}}),ge=yt({mutationFn:async()=>{const{data:He,error:tt}=await q.functions.invoke("zoom-retry-registrations",{body:{}});if(tt)throw tt;return He},onSuccess:He=>{t.invalidateQueries({queryKey:["event-registrations-details",v==null?void 0:v.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),re.success(`Retry complete: ${(He==null?void 0:He.successCount)??0} fixed, ${(He==null?void 0:He.failCount)??0} still failing, ${(He==null?void 0:He.rateLimitedCount)??0} rate-limited`)},onError:He=>{re.error("Retry failed: "+He.message)}}),ke=yt({mutationFn:async({eventId:He,testMode:tt})=>{const{data:{session:pt}}=await q.auth.getSession();if(!pt)throw new Error("Not authenticated");const ft=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:He,test_mode:tt})}),qt=await ft.json();if(!ft.ok)throw new Error(qt.error||"Failed to send reminders");return qt},onSuccess:He=>{He.test?re.success(He.message||"Test email sent!"):re.success(He.message||`Reminder emails sent to ${He.sent} registrants!`)},onError:He=>{re.error("Failed to send reminders: "+He.message)}}),{data:Te}=ct({queryKey:["all-profiles-for-linking"],queryFn:async()=>{let He=[],tt=0;const pt=1e3;for(;;){const{data:ft,error:qt}=await q.from("profiles").select("id, name, email").order("name",{ascending:!0}).range(tt,tt+pt-1);if(qt)throw qt;if(!ft||ft.length===0||(He=[...He,...ft],ft.length{const{error:qt}=await q.from("event_attendees").update({user_id:tt}).eq("id",He);if(qt)throw qt;if(ft&&pt){const{error:Wt}=await q.from("zoom_email_aliases").upsert({user_id:tt,zoom_email:pt.toLowerCase()},{onConflict:"zoom_email"});Wt&&console.error("Failed to save alias:",Wt)}const Ut=v==null?void 0:v.id;if(Ut){const{data:Wt}=await q.from("user_roles").select("id").eq("user_id",tt).eq("role","admin").single();if(!Wt){const{data:us}=await q.from("agent_points").select("id").eq("user_id",tt).eq("event_id",Ut).single();us||(await q.rpc("award_attendance_points",{p_user_id:tt,p_event_id:Ut,p_points:10,p_reason:"Event Attendance (Manual Link)"}),await q.rpc("check_and_award_badges",{p_user_id:tt}))}}return{userId:tt,zoomEmail:pt,shouldSaveAlias:ft}},onSuccess:He=>{t.invalidateQueries({queryKey:["event-attendees-details",v==null?void 0:v.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]});let tt="Attendee linked and points awarded!";He.shouldSaveAlias&&He.zoomEmail&&(tt+=` Email "${He.zoomEmail}" will be auto-matched in the future.`),re.success(tt),S(!1),T(null),M(null),$("")},onError:He=>{re.error("Failed to link attendee: "+He.message)}}),Oe=He=>{T(He),M(null),R(!0),$(""),S(!0)},Se=()=>{!A||!L||Me.mutate({attendeeId:A.id,userId:L,zoomEmail:A.zoom_email,shouldSaveAlias:I})},Qe=(Te==null?void 0:Te.filter(He=>{var pt,ft;if(!z)return!0;const tt=z.toLowerCase();return((pt=He.name)==null?void 0:pt.toLowerCase().includes(tt))||((ft=He.email)==null?void 0:ft.toLowerCase().includes(tt))}))||[],Ae=async He=>{const tt=He.name.split(".").pop(),ft=`${`${crypto.randomUUID()}.${tt}`}`,{error:qt}=await q.storage.from("event-images").upload(ft,He);if(qt)throw qt;const{data:{publicUrl:Ut}}=q.storage.from("event-images").getPublicUrl(ft);return Ut},Fe=He=>{var pt;const tt=(pt=He.target.files)==null?void 0:pt[0];if(tt){if(tt.size>5*1024*1024){re.error("Image must be less than 5MB");return}d(tt),h(URL.createObjectURL(tt))}},Ne=()=>{d(null),h(null),o({...l,image_url:""}),f.current&&(f.current.value="")},$e=yt({mutationFn:async He=>{p(!0);let tt=He.image_url;c&&(tt=await Ae(c)||"");const pt=new Date(He.event_date),[ft,qt]=He.event_time.split(":");pt.setHours(parseInt(ft),parseInt(qt));const Ut=[new Date(pt)];if(He.is_recurring&&He.recurrence_end_date){let bt=new Date(pt);for(;He.recurrence_pattern==="weekly"?bt=qD(bt,1):He.recurrence_pattern==="biweekly"?bt=qD(bt,2):bt=dy(bt,1),!(bt>He.recurrence_end_date);)Ut.push(new Date(bt))}const Wt=Ut.map(bt=>({title:He.title,description:He.description||null,image_url:tt||null,video_url:He.video_url||null,event_date:bt.toISOString(),zoom_link:He.zoom_link,zoom_meeting_id:He.zoom_meeting_id||null,capacity:He.capacity?parseInt(He.capacity):null,is_published:He.is_published})),{data:us,error:zt}=await q.from("events").insert(Wt).select();if(zt)throw zt;return us&&us.length>0&&Mrn(He.title,us[0].id),Ut.length},onSuccess:He=>{t.invalidateQueries({queryKey:["admin-events"]}),re.success(He>1?`${He} recurring events created successfully`:"Event created successfully"),r(!1),o(yle),d(null),h(null),p(!1)},onError:He=>{re.error("Failed to create event: "+He.message),p(!1)}}),Ve=yt({mutationFn:async({id:He,data:tt})=>{p(!0);let pt=tt.image_url;c&&(pt=await Ae(c)||"");const ft=new Date(tt.event_date),[qt,Ut]=tt.event_time.split(":");ft.setHours(parseInt(qt),parseInt(Ut));const{error:Wt}=await q.from("events").update({title:tt.title,description:tt.description||null,image_url:pt||null,video_url:tt.video_url||null,event_date:ft.toISOString(),zoom_link:tt.zoom_link,zoom_meeting_id:tt.zoom_meeting_id||null,capacity:tt.capacity?parseInt(tt.capacity):null,is_published:tt.is_published}).eq("id",He);if(Wt)throw Wt},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),re.success("Event updated successfully"),r(!1),i(null),o(yle),d(null),h(null),p(!1)},onError:He=>{re.error("Failed to update event: "+He.message),p(!1)}}),qe=yt({mutationFn:async He=>{const{error:tt}=await q.from("events").delete().eq("id",He);if(tt)throw tt},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),re.success("Event deleted successfully")},onError:He=>{re.error("Failed to delete event: "+He.message)}}),Ze=yt({mutationFn:async He=>{var bt;const{data:tt}=await q.auth.getUser(),pt=new Date(He.event_date),ft=new Date(pt.getTime()+60*60*1e3),qt=Crn(He.title),Ut=Math.random().toString(36).slice(2,7),Wt=`${qt}-${Ut}`,{data:us,error:zt}=await q.from("live_events").insert({slug:Wt,title:He.title,description:He.description||null,hero_image_url:He.image_url||null,starts_at:He.event_date,ends_at:ft.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:He.zoom_meeting_id||null,cta_label:"Join the training",cta_url:He.zoom_link||"https://dashboard.relevelup.com/trial",created_by:(bt=tt.user)==null?void 0:bt.id,agenda:[],offer_bullets:[]}).select().single();if(zt)throw zt;return us},onSuccess:He=>{t.invalidateQueries({queryKey:["live-events"]}),re.success("Cloned to LevelUp Live — configure stream next"),s(`/admin/live/${He.id}`)},onError:He=>{re.error("Failed to clone to LevelUp Live: "+He.message)}}),Ue=He=>{var pt;const tt=new Date(He.event_date);i(He),o({title:He.title,description:He.description||"",image_url:He.image_url||"",video_url:He.video_url||"",event_date:tt,event_time:Gs(tt,"HH:mm"),zoom_link:He.zoom_link,zoom_meeting_id:He.zoom_meeting_id||"",capacity:((pt=He.capacity)==null?void 0:pt.toString())||"",is_published:He.is_published,is_recurring:!1,recurrence_pattern:"weekly",recurrence_end_date:void 0}),h(He.image_url||null),d(null),r(!0)},Ye=He=>{if(He.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?Ve.mutate({id:a.id,data:l}):$e.mutate(l)},Ge=()=>{r(!1),i(null),o(yle),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(Xh,{title:"Event Management",description:"Create and manage upcoming events"}),e.jsxs(we,{className:"mb-6",children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsx(It,{children:"All Events"}),e.jsxs(zs,{open:n,onOpenChange:He=>!He&&Ge(),children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{onClick:()=>r(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Add Event"]})}),e.jsxs(Ds,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:a?"Edit Event":"Create New Event"})}),e.jsxs("form",{onSubmit:Ye,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"title",children:"Title *"}),e.jsx(xe,{id:"title",value:l.title,onChange:He=>o({...l,title:He.target.value}),placeholder:"Event title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Description"}),e.jsx(SN,{content:l.description,onChange:He=>o({...l,description:He}),placeholder:"Event description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Event Image"}),e.jsx("input",{type:"file",ref:f,accept:"image/*",onChange:Fe,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(U,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:Ne,children:e.jsx(er,{className:"h-4 w-4"})})]}):e.jsxs(U,{type:"button",variant:"outline",className:"w-full h-32 border-dashed flex flex-col gap-2",onClick:()=>{var He;return(He=f.current)==null?void 0:He.click()},children:[e.jsx(qa,{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(te,{children:"Date *"}),e.jsxs(md,{children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{variant:"outline",className:Mt("w-full justify-start text-left font-normal",!l.event_date&&"text-muted-foreground"),children:[e.jsx(pa,{className:"mr-2 h-4 w-4"}),l.event_date?Gs(l.event_date,"PPP"):"Pick a date"]})}),e.jsx(id,{className:"w-auto p-0",align:"start",children:e.jsx(yj,{mode:"single",selected:l.event_date,onSelect:He=>o({...l,event_date:He}),initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"time",children:"Time *"}),e.jsx(xe,{id:"time",type:"time",value:l.event_time,onChange:He=>o({...l,event_time:He.target.value}),required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"zoom_link",children:"Zoom Link *"}),e.jsx(xe,{id:"zoom_link",value:l.zoom_link,onChange:He=>o({...l,zoom_link:He.target.value}),placeholder:"https://zoom.us/j/...",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"zoom_meeting_id",children:"Zoom Meeting ID (for API registration)"}),e.jsx(xe,{id:"zoom_meeting_id",value:l.zoom_meeting_id,onChange:He=>o({...l,zoom_meeting_id:He.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(te,{htmlFor:"video_url",children:"Promo Video URL (optional)"}),e.jsx(xe,{id:"video_url",value:l.video_url,onChange:He=>o({...l,video_url:He.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(te,{htmlFor:"capacity",children:"Capacity (optional)"}),e.jsx(xe,{id:"capacity",type:"number",value:l.capacity,onChange:He=>o({...l,capacity:He.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(IA,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(te,{htmlFor:"is_recurring",children:"Recurring Event"})]}),e.jsx(wn,{id:"is_recurring",checked:l.is_recurring,onCheckedChange:He=>o({...l,is_recurring:He})})]}),l.is_recurring&&e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Frequency"}),e.jsxs(Ns,{value:l.recurrence_pattern,onValueChange:He=>o({...l,recurrence_pattern:He}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"weekly",children:"Weekly"}),e.jsx(et,{value:"biweekly",children:"Every 2 Weeks"}),e.jsx(et,{value:"monthly",children:"Monthly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Repeat Until"}),e.jsxs(md,{children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{variant:"outline",className:Mt("w-full justify-start text-left font-normal",!l.recurrence_end_date&&"text-muted-foreground"),children:[e.jsx(pa,{className:"mr-2 h-4 w-4"}),l.recurrence_end_date?Gs(l.recurrence_end_date,"PPP"):"Pick end date"]})}),e.jsx(id,{className:"w-auto p-0",align:"start",children:e.jsx(yj,{mode:"single",selected:l.recurrence_end_date,onSelect:He=>o({...l,recurrence_end_date:He}),disabled:He=>He<(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 He=1,tt=new Date(l.event_date);for(;tt=l.recurrence_pattern==="weekly"?qD(tt,1):l.recurrence_pattern==="biweekly"?qD(tt,2):dy(tt,1),!(tt>l.recurrence_end_date);)He++;return He})()," events with the same Zoom link"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{htmlFor:"is_published",children:"Published"}),e.jsx(wn,{id:"is_published",checked:l.is_published,onCheckedChange:He=>o({...l,is_published:He})})]}),e.jsxs("div",{className:"flex gap-2 pt-4",children:[e.jsx(U,{type:"button",variant:"outline",onClick:Ge,className:"flex-1",children:"Cancel"}),e.jsx(U,{type:"submit",className:"flex-1",disabled:$e.isPending||Ve.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:le?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading events..."}):(Q==null?void 0:Q.length)===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No events yet. Create your first event!"}):(()=>{const He=new Date,tt=[...Q||[]],pt=tt.filter(us=>new Date(us.event_date)>=He).sort((us,zt)=>new Date(us.event_date).getTime()-new Date(zt.event_date).getTime()),ft=tt.filter(us=>new Date(us.event_date)new Date(zt.event_date).getTime()-new Date(us.event_date).getTime()),qt=pt[0],Ut=us=>e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium",children:us.title}),e.jsx(gt,{className:"whitespace-nowrap",children:Gs(new Date(us.event_date),"PPP p")}),e.jsx(gt,{children:e.jsxs(U,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>je(us),children:[e.jsx(Bn,{className:"h-4 w-4"}),(ue==null?void 0:ue[us.id])||0,us.capacity&&` / ${us.capacity}`]})}),e.jsx(gt,{children:e.jsx("span",{className:Mt("px-2 py-1 rounded-full text-xs font-medium",us.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:us.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsxs(U,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>{Z(us),V(!0)},title:"Send invite email to members",children:[e.jsx($r,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Invite Members"})]}),e.jsxs(U,{variant:"outline",size:"sm",className:"gap-1.5 border-primary/50 text-primary hover:bg-primary/10",onClick:()=>Ze.mutate(us),disabled:Ze.isPending,title:"Clone to LevelUp Live",children:[e.jsx(mv,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"LevelUp Live"})]}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>window.open(us.zoom_link,"_blank"),title:"Open Zoom Link",children:e.jsx(Sr,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>Ue(us),children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:async()=>{await Yi("Are you sure you want to delete this event?")&&qe.mutate(us.id)},children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]})})]},us.id),Wt=(us,zt)=>us.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:zt}):e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Title"}),e.jsx(Lt,{children:"Date & Time"}),e.jsx(Lt,{children:"Registrations"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:us.map(Ut)})]});return e.jsxs("div",{className:"space-y-6",children:[qt&&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(Yr,{className:"h-3.5 w-3.5"}),"Next Upcoming Event"]}),e.jsx("h3",{className:"text-xl font-bold truncate",children:qt.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Gs(new Date(qt.event_date),"EEEE, PPP 'at' p")}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[(ue==null?void 0:ue[qt.id])||0," registered",qt.capacity?` of ${qt.capacity}`:""]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(U,{size:"sm",className:"gap-1.5",onClick:()=>{Z(qt),V(!0)},children:[e.jsx($r,{className:"h-4 w-4"}),"Invite Members"]}),e.jsxs(U,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>je(qt),children:[e.jsx(Bn,{className:"h-4 w-4"}),"Registrations"]}),e.jsxs(U,{size:"sm",variant:"outline",className:"gap-1.5 border-primary/50 text-primary hover:bg-primary/10",onClick:()=>Ze.mutate(qt),disabled:Ze.isPending,children:[e.jsx(mv,{className:"h-4 w-4"}),"LevelUp Live"]}),e.jsxs(U,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>window.open(qt.zoom_link,"_blank"),children:[e.jsx(Sr,{className:"h-4 w-4"}),"Zoom"]})]})]})}),e.jsxs(oa,{defaultValue:"upcoming",className:"w-full",children:[e.jsxs(la,{children:[e.jsxs(Kt,{value:"upcoming",className:"gap-2",children:[e.jsx(Yr,{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(Kt,{value:"past",className:"gap-2",children:[e.jsx(zr,{className:"h-4 w-4"}),"Past",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:ft.length})]})]}),e.jsx(Zt,{value:"upcoming",className:"mt-4",children:Wt(pt,"No upcoming events scheduled.")}),e.jsx(Zt,{value:"past",className:"mt-4",children:Wt(ft,"No past events.")})]})]})})()})]}),e.jsx(Drn,{open:H,onOpenChange:V,event:K}),e.jsx(zs,{open:x,onOpenChange:y,children:e.jsxs(Ds,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Bn,{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(U,{variant:"ghost",size:"sm",onClick:()=>ke.mutate({eventId:v.id,testMode:!0}),disabled:ke.isPending,children:[e.jsx(ln,{className:Mt("h-4 w-4 mr-2",ke.isPending&&"animate-spin")}),"Send Test to Me"]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>ke.mutate({eventId:v.id}),disabled:ke.isPending||!(se!=null&&se.length),children:[e.jsx(ln,{className:Mt("h-4 w-4 mr-2",ke.isPending&&"animate-spin")}),ke.isPending?"Sending...":"Send Reminder to All"]}),(v==null?void 0:v.zoom_meeting_id)&&e.jsxs(e.Fragment,{children:[e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>be.mutate(v.id),disabled:be.isPending,children:[e.jsx(no,{className:Mt("h-4 w-4 mr-2",be.isPending&&"animate-spin")}),be.isPending?"Syncing...":"Sync Registrations"]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>ge.mutate(),disabled:ge.isPending,children:[e.jsx(no,{className:Mt("h-4 w-4 mr-2",ge.isPending&&"animate-spin")}),ge.isPending?"Retrying...":"Retry Failed Registrations"]}),e.jsxs(U,{variant:"default",size:"sm",onClick:()=>he.mutate(v.id),disabled:he.isPending,children:[e.jsx(Al,{className:Mt("h-4 w-4 mr-2",he.isPending&&"animate-spin")}),he.isPending?"Syncing...":"Sync Attendees & Award Points"]})]})]}),e.jsxs(oa,{defaultValue:"registrations",className:"w-full",children:[e.jsxs(la,{className:"grid w-full grid-cols-2",children:[e.jsxs(Kt,{value:"registrations",className:"gap-2",children:[e.jsx(Bn,{className:"h-4 w-4"}),"Registrations (",(se==null?void 0:se.length)||0,")"]}),e.jsxs(Kt,{value:"attendees",className:"gap-2",children:[e.jsx(zr,{className:"h-4 w-4"}),"Attendees (",(ie==null?void 0:ie.length)||0,")"]})]}),e.jsx(Zt,{value:"registrations",className:"mt-4",children:ne?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading registrations..."}):(se==null?void 0:se.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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Name"}),e.jsx(Lt,{children:"Email"}),e.jsx(Lt,{children:"Registered"}),e.jsx(Lt,{children:"Status"})]})}),e.jsx(Xa,{children:se==null?void 0:se.map(He=>{var qt,Ut;const tt=((qt=He.profiles)==null?void 0:qt.name)||He.zoom_name||"Unknown",pt=((Ut=He.profiles)==null?void 0:Ut.email)||He.zoom_email||null,ft=!He.user_id;return e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[tt,ft&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:"External"})]})}),e.jsx(gt,{children:pt?e.jsxs("a",{href:`mailto:${pt}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(ln,{className:"h-3 w-3"}),pt]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(gt,{className:"text-muted-foreground text-sm",children:Gs(new Date(He.registered_at),"MMM d, yyyy h:mm a")}),e.jsx(gt,{children:He.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"})})]},He.id)})})]})}),e.jsx(Zt,{value:"attendees",className:"mt-4",children:ce?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading attendees..."}):(ie==null?void 0:ie.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:[(ie==null?void 0:ie.filter(He=>!He.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(Vo,{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 (",ie==null?void 0:ie.filter(He=>!He.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:ie==null?void 0:ie.filter(He=>!He.user_id).map(He=>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:He.zoom_name||"Unknown"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:He.zoom_email||"No email"})]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>Oe(He),className:"gap-1",children:[e.jsx(ad,{className:"h-3 w-3"}),"Link to Profile"]})]},He.id))})]}),e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Name"}),e.jsx(Lt,{children:"Email"}),e.jsx(Lt,{children:"Duration"}),e.jsx(Lt,{children:"Points"})]})}),e.jsx(Xa,{children:ie==null?void 0:ie.filter(He=>He.user_id).map(He=>{var ft,qt;const tt=((ft=He.profiles)==null?void 0:ft.name)||He.zoom_name||"Unknown",pt=((qt=He.profiles)==null?void 0:qt.email)||He.zoom_email||null;return e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[tt,He.manually_added&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200",children:"Manual"})]})}),e.jsx(gt,{children:pt?e.jsxs("a",{href:`mailto:${pt}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(ln,{className:"h-3 w-3"}),pt]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(gt,{children:He.duration_minutes?e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground text-sm",children:[e.jsx(Yr,{className:"h-3 w-3"}),He.duration_minutes," min"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(gt,{children:He.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(Al,{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"})})]},He.id)})})]})]})})]})]})}),e.jsx(zs,{open:N,onOpenChange:S,children:e.jsxs(Ds,{className:"max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(ad,{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(te,{children:"Search for a profile"}),e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name or email...",value:z,onChange:He=>$(He.target.value),className:"pl-9"})]})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto border rounded-md",children:Qe.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:Qe.slice(0,20).map(He=>e.jsxs("button",{type:"button",onClick:()=>M(He.id),className:Mt("w-full p-3 text-left hover:bg-muted/50 transition-colors",L===He.id&&"bg-primary/10 border-l-2 border-primary"),children:[e.jsx("p",{className:"text-sm font-medium",children:He.name||"Unnamed"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:He.email})]},He.id))})}),A.zoom_email&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(xi,{id:"save-alias",checked:I,onCheckedChange:He=>R(He)}),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(U,{variant:"outline",onClick:()=>S(!1),children:"Cancel"}),e.jsx(U,{onClick:Se,disabled:!L||Me.isPending,children:Me.isPending?"Linking...":"Link & Award Points"})]})]})]})})]})})}const Frn={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 zrn(){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(qs,{title:"MCP Audit Log",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{title:"MCP Audit Log",description:"Recent LevelUp MCP tool calls — ChatGPT / Claude / Codex activity, denials, and rate limits."}),e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(fq,{className:"h-5 w-5"}),"Recent activity"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{variant:a==="issues"?"default":"outline",size:"sm",onClick:()=>i("issues"),children:"Issues only"}),e.jsx(U,{variant:a==="all"?"default":"outline",size:"sm",onClick:()=>i("all"),children:"All calls"}),e.jsx(U,{variant:"ghost",size:"sm",onClick:l,disabled:n,children:e.jsx(no,{className:`h-4 w-4 ${n?"animate-spin":""}`})})]})]}),e.jsx(Ie,{children:n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No entries."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"border-b text-left text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"py-2 pr-4",children:"When"}),e.jsx("th",{className:"py-2 pr-4",children:"Tool"}),e.jsx("th",{className:"py-2 pr-4",children:"Outcome"}),e.jsx("th",{className:"py-2 pr-4",children:"User"}),e.jsx("th",{className:"py-2 pr-4",children:"Client"}),e.jsx("th",{className:"py-2 pr-4",children:"ms"}),e.jsx("th",{className:"py-2 pr-4",children:"Error"})]})}),e.jsx("tbody",{children:s.map(o=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsx("td",{className:"py-2 pr-4 whitespace-nowrap",children:new Date(o.created_at).toLocaleString()}),e.jsx("td",{className:"py-2 pr-4 font-mono text-xs",children:o.tool_name}),e.jsx("td",{className:"py-2 pr-4",children:e.jsx(Be,{className:Frn[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 Brn({selectedKitIds:s,onChange:t}){const[n,r]=j.useState(""),[a,i]=j.useState(!1),{data:l=[]}=ct({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(te,{className:"flex items-center gap-2",children:[e.jsx(dh,{className:"h-4 w-4"}),"Linked Toolkits"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map(h=>e.jsxs(Be,{variant:"secondary",className:"gap-1 pr-1",children:[h.name,e.jsx("button",{type:"button",onClick:()=>u(h.id),className:"ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5",children:e.jsx(er,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(md,{open:a,onOpenChange:i,children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(dh,{className:"h-3.5 w-3.5"}),"Add Toolkit"]})}),e.jsxs(id,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Fr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(xe,{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(dh,{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 Urn=()=>{const{user:s}=vs(),{toast:t}=Ai(),n=Qt(),[r,a]=fc(),[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),[p,f]=j.useState(0),[x,y]=j.useState(!1),[v,b]=j.useState(null),[N,S]=j.useState(""),[A,T]=j.useState([]),[L,M]=j.useState(""),[I,R]=j.useState(""),[z,$]=j.useState(!1),[H,V]=j.useState(!1),{data:K=[]}=ct({queryKey:["template-categories"],queryFn:async()=>{const{data:Ne,error:$e}=await q.from("template_categories").select("*").order("name");if($e)throw $e;return Ne}}),{data:Z=[]}=ct({queryKey:["template-types"],queryFn:async()=>{const{data:Ne,error:$e}=await q.from("template_types").select("*").order("name");if($e)throw $e;return Ne}}),{data:Q=[],isLoading:le}=ct({queryKey:["canva-templates-admin"],queryFn:async()=>{const{data:Ne,error:$e}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if($e)throw $e;const{data:Ve,error:qe}=await q.from("template_links").select("*").order("sort_order");if(qe)throw qe;const{data:Ze,error:Ue}=await q.from("template_guides").select("*").order("sort_order");if(Ue)throw Ue;return Ne.map(Ge=>({...Ge,links:(Ve==null?void 0:Ve.filter(He=>He.template_id===Ge.id))||[],guides:(Ze==null?void 0:Ze.filter(He=>He.template_id===Ge.id))||[]}))}});j.useEffect(()=>{const Ne=r.get("edit");if(Ne&&Q.length>0){const $e=Q.find(Ve=>Ve.id===Ne);$e&&(be($e),a({},{replace:!0}))}},[Q,r]);const ue=yt({mutationFn:async Ne=>{const{data:$e,error:Ve}=await q.from("template_categories").insert({name:Ne}).select().single();if(Ve)throw Ve;return $e},onSuccess:Ne=>{n.invalidateQueries({queryKey:["template-categories"]}),u({...d,category_id:Ne.id}),M(""),$(!1),t({title:"Category added"})},onError:Ne=>{t({title:"Error adding category",description:Ne.message,variant:"destructive"})}}),se=yt({mutationFn:async Ne=>{const{data:$e,error:Ve}=await q.from("template_types").insert({name:Ne}).select().single();if(Ve)throw Ve;return $e},onSuccess:Ne=>{n.invalidateQueries({queryKey:["template-types"]}),u({...d,type_id:Ne.id}),R(""),V(!1),t({title:"Type added"})},onError:Ne=>{t({title:"Error adding type",description:Ne.message,variant:"destructive"})}}),ne=yt({mutationFn:async Ne=>{var Ue;let $e=Ne.existingImageUrl;if(Ne.image){const Ye=Ne.image.name.split(".").pop(),Ge=`${Date.now()}-${Math.random().toString(36).substring(7)}.${Ye}`,{error:He}=await q.storage.from("template-previews").upload(Ge,Ne.image);if(He)throw He;const{data:tt}=q.storage.from("template-previews").getPublicUrl(Ge);$e=tt.publicUrl}const Ve={name:Ne.template.name,description:Ne.template.description||null,category_id:Ne.template.category_id||null,type_id:Ne.template.type_id||null,preview_image_url:$e,video_url:Ne.videoUrl||null,publish_date:Ne.template.publish_date?new Date(Ne.template.publish_date).toISOString():new Date().toISOString(),created_by:s==null?void 0:s.id};let qe=Ne.templateId;if(qe){const{error:Ye}=await q.from("canva_templates").update(Ve).eq("id",qe);if(Ye)throw Ye;const{error:Ge}=await q.from("template_links").delete().eq("template_id",qe);if(Ge)throw Ge;const He=((Ue=Ne.existingGuides)==null?void 0:Ue.map(ft=>ft.id).filter(Boolean))||[],tt=Ne.template.guides.map(ft=>ft.id).filter(Boolean),pt=He.filter(ft=>!tt.includes(ft));pt.length>0&&await q.from("template_guides").delete().in("id",pt)}else{const{data:Ye,error:Ge}=await q.from("canva_templates").insert(Ve).select().single();if(Ge)throw Ge;qe=Ye.id,Ern(Ne.template.name,Ye.id)}const Ze=Ne.template.links.filter(Ye=>Ye.title.trim()&&Ye.canva_share_link.trim());if(Ze.length>0){const Ye=Ze.map((He,tt)=>({template_id:qe,title:He.title.trim(),canva_share_link:He.canva_share_link.trim(),sort_order:tt})),{error:Ge}=await q.from("template_links").insert(Ye);if(Ge)throw Ge}for(let Ye=0;Ye0)){const{error:Ye}=await q.from("resource_kit_templates").insert(Ne.linkedKitIds.map(Ge=>({template_id:qe,kit_id:Ge})));if(Ye)throw Ye}},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),je(),l(!1),t({title:o?"Template updated":"Template created"})},onError:Ne=>{t({title:"Error saving template",description:Ne.message,variant:"destructive"})}}),ie=yt({mutationFn:async Ne=>{const{error:$e}=await q.from("canva_templates").delete().eq("id",Ne);if($e)throw $e},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),t({title:"Template deleted"})},onError:Ne=>{t({title:"Error deleting template",description:Ne.message,variant:"destructive"})}}),ce=yt({mutationFn:async({id:Ne,is_featured:$e})=>{const{error:Ve}=await q.from("canva_templates").update({is_featured:$e}).eq("id",Ne);if(Ve)throw Ve},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]})},onError:Ne=>{t({title:"Error updating featured",description:Ne.message,variant:"destructive"})}}),je=()=>{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),$(!1),V(!1),M(""),R(""),m(null),f(0),y(!1),T([])},be=async Ne=>{var Ve;c(Ne),u({name:Ne.name,description:Ne.description||"",category_id:Ne.category_id||"",type_id:Ne.type_id||"",publish_date:Ne.publish_date?new Date(Ne.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],links:Ne.links&&Ne.links.length>0?Ne.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:((Ve=Ne.guides)==null?void 0:Ve.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:Ne.video_url||""}),S(Ne.preview_image_url||""),m(null);const{data:$e}=await q.from("resource_kit_templates").select("kit_id").eq("template_id",Ne.id);T(($e||[]).map(qe=>qe.kit_id)),l(!0)},he=Ne=>{var Ve;const $e=(Ve=Ne.target.files)==null?void 0:Ve[0];$e&&(b($e),S(URL.createObjectURL($e)))},ge=()=>{u({...d,links:[...d.links,{title:"",canva_share_link:"",sort_order:d.links.length}]})},ke=Ne=>{if(d.links.length<=1)return;const $e=d.links.filter((Ve,qe)=>qe!==Ne);u({...d,links:$e})},Te=(Ne,$e,Ve)=>{const qe=[...d.links];qe[Ne]={...qe[Ne],[$e]:Ve},u({...d,links:qe})},Me=Ne=>{const $e=Ne.target.files;if(!$e)return;const Ve=Array.from($e).map((qe,Ze)=>({name:qe.name.replace(/\.[^/.]+$/,""),file_url:"",file_type:qe.type,file_size:qe.size,sort_order:d.guides.length+Ze,file:qe}));u({...d,guides:[...d.guides,...Ve]}),Ne.target.value=""},Oe=Ne=>{const $e=d.guides.filter((Ve,qe)=>qe!==Ne);u({...d,guides:$e})},Se=(Ne,$e)=>{const Ve=[...d.guides];Ve[Ne]={...Ve[Ne],name:$e},u({...d,guides:Ve})},Qe=async()=>{if(!h)return null;y(!0),f(0);try{const{data:Ne,error:$e}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:d.name||h.name}});if($e)throw new Error($e.message);const{videoId:Ve,libraryId:qe}=Ne,{data:Ze,error:Ue}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ve}});if(Ue)throw new Error(Ue.message);const Ye=new XMLHttpRequest;return await new Promise((He,tt)=>{Ye.upload.addEventListener("progress",pt=>{if(pt.lengthComputable){const ft=Math.round(pt.loaded/pt.total*100);f(ft)}}),Ye.addEventListener("load",()=>{Ye.status>=200&&Ye.status<300?He():tt(new Error(`Upload failed with status ${Ye.status}`))}),Ye.addEventListener("error",()=>tt(new Error("Upload failed"))),Ye.open("PUT",Ze.uploadUrl),Ye.setRequestHeader("AccessKey",Ze.apiKey),Ye.send(h)}),`https://player.mediadelivery.net/embed/${qe}/${Ve}`}catch(Ne){return console.error("Bunny upload error:",Ne),t({title:"Video upload failed",description:Ne instanceof Error?Ne.message:"Unknown error",variant:"destructive"}),null}finally{y(!1)}},Ae=Ne=>{var Ve;const $e=(Ve=Ne.target.files)==null?void 0:Ve[0];$e&&m($e),Ne.target.value=""},Fe=async Ne=>{if(Ne.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 Ve=d.video_url;if(h){const qe=await Qe();if(!qe)return;Ve=qe}ne.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:Ve,linkedKitIds:A})};return e.jsx(qs,{title:"Manage Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{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(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Total Templates"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:Q.length})})]}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Categories"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:K.length})})]}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Template Types"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:Z.length})})]})]}),e.jsxs(zs,{open:i,onOpenChange:Ne=>{l(Ne),Ne||je()},children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{className:"gap-2",children:[e.jsx(an,{className:"h-4 w-4"}),"Add Template"]})}),e.jsxs(Ds,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:o?"Edit Template":"Add New Template"})}),e.jsxs("form",{onSubmit:Fe,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"name",children:"Name *"}),e.jsx(xe,{id:"name",value:d.name,onChange:Ne=>u({...d,name:Ne.target.value}),placeholder:"Template name",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Description"}),e.jsx(SN,{content:d.description,onChange:Ne=>u({...d,description:Ne}),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(te,{children:"Canva Links *"}),e.jsxs(U,{type:"button",variant:"outline",size:"sm",onClick:ge,className:"gap-1",children:[e.jsx(an,{className:"h-3 w-3"}),"Add Link"]})]}),e.jsx("div",{className:"space-y-3",children:d.links.map((Ne,$e)=>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(xe,{value:Ne.title,onChange:Ve=>Te($e,"title",Ve.target.value),placeholder:"Link title (e.g., Instagram Post, Story)"}),e.jsx(xe,{value:Ne.canva_share_link,onChange:Ve=>Te($e,"canva_share_link",Ve.target.value),placeholder:"https://www.canva.com/design/..."})]}),d.links.length>1&&e.jsx(U,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>ke($e),children:e.jsx(er,{className:"h-4 w-4"})})]},$e))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Category"}),z?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:L,onChange:Ne=>M(Ne.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(U,{type:"button",size:"sm",onClick:()=>L.trim()&&ue.mutate(L.trim()),disabled:ue.isPending,children:"Add"}),e.jsx(U,{type:"button",size:"sm",variant:"ghost",onClick:()=>{$(!1),M("")},children:e.jsx(er,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ns,{value:d.category_id,onValueChange:Ne=>u({...d,category_id:Ne}),children:[e.jsx(ws,{className:"flex-1",children:e.jsx(ks,{placeholder:"Select category"})}),e.jsx(js,{children:K.map(Ne=>e.jsx(et,{value:Ne.id,children:Ne.name},Ne.id))})]}),e.jsx(U,{type:"button",variant:"outline",size:"icon",onClick:()=>$(!0),children:e.jsx(an,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Template Type"}),H?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:I,onChange:Ne=>R(Ne.target.value),placeholder:"New type name",className:"flex-1"}),e.jsx(U,{type:"button",size:"sm",onClick:()=>I.trim()&&se.mutate(I.trim()),disabled:se.isPending,children:"Add"}),e.jsx(U,{type:"button",size:"sm",variant:"ghost",onClick:()=>{V(!1),R("")},children:e.jsx(er,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ns,{value:d.type_id,onValueChange:Ne=>u({...d,type_id:Ne}),children:[e.jsx(ws,{className:"flex-1",children:e.jsx(ks,{placeholder:"Select type"})}),e.jsx(js,{children:Z.map(Ne=>e.jsx(et,{value:Ne.id,children:Ne.name},Ne.id))})]}),e.jsx(U,{type:"button",variant:"outline",size:"icon",onClick:()=>V(!0),children:e.jsx(an,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(xe,{id:"publish_date",type:"date",value:d.publish_date,onChange:Ne=>u({...d,publish_date:Ne.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(te,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[N?e.jsxs("div",{className:"relative w-32 h-24 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("img",{src:N,alt:"Preview",className:"w-full h-full object-cover"}),e.jsx(U,{type:"button",size:"icon",variant:"destructive",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>{b(null),S("")},children:e.jsx(er,{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(pc,{className:"h-8 w-8 text-muted-foreground/50"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(xe,{type:"file",accept:"image/*",onChange:he,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(te,{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(Wr,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:"Video uploaded"}),e.jsx(U,{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(Et,{className:"h-4 w-4 animate-spin"}),e.jsxs("span",{className:"text-sm",children:["Uploading video... ",p,"%"]})]}),e.jsx(ro,{value:p,className:"h-2"})]}):h?e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/30",children:[e.jsx(Wr,{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(U,{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(er,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(xe,{type:"file",accept:"video/*",onChange:Ae,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(Wr,{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(te,{children:"Guide Files (PDFs)"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(xe,{type:"file",accept:".pdf,.doc,.docx",multiple:!0,onChange:Me,className:"hidden"}),e.jsx(U,{type:"button",variant:"outline",size:"sm",className:"gap-1",asChild:!0,children:e.jsxs("span",{children:[e.jsx(qa,{className:"h-3 w-3"}),"Add Files"]})})]})]}),d.guides.length>0?e.jsx("div",{className:"space-y-2",children:d.guides.map((Ne,$e)=>e.jsxs("div",{className:"flex gap-2 items-center p-3 border rounded-lg bg-muted/30",children:[e.jsx(Ur,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx(xe,{value:Ne.name,onChange:Ve=>Se($e,Ve.target.value),placeholder:"Guide name",className:"flex-1"}),Ne.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(Ne.file_size/1024).toFixed(0)," KB"]}),e.jsx(U,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>Oe($e),children:e.jsx(er,{className:"h-4 w-4"})})]},Ne.id||$e))}):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(Brn,{selectedKitIds:A,onChange:T}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>{l(!1),je()},children:"Cancel"}),e.jsx(U,{type:"submit",disabled:ne.isPending,children:ne.isPending?"Saving...":o?"Update":"Create"})]})]})]})]})]}),e.jsx(we,{children:e.jsx(Ie,{className:"p-0",children:le?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading..."}):Q.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No templates yet. Add your first template!"}):e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Preview"}),e.jsx(Lt,{children:"Name"}),e.jsx(Lt,{children:"Links"}),e.jsx(Lt,{children:"Category"}),e.jsx(Lt,{children:"Type"}),e.jsx(Lt,{children:"Publish Date"}),e.jsx(Lt,{className:"w-[72px] text-center",children:"Featured"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:Q.map(Ne=>{var $e,Ve,qe,Ze,Ue;return e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsx("div",{className:"w-16 h-12 rounded overflow-hidden bg-muted",children:Ne.preview_image_url?e.jsx("img",{src:Ne.preview_image_url,alt:Ne.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(pc,{className:"h-4 w-4 text-muted-foreground"})})})}),e.jsx(gt,{className:"font-medium",children:Ne.name}),e.jsx(gt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs(Be,{variant:"secondary",children:[(($e=Ne.links)==null?void 0:$e.length)||0," link",(((Ve=Ne.links)==null?void 0:Ve.length)||0)!==1?"s":""]}),(((qe=Ne.guides)==null?void 0:qe.length)||0)>0&&e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(Ur,{className:"h-3 w-3"}),(Ze=Ne.guides)==null?void 0:Ze.length," guide",(((Ue=Ne.guides)==null?void 0:Ue.length)||0)!==1?"s":""]})]})}),e.jsx(gt,{children:Ne.category?e.jsx(Be,{variant:"secondary",children:Ne.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(gt,{children:Ne.type?e.jsx(Be,{variant:"outline",children:Ne.type.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(gt,{className:"text-muted-foreground",children:new Date(Ne.publish_date).toLocaleDateString()}),e.jsx(gt,{className:"text-center",children:e.jsx(U,{type:"button",size:"icon",variant:"ghost",className:"mx-auto",title:Ne.is_featured?"Remove from featured templates":"Add to featured templates",onClick:()=>ce.mutate({id:Ne.id,is_featured:!Ne.is_featured}),children:e.jsx(Ua,{className:`h-4 w-4 ${Ne.is_featured?"fill-yellow-400 text-yellow-400":"text-muted-foreground"}`})})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(U,{size:"icon",variant:"ghost",onClick:()=>be(Ne),children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{size:"icon",variant:"ghost",className:"text-destructive hover:text-destructive",onClick:async()=>{await Yi("Delete this template?")&&ie.mutate(Ne.id)},children:e.jsx(In,{className:"h-4 w-4"})})]})})]},Ne.id)})})]})})})]})})};function uqt({selectedTemplateIds:s,onChange:t}){const[n,r]=j.useState(""),[a,i]=j.useState(!1),{data:l=[]}=ct({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(te,{className:"flex items-center gap-2",children:[e.jsx(ej,{className:"h-4 w-4"}),"Linked Templates"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map(h=>e.jsxs(Be,{variant:"secondary",className:"gap-1 pr-1",children:[h.name,e.jsx("button",{type:"button",onClick:()=>u(h.id),className:"ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5",children:e.jsx(er,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(md,{open:a,onOpenChange:i,children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(ej,{className:"h-3.5 w-3.5"}),"Add Template"]})}),e.jsxs(id,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Fr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(xe,{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(ej,{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 qrn=[{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"}],ayt=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),iyt=s=>{const[t,n,r]=s.split(/[-/T]/);return`${Number(n)}/${Number(r)}/${t}`},$rn=()=>{const{user:s}=vs(),[t,n]=fc(),{toast:r}=Ai(),a=Qt(),[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),[p,f]=j.useState(""),[x,y]=j.useState([]),[v,b]=j.useState([]),[N,S]=j.useState([]),[A,T]=j.useState([]),[L,M]=j.useState(""),[I,R]=j.useState(!1),[z,$]=j.useState(null),[H,V]=j.useState(0),[K,Z]=j.useState(!1),[Q,le]=j.useState(null),{data:ue=[]}=ct({queryKey:["academy-categories"],queryFn:async()=>{const{data:Ne,error:$e}=await q.from("academy_categories").select("*").order("sort_order",{ascending:!0});if($e)throw $e;return Ne}}),{data:se=[],isLoading:ne}=ct({queryKey:["academy-videos-admin"],queryFn:async()=>{const{data:Ne,error:$e}=await q.from("academy_videos").select(` *, category:academy_categories(id, name) `).order("publish_date",{ascending:!1});if($e)throw $e;const{data:Ve,error:qe}=await q.from("academy_resources").select("*").order("sort_order");if(qe)throw qe;return Ne.map(Ue=>({...Ue,resources:(Ve==null?void 0:Ve.filter(Ye=>Ye.video_id===Ue.id))||[]}))}});j.useEffect(()=>{const Ne=t.get("edit");if(Ne&&se.length>0){const $e=se.find(Ve=>Ve.id===Ne);$e&&(Te($e),n({},{replace:!0}))}},[se,t]);const ie=yt({mutationFn:async Ne=>{const{data:$e,error:Ve}=await q.from("academy_categories").insert({name:Ne,sort_order:ue.length}).select().single();if(Ve)throw Ve;return $e},onSuccess:Ne=>{a.invalidateQueries({queryKey:["academy-categories"]}),u({...d,category_id:Ne.id}),M(""),R(!1),r({title:"Category added"})},onError:Ne=>{r({title:"Error adding category",description:Ne.message,variant:"destructive"})}}),ce=yt({mutationFn:async Ne=>{let $e=Ne.existingThumbnailUrl;if(Ne.thumbnail){const Ze=Ne.thumbnail.name.split(".").pop(),Ue=`thumbnails/${Date.now()}-${Math.random().toString(36).substring(7)}.${Ze}`,{error:Ye}=await q.storage.from("academy-resources").upload(Ue,Ne.thumbnail);if(Ye)throw Ye;const{data:Ge}=q.storage.from("academy-resources").getPublicUrl(Ue);$e=Ge.publicUrl}const Ve={title:Ne.video.title,description:Ne.video.description||null,video_url:Ne.video.video_url,video_type:Ne.video.video_type,duration:Ne.video.duration||null,thumbnail_url:$e,category_id:Ne.video.category_id||null,publish_date:Ne.video.publish_date?new Date(Ne.video.publish_date).toISOString():new Date().toISOString(),is_published:Ne.video.is_published,created_by:s==null?void 0:s.id};let qe=Ne.videoId;if(qe){const{error:Ze}=await q.from("academy_videos").update(Ve).eq("id",qe);if(Ze)throw Ze}else{const{data:Ze,error:Ue}=await q.from("academy_videos").insert(Ve).select().single();if(Ue)throw Ue;qe=Ze.id,Trn(Ne.video.title,Ze.id)}if(Ne.resourcesToDelete.length>0){const{error:Ze}=await q.from("academy_resources").delete().in("id",Ne.resourcesToDelete);if(Ze)throw Ze}for(let Ze=0;Ze0){const{error:Ze}=await q.from("academy_video_templates").insert(A.map(Ue=>({video_id:qe,template_id:Ue})));if(Ze)throw Ze}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),ke(),l(!1),r({title:o?"Video updated":"Video created"})},onError:Ne=>{r({title:"Error saving video",description:Ne.message,variant:"destructive"})}}),je=yt({mutationFn:async Ne=>{const{error:$e}=await q.from("academy_videos").delete().eq("id",Ne);if($e)throw $e},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),r({title:"Video deleted"})},onError:Ne=>{r({title:"Error deleting video",description:Ne.message,variant:"destructive"})}}),be=yt({mutationFn:async({id:Ne,is_published:$e})=>{const{error:Ve}=await q.from("academy_videos").update({is_published:$e}).eq("id",Ne);if(Ve)throw Ve},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]})},onError:Ne=>{r({title:"Error updating video",description:Ne.message,variant:"destructive"})}}),he=async Ne=>{try{let $e=Ne.public_slug||null,Ve=!!Ne.is_public;if(!$e||!Ve){const Ze=(Ne.title||"video").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"video";if(!$e){let Ye=Ze;const{data:Ge}=await q.from("academy_videos").select("id").eq("public_slug",Ye).maybeSingle();Ge&&Ge.id!==Ne.id&&(Ye=`${Ze}-${Ne.id.slice(0,6)}`),$e=Ye}const{error:Ue}=await q.from("academy_videos").update({public_slug:$e,is_public:!0}).eq("id",Ne.id);if(Ue)throw Ue;a.invalidateQueries({queryKey:["academy-videos-admin"]})}const qe=`${window.location.origin}/watch/${$e}`;await navigator.clipboard.writeText(qe),r({title:"Public link copied",description:qe})}catch($e){r({title:"Could not copy link",description:$e.message,variant:"destructive"})}},ge=async Ne=>{if(!await Yi("Disable the public teaser link for this video?"))return;const{error:$e}=await q.from("academy_videos").update({is_public:!1}).eq("id",Ne.id);if($e){r({title:"Error",description:$e.message,variant:"destructive"});return}a.invalidateQueries({queryKey:["academy-videos-admin"]}),r({title:"Public link disabled"})},ke=()=>{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),f(""),y([]),b([]),S([]),c(null),T([]),M(""),$(null),V(0),Z(!1),le(null)},Te=async Ne=>{c(Ne),u({title:Ne.title,description:Ne.description||"",video_url:Ne.video_url,video_type:Ne.video_type,duration:Ne.duration||"",category_id:Ne.category_id||"",publish_date:Ne.publish_date?new Date(Ne.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:Ne.is_published}),f(Ne.thumbnail_url||""),b(Ne.resources||[]),y([]),S([]);const{data:$e}=await q.from("academy_video_templates").select("template_id").eq("video_id",Ne.id);T(($e||[]).map(Ve=>Ve.template_id)),l(!0)},Me=Ne=>{var Ve;const $e=(Ve=Ne.target.files)==null?void 0:Ve[0];$e&&(m($e),f(URL.createObjectURL($e)))},Oe=Ne=>{const $e=Ne.target.files;if($e){const Ve=Array.from($e).map(qe=>({file:qe,title:qe.name.replace(/\.[^/.]+$/,"")}));y([...x,...Ve])}Ne.target.value=""},Se=Ne=>{y(x.filter(($e,Ve)=>Ve!==Ne))},Qe=Ne=>{S([...N,Ne]),b(v.filter($e=>$e.id!==Ne))},Ae=async()=>{if(!z)return null;Z(!0),V(0);try{const{data:Ne,error:$e}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:d.title||z.name}});if($e)throw new Error($e.message);const{videoId:Ve,libraryId:qe}=Ne;le(Ve);const{data:Ze,error:Ue}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ve}});if(Ue)throw new Error(Ue.message);const Ye=new XMLHttpRequest;return await new Promise((He,tt)=>{Ye.upload.addEventListener("progress",pt=>{if(pt.lengthComputable){const ft=Math.round(pt.loaded/pt.total*100);V(ft)}}),Ye.addEventListener("load",()=>{Ye.status>=200&&Ye.status<300?He():tt(new Error(`Upload failed with status ${Ye.status}`))}),Ye.addEventListener("error",()=>tt(new Error("Upload failed"))),Ye.open("PUT",Ze.uploadUrl),Ye.setRequestHeader("AccessKey",Ze.apiKey),Ye.send(z)}),`https://player.mediadelivery.net/embed/${qe}/${Ve}`}catch(Ne){return console.error("Bunny upload error:",Ne),r({title:"Video upload failed",description:Ne instanceof Error?Ne.message:"Unknown error",variant:"destructive"}),null}finally{Z(!1)}},Fe=async Ne=>{if(Ne.preventDefault(),!d.title.trim()){r({title:"Please enter a video title",variant:"destructive"});return}let $e=d.video_url;if(d.video_type==="bunny_stream"&&z&&!o){const Ve=await Ae();if(!Ve)return;$e=Ve}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"&&!z&&!d.video_url&&!o){r({title:"Please select a video file to upload",variant:"destructive"});return}ce.mutate({video:{...d,video_url:$e},thumbnail:h,existingThumbnailUrl:(o==null?void 0:o.thumbnail_url)||null,videoId:o==null?void 0:o.id,newResources:x,resourcesToDelete:N})};return e.jsx(qs,{title:"Manage Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{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(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Total Videos"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:se.length})})]}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:se.filter(Ne=>Ne.is_published).length})})]}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Public Teasers"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:se.filter(Ne=>Ne.is_public).length})})]}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{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:se.reduce((Ne,$e)=>Ne+($e.public_view_count||0),0).toLocaleString()})})]})]}),e.jsxs(zs,{open:i,onOpenChange:Ne=>{l(Ne),Ne||ke()},children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{className:"gap-2",children:[e.jsx(an,{className:"h-4 w-4"}),"Add Video"]})}),e.jsxs(Ds,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:o?"Edit Video":"Add New Video"})}),e.jsxs("form",{onSubmit:Fe,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"title",children:"Title *"}),e.jsx(xe,{id:"title",value:d.title,onChange:Ne=>u({...d,title:Ne.target.value}),placeholder:"Video title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Description"}),e.jsx(SN,{content:d.description,onChange:Ne=>u({...d,description:Ne}),placeholder:"Brief description of the video",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Video Type"}),e.jsxs(Ns,{value:d.video_type,onValueChange:Ne=>{u({...d,video_type:Ne,video_url:""}),$(null)},disabled:K,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:qrn.map(Ne=>e.jsx(et,{value:Ne.value,children:Ne.label},Ne.value))})]})]}),d.video_type==="bunny_stream"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs(te,{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(xe,{type:"file",accept:"video/*",onChange:Ne=>{var Ve;const $e=(Ve=Ne.target.files)==null?void 0:Ve[0];$e&&$($e)},disabled:K}),z&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Wr,{className:"h-4 w-4"}),z.name," (",(z.size/(1024*1024)).toFixed(1)," MB)"]}),K&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Et,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Uploading to Bunny.net..."})]}),e.jsx(ro,{value:H,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[H,"%"]})]})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"video_url",children:"Video URL *"}),e.jsx(xe,{id:"video_url",value:d.video_url,onChange:Ne=>u({...d,video_url:Ne.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(te,{htmlFor:"duration",children:"Duration"}),e.jsx(xe,{id:"duration",value:d.duration,onChange:Ne=>u({...d,duration:Ne.target.value}),placeholder:"e.g., 45:30"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"publish_date",children:"Publish Date (go-live)"}),e.jsx(xe,{id:"publish_date",type:"date",value:d.publish_date,onChange:Ne=>u({...d,publish_date:Ne.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(te,{children:"Category"}),I?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:L,onChange:Ne=>M(Ne.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(U,{type:"button",size:"sm",onClick:()=>L.trim()&&ie.mutate(L.trim()),disabled:ie.isPending,children:"Add"}),e.jsx(U,{type:"button",size:"sm",variant:"ghost",onClick:()=>{R(!1),M("")},children:e.jsx(er,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ns,{value:d.category_id,onValueChange:Ne=>u({...d,category_id:Ne}),children:[e.jsx(ws,{className:"flex-1",children:e.jsx(ks,{placeholder:"Select category"})}),e.jsx(js,{children:ue.map(Ne=>e.jsx(et,{value:Ne.id,children:Ne.name},Ne.id))})]}),e.jsx(U,{type:"button",variant:"outline",size:"sm",onClick:()=>R(!0),children:e.jsx(an,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Thumbnail Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[p&&e.jsx("img",{src:p,alt:"Thumbnail preview",className:"w-32 h-20 object-cover rounded-md border"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(xe,{type:"file",accept:"image/*",onChange:Me,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(te,{children:"Resource Files"}),e.jsx(U,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{className:"cursor-pointer gap-1",children:[e.jsx(qa,{className:"h-3 w-3"}),"Add Files",e.jsx("input",{type:"file",multiple:!0,accept:".pdf,.pptx,.ppt,.xlsx,.xls,.docx,.doc,.zip",onChange:Oe,className:"hidden"})]})})]}),(v.length>0||x.length>0)&&e.jsxs("div",{className:"space-y-2 mt-2",children:[v.map(Ne=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(Ur,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm truncate",children:Ne.title}),e.jsx(Be,{variant:"outline",className:"text-xs",children:Ne.file_type}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:()=>Qe(Ne.id),className:"text-destructive hover:text-destructive",children:e.jsx(er,{className:"h-4 w-4"})})]},Ne.id)),x.map((Ne,$e)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(Ur,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:Ne.title,onChange:Ve=>{const qe=[...x];qe[$e].title=Ve.target.value,y(qe)},className:"flex-1 h-8",placeholder:"Resource title"}),e.jsx(Be,{variant:"secondary",className:"text-xs",children:"New"}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:()=>Se($e),className:"text-destructive hover:text-destructive",children:e.jsx(er,{className:"h-4 w-4"})})]},$e))]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Supported: PDF, PowerPoint, Excel, Word, ZIP"})]}),e.jsx(uqt,{selectedTemplateIds:A,onChange:T}),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(wn,{id:"is_published",checked:d.is_published,onCheckedChange:Ne=>u({...d,is_published:Ne})}),e.jsx(te,{htmlFor:"is_published",children:"Published"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.is_published?d.publish_date>ayt?`Scheduled — goes live automatically on ${iyt(d.publish_date)}.`:"Live now for members.":"Draft — hidden from members until you turn this on."})]}),e.jsxs(Mr,{children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>l(!1),disabled:K,children:"Cancel"}),e.jsx(U,{type:"submit",disabled:ce.isPending||K,children:K?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):ce.isPending?"Saving...":o?"Update Video":"Add Video"})]})]})]})]})]}),e.jsx(we,{children:e.jsx(Ie,{className:"p-0",children:ne?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"})}):se.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Wr,{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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Title"}),e.jsx(Lt,{children:"Category"}),e.jsx(Lt,{children:"Duration"}),e.jsx(Lt,{children:"Resources"}),e.jsx(Lt,{children:"Publish Date"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{children:"Public Views"}),e.jsx(Lt,{className:"w-[120px]",children:"Actions"})]})}),e.jsx(Xa,{children:se.map(Ne=>e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Ne.thumbnail_url?e.jsx("img",{src:Ne.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(Wr,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:Ne.title}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:Ne.video_type.replace("_"," ")})]})]})}),e.jsx(gt,{children:Ne.category?e.jsx(Be,{variant:"outline",children:Ne.category.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(gt,{children:Ne.duration||"-"}),e.jsx(gt,{children:Ne.resources&&Ne.resources.length>0?e.jsxs(Be,{variant:"secondary",children:[Ne.resources.length," file(s)"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(gt,{children:iyt(Ne.publish_date)}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wn,{checked:Ne.is_published,onCheckedChange:$e=>be.mutate({id:Ne.id,is_published:$e})}),Ne.is_published?Ne.publish_date.slice(0,10)>ayt?e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(Yr,{className:"h-3 w-3"})," Scheduled"]}):e.jsx(Be,{variant:"secondary",children:"Live"}):e.jsx(Be,{variant:"outline",className:"text-muted-foreground",children:"Draft"})]})}),e.jsx(gt,{children:Ne.is_public?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(xa,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:(Ne.public_view_count||0).toLocaleString()})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(U,{variant:"ghost",size:"sm",title:Ne.is_public?"Copy public teaser link":"Make public & copy teaser link",onClick:()=>he(Ne),children:Ne.is_public?e.jsx(Pa,{className:"h-4 w-4 text-primary"}):e.jsx(jd,{className:"h-4 w-4"})}),Ne.is_public&&e.jsx(U,{variant:"ghost",size:"sm",title:"Disable public link",onClick:()=>ge(Ne),children:e.jsx(fl,{className:"h-4 w-4 text-emerald-500"})}),e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>Te(Ne),children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>je.mutate(Ne.id),className:"text-destructive hover:text-destructive",children:e.jsx(In,{className:"h-4 w-4"})})]})})]},Ne.id))})]})})})]})})},dY=s=>s.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),oyt={public_enabled:!1,public_slug:"",public_headline:"",public_subheadline:"",public_cta_text:"",public_benefits:"",public_hero_image_url:""};function Vrn(){var je,be,he;const s=Qt(),[t,n]=fc(),[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,...oyt}),[d,u]=j.useState(null),[h,m]=j.useState(""),[p,f]=j.useState([]),[x,y]=j.useState([]),[v,b]=j.useState([]),[N,S]=j.useState(null),{data:A,isLoading:T}=ct({queryKey:["resource-kits"],queryFn:async()=>{const{data:ge,error:ke}=await q.from("resource_kits").select("*").order("publish_date",{ascending:!1});if(ke)throw ke;return ge}}),{data:L}=ct({queryKey:["resource-kit-files"],queryFn:async()=>{const{data:ge,error:ke}=await q.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(ke)throw ke;return ge}}),{data:M}=ct({queryKey:["resource-kit-links"],queryFn:async()=>{const{data:ge,error:ke}=await q.from("resource_kit_links").select("*").order("sort_order",{ascending:!0});if(ke)throw ke;return ge}}),{data:I}=ct({queryKey:["resource-kit-leads"],queryFn:async()=>{const{data:ge,error:ke}=await q.from("resource_kit_leads").select("id, kit_id, full_name, email, brokerage, created_at").order("created_at",{ascending:!1}).limit(500);if(ke)throw ke;return ge}});j.useEffect(()=>{const ge=t.get("edit");if(ge&&A&&A.length>0&&L&&M){const ke=A.find(Te=>Te.id===ge);ke&&(z(ke),n({},{replace:!0}))}},[A,L,M,t]);const R=()=>{c({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,...oyt}),u(null),m(""),f([]),y([]),b([]),l(null)},z=async ge=>{l(ge),c({name:ge.name,description:ge.description||"",publish_date:ge.publish_date.split("T")[0],is_published:ge.is_published,public_enabled:!!ge.public_enabled,public_slug:ge.public_slug||"",public_headline:ge.public_headline||"",public_subheadline:ge.public_subheadline||"",public_cta_text:ge.public_cta_text||"",public_benefits:Array.isArray(ge.public_benefits)?ge.public_benefits.join(` `):"",public_hero_image_url:ge.public_hero_image_url||""}),m(ge.featured_image_url||"");const ke=(L==null?void 0:L.filter(Oe=>Oe.kit_id===ge.id))||[];f(ke.map(Oe=>({id:Oe.id,name:Oe.name,file_url:Oe.file_url,file_type:Oe.file_type,file_size:Oe.file_size,sort_order:Oe.sort_order})));const Te=(M==null?void 0:M.filter(Oe=>Oe.kit_id===ge.id))||[];y(Te.map(Oe=>({id:Oe.id,title:Oe.title,canva_share_link:Oe.canva_share_link,sort_order:Oe.sort_order})));const{data:Me}=await q.from("resource_kit_templates").select("template_id").eq("kit_id",ge.id);b((Me||[]).map(Oe=>Oe.template_id)),a(!0)},$=ge=>{var Te;const ke=(Te=ge.target.files)==null?void 0:Te[0];ke&&(u(ke),m(URL.createObjectURL(ke)))},H=()=>{f([...p,{name:"",file_url:"",sort_order:p.length}])},V=ge=>{f(p.filter((ke,Te)=>Te!==ge))},K=(ge,ke,Te)=>{const Me=[...p];Me[ge]={...Me[ge],[ke]:Te},f(Me)},Z=()=>{y([...x,{title:"",canva_share_link:"",sort_order:x.length}])},Q=ge=>{y(x.filter((ke,Te)=>Te!==ge))},le=(ge,ke,Te)=>{const Me=[...x];Me[ge]={...Me[ge],[ke]:Te},y(Me)},ue=(ge,ke)=>{var Me;const Te=(Me=ke.target.files)==null?void 0:Me[0];if(Te){const Oe=[...p],Se=Te.name.replace(/\.[^/.]+$/,"");Oe[ge]={...Oe[ge],file:Te,file_type:Te.type,file_size:Te.size,name:Oe[ge].name||Se},f(Oe)}},se=yt({mutationFn:async()=>{let ge=(i==null?void 0:i.featured_image_url)||null;if(d){const Qe=d.name.split(".").pop(),Ae=`${Date.now()}.${Qe}`,{error:Fe}=await q.storage.from("resource-kits").upload(`featured/${Ae}`,d);if(Fe)throw Fe;const{data:Ne}=q.storage.from("resource-kits").getPublicUrl(`featured/${Ae}`);ge=Ne.publicUrl}const ke=o.public_enabled?o.public_slug?dY(o.public_slug):dY(o.name):o.public_slug?dY(o.public_slug):null,Te={name:o.name,description:o.description||null,featured_image_url:ge,publish_date:o.publish_date,is_published:o.is_published,public_enabled:o.public_enabled,public_slug:ke||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(Qe=>Qe.trim()).filter(Boolean),public_hero_image_url:o.public_hero_image_url||null};let Me;const Oe=!i,Se=(i==null?void 0:i.is_published)||!1;if(i){const{error:Qe}=await q.from("resource_kits").update(Te).eq("id",i.id);if(Qe)throw Qe;Me=i.id;const Ae=(L==null?void 0:L.filter(Ze=>Ze.kit_id===i.id).map(Ze=>Ze.id))||[],Fe=p.filter(Ze=>Ze.id).map(Ze=>Ze.id),Ne=Ae.filter(Ze=>!Fe.includes(Ze));Ne.length>0&&await q.from("resource_kit_files").delete().in("id",Ne);const $e=(M==null?void 0:M.filter(Ze=>Ze.kit_id===i.id).map(Ze=>Ze.id))||[],Ve=x.filter(Ze=>Ze.id).map(Ze=>Ze.id),qe=$e.filter(Ze=>!Ve.includes(Ze));qe.length>0&&await q.from("resource_kit_links").delete().in("id",qe)}else{const{data:Qe,error:Ae}=await q.from("resource_kits").insert(Te).select().single();if(Ae)throw Ae;Me=Qe.id}for(let Qe=0;Qe0){const{error:Qe}=await q.from("resource_kit_templates").insert(v.map(Ae=>({kit_id:Me,template_id:Ae})));if(Qe)throw Qe}return{kitId:Me,kitName:o.name,isNewKit:Oe,wasPublished:Se,isPublished:o.is_published}},onSuccess:ge=>{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"),ge.isPublished&&(ge.isNewKit||!ge.wasPublished)&&Prn(ge.kitName,ge.kitId),a(!1),R()},onError:ge=>{re.error("Failed to save resource kit: "+ge.message)}}),ne=yt({mutationFn:async ge=>{const{error:ke}=await q.from("resource_kits").delete().eq("id",ge);if(ke)throw ke},onSuccess:()=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),re.success("Resource kit deleted")},onError:ge=>{re.error("Failed to delete: "+ge.message)}}),ie=ge=>{if(ge.preventDefault(),!o.name){re.error("Please enter a name");return}se.mutate()},ce=ge=>(L==null?void 0:L.filter(ke=>ke.kit_id===ge).length)||0;return e.jsx(qs,{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(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{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(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{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(ge=>ge.is_published).length)||0})})]})]}),e.jsxs(U,{onClick:()=>{R(),a(!0)},children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Add Resource Kit"]})]}),e.jsx(we,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Name"}),e.jsx(Lt,{children:"Files"}),e.jsx(Lt,{children:"Publish Date"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:T?e.jsx(gn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):(A==null?void 0:A.length)===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No resource kits yet. Create your first one!"})}):A==null?void 0:A.map(ge=>e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[ge.featured_image_url?e.jsx("img",{src:ge.featured_image_url,alt:ge.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(dh,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ge.name}),ge.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:ge.description})]})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ur,{className:"h-4 w-4 text-muted-foreground"}),ce(ge.id)]})}),e.jsx(gt,{children:Gs(new Date(ge.publish_date),"MMM d, yyyy")}),e.jsx(gt,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${ge.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:ge.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[ge.public_enabled&&ge.public_slug&&e.jsx(U,{variant:"ghost",size:"icon",title:"Copy public landing page link",onClick:()=>{navigator.clipboard.writeText(`${window.location.origin}/resources/${ge.public_slug}`),re.success("Public link copied")},children:e.jsx(fl,{className:"h-4 w-4 text-emerald-600"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>{const ke=(L==null?void 0:L.filter(Me=>Me.kit_id===ge.id))||[],Te=(M==null?void 0:M.filter(Me=>Me.kit_id===ge.id))||[];S({...ge,files:ke,links:Te})},children:e.jsx(xa,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>z(ge),children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:async()=>{await Yi("Delete this resource kit?")&&ne.mutate(ge.id)},children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]})})]},ge.id))})]})})}),e.jsxs(we,{className:"mt-6",children:[e.jsx(Tt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-5 w-5"}),"Public Resource Leads",e.jsxs("span",{className:"text-sm font-normal text-muted-foreground",children:["(",(I==null?void 0:I.length)||0,")"]})]})}),e.jsx(Ie,{children:!I||I.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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Agent"}),e.jsx(Lt,{children:"Email"}),e.jsx(Lt,{children:"Brokerage"}),e.jsx(Lt,{children:"Resource"}),e.jsx(Lt,{children:"Captured"})]})}),e.jsx(Xa,{children:I.map(ge=>{var ke;return e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium",children:ge.full_name}),e.jsx(gt,{children:ge.email}),e.jsx(gt,{children:ge.brokerage||"—"}),e.jsx(gt,{children:((ke=A==null?void 0:A.find(Te=>Te.id===ge.kit_id))==null?void 0:ke.name)||"—"}),e.jsx(gt,{children:Gs(new Date(ge.created_at),"MMM d, yyyy")})]},ge.id)})})]})})]}),e.jsx(zs,{open:r,onOpenChange:a,children:e.jsxs(Ds,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:i?"Edit Resource Kit":"Add Resource Kit"})}),e.jsxs("form",{onSubmit:ie,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{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(dh,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(xe,{type:"file",accept:"image/*",onChange:$})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"name",children:"Name *"}),e.jsx(xe,{id:"name",value:o.name,onChange:ge=>c({...o,name:ge.target.value}),placeholder:"Resource Kit Name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Description"}),e.jsx(SN,{content:o.description,onChange:ge=>c({...o,description:ge}),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(te,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(xe,{id:"publish_date",type:"date",value:o.publish_date,onChange:ge=>c({...o,publish_date:ge.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(wn,{checked:o.is_published,onCheckedChange:ge=>c({...o,is_published:ge})}),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(te,{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(wn,{checked:o.public_enabled,onCheckedChange:ge=>c({...o,public_enabled:ge,public_slug:o.public_slug||dY(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(te,{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(xe,{value:o.public_slug,onChange:ge=>c({...o,public_slug:ge.target.value}),placeholder:"listing-checklist"}),e.jsxs(U,{type:"button",variant:"outline",onClick:()=>{const ge=dY(o.public_slug||o.name);navigator.clipboard.writeText(`${window.location.origin}/resources/${ge}`),re.success("Public link copied")},children:[e.jsx(Rc,{className:"h-4 w-4 mr-1"})," Copy"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Headline"}),e.jsx(xe,{value:o.public_headline,onChange:ge=>c({...o,public_headline:ge.target.value}),placeholder:o.name||"The Ultimate Listing Checklist"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Subheadline"}),e.jsx(xe,{value:o.public_subheadline,onChange:ge=>c({...o,public_subheadline:ge.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(te,{children:"Button text"}),e.jsx(xe,{value:o.public_cta_text,onChange:ge=>c({...o,public_cta_text:ge.target.value}),placeholder:"Get Instant Access"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Hero image URL (optional)"}),e.jsx(xe,{value:o.public_hero_image_url,onChange:ge=>c({...o,public_hero_image_url:ge.target.value}),placeholder:"Defaults to featured image"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Benefit bullets (one per line)"}),e.jsx("textarea",{value:o.public_benefits,onChange:ge=>c({...o,public_benefits:ge.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(te,{children:"Resource Files"}),e.jsxs(U,{type:"button",variant:"outline",size:"sm",onClick:H,children:[e.jsx(an,{className:"h-4 w-4 mr-1"}),"Add File"]})]}),p.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:p.map((ge,ke)=>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 ",ke+1]}),e.jsx(U,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>V(ke),children:e.jsx(er,{className:"h-4 w-4"})})]}),e.jsx(xe,{placeholder:"File name (e.g., Getting Started Guide)",value:ge.name,onChange:Te=>K(ke,"name",Te.target.value)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"file",onChange:Te=>ue(ke,Te),className:"flex-1"}),ge.file_url&&!ge.file&&e.jsx("a",{href:ge.file_url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-primary hover:underline whitespace-nowrap",children:"Current file"}),ge.file&&e.jsx("span",{className:"text-sm text-green-600 whitespace-nowrap",children:"New file selected"})]})]},ke))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(te,{children:"Canva Links"}),e.jsxs(U,{type:"button",variant:"outline",size:"sm",onClick:Z,children:[e.jsx(an,{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((ge,ke)=>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 ",ke+1]}),e.jsx(U,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>Q(ke),children:e.jsx(er,{className:"h-4 w-4"})})]}),e.jsx(xe,{placeholder:"Link title (e.g., Social Media Post Template)",value:ge.title,onChange:Te=>le(ke,"title",Te.target.value)}),e.jsx(xe,{placeholder:"Canva share link (e.g., https://www.canva.com/design/...)",value:ge.canva_share_link,onChange:Te=>le(ke,"canva_share_link",Te.target.value)})]},ke))})]}),e.jsx(uqt,{selectedTemplateIds:v,onChange:b}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(U,{type:"submit",disabled:se.isPending,children:se.isPending?"Saving...":i?"Update":"Create"})]})]})]})}),e.jsx(zs,{open:!!N,onOpenChange:()=>S(null),children:e.jsxs(Ds,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsx($s,{children:N==null?void 0:N.name})}),e.jsxs("div",{className:"space-y-4",children:[(N==null?void 0:N.featured_image_url)&&e.jsx("img",{src:N.featured_image_url,alt:N.name,className:"w-full h-48 object-cover rounded-lg"}),(N==null?void 0:N.description)&&e.jsx("p",{className:"text-muted-foreground",children:N.description}),e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Resource Files (",((je=N==null?void 0:N.files)==null?void 0:je.length)||0,")"]}),((be=N==null?void 0:N.files)==null?void 0:be.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:(he=N==null?void 0:N.files)==null?void 0:he.map(ge=>e.jsxs("a",{href:ge.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(Ur,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:ge.name})]},ge.id))})]}),(N==null?void 0:N.links)&&N.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Canva Links (",N.links.length,")"]}),e.jsx("div",{className:"space-y-2",children:N.links.map(ge=>e.jsxs("a",{href:ge.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(Rc,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:ge.title})]},ge.id))})]})]})]})})]})})}const Hrn=()=>{const{user:s}=vs(),{toast:t}=Ai(),n=Qt(),[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:p=[],isLoading:f}=ct({queryKey:["social-swag-admin"],queryFn:async()=>{const{data:M,error:I}=await q.from("social_swag").select("*").order("publish_date",{ascending:!1});if(I)throw I;const{data:R,error:z}=await q.from("social_swag_links").select("*").order("sort_order");if(z)throw z;return M.map(H=>({...H,links:(R==null?void 0:R.filter(V=>V.swag_id===H.id))||[]}))}}),x=yt({mutationFn:async M=>{let I=M.existingImageUrl;if(M.image){const K=M.image.name.split(".").pop(),Z=`${Date.now()}-${Math.random().toString(36).substring(7)}.${K}`,{error:Q}=await q.storage.from("template-previews").upload(Z,M.image);if(Q)throw Q;const{data:le}=q.storage.from("template-previews").getPublicUrl(Z);I=le.publicUrl}const R={title:M.item.title,description:M.item.description||null,preview_image_url:I,publish_date:M.item.publish_date?new Date(M.item.publish_date).toISOString():new Date().toISOString(),is_published:M.item.is_published,created_by:s==null?void 0:s.id};let z=M.itemId;const $=!z,H=(i==null?void 0:i.is_published)||!1;if(z){const{error:K}=await q.from("social_swag").update(R).eq("id",z);if(K)throw K;await q.from("social_swag_links").delete().eq("swag_id",z)}else{const{data:K,error:Z}=await q.from("social_swag").insert(R).select().single();if(Z)throw Z;z=K.id}const V=M.item.links.filter(K=>K.title.trim()&&K.canva_share_link.trim());if(V.length>0){const K=V.map((Q,le)=>({swag_id:z,title:Q.title.trim(),canva_share_link:Q.canva_share_link.trim(),sort_order:le})),{error:Z}=await q.from("social_swag_links").insert(K);if(Z)throw Z}return{itemId:z,itemTitle:M.item.title,isNewItem:$,wasPublished:H,isPublished:M.item.is_published}},onSuccess:M=>{n.invalidateQueries({queryKey:["social-swag-admin"]}),n.invalidateQueries({queryKey:["social-swag"]}),t({title:i?"Item updated":"Item created"}),M.isPublished&&(M.isNewItem||!M.wasPublished)&&cVe(M.itemTitle,M.itemId),a(!1),v()},onError:M=>{t({title:"Error saving item",description:M.message,variant:"destructive"})}}),y=yt({mutationFn:async M=>{const{error:I}=await q.from("social_swag").delete().eq("id",M);if(I)throw I},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-admin"]}),n.invalidateQueries({queryKey:["social-swag"]}),t({title:"Item deleted"})},onError:M=>{t({title:"Error deleting item",description:M.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=M=>{l(M),c({title:M.title,description:M.description||"",publish_date:M.publish_date?new Date(M.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:M.is_published,links:M.links&&M.links.length>0?M.links.map(I=>({id:I.id,title:I.title,canva_share_link:I.canva_share_link,sort_order:I.sort_order})):[{title:"",canva_share_link:"",sort_order:0}]}),m(M.preview_image_url||""),a(!0)},N=M=>{var R;const I=(R=M.target.files)==null?void 0:R[0];I&&(u(I),m(URL.createObjectURL(I)))},S=()=>{c({...o,links:[...o.links,{title:"",canva_share_link:"",sort_order:o.links.length}]})},A=M=>{if(o.links.length<=1)return;const I=o.links.filter((R,z)=>z!==M);c({...o,links:I})},T=(M,I,R)=>{const z=[...o.links];z[M]={...z[M],[I]:R},c({...o,links:z})},L=M=>{if(M.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(qs,{title:"Manage Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{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(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Total Items"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.length})})]}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.filter(M=>M.is_published).length})})]})]}),e.jsxs(zs,{open:r,onOpenChange:M=>{a(M),M||v()},children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{className:"gap-2",children:[e.jsx(an,{className:"h-4 w-4"}),"Add Item"]})}),e.jsxs(Ds,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:i?"Edit Item":"Add New Item"})}),e.jsxs("form",{onSubmit:L,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"title",children:"Title *"}),e.jsx(xe,{id:"title",value:o.title,onChange:M=>c({...o,title:M.target.value}),placeholder:"Enter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Description"}),e.jsx(SN,{content:o.description,onChange:M=>c({...o,description:M}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(xe,{id:"publish_date",type:"date",value:o.publish_date,onChange:M=>c({...o,publish_date:M.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(wn,{id:"is_published",checked:o.is_published,onCheckedChange:M=>c({...o,is_published:M})}),e.jsx(te,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{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(U,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),m("")},children:e.jsx(er,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(pc,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(xe,{type:"file",accept:"image/*",onChange:N,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{children:"Canva Links"}),e.jsxs(U,{type:"button",variant:"outline",size:"sm",onClick:S,children:[e.jsx(an,{className:"h-3 w-3 mr-1"}),"Add Link"]})]}),o.links.map((M,I)=>e.jsx(we,{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 ",I+1]}),o.links.length>1&&e.jsx(U,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>A(I),children:e.jsx(er,{className:"h-3 w-3"})})]}),e.jsx(xe,{placeholder:"Link title (e.g., Instagram Post)",value:M.title,onChange:R=>T(I,"title",R.target.value)}),e.jsx(xe,{placeholder:"Canva share link",value:M.canva_share_link,onChange:R=>T(I,"canva_share_link",R.target.value)})]})},I))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(U,{type:"submit",disabled:x.isPending,children:x.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(we,{children:e.jsx(Ie,{className:"p-0",children:f?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"})}):p.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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{className:"w-16",children:"Preview"}),e.jsx(Lt,{children:"Title"}),e.jsx(Lt,{children:"Links"}),e.jsx(Lt,{children:"Publish Date"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:p.map(M=>{var I;return e.jsxs(gn,{children:[e.jsx(gt,{children:M.preview_image_url?e.jsx("img",{src:M.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(pc,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(gt,{className:"font-medium",children:M.title}),e.jsxs(gt,{children:[((I=M.links)==null?void 0:I.length)||0," links"]}),e.jsx(gt,{children:new Date(M.publish_date).toLocaleDateString()}),e.jsx(gt,{children:e.jsx(Be,{variant:M.is_published?"default":"secondary",children:M.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>window.open(`/social-swag/${M.id}`,"_blank"),children:e.jsx(xa,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>b(M),children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:async()=>{await Yi("Are you sure you want to delete this item?")&&y.mutate(M.id)},children:e.jsx(In,{className:"h-4 w-4"})})]})})]},M.id)})})]})})})]})})};function Grn({item:s,onEdit:t,onDelete:n,onDateChange:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=QMe({id:s.id}),u={transform:pP.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(we,{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(kf,{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(U,{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(ri,{className:"h-3.5 w-3.5"})}),e.jsx(U,{variant:"destructive",size:"icon",className:"h-7 w-7",onClick:()=>n(s),children:e.jsx(In,{className:"h-3.5 w-3.5"})})]}),s.post_date&&e.jsx("div",{className:"absolute bottom-2 left-2",children:e.jsxs(Be,{className:"bg-primary/90 text-primary-foreground text-[10px] gap-1 backdrop-blur-sm px-1.5 py-0.5",children:[e.jsx(pa,{className:"h-2.5 w-2.5"}),Gs(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(md,{children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{variant:"outline",size:"sm",className:Mt("w-full h-7 text-[11px] gap-1 justify-start font-normal",!s.post_date&&"text-muted-foreground"),children:[e.jsx(pa,{className:"h-3 w-3"}),s.post_date?Gs(new Date(s.post_date+"T00:00:00"),"MMM d, yyyy"):"Set post date"]})}),e.jsxs(id,{className:"w-auto p-0",align:"start",children:[e.jsx(yj,{mode:"single",selected:s.post_date?new Date(s.post_date+"T00:00:00"):void 0,onSelect:h=>r(s.id,h?Gs(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(U,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>r(s.id,null),children:"Clear date"})})]})]})]})]})})}const Wrn=()=>{const s=Qt(),[t,n]=j.useState("all"),[r,a]=j.useState(!1),[i,l]=j.useState(Gs(new Date,"yyyy-MM")),[o,c]=j.useState([]),[d,u]=j.useState(!1),[h,m]=j.useState(null),[p,f]=j.useState(null),[x,y]=j.useState(""),[v,b]=j.useState(null),[N,S]=j.useState(!1),[A,T]=j.useState(!1),[L,M]=j.useState(Gs(new Date,"yyyy-MM")),[I,R]=j.useState(null),[z,$]=j.useState(""),[H,V]=j.useState(""),[K,Z]=j.useState(""),[Q,le]=j.useState(!1),ue=$Me(HV(SG,{activationConstraint:{distance:5}}),HV(GMe,{coordinateGetter:FFt})),{data:se=[],isLoading:ne}=ct({queryKey:["admin-social-swag-2"],queryFn:async()=>{const{data:Ge,error:He}=await q.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(He)throw He;return Ge}}),{data:ie=[]}=ct({queryKey:["admin-social-swag-2-months"],queryFn:async()=>{const{data:Ge,error:He}=await q.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(He)throw He;return Ge}}),{data:ce=[]}=ct({queryKey:["admin-social-swag-2-reels"],queryFn:async()=>{const{data:Ge,error:He}=await q.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(He)throw He;return Ge}}),je=[...new Set(se.map(Ge=>Ge.month))].sort((Ge,He)=>He.localeCompare(Ge)),be=t==="all"?se:se.filter(Ge=>Ge.month===t),he=Ge=>{const He=NXe(Ge,"yyyy-MM",new Date);return Gs(He,"MMMM yyyy")},ge=Ge=>{f(Ge),y(Ge.caption),b(Ge.post_date)},ke=async()=>{if(p){S(!0);try{const{error:Ge}=await q.from("social_swag_2").update({caption:x,post_date:v}).eq("id",p.id);if(Ge)throw Ge;re.success("Image updated"),f(null),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})}catch{re.error("Failed to update image")}finally{S(!1)}}},Te=async Ge=>{const{active:He,over:tt}=Ge;if(!tt||He.id===tt.id)return;const pt=be,ft=pt.findIndex(Wt=>Wt.id===He.id),qt=pt.findIndex(Wt=>Wt.id===tt.id);if(ft===-1||qt===-1)return;const Ut=ZMe(pt,ft,qt);s.setQueryData(["admin-social-swag-2"],Wt=>{if(!Wt)return Wt;const us={};return Ut.forEach((zt,bt)=>{us[zt.id]=bt}),Wt.map(zt=>us[zt.id]!==void 0?{...zt,sort_order:us[zt.id]}:zt).sort((zt,bt)=>zt.month!==bt.month?bt.month.localeCompare(zt.month):zt.sort_order-bt.sort_order)});try{await Promise.all(Ut.map((Wt,us)=>q.from("social_swag_2").update({sort_order:us}).eq("id",Wt.id)))}catch{re.error("Failed to save order"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})}},Me=Ge=>{const tt=Array.from(Ge.target.files||[]).sort((pt,ft)=>pt.name.localeCompare(ft.name,void 0,{numeric:!0,sensitivity:"base"})).slice(0,16-o.length).map(pt=>({file:pt,preview:URL.createObjectURL(pt),caption:""}));c(pt=>[...pt,...tt].slice(0,16))},Oe=Ge=>{c(He=>{const tt=[...He];return URL.revokeObjectURL(tt[Ge].preview),tt.splice(Ge,1),tt})},Se=(Ge,He)=>{c(tt=>{const pt=[...tt];return pt[Ge]={...pt[Ge],caption:He},pt})},Qe=async()=>{var He;if(o.length===0){re.error("Please add at least one image");return}if(o.filter(tt=>!tt.caption.trim()).length>0){re.error("Please add captions to all images");return}u(!0);try{const{data:tt}=await q.from("social_swag_2").select("sort_order").eq("month",i).order("sort_order",{ascending:!1}).limit(1),pt=(((He=tt==null?void 0:tt[0])==null?void 0:He.sort_order)??-1)+1;for(let ft=0;ft{const He=Ge.image_url.split("/social-swag-2/");He[1]&&await q.storage.from("social-swag-2").remove([He[1]]);const{error:tt}=await q.from("social_swag_2").delete().eq("id",Ge.id);if(tt)throw tt},onSuccess:()=>{re.success("Image deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})},onError:()=>re.error("Failed to delete image")}),Fe=yt({mutationFn:async({id:Ge,postDate:He})=>{const{error:tt}=await q.from("social_swag_2").update({post_date:He}).eq("id",Ge);if(tt)throw tt},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")}),Ne=yt({mutationFn:async({month:Ge,link:He})=>{const{error:tt}=await q.from("social_swag_2_months").upsert({month:Ge,canva_link:He||null},{onConflict:"month"});if(tt)throw tt},onSuccess:()=>{re.success("Canva link updated"),m(null),s.invalidateQueries({queryKey:["admin-social-swag-2-months"]})},onError:()=>re.error("Failed to update Canva link")}),$e=Ge=>{var He;return((He=ie.find(tt=>tt.month===Ge))==null?void 0:He.canva_link)||""},Ve=Ge=>ce.find(He=>He.month===Ge)||null,qe=Ge=>{var tt;const He=(tt=Ge.target.files)==null?void 0:tt[0];He&&(R(He),$(URL.createObjectURL(He)))},Ze=()=>{z&&URL.revokeObjectURL(z),R(null),$(""),V(""),Z("")},Ue=async()=>{if(!I){re.error("Please select an image");return}le(!0);try{const Ge=I.name.split(".").pop(),He=`reels/${L}-${Date.now()}.${Ge}`,{error:tt}=await q.storage.from("social-swag-2").upload(He,I);if(tt)throw tt;const{data:{publicUrl:pt}}=q.storage.from("social-swag-2").getPublicUrl(He),{error:ft}=await q.from("social_swag_2_reels").upsert({month:L,image_url:pt,canva_link:K||null,caption:H||null},{onConflict:"month"});if(ft)throw ft;re.success("Reel uploaded successfully!"),cVe(`${he(L)} Reel`,"social-swag-2"),Ze(),T(!1),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})}catch(Ge){console.error("Reel upload error:",Ge),re.error("Failed to upload reel")}finally{le(!1)}},Ye=yt({mutationFn:async Ge=>{const He=Ge.image_url.split("/social-swag-2/");He[1]&&await q.storage.from("social-swag-2").remove([He[1]]);const{error:tt}=await q.from("social_swag_2_reels").delete().eq("id",Ge.id);if(tt)throw tt},onSuccess:()=>{re.success("Reel deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})},onError:()=>re.error("Failed to delete reel")});return e.jsxs(qs,{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(al,{asChild:!0,children:e.jsxs(U,{className:"gap-2",children:[e.jsx(an,{className:"h-4 w-4"}),"Upload Images"]})}),e.jsxs(Ds,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Upload Social Swag Images"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Month"}),e.jsx(xe,{type:"month",value:i,onChange:Ge=>l(Ge.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{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:Me,className:"hidden",id:"swag-upload",disabled:o.length>=16}),e.jsxs("label",{htmlFor:"swag-upload",className:"cursor-pointer",children:[e.jsx(qa,{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((Ge,He)=>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:Ge.preview,alt:`Upload ${He+1}`,className:"w-full h-full object-cover"}),e.jsx(U,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>Oe(He),children:e.jsx(er,{className:"h-3 w-3"})})]}),e.jsx(Fs,{placeholder:"Caption...",value:Ge.caption,onChange:tt=>Se(He,tt.target.value),className:"text-xs h-20"})]},He))}),e.jsx(U,{onClick:Qe,disabled:d||o.length===0,className:"w-full gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qa,{className:"h-4 w-4"}),"Upload ",o.length," Images"]})})]})]})]}),e.jsxs(zs,{open:A,onOpenChange:Ge=>{T(Ge),Ge||Ze()},children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{variant:"outline",className:"gap-2",children:[e.jsx(Gh,{className:"h-4 w-4"}),"Upload Reel"]})}),e.jsxs(Ds,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Upload Monthly Reel"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Month"}),e.jsx(xe,{type:"month",value:L,onChange:Ge=>M(Ge.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Reel Preview Image"}),z?e.jsxs("div",{className:"relative aspect-[9/16] max-w-[120px] mx-auto rounded-lg overflow-hidden bg-muted",children:[e.jsx("img",{src:z,alt:"Reel preview",className:"w-full h-full object-cover"}),e.jsx(U,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{URL.revokeObjectURL(z),R(null),$("")},children:e.jsx(er,{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(Gh,{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(te,{children:"Canva Download Link"}),e.jsx(xe,{value:K,onChange:Ge=>Z(Ge.target.value),placeholder:"https://www.canva.com/..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Caption"}),e.jsx(Fs,{value:H,onChange:Ge=>V(Ge.target.value),placeholder:"Enter caption for this reel...",className:"h-24"})]}),e.jsx(U,{onClick:Ue,disabled:Q||!I,className:"w-full gap-2",children:Q?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qa,{className:"h-4 w-4"}),"Upload Reel"]})})]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(we,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:se.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total Images"})]})}),e.jsx(we,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:je.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Months"})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(oa,{value:t,onValueChange:n,children:e.jsxs(la,{children:[e.jsx(Kt,{value:"all",children:"All"}),je.map(Ge=>e.jsx(Kt,{value:Ge,children:he(Ge)},Ge))]})}),t!=="all"&&e.jsx(we,{children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Rc,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(te,{className:"text-sm text-muted-foreground",children:["Canva Edit Link for ",he(t)]}),(h==null?void 0:h.month)===t?e.jsxs("div",{className:"flex gap-2 mt-1",children:[e.jsx(xe,{value:h.link,onChange:Ge=>m({...h,link:Ge.target.value}),placeholder:"https://www.canva.com/..."}),e.jsx(U,{size:"sm",onClick:()=>Ne.mutate(h),children:"Save"}),e.jsx(U,{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:$e(t)||"No link set"}),e.jsx(U,{size:"sm",variant:"outline",onClick:()=>m({month:t,link:$e(t)}),children:"Edit"})]})]})]})})}),t!=="all"&&e.jsx(we,{children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Gh,{className:"h-4 w-4 text-muted-foreground mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(te,{className:"text-sm text-muted-foreground",children:["Reel for ",he(t)]}),(()=>{const Ge=Ve(t);return Ge?e.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[e.jsx("img",{src:Ge.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:Ge.caption||"No caption"}),Ge.canva_link&&e.jsx("a",{href:Ge.canva_link,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-xs",children:"View Canva Link"})]}),e.jsx(U,{variant:"destructive",size:"sm",onClick:()=>Ye.mutate(Ge),children:e.jsx(In,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"No reel uploaded for this month"})})()]})]})})})]}),ne?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):be.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(pc,{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(YMe,{sensors:ue,collisionDetection:VMe,onDragEnd:Te,children:e.jsx(XMe,{items:be.map(Ge=>Ge.id),strategy:lre,children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:be.map(Ge=>e.jsx(Grn,{item:Ge,onEdit:ge,onDelete:He=>Ae.mutate(He),onDateChange:(He,tt)=>Fe.mutate({id:He,postDate:tt})},Ge.id))})})})]}),e.jsx(zs,{open:!!p,onOpenChange:Ge=>{Ge||f(null)},children:e.jsxs(Ds,{className:"max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Edit Image"})}),p&&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:p.image_url,alt:"Preview",className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Caption"}),e.jsx(Fs,{value:x,onChange:Ge=>y(Ge.target.value),placeholder:"Enter caption...",className:"h-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Post Date"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs(md,{children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{variant:"outline",className:Mt("flex-1 justify-start gap-2 font-normal",!v&&"text-muted-foreground"),children:[e.jsx(pa,{className:"h-4 w-4"}),v?Gs(new Date(v+"T00:00:00"),"MMM d, yyyy"):"Pick a date"]})}),e.jsx(id,{className:"w-auto p-0",align:"start",children:e.jsx(yj,{mode:"single",selected:v?new Date(v+"T00:00:00"):void 0,onSelect:Ge=>b(Ge?Gs(Ge,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"})})]}),v&&e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>b(null),children:e.jsx(er,{className:"h-4 w-4"})})]})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>f(null),children:"Cancel"}),e.jsx(U,{onClick:ke,disabled:N,className:"gap-2",children:N?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 animate-spin"}),"Saving..."]}):"Save Changes"})]})]})})]})},Krn=()=>{const{toast:s}=Ai(),t=Qt(),[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,p]=j.useState(null),[f,x]=j.useState({name:"",description:"",icon:""}),[y,v]=j.useState(!1),[b,N]=j.useState(null),[S,A]=j.useState(""),{data:T=[],isLoading:L}=ct({queryKey:["admin-community-categories"],queryFn:async()=>{const{data:Te,error:Me}=await q.from("community_categories").select("*").order("sort_order");if(Me)throw Me;return Te}}),{data:M=[],isLoading:I}=ct({queryKey:["admin-private-groups"],queryFn:async()=>{const{data:Te,error:Me}=await q.from("community_private_groups").select("*").order("sort_order");if(Me)throw Me;return Te}}),{data:R=[]}=ct({queryKey:["admin-group-members",b==null?void 0:b.id],queryFn:async()=>{if(!b)return[];const{data:Te,error:Me}=await q.from("community_private_group_members").select("*").eq("group_id",b.id);if(Me)throw Me;return Te},enabled:!!b}),{data:z=[]}=ct({queryKey:["admin-all-profiles"],queryFn:async()=>{let Me=[],Oe=0,Se=!0;for(;Se;){const{data:Qe,error:Ae}=await q.from("profiles").select("id, name, email, brokerage_id").order("name").range(Oe,Oe+1e3-1);if(Ae)throw Ae;Qe&&Qe.length>0?(Me=[...Me,...Qe],Oe+=1e3,Se=Qe.length===1e3):Se=!1}return Me}}),{data:$=[]}=ct({queryKey:["admin-all-brokerages"],queryFn:async()=>{const{data:Te,error:Me}=await q.from("brokerages").select("*").order("name");if(Me)throw Me;return Te}}),H=yt({mutationFn:async Te=>{if(Te.id){const{error:Me}=await q.from("community_categories").update({name:Te.name,description:Te.description||null,icon:Te.icon||null}).eq("id",Te.id);if(Me)throw Me}else{const Me=Math.max(...T.map(Se=>Se.sort_order),0),{error:Oe}=await q.from("community_categories").insert({name:Te.name,description:Te.description||null,icon:Te.icon||null,sort_order:Me+1});if(Oe)throw Oe}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),i(!1),o(null),d({name:"",description:"",icon:""}),s({title:l?"Category updated!":"Category created!"})},onError:Te=>{s({title:"Error",description:Te.message,variant:"destructive"})}}),V=yt({mutationFn:async Te=>{const{error:Me}=await q.from("community_categories").delete().eq("id",Te);if(Me)throw Me},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),s({title:"Category deleted"})}}),K=yt({mutationFn:async({id:Te,direction:Me})=>{const Oe=T.findIndex(Se=>Se.id===Te);if(Me==="up"&&Oe>0){const Se=T[Oe-1],Qe=T[Oe];await q.from("community_categories").update({sort_order:Qe.sort_order}).eq("id",Se.id),await q.from("community_categories").update({sort_order:Se.sort_order}).eq("id",Qe.id)}else if(Me==="down"&&Oet.invalidateQueries({queryKey:["admin-community-categories"]})}),Z=yt({mutationFn:async Te=>{if(Te.id){const{error:Me}=await q.from("community_private_groups").update({name:Te.name,description:Te.description||null,icon:Te.icon||null}).eq("id",Te.id);if(Me)throw Me}else{const Me=Math.max(...M.map(Se=>Se.sort_order),0),{error:Oe}=await q.from("community_private_groups").insert({name:Te.name,description:Te.description||null,icon:Te.icon||null,sort_order:Me+1});if(Oe)throw Oe}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),h(!1),p(null),x({name:"",description:"",icon:""}),s({title:m?"Private group updated!":"Private group created!"})},onError:Te=>{s({title:"Error",description:Te.message,variant:"destructive"})}}),Q=yt({mutationFn:async Te=>{const{error:Me}=await q.from("community_private_groups").delete().eq("id",Te);if(Me)throw Me},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),s({title:"Private group deleted"})}}),le=yt({mutationFn:async({id:Te,direction:Me})=>{const Oe=M.findIndex(Se=>Se.id===Te);if(Me==="up"&&Oe>0){const Se=M[Oe-1],Qe=M[Oe];await q.from("community_private_groups").update({sort_order:Qe.sort_order}).eq("id",Se.id),await q.from("community_private_groups").update({sort_order:Se.sort_order}).eq("id",Qe.id)}else if(Me==="down"&&Oet.invalidateQueries({queryKey:["admin-private-groups"]})}),ue=yt({mutationFn:async({groupId:Te,userId:Me,isMember:Oe})=>{if(Oe){const{error:Se}=await q.from("community_private_group_members").delete().eq("group_id",Te).eq("user_id",Me);if(Se)throw Se}else{const{error:Se}=await q.from("community_private_group_members").insert({group_id:Te,user_id:Me});if(Se)throw Se}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",b==null?void 0:b.id]})}}),se=yt({mutationFn:async({groupId:Te,brokerageId:Me,isMember:Oe})=>{if(Oe){const{error:Se}=await q.from("community_private_group_members").delete().eq("group_id",Te).eq("brokerage_id",Me);if(Se)throw Se}else{const{error:Se}=await q.from("community_private_group_members").insert({group_id:Te,brokerage_id:Me});if(Se)throw Se}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",b==null?void 0:b.id]})}}),ne=Te=>{o(Te),d({name:Te.name,description:Te.description||"",icon:Te.icon||""}),i(!0)},ie=()=>{o(null),d({name:"",description:"",icon:""}),i(!0)},ce=Te=>{p(Te),x({name:Te.name,description:Te.description||"",icon:Te.icon||""}),h(!0)},je=()=>{p(null),x({name:"",description:"",icon:""}),h(!0)},be=Te=>{N(Te),A(""),v(!0)},he=Te=>R.some(Me=>Me.user_id===Te),ge=Te=>R.some(Me=>Me.brokerage_id===Te),ke=z.filter(Te=>Te.name.toLowerCase().includes(S.toLowerCase())||Te.email.toLowerCase().includes(S.toLowerCase()));return e.jsx(qs,{title:"Community Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{title:"Community Management",description:"Manage categories and private groups for community discussions"}),e.jsxs(oa,{value:n,onValueChange:r,children:[e.jsxs(la,{children:[e.jsx(Kt,{value:"categories",children:"Public Categories"}),e.jsxs(Kt,{value:"private-groups",children:[e.jsx(Ql,{className:"h-4 w-4 mr-1"}),"Private Groups"]})]}),e.jsxs(Zt,{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(U,{onClick:ie,children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(we,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{className:"w-[50px]",children:"Order"}),e.jsx(Lt,{className:"w-[80px]",children:"Icon"}),e.jsx(Lt,{children:"Name"}),e.jsx(Lt,{children:"Description"}),e.jsx(Lt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(Xa,{children:L?e.jsx(gn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):T.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first one!"})}):T.map((Te,Me)=>e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(U,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Me===0,onClick:()=>K.mutate({id:Te.id,direction:"up"}),children:"↑"}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Me===T.length-1,onClick:()=>K.mutate({id:Te.id,direction:"down"}),children:"↓"})]})}),e.jsx(gt,{className:"text-2xl",children:Te.icon||"📁"}),e.jsx(gt,{className:"font-medium",children:Te.name}),e.jsx(gt,{className:"text-muted-foreground",children:Te.description||"—"}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>ne(Te),children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",className:"text-destructive",onClick:async()=>{await Yi("Delete this category? Posts will be uncategorized.")&&V.mutate(Te.id)},children:e.jsx(In,{className:"h-4 w-4"})})]})})]},Te.id))})]})})})]}),e.jsxs(Zt,{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(_i,{className:"h-3 w-3"}),"Brokerage groups are created automatically and sync with brokerage names"]})]}),e.jsxs(U,{onClick:je,children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Add Private Group"]})]}),e.jsx(we,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{className:"w-[50px]",children:"Order"}),e.jsx(Lt,{className:"w-[80px]",children:"Icon"}),e.jsx(Lt,{children:"Name"}),e.jsx(Lt,{children:"Description"}),e.jsx(Lt,{className:"w-[120px]",children:"Members"}),e.jsx(Lt,{className:"w-[140px]",children:"Actions"})]})}),e.jsx(Xa,{children:I?e.jsx(gn,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):M.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No private groups yet. Create your first one!"})}):M.map((Te,Me)=>e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(U,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Me===0,onClick:()=>le.mutate({id:Te.id,direction:"up"}),children:"↑"}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Me===M.length-1,onClick:()=>le.mutate({id:Te.id,direction:"down"}),children:"↓"})]})}),e.jsx(gt,{className:"text-2xl",children:Te.icon||"🔒"}),e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Te.name,Te.brokerage_id?e.jsxs(Be,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:[e.jsx(_i,{className:"h-3 w-3 mr-1"}),"Auto-managed"]}):e.jsxs(Be,{variant:"secondary",className:"text-xs",children:[e.jsx(Ql,{className:"h-3 w-3 mr-1"}),"Private"]})]})}),e.jsx(gt,{className:"text-muted-foreground",children:Te.description||"—"}),e.jsx(gt,{children:e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>be(Te),children:[e.jsx(Bn,{className:"h-4 w-4 mr-1"}),"Manage"]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1",children:[!Te.brokerage_id&&e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>ce(Te),children:e.jsx(ri,{className:"h-4 w-4"})}),!Te.brokerage_id&&e.jsx(U,{variant:"ghost",size:"icon",className:"text-destructive",onClick:async()=>{await Yi("Delete this private group? All posts in this group will be deleted.")&&Q.mutate(Te.id)},children:e.jsx(In,{className:"h-4 w-4"})}),Te.brokerage_id&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"Managed via brokerage"})]})})]},Te.id))})]})})})]})]}),e.jsx(zs,{open:a,onOpenChange:i,children:e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:l?"Edit Category":"Create Category"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),e.jsx(xe,{value:c.icon,onChange:Te=>d(Me=>({...Me,icon:Te.target.value})),placeholder:"💬",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(xe,{value:c.name,onChange:Te=>d(Me=>({...Me,name:Te.target.value})),placeholder:"Category name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(Fs,{value:c.description,onChange:Te=>d(Me=>({...Me,description:Te.target.value})),placeholder:"Brief description of this category",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(U,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(U,{onClick:()=>H.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(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:m?"Edit Private Group":"Create Private Group"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),e.jsx(xe,{value:f.icon,onChange:Te=>x(Me=>({...Me,icon:Te.target.value})),placeholder:"🔒",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(xe,{value:f.name,onChange:Te=>x(Me=>({...Me,name:Te.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(Fs,{value:f.description,onChange:Te=>x(Me=>({...Me,description:Te.target.value})),placeholder:"Brief description of this private group",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(U,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsx(U,{onClick:()=>Z.mutate({...f,id:m==null?void 0:m.id}),disabled:!f.name.trim(),children:m?"Save Changes":"Create Private Group"})]})]})]})}),e.jsx(zs,{open:y,onOpenChange:v,children:e.jsxs(Ds,{className:"max-w-2xl",children:[e.jsx(Vs,{children:e.jsxs($s,{children:["Manage Members: ",b==null?void 0:b.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(oa,{defaultValue:"brokerages",children:[e.jsxs(la,{className:"w-full",children:[e.jsx(Kt,{value:"brokerages",className:"flex-1",children:"By Brokerage"}),e.jsx(Kt,{value:"users",className:"flex-1",children:"Individual Users"})]}),e.jsxs(Zt,{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(Gi,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[$.map(Te=>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(xi,{checked:ge(Te.id),onCheckedChange:()=>{b&&se.mutate({groupId:b.id,brokerageId:Te.id,isMember:ge(Te.id)})}}),e.jsx("span",{className:"font-medium",children:Te.name})]}),e.jsxs(Be,{variant:"secondary",children:[z.filter(Me=>Me.brokerage_id===Te.id).length," agents"]})]},Te.id)),$.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No brokerages found"})]})})]}),e.jsxs(Zt,{value:"users",className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search users...",value:S,onChange:Te=>A(Te.target.value),className:"pl-9"})]}),e.jsx(Gi,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[ke.map(Te=>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(xi,{checked:he(Te.id),onCheckedChange:()=>{b&&ue.mutate({groupId:b.id,userId:Te.id,isMember:he(Te.id)})}}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Te.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Te.email})]})]})},Te.id)),ke.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(U,{onClick:()=>v(!1),children:"Done"})})]})]})})]})})},lyt=s=>{switch(s){case"academy_video":return e.jsx(lu,{className:"h-3 w-3"});case"template":return e.jsx(Ur,{className:"h-3 w-3"});case"toolbox":return e.jsx(dh,{className:"h-3 w-3"});case"newsletter":return e.jsx(Q2,{className:"h-3 w-3"});case"social_swag":return e.jsx(cn,{className:"h-3 w-3"});default:return e.jsx(Sr,{className:"h-3 w-3"})}},Yrn=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}},Zrn=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}},Xrn=()=>{const{toast:s}=Ai(),[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),[p,f]=j.useState([]),[x,y]=j.useState([]);j.useEffect(()=>{v()},[]);const v=async()=>{try{c(!0);const{data:R,error:z}=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(z)throw z;const{data:$,error:H}=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(H)throw H;const V=[...new Set(($==null?void 0:$.map(ne=>ne.user_id))||[])],{data:K}=await q.from("profiles").select(` id, name, email, brokerages ( name ) `).in("id",V),Z=new Map((K==null?void 0:K.map(ne=>[ne.id,ne]))||[]),Q=(R==null?void 0:R.map(ne=>{var ie,ce,je,be;return{id:ne.id,user_id:ne.user_id,app_name:ne.app_name,launched_at:ne.launched_at,user_name:((ie=ne.profiles)==null?void 0:ie.name)||"Unknown",user_email:((ce=ne.profiles)==null?void 0:ce.email)||"Unknown",brokerage_name:((be=(je=ne.profiles)==null?void 0:je.brokerages)==null?void 0:be.name)||null}}))||[],le=($==null?void 0:$.map(ne=>{var ce;const ie=Z.get(ne.user_id);return{id:ne.id,user_id:ne.user_id,resource_type:ne.resource_type,resource_id:ne.resource_id,resource_title:ne.resource_title,action_type:ne.action_type,created_at:ne.created_at,user_name:(ie==null?void 0:ie.name)||"Unknown",user_email:(ie==null?void 0:ie.email)||"Unknown",brokerage_name:((ce=ie==null?void 0:ie.brokerages)==null?void 0:ce.name)||null}}))||[];n(Q),a(le);const ue=new Map;Q.forEach(ne=>{if(!ue.has(ne.user_id))ue.set(ne.user_id,{user_id:ne.user_id,user_name:ne.user_name,user_email:ne.user_email,brokerage_name:ne.brokerage_name,last_activity_type:"app",last_activity_name:ne.app_name,last_activity_at:ne.launched_at,total_app_launches:1,total_content_views:0});else{const ie=ue.get(ne.user_id);ie.total_app_launches++,new Date(ne.launched_at)>new Date(ie.last_activity_at)&&(ie.last_activity_type="app",ie.last_activity_name=ne.app_name,ie.last_activity_at=ne.launched_at)}}),le.forEach(ne=>{if(!ue.has(ne.user_id))ue.set(ne.user_id,{user_id:ne.user_id,user_name:ne.user_name,user_email:ne.user_email,brokerage_name:ne.brokerage_name,last_activity_type:ne.resource_type,last_activity_name:ne.resource_title,last_activity_at:ne.created_at,total_app_launches:0,total_content_views:1});else{const ie=ue.get(ne.user_id);ie.total_content_views++,new Date(ne.created_at)>new Date(ie.last_activity_at)&&(ie.last_activity_type=ne.resource_type,ie.last_activity_name=ne.resource_title,ie.last_activity_at=ne.created_at)}});const se=Array.from(ue.values()).sort((ne,ie)=>new Date(ie.last_activity_at).getTime()-new Date(ne.last_activity_at).getTime());l(se)}catch(R){console.error("Error loading activity:",R),s({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{c(!1)}},b=R=>{m({id:R.user_id,name:R.user_name,email:R.user_email});const z=t.filter(H=>H.user_id===R.user_id),$=r.filter(H=>H.user_id===R.user_id);f(z),y($)},N=()=>{m(null),f([]),y([])},{sortKey:S,sortDirection:A,handleSort:T,sortData:L}=Sre("last_activity_at","desc"),M=i.filter(R=>{var $;if(!d)return!0;const z=d.toLowerCase();return R.user_name.toLowerCase().includes(z)||R.user_email.toLowerCase().includes(z)||(($=R.brokerage_name)==null?void 0:$.toLowerCase().includes(z))}),I=L(M,{user:R=>{var z;return((z=R.user_name)==null?void 0:z.toLowerCase())||""},brokerage:R=>{var z;return((z=R.brokerage_name)==null?void 0:z.toLowerCase())||""},last_activity_at:R=>new Date(R.last_activity_at).getTime(),apps:R=>R.total_app_launches,content:R=>R.total_content_views});return o?e.jsx(we,{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(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"User Activity"}),e.jsx(Jn,{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(Fr,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name, email, or brokerage...",value:d,onChange:R=>u(R.target.value),className:"pl-9"})]})}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Sh,{sortKey:"user",currentSortKey:S,currentDirection:A,onSort:T,children:"User"}),e.jsx(Sh,{sortKey:"brokerage",currentSortKey:S,currentDirection:A,onSort:T,children:"Brokerage"}),e.jsx(Lt,{children:"Last Activity"}),e.jsx(Sh,{sortKey:"last_activity_at",currentSortKey:S,currentDirection:A,onSort:T,children:"Last Active"}),e.jsx(Sh,{sortKey:"apps",currentSortKey:S,currentDirection:A,onSort:T,className:"text-right",children:"Apps"}),e.jsx(Sh,{sortKey:"content",currentSortKey:S,currentDirection:A,onSort:T,className:"text-right",children:"Content"})]})}),e.jsx(Xa,{children:I.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:6,className:"text-center text-muted-foreground",children:"No activity found"})}):I.map(R=>e.jsxs(gn,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>b(R),children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:R.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:R.user_email})]})}),e.jsx(gt,{children:R.brokerage_name?e.jsx(Be,{variant:"outline",children:R.brokerage_name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(gt,{children:e.jsx("div",{className:"flex items-center gap-2",children:R.last_activity_type==="app"?e.jsxs(Be,{variant:"secondary",children:[e.jsx(Sr,{className:"h-3 w-3 mr-1"}),R.last_activity_name]}):e.jsxs(Be,{variant:"outline",className:"flex items-center gap-1",children:[lyt(R.last_activity_type),e.jsx("span",{className:"max-w-32 truncate",children:R.last_activity_name})]})})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Nd(new Date(R.last_activity_at),{addSuffix:!0})}),e.jsx(gt,{className:"text-right",children:e.jsx(Be,{variant:"outline",children:R.total_app_launches})}),e.jsx(gt,{className:"text-right",children:e.jsx(Be,{variant:"outline",children:R.total_content_views})})]},R.user_id))})]})})]})]}),e.jsx(zs,{open:!!h,onOpenChange:R=>!R&&N(),children:e.jsxs(Ds,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(Vs,{children:[e.jsxs($s,{children:[h==null?void 0:h.name,"'s Activity"]}),e.jsx(Pr,{children:h==null?void 0:h.email})]}),e.jsxs(oa,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(la,{className:"grid w-full grid-cols-2",children:[e.jsxs(Kt,{value:"content",children:["Content (",x.length,")"]}),e.jsxs(Kt,{value:"apps",children:["App Launches (",p.length,")"]})]}),e.jsx(Zt,{value:"content",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Type"}),e.jsx(Lt,{children:"Resource"}),e.jsx(Lt,{children:"Action"}),e.jsx(Lt,{children:"Time"})]})}),e.jsx(Xa,{children:x.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement"})}):x.map(R=>e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsxs(Be,{variant:"outline",className:"flex items-center gap-1 w-fit",children:[lyt(R.resource_type),Yrn(R.resource_type)]})}),e.jsx(gt,{className:"max-w-48",children:e.jsx("span",{className:"truncate block",children:R.resource_title})}),e.jsx(gt,{children:e.jsx(Be,{variant:"secondary",children:Zrn(R.action_type)})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Nd(new Date(R.created_at),{addSuffix:!0})})]},R.id))})]})})}),e.jsx(Zt,{value:"apps",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"App"}),e.jsx(Lt,{children:"Time"})]})}),e.jsx(Xa,{children:p.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches"})}):p.map(R=>e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsx(Be,{variant:"secondary",children:R.app_name})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Nd(new Date(R.launched_at),{addSuffix:!0})})]},R.id))})]})})})]})]})})]})},Qrn=()=>{const{toast:s}=Ai(),[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()),p=new Date;p.setMonth(p.getMonth()-1);const{count:f}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",p.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:f||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(we,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Total Users"}),e.jsx(Bn,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(Yo,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(Yr,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Brokerages"}),e.jsx(_i,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(Lm,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Launches This Week"}),e.jsx(Lm,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Launches This Month"}),e.jsx(Lm,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Active This Week"}),e.jsx(rc,{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"})]})]})]})},cyt={event:"Event",template:"Template",academy_video:"Academy Video",resource_kit:"Resource Kit",newsletter:"Newsletter",social_swag:"Social Swag"},dyt={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 hqt({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 T=[];if(s&&t){const{data:V}=await q.from("profiles").select("id").eq("brokerage_id",t);if(T=(V==null?void 0:V.map(K=>K.id))||[],T.length===0){r([]),i(!1);return}}let L=q.from("resource_shares").select("*").order("created_at",{ascending:!1});s&&T.length>0&&(L=L.or(`sender_id.in.(${T.join(",")}),recipient_id.in.(${T.join(",")})`));const{data:M,error:I}=await L;if(I)throw I;const R=new Set;M==null||M.forEach(V=>{R.add(V.sender_id),R.add(V.recipient_id)});const{data:z}=await q.from("profiles").select("id, name, email").in("id",Array.from(R)),$=new Map((z==null?void 0:z.map(V=>[V.id,V]))||[]),H=(M==null?void 0:M.map(V=>({...V,sender:$.get(V.sender_id),recipient:$.get(V.recipient_id)})))||[];r(H)}catch(T){console.error("Error loading shares:",T)}finally{i(!1)}},{sortKey:h,sortDirection:m,handleSort:p,sortData:f}=Sre("created_at","desc"),x=n.filter(T=>{var I,R;const L=l===""||T.resource_title.toLowerCase().includes(l.toLowerCase())||((I=T.sender)==null?void 0:I.name.toLowerCase().includes(l.toLowerCase()))||((R=T.recipient)==null?void 0:R.name.toLowerCase().includes(l.toLowerCase())),M=c==="all"||T.resource_type===c;return L&&M}),y=f(x,{resource:T=>{var L;return((L=T.resource_title)==null?void 0:L.toLowerCase())||""},type:T=>T.resource_type,sender:T=>{var L,M;return((M=(L=T.sender)==null?void 0:L.name)==null?void 0:M.toLowerCase())||""},recipient:T=>{var L,M;return((M=(L=T.recipient)==null?void 0:L.name)==null?void 0:M.toLowerCase())||""},status:T=>T.is_read?1:0,created_at:T=>new Date(T.created_at).getTime()}),v=n.length,b=new Set(n.map(T=>T.sender_id)).size,N=new Set(n.map(T=>T.recipient_id)).size,S=n.length>0?Math.round(n.filter(T=>T.is_read).length/n.length*100):0,A=n.reduce((T,L)=>(T[L.resource_type]=(T[L.resource_type]||0)+1,T),{});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((T,L)=>e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(xn,{className:"h-4 w-20"})}),e.jsx(Ie,{children:e.jsx(xn,{className:"h-8 w-16"})})]},L))}),e.jsx(we,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Total Shares"}),e.jsx(jd,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:v})})]}),e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Active Sharers"}),e.jsx(Bn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:b})})]}),e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Recipients Reached"}),e.jsx(rc,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:N})})]}),e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Read Rate"}),e.jsx(Ur,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ie,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[S,"%"]})})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(([T,L])=>e.jsxs(Be,{variant:"secondary",className:dyt[T],children:[cyt[T],": ",L]},T)),Object.keys(A).length===0&&e.jsx("span",{className:"text-muted-foreground text-sm",children:"No shares yet"})]})})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"Share History"}),e.jsxs(Jn,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by resource, sender, or recipient...",value:l,onChange:T=>o(T.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:c,onValueChange:d,children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{placeholder:"Resource type"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Types"}),e.jsx(et,{value:"event",children:"Events"}),e.jsx(et,{value:"template",children:"Templates"}),e.jsx(et,{value:"academy_video",children:"Academy Videos"}),e.jsx(et,{value:"resource_kit",children:"Resource Kits"}),e.jsx(et,{value:"newsletter",children:"Newsletters"}),e.jsx(et,{value:"social_swag",children:"Social Swag"})]})]})]}),e.jsx(Gi,{className:"h-[400px]",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Sh,{sortKey:"resource",currentSortKey:h,currentDirection:m,onSort:p,children:"Resource"}),e.jsx(Sh,{sortKey:"type",currentSortKey:h,currentDirection:m,onSort:p,children:"Type"}),e.jsx(Sh,{sortKey:"sender",currentSortKey:h,currentDirection:m,onSort:p,children:"Sender"}),e.jsx(Sh,{sortKey:"recipient",currentSortKey:h,currentDirection:m,onSort:p,children:"Recipient"}),e.jsx(Sh,{sortKey:"status",currentSortKey:h,currentDirection:m,onSort:p,children:"Status"}),e.jsx(Sh,{sortKey:"created_at",currentSortKey:h,currentDirection:m,onSort:p,children:"Date"})]})}),e.jsx(Xa,{children:y.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No shares found"})}):y.map(T=>{var L,M;return e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium max-w-[200px] truncate",children:T.resource_title}),e.jsx(gt,{children:e.jsx(Be,{variant:"secondary",className:dyt[T.resource_type],children:cyt[T.resource_type]})}),e.jsx(gt,{children:((L=T.sender)==null?void 0:L.name)||"Unknown"}),e.jsx(gt,{children:((M=T.recipient)==null?void 0:M.name)||"Unknown"}),e.jsx(gt,{children:e.jsx(Be,{variant:T.is_read?"default":"outline",children:T.is_read?"Read":"Unread"})}),e.jsx(gt,{className:"text-muted-foreground",children:Gs(new Date(T.created_at),"MMM d, yyyy")})]},T.id)})})]})})]})]})]})}const s7e={academy_video:{label:"Academy Videos",icon:Wr,color:"bg-purple-100 text-purple-800",actionLabel:"Watched",actionIcon:xa},template:{label:"Templates",icon:LC,color:"bg-blue-100 text-blue-800",actionLabel:"Accessed",actionIcon:n0},toolbox:{label:"Toolkit",icon:O4,color:"bg-amber-100 text-amber-800",actionLabel:"Downloaded",actionIcon:pi},newsletter:{label:"Newsletters",icon:ln,color:"bg-emerald-100 text-emerald-800",actionLabel:"Clicked",actionIcon:n0},social_swag:{label:"Social Swag",icon:$c,color:"bg-pink-100 text-pink-800",actionLabel:"Accessed",actionIcon:n0},event:{label:"Events",icon:pa,color:"bg-cyan-100 text-cyan-800",actionLabel:"Registered",actionIcon:n0}};function uyt(s){return s.resource_type==="toolbox"?s.total_downloads:s.total_clicks}function Jrn(s,t){return s==="toolbox"?t.downloads:t.clicks}function ean(){var T;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}=Sre("total_views","desc");j.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:L,error:M}=await q.rpc("get_admin_content_engagement");if(M)throw M;t(L||[])}catch(L){console.error("Error loading content engagement:",L)}finally{r(!1)}},m=L=>{i(M=>{const I=M===L?null:L;return requestAnimationFrame(()=>{var R;(R=l.current)==null||R.scrollIntoView({behavior:"smooth",block:"start"})}),I})};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((L,M)=>e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(xn,{className:"h-4 w-20"})}),e.jsx(Ie,{children:e.jsx(xn,{className:"h-8 w-16"})})]},M))}),e.jsx(we,{children:e.jsx(Ie,{className:"py-8",children:e.jsx(xn,{className:"h-64 w-full"})})})]});const p=s.reduce((L,M)=>L+M.total_views,0),f=s.reduce((L,M)=>L+M.total_clicks,0),x=s.reduce((L,M)=>L+M.total_downloads,0),y=s.length,v=s.reduce((L,M)=>(L[M.resource_type]||(L[M.resource_type]={views:0,clicks:0,downloads:0,assets:0,uniqueUsers:0}),L[M.resource_type].views+=M.total_views,L[M.resource_type].clicks+=M.total_clicks,L[M.resource_type].downloads+=M.total_downloads,L[M.resource_type].assets+=1,L[M.resource_type].uniqueUsers+=M.unique_users,L),{}),b=a?s.filter(L=>L.resource_type===a):s,N=u(b,{asset:L=>{var M;return((M=L.resource_title)==null?void 0:M.toLowerCase())||""},type:L=>L.resource_type,views:L=>L.total_views,actions:L=>uyt(L),unique_users:L=>L.unique_users,last_activity:L=>L.last_engaged_at?new Date(L.last_engaged_at).getTime():0}),S=a?s7e[a]||{label:a,icon:xa,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:n0}: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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Total Views"}),e.jsx(xa,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:p.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Across all content"})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Total Clicks"}),e.jsx(n0,{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:"Link & Canva clicks"})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Downloads"}),e.jsx(pi,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Assets Tracked"}),e.jsx(rc,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(n0,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[p>0?Math.round((f+x)/p*100):0,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Of views → actions"})]})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-sm font-medium",children:"Engagement by Content Type"}),e.jsx(Jn,{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(([L,M])=>{const I=s7e[L]||{label:L,icon:xa,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:n0},R=I.icon,z=a===L;return e.jsxs("button",{type:"button",onClick:()=>m(L),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors cursor-pointer ${z?"ring-2 ring-primary border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx("div",{className:`p-2 rounded-md ${I.color}`,children:e.jsx(R,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:I.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(xa,{className:"h-3 w-3"})," ",M.views]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(I.actionIcon,{className:"h-3 w-3"})," ",Jrn(L,M)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3 w-3"})," ",M.uniqueUsers]})]})]}),e.jsxs(Be,{variant:"secondary",className:"text-[10px]",children:[M.assets," items"]})]},L)})})})]}),e.jsx("div",{ref:l,children:e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{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(Jn,{children:a?`${b.length} ${((T=S==null?void 0:S.label)==null?void 0:T.toLowerCase())||"items"} ranked by total interactions`:"All tracked assets ranked by total interactions"})]}),a&&e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>i(null),className:"gap-1",children:[e.jsx(Aa,{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(Gi,{className:"h-[400px]",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{className:"w-[40px]",children:"#"}),e.jsx(Sh,{sortKey:"asset",currentSortKey:o,currentDirection:c,onSort:d,children:"Asset"}),!a&&e.jsx(Sh,{sortKey:"type",currentSortKey:o,currentDirection:c,onSort:d,children:"Type"}),e.jsx(Sh,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Views"}),e.jsx(Sh,{sortKey:"actions",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:S?S.actionLabel:"Actions"}),e.jsx(Sh,{sortKey:"unique_users",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Unique Users"}),e.jsx(Sh,{sortKey:"last_activity",currentSortKey:o,currentDirection:c,onSort:d,children:"Last Activity"})]})}),e.jsx(Xa,{children:N.map((L,M)=>{const I=s7e[L.resource_type]||{label:L.resource_type,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:n0};return e.jsxs(gn,{children:[e.jsx(gt,{className:"text-muted-foreground text-xs",children:M+1}),e.jsx(gt,{children:e.jsx("p",{className:"font-medium text-sm truncate max-w-[250px]",children:L.resource_title})}),!a&&e.jsx(gt,{children:e.jsx(Be,{className:`text-[10px] ${I.color}`,children:I.label})}),e.jsx(gt,{className:"text-right font-medium",children:L.total_views}),e.jsx(gt,{className:"text-right font-medium",children:uyt(L)}),e.jsx(gt,{className:"text-right",children:L.unique_users}),e.jsx(gt,{className:"text-xs text-muted-foreground",children:L.last_engaged_at?Nd(new Date(L.last_engaged_at),{addSuffix:!0}):"—"})]},`${L.resource_type}-${L.resource_id}`)})})]})})})]})})]})}var tan=Array.isArray,z_=tan,san=typeof op=="object"&&op&&op.Object===Object&&op,mqt=san,nan=mqt,ran=typeof self=="object"&&self&&self.Object===Object&&self,aan=nan||ran||Function("return this")(),h3=aan,ian=h3,oan=ian.Symbol,Are=oan,hyt=Are,pqt=Object.prototype,lan=pqt.hasOwnProperty,can=pqt.toString,uY=hyt?hyt.toStringTag:void 0;function dan(s){var t=lan.call(s,uY),n=s[uY];try{s[uY]=void 0;var r=!0}catch{}var a=can.call(s);return r&&(t?s[uY]=n:delete s[uY]),a}var uan=dan,han=Object.prototype,man=han.toString;function pan(s){return man.call(s)}var fan=pan,myt=Are,gan=uan,xan=fan,yan="[object Null]",van="[object Undefined]",pyt=myt?myt.toStringTag:void 0;function ban(s){return s==null?s===void 0?van:yan:pyt&&pyt in Object(s)?gan(s):xan(s)}var wE=ban;function _an(s){return s!=null&&typeof s=="object"}var jE=_an,wan=wE,jan=jE,Nan="[object Symbol]";function kan(s){return typeof s=="symbol"||jan(s)&&wan(s)==Nan}var RG=kan,San=z_,Can=RG,Aan=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ean=/^\w*$/;function Tan(s,t){if(San(s))return!1;var n=typeof s;return n=="number"||n=="symbol"||n=="boolean"||s==null||Can(s)?!0:Ean.test(s)||!Aan.test(s)||t!=null&&s in Object(t)}var bet=Tan;function Man(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var rL=Man;const DG=od(rL);var Pan=wE,Lan=rL,Ian="[object AsyncFunction]",Ran="[object Function]",Dan="[object GeneratorFunction]",Oan="[object Proxy]";function Fan(s){if(!Lan(s))return!1;var t=Pan(s);return t==Ran||t==Dan||t==Ian||t==Oan}var _et=Fan;const kl=od(_et);var zan=h3,Ban=zan["__core-js_shared__"],Uan=Ban,n7e=Uan,fyt=function(){var s=/[^.]+$/.exec(n7e&&n7e.keys&&n7e.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function qan(s){return!!fyt&&fyt in s}var $an=qan,Van=Function.prototype,Han=Van.toString;function Gan(s){if(s!=null){try{return Han.call(s)}catch{}try{return s+""}catch{}}return""}var fqt=Gan,Wan=_et,Kan=$an,Yan=rL,Zan=fqt,Xan=/[\\^$.*+?()[\]{}|]/g,Qan=/^\[object .+?Constructor\]$/,Jan=Function.prototype,ein=Object.prototype,tin=Jan.toString,sin=ein.hasOwnProperty,nin=RegExp("^"+tin.call(sin).replace(Xan,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function rin(s){if(!Yan(s)||Kan(s))return!1;var t=Wan(s)?nin:Qan;return t.test(Zan(s))}var ain=rin;function iin(s,t){return s==null?void 0:s[t]}var oin=iin,lin=ain,cin=oin;function din(s,t){var n=cin(s,t);return lin(n)?n:void 0}var k9=din,uin=k9,hin=uin(Object,"create"),VPe=hin,gyt=VPe;function min(){this.__data__=gyt?gyt(null):{},this.size=0}var pin=min;function fin(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var gin=fin,xin=VPe,yin="__lodash_hash_undefined__",vin=Object.prototype,bin=vin.hasOwnProperty;function _in(s){var t=this.__data__;if(xin){var n=t[s];return n===yin?void 0:n}return bin.call(t,s)?t[s]:void 0}var win=_in,jin=VPe,Nin=Object.prototype,kin=Nin.hasOwnProperty;function Sin(s){var t=this.__data__;return jin?t[s]!==void 0:kin.call(t,s)}var Cin=Sin,Ain=VPe,Ein="__lodash_hash_undefined__";function Tin(s,t){var n=this.__data__;return this.size+=this.has(s)?0:1,n[s]=Ain&&t===void 0?Ein:t,this}var Min=Tin,Pin=pin,Lin=gin,Iin=win,Rin=Cin,Din=Min;function OG(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t-1}var Jin=Qin,eon=HPe;function ton(s,t){var n=this.__data__,r=eon(n,s);return r<0?(++this.size,n.push([s,t])):n[r][1]=t,this}var son=ton,non=zin,ron=Win,aon=Zin,ion=Jin,oon=son;function FG(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t0?1:-1},QD=function(t){return D7(t)&&t.indexOf("%")===t.length-1},Wa=function(t){return Eln(t)&&!BG(t)},Lln=function(t){return sc(t)},o0=function(t){return Wa(t)||D7(t)},Iln=0,S9=function(t){var n=++Iln;return"".concat(t||"").concat(n)},rb=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(!Wa(t)&&!D7(t))return r;var i;if(QD(t)){var l=t.indexOf("%");i=n*parseFloat(t.slice(0,l))/100}else i=+t;return BG(i)&&(i=r),a&&i>n&&(i=n),i},o6=function(t){if(!t)return null;var n=Object.keys(t);return n&&n.length?t[n[0]]:null},Rln=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 qln(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 uVe(s){"@babel/helpers - typeof";return uVe=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},uVe(s)}var jyt={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"},FA=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},Nyt=null,a7e=null,Pet=function s(t){if(t===Nyt&&Array.isArray(a7e))return a7e;var n=[];return j.Children.forEach(t,function(r){sc(r)||(Nln.isFragment(r)?n=n.concat(s(r.props.children)):n.push(r))}),a7e=n,Nyt=t,n};function ij(s,t){var n=[],r=[];return Array.isArray(t)?r=t.map(function(a){return FA(a)}):r=[FA(t)],Pet(s).forEach(function(a){var i=aj(a,"type.displayName")||aj(a,"type.name");r.indexOf(i)!==-1&&n.push(a)}),n}function Pw(s,t){var n=ij(s,t);return n&&n[0]}var kyt=function(t){if(!t||!t.props)return!1;var n=t.props,r=n.width,a=n.height;return!(!Wa(r)||r<=0||!Wa(a)||a<=0)},$ln=["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"],Vln=function(t){return t&&t.type&&D7(t.type)&&$ln.indexOf(t.type)>=0},kqt=function(t){return t&&uVe(t)==="object"&&"clipDot"in t},Hln=function(t,n,r,a){var i,l=(i=r7e==null?void 0:r7e[a])!==null&&i!==void 0?i:[];return n.startsWith("data-")||!kl(t)&&(a&&l.includes(n)||Fln.includes(n))||r&&Met.includes(n)},Io=function(t,n,r){if(!t||typeof t=="function"||typeof t=="boolean")return null;var a=t;if(j.isValidElement(t)&&(a=t.props),!DG(a))return null;var i={};return Object.keys(a).forEach(function(l){var o;Hln((o=a)===null||o===void 0?void 0:o[l],l,n,r)&&(i[l]=a[l])}),i},hVe=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 Syt(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 Zln(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 pVe(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=Yln(s,Kln),u=a||{width:n,height:r,x:0,y:0},h=mc("recharts-surface",i);return Dt.createElement("svg",mVe({},Io(d,!0,"svg"),{className:h,width:n,height:r,style:l,viewBox:"".concat(u.x," ").concat(u.y," ").concat(u.width," ").concat(u.height)}),Dt.createElement("title",null,o),Dt.createElement("desc",null,c),t)}var Xln=["children","className"];function fVe(){return fVe=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Jln(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}var wd=Dt.forwardRef(function(s,t){var n=s.children,r=s.className,a=Qln(s,Xln),i=mc("recharts-layer",r);return Dt.createElement("g",fVe({className:i},Io(a,!0),{ref:t}),n)}),iS=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:scn(s,t,n)}var rcn=ncn,acn="\\ud800-\\udfff",icn="\\u0300-\\u036f",ocn="\\ufe20-\\ufe2f",lcn="\\u20d0-\\u20ff",ccn=icn+ocn+lcn,dcn="\\ufe0e\\ufe0f",ucn="\\u200d",hcn=RegExp("["+ucn+acn+ccn+dcn+"]");function mcn(s){return hcn.test(s)}var Sqt=mcn;function pcn(s){return s.split("")}var fcn=pcn,Cqt="\\ud800-\\udfff",gcn="\\u0300-\\u036f",xcn="\\ufe20-\\ufe2f",ycn="\\u20d0-\\u20ff",vcn=gcn+xcn+ycn,bcn="\\ufe0e\\ufe0f",_cn="["+Cqt+"]",gVe="["+vcn+"]",xVe="\\ud83c[\\udffb-\\udfff]",wcn="(?:"+gVe+"|"+xVe+")",Aqt="[^"+Cqt+"]",Eqt="(?:\\ud83c[\\udde6-\\uddff]){2}",Tqt="[\\ud800-\\udbff][\\udc00-\\udfff]",jcn="\\u200d",Mqt=wcn+"?",Pqt="["+bcn+"]?",Ncn="(?:"+jcn+"(?:"+[Aqt,Eqt,Tqt].join("|")+")"+Pqt+Mqt+")*",kcn=Pqt+Mqt+Ncn,Scn="(?:"+[Aqt+gVe+"?",gVe,Eqt,Tqt,_cn].join("|")+")",Ccn=RegExp(xVe+"(?="+xVe+")|"+Scn+kcn,"g");function Acn(s){return s.match(Ccn)||[]}var Ecn=Acn,Tcn=fcn,Mcn=Sqt,Pcn=Ecn;function Lcn(s){return Mcn(s)?Pcn(s):Tcn(s)}var Icn=Lcn,Rcn=rcn,Dcn=Sqt,Ocn=Icn,Fcn=vqt;function zcn(s){return function(t){t=Fcn(t);var n=Dcn(t)?Ocn(t):void 0,r=n?n[0]:t.charAt(0),a=n?Rcn(n,1).join(""):t.slice(1);return r[s]()+a}}var Bcn=zcn,Ucn=Bcn,qcn=Ucn("toUpperCase"),$cn=qcn;const aLe=od($cn);function Am(s){return function(){return s}}const Lqt=Math.cos,PAe=Math.sin,CS=Math.sqrt,LAe=Math.PI,iLe=2*LAe,yVe=Math.PI,vVe=2*yVe,xD=1e-6,Vcn=vVe-xD;function Iqt(s){this._+=s[0];for(let t=1,n=s.length;t=0))throw new Error(`invalid digits: ${s}`);if(t>15)return Iqt;const n=10**t;return function(r){this._+=r[0];for(let a=1,i=r.length;axD)if(!(Math.abs(h*c-d*u)>xD)||!i)this._append`L${this._x1=t},${this._y1=n}`;else{let p=r-l,f=a-o,x=c*c+d*d,y=p*p+f*f,v=Math.sqrt(x),b=Math.sqrt(m),N=i*Math.tan((yVe-Math.acos((x+m-y)/(2*v*b)))/2),S=N/b,A=N/v;Math.abs(S-1)>xD&&this._append`L${t+S*u},${n+S*h}`,this._append`A${i},${i},0,0,${+(h*p>u*f)},${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)>xD||Math.abs(this._y1-u)>xD)&&this._append`L${d},${u}`,r&&(m<0&&(m=m%vVe+vVe),m>Vcn?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>xD&&this._append`A${r},${r},0,${+(m>=yVe)},${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 Let(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 Gcn(t)}function Iet(s){return typeof s=="object"&&"length"in s?s:Array.from(s)}function Rqt(s){this._context=s}Rqt.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 oLe(s){return new Rqt(s)}function Dqt(s){return s[0]}function Oqt(s){return s[1]}function Fqt(s,t){var n=Am(!0),r=null,a=oLe,i=null,l=Let(o);s=typeof s=="function"?s:s===void 0?Dqt:Am(s),t=typeof t=="function"?t:t===void 0?Oqt:Am(t);function o(c){var d,u=(c=Iet(c)).length,h,m=!1,p;for(r==null&&(i=a(p=l())),d=0;d<=u;++d)!(d=p;--f)o.point(N[f],S[f]);o.lineEnd(),o.areaEnd()}v&&(N[m]=+s(y,m,h),S[m]=+t(y,m,h),o.point(r?+r(y,m,h):N[m],n?+n(y,m,h):S[m]))}if(b)return o=null,b+""||null}function u(){return Fqt().defined(a).curve(l).context(i)}return d.x=function(h){return arguments.length?(s=typeof h=="function"?h:Am(+h),r=null,d):s},d.x0=function(h){return arguments.length?(s=typeof h=="function"?h:Am(+h),d):s},d.x1=function(h){return arguments.length?(r=h==null?null:typeof h=="function"?h:Am(+h),d):r},d.y=function(h){return arguments.length?(t=typeof h=="function"?h:Am(+h),n=null,d):t},d.y0=function(h){return arguments.length?(t=typeof h=="function"?h:Am(+h),d):t},d.y1=function(h){return arguments.length?(n=h==null?null:typeof h=="function"?h:Am(+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:Am(!!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 zqt{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 Wcn(s){return new zqt(s,!0)}function Kcn(s){return new zqt(s,!1)}const Ret={draw(s,t){const n=CS(t/LAe);s.moveTo(n,0),s.arc(0,0,n,0,iLe)}},Ycn={draw(s,t){const n=CS(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()}},Bqt=CS(1/3),Zcn=Bqt*2,Xcn={draw(s,t){const n=CS(t/Zcn),r=n*Bqt;s.moveTo(0,-n),s.lineTo(r,0),s.lineTo(0,n),s.lineTo(-r,0),s.closePath()}},Qcn={draw(s,t){const n=CS(t),r=-n/2;s.rect(r,r,n,n)}},Jcn=.8908130915292852,Uqt=PAe(LAe/10)/PAe(7*LAe/10),edn=PAe(iLe/10)*Uqt,tdn=-Lqt(iLe/10)*Uqt,sdn={draw(s,t){const n=CS(t*Jcn),r=edn*n,a=tdn*n;s.moveTo(0,-n),s.lineTo(r,a);for(let i=1;i<5;++i){const l=iLe*i/5,o=Lqt(l),c=PAe(l);s.lineTo(c*n,-o*n),s.lineTo(o*r-c*a,c*r+o*a)}s.closePath()}},i7e=CS(3),ndn={draw(s,t){const n=-CS(t/(i7e*3));s.moveTo(0,n*2),s.lineTo(-i7e*n,-n),s.lineTo(i7e*n,-n),s.closePath()}},n2=-.5,r2=CS(3)/2,bVe=1/CS(12),rdn=(bVe/2+1)*3,adn={draw(s,t){const n=CS(t/rdn),r=n/2,a=n*bVe,i=r,l=n*bVe+n,o=-i,c=l;s.moveTo(r,a),s.lineTo(i,l),s.lineTo(o,c),s.lineTo(n2*r-r2*a,r2*r+n2*a),s.lineTo(n2*i-r2*l,r2*i+n2*l),s.lineTo(n2*o-r2*c,r2*o+n2*c),s.lineTo(n2*r+r2*a,n2*a-r2*r),s.lineTo(n2*i+r2*l,n2*l-r2*i),s.lineTo(n2*o+r2*c,n2*c-r2*o),s.closePath()}};function idn(s,t){let n=null,r=Let(a);s=typeof s=="function"?s:Am(s||Ret),t=typeof t=="function"?t:Am(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:Am(i),a):s},a.size=function(i){return arguments.length?(t=typeof i=="function"?i:Am(+i),a):t},a.context=function(i){return arguments.length?(n=i??null,a):n},a}function IAe(){}function RAe(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 qqt(s){this._context=s}qqt.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:RAe(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:RAe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function odn(s){return new qqt(s)}function $qt(s){this._context=s}$qt.prototype={areaStart:IAe,areaEnd:IAe,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:RAe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function ldn(s){return new $qt(s)}function Vqt(s){this._context=s}Vqt.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:RAe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function cdn(s){return new Vqt(s)}function Hqt(s){this._context=s}Hqt.prototype={areaStart:IAe,areaEnd:IAe,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 ddn(s){return new Hqt(s)}function Ayt(s){return s<0?-1:1}function Eyt(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(Ayt(i)+Ayt(l))*Math.min(Math.abs(i),Math.abs(l),.5*Math.abs(o))||0}function Tyt(s,t){var n=s._x1-s._x0;return n?(3*(s._y1-s._y0)/n-t)/2:t}function o7e(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 DAe(s){this._context=s}DAe.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:o7e(this,this._t0,Tyt(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,o7e(this,Tyt(this,n=Eyt(this,s,t)),n);break;default:o7e(this,this._t0,n=Eyt(this,s,t));break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t,this._t0=n}}};function Gqt(s){this._context=new Wqt(s)}(Gqt.prototype=Object.create(DAe.prototype)).point=function(s,t){DAe.prototype.point.call(this,t,s)};function Wqt(s){this._context=s}Wqt.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 udn(s){return new DAe(s)}function hdn(s){return new Gqt(s)}function Kqt(s){this._context=s}Kqt.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=Myt(s),a=Myt(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 pdn(s){return new lLe(s,.5)}function fdn(s){return new lLe(s,0)}function gdn(s){return new lLe(s,1)}function sH(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 xdn(s,t){return s[t]}function ydn(s){const t=[];return t.key=s,t}function vdn(){var s=Am([]),t=_Ve,n=sH,r=xdn;function a(i){var l=Array.from(s.apply(this,arguments),ydn),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 Adn(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 Yqt={symbolCircle:Ret,symbolCross:Ycn,symbolDiamond:Xcn,symbolSquare:Qcn,symbolStar:sdn,symbolTriangle:ndn,symbolWye:adn},Edn=Math.PI/180,Tdn=function(t){var n="symbol".concat(aLe(t));return Yqt[n]||Ret},Mdn=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*Edn;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}},Pdn=function(t,n){Yqt["symbol".concat(aLe(t))]=n},Det=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=Cdn(t,jdn),d=Lyt(Lyt({},c),{},{type:r,size:i,sizeType:o}),u=function(){var y=Tdn(r),v=idn().type(y).size(Mdn(i,o,r));return v()},h=d.className,m=d.cx,p=d.cy,f=Io(d,!0);return m===+m&&p===+p&&i===+i?Dt.createElement("path",wVe({},f,{className:mc("recharts-symbols",h),transform:"translate(".concat(m,", ").concat(p,")"),d:u()})):null};Det.registerSymbol=Pdn;function nH(s){"@babel/helpers - typeof";return nH=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},nH(s)}function jVe(){return jVe=Object.assign?Object.assign.bind():function(s){for(var t=1;t`);var b=p.inactive?d:p.color;return Dt.createElement("li",jVe({className:y,style:h,key:"legend-item-".concat(f)},O7(r.props,p,f)),Dt.createElement(pVe,{width:l,height:l,viewBox:u,style:m},r.renderIcon(p)),Dt.createElement("span",{className:"recharts-legend-item-text",style:{color:b}},x?x(v,p,f):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 Dt.createElement("ul",{className:"recharts-default-legend",style:o},this.renderItems())}}])}(j.PureComponent);Fee(Oet,"displayName","Legend");Fee(Oet,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var qdn=GPe;function $dn(){this.__data__=new qdn,this.size=0}var Vdn=$dn;function Hdn(s){var t=this.__data__,n=t.delete(s);return this.size=t.size,n}var Gdn=Hdn;function Wdn(s){return this.__data__.get(s)}var Kdn=Wdn;function Ydn(s){return this.__data__.has(s)}var Zdn=Ydn,Xdn=GPe,Qdn=jet,Jdn=Net,eun=200;function tun(s,t){var n=this.__data__;if(n instanceof Xdn){var r=n.__data__;if(!Qdn||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,p=n&jun?new vun:void 0;for(i.set(s,t),i.set(t,s);++h-1&&s%1==0&&s-1&&s%1==0&&s<=Chn}var Uet=Ahn,Ehn=wE,Thn=Uet,Mhn=jE,Phn="[object Arguments]",Lhn="[object Array]",Ihn="[object Boolean]",Rhn="[object Date]",Dhn="[object Error]",Ohn="[object Function]",Fhn="[object Map]",zhn="[object Number]",Bhn="[object Object]",Uhn="[object RegExp]",qhn="[object Set]",$hn="[object String]",Vhn="[object WeakMap]",Hhn="[object ArrayBuffer]",Ghn="[object DataView]",Whn="[object Float32Array]",Khn="[object Float64Array]",Yhn="[object Int8Array]",Zhn="[object Int16Array]",Xhn="[object Int32Array]",Qhn="[object Uint8Array]",Jhn="[object Uint8ClampedArray]",emn="[object Uint16Array]",tmn="[object Uint32Array]",ep={};ep[Whn]=ep[Khn]=ep[Yhn]=ep[Zhn]=ep[Xhn]=ep[Qhn]=ep[Jhn]=ep[emn]=ep[tmn]=!0;ep[Phn]=ep[Lhn]=ep[Hhn]=ep[Ihn]=ep[Ghn]=ep[Rhn]=ep[Dhn]=ep[Ohn]=ep[Fhn]=ep[zhn]=ep[Bhn]=ep[Uhn]=ep[qhn]=ep[$hn]=ep[Vhn]=!1;function smn(s){return Mhn(s)&&Thn(s.length)&&!!ep[Ehn(s)]}var nmn=smn;function rmn(s){return function(t){return s(t)}}var i$t=rmn,BAe={exports:{}};BAe.exports;(function(s,t){var n=mqt,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})(BAe,BAe.exports);var amn=BAe.exports,imn=nmn,omn=i$t,Byt=amn,Uyt=Byt&&Byt.isTypedArray,lmn=Uyt?omn(Uyt):imn,o$t=lmn,cmn=hhn,dmn=zet,umn=z_,hmn=a$t,mmn=Bet,pmn=o$t,fmn=Object.prototype,gmn=fmn.hasOwnProperty;function xmn(s,t){var n=umn(s),r=!n&&dmn(s),a=!n&&!r&&hmn(s),i=!n&&!r&&!a&&pmn(s),l=n||r||a||i,o=l?cmn(s.length,String):[],c=o.length;for(var d in s)(t||gmn.call(s,d))&&!(l&&(d=="length"||a&&(d=="offset"||d=="parent")||i&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||mmn(d,c)))&&o.push(d);return o}var ymn=xmn,vmn=Object.prototype;function bmn(s){var t=s&&s.constructor,n=typeof t=="function"&&t.prototype||vmn;return s===n}var _mn=bmn;function wmn(s,t){return function(n){return s(t(n))}}var l$t=wmn,jmn=l$t,Nmn=jmn(Object.keys,Object),kmn=Nmn,Smn=_mn,Cmn=kmn,Amn=Object.prototype,Emn=Amn.hasOwnProperty;function Tmn(s){if(!Smn(s))return Cmn(s);var t=[];for(var n in Object(s))Emn.call(s,n)&&n!="constructor"&&t.push(n);return t}var Mmn=Tmn,Pmn=_et,Lmn=Uet;function Imn(s){return s!=null&&Lmn(s.length)&&!Pmn(s)}var Ere=Imn,Rmn=ymn,Dmn=Mmn,Omn=Ere;function Fmn(s){return Omn(s)?Rmn(s):Dmn(s)}var cLe=Fmn,zmn=ehn,Bmn=dhn,Umn=cLe;function qmn(s){return zmn(s,Umn,Bmn)}var $mn=qmn,qyt=$mn,Vmn=1,Hmn=Object.prototype,Gmn=Hmn.hasOwnProperty;function Wmn(s,t,n,r,a,i){var l=n&Vmn,o=qyt(s),c=o.length,d=qyt(t),u=d.length;if(c!=u&&!l)return!1;for(var h=c;h--;){var m=o[h];if(!(l?m in t:Gmn.call(t,m)))return!1}var p=i.get(s),f=i.get(t);if(p&&f)return p==t&&f==s;var x=!0;i.set(s,t),i.set(t,s);for(var y=l;++h-1}var Hfn=Vfn;function Gfn(s,t,n){for(var r=-1,a=s==null?0:s.length;++r=ogn){var d=t?null:agn(s);if(d)return ign(d);l=!1,a=rgn,c=new tgn}else c=t?[]:o;e:for(;++r=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function jgn(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 Ngn(s){return s.value}function kgn(s,t){if(Dt.isValidElement(s))return Dt.cloneElement(s,t);if(typeof s=="function")return Dt.createElement(s,t);t.ref;var n=wgn(t,pgn);return Dt.createElement(Oet,n)}var rvt=1,$q=function(s){function t(){var n;fgn(this,t);for(var r=arguments.length,a=new Array(r),i=0;irvt||Math.abs(a.height-this.lastBoundingBox.height)>rvt)&&(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?sC({},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 p=this.getBBoxSnapshot();h={left:((d||0)-p.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 f=this.getBBoxSnapshot();m={top:((u||0)-f.height)/2}}else m=o==="bottom"?{bottom:c&&c.bottom||0}:{top:c&&c.top||0};return sC(sC({},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=sC(sC({position:"absolute",width:l||"auto",height:o||"auto"},this.getDefaultPosition(c)),c);return Dt.createElement("div",{className:"recharts-legend-wrapper",style:h,ref:function(p){r.wrapperNode=p}},kgn(i,sC(sC({},this.props),{},{payload:f$t(u,d,Ngn)})))}}],[{key:"getWithHeight",value:function(r,a){var i=sC(sC({},this.defaultProps),r.props),l=i.layout;return l==="vertical"&&Wa(r.props.height)?{height:r.props.height}:l==="horizontal"?{width:r.props.width||a}:null}}])}(j.PureComponent);dLe($q,"displayName","Legend");dLe($q,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var avt=Are,Sgn=zet,Cgn=z_,ivt=avt?avt.isConcatSpreadable:void 0;function Agn(s){return Cgn(s)||Sgn(s)||!!(ivt&&s&&s[ivt])}var Egn=Agn,Tgn=n$t,Mgn=Egn;function y$t(s,t,n,r,a){var i=-1,l=s.length;for(n||(n=Mgn),a||(a=[]);++i0&&n(o)?t>1?y$t(o,t-1,n,r,a):Tgn(a,o):r||(a[a.length]=o)}return a}var v$t=y$t;function Pgn(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 Lgn=Pgn,Ign=Lgn,Rgn=Ign(),Dgn=Rgn,Ogn=Dgn,Fgn=cLe;function zgn(s,t){return s&&Ogn(s,t,Fgn)}var b$t=zgn,Bgn=Ere;function Ugn(s,t){return function(n,r){if(n==null)return n;if(!Bgn(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 txn=exn,u7e=Cet,sxn=Aet,nxn=m3,rxn=_$t,axn=Zgn,ixn=i$t,oxn=txn,lxn=$G,cxn=z_;function dxn(s,t,n){t.length?t=u7e(t,function(i){return cxn(i)?function(l){return sxn(l,i.length===1?i[0]:i)}:i}):t=[lxn];var r=-1;t=u7e(t,ixn(nxn));var a=rxn(s,function(i,l,o){var c=u7e(t,function(d){return d(i)});return{criteria:c,index:++r,value:i}});return axn(a,function(i,l){return oxn(i,l,n)})}var uxn=dxn;function hxn(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 mxn=hxn,pxn=mxn,lvt=Math.max;function fxn(s,t,n){return t=lvt(t===void 0?s.length-1:t,0),function(){for(var r=arguments,a=-1,i=lvt(r.length-t,0),l=Array(i);++a0){if(++t>=kxn)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}var Exn=Axn,Txn=Nxn,Mxn=Exn,Pxn=Mxn(Txn),Lxn=Pxn,Ixn=$G,Rxn=gxn,Dxn=Lxn;function Oxn(s,t){return Dxn(Rxn(s,t,Ixn),s+"")}var Fxn=Oxn,zxn=wet,Bxn=Ere,Uxn=Bet,qxn=rL;function $xn(s,t,n){if(!qxn(n))return!1;var r=typeof t;return(r=="number"?Bxn(n)&&Uxn(t,n.length):r=="string"&&t in n)?zxn(n[t],s):!1}var uLe=$xn,Vxn=v$t,Hxn=uxn,Gxn=Fxn,dvt=uLe,Wxn=Gxn(function(s,t){if(s==null)return[];var n=t.length;return n>1&&dvt(s,t[0],t[1])?t=[]:n>2&&dvt(t[0],t[1],t[2])&&(t=[t[0]]),Hxn(s,Vxn(t,1),[])}),Kxn=Wxn;const Vet=od(Kxn);function zee(s){"@babel/helpers - typeof";return zee=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},zee(s)}function MVe(){return MVe=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(hY,"-left"),Wa(n)&&t&&Wa(t.x)&&n=t.y),"".concat(hY,"-top"),Wa(r)&&t&&Wa(t.y)&&rx?Math.max(u,c[r]):Math.max(h,c[r])}function c0n(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 d0n(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=mvt({allowEscapeViewBox:t,coordinate:n,key:"x",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.width,viewBox:c,viewBoxDimension:c.width}),h=mvt({allowEscapeViewBox:t,coordinate:n,key:"y",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.height,viewBox:c,viewBoxDimension:c.height}),d=c0n({translateX:u,translateY:h,useTranslate3d:o})):d=o0n,{cssProperties:d,cssClasses:l0n({translateX:u,translateY:h,coordinate:n})}}function aH(s){"@babel/helpers - typeof";return aH=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},aH(s)}function pvt(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 fvt(s){for(var t=1;tgvt||Math.abs(r.height-this.state.lastBoundingBox.height)>gvt)&&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,p=a.offset,f=a.position,x=a.reverseDirection,y=a.useTranslate3d,v=a.viewBox,b=a.wrapperStyle,N=d0n({allowEscapeViewBox:l,coordinate:u,offsetTopLeft:p,position:f,reverseDirection:x,tooltipBox:this.state.lastBoundingBox,useTranslate3d:y,viewBox:v}),S=N.cssClasses,A=N.cssProperties,T=fvt(fvt({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 Dt.createElement("div",{tabIndex:-1,className:S,style:T,ref:function(M){r.wrapperNode=M}},d)}}])}(j.PureComponent),b0n=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},oS={isSsr:b0n(),get:function(t){return oS[t]},set:function(t,n){if(typeof t=="string")oS[t]=n;else{var r=Object.keys(t);r&&r.length&&r.forEach(function(a){oS[a]=t[a]})}}};function iH(s){"@babel/helpers - typeof";return iH=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},iH(s)}function xvt(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 yvt(s){for(var t=1;t0;return Dt.createElement(v0n,{allowEscapeViewBox:l,animationDuration:o,animationEasing:c,isAnimationActive:m,active:i,coordinate:u,hasPayload:T,offset:p,position:y,reverseDirection:v,useTranslate3d:b,viewBox:N,wrapperStyle:S},T0n(d,yvt(yvt({},this.props),{},{payload:A})))}}])}(j.PureComponent);Het(Tg,"displayName","Tooltip");Het(Tg,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!oS.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 M0n=h3,P0n=function(){return M0n.Date.now()},L0n=P0n,I0n=/\s/;function R0n(s){for(var t=s.length;t--&&I0n.test(s.charAt(t)););return t}var D0n=R0n,O0n=D0n,F0n=/^\s+/;function z0n(s){return s&&s.slice(0,O0n(s)+1).replace(F0n,"")}var B0n=z0n,U0n=B0n,vvt=rL,q0n=RG,bvt=NaN,$0n=/^[-+]0x[0-9a-f]+$/i,V0n=/^0b[01]+$/i,H0n=/^0o[0-7]+$/i,G0n=parseInt;function W0n(s){if(typeof s=="number")return s;if(q0n(s))return bvt;if(vvt(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=vvt(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=U0n(s);var n=V0n.test(s);return n||H0n.test(s)?G0n(s.slice(2),n?2:8):$0n.test(s)?bvt:+s}var C$t=W0n,K0n=rL,m7e=L0n,_vt=C$t,Y0n="Expected a function",Z0n=Math.max,X0n=Math.min;function Q0n(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(Y0n);t=_vt(t)||0,K0n(n)&&(u=!!n.leading,h="maxWait"in n,i=h?Z0n(_vt(n.maxWait)||0,t):i,m="trailing"in n?!!n.trailing:m);function p(T){var L=r,M=a;return r=a=void 0,d=T,l=s.apply(M,L),l}function f(T){return d=T,o=setTimeout(v,t),u?p(T):l}function x(T){var L=T-c,M=T-d,I=t-L;return h?X0n(I,i-M):I}function y(T){var L=T-c,M=T-d;return c===void 0||L>=t||L<0||h&&M>=i}function v(){var T=m7e();if(y(T))return b(T);o=setTimeout(v,x(T))}function b(T){return o=void 0,m&&r?p(T):(r=a=void 0,l)}function N(){o!==void 0&&clearTimeout(o),d=0,r=c=a=o=void 0}function S(){return o===void 0?l:b(m7e())}function A(){var T=m7e(),L=y(T);if(r=arguments,a=this,c=T,L){if(o===void 0)return f(c);if(h)return clearTimeout(o),o=setTimeout(v,t),p(c)}return o===void 0&&(o=setTimeout(v,t)),l}return A.cancel=N,A.flush=S,A}var J0n=Q0n,eyn=J0n,tyn=rL,syn="Expected a function";function nyn(s,t,n){var r=!0,a=!0;if(typeof s!="function")throw new TypeError(syn);return tyn(n)&&(r="leading"in n?!!n.leading:r,a="trailing"in n?!!n.trailing:a),eyn(s,t,{leading:r,maxWait:t,trailing:a})}var ryn=nyn;const A$t=od(ryn);function Uee(s){"@babel/helpers - typeof";return Uee=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},Uee(s)}function wvt(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 wle(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&(H=A$t(H,x,{trailing:!0,leading:!1}));var V=new ResizeObserver(H),K=A.current.getBoundingClientRect(),Z=K.width,Q=K.height;return z(Z,Q),V.observe(A.current),function(){V.disconnect()}},[z,x]);var $=j.useMemo(function(){var H=I.containerWidth,V=I.containerHeight;if(H<0||V<0)return null;iS(QD(l)||QD(c),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,l,c),iS(!n||n>0,"The aspect(%s) must be greater than zero.",n);var K=QD(l)?H:l,Z=QD(c)?V:c;n&&n>0&&(K?Z=K/n:Z&&(K=Z*n),m&&Z>m&&(Z=m)),iS(K>0||Z>0,`The width(%s) and height(%s) of chart should be greater than 0, please check the style of container, or the props width(%s) and height(%s), or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the height and width.`,K,Z,l,c,u,h,n);var Q=!Array.isArray(p)&&FA(p.type).endsWith("Chart");return Dt.Children.map(p,function(le){return Dt.isValidElement(le)?j.cloneElement(le,wle({width:K,height:Z},Q?{style:wle({height:"100%",width:"100%",maxHeight:Z,maxWidth:K},le.props.style)}:{})):le})},[n,p,c,m,h,u,I,l]);return Dt.createElement("div",{id:y?"".concat(y):void 0,className:mc("recharts-responsive-container",v),style:wle(wle({},S),{},{width:l,height:c,minWidth:u,minHeight:h,maxHeight:m}),ref:A},$)}),VG=function(t){return null};VG.displayName="Cell";function qee(s){"@babel/helpers - typeof";return qee=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},qee(s)}function Nvt(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 RVe(s){for(var t=1;t1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||oS.isSsr)return{width:0,height:0};var r=yyn(n),a=JSON.stringify({text:t,copyStyle:r});if(nB.widthCache[a])return nB.widthCache[a];try{var i=document.getElementById(kvt);i||(i=document.createElement("span"),i.setAttribute("id",kvt),i.setAttribute("aria-hidden","true"),document.body.appendChild(i));var l=RVe(RVe({},xyn),r);Object.assign(i.style,l),i.textContent="".concat(t);var o=i.getBoundingClientRect(),c={width:o.width,height:o.height};return nB.widthCache[a]=c,++nB.cacheCount>gyn&&(nB.cacheCount=0,nB.widthCache={}),c}catch{return{width:0,height:0}}},vyn=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function $ee(s){"@babel/helpers - typeof";return $ee=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},$ee(s)}function VAe(s,t){return jyn(s)||wyn(s,t)||_yn(s,t)||byn()}function byn(){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 _yn(s,t){if(s){if(typeof s=="string")return Svt(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 Svt(s,t)}}function Svt(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 Oyn(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 Pvt(s,t){return Uyn(s)||Byn(s,t)||zyn(s,t)||Fyn()}function Fyn(){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 zyn(s,t){if(s){if(typeof s=="string")return Lvt(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 Lvt(s,t)}}function Lvt(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 K.reduce(function(Z,Q){var le=Q.word,ue=Q.width,se=Z[Z.length-1];if(se&&(a==null||i||se.width+ue+rQ.width?Z:Q})};if(!u)return p;for(var x="…",y=function(K){var Z=h.slice(0,K),Q=P$t({breakAll:d,style:c,children:Z+x}).wordsWithComputedWidth,le=m(Q),ue=le.length>l||f(le).width>Number(a);return[ue,le]},v=0,b=h.length-1,N=0,S;v<=b&&N<=h.length-1;){var A=Math.floor((v+b)/2),T=A-1,L=y(T),M=Pvt(L,2),I=M[0],R=M[1],z=y(A),$=Pvt(z,1),H=$[0];if(!I&&!H&&(v=A+1),I&&H&&(b=A-1),!I&&H){S=R;break}N++}return S||p},Ivt=function(t){var n=sc(t)?[]:t.toString().split(M$t);return[{words:n}]},$yn=function(t){var n=t.width,r=t.scaleToFit,a=t.children,i=t.style,l=t.breakAll,o=t.maxLines;if((n||r)&&!oS.isSsr){var c,d,u=P$t({breakAll:l,children:a,style:i});if(u){var h=u.wordsWithComputedWidth,m=u.spaceWidth;c=h,d=m}else return Ivt(a);return qyn({breakAll:l,children:a,maxLines:o,style:i},c,d,n,r)}return Ivt(a)},Rvt="#808080",F7=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,p=m===void 0?"start":m,f=t.verticalAnchor,x=f===void 0?"end":f,y=t.fill,v=y===void 0?Rvt:y,b=Mvt(t,Ryn),N=j.useMemo(function(){return $yn({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,T=b.angle,L=b.className,M=b.breakAll,I=Mvt(b,Dyn);if(!o0(r)||!o0(i))return null;var R=r+(Wa(S)?S:0),z=i+(Wa(A)?A:0),$;switch(x){case"start":$=p7e("calc(".concat(d,")"));break;case"middle":$=p7e("calc(".concat((N.length-1)/2," * -").concat(o," + (").concat(d," / 2))"));break;default:$=p7e("calc(".concat(N.length-1," * -").concat(o,")"));break}var H=[];if(h){var V=N[0].width,K=b.width;H.push("scale(".concat((Wa(K)?K/V:1)/V,")"))}return T&&H.push("rotate(".concat(T,", ").concat(R,", ").concat(z,")")),H.length&&(I.transform=H.join(" ")),Dt.createElement("text",DVe({},Io(I,!0),{x:R,y:z,className:mc("recharts-text",L),textAnchor:p,fill:v.includes("url")?Rvt:v}),N.map(function(Z,Q){var le=Z.words.join(M?"":" ");return Dt.createElement("tspan",{x:R,dy:Q===0?$:o,key:"".concat(le,"-").concat(Q)},le)}))};function WM(s,t){return s==null||t==null?NaN:st?1:s>=t?0:NaN}function Vyn(s,t){return s==null||t==null?NaN:ts?1:t>=s?0:NaN}function Get(s){let t,n,r;s.length!==2?(t=WM,n=(o,c)=>WM(s(o),c),r=(o,c)=>s(o)-c):(t=s===WM||s===Vyn?s:Hyn,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 Hyn(){return 0}function L$t(s){return s===null?NaN:+s}function*Gyn(s,t){for(let n of s)n!=null&&(n=+n)>=n&&(yield n)}const Wyn=Get(WM),Tre=Wyn.right;Get(L$t).center;class Dvt extends Map{constructor(t,n=Zyn){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(Ovt(this,t))}has(t){return super.has(Ovt(this,t))}set(t,n){return super.set(Kyn(this,t),n)}delete(t){return super.delete(Yyn(this,t))}}function Ovt({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):n}function Kyn({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):(s.set(r,n),n)}function Yyn({_intern:s,_key:t},n){const r=t(n);return s.has(r)&&(n=s.get(r),s.delete(r)),n}function Zyn(s){return s!==null&&typeof s=="object"?s.valueOf():s}function Xyn(s=WM){if(s===WM)return I$t;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 I$t(s,t){return(s==null||!(s>=s))-(t==null||!(t>=t))||(st?1:0)}const Qyn=Math.sqrt(50),Jyn=Math.sqrt(10),evn=Math.sqrt(2);function HAe(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>=Qyn?10:i>=Jyn?5:i>=evn?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 zvt(s,t){let n;for(const r of s)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);return n}function R$t(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?I$t:Xyn(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),p=Math.max(n,Math.floor(t-d*h/c+m)),f=Math.min(r,Math.floor(t+(c-d)*h/c+m));R$t(s,t,p,f,a)}const i=s[t];let l=n,o=r;for(mY(s,n,t),a(s[r],i)>0&&mY(s,n,r);l0;)--o}a(s[n],i)===0?mY(s,n,o):(++o,mY(s,o,r)),o<=t&&(n=o+1),t<=o&&(r=o-1)}return s}function mY(s,t,n){const r=s[t];s[t]=s[n],s[n]=r}function tvn(s,t,n){if(s=Float64Array.from(Gyn(s)),!(!(r=s.length)||isNaN(t=+t))){if(t<=0||r<2)return zvt(s);if(t>=1)return Fvt(s);var r,a=(r-1)*t,i=Math.floor(a),l=Fvt(R$t(s,i).subarray(0,i+1)),o=zvt(s.subarray(i+1));return l+(o-l)*(a-i)}}function svn(s,t,n=L$t){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 nvn(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?Nle(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?Nle(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=avn.exec(s))?new v_(t[1],t[2],t[3],1):(t=ivn.exec(s))?new v_(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=ovn.exec(s))?Nle(t[1],t[2],t[3],t[4]):(t=lvn.exec(s))?Nle(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=cvn.exec(s))?Gvt(t[1],t[2]/100,t[3]/100,1):(t=dvn.exec(s))?Gvt(t[1],t[2]/100,t[3]/100,t[4]):Bvt.hasOwnProperty(s)?$vt(Bvt[s]):s==="transparent"?new v_(NaN,NaN,NaN,0):null}function $vt(s){return new v_(s>>16&255,s>>8&255,s&255,1)}function Nle(s,t,n,r){return r<=0&&(s=t=n=NaN),new v_(s,t,n,r)}function mvn(s){return s instanceof Mre||(s=Wee(s)),s?(s=s.rgb(),new v_(s.r,s.g,s.b,s.opacity)):new v_}function UVe(s,t,n,r){return arguments.length===1?mvn(s):new v_(s,t,n,r??1)}function v_(s,t,n,r){this.r=+s,this.g=+t,this.b=+n,this.opacity=+r}Ket(v_,UVe,O$t(Mre,{brighter(s){return s=s==null?GAe:Math.pow(GAe,s),new v_(this.r*s,this.g*s,this.b*s,this.opacity)},darker(s){return s=s==null?Hee:Math.pow(Hee,s),new v_(this.r*s,this.g*s,this.b*s,this.opacity)},rgb(){return this},clamp(){return new v_(e7(this.r),e7(this.g),e7(this.b),WAe(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:Vvt,formatHex:Vvt,formatHex8:pvn,formatRgb:Hvt,toString:Hvt}));function Vvt(){return`#${JD(this.r)}${JD(this.g)}${JD(this.b)}`}function pvn(){return`#${JD(this.r)}${JD(this.g)}${JD(this.b)}${JD((isNaN(this.opacity)?1:this.opacity)*255)}`}function Hvt(){const s=WAe(this.opacity);return`${s===1?"rgb(":"rgba("}${e7(this.r)}, ${e7(this.g)}, ${e7(this.b)}${s===1?")":`, ${s})`}`}function WAe(s){return isNaN(s)?1:Math.max(0,Math.min(1,s))}function e7(s){return Math.max(0,Math.min(255,Math.round(s)||0))}function JD(s){return s=e7(s),(s<16?"0":"")+s.toString(16)}function Gvt(s,t,n,r){return r<=0?s=t=n=NaN:n<=0||n>=1?s=t=NaN:t<=0&&(s=NaN),new Vk(s,t,n,r)}function F$t(s){if(s instanceof Vk)return new Vk(s.h,s.s,s.l,s.opacity);if(s instanceof Mre||(s=Wee(s)),!s)return new Vk;if(s instanceof Vk)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 Vk(l,o,c,s.opacity)}function fvn(s,t,n,r){return arguments.length===1?F$t(s):new Vk(s,t,n,r??1)}function Vk(s,t,n,r){this.h=+s,this.s=+t,this.l=+n,this.opacity=+r}Ket(Vk,fvn,O$t(Mre,{brighter(s){return s=s==null?GAe:Math.pow(GAe,s),new Vk(this.h,this.s,this.l*s,this.opacity)},darker(s){return s=s==null?Hee:Math.pow(Hee,s),new Vk(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 v_(f7e(s>=240?s-240:s+120,a,r),f7e(s,a,r),f7e(s<120?s+240:s-120,a,r),this.opacity)},clamp(){return new Vk(Wvt(this.h),kle(this.s),kle(this.l),WAe(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=WAe(this.opacity);return`${s===1?"hsl(":"hsla("}${Wvt(this.h)}, ${kle(this.s)*100}%, ${kle(this.l)*100}%${s===1?")":`, ${s})`}`}}));function Wvt(s){return s=(s||0)%360,s<0?s+360:s}function kle(s){return Math.max(0,Math.min(1,s||0))}function f7e(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 Yet=s=>()=>s;function gvn(s,t){return function(n){return s+n*t}}function xvn(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 yvn(s){return(s=+s)==1?z$t:function(t,n){return n-t?xvn(t,n,s):Yet(isNaN(t)?n:t)}}function z$t(s,t){var n=t-s;return n?gvn(s,n):Yet(isNaN(s)?t:s)}const Kvt=function s(t){var n=yvn(t);function r(a,i){var l=n((a=UVe(a)).r,(i=UVe(i)).r),o=n(a.g,i.g),c=n(a.b,i.b),d=z$t(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 vvn(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:KAe(r,a)})),n=g7e.lastIndex;return nt&&(n=s,s=t,t=n),function(r){return Math.max(s,Math.min(t,r))}}function Tvn(s,t,n){var r=s[0],a=s[1],i=t[0],l=t[1];return a2?Mvn:Tvn,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),KAe)))(m)))},h.domain=function(m){return arguments.length?(s=Array.from(m,YAe),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=Zet,u()},h.clamp=function(m){return arguments.length?(l=m?!0:ab,u()):l!==ab},h.interpolate=function(m){return arguments.length?(n=m,u()):n},h.unknown=function(m){return arguments.length?(i=m,h):i},function(m,p){return r=m,a=p,u()}}function Xet(){return hLe()(ab,ab)}function Pvn(s){return Math.abs(s=Math.round(s))>=1e21?s.toLocaleString("en").replace(/,/g,""):s.toString(10)}function ZAe(s,t){if((n=(s=t?s.toExponential(t-1):s.toExponential()).indexOf("e"))<0)return null;var n,r=s.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+s.slice(n+1)]}function oH(s){return s=ZAe(Math.abs(s)),s?s[1]:NaN}function Lvn(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 Ivn(s){return function(t){return t.replace(/[0-9]/g,function(n){return s[+n]})}}var Rvn=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Kee(s){if(!(t=Rvn.exec(s)))throw new Error("invalid format: "+s);var t;return new Qet({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]})}Kee.prototype=Qet.prototype;function Qet(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+""}Qet.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 Dvn(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 B$t;function Ovn(s,t){var n=ZAe(s,t);if(!n)return s+"";var r=n[0],a=n[1],i=a-(B$t=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")+ZAe(s,Math.max(0,t+i-1))[0]}function Zvt(s,t){var n=ZAe(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 Xvt={"%":(s,t)=>(s*100).toFixed(t),b:s=>Math.round(s).toString(2),c:s=>s+"",d:Pvn,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)=>Zvt(s*100,t),r:Zvt,s:Ovn,X:s=>Math.round(s).toString(16).toUpperCase(),x:s=>Math.round(s).toString(16)};function Qvt(s){return s}var Jvt=Array.prototype.map,e1t=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function Fvn(s){var t=s.grouping===void 0||s.thousands===void 0?Qvt:Lvn(Jvt.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?Qvt:Ivn(Jvt.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){h=Kee(h);var m=h.fill,p=h.align,f=h.sign,x=h.symbol,y=h.zero,v=h.width,b=h.comma,N=h.precision,S=h.trim,A=h.type;A==="n"?(b=!0,A="g"):Xvt[A]||(N===void 0&&(N=12),S=!0,A="g"),(y||m==="0"&&p==="=")&&(y=!0,m="0",p="=");var T=x==="$"?n:x==="#"&&/[boxX]/.test(A)?"0"+A.toLowerCase():"",L=x==="$"?r:/[%p]/.test(A)?l:"",M=Xvt[A],I=/[defgprs%]/.test(A);N=N===void 0?6:/[gprs]/.test(A)?Math.max(1,Math.min(21,N)):Math.max(0,Math.min(20,N));function R(z){var $=T,H=L,V,K,Z;if(A==="c")H=M(z)+H,z="";else{z=+z;var Q=z<0||1/z<0;if(z=isNaN(z)?c:M(Math.abs(z),N),S&&(z=Dvn(z)),Q&&+z==0&&f!=="+"&&(Q=!1),$=(Q?f==="("?f:o:f==="-"||f==="("?"":f)+$,H=(A==="s"?e1t[8+B$t/3]:"")+H+(Q&&f==="("?")":""),I){for(V=-1,K=z.length;++VZ||Z>57){H=(Z===46?a+z.slice(V+1):z.slice(V))+H,z=z.slice(0,V);break}}}b&&!y&&(z=t(z,1/0));var le=$.length+z.length+H.length,ue=le>1)+$+z+H+ue.slice(le);break;default:z=ue+$+z+H;break}return i(z)}return R.toString=function(){return h+""},R}function u(h,m){var p=d((h=Kee(h),h.type="f",h)),f=Math.max(-8,Math.min(8,Math.floor(oH(m)/3)))*3,x=Math.pow(10,-f),y=e1t[8+f/3];return function(v){return p(x*v)+y}}return{format:d,formatPrefix:u}}var Sle,Jet,U$t;zvn({thousands:",",grouping:[3],currency:["$",""]});function zvn(s){return Sle=Fvn(s),Jet=Sle.format,U$t=Sle.formatPrefix,Sle}function Bvn(s){return Math.max(0,-oH(Math.abs(s)))}function Uvn(s,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(oH(t)/3)))*3-oH(Math.abs(s)))}function qvn(s,t){return s=Math.abs(s),t=Math.abs(t)-s,Math.max(0,oH(t)-oH(s))+1}function q$t(s,t,n,r){var a=zVe(s,t,n),i;switch(r=Kee(r??",f"),r.type){case"s":{var l=Math.max(Math.abs(s),Math.abs(t));return r.precision==null&&!isNaN(i=Uvn(a,l))&&(r.precision=i),U$t(r,l)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(i=qvn(a,Math.max(Math.abs(s),Math.abs(t))))&&(r.precision=i-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(i=Bvn(a))&&(r.precision=i-(r.type==="%")*2);break}}return Jet(r)}function aL(s){var t=s.domain;return s.ticks=function(n){var r=t();return OVe(r[0],r[r.length-1],n??10)},s.tickFormat=function(n,r){var a=t();return q$t(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=FVe(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 XAe(){var s=Xet();return s.copy=function(){return Pre(s,XAe())},AN.apply(s,arguments),aL(s)}function $$t(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,YAe),n):s.slice()},n.unknown=function(r){return arguments.length?(t=r,n):t},n.copy=function(){return $$t(s).unknown(t)},s=arguments.length?Array.from(s,YAe):[0,1],aL(n)}function V$t(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 Wvn(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 n1t(s){return(t,n)=>-s(-t,n)}function ett(s){const t=s(t1t,s1t),n=t.domain;let r=10,a,i;function l(){return a=Wvn(r),i=Gvn(r),n()[0]<0?(a=n1t(a),i=n1t(i),s($vn,Vvn)):s(t1t,s1t),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<=p;++m)for(f=1;fu)break;v.push(x)}}else for(;m<=p;++m)for(f=r-1;f>=1;--f)if(x=m>0?f/i(-m):f*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=Kee(c)).precision==null&&(c.trim=!0),c=Jet(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(V$t(n(),{floor:o=>i(Math.floor(a(o))),ceil:o=>i(Math.ceil(a(o)))})),t}function H$t(){const s=ett(hLe()).domain([1,10]);return s.copy=()=>Pre(s,H$t()).base(s.base()),AN.apply(s,arguments),s}function r1t(s){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/s))}}function a1t(s){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*s}}function ttt(s){var t=1,n=s(r1t(t),a1t(t));return n.constant=function(r){return arguments.length?s(r1t(t=+r),a1t(t)):t},aL(n)}function G$t(){var s=ttt(hLe());return s.copy=function(){return Pre(s,G$t()).constant(s.constant())},AN.apply(s,arguments)}function i1t(s){return function(t){return t<0?-Math.pow(-t,s):Math.pow(t,s)}}function Kvn(s){return s<0?-Math.sqrt(-s):Math.sqrt(s)}function Yvn(s){return s<0?-s*s:s*s}function stt(s){var t=s(ab,ab),n=1;function r(){return n===1?s(ab,ab):n===.5?s(Kvn,Yvn):s(i1t(n),i1t(1/n))}return t.exponent=function(a){return arguments.length?(n=+a,r()):n},aL(t)}function ntt(){var s=stt(hLe());return s.copy=function(){return Pre(s,ntt()).exponent(s.exponent())},AN.apply(s,arguments),s}function Zvn(){return ntt.apply(null,arguments).exponent(.5)}function o1t(s){return Math.sign(s)*s*s}function Xvn(s){return Math.sign(s)*Math.sqrt(Math.abs(s))}function W$t(){var s=Xet(),t=[0,1],n=!1,r;function a(i){var l=Xvn(s(i));return isNaN(l)?r:n?Math.round(l):l}return a.invert=function(i){return s.invert(o1t(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,YAe)).map(o1t)),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 W$t(s.domain(),t).round(n).clamp(s.clamp()).unknown(r)},AN.apply(a,arguments),aL(a)}function K$t(){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 Y$t().domain([s,t]).range(a).unknown(i)},AN.apply(aL(l),arguments)}function Z$t(){var s=[.5],t=[0,1],n,r=1;function a(i){return i!=null&&i<=i?t[Tre(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 Z$t().domain(s).range(t).unknown(n)},AN.apply(a,arguments)}const x7e=new Date,y7e=new Date;function w0(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(dw0(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)=>(x7e.setTime(+i),y7e.setTime(+l),s(x7e),s(y7e),Math.floor(n(x7e,y7e))),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 QAe=w0(()=>{},(s,t)=>{s.setTime(+s+t)},(s,t)=>t-s);QAe.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?w0(t=>{t.setTime(Math.floor(t/s)*s)},(t,n)=>{t.setTime(+t+n*s)},(t,n)=>(n-t)/s):QAe);QAe.range;const yA=1e3,U2=yA*60,vA=U2*60,rE=vA*24,rtt=rE*7,l1t=rE*30,v7e=rE*365,eO=w0(s=>{s.setTime(s-s.getMilliseconds())},(s,t)=>{s.setTime(+s+t*yA)},(s,t)=>(t-s)/yA,s=>s.getUTCSeconds());eO.range;const att=w0(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*yA)},(s,t)=>{s.setTime(+s+t*U2)},(s,t)=>(t-s)/U2,s=>s.getMinutes());att.range;const itt=w0(s=>{s.setUTCSeconds(0,0)},(s,t)=>{s.setTime(+s+t*U2)},(s,t)=>(t-s)/U2,s=>s.getUTCMinutes());itt.range;const ott=w0(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*yA-s.getMinutes()*U2)},(s,t)=>{s.setTime(+s+t*vA)},(s,t)=>(t-s)/vA,s=>s.getHours());ott.range;const ltt=w0(s=>{s.setUTCMinutes(0,0,0)},(s,t)=>{s.setTime(+s+t*vA)},(s,t)=>(t-s)/vA,s=>s.getUTCHours());ltt.range;const Lre=w0(s=>s.setHours(0,0,0,0),(s,t)=>s.setDate(s.getDate()+t),(s,t)=>(t-s-(t.getTimezoneOffset()-s.getTimezoneOffset())*U2)/rE,s=>s.getDate()-1);Lre.range;const mLe=w0(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/rE,s=>s.getUTCDate()-1);mLe.range;const X$t=w0(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/rE,s=>Math.floor(s/rE));X$t.range;function C9(s){return w0(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())*U2)/rtt)}const pLe=C9(0),JAe=C9(1),Qvn=C9(2),Jvn=C9(3),lH=C9(4),e1n=C9(5),t1n=C9(6);pLe.range;JAe.range;Qvn.range;Jvn.range;lH.range;e1n.range;t1n.range;function A9(s){return w0(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)/rtt)}const fLe=A9(0),eEe=A9(1),s1n=A9(2),n1n=A9(3),cH=A9(4),r1n=A9(5),a1n=A9(6);fLe.range;eEe.range;s1n.range;n1n.range;cH.range;r1n.range;a1n.range;const ctt=w0(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());ctt.range;const dtt=w0(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());dtt.range;const aE=w0(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());aE.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:w0(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)});aE.range;const iE=w0(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());iE.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:w0(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)});iE.range;function Q$t(s,t,n,r,a,i){const l=[[eO,1,yA],[eO,5,5*yA],[eO,15,15*yA],[eO,30,30*yA],[i,1,U2],[i,5,5*U2],[i,15,15*U2],[i,30,30*U2],[a,1,vA],[a,3,3*vA],[a,6,6*vA],[a,12,12*vA],[r,1,rE],[r,2,2*rE],[n,1,rtt],[t,1,l1t],[t,3,3*l1t],[s,1,v7e]];function o(d,u,h){const m=uy).right(l,m);if(p===l.length)return s.every(zVe(d/v7e,u/v7e,h));if(p===0)return QAe.every(Math.max(zVe(d,u,h),1));const[f,x]=l[m/l[p-1][2]53)return null;"w"in Se||(Se.w=1),"Z"in Se?(Ae=_7e(pY(Se.y,0,1)),Fe=Ae.getUTCDay(),Ae=Fe>4||Fe===0?eEe.ceil(Ae):eEe(Ae),Ae=mLe.offset(Ae,(Se.V-1)*7),Se.y=Ae.getUTCFullYear(),Se.m=Ae.getUTCMonth(),Se.d=Ae.getUTCDate()+(Se.w+6)%7):(Ae=b7e(pY(Se.y,0,1)),Fe=Ae.getDay(),Ae=Fe>4||Fe===0?JAe.ceil(Ae):JAe(Ae),Ae=Lre.offset(Ae,(Se.V-1)*7),Se.y=Ae.getFullYear(),Se.m=Ae.getMonth(),Se.d=Ae.getDate()+(Se.w+6)%7)}else("W"in Se||"U"in Se)&&("w"in Se||(Se.w="u"in Se?Se.u%7:"W"in Se?1:0),Fe="Z"in Se?_7e(pY(Se.y,0,1)).getUTCDay():b7e(pY(Se.y,0,1)).getDay(),Se.m=0,Se.d="W"in Se?(Se.w+6)%7+Se.W*7-(Fe+5)%7:Se.w+Se.U*7-(Fe+6)%7);return"Z"in Se?(Se.H+=Se.Z/100|0,Se.M+=Se.Z%100,_7e(Se)):b7e(Se)}}function M(Te,Me,Oe,Se){for(var Qe=0,Ae=Me.length,Fe=Oe.length,Ne,$e;Qe=Fe)return-1;if(Ne=Me.charCodeAt(Qe++),Ne===37){if(Ne=Me.charAt(Qe++),$e=A[Ne in c1t?Me.charAt(Qe++):Ne],!$e||(Se=$e(Te,Oe,Se))<0)return-1}else if(Ne!=Oe.charCodeAt(Se++))return-1}return Se}function I(Te,Me,Oe){var Se=d.exec(Me.slice(Oe));return Se?(Te.p=u.get(Se[0].toLowerCase()),Oe+Se[0].length):-1}function R(Te,Me,Oe){var Se=p.exec(Me.slice(Oe));return Se?(Te.w=f.get(Se[0].toLowerCase()),Oe+Se[0].length):-1}function z(Te,Me,Oe){var Se=h.exec(Me.slice(Oe));return Se?(Te.w=m.get(Se[0].toLowerCase()),Oe+Se[0].length):-1}function $(Te,Me,Oe){var Se=v.exec(Me.slice(Oe));return Se?(Te.m=b.get(Se[0].toLowerCase()),Oe+Se[0].length):-1}function H(Te,Me,Oe){var Se=x.exec(Me.slice(Oe));return Se?(Te.m=y.get(Se[0].toLowerCase()),Oe+Se[0].length):-1}function V(Te,Me,Oe){return M(Te,t,Me,Oe)}function K(Te,Me,Oe){return M(Te,n,Me,Oe)}function Z(Te,Me,Oe){return M(Te,r,Me,Oe)}function Q(Te){return l[Te.getDay()]}function le(Te){return i[Te.getDay()]}function ue(Te){return c[Te.getMonth()]}function se(Te){return o[Te.getMonth()]}function ne(Te){return a[+(Te.getHours()>=12)]}function ie(Te){return 1+~~(Te.getMonth()/3)}function ce(Te){return l[Te.getUTCDay()]}function je(Te){return i[Te.getUTCDay()]}function be(Te){return c[Te.getUTCMonth()]}function he(Te){return o[Te.getUTCMonth()]}function ge(Te){return a[+(Te.getUTCHours()>=12)]}function ke(Te){return 1+~~(Te.getUTCMonth()/3)}return{format:function(Te){var Me=T(Te+="",N);return Me.toString=function(){return Te},Me},parse:function(Te){var Me=L(Te+="",!1);return Me.toString=function(){return Te},Me},utcFormat:function(Te){var Me=T(Te+="",S);return Me.toString=function(){return Te},Me},utcParse:function(Te){var Me=L(Te+="",!0);return Me.toString=function(){return Te},Me}}}var c1t={"-":"",_:" ",0:"0"},gy=/^\s*\d+/,u1n=/^%/,h1n=/[\\^$*+?|[\]().{}]/g;function Tu(s,t,n){var r=s<0?"-":"",a=(r?-s:s)+"",i=a.length;return r+(i[t.toLowerCase(),n]))}function p1n(s,t,n){var r=gy.exec(t.slice(n,n+1));return r?(s.w=+r[0],n+r[0].length):-1}function f1n(s,t,n){var r=gy.exec(t.slice(n,n+1));return r?(s.u=+r[0],n+r[0].length):-1}function g1n(s,t,n){var r=gy.exec(t.slice(n,n+2));return r?(s.U=+r[0],n+r[0].length):-1}function x1n(s,t,n){var r=gy.exec(t.slice(n,n+2));return r?(s.V=+r[0],n+r[0].length):-1}function y1n(s,t,n){var r=gy.exec(t.slice(n,n+2));return r?(s.W=+r[0],n+r[0].length):-1}function d1t(s,t,n){var r=gy.exec(t.slice(n,n+4));return r?(s.y=+r[0],n+r[0].length):-1}function u1t(s,t,n){var r=gy.exec(t.slice(n,n+2));return r?(s.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function v1n(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 b1n(s,t,n){var r=gy.exec(t.slice(n,n+1));return r?(s.q=r[0]*3-3,n+r[0].length):-1}function _1n(s,t,n){var r=gy.exec(t.slice(n,n+2));return r?(s.m=r[0]-1,n+r[0].length):-1}function h1t(s,t,n){var r=gy.exec(t.slice(n,n+2));return r?(s.d=+r[0],n+r[0].length):-1}function w1n(s,t,n){var r=gy.exec(t.slice(n,n+3));return r?(s.m=0,s.d=+r[0],n+r[0].length):-1}function m1t(s,t,n){var r=gy.exec(t.slice(n,n+2));return r?(s.H=+r[0],n+r[0].length):-1}function j1n(s,t,n){var r=gy.exec(t.slice(n,n+2));return r?(s.M=+r[0],n+r[0].length):-1}function N1n(s,t,n){var r=gy.exec(t.slice(n,n+2));return r?(s.S=+r[0],n+r[0].length):-1}function k1n(s,t,n){var r=gy.exec(t.slice(n,n+3));return r?(s.L=+r[0],n+r[0].length):-1}function S1n(s,t,n){var r=gy.exec(t.slice(n,n+6));return r?(s.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function C1n(s,t,n){var r=u1n.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function A1n(s,t,n){var r=gy.exec(t.slice(n));return r?(s.Q=+r[0],n+r[0].length):-1}function E1n(s,t,n){var r=gy.exec(t.slice(n));return r?(s.s=+r[0],n+r[0].length):-1}function p1t(s,t){return Tu(s.getDate(),t,2)}function T1n(s,t){return Tu(s.getHours(),t,2)}function M1n(s,t){return Tu(s.getHours()%12||12,t,2)}function P1n(s,t){return Tu(1+Lre.count(aE(s),s),t,3)}function J$t(s,t){return Tu(s.getMilliseconds(),t,3)}function L1n(s,t){return J$t(s,t)+"000"}function I1n(s,t){return Tu(s.getMonth()+1,t,2)}function R1n(s,t){return Tu(s.getMinutes(),t,2)}function D1n(s,t){return Tu(s.getSeconds(),t,2)}function O1n(s){var t=s.getDay();return t===0?7:t}function F1n(s,t){return Tu(pLe.count(aE(s)-1,s),t,2)}function eVt(s){var t=s.getDay();return t>=4||t===0?lH(s):lH.ceil(s)}function z1n(s,t){return s=eVt(s),Tu(lH.count(aE(s),s)+(aE(s).getDay()===4),t,2)}function B1n(s){return s.getDay()}function U1n(s,t){return Tu(JAe.count(aE(s)-1,s),t,2)}function q1n(s,t){return Tu(s.getFullYear()%100,t,2)}function $1n(s,t){return s=eVt(s),Tu(s.getFullYear()%100,t,2)}function V1n(s,t){return Tu(s.getFullYear()%1e4,t,4)}function H1n(s,t){var n=s.getDay();return s=n>=4||n===0?lH(s):lH.ceil(s),Tu(s.getFullYear()%1e4,t,4)}function G1n(s){var t=s.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+Tu(t/60|0,"0",2)+Tu(t%60,"0",2)}function f1t(s,t){return Tu(s.getUTCDate(),t,2)}function W1n(s,t){return Tu(s.getUTCHours(),t,2)}function K1n(s,t){return Tu(s.getUTCHours()%12||12,t,2)}function Y1n(s,t){return Tu(1+mLe.count(iE(s),s),t,3)}function tVt(s,t){return Tu(s.getUTCMilliseconds(),t,3)}function Z1n(s,t){return tVt(s,t)+"000"}function X1n(s,t){return Tu(s.getUTCMonth()+1,t,2)}function Q1n(s,t){return Tu(s.getUTCMinutes(),t,2)}function J1n(s,t){return Tu(s.getUTCSeconds(),t,2)}function ebn(s){var t=s.getUTCDay();return t===0?7:t}function tbn(s,t){return Tu(fLe.count(iE(s)-1,s),t,2)}function sVt(s){var t=s.getUTCDay();return t>=4||t===0?cH(s):cH.ceil(s)}function sbn(s,t){return s=sVt(s),Tu(cH.count(iE(s),s)+(iE(s).getUTCDay()===4),t,2)}function nbn(s){return s.getUTCDay()}function rbn(s,t){return Tu(eEe.count(iE(s)-1,s),t,2)}function abn(s,t){return Tu(s.getUTCFullYear()%100,t,2)}function ibn(s,t){return s=sVt(s),Tu(s.getUTCFullYear()%100,t,2)}function obn(s,t){return Tu(s.getUTCFullYear()%1e4,t,4)}function lbn(s,t){var n=s.getUTCDay();return s=n>=4||n===0?cH(s):cH.ceil(s),Tu(s.getUTCFullYear()%1e4,t,4)}function cbn(){return"+0000"}function g1t(){return"%"}function x1t(s){return+s}function y1t(s){return Math.floor(+s/1e3)}var rB,nVt,rVt;dbn({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 dbn(s){return rB=d1n(s),nVt=rB.format,rB.parse,rVt=rB.utcFormat,rB.utcParse,rB}function ubn(s){return new Date(s)}function hbn(s){return s instanceof Date?+s:+new Date(+s)}function utt(s,t,n,r,a,i,l,o,c,d){var u=Xet(),h=u.invert,m=u.domain,p=d(".%L"),f=d(":%S"),x=d("%I:%M"),y=d("%I %p"),v=d("%a %d"),b=d("%b %d"),N=d("%B"),S=d("%Y");function A(T){return(c(T)t(a/(s.length-1)))},n.quantiles=function(r){return Array.from({length:r+1},(a,i)=>tvn(s,i/r))},n.copy=function(){return lVt(t).domain(s)},NE.apply(n,arguments)}function xLe(){var s=0,t=.5,n=1,r=1,a,i,l,o,c,d=ab,u,h=!1,m;function p(x){return isNaN(x=+x)?m:(x=.5+((x=+u(x))-i)*(r*xt}var hVt=vbn,bbn=yLe,_bn=hVt,wbn=$G;function jbn(s){return s&&s.length?bbn(s,wbn,_bn):void 0}var Nbn=jbn;const rM=od(Nbn);function kbn(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};uo.decimalPlaces=uo.dp=function(){var s=this,t=s.d.length-1,n=(t-s.e)*np;if(t=s.d[t],t)for(;t%10==0;t/=10)n--;return n<0?0:n};uo.dividedBy=uo.div=function(s){return zA(this,new this.constructor(s))};uo.dividedToIntegerBy=uo.idiv=function(s){var t=this,n=t.constructor;return pm(zA(t,new n(s),0,1),n.precision)};uo.equals=uo.eq=function(s){return!this.cmp(s)};uo.exponent=function(){return Nx(this)};uo.greaterThan=uo.gt=function(s){return this.cmp(s)>0};uo.greaterThanOrEqualTo=uo.gte=function(s){return this.cmp(s)>=0};uo.isInteger=uo.isint=function(){return this.e>this.d.length-2};uo.isNegative=uo.isneg=function(){return this.s<0};uo.isPositive=uo.ispos=function(){return this.s>0};uo.isZero=function(){return this.s===0};uo.lessThan=uo.lt=function(s){return this.cmp(s)<0};uo.lessThanOrEqualTo=uo.lte=function(s){return this.cmp(s)<1};uo.logarithm=uo.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(Uw))throw Error(mN+"NaN");if(n.s<1)throw Error(mN+(n.s?"NaN":"-Infinity"));return n.eq(Uw)?new r(0):(Fp=!1,t=zA(Yee(n,i),Yee(s,i),i),Fp=!0,pm(t,a))};uo.minus=uo.sub=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?xVt(t,s):fVt(t,(s.s=-s.s,s))};uo.modulo=uo.mod=function(s){var t,n=this,r=n.constructor,a=r.precision;if(s=new r(s),!s.s)throw Error(mN+"NaN");return n.s?(Fp=!1,t=zA(n,s,0,1).times(s),Fp=!0,n.minus(t)):pm(new r(n),a)};uo.naturalExponential=uo.exp=function(){return gVt(this)};uo.naturalLogarithm=uo.ln=function(){return Yee(this)};uo.negated=uo.neg=function(){var s=new this.constructor(this);return s.s=-s.s||0,s};uo.plus=uo.add=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?fVt(t,s):xVt(t,(s.s=-s.s,s))};uo.precision=uo.sd=function(s){var t,n,r,a=this;if(s!==void 0&&s!==!!s&&s!==1&&s!==0)throw Error(t7+s);if(t=Nx(a)+1,r=a.d.length-1,n=r*np+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};uo.squareRoot=uo.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(mN+"NaN")}for(s=Nx(o),Fp=!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=WG((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(zA(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(pm(i,n+1,0),i.times(i).eq(o)){r=i;break}}else if(t!="9999")break;l+=4}return Fp=!0,pm(r,n)};uo.times=uo.mul=function(s){var t,n,r,a,i,l,o,c,d,u=this,h=u.constructor,m=u.d,p=(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=p.length,c=0;){for(t=0,a=c+r;a>r;)o=i[a]+p[r]*m[a-r-1]+t,i[a--]=o%Y0|0,t=o/Y0|0;i[a]=(i[a]+t)%Y0|0}for(;!i[--l];)i.pop();return t?++n:i.shift(),s.d=i,s.e=n,Fp?pm(s,h.precision):s};uo.toDecimalPlaces=uo.todp=function(s,t){var n=this,r=n.constructor;return n=new r(n),s===void 0?n:(e3(s,0,GG),t===void 0?t=r.rounding:e3(t,0,8),pm(n,s+Nx(n)+1,t))};uo.toExponential=function(s,t){var n,r=this,a=r.constructor;return s===void 0?n=B7(r,!0):(e3(s,0,GG),t===void 0?t=a.rounding:e3(t,0,8),r=pm(new a(r),s+1,t),n=B7(r,!0,s+1)),n};uo.toFixed=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?B7(a):(e3(s,0,GG),t===void 0?t=i.rounding:e3(t,0,8),r=pm(new i(a),s+Nx(a)+1,t),n=B7(r.abs(),!1,s+Nx(r)+1),a.isneg()&&!a.isZero()?"-"+n:n)};uo.toInteger=uo.toint=function(){var s=this,t=s.constructor;return pm(new t(s),Nx(s)+1,t.rounding)};uo.toNumber=function(){return+this};uo.toPower=uo.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(Uw);if(o=new c(o),!o.s){if(s.s<1)throw Error(mN+"Infinity");return o}if(o.eq(Uw))return o;if(r=c.precision,s.eq(Uw))return pm(o,r);if(t=s.e,n=s.d.length-1,l=t>=n,i=o.s,l){if((n=u<0?-u:u)<=pVt){for(a=new c(Uw),t=Math.ceil(r/np+4),Fp=!1;n%2&&(a=a.times(o),_1t(a.d,t)),n=WG(n/2),n!==0;)o=o.times(o),_1t(o.d,t);return Fp=!0,s.s<0?new c(Uw).div(a):pm(a,r)}}else if(i<0)throw Error(mN+"NaN");return i=i<0&&s.d[Math.max(t,n)]&1?-1:1,o.s=1,Fp=!1,a=s.times(Yee(o,r+d)),Fp=!0,a=gVt(a),a.s=i,a};uo.toPrecision=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?(n=Nx(a),r=B7(a,n<=i.toExpNeg||n>=i.toExpPos)):(e3(s,1,GG),t===void 0?t=i.rounding:e3(t,0,8),a=pm(new i(a),s,t),n=Nx(a),r=B7(a,s<=n||n<=i.toExpNeg,s)),r};uo.toSignificantDigits=uo.tosd=function(s,t){var n=this,r=n.constructor;return s===void 0?(s=r.precision,t=r.rounding):(e3(s,1,GG),t===void 0?t=r.rounding:e3(t,0,8)),pm(new r(n),s,t)};uo.toString=uo.valueOf=uo.val=uo.toJSON=uo[Symbol.for("nodejs.util.inspect.custom")]=function(){var s=this,t=Nx(s),n=s.constructor;return B7(s,t<=n.toExpNeg||t>=n.toExpPos)};function fVt(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)),Fp?pm(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/np),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)/Y0|0,c[i]%=Y0;for(n&&(c.unshift(n),++a),o=c.length;c[--o]==0;)c.pop();return t.d=c,t.e=a,Fp?pm(t,h):t}function e3(s,t,n){if(s!==~~s||sn)throw Error(t7+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,p,f,x,y,v,b,N,S,A,T,L,M,I=r.constructor,R=r.s==a.s?1:-1,z=r.d,$=a.d;if(!r.s)return new I(r);if(!a.s)throw Error(mN+"Division by zero");for(c=r.e-a.e,L=$.length,A=z.length,p=new I(R),f=p.d=[],d=0;$[d]==(z[d]||0);)++d;if($[d]>(z[d]||0)&&--c,i==null?b=i=I.precision:l?b=i+(Nx(r)-Nx(a))+1:b=i,b<0)return new I(0);if(b=b/np+2|0,d=0,L==1)for(u=0,$=$[0],b++;(d1&&($=s($,u),z=s(z,u),L=$.length,A=z.length),S=L,x=z.slice(0,L),y=x.length;y=Y0/2&&++T;do u=0,o=t($,x,L,y),o<0?(v=x[0],L!=y&&(v=v*Y0+(x[1]||0)),u=v/T|0,u>1?(u>=Y0&&(u=Y0-1),h=s($,u),m=h.length,y=x.length,o=t(h,x,m,y),o==1&&(u--,n(h,L16)throw Error(ptt+Nx(s));if(!s.s)return new u(Uw);for(t==null?(Fp=!1,o=h):o=t,l=new u(.03125);s.abs().gte(.1);)s=s.times(l),d+=5;for(r=Math.log(vD(2,d))/Math.LN10*2+5|0,o+=r,n=a=i=new u(Uw),u.precision=o;;){if(a=pm(a.times(s),o),n=n.times(++c),l=i.plus(zA(a,n,o)),x4(l.d).slice(0,o)===x4(i.d).slice(0,o)){for(;d--;)i=pm(i.times(i),o);return u.precision=h,t==null?(Fp=!0,pm(i,h)):i}i=l}}function Nx(s){for(var t=s.e*np,n=s.d[0];n>=10;n/=10)t++;return t}function w7e(s,t,n){if(t>s.LN10.sd())throw Fp=!0,n&&(s.precision=n),Error(mN+"LN10 precision limit exceeded");return pm(new s(s.LN10),t)}function KT(s){for(var t="";s--;)t+="0";return t}function Yee(s,t){var n,r,a,i,l,o,c,d,u,h=1,m=10,p=s,f=p.d,x=p.constructor,y=x.precision;if(p.s<1)throw Error(mN+(p.s?"NaN":"-Infinity"));if(p.eq(Uw))return new x(0);if(t==null?(Fp=!1,d=y):d=t,p.eq(10))return t==null&&(Fp=!0),w7e(x,d);if(d+=m,x.precision=d,n=x4(f),r=n.charAt(0),i=Nx(p),Math.abs(i)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)p=p.times(s),n=x4(p.d),r=n.charAt(0),h++;i=Nx(p),r>1?(p=new x("0."+n),i++):p=new x(r+"."+n.slice(1))}else return c=w7e(x,d+2,y).times(i+""),p=Yee(new x(r+"."+n.slice(1)),d-m).plus(c),x.precision=y,t==null?(Fp=!0,pm(p,y)):p;for(o=l=p=zA(p.minus(Uw),p.plus(Uw),d),u=pm(p.times(p),d),a=3;;){if(l=pm(l.times(u),d),c=o.plus(zA(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(w7e(x,d+2,y).times(i+""))),o=zA(o,new x(h),d),x.precision=y,t==null?(Fp=!0,pm(o,y)):o;o=c,a+=2}}function b1t(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=WG(n/np),s.d=[],r=(n+1)%np,n<0&&(r+=np),rtEe||s.e<-tEe))throw Error(ptt+n)}else s.s=0,s.e=0,s.d=[0];return s}function pm(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+=np,a=t,d=h[u=0];else{if(u=Math.ceil((r+1)/np),i=h.length,u>=i)return s;for(d=i=h[u],l=1;i>=10;i/=10)l++;r%=np,a=r-np+l}if(n!==void 0&&(i=vD(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/vD(10,l-a):0:h[u-1])%10&1||n==(s.s<0?8:7))),t<1||!h[0])return c?(i=Nx(s),h.length=1,t=t-i-1,h[0]=vD(10,(np-t%np)%np),s.e=WG(-t/np)||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=vD(10,np-r),h[u]=a>0?(d/vD(10,l-a)%vD(10,a)|0)*i:0),c)for(;;)if(u==0){(h[0]+=i)==Y0&&(h[0]=1,++s.e);break}else{if(h[u]+=i,h[u]!=Y0)break;h[u--]=0,i=1}for(r=h.length;h[--r]===0;)h.pop();if(Fp&&(s.e>tEe||s.e<-tEe))throw Error(ptt+Nx(s));return s}function xVt(s,t){var n,r,a,i,l,o,c,d,u,h,m=s.constructor,p=m.precision;if(!s.s||!t.s)return t.s?t.s=-t.s:t=new m(s),Fp?pm(t,p):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(p/np),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)+KT(r):l>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(a<0?"e":"e+")+a):a<0?(i="0."+KT(-a-1)+i,n&&(r=n-l)>0&&(i+=KT(r))):a>=l?(i+=KT(a+1-l),n&&(r=n-a-1)>0&&(i=i+"."+KT(r))):((r=a+1)0&&(a+1===l&&(i+="."),i+=KT(r))),s.s<0?"-"+i:i}function _1t(s,t){if(s.length>t)return s.length=t,!0}function yVt(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(t7+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 b1t(l,i.toString())}else if(typeof i!="string")throw Error(t7+i);if(i.charCodeAt(0)===45?(i=i.slice(1),l.s=-1):l.s=1,Gbn.test(i))b1t(l,i);else throw Error(t7+i)}if(a.prototype=uo,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=yVt,a.config=a.set=Wbn,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(t7+n+": "+r);if((r=s[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(t7+n+": "+r);return this}var ftt=yVt(Hbn);Uw=new ftt(1);const zh=ftt;function Kbn(s){return Qbn(s)||Xbn(s)||Zbn(s)||Ybn()}function Ybn(){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 Zbn(s,t){if(s){if(typeof s=="string")return VVe(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 VVe(s,t)}}function Xbn(s){if(typeof Symbol<"u"&&Symbol.iterator in Object(s))return Array.from(s)}function Qbn(s){if(Array.isArray(s))return VVe(s)}function VVe(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,w1t(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 m_n(s){if(Array.isArray(s))return s}function jVt(s){var t=Zee(s,2),n=t[0],r=t[1],a=n,i=r;return n>r&&(a=r,i=n),[a,i]}function NVt(s,t,n){if(s.lte(0))return new zh(0);var r=_Le.getDigitCount(s.toNumber()),a=new zh(10).pow(r),i=s.div(a),l=r!==1?.05:.1,o=new zh(Math.ceil(i.div(l).toNumber())).add(n).mul(l),c=o.mul(a);return t?c:new zh(Math.ceil(c))}function p_n(s,t,n){var r=1,a=new zh(s);if(!a.isint()&&n){var i=Math.abs(s);i<1?(r=new zh(10).pow(_Le.getDigitCount(s)-1),a=new zh(Math.floor(a.div(r).toNumber())).mul(r)):i>1&&(a=new zh(Math.floor(s)))}else s===0?a=new zh(Math.floor((t-1)/2)):n||(a=new zh(Math.floor(s)));var l=Math.floor((t-1)/2),o=s_n(t_n(function(c){return a.add(new zh(c-l).mul(r)).toNumber()}),HVe);return o(0,t)}function kVt(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 zh(0),tickMin:new zh(0),tickMax:new zh(0)};var i=NVt(new zh(t).sub(s).div(n-1),r,a),l;s<=0&&t>=0?l=new zh(0):(l=new zh(s).add(t).div(2),l=l.sub(new zh(l).mod(i)));var o=Math.ceil(l.sub(s).div(i).toNumber()),c=Math.ceil(new zh(t).sub(l).div(i).toNumber()),d=o+c+1;return d>n?kVt(s,t,n,r,a+1):(d0?c+(n-d):c,o=t>0?o:o+(n-d)),{step:i,tickMin:l.sub(new zh(o).mul(i)),tickMax:l.add(new zh(c).mul(i))})}function f_n(s){var t=Zee(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=jVt([n,r]),c=Zee(o,2),d=c[0],u=c[1];if(d===-1/0||u===1/0){var h=u===1/0?[d].concat(WVe(HVe(0,a-1).map(function(){return 1/0}))):[].concat(WVe(HVe(0,a-1).map(function(){return-1/0})),[u]);return n>r?GVe(h):h}if(d===u)return p_n(d,a,i);var m=kVt(d,u,l,i),p=m.step,f=m.tickMin,x=m.tickMax,y=_Le.rangeStep(f,x.add(new zh(.1).mul(p)),p);return n>r?GVe(y):y}function g_n(s,t){var n=Zee(s,2),r=n[0],a=n[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=jVt([r,a]),o=Zee(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=NVt(new zh(d).sub(c).div(u-1),i,0),m=[].concat(WVe(_Le.rangeStep(new zh(c),new zh(d).sub(new zh(.99).mul(h)),h)),[d]);return r>a?GVe(m):m}var x_n=_Vt(f_n),y_n=_Vt(g_n),v_n="Invariant failed";function U7(s,t){throw new Error(v_n)}var b_n=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function dH(s){"@babel/helpers - typeof";return dH=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},dH(s)}function sEe(){return sEe=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 C_n(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 A_n(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function E_n(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,p=void 0;if(nb(h-u)!==nb(m-h)){var f=[];if(nb(m-h)===nb(c[1]-c[0])){p=m;var x=h+c[1]-c[0];f[0]=Math.min(x,(x+u)/2),f[1]=Math.max(x,(x+u)/2)}else{p=u;var y=m+c[1]-c[0];f[0]=Math.min(h,(y+h)/2),f[1]=Math.max(h,(y+h)/2)}var v=[Math.min(h,(p+h)/2),Math.max(h,(p+h)/2)];if(t>v[0]&&t<=v[1]||t>=f[0]&&t<=f[1]){l=a[d].index;break}}else{var b=Math.min(u,m),N=Math.max(u,m);if(t>(b+h)/2&&t<=(N+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},gtt=function(t){var n,r=t,a=r.type.displayName,i=(n=t.type)!==null&&n!==void 0&&n.defaultProps?Qf(Qf({},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},G_n=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,N=b!==void 0?Qf(Qf({},b),v[0].props):v[0].props,S=N.barSize,A=N[y];l[A]||(l[A]=[]);var T=sc(S)?n:S;l[A].push({item:v[0],stackList:v.slice(1),barSize:sc(T)?void 0:rb(T,r,0)})}}return l},W_n=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=rb(n,a,0,!0),u,h=[];if(l[0].barSize===+l[0].barSize){var m=!1,p=a/c,f=l.reduce(function(S,A){return S+A.barSize||0},0);f+=(c-1)*d,f>=a&&(f-=(c-1)*d,d=0),f>=a&&p>0&&(m=!0,p*=.9,f=c*p);var x=(a-f)/2>>0,y={offset:x-d,size:0};u=l.reduce(function(S,A){var T={item:A.item,position:{offset:y.offset+y.size+d,size:m?p:A.barSize}},L=[].concat(k1t(S),[T]);return y=L[L.length-1].position,A.stackList&&A.stackList.length&&A.stackList.forEach(function(M){L.push({item:M,position:y})}),L},h)}else{var v=rb(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 N=o===+o?Math.min(b,o):b;u=l.reduce(function(S,A,T){var L=[].concat(k1t(S),[{item:A.item,position:{offset:v+(b+d)*T+(b-N)/2,size:N}}]);return A.stackList&&A.stackList.length&&A.stackList.forEach(function(M){L.push({item:M,position:L[L.length-1].position})}),L},h)}return u},K_n=function(t,n,r,a){var i=r.children,l=r.width,o=r.margin,c=l-(o.left||0)-(o.right||0),d=EVt({children:i,legendWidth:c});if(d){var u=a||{},h=u.width,m=u.height,p=d.align,f=d.verticalAlign,x=d.layout;if((x==="vertical"||x==="horizontal"&&f==="middle")&&p!=="center"&&Wa(t[p]))return Qf(Qf({},t),{},Hq({},p,t[p]+(h||0)));if((x==="horizontal"||x==="vertical"&&p==="center")&&f!=="middle"&&Wa(t[f]))return Qf(Qf({},t),{},Hq({},f,t[f]+(m||0)))}return t},Y_n=function(t,n,r){return sc(n)?!0:t==="horizontal"?n==="yAxis":t==="vertical"||r==="x"?n==="xAxis":r==="y"?n==="yAxis":!0},TVt=function(t,n,r,a,i){var l=n.props.children,o=ij(l,Ire).filter(function(d){return Y_n(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=zg(u,r);if(sc(h))return d;var m=Array.isArray(h)?[vLe(h),rM(h)]:[h,h],p=c.reduce(function(f,x){var y=zg(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,f[0]),Math.max(b,f[1])]},[1/0,-1/0]);return[Math.min(p[0],d[0]),Math.max(p[1],d[1])]},[1/0,-1/0])}return null},Z_n=function(t,n,r,a,i){var l=n.map(function(o){return TVt(t,o,r,i,a)}).filter(function(o){return!sc(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},MVt=function(t,n,r,a,i){var l=n.map(function(c){var d=c.props.dataKey;return r==="number"&&d&&TVt(t,c,d,a)||XQ(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?nb(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!BG(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}})},j7e=new WeakMap,Cle=function(t,n){if(typeof n!="function")return t;j7e.has(t)||j7e.set(t,new WeakMap);var r=j7e.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},IVt=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:Vee(),realScaleType:"band"}:l==="radial"&&o==="angleAxis"?{scale:XAe(),realScaleType:"linear"}:i==="category"&&n&&(n.indexOf("LineChart")>=0||n.indexOf("AreaChart")>=0||n.indexOf("ComposedChart")>=0&&!r)?{scale:ZQ(),realScaleType:"point"}:i==="category"?{scale:Vee(),realScaleType:"band"}:{scale:XAe(),realScaleType:"linear"};if(D7(a)){var c="scale".concat(aLe(a));return{scale:(v1t[c]||ZQ)(),realScaleType:v1t[c]?c:"point"}}return kl(a)?{scale:a}:{scale:ZQ(),realScaleType:"point"}},C1t=1e-4,RVt=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])-C1t,l=Math.max(a[0],a[1])+C1t,o=t(n[0]),c=t(n[r-1]);(ol||cl)&&t.domain([n[0],n[r-1]])}},X_n=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])}},ewn=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)}},twn={sign:J_n,expand:bdn,none:sH,silhouette:_dn,wiggle:wdn,positive:ewn},swn=function(t,n,r){var a=n.map(function(o){return o.props.dataKey}),i=twn[r],l=vdn().keys(a).value(function(o,c){return+zg(o,c,0)}).order(_Ve).offset(i);return l(t)},nwn=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 p,f=(p=m.type)!==null&&p!==void 0&&p.defaultProps?Qf(Qf({},m.type.defaultProps),m.props):m.props,x=f.stackId,y=f.hide;if(y)return h;var v=f[r],b=h[v]||{hasStack:!1,stackGroups:{}};if(o0(x)){var N=b.stackGroups[x]||{numericAxisId:r,cateAxisId:a,items:[]};N.items.push(m),b.hasStack=!0,b.stackGroups[x]=N}else b.stackGroups[S9("_stackId_")]={numericAxisId:r,cateAxisId:a,items:[m]};return Qf(Qf({},h),{},Hq({},v,b))},c),u={};return Object.keys(d).reduce(function(h,m){var p=d[m];if(p.hasStack){var f={};p.stackGroups=Object.keys(p.stackGroups).reduce(function(x,y){var v=p.stackGroups[y];return Qf(Qf({},x),{},Hq({},y,{numericAxisId:r,cateAxisId:a,items:v.items,stackedData:swn(t,v.items,i)}))},f)}return Qf(Qf({},h),{},Hq({},m,p))},u)},DVt=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=x_n(d,i,o);return t.domain([vLe(u),rM(u)]),{niceTicks:u}}if(i&&a==="number"){var h=t.domain(),m=y_n(h,i,o);return{niceTicks:m}}return null};function rEe(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&&!sc(a[t.dataKey])){var o=TAe(n,"value",a[t.dataKey]);if(o)return o.coordinate+r/2}return n[i]?n[i].coordinate+r/2:null}var c=zg(a,sc(l)?t.dataKey:l);return sc(c)?null:t.scale(c)}var A1t=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=zg(l,n.dataKey,n.domain[o]);return sc(c)?null:n.scale(c)-i/2+a},rwn=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]},awn=function(t,n){var r,a=(r=t.type)!==null&&r!==void 0&&r.defaultProps?Qf(Qf({},t.type.defaultProps),t.props):t.props,i=a.stackId;if(o0(i)){var l=n[i];if(l){var o=l.items.indexOf(t);return o>=0?l.stackedData[o]:null}}return null},iwn=function(t){return t.reduce(function(n,r){return[vLe(r.concat([n[0]]).filter(Wa)),rM(r.concat([n[1]]).filter(Wa))]},[1/0,-1/0])},OVt=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=iwn(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})},E1t=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,T1t=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,XVe=function(t,n,r){if(kl(t))return t(n,r);if(!Array.isArray(t))return n;var a=[];if(Wa(t[0]))a[0]=r?t[0]:Math.min(t[0],n[0]);else if(E1t.test(t[0])){var i=+E1t.exec(t[0])[1];a[0]=n[0]-i}else kl(t[0])?a[0]=t[0](n[0]):a[0]=n[0];if(Wa(t[1]))a[1]=r?t[1]:Math.max(t[1],n[1]);else if(T1t.test(t[1])){var l=+T1t.exec(t[1])[1];a[1]=n[1]+l}else kl(t[1])?a[1]=t[1](n[1]):a[1]=n[1];return a},aEe=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=Vet(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},fwn=function(t,n,r,a,i){var l=t.width,o=t.height,c=t.startAngle,d=t.endAngle,u=rb(t.cx,l,l/2),h=rb(t.cy,o,o/2),m=BVt(l,o,r),p=rb(t.innerRadius,m,0),f=rb(t.outerRadius,m,m*.8),x=Object.keys(n);return x.reduce(function(y,v){var b=n[v],N=b.domain,S=b.reversed,A;if(sc(b.range))a==="angleAxis"?A=[c,d]:a==="radiusAxis"&&(A=[p,f]),S&&(A=[A[1],A[0]]);else{A=b.range;var T=A,L=cwn(T,2);c=L[0],d=L[1]}var M=IVt(b,i),I=M.realScaleType,R=M.scale;R.domain(N).range(A),RVt(R);var z=DVt(R,jC(jC({},b),{},{realScaleType:I})),$=jC(jC(jC({},b),z),{},{range:A,radius:f,realScaleType:I,scale:R,cx:u,cy:h,innerRadius:p,outerRadius:f,startAngle:c,endAngle:d});return jC(jC({},y),{},zVt({},v,$))},{})},gwn=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))},xwn=function(t,n){var r=t.x,a=t.y,i=n.cx,l=n.cy,o=gwn({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:pwn(d),angleInRadian:d}},ywn=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}},vwn=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},I1t=function(t,n){var r=t.x,a=t.y,i=xwn({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=ywn(n),h=u.startAngle,m=u.endAngle,p=o,f;if(h<=m){for(;p>m;)p-=360;for(;p=h&&p<=m}else{for(;p>h;)p-=360;for(;p=m&&p<=h}return f?jC(jC({},n),{},{radius:l,angle:vwn(p,n)}):null},UVt=function(t){return!j.isValidElement(t)&&!kl(t)&&typeof t!="boolean"?t.className:""};function ete(s){"@babel/helpers - typeof";return ete=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},ete(s)}var bwn=["offset"];function _wn(s){return kwn(s)||Nwn(s)||jwn(s)||wwn()}function wwn(){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 jwn(s,t){if(s){if(typeof s=="string")return QVe(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 QVe(s,t)}}function Nwn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function kwn(s){if(Array.isArray(s))return QVe(s)}function QVe(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 Cwn(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 R1t(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 Bx(s){for(var t=1;t=0?1:-1,N,S;a==="insideStart"?(N=p+b*l,S=x):a==="insideEnd"?(N=f-b*l,S=!x):a==="end"&&(N=f+b*l,S=x),S=v<=0?S:!S;var A=Pm(d,u,y,N),T=Pm(d,u,y,N+(S?1:-1)*359),L="M".concat(A.x,",").concat(A.y,` A`).concat(y,",").concat(y,",0,1,").concat(S?0:1,`, `).concat(T.x,",").concat(T.y),M=sc(t.id)?S9("recharts-radial-line-"):t.id;return Dt.createElement("text",tte({},r,{dominantBaseline:"central",className:mc("recharts-radial-bar-label",o)}),Dt.createElement("defs",null,Dt.createElement("path",{id:M,d:L})),Dt.createElement("textPath",{xlinkHref:"#".concat(M)},n))},Iwn=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 p=Pm(l,o,d+r,m),f=p.x,x=p.y;return{x:f,y:x,textAnchor:f>=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=Pm(l,o,y,m),b=v.x,N=v.y;return{x:b,y:N,textAnchor:"middle",verticalAnchor:"middle"}},Rwn=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,p=h>0?"end":"start",f=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 N={x:o+d/2,y:c-h*a,textAnchor:"middle",verticalAnchor:p};return Bx(Bx({},N),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:f};return Bx(Bx({},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 Bx(Bx({},A),r?{width:Math.max(A.x-r.x,0),height:u}:{})}if(i==="right"){var T={x:o+d+y,y:c+u/2,textAnchor:b,verticalAnchor:"middle"};return Bx(Bx({},T),r?{width:Math.max(r.x+r.width-T.x,0),height:u}:{})}var L=r?{width:d,height:u}:{};return i==="insideLeft"?Bx({x:o+y,y:c+u/2,textAnchor:b,verticalAnchor:"middle"},L):i==="insideRight"?Bx({x:o+d-y,y:c+u/2,textAnchor:v,verticalAnchor:"middle"},L):i==="insideTop"?Bx({x:o+d/2,y:c+m,textAnchor:"middle",verticalAnchor:f},L):i==="insideBottom"?Bx({x:o+d/2,y:c+u-m,textAnchor:"middle",verticalAnchor:p},L):i==="insideTopLeft"?Bx({x:o+y,y:c+m,textAnchor:b,verticalAnchor:f},L):i==="insideTopRight"?Bx({x:o+d-y,y:c+m,textAnchor:v,verticalAnchor:f},L):i==="insideBottomLeft"?Bx({x:o+y,y:c+u-m,textAnchor:b,verticalAnchor:p},L):i==="insideBottomRight"?Bx({x:o+d-y,y:c+u-m,textAnchor:v,verticalAnchor:p},L):DG(i)&&(Wa(i.x)||QD(i.x))&&(Wa(i.y)||QD(i.y))?Bx({x:o+rb(i.x,d),y:c+rb(i.y,u),textAnchor:"end",verticalAnchor:"end"},L):Bx({x:o+d/2,y:c+u/2,textAnchor:"middle",verticalAnchor:"middle"},L)},Dwn=function(t){return"cx"in t&&Wa(t.cx)};function sy(s){var t=s.offset,n=t===void 0?5:t,r=Swn(s,bwn),a=Bx({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||sc(o)&&sc(c)&&!j.isValidElement(d)&&!kl(d))return null;if(j.isValidElement(d))return j.cloneElement(d,a);var p;if(kl(d)){if(p=j.createElement(d,a),j.isValidElement(p))return p}else p=Mwn(a);var f=Dwn(i),x=Io(a,!0);if(f&&(l==="insideStart"||l==="insideEnd"||l==="end"))return Lwn(a,p,x);var y=f?Iwn(a):Rwn(a);return Dt.createElement(F7,tte({className:mc("recharts-label",h)},x,y,{breakAll:m}),p)}sy.displayName="Label";var qVt=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,p=t.top,f=t.left,x=t.width,y=t.height,v=t.clockWise,b=t.labelViewBox;if(b)return b;if(Wa(x)&&Wa(y)){if(Wa(h)&&Wa(m))return{x:h,y:m,width:x,height:y};if(Wa(p)&&Wa(f))return{x:p,y:f,width:x,height:y}}return Wa(h)&&Wa(m)?{x:h,y:m,width:0,height:0}:Wa(n)&&Wa(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:{}},Own=function(t,n){return t?t===!0?Dt.createElement(sy,{key:"label-implicit",viewBox:n}):o0(t)?Dt.createElement(sy,{key:"label-implicit",viewBox:n,value:t}):j.isValidElement(t)?t.type===sy?j.cloneElement(t,{key:"label-implicit",viewBox:n}):Dt.createElement(sy,{key:"label-implicit",content:t,viewBox:n}):kl(t)?Dt.createElement(sy,{key:"label-implicit",content:t,viewBox:n}):DG(t)?Dt.createElement(sy,tte({viewBox:n},t,{key:"label-implicit"})):null:null},Fwn=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=qVt(t),l=ij(a,sy).map(function(c,d){return j.cloneElement(c,{viewBox:n||i,key:"label-".concat(d)})});if(!r)return l;var o=Own(t.label,n||i);return[o].concat(_wn(l))};sy.parseViewBox=qVt;sy.renderCallByParent=Fwn;function zwn(s){var t=s==null?0:s.length;return t?s[t-1]:void 0}var Bwn=zwn;const Uwn=od(Bwn);function ste(s){"@babel/helpers - typeof";return ste=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},ste(s)}var qwn=["valueAccessor"],$wn=["data","dataKey","clockWise","id","textBreakAll"];function Vwn(s){return Kwn(s)||Wwn(s)||Gwn(s)||Hwn()}function Hwn(){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 Gwn(s,t){if(s){if(typeof s=="string")return JVe(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 JVe(s,t)}}function Wwn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function Kwn(s){if(Array.isArray(s))return JVe(s)}function JVe(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 Qwn(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 Jwn=function(t){return Array.isArray(t.value)?Uwn(t.value):t.value};function q4(s){var t=s.valueAccessor,n=t===void 0?Jwn:t,r=F1t(s,qwn),a=r.data,i=r.dataKey,l=r.clockWise,o=r.id,c=r.textBreakAll,d=F1t(r,$wn);return!a||!a.length?null:Dt.createElement(wd,{className:"recharts-label-list"},a.map(function(u,h){var m=sc(i)?n(u,h):zg(u&&u.payload,i),p=sc(o)?{}:{id:"".concat(o,"-").concat(h)};return Dt.createElement(sy,oEe({},Io(u,!0),d,p,{parentViewBox:u.parentViewBox,value:m,textBreakAll:c,viewBox:sy.parseViewBox(sc(l)?u:O1t(O1t({},u),{},{clockWise:l})),key:"label-".concat(h),index:h}))}))}q4.displayName="LabelList";function ejn(s,t){return s?s===!0?Dt.createElement(q4,{key:"labelList-implicit",data:t}):Dt.isValidElement(s)||kl(s)?Dt.createElement(q4,{key:"labelList-implicit",data:t,content:s}):DG(s)?Dt.createElement(q4,oEe({data:t},s,{key:"labelList-implicit"})):null:null}function tjn(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=ij(r,q4).map(function(l,o){return j.cloneElement(l,{data:t,key:"labelList-".concat(o)})});if(!n)return a;var i=ejn(s.label,t);return[i].concat(Vwn(a))}q4.renderCallByParent=tjn;function nte(s){"@babel/helpers - typeof";return nte=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},nte(s)}function eHe(){return eHe=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 p=Pm(n,r,a,l),f=Pm(n,r,a,d);m+="L ".concat(f.x,",").concat(f.y,` A `).concat(a,",").concat(a,`,0, `).concat(+(Math.abs(c)>180),",").concat(+(l<=d),`, `).concat(p.x,",").concat(p.y," Z")}else m+="L ".concat(n,",").concat(r," Z");return m},ijn=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=nb(u-d),m=Ale({cx:n,cy:r,radius:i,angle:d,sign:h,cornerRadius:l,cornerIsExternal:c}),p=m.circleTangency,f=m.lineTangency,x=m.theta,y=Ale({cx:n,cy:r,radius:i,angle:u,sign:-h,cornerRadius:l,cornerIsExternal:c}),v=y.circleTangency,b=y.lineTangency,N=y.theta,S=c?Math.abs(d-u):Math.abs(d-u)-x-N;if(S<0)return o?"M ".concat(f.x,",").concat(f.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 `):$Vt({cx:n,cy:r,innerRadius:a,outerRadius:i,startAngle:d,endAngle:u});var A="M ".concat(f.x,",").concat(f.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(p.x,",").concat(p.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 T=Ale({cx:n,cy:r,radius:a,angle:d,sign:h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),L=T.circleTangency,M=T.lineTangency,I=T.theta,R=Ale({cx:n,cy:r,radius:a,angle:u,sign:-h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),z=R.circleTangency,$=R.lineTangency,H=R.theta,V=c?Math.abs(d-u):Math.abs(d-u)-I-H;if(V<0&&l===0)return"".concat(A,"L").concat(n,",").concat(r,"Z");A+="L".concat($.x,",").concat($.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(z.x,",").concat(z.y,` A`).concat(a,",").concat(a,",0,").concat(+(V>180),",").concat(+(h>0),",").concat(L.x,",").concat(L.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(M.x,",").concat(M.y,"Z")}else A+="L".concat(n,",").concat(r,"Z");return A},ojn={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},VVt=function(t){var n=B1t(B1t({},ojn),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=ijn({cx:r,cy:a,innerRadius:i,outerRadius:l,cornerRadius:Math.min(x,f/2),forceCornerRadius:c,cornerIsExternal:d,startAngle:u,endAngle:h}):y=$Vt({cx:r,cy:a,innerRadius:i,outerRadius:l,startAngle:u,endAngle:h}),Dt.createElement("path",eHe({},Io(n,!0),{className:p,d:y,role:"img"}))};function rte(s){"@babel/helpers - typeof";return rte=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},rte(s)}function tHe(){return tHe=Object.assign?Object.assign.bind():function(s){for(var t=1;t0;)if(!n.equals(s[r],t[r],r,r,s,t,n))return!1;return!0}function wjn(s,t){return KG(s.getTime(),t.getTime())}function K1t(s,t,n){if(s.size!==t.size)return!1;for(var r={},a=s.entries(),i=0,l,o;(l=a.next())&&!l.done;){for(var c=t.entries(),d=!1,u=0;(o=c.next())&&!o.done;){var h=l.value,m=h[0],p=h[1],f=o.value,x=f[0],y=f[1];!d&&!r[u]&&(d=n.equals(m,x,i,u,s,t,n)&&n.equals(p,y,m,x,s,t,n))&&(r[u]=!0),u++}if(!d)return!1;i++}return!0}function jjn(s,t,n){var r=W1t(s),a=r.length;if(W1t(t).length!==a)return!1;for(var i;a-- >0;)if(i=r[a],i===YVt&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!KVt(t,i)||!n.equals(s[i],t[i],i,i,s,t,n))return!1;return!0}function vY(s,t,n){var r=H1t(s),a=r.length;if(H1t(t).length!==a)return!1;for(var i,l,o;a-- >0;)if(i=r[a],i===YVt&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!KVt(t,i)||!n.equals(s[i],t[i],i,i,s,t,n)||(l=G1t(s,i),o=G1t(t,i),(l||o)&&(!l||!o||l.configurable!==o.configurable||l.enumerable!==o.enumerable||l.writable!==o.writable)))return!1;return!0}function Njn(s,t){return KG(s.valueOf(),t.valueOf())}function kjn(s,t){return s.source===t.source&&s.flags===t.flags}function Y1t(s,t,n){if(s.size!==t.size)return!1;for(var r={},a=s.values(),i,l;(i=a.next())&&!i.done;){for(var o=t.values(),c=!1,d=0;(l=o.next())&&!l.done;)!c&&!r[d]&&(c=n.equals(i.value,l.value,i.value,l.value,s,t,n))&&(r[d]=!0),d++;if(!c)return!1}return!0}function Sjn(s,t){var n=s.length;if(t.length!==n)return!1;for(;n-- >0;)if(s[n]!==t[n])return!1;return!0}var Cjn="[object Arguments]",Ajn="[object Boolean]",Ejn="[object Date]",Tjn="[object Map]",Mjn="[object Number]",Pjn="[object Object]",Ljn="[object RegExp]",Ijn="[object Set]",Rjn="[object String]",Djn=Array.isArray,Z1t=typeof ArrayBuffer=="function"&&ArrayBuffer.isView?ArrayBuffer.isView:null,X1t=Object.assign,Ojn=Object.prototype.toString.call.bind(Object.prototype.toString);function Fjn(s){var t=s.areArraysEqual,n=s.areDatesEqual,r=s.areMapsEqual,a=s.areObjectsEqual,i=s.arePrimitiveWrappersEqual,l=s.areRegExpsEqual,o=s.areSetsEqual,c=s.areTypedArraysEqual;return function(u,h,m){if(u===h)return!0;if(u==null||h==null||typeof u!="object"||typeof h!="object")return u!==u&&h!==h;var p=u.constructor;if(p!==h.constructor)return!1;if(p===Object)return a(u,h,m);if(Djn(u))return t(u,h,m);if(Z1t!=null&&Z1t(u))return c(u,h,m);if(p===Date)return n(u,h,m);if(p===RegExp)return l(u,h,m);if(p===Map)return r(u,h,m);if(p===Set)return o(u,h,m);var f=Ojn(u);return f===Ejn?n(u,h,m):f===Ljn?l(u,h,m):f===Tjn?r(u,h,m):f===Ijn?o(u,h,m):f===Pjn?typeof u.then!="function"&&typeof h.then!="function"&&a(u,h,m):f===Cjn?a(u,h,m):f===Ajn||f===Mjn||f===Rjn?i(u,h,m):!1}}function zjn(s){var t=s.circular,n=s.createCustomConfig,r=s.strict,a={areArraysEqual:r?vY:_jn,areDatesEqual:wjn,areMapsEqual:r?V1t(K1t,vY):K1t,areObjectsEqual:r?vY:jjn,arePrimitiveWrappersEqual:Njn,areRegExpsEqual:kjn,areSetsEqual:r?V1t(Y1t,vY):Y1t,areTypedArraysEqual:r?vY:Sjn};if(n&&(a=X1t({},a,n(a))),t){var i=Tle(a.areArraysEqual),l=Tle(a.areMapsEqual),o=Tle(a.areObjectsEqual),c=Tle(a.areSetsEqual);a=X1t({},a,{areArraysEqual:i,areMapsEqual:l,areObjectsEqual:o,areSetsEqual:c})}return a}function Bjn(s){return function(t,n,r,a,i,l,o){return s(t,n,o)}}function Ujn(s){var t=s.circular,n=s.comparator,r=s.createState,a=s.equals,i=s.strict;if(r)return function(c,d){var u=r(),h=u.cache,m=h===void 0?t?new WeakMap:void 0:h,p=u.meta;return n(c,d,{cache:m,equals:a,meta:p,strict:i})};if(t)return function(c,d){return n(c,d,{cache:new WeakMap,equals:a,meta:void 0,strict:i})};var l={cache:void 0,equals:a,meta:void 0,strict:i};return function(c,d){return n(c,d,l)}}var qjn=oL();oL({strict:!0});oL({circular:!0});oL({circular:!0,strict:!0});oL({createInternalComparator:function(){return KG}});oL({strict:!0,createInternalComparator:function(){return KG}});oL({circular:!0,createInternalComparator:function(){return KG}});oL({circular:!0,createInternalComparator:function(){return KG},strict:!0});function oL(s){s===void 0&&(s={});var t=s.circular,n=t===void 0?!1:t,r=s.createInternalComparator,a=s.createState,i=s.strict,l=i===void 0?!1:i,o=zjn(s),c=Fjn(o),d=r?r(c):Bjn(c);return Ujn({circular:n,comparator:c,createState:a,equals:d,strict:l})}function $jn(s){typeof requestAnimationFrame<"u"&&requestAnimationFrame(s)}function Q1t(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):$jn(a)};requestAnimationFrame(r)}function sHe(s){"@babel/helpers - typeof";return sHe=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},sHe(s)}function Vjn(s){return Kjn(s)||Wjn(s)||Gjn(s)||Hjn()}function Hjn(){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 Gjn(s,t){if(s){if(typeof s=="string")return J1t(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 J1t(s,t)}}function J1t(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,N=b,S=0;S<8;++S){var A=h(N)-b,T=p(N);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 p=-(u-h)*r,f=m*i,x=m+(p-f)*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 k2n(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 N7e(s){return E2n(s)||A2n(s)||C2n(s)||S2n()}function S2n(){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 C2n(s,t){if(s){if(typeof s=="string")return oHe(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 oHe(s,t)}}function A2n(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function E2n(s){if(Array.isArray(s))return oHe(s)}function oHe(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 dEe(s){return dEe=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},dEe(s)}var yS=function(s){I2n(n,s);var t=R2n(n);function n(r,a){var i;T2n(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,p=l.duration;if(i.handleStyleChange=i.handleStyleChange.bind(dHe(i)),i.changeStyle=i.changeStyle.bind(dHe(i)),!o||p<=0)return i.state={style:{}},typeof m=="function"&&(i.state={style:u}),cHe(i);if(h&&h.length)i.state={style:h[0].style};else if(d){if(typeof m=="function")return i.state={style:d},cHe(i);i.state={style:c?LZ({},c,d):d}}else i.state={style:{}};return i}return P2n(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 p={style:c?LZ({},c,u):u};this.state&&m&&(c&&m[c]!==u||!c&&m!==u)&&this.setState(p);return}if(!(qjn(a.to,u)&&a.canBegin&&a.isActive)){var f=!a.canBegin||!a.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var x=f||d?h:a.to;if(this.state&&m){var y={style:c?LZ({},c,x):x};(c&&m[c]!==x||!c&&m!==x)&&this.setState(y)}this.runAnimation(sk(sk({},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,p=w2n(l,o,u2n(d),c,this.changeStyle),f=function(){i.stopJSAnimation=p()};this.manager.start([m,u,f,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,p=function(x,y,v){if(v===0)return x;var b=y.duration,N=y.easing,S=N===void 0?"ease":N,A=y.style,T=y.properties,L=y.onAnimationEnd,M=v>0?l[v-1]:y,I=T||Object.keys(A);if(typeof S=="function"||S==="spring")return[].concat(N7e(x),[i.runJSAnimation.bind(i,{from:M.style,to:A,duration:b,easing:S}),b]);var R=sbt(I,b,S),z=sk(sk(sk({},M.style),A),{},{transition:R});return[].concat(N7e(x),[z,b,L]).filter(Jjn)};return this.manager.start([c].concat(N7e(l.reduce(p,[u,Math.max(m,o)])),[a.onAnimationEnd]))}},{key:"runAnimation",value:function(a){this.manager||(this.manager=Yjn());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,p=a.children,f=this.manager;if(this.unSubscribe=f.subscribe(this.handleStyleChange),typeof d=="function"||typeof p=="function"||d==="spring"){this.runJSAnimation(a);return}if(m.length>1){this.runStepAnimation(a);return}var x=o?LZ({},o,c):c,y=sbt(Object.keys(x),l,d);f.start([u,i,sk(sk({},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=N2n(a,j2n),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(p){var f=p.props,x=f.style,y=x===void 0?{}:x,v=f.className,b=j.cloneElement(p,sk(sk({},c),{},{style:sk(sk({},y),u),className:v}));return b};return d===1?h(j.Children.only(i)):Dt.createElement("div",null,j.Children.map(i,function(m){return h(m)}))}}]),n}(j.PureComponent);yS.displayName="Animate";yS.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};yS.propTypes={from:ih.oneOfType([ih.object,ih.string]),to:ih.oneOfType([ih.object,ih.string]),attributeName:ih.string,duration:ih.number,begin:ih.number,easing:ih.oneOfType([ih.string,ih.func]),steps:ih.arrayOf(ih.shape({duration:ih.number.isRequired,style:ih.object.isRequired,easing:ih.oneOfType([ih.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),ih.func]),properties:ih.arrayOf("string"),onAnimationEnd:ih.func})),children:ih.oneOfType([ih.node,ih.func]),isActive:ih.bool,canBegin:ih.bool,onAnimationEnd:ih.func,shouldReAnimate:ih.bool,onAnimationStart:ih.func,onAnimationReStart:ih.func};function ote(s){"@babel/helpers - typeof";return ote=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},ote(s)}function uEe(){return uEe=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,p=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 f=Math.min(l,i);u="M ".concat(t,",").concat(n+o*f,` A `).concat(f,",").concat(f,",0,0,").concat(d,",").concat(t+c*f,",").concat(n,` L `).concat(t+r-c*f,",").concat(n,` A `).concat(f,",").concat(f,",0,0,").concat(d,",").concat(t+r,",").concat(n+o*f,` L `).concat(t+r,",").concat(n+a-o*f,` A `).concat(f,",").concat(f,",0,0,").concat(d,",").concat(t+r-c*f,",").concat(n+a,` L `).concat(t+c*f,",").concat(n+a,` A `).concat(f,",").concat(f,",0,0,").concat(d,",").concat(t,",").concat(n+a-o*f," Z")}else u="M ".concat(t,",").concat(n," h ").concat(r," v ").concat(a," h ").concat(-r," Z");return u},H2n=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},G2n={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},xtt=function(t){var n=dbt(dbt({},G2n),t),r=j.useRef(),a=j.useState(-1),i=O2n(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,p=n.className,f=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 N=mc("recharts-rectangle",p);return b?Dt.createElement(yS,{canBegin:l>0,from:{width:u,height:h,x:c,y:d},to:{width:u,height:h,x:c,y:d},duration:x,animationEasing:f,isActive:b},function(S){var A=S.width,T=S.height,L=S.x,M=S.y;return Dt.createElement(yS,{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:f},Dt.createElement("path",uEe({},Io(n,!0),{className:N,d:ubt(L,M,A,T,m),ref:r})))}):Dt.createElement("path",uEe({},Io(n,!0),{className:N,d:ubt(c,d,u,h,m)}))},W2n=["points","className","baseLinePoints","connectNulls"];function SU(){return SU=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 Y2n(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 hbt(s){return J2n(s)||Q2n(s)||X2n(s)||Z2n()}function Z2n(){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 X2n(s,t){if(s){if(typeof s=="string")return uHe(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 uHe(s,t)}}function Q2n(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function J2n(s){if(Array.isArray(s))return uHe(s)}function uHe(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){mbt(r)?n[n.length-1].push(r):n[n.length-1].length>0&&n.push([])}),mbt(t[0])&&n[n.length-1].push(t[0]),n[n.length-1].length<=0&&(n=n.slice(0,-1)),n},JQ=function(t,n){var r=eNn(t);n&&(r=[r.reduce(function(i,l){return[].concat(hbt(i),hbt(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},tNn=function(t,n,r){var a=JQ(t,r);return"".concat(a.slice(-1)==="Z"?a.slice(0,-1):a,"L").concat(JQ(n.reverse(),r).slice(1))},sNn=function(t){var n=t.points,r=t.className,a=t.baseLinePoints,i=t.connectNulls,l=K2n(t,W2n);if(!n||!n.length)return null;var o=mc("recharts-polygon",r);if(a&&a.length){var c=l.stroke&&l.stroke!=="none",d=tNn(n,a,i);return Dt.createElement("g",{className:o},Dt.createElement("path",SU({},Io(l,!0),{fill:d.slice(-1)==="Z"?l.fill:"none",stroke:"none",d})),c?Dt.createElement("path",SU({},Io(l,!0),{fill:"none",d:JQ(n,i)})):null,c?Dt.createElement("path",SU({},Io(l,!0),{fill:"none",d:JQ(a,i)})):null)}var u=JQ(n,i);return Dt.createElement("path",SU({},Io(l,!0),{fill:u.slice(-1)==="Z"?l.fill:"none",className:o,d:u}))};function hHe(){return hHe=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 cNn(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 dNn=function(t,n,r,a,i,l){return"M".concat(t,",").concat(i,"v").concat(a,"M").concat(l,",").concat(n,"h").concat(r)},uNn=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,p=m===void 0?0:m,f=t.className,x=lNn(t,nNn),y=rNn({x:r,y:i,top:o,left:d,width:h,height:p},x);return!Wa(r)||!Wa(i)||!Wa(h)||!Wa(p)||!Wa(o)||!Wa(d)?null:Dt.createElement("path",mHe({},Io(y,!0),{className:mc("recharts-cross",f),d:dNn(r,i,h,p,o,d)}))},hNn=yLe,mNn=hVt,pNn=m3;function fNn(s,t){return s&&s.length?hNn(s,pNn(t),mNn):void 0}var gNn=fNn;const xNn=od(gNn);var yNn=yLe,vNn=m3,bNn=mVt;function _Nn(s,t){return s&&s.length?yNn(s,vNn(t),bNn):void 0}var wNn=_Nn;const jNn=od(wNn);var NNn=["cx","cy","angle","ticks","axisLine"],kNn=["ticks","tick","angle","tickFormatter","stroke"];function hH(s){"@babel/helpers - typeof";return hH=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},hH(s)}function eJ(){return eJ=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 SNn(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 CNn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function xbt(s,t){for(var n=0;nbbt?l=a==="outer"?"start":"end":i<-bbt?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=sI(sI({},Io(this.props,!1)),{},{fill:"none"},Io(o,!1));if(c==="circle")return Dt.createElement(Rre,PD({className:"recharts-polar-angle-axis-line"},d,{cx:a,cy:i,r:l}));var u=this.props.ticks,h=u.map(function(m){return Pm(a,i,l,m.coordinate)});return Dt.createElement(sNn,PD({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=Io(this.props,!1),h=Io(l,!1),m=sI(sI({},u),{},{fill:"none"},Io(o,!1)),p=i.map(function(f,x){var y=r.getTickLineCoord(f),v=r.getTickTextAnchor(f),b=sI(sI(sI({textAnchor:v},u),{},{stroke:"none",fill:d},h),{},{index:x,payload:f,x:y.x2,y:y.y2});return Dt.createElement(wd,PD({className:mc("recharts-polar-angle-axis-tick",UVt(l)),key:"tick-".concat(f.coordinate)},O7(r.props,f,x)),o&&Dt.createElement("line",PD({className:"recharts-polar-angle-axis-tick-line"},m,y)),l&&t.renderTickItem(l,b,c?c(f.value,x):f.value))});return Dt.createElement(wd,{className:"recharts-polar-angle-axis-ticks"},p)}},{key:"render",value:function(){var r=this.props,a=r.ticks,i=r.radius,l=r.axisLine;return i<=0||!a||!a.length?null:Dt.createElement(wd,{className:mc("recharts-polar-angle-axis",this.props.className)},l&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(r,a,i){var l;return Dt.isValidElement(r)?l=Dt.cloneElement(r,a):kl(r)?l=r(a):l=Dt.createElement(F7,PD({},a,{className:"recharts-polar-angle-axis-tick-value"}),i),l}}])}(j.PureComponent);NLe(kLe,"displayName","PolarAngleAxis");NLe(kLe,"axisType","angleAxis");NLe(kLe,"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 qNn=l$t,$Nn=qNn(Object.getPrototypeOf,Object),VNn=$Nn,HNn=wE,GNn=VNn,WNn=jE,KNn="[object Object]",YNn=Function.prototype,ZNn=Object.prototype,iHt=YNn.toString,XNn=ZNn.hasOwnProperty,QNn=iHt.call(Object);function JNn(s){if(!WNn(s)||HNn(s)!=KNn)return!1;var t=GNn(s);if(t===null)return!0;var n=XNn.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&iHt.call(n)==QNn}var ekn=JNn;const tkn=od(ekn);var skn=wE,nkn=jE,rkn="[object Boolean]";function akn(s){return s===!0||s===!1||nkn(s)&&skn(s)==rkn}var ikn=akn;const okn=od(ikn);function cte(s){"@babel/helpers - typeof";return cte=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},cte(s)}function pEe(){return pEe=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:f,isActive:v},function(N){var S=N.upperWidth,A=N.lowerWidth,T=N.height,L=N.x,M=N.y;return Dt.createElement(yS,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:y,duration:x,easing:f},Dt.createElement("path",pEe({},Io(n,!0),{className:b,d:Nbt(L,M,S,A,T),ref:r})))}):Dt.createElement("g",null,Dt.createElement("path",pEe({},Io(n,!0),{className:b,d:Nbt(c,d,u,h,m)})))},ykn=["option","shapeType","propTransformer","activeClassName","isActive"];function dte(s){"@babel/helpers - typeof";return dte=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},dte(s)}function vkn(s,t){if(s==null)return{};var n=bkn(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 bkn(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 kbt(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 fEe(s){for(var t=1;t0?aj(N,"paddingAngle",0):0;if(A){var L=s0(A.endAngle-A.startAngle,N.endAngle-N.startAngle),M=Cm(Cm({},N),{},{startAngle:b+T,endAngle:b+L(x)+T});y.push(M),b=M.endAngle}else{var I=N.endAngle,R=N.startAngle,z=s0(0,I-R),$=z(x),H=Cm(Cm({},N),{},{startAngle:b+T,endAngle:b+$+T});y.push(H),b=H.endAngle}}),Dt.createElement(wd,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||!z7(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,p=a.isAnimationActive,f=this.state.isAnimationFinished;if(i||!l||!l.length||!Wa(d)||!Wa(u)||!Wa(h)||!Wa(m))return null;var x=mc("recharts-pie",o);return Dt.createElement(wd,{tabIndex:this.props.rootTabIndex,className:x,ref:function(v){r.pieRef=v}},this.renderSectors(),c&&this.renderLabels(l),sy.renderCallByParent(this.props,null,!1),(!p||f)&&q4.renderCallByParent(this.props,l,!1))}}],[{key:"getDerivedStateFromProps",value:function(r,a){return a.prevIsAnimationActive!==r.isAnimationActive?{prevIsAnimationActive:r.isAnimationActive,prevAnimationId:r.animationId,curSectors:r.sectors,prevSectors:[],isAnimationFinished:!0}:r.isAnimationActive&&r.animationId!==a.prevAnimationId?{prevAnimationId:r.animationId,curSectors:r.sectors,prevSectors:a.curSectors,isAnimationFinished:!0}:r.sectors!==a.curSectors?{curSectors:r.sectors,isAnimationFinished:!0}:null}},{key:"getTextAnchor",value:function(r,a){return r>a?"start":r=360?b:b-1)*c,S=y-b*p-N,A=a.reduce(function(M,I){var R=zg(I,v,0);return M+(Wa(R)?R:0)},0),T;if(A>0){var L;T=a.map(function(M,I){var R=zg(M,v,0),z=zg(M,u,I),$=(Wa(R)?R:0)/A,H;I?H=L.endAngle+nb(x)*c*(R!==0?1:0):H=l;var V=H+nb(x)*((R!==0?p:0)+$*S),K=(H+V)/2,Z=(f.innerRadius+f.outerRadius)/2,Q=[{name:z,value:R,payload:M,dataKey:v,type:m}],le=Pm(f.cx,f.cy,Z,K);return L=Cm(Cm(Cm({percent:$,cornerRadius:i,name:z,tooltipPayload:Q,midAngle:K,middleRadius:Z,tooltipPosition:le},M),f),{},{value:zg(M,v),startAngle:H,endAngle:V,payload:M,paddingAngle:nb(x)*c}),L})}return Cm(Cm({},f),{},{sectors:T,data:a})});var Ukn=Math.ceil,qkn=Math.max;function $kn(s,t,n,r){for(var a=-1,i=qkn(Ukn((t-s)/(n||1)),0),l=Array(i);i--;)l[r?i:++a]=s,s+=n;return l}var Vkn=$kn,Hkn=C$t,Ebt=1/0,Gkn=17976931348623157e292;function Wkn(s){if(!s)return s===0?s:0;if(s=Hkn(s),s===Ebt||s===-Ebt){var t=s<0?-1:1;return t*Gkn}return s===s?s:0}var dHt=Wkn,Kkn=Vkn,Ykn=uLe,k7e=dHt;function Zkn(s){return function(t,n,r){return r&&typeof r!="number"&&Ykn(t,n,r)&&(n=r=void 0),t=k7e(t),n===void 0?(n=t,t=0):n=k7e(n),r=r===void 0?t0&&r.handleDrag(a.changedTouches[0])}),xw(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()}),xw(r,"handleLeaveWrapper",function(){(r.state.isTravellerMoving||r.state.isSlideMoving)&&(r.leaveTimer=window.setTimeout(r.handleDragEnd,r.props.leaveTimeOut))}),xw(r,"handleEnterSlideOrTraveller",function(){r.setState({isTextActive:!0})}),xw(r,"handleLeaveSlideOrTraveller",function(){r.setState({isTextActive:!1})}),xw(r,"handleSlideDragStart",function(a){var i=Ibt(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 dSn(t,s),iSn(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),p=t.getIndexInRange(l,h),f=t.getIndexInRange(l,m);return{startIndex:p-p%c,endIndex:f===u?u:f-f%c}}},{key:"getTextOfTick",value:function(r){var a=this.props,i=a.data,l=a.tickFormatter,o=a.dataKey,c=zg(i[r],o,r);return kl(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,p=c.endIndex,f=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!==p)&&f&&f(y),this.setState({startX:l+x,endX:o+x,slideMoveStartX:r.pageX})}},{key:"handleTravellerDragStart",value:function(r,a){var i=Ibt(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,p=u.travellerWidth,f=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-p-d):b<0&&(b=Math.max(b,h-d)),v[l]=d+b;var N=this.getIndex(v),S=N.startIndex,A=N.endIndex,T=function(){var M=y.length-1;return l==="startX"&&(o>c?S%x===0:A%x===0)||oc?A%x===0:S%x===0)||o>c&&A===M};this.setState(xw(xw({},l,d+b),"brushMoveStartX",r.pageX),function(){f&&T()&&f(N)})}},{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 p=o[m];a==="startX"&&p>=d||a==="endX"&&p<=c||this.setState(xw({},a,p),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 Dt.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?Dt.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,p=c.ariaLabel,f=c.data,x=c.startIndex,y=c.endIndex,v=Math.max(r,this.props.x),b=S7e(S7e({},Io(this.props,!1)),{},{x:v,y:d,width:u,height:h}),N=p||"Min value: ".concat((i=f[x])===null||i===void 0?void 0:i.name,", Max value: ").concat((l=f[y])===null||l===void 0?void 0:l.name);return Dt.createElement(wd,{tabIndex:0,role:"slider","aria-label":N,"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 Dt.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,p=5,f={pointerEvents:"none",fill:d};return Dt.createElement(wd,{className:"recharts-brush-texts"},Dt.createElement(F7,yEe({textAnchor:"end",verticalAnchor:"middle",x:Math.min(h,m)-p,y:l+o/2},f),this.getTextOfTick(a)),Dt.createElement(F7,yEe({textAnchor:"start",verticalAnchor:"middle",x:Math.max(h,m)+c+p,y:l+o/2},f),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,p=m.startX,f=m.endX,x=m.isTextActive,y=m.isSlideMoving,v=m.isTravellerMoving,b=m.isTravellerFocused;if(!a||!a.length||!Wa(o)||!Wa(c)||!Wa(d)||!Wa(u)||d<=0||u<=0)return null;var N=mc("recharts-brush",i),S=Dt.Children.count(l)===1,A=rSn("userSelect","none");return Dt.createElement(wd,{className:N,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:A},this.renderBackground(),S&&this.renderPanorama(),this.renderSlide(p,f),this.renderTravellerLayer(p,"startX"),this.renderTravellerLayer(f,"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 Dt.createElement(Dt.Fragment,null,Dt.createElement("rect",{x:a,y:i,width:l,height:o,fill:c,stroke:"none"}),Dt.createElement("line",{x1:a+1,y1:d,x2:a+l-1,y2:d,fill:"none",stroke:"#fff"}),Dt.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 Dt.isValidElement(r)?i=Dt.cloneElement(r,a):kl(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 S7e({prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l},i&&i.length?hSn({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(p){return a.scale(p)});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);xw(gH,"displayName","Brush");xw(gH,"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 mSn=$et;function pSn(s,t){var n;return mSn(s,function(r,a,i){return n=t(r,a,i),!n}),!!n}var fSn=pSn,gSn=e$t,xSn=m3,ySn=fSn,vSn=z_,bSn=uLe;function _Sn(s,t,n){var r=vSn(s)?gSn:ySn;return n&&bSn(s,t,n)&&(t=void 0),r(s,xSn(t))}var wSn=_Sn;const jSn=od(wSn);var $4=function(t,n){var r=t.alwaysShow,a=t.ifOverflow;return r&&(a="extendDomain"),a===n},Rbt=w$t;function NSn(s,t,n){t=="__proto__"&&Rbt?Rbt(s,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):s[t]=n}var kSn=NSn,SSn=kSn,CSn=b$t,ASn=m3;function ESn(s,t){var n={};return t=ASn(t),CSn(s,function(r,a,i){SSn(n,a,t(r,a,i))}),n}var TSn=ESn;const MSn=od(TSn);function PSn(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 YSn(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 ZSn(s,t){var n=s.x,r=s.y,a=KSn(s,VSn),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 bY(bY(bY(bY(bY({},t),a),l?{x:l}:{}),c?{y:c}:{}),{},{height:u,width:m,name:t.name,radius:t.radius})}function Obt(s){return Dt.createElement(oHt,yHe({shapeType:"rectangle",propTransformer:ZSn,activeClassName:"recharts-active-bar"},s))}var XSn=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=Wa(r)||Lln(r);return i?t(r,a):(i||U7(),n)}},QSn=["value","background"],fHt;function xH(s){"@babel/helpers - typeof";return xH=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},xH(s)}function JSn(s,t){if(s==null)return{};var n=e5n(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 e5n(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function bEe(){return bEe=Object.assign?Object.assign.bind():function(s){for(var t=1;t0&&Math.abs(K)0&&Math.abs(V)0&&(H=Math.min((je||0)-(V[be-1]||0),H))}),Number.isFinite(H)){var K=H/$,Z=x.layout==="vertical"?r.height:r.width;if(x.padding==="gap"&&(L=K*Z/2),x.padding==="no-gap"){var Q=rb(t.barCategoryGap,K*Z),le=K*Z/2;L=le-Q-(le-Q)/Z*Q}}}a==="xAxis"?M=[r.left+(N.left||0)+(L||0),r.left+r.width-(N.right||0)-(L||0)]:a==="yAxis"?M=c==="horizontal"?[r.top+r.height-(N.bottom||0),r.top+(N.top||0)]:[r.top+(N.top||0)+(L||0),r.top+r.height-(N.bottom||0)-(L||0)]:M=x.range,A&&(M=[M[1],M[0]]);var ue=IVt(x,i,m),se=ue.scale,ne=ue.realScaleType;se.domain(v).range(M),RVt(se);var ie=DVt(se,Lk(Lk({},x),{},{realScaleType:ne}));a==="xAxis"?(z=y==="top"&&!S||y==="bottom"&&S,I=r.left,R=h[T]-z*x.height):a==="yAxis"&&(z=y==="left"&&!S||y==="right"&&S,I=h[T]-z*x.width,R=r.top);var ce=Lk(Lk(Lk({},x),ie),{},{realScaleType:ne,x:I,y:R,scale:se,width:a==="xAxis"?r.width:x.width,height:a==="yAxis"?r.height:x.height});return ce.bandSize=aEe(ce,ie),!x.hide&&a==="xAxis"?h[T]+=(z?-1:1)*ce.height:x.hide||(h[T]+=(z?-1:1)*ce.width),Lk(Lk({},p),{},ALe({},f,ce))},{})},vHt=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)}},u5n=function(t){var n=t.x1,r=t.y1,a=t.x2,i=t.y2;return vHt({x:n,y:r},{x:a,y:i})},bHt=function(){function s(t){l5n(this,s),this.scale=t}return c5n(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)}}])}();ALe(bHt,"EPS",1e-4);var vtt=function(t){var n=Object.keys(t).reduce(function(r,a){return Lk(Lk({},r),{},ALe({},a,bHt.create(t[a])))},{});return Lk(Lk({},n),{},{apply:function(a){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},l=i.bandAware,o=i.position;return MSn(a,function(c,d){return n[d].apply(c,{bandAware:l,position:o})})},isInRange:function(a){return pHt(a,function(i,l){return n[l].isInRange(i)})}})};function h5n(s){return(s%180+180)%180}var m5n=function(t){var n=t.width,r=t.height,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=h5n(a),l=i*Math.PI/180,o=Math.atan(r/n),c=l>o&&l-1?a[i?t[l]:l]:void 0}}var y5n=x5n,v5n=dHt;function b5n(s){var t=v5n(s),n=t%1;return t===t?n?t-n:t:0}var _5n=b5n,w5n=p$t,j5n=m3,N5n=_5n,k5n=Math.max;function S5n(s,t,n){var r=s==null?0:s.length;if(!r)return-1;var a=n==null?0:N5n(n);return a<0&&(a=k5n(r+a,0)),w5n(s,j5n(t),a)}var C5n=S5n,A5n=y5n,E5n=C5n,T5n=A5n(E5n),M5n=T5n;const P5n=od(M5n);var L5n=Oon(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("")}),btt=j.createContext(void 0),_tt=j.createContext(void 0),_Ht=j.createContext(void 0),wHt=j.createContext({}),jHt=j.createContext(void 0),NHt=j.createContext(0),kHt=j.createContext(0),qbt=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=L5n(i);return Dt.createElement(btt.Provider,{value:r},Dt.createElement(_tt.Provider,{value:a},Dt.createElement(wHt.Provider,{value:i},Dt.createElement(_Ht.Provider,{value:u},Dt.createElement(jHt.Provider,{value:l},Dt.createElement(NHt.Provider,{value:d},Dt.createElement(kHt.Provider,{value:c},o)))))))},I5n=function(){return j.useContext(jHt)},SHt=function(t){var n=j.useContext(btt);n==null&&U7();var r=n[t];return r==null&&U7(),r},R5n=function(){var t=j.useContext(btt);return o6(t)},D5n=function(){var t=j.useContext(_tt),n=P5n(t,function(r){return pHt(r.domain,Number.isFinite)});return n||o6(t)},CHt=function(t){var n=j.useContext(_tt);n==null&&U7();var r=n[t];return r==null&&U7(),r},O5n=function(){var t=j.useContext(_Ht);return t},F5n=function(){return j.useContext(wHt)},wtt=function(){return j.useContext(kHt)},jtt=function(){return j.useContext(NHt)};function yH(s){"@babel/helpers - typeof";return yH=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},yH(s)}function z5n(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function B5n(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 _4n(s,t){return IHt(s,t+1)}function w4n(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 f=r==null?void 0:r[c];if(f===void 0)return{v:IHt(r,d)};var x=c,y,v=function(){return y===void 0&&(y=n(f,x)),y},b=f.coordinate,N=c===0||kEe(s,b,v,u,o);N||(c=0,u=l,d+=1),N&&(u=b+s*(v()/2+a),c+=d)},m;d<=i.length;)if(m=h(),m)return m.v;return[]}function fte(s){"@babel/helpers - typeof";return fte=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},fte(s)}function Zbt(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 Zv(s){for(var t=1;t0?p.coordinate-y*s:p.coordinate})}else i[m]=p=Zv(Zv({},p),{},{tickCoord:p.coordinate});var v=kEe(s,p.tickCoord,x,o,c);v&&(c=p.tickCoord-s*(x()/2+a),i[m]=Zv(Zv({},p),{},{isShow:!0}))},u=l-1;u>=0;u--)d(u);return i}function C4n(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=Zv(Zv({},u),{},{tickCoord:m>0?u.coordinate-m*s:u.coordinate});var p=kEe(s,u.tickCoord,function(){return h},c,d);p&&(d=u.tickCoord-s*(h/2+a),l[o-1]=Zv(Zv({},u),{},{isShow:!0}))}for(var f=i?o-1:o,x=function(b){var N=l[b],S,A=function(){return S===void 0&&(S=n(N,b)),S};if(b===0){var T=s*(N.coordinate-s*A()/2-c);l[b]=N=Zv(Zv({},N),{},{tickCoord:T<0?N.coordinate-T*s:N.coordinate})}else l[b]=N=Zv(Zv({},N),{},{tickCoord:N.coordinate});var L=kEe(s,N.tickCoord,A,c,d);L&&(c=N.tickCoord+s*(A()/2+a),l[b]=Zv(Zv({},N),{},{isShow:!0}))},y=0;y=2?nb(a[1].coordinate-a[0].coordinate):1,v=b4n(i,y,p);return c==="equidistantPreserveStart"?w4n(y,v,x,a,l):(c==="preserveStart"||c==="preserveStartEnd"?m=C4n(y,v,x,a,l,c==="preserveStartEnd"):m=S4n(y,v,x,a,l),m.filter(function(b){return b.isShow}))}var A4n=["viewBox"],E4n=["viewBox"],T4n=["ticks"];function _H(s){"@babel/helpers - typeof";return _H=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},_H(s)}function AU(){return AU=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 M4n(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 P4n(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function Qbt(s,t){for(var n=0;n0?c(this.props):c(p)),l<=0||o<=0||!f||!f.length?null:Dt.createElement(wd,{className:mc("recharts-cartesian-axis",d),ref:function(y){r.layerReference=y}},i&&this.renderAxisLine(),this.renderTicks(f,this.state.fontSize,this.state.letterSpacing),sy.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(r,a,i){var l,o=mc(a.className,"recharts-cartesian-axis-tick-value");return Dt.isValidElement(r)?l=Dt.cloneElement(r,Fx(Fx({},a),{},{className:o})):kl(r)?l=r(Fx(Fx({},a),{},{className:o})):l=Dt.createElement(F7,AU({},a,{className:"recharts-cartesian-axis-tick-value"}),i),l}}])}(j.Component);Ctt(YG,"displayName","CartesianAxis");Ctt(YG,"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 z4n=["x1","y1","x2","y2","key"],B4n=["offset"];function q7(s){"@babel/helpers - typeof";return q7=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},q7(s)}function Jbt(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 Jv(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function V4n(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 H4n=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 Dt.createElement("rect",{x:a,y:i,ry:c,width:l,height:o,stroke:"none",fill:n,fillOpacity:r,className:"recharts-cartesian-grid-bg"})};function OHt(s,t){var n;if(Dt.isValidElement(s))n=Dt.cloneElement(s,t);else if(kl(s))n=s(t);else{var r=t.x1,a=t.y1,i=t.x2,l=t.y2,o=t.key,c=e_t(t,z4n),d=Io(c,!1);d.offset;var u=e_t(d,B4n);n=Dt.createElement("line",tO({},u,{x1:r,y1:a,x2:i,y2:l,fill:"none",key:o}))}return n}function G4n(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=Jv(Jv({},s),{},{x1:t,y1:o,x2:t+n,y2:o,key:"line-".concat(c),index:c});return OHt(a,d)});return Dt.createElement("g",{className:"recharts-cartesian-grid-horizontal"},l)}function W4n(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=Jv(Jv({},s),{},{x1:o,y1:t,x2:o,y2:t+n,key:"line-".concat(c),index:c});return OHt(a,d)});return Dt.createElement("g",{className:"recharts-cartesian-grid-vertical"},l)}function K4n(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,p){return m-p});a!==u[0]&&u.unshift(0);var h=u.map(function(m,p){var f=!u[p+1],x=f?a+l-m:u[p+1]-m;if(x<=0)return null;var y=p%t.length;return Dt.createElement("rect",{key:"react-".concat(p),y:m,x:r,height:x,width:i,stroke:"none",fill:t[y],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return Dt.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},h)}function Y4n(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,p){return m-p});i!==u[0]&&u.unshift(0);var h=u.map(function(m,p){var f=!u[p+1],x=f?i+o-m:u[p+1]-m;if(x<=0)return null;var y=p%r.length;return Dt.createElement("rect",{key:"react-".concat(p),x:m,y:l,width:x,height:c,stroke:"none",fill:r[y],fillOpacity:a,className:"recharts-cartesian-grid-bg"})});return Dt.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},h)}var Z4n=function(t,n){var r=t.xAxis,a=t.width,i=t.height,l=t.offset;return LVt(Stt(Jv(Jv(Jv({},YG.defaultProps),r),{},{ticks:bA(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.left,l.left+l.width,n)},X4n=function(t,n){var r=t.yAxis,a=t.width,i=t.height,l=t.offset;return LVt(Stt(Jv(Jv(Jv({},YG.defaultProps),r),{},{ticks:bA(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.top,l.top+l.height,n)},aB={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function $7(s){var t,n,r,a,i,l,o=wtt(),c=jtt(),d=F5n(),u=Jv(Jv({},s),{},{stroke:(t=s.stroke)!==null&&t!==void 0?t:aB.stroke,fill:(n=s.fill)!==null&&n!==void 0?n:aB.fill,horizontal:(r=s.horizontal)!==null&&r!==void 0?r:aB.horizontal,horizontalFill:(a=s.horizontalFill)!==null&&a!==void 0?a:aB.horizontalFill,vertical:(i=s.vertical)!==null&&i!==void 0?i:aB.vertical,verticalFill:(l=s.verticalFill)!==null&&l!==void 0?l:aB.verticalFill,x:Wa(s.x)?s.x:d.left,y:Wa(s.y)?s.y:d.top,width:Wa(s.width)?s.width:d.width,height:Wa(s.height)?s.height:d.height}),h=u.x,m=u.y,p=u.width,f=u.height,x=u.syncWithTicks,y=u.horizontalValues,v=u.verticalValues,b=R5n(),N=D5n();if(!Wa(p)||p<=0||!Wa(f)||f<=0||!Wa(h)||h!==+h||!Wa(m)||m!==+m)return null;var S=u.verticalCoordinatesGenerator||Z4n,A=u.horizontalCoordinatesGenerator||X4n,T=u.horizontalPoints,L=u.verticalPoints;if((!T||!T.length)&&kl(A)){var M=y&&y.length,I=A({yAxis:N?Jv(Jv({},N),{},{ticks:M?y:N.ticks}):void 0,width:o,height:c,offset:d},M?!0:x);iS(Array.isArray(I),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(q7(I),"]")),Array.isArray(I)&&(T=I)}if((!L||!L.length)&&kl(S)){var R=v&&v.length,z=S({xAxis:b?Jv(Jv({},b),{},{ticks:R?v:b.ticks}):void 0,width:o,height:c,offset:d},R?!0:x);iS(Array.isArray(z),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(q7(z),"]")),Array.isArray(z)&&(L=z)}return Dt.createElement("g",{className:"recharts-cartesian-grid"},Dt.createElement(H4n,{fill:u.fill,fillOpacity:u.fillOpacity,x:u.x,y:u.y,width:u.width,height:u.height,ry:u.ry}),Dt.createElement(G4n,tO({},u,{offset:d,horizontalPoints:T,xAxis:b,yAxis:N})),Dt.createElement(W4n,tO({},u,{offset:d,verticalPoints:L,xAxis:b,yAxis:N})),Dt.createElement(K4n,tO({},u,{horizontalPoints:T})),Dt.createElement(Y4n,tO({},u,{verticalPoints:L})))}$7.displayName="CartesianGrid";var Q4n=["type","layout","connectNulls","ref"],J4n=["key"];function wH(s){"@babel/helpers - typeof";return wH=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},wH(s)}function t_t(s,t){if(s==null)return{};var n=e3n(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 e3n(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function tJ(){return tJ=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){p=[].concat(iB(c.slice(0,f)),[h-x]);break}var y=p.length%2===0?[0,m]:[m];return[].concat(iB(t.repeat(c,u)),iB(p),y).map(function(v){return"".concat(v,"px")}).join(", ")}),Ik(n,"id",S9("recharts-line-")),Ik(n,"pathRef",function(l){n.mainCurve=l}),Ik(n,"handleAnimationEnd",function(){n.setState({isAnimationFinished:!0}),n.props.onAnimationEnd&&n.props.onAnimationEnd()}),Ik(n,"handleAnimationStart",function(){n.setState({isAnimationFinished:!1}),n.props.onAnimationStart&&n.props.onAnimationStart()}),n}return d3n(t,s),i3n(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=ij(u,Ire);if(!h)return null;var m=function(x,y){return{x:x.x,y:x.y,value:x.value,errorVal:zg(x.payload,y)}},p={clipPath:r?"url(#clipPath-".concat(a,")"):null};return Dt.createElement(wd,p,h.map(function(f){return Dt.cloneElement(f,{key:"bar-".concat(f.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=Io(this.props,!1),m=Io(c,!0),p=d.map(function(x,y){var v=hw(hw(hw({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)}),f={clipPath:r?"url(#clipPath-".concat(a?"":"dots-").concat(i,")"):null};return Dt.createElement(wd,tJ({className:"recharts-line-dots",key:"dots"},f),p)}},{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=t_t(o,Q4n),m=hw(hw(hw({},Io(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 Dt.createElement(s7,tJ({},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,p=l.animationId,f=l.animateNewValues,x=l.width,y=l.height,v=this.state,b=v.prevPoints,N=v.totalLength;return Dt.createElement(yS,{begin:u,duration:h,isActive:d,easing:m,from:{t:0},to:{t:1},key:"line-".concat(p),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(S){var A=S.t;if(b){var T=b.length/o.length,L=o.map(function($,H){var V=Math.floor(H*T);if(b[V]){var K=b[V],Z=s0(K.x,$.x),Q=s0(K.y,$.y);return hw(hw({},$),{},{x:Z(A),y:Q(A)})}if(f){var le=s0(x*2,$.x),ue=s0(y/2,$.y);return hw(hw({},$),{},{x:le(A),y:ue(A)})}return hw(hw({},$),{},{x:$.x,y:$.y})});return i.renderCurveStatically(L,r,a)}var M=s0(0,N),I=M(A),R;if(c){var z="".concat(c).split(/[,\s]+/gim).map(function($){return parseFloat($)});R=i.getStrokeDasharray(I,N,z)}else R=i.generateSimpleStrokeDasharray(N,I);return i.renderCurveStatically(o,r,a,{strokeDasharray:R})})}},{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||!z7(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,p=a.width,f=a.height,x=a.isAnimationActive,y=a.id;if(i||!o||!o.length)return null;var v=this.state.isAnimationFinished,b=o.length===1,N=mc("recharts-line",c),S=d&&d.allowDataOverflow,A=u&&u.allowDataOverflow,T=S||A,L=sc(y)?this.id:y,M=(r=Io(l,!1))!==null&&r!==void 0?r:{r:3,strokeWidth:2},I=M.r,R=I===void 0?3:I,z=M.strokeWidth,$=z===void 0?2:z,H=kqt(l)?l:{},V=H.clipDot,K=V===void 0?!0:V,Z=R*2+$;return Dt.createElement(wd,{className:N},S||A?Dt.createElement("defs",null,Dt.createElement("clipPath",{id:"clipPath-".concat(L)},Dt.createElement("rect",{x:S?m:m-p/2,y:A?h:h-f/2,width:S?p:p*2,height:A?f:f*2})),!K&&Dt.createElement("clipPath",{id:"clipPath-dots-".concat(L)},Dt.createElement("rect",{x:m-Z/2,y:h-Z/2,width:p+Z,height:f+Z}))):null,!b&&this.renderCurve(T,L),this.renderErrorBar(T,L),(b||l)&&this.renderDots(T,K,L),(!x||v)&&q4.renderCallByParent(this.props,o))}}],[{key:"getDerivedStateFromProps",value:function(r,a){return r.animationId!==a.prevAnimationId?{prevAnimationId:r.animationId,curPoints:r.points,prevPoints:a.curPoints}:r.points!==a.curPoints?{curPoints:r.points}:null}},{key:"repeat",value:function(r,a){for(var i=r.length%2!==0?[].concat(iB(r),[0]):r,l=[],o=0;o=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function p3n(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 sO(){return sO=Object.assign?Object.assign.bind():function(s){for(var t=1;t0||!z7(u,l)||!z7(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,p=a.width,f=a.height,x=a.isAnimationActive,y=a.id;if(i||!o||!o.length)return null;var v=this.state.isAnimationFinished,b=o.length===1,N=mc("recharts-area",c),S=h&&h.allowDataOverflow,A=m&&m.allowDataOverflow,T=S||A,L=sc(y)?this.id:y,M=(r=Io(l,!1))!==null&&r!==void 0?r:{r:3,strokeWidth:2},I=M.r,R=I===void 0?3:I,z=M.strokeWidth,$=z===void 0?2:z,H=kqt(l)?l:{},V=H.clipDot,K=V===void 0?!0:V,Z=R*2+$;return Dt.createElement(wd,{className:N},S||A?Dt.createElement("defs",null,Dt.createElement("clipPath",{id:"clipPath-".concat(L)},Dt.createElement("rect",{x:S?u:u-p/2,y:A?d:d-f/2,width:S?p:p*2,height:A?f:f*2})),!K&&Dt.createElement("clipPath",{id:"clipPath-dots-".concat(L)},Dt.createElement("rect",{x:u-Z/2,y:d-Z/2,width:p+Z,height:f+Z}))):null,b?null:this.renderArea(T,L),(l||b)&&this.renderDots(T,K,L),(!x||v)&&q4.renderCallByParent(this.props,o))}}],[{key:"getDerivedStateFromProps",value:function(r,a){return r.animationId!==a.prevAnimationId?{prevAnimationId:r.animationId,curPoints:r.points,curBaseLine:r.baseLine,prevPoints:a.curPoints,prevBaseLine:a.curBaseLine}:r.points!==a.curPoints||r.baseLine!==a.curBaseLine?{curPoints:r.points,curBaseLine:r.baseLine}:null}}])}(j.PureComponent);BHt=M_;y4(M_,"displayName","Area");y4(M_,"defaultProps",{stroke:"#3182bd",fill:"#3182bd",fillOpacity:.6,xAxisId:0,yAxisId:0,legendType:"line",connectNulls:!1,points:[],dot:!1,activeDot:!0,hide:!1,isAnimationActive:!oS.isSsr,animationBegin:0,animationDuration:1500,animationEasing:"ease"});y4(M_,"getBaseValue",function(s,t,n,r){var a=s.layout,i=s.baseValue,l=t.props.baseValue,o=l??i;if(Wa(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(M_,"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,p=t.layout,f=d&&d.length,x=BHt.getBaseValue(t,n,r,a),y=p==="horizontal",v=!1,b=h.map(function(S,A){var T;f?T=d[u+A]:(T=zg(S,c),Array.isArray(T)?v=!0:T=[x,T]);var L=T[1]==null||f&&zg(S,c)==null;return y?{x:rEe({axis:r,ticks:i,bandSize:o,entry:S,index:A}),y:L?null:a.scale(T[1]),value:T,payload:S}:{x:L?null:r.scale(T[1]),y:rEe({axis:a,ticks:l,bandSize:o,entry:S,index:A}),value:T,payload:S}}),N;return f||v?N=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}}):N=y?a.scale(x):r.scale(x),MT({points:b,baseLine:N,layout:p,isRange:v},m)});y4(M_,"renderDotItem",function(s,t){var n;if(Dt.isValidElement(s))n=Dt.cloneElement(s,t);else if(kl(s))n=s(t);else{var r=mc("recharts-area-dot",typeof s!="boolean"?s.className:""),a=t.key,i=UHt(t,m3n);n=Dt.createElement(Rre,sO({},i,{key:a,className:r}))}return n});function NH(s){"@babel/helpers - typeof";return NH=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},NH(s)}function w3n(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function j3n(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 cCn(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 dCn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function uCn(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n0?l:t&&t.length&&Wa(a)&&Wa(i)?t.slice(a,i+1):[]};function nGt(s){return s==="number"?[0,"auto"]:void 0}var FHe=function(t,n,r,a){var i=t.graphicalItems,l=t.tooltipAxis,o=LLe(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 p=h===void 0?o:h;m=TAe(p,l.dataKey,a)}else m=h&&h[r]||o[r];return m?[].concat(CH(c),[FVt(d,m)]):c},[])},u_t=function(t,n,r,a){var i=a||{x:t.chartX,y:t.chartY},l=jCn(i,r),o=t.orderedTooltipTicks,c=t.tooltipAxis,d=t.tooltipTicks,u=H_n(l,o,d,c);if(u>=0&&d){var h=d[u]&&d[u].value,m=FHe(t,n,u,h),p=NCn(r,o,u,i);return{activeTooltipIndex:u,activeLabel:h,activePayload:m,activeCoordinate:p}}return null},kCn=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,p=PVt(u,i);return r.reduce(function(f,x){var y,v=x.type.defaultProps!==void 0?sa(sa({},x.type.defaultProps),x.props):x.props,b=v.type,N=v.dataKey,S=v.allowDataOverflow,A=v.allowDuplicatedCategory,T=v.scale,L=v.ticks,M=v.includeHidden,I=v[l];if(f[I])return f;var R=LLe(t.data,{graphicalItems:a.filter(function(ie){var ce,je=l in ie.props?ie.props[l]:(ce=ie.type.defaultProps)===null||ce===void 0?void 0:ce[l];return je===I}),dataStartIndex:c,dataEndIndex:d}),z=R.length,$,H,V;X3n(v.domain,S,b)&&($=XVe(v.domain,null,S),p&&(b==="number"||T!=="auto")&&(V=XQ(R,N,"category")));var K=nGt(b);if(!$||$.length===0){var Z,Q=(Z=v.domain)!==null&&Z!==void 0?Z:K;if(N){if($=XQ(R,N,b),b==="category"&&p){var le=Rln($);A&&le?(H=$,$=xEe(0,z)):A||($=M1t(Q,$,x).reduce(function(ie,ce){return ie.indexOf(ce)>=0?ie:[].concat(CH(ie),[ce])},[]))}else if(b==="category")A?$=$.filter(function(ie){return ie!==""&&!sc(ie)}):$=M1t(Q,$,x).reduce(function(ie,ce){return ie.indexOf(ce)>=0||ce===""||sc(ce)?ie:[].concat(CH(ie),[ce])},[]);else if(b==="number"){var ue=Z_n(R,a.filter(function(ie){var ce,je,be=l in ie.props?ie.props[l]:(ce=ie.type.defaultProps)===null||ce===void 0?void 0:ce[l],he="hide"in ie.props?ie.props.hide:(je=ie.type.defaultProps)===null||je===void 0?void 0:je.hide;return be===I&&(M||!he)}),N,i,u);ue&&($=ue)}p&&(b==="number"||T!=="auto")&&(V=XQ(R,N,"category"))}else p?$=xEe(0,z):o&&o[I]&&o[I].hasStack&&b==="number"?$=m==="expand"?[0,1]:OVt(o[I].stackGroups,c,d):$=MVt(R,a.filter(function(ie){var ce=l in ie.props?ie.props[l]:ie.type.defaultProps[l],je="hide"in ie.props?ie.props.hide:ie.type.defaultProps.hide;return ce===I&&(M||!je)}),b,u,!0);if(b==="number")$=RHe(h,$,I,i,L),Q&&($=XVe(Q,$,S));else if(b==="category"&&Q){var se=Q,ne=$.every(function(ie){return se.indexOf(ie)>=0});ne&&($=se)}}return sa(sa({},f),{},Nl({},I,sa(sa({},v),{},{axisType:i,domain:$,categoricalDomain:V,duplicateDomain:H,originalDomain:(y=v.domain)!==null&&y!==void 0?y:K,isCategorical:p,layout:u})))},{})},SCn=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=LLe(t.data,{graphicalItems:r,dataStartIndex:c,dataEndIndex:d}),p=m.length,f=PVt(u,i),x=-1;return r.reduce(function(y,v){var b=v.type.defaultProps!==void 0?sa(sa({},v.type.defaultProps),v.props):v.props,N=b[l],S=nGt("number");if(!y[N]){x++;var A;return f?A=xEe(0,p):o&&o[N]&&o[N].hasStack?(A=OVt(o[N].stackGroups,c,d),A=RHe(h,A,N,i)):(A=XVe(S,MVt(m,r.filter(function(T){var L,M,I=l in T.props?T.props[l]:(L=T.type.defaultProps)===null||L===void 0?void 0:L[l],R="hide"in T.props?T.props.hide:(M=T.type.defaultProps)===null||M===void 0?void 0:M.hide;return I===N&&!R}),"number",u),a.defaultProps.allowDataOverflow),A=RHe(h,A,N,i)),sa(sa({},y),{},Nl({},N,sa(sa({axisType:i},a.defaultProps),{},{hide:!0,orientation:aj(_Cn,"".concat(i,".").concat(x%2),null),domain:A,originalDomain:S,isCategorical:f,layout:u})))}return y},{})},CCn=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=ij(u,i),p={};return m&&m.length?p=kCn(t,{axes:m,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d}):l&&l.length&&(p=SCn(t,{Axis:i,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d})),p},ACn=function(t){var n=o6(t),r=bA(n,!1,!0);return{tooltipTicks:r,orderedTooltipTicks:Vet(r,function(a){return a.coordinate}),tooltipAxis:n,tooltipAxisBandSize:aEe(n,r)}},h_t=function(t){var n=t.children,r=t.defaultShowTooltip,a=Pw(n,gH),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}},ECn=function(t){return!t||!t.length?!1:t.some(function(n){var r=FA(n&&n.type);return r&&r.indexOf("Bar")>=0})},m_t=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"}},TCn=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||{},p=Pw(h,gH),f=Pw(h,$q),x=Object.keys(c).reduce(function(A,T){var L=c[T],M=L.orientation;return!L.mirror&&!L.hide?sa(sa({},A),{},Nl({},M,A[M]+L.width)):A},{left:m.left||0,right:m.right||0}),y=Object.keys(l).reduce(function(A,T){var L=l[T],M=L.orientation;return!L.mirror&&!L.hide?sa(sa({},A),{},Nl({},M,aj(A,"".concat(M))+L.height)):A},{top:m.top||0,bottom:m.bottom||0}),v=sa(sa({},y),x),b=v.bottom;p&&(v.bottom+=p.props.height||gH.defaultProps.height),f&&n&&(v=K_n(v,a,r,n));var N=d-v.left-v.right,S=u-v.top-v.bottom;return sa(sa({brushBottom:b},v),{},{width:Math.max(N,0),height:Math.max(S,0)})},MCn=function(t,n){if(n==="xAxis")return t[n].width;if(n==="yAxis")return t[n].height},ILe=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 N=b.graphicalItems,S=b.stackGroups,A=b.offset,T=b.updateId,L=b.dataStartIndex,M=b.dataEndIndex,I=v.barSize,R=v.layout,z=v.barGap,$=v.barCategoryGap,H=v.maxBarSize,V=m_t(R),K=V.numericAxisName,Z=V.cateAxisName,Q=ECn(N),le=[];return N.forEach(function(ue,se){var ne=LLe(v.data,{graphicalItems:[ue],dataStartIndex:L,dataEndIndex:M}),ie=ue.type.defaultProps!==void 0?sa(sa({},ue.type.defaultProps),ue.props):ue.props,ce=ie.dataKey,je=ie.maxBarSize,be=ie["".concat(K,"Id")],he=ie["".concat(Z,"Id")],ge={},ke=c.reduce(function(Ue,Ye){var Ge=b["".concat(Ye.axisType,"Map")],He=ie["".concat(Ye.axisType,"Id")];Ge&&Ge[He]||Ye.axisType==="zAxis"||U7();var tt=Ge[He];return sa(sa({},Ue),{},Nl(Nl({},Ye.axisType,tt),"".concat(Ye.axisType,"Ticks"),bA(tt)))},ge),Te=ke[Z],Me=ke["".concat(Z,"Ticks")],Oe=S&&S[be]&&S[be].hasStack&&awn(ue,S[be].stackGroups),Se=FA(ue.type).indexOf("Bar")>=0,Qe=aEe(Te,Me),Ae=[],Fe=Q&&G_n({barSize:I,stackGroups:S,totalSize:MCn(ke,Z)});if(Se){var Ne,$e,Ve=sc(je)?H:je,qe=(Ne=($e=aEe(Te,Me,!0))!==null&&$e!==void 0?$e:Ve)!==null&&Ne!==void 0?Ne:0;Ae=W_n({barGap:z,barCategoryGap:$,bandSize:qe!==Qe?qe:Qe,sizeList:Fe[he],maxBarSize:Ve}),qe!==Qe&&(Ae=Ae.map(function(Ue){return sa(sa({},Ue),{},{position:sa(sa({},Ue.position),{},{offset:Ue.position.offset-qe/2})})}))}var Ze=ue&&ue.type&&ue.type.getComposedData;Ze&&le.push({props:sa(sa({},Ze(sa(sa({},ke),{},{displayedData:ne,props:v,dataKey:ce,item:ue,bandSize:Qe,barPosition:Ae,offset:A,stackedData:Oe,layout:R,dataStartIndex:L,dataEndIndex:M}))),{},Nl(Nl(Nl({key:ue.key||"item-".concat(se)},K,ke[K]),Z,ke[Z]),"animationId",T)),childIndex:Wln(ue,v.children),item:ue})}),le},p=function(v,b){var N=v.props,S=v.dataStartIndex,A=v.dataEndIndex,T=v.updateId;if(!kyt({props:N}))return null;var L=N.children,M=N.layout,I=N.stackOffset,R=N.data,z=N.reverseStackOrder,$=m_t(M),H=$.numericAxisName,V=$.cateAxisName,K=ij(L,r),Z=nwn(R,K,"".concat(H,"Id"),"".concat(V,"Id"),I,z),Q=c.reduce(function(ie,ce){var je="".concat(ce.axisType,"Map");return sa(sa({},ie),{},Nl({},je,CCn(N,sa(sa({},ce),{},{graphicalItems:K,stackGroups:ce.axisType===H&&Z,dataStartIndex:S,dataEndIndex:A}))))},{}),le=TCn(sa(sa({},Q),{},{props:N,graphicalItems:K}),b==null?void 0:b.legendBBox);Object.keys(Q).forEach(function(ie){Q[ie]=u(N,Q[ie],le,ie.replace("Map",""),n)});var ue=Q["".concat(V,"Map")],se=ACn(ue),ne=m(N,sa(sa({},Q),{},{dataStartIndex:S,dataEndIndex:A,updateId:T,graphicalItems:K,stackGroups:Z,offset:le}));return sa(sa({formattedGraphicalItems:ne,graphicalItems:K,offset:le,stackGroups:Z},se),Q)},f=function(y){function v(b){var N,S,A;return dCn(this,v),A=mCn(this,v,[b]),Nl(A,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),Nl(A,"accessibilityManager",new Z3n),Nl(A,"handleLegendBBoxUpdate",function(T){if(T){var L=A.state,M=L.dataStartIndex,I=L.dataEndIndex,R=L.updateId;A.setState(sa({legendBBox:T},p({props:A.props,dataStartIndex:M,dataEndIndex:I,updateId:R},sa(sa({},A.state),{},{legendBBox:T}))))}}),Nl(A,"handleReceiveSyncEvent",function(T,L,M){if(A.props.syncId===T){if(M===A.eventEmitterSymbol&&typeof A.props.syncMethod!="function")return;A.applySyncEvent(L)}}),Nl(A,"handleBrushChange",function(T){var L=T.startIndex,M=T.endIndex;if(L!==A.state.dataStartIndex||M!==A.state.dataEndIndex){var I=A.state.updateId;A.setState(function(){return sa({dataStartIndex:L,dataEndIndex:M},p({props:A.props,dataStartIndex:L,dataEndIndex:M,updateId:I},A.state))}),A.triggerSyncEvent({dataStartIndex:L,dataEndIndex:M})}}),Nl(A,"handleMouseEnter",function(T){var L=A.getMouseInfo(T);if(L){var M=sa(sa({},L),{},{isTooltipActive:!0});A.setState(M),A.triggerSyncEvent(M);var I=A.props.onMouseEnter;kl(I)&&I(M,T)}}),Nl(A,"triggeredAfterMouseMove",function(T){var L=A.getMouseInfo(T),M=L?sa(sa({},L),{},{isTooltipActive:!0}):{isTooltipActive:!1};A.setState(M),A.triggerSyncEvent(M);var I=A.props.onMouseMove;kl(I)&&I(M,T)}),Nl(A,"handleItemMouseEnter",function(T){A.setState(function(){return{isTooltipActive:!0,activeItem:T,activePayload:T.tooltipPayload,activeCoordinate:T.tooltipPosition||{x:T.cx,y:T.cy}}})}),Nl(A,"handleItemMouseLeave",function(){A.setState(function(){return{isTooltipActive:!1}})}),Nl(A,"handleMouseMove",function(T){T.persist(),A.throttleTriggeredAfterMouseMove(T)}),Nl(A,"handleMouseLeave",function(T){A.throttleTriggeredAfterMouseMove.cancel();var L={isTooltipActive:!1};A.setState(L),A.triggerSyncEvent(L);var M=A.props.onMouseLeave;kl(M)&&M(L,T)}),Nl(A,"handleOuterEvent",function(T){var L=Gln(T),M=aj(A.props,"".concat(L));if(L&&kl(M)){var I,R;/.*touch.*/i.test(L)?R=A.getMouseInfo(T.changedTouches[0]):R=A.getMouseInfo(T),M((I=R)!==null&&I!==void 0?I:{},T)}}),Nl(A,"handleClick",function(T){var L=A.getMouseInfo(T);if(L){var M=sa(sa({},L),{},{isTooltipActive:!0});A.setState(M),A.triggerSyncEvent(M);var I=A.props.onClick;kl(I)&&I(M,T)}}),Nl(A,"handleMouseDown",function(T){var L=A.props.onMouseDown;if(kl(L)){var M=A.getMouseInfo(T);L(M,T)}}),Nl(A,"handleMouseUp",function(T){var L=A.props.onMouseUp;if(kl(L)){var M=A.getMouseInfo(T);L(M,T)}}),Nl(A,"handleTouchMove",function(T){T.changedTouches!=null&&T.changedTouches.length>0&&A.throttleTriggeredAfterMouseMove(T.changedTouches[0])}),Nl(A,"handleTouchStart",function(T){T.changedTouches!=null&&T.changedTouches.length>0&&A.handleMouseDown(T.changedTouches[0])}),Nl(A,"handleTouchEnd",function(T){T.changedTouches!=null&&T.changedTouches.length>0&&A.handleMouseUp(T.changedTouches[0])}),Nl(A,"handleDoubleClick",function(T){var L=A.props.onDoubleClick;if(kl(L)){var M=A.getMouseInfo(T);L(M,T)}}),Nl(A,"handleContextMenu",function(T){var L=A.props.onContextMenu;if(kl(L)){var M=A.getMouseInfo(T);L(M,T)}}),Nl(A,"triggerSyncEvent",function(T){A.props.syncId!==void 0&&A7e.emit(E7e,A.props.syncId,T,A.eventEmitterSymbol)}),Nl(A,"applySyncEvent",function(T){var L=A.props,M=L.layout,I=L.syncMethod,R=A.state.updateId,z=T.dataStartIndex,$=T.dataEndIndex;if(T.dataStartIndex!==void 0||T.dataEndIndex!==void 0)A.setState(sa({dataStartIndex:z,dataEndIndex:$},p({props:A.props,dataStartIndex:z,dataEndIndex:$,updateId:R},A.state)));else if(T.activeTooltipIndex!==void 0){var H=T.chartX,V=T.chartY,K=T.activeTooltipIndex,Z=A.state,Q=Z.offset,le=Z.tooltipTicks;if(!Q)return;if(typeof I=="function")K=I(le,T);else if(I==="value"){K=-1;for(var ue=0;ue=0){var Oe,Se;if(H.dataKey&&!H.allowDuplicatedCategory){var Qe=typeof H.dataKey=="function"?Me:"payload.".concat(H.dataKey.toString());Oe=TAe(ue,Qe,K),Se=se&&ne&&TAe(ne,Qe,K)}else Oe=ue==null?void 0:ue[V],Se=se&&ne&&ne[V];if(he||be){var Ae=T.props.activeIndex!==void 0?T.props.activeIndex:V;return[j.cloneElement(T,sa(sa(sa({},I.props),ke),{},{activeIndex:Ae})),null,null]}if(!sc(Oe))return[Te].concat(CH(A.renderActivePoints({item:I,activePoint:Oe,basePoint:Se,childIndex:V,isRange:se})))}else{var Fe,Ne=(Fe=A.getItemByXY(A.state.activeCoordinate))!==null&&Fe!==void 0?Fe:{graphicalItem:Te},$e=Ne.graphicalItem,Ve=$e.item,qe=Ve===void 0?T:Ve,Ze=$e.childIndex,Ue=sa(sa(sa({},I.props),ke),{},{activeIndex:Ze});return[j.cloneElement(qe,Ue),null,null]}return se?[Te,null,null]:[Te,null]}),Nl(A,"renderCustomized",function(T,L,M){return j.cloneElement(T,sa(sa({key:"recharts-customized-".concat(M)},A.props),A.state))}),Nl(A,"renderMap",{CartesianGrid:{handler:Ple,once:!0},ReferenceArea:{handler:A.renderReferenceElement},ReferenceLine:{handler:Ple},ReferenceDot:{handler:A.renderReferenceElement},XAxis:{handler:Ple},YAxis:{handler:Ple},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((N=b.id)!==null&&N!==void 0?N:S9("recharts"),"-clip"),A.throttleTriggeredAfterMouseMove=A$t(A.triggeredAfterMouseMove,(S=b.throttleDelay)!==null&&S!==void 0?S:1e3/60),A.state={},A}return gCn(v,y),hCn(v,[{key:"componentDidMount",value:function(){var N,S;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(N=this.props.margin.left)!==null&&N!==void 0?N: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 N=this.props,S=N.children,A=N.data,T=N.height,L=N.layout,M=Pw(S,Tg);if(M){var I=M.props.defaultIndex;if(!(typeof I!="number"||I<0||I>this.state.tooltipTicks.length-1)){var R=this.state.tooltipTicks[I]&&this.state.tooltipTicks[I].value,z=FHe(this.state,A,I,R),$=this.state.tooltipTicks[I].coordinate,H=(this.state.offset.top+T)/2,V=L==="horizontal",K=V?{x:$,y:H}:{y:$,x:H},Z=this.state.formattedGraphicalItems.find(function(le){var ue=le.item;return ue.type.name==="Scatter"});Z&&(K=sa(sa({},K),Z.props.points[I].tooltipPosition),z=Z.props.points[I].tooltipPayload);var Q={activeTooltipIndex:I,isTooltipActive:!0,activeLabel:R,activePayload:z,activeCoordinate:K};this.setState(Q),this.renderCursor(M),this.accessibilityManager.setIndex(I)}}}},{key:"getSnapshotBeforeUpdate",value:function(N,S){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==S.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==N.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==N.margin){var A,T;this.accessibilityManager.setDetails({offset:{left:(A=this.props.margin.left)!==null&&A!==void 0?A:0,top:(T=this.props.margin.top)!==null&&T!==void 0?T:0}})}return null}},{key:"componentDidUpdate",value:function(N){hVe([Pw(N.children,Tg)],[Pw(this.props.children,Tg)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var N=Pw(this.props.children,Tg);if(N&&typeof N.props.shared=="boolean"){var S=N.props.shared?"axis":"item";return o.indexOf(S)>=0?S:i}return i}},{key:"getMouseInfo",value:function(N){if(!this.container)return null;var S=this.container,A=S.getBoundingClientRect(),T=vyn(A),L={chartX:Math.round(N.pageX-T.left),chartY:Math.round(N.pageY-T.top)},M=A.width/S.offsetWidth||1,I=this.inRange(L.chartX,L.chartY,M);if(!I)return null;var R=this.state,z=R.xAxisMap,$=R.yAxisMap,H=this.getTooltipEventType(),V=u_t(this.state,this.props.data,this.props.layout,I);if(H!=="axis"&&z&&$){var K=o6(z).scale,Z=o6($).scale,Q=K&&K.invert?K.invert(L.chartX):null,le=Z&&Z.invert?Z.invert(L.chartY):null;return sa(sa({},L),{},{xValue:Q,yValue:le},V)}return V?sa(sa({},L),V):null}},{key:"inRange",value:function(N,S){var A=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,T=this.props.layout,L=N/A,M=S/A;if(T==="horizontal"||T==="vertical"){var I=this.state.offset,R=L>=I.left&&L<=I.left+I.width&&M>=I.top&&M<=I.top+I.height;return R?{x:L,y:M}:null}var z=this.state,$=z.angleAxisMap,H=z.radiusAxisMap;if($&&H){var V=o6($);return I1t({x:L,y:M},V)}return null}},{key:"parseEventsOfWrapper",value:function(){var N=this.props.children,S=this.getTooltipEventType(),A=Pw(N,Tg),T={};A&&S==="axis"&&(A.props.trigger==="click"?T={onClick:this.handleClick}:T={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 L=MAe(this.props,this.handleOuterEvent);return sa(sa({},L),T)}},{key:"addListener",value:function(){A7e.on(E7e,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){A7e.removeListener(E7e,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(N,S,A){for(var T=this.state.formattedGraphicalItems,L=0,M=T.length;L{const{data:b,error:N}=await q.from("email_campaigns").select("*").eq("status","sent").order("sent_at",{ascending:!0});if(N)throw N;return b}}),{data:r}=ct({queryKey:["campaign-agent-profiles"],queryFn:async()=>{const{data:b,error:N}=await q.from("profiles").select("id, name, email");if(N)throw N;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,N)=>b+(N.sent_count||0),0),o=a.reduce((b,N)=>b+(N.open_count||0),0),c=a.reduce((b,N)=>b+(N.click_count||0),0),d=a.reduce((b,N)=>b+(N.bounce_count||0),0),u=a.reduce((b,N)=>b+(N.complaint_count||0),0),h=l>0?(o/l*100).toFixed(1):"0.0",m=l>0?(c/l*100).toFixed(1):"0.0",p=[{label:"Campaigns Sent",value:a.length,icon:$r,color:"text-foreground"},{label:"Total Emails Sent",value:l,icon:Bn,color:"text-green-600"},{label:"Avg Open Rate",value:`${h}%`,icon:xa,color:"text-blue-600"},{label:"Avg Click Rate",value:`${m}%`,icon:n0,color:"text-purple-600"},{label:"Total Bounces",value:d,icon:tc,color:"text-orange-600"},{label:"Complaints",value:u,icon:rc,color:"text-destructive"}],f=new Map;a.forEach(b=>{var A,T;const N=b.user_id,S=f.get(N)||{name:((A=i.get(N))==null?void 0:A.name)||((T=i.get(N))==null?void 0:T.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,f.set(N,S)});const x=[...f.entries()].map(([b,N])=>({id:b,...N,openRate:N.sent>0?+(N.opens/N.sent*100).toFixed(1):0})).sort((b,N)=>N.sent-b.sent),y=x.slice(0,6).map(b=>({name:b.name,value:b.sent})),v=a.map(b=>{var N;return{name:b.name.length>20?b.name.slice(0,20)+"…":b.name,agent:((N=i.get(b.user_id))==null?void 0:N.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?Gs(new Date(b.sent_at),"MMM d"):""}});return e.jsx("div",{className:"space-y-6",children:a.length===0?e.jsx(we,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx($r,{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:p.map(b=>e.jsx(we,{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(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Open & Click Rates by Campaign"})}),e.jsx(Ie,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(oj,{width:"100%",height:"100%",children:e.jsxs(RLe,{data:v,children:[e.jsx(wb,{dataKey:"date",fontSize:11}),e.jsx(jb,{fontSize:11,unit:"%"}),e.jsx(Tg,{formatter:b=>`${b}%`}),e.jsx(pN,{dataKey:"openRate",fill:"hsl(220, 70%, 50%)",name:"Open Rate",radius:[2,2,0,0]}),e.jsx(pN,{dataKey:"clickRate",fill:"hsl(270, 70%, 50%)",name:"Click Rate",radius:[2,2,0,0]})]})})})})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Send Volume by Agent"})}),e.jsx(Ie,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(oj,{width:"100%",height:"100%",children:e.jsxs(rGt,{children:[e.jsx(p3,{data:y,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:100,label:({name:b,percent:N})=>`${b} (${(N*100).toFixed(0)}%)`,fontSize:11,children:y.map((b,N)=>e.jsx(VG,{fill:p_t[N%p_t.length]},N))}),e.jsx(Tg,{})]})})})})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Send Volume Trend"})}),e.jsx(Ie,{children:e.jsx("div",{className:"h-[240px]",children:e.jsx(oj,{width:"100%",height:"100%",children:e.jsxs(Att,{data:v,children:[e.jsx(wb,{dataKey:"date",fontSize:11}),e.jsx(jb,{fontSize:11}),e.jsx(Tg,{}),e.jsx(gP,{type:"monotone",dataKey:"sent",stroke:"hsl(142, 71%, 45%)",strokeWidth:2,name:"Emails Sent",dot:{r:4}})]})})})})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Agent Performance"})}),e.jsx(Ie,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-left text-muted-foreground",children:[e.jsx("th",{className:"pb-2 font-medium",children:"Agent"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Campaigns"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Sent"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Opens"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Clicks"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Open Rate"})]})}),e.jsx("tbody",{children:x.map(b=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-2.5 font-medium",children:b.name}),e.jsx("td",{className:"py-2.5 text-center",children:b.campaigns}),e.jsx("td",{className:"py-2.5 text-center",children:b.sent}),e.jsx("td",{className:"py-2.5 text-center",children:b.opens}),e.jsx("td",{className:"py-2.5 text-center",children:b.clicks}),e.jsx("td",{className:"py-2.5 text-center",children:e.jsxs(Be,{variant:"outline",children:[b.openRate,"%"]})})]},b.id))})]})})})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Campaign Leaderboard"})}),e.jsx(Ie,{children:e.jsx("div",{className:"space-y-2",children:[...a].sort((b,N)=>{const S=b.sent_count>0?b.open_count/b.sent_count:0;return(N.sent_count>0?N.open_count/N.sent_count:0)-S}).slice(0,10).map((b,N)=>{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",T=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:["#",N+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:[(T==null?void 0:T.name)||"Unknown"," · ",b.sent_at?Gs(new Date(b.sent_at),"MMM d, yyyy"):""," · ",b.sent_count," sent"]})]}),e.jsxs("div",{className:"flex gap-3 text-xs",children:[e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(xa,{className:"h-3 w-3"})," ",S,"%"]}),e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(n0,{className:"h-3 w-3"})," ",A,"%"]})]})]},b.id)})})})]})]})})}const LCn=()=>{const{toast:s}=Ai(),[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"),p=[];let f=0;for(;;){const{data:A,error:T}=await q.from("agent_website_app_installs").select("user_id, app_slug, enabled").range(f,f+999);if(T)throw T;if(p.push(...A||[]),!A||A.length<1e3)break;f+=1e3}const x=[];for(f=0;;){const{data:A,error:T}=await q.from("widget_events").select("user_id, app_slug, event_type, created_at").gte("created_at",h).order("created_at",{ascending:!1}).range(f,f+999);if(T)throw T;if(x.push(...A||[]),!A||A.length<1e3||(f+=1e3,f>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 p){const T=y.get(A.app_slug);T&&(T.installs+=1,A.enabled&&(T.enabled+=1))}for(const A of x){const T=y.get(A.app_slug);T&&(A.event_type==="impression"?T.impressions+=1:A.event_type==="expand"?T.expands+=1:A.event_type==="cta_click"?T.cta_clicks+=1:A.event_type==="lead_capture"&&(T.lead_captures+=1))}const v=new Map;for(const A of p){if(!A.enabled)continue;const T=v.get(A.user_id)||{user_id:A.user_id,name:null,email:null,apps_enabled:[],events_30d:0,leads_30d:0};T.apps_enabled.includes(A.app_slug)||T.apps_enabled.push(A.app_slug),v.set(A.user_id,T)}for(const A of x){const T=v.get(A.user_id);T&&(T.events_30d+=1,A.event_type==="lead_capture"&&(T.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 T of A||[]){const L=v.get(T.id);L&&(L.name=T.name,L.email=T.email)}}const N=Array.from(y.values()),S=Array.from(v.values()).sort((A,T)=>T.events_30d-A.events_30d);a(N),l(S),c({installs:N.reduce((A,T)=>A+T.enabled,0),activeAgents:S.length,impressions30d:N.reduce((A,T)=>A+T.impressions,0),leads30d:N.reduce((A,T)=>A+T.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(we,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Active Installs"}),e.jsx(fl,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Agents Using Apps"}),e.jsx(Bn,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Impressions (30d)"}),e.jsx(xa,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Leads Captured (30d)"}),e.jsx(ln,{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(we,{children:[e.jsx(Tt,{children:e.jsx(It,{children:"App Performance (last 30 days)"})}),e.jsx(Ie,{children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"App"}),e.jsx(Lt,{className:"text-right",children:"Installs"}),e.jsx(Lt,{className:"text-right",children:"Enabled"}),e.jsx(Lt,{className:"text-right",children:"Impressions"}),e.jsx(Lt,{className:"text-right",children:"Expands"}),e.jsx(Lt,{className:"text-right",children:"CTA Clicks"}),e.jsx(Lt,{className:"text-right",children:"Leads"}),e.jsx(Lt,{className:"text-right",children:"Conv. Rate"})]})}),e.jsxs(Xa,{children:[r.map(u=>{const h=u.impressions>0?(u.lead_captures/u.impressions*100).toFixed(1):"—";return e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium",children:u.app_name}),e.jsx(gt,{className:"text-right",children:u.installs}),e.jsx(gt,{className:"text-right",children:u.enabled}),e.jsx(gt,{className:"text-right",children:u.impressions}),e.jsx(gt,{className:"text-right",children:u.expands}),e.jsx(gt,{className:"text-right",children:u.cta_clicks}),e.jsx(gt,{className:"text-right font-semibold",children:u.lead_captures}),e.jsx(gt,{className:"text-right text-muted-foreground",children:h==="—"?"—":`${h}%`})]},u.app_slug)}),r.length===0&&e.jsx(gn,{children:e.jsx(gt,{colSpan:8,className:"text-center text-muted-foreground py-6",children:"No data yet"})})]})]})})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{children:"Agent Usage (last 30 days)"})}),e.jsxs(Ie,{children:[e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Agent"}),e.jsx(Lt,{children:"Email"}),e.jsx(Lt,{children:"Apps Enabled"}),e.jsx(Lt,{className:"text-right",children:"Events (30d)"}),e.jsx(Lt,{className:"text-right",children:"Leads (30d)"})]})}),e.jsxs(Xa,{children:[i.slice(0,100).map(u=>e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium",children:u.name||"—"}),e.jsx(gt,{className:"text-muted-foreground",children:u.email||"—"}),e.jsx(gt,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:u.apps_enabled.map(h=>e.jsx(Be,{variant:"secondary",className:"text-xs",children:h},h))})}),e.jsx(gt,{className:"text-right",children:u.events_30d}),e.jsx(gt,{className:"text-right font-semibold",children:u.leads_30d})]},u.user_id)),i.length===0&&e.jsx(gn,{children:e.jsx(gt,{colSpan:5,className:"text-center text-muted-foreground py-6",children:"No agents have enabled website apps yet"})})]})]}),i.length>100&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Showing top 100 of ",i.length," agents."]})]})]})]})},ICn=()=>{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)]),p=h||[],f=m||[];t(p),r(f);const x=Array.from(new Set(f.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(we,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(Bn,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Total Actions"}),e.jsx(NF,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Contacts Saved"}),e.jsx(zl,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Listings Imported"}),e.jsx(ra,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Activities Logged"}),e.jsx(Ki,{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(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"User"}),e.jsx(Lt,{className:"text-right",children:"Total"}),e.jsx(Lt,{className:"text-right",children:"Contacts"}),e.jsx(Lt,{className:"text-right",children:"Listings"}),e.jsx(Lt,{className:"text-right",children:"Activities"}),e.jsx(Lt,{children:"First Used"}),e.jsx(Lt,{children:"Last Used"})]})}),e.jsx(Xa,{children:s.map(h=>e.jsxs(gn,{children:[e.jsxs(gt,{children:[e.jsx("div",{className:"font-medium",children:h.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:h.email})]}),e.jsx(gt,{className:"text-right font-medium",children:h.total_events}),e.jsx(gt,{className:"text-right",children:h.contacts_saved}),e.jsx(gt,{className:"text-right",children:h.listings_imported}),e.jsx(gt,{className:"text-right",children:h.activities_logged}),e.jsx(gt,{className:"text-xs text-muted-foreground",children:h.first_event_at?Gs(new Date(h.first_event_at),"MMM d, yyyy"):"—"}),e.jsx(gt,{className:"text-xs text-muted-foreground",children:h.last_event_at?Gs(new Date(h.last_event_at),"MMM d, h:mm a"):"—"})]},h.user_id))})]})})})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{children:"Recent Activity"})}),e.jsx(Ie,{children:n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No recent events."}):e.jsx("div",{className:"space-y-2",children:n.map(h=>{const m=a[h.user_id];return e.jsxs("div",{className:"flex items-center justify-between border-b pb-2 last:border-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Be,{variant:"secondary",children:u(h.action)}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:(m==null?void 0:m.name)||(m==null?void 0:m.email)||h.user_id.slice(0,8)}),h.metadata&&Object.keys(h.metadata).length>0&&e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:JSON.stringify(h.metadata)})]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Gs(new Date(h.created_at),"MMM d, h:mm a")})]},h.id)})})})]})]})},RCn=()=>e.jsx(qs,{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(oa,{defaultValue:"analytics",className:"space-y-4",children:[e.jsxs(la,{children:[e.jsx(Kt,{value:"analytics",children:"Analytics"}),e.jsx(Kt,{value:"website-apps",children:"Website Apps"}),e.jsx(Kt,{value:"extension",children:"Chrome Extension"}),e.jsx(Kt,{value:"content",children:"Content"}),e.jsx(Kt,{value:"email-campaigns",children:"Email Campaigns"}),e.jsx(Kt,{value:"activity",children:"Activity"}),e.jsx(Kt,{value:"shares",children:"Shares"})]}),e.jsx(Zt,{value:"analytics",className:"space-y-4",children:e.jsx(Qrn,{})}),e.jsx(Zt,{value:"website-apps",className:"space-y-4",children:e.jsx(LCn,{})}),e.jsx(Zt,{value:"extension",className:"space-y-4",children:e.jsx(ICn,{})}),e.jsx(Zt,{value:"content",className:"space-y-4",children:e.jsx(ean,{})}),e.jsx(Zt,{value:"email-campaigns",className:"space-y-4",children:e.jsx(PCn,{})}),e.jsx(Zt,{value:"activity",className:"space-y-4",children:e.jsx(Xrn,{})}),e.jsx(Zt,{value:"shares",className:"space-y-4",children:e.jsx(hqt,{})})]})]})});function DCn(){const s=Qt(),[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([]),[p,f]=j.useState([]),[x,y]=j.useState([]),[v,b]=j.useState(!1),[N,S]=j.useState(null),[A,T]=j.useState(""),{data:L,isLoading:M}=ct({queryKey:["brokerage-resources"],queryFn:async()=>{const{data:Se,error:Qe}=await q.from("brokerage_resources").select("*").order("publish_date",{ascending:!1});if(Qe)throw Qe;return Se}}),{data:I}=ct({queryKey:["brokerage-resource-pdfs"],queryFn:async()=>{const{data:Se,error:Qe}=await q.from("brokerage_resource_pdfs").select("*").order("sort_order",{ascending:!0});if(Qe)throw Qe;return Se}}),{data:R}=ct({queryKey:["brokerage-resource-videos"],queryFn:async()=>{const{data:Se,error:Qe}=await q.from("brokerage_resource_videos").select("*").order("sort_order",{ascending:!0});if(Qe)throw Qe;return Se}}),{data:z}=ct({queryKey:["brokerage-resource-links"],queryFn:async()=>{const{data:Se,error:Qe}=await q.from("brokerage_resource_links").select("*").order("sort_order",{ascending:!0});if(Qe)throw Qe;return Se}}),{data:$,isLoading:H}=ct({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:Se,error:Qe}=await q.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(Qe)throw Qe;return Se}}),V=()=>{l({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),c(null),u(""),m([]),f([]),y([]),a(null),T("")},K=Se=>{a(Se),l({title:Se.title,description:Se.description||"",publish_date:Se.publish_date.split("T")[0],is_published:Se.is_published,category_id:Se.category_id||""}),u(Se.preview_image_url||""),T("");const Qe=(I==null?void 0:I.filter(Ne=>Ne.resource_id===Se.id))||[];m(Qe.map(Ne=>({id:Ne.id,name:Ne.name,file_url:Ne.file_url,file_size:Ne.file_size,sort_order:Ne.sort_order})));const Ae=(R==null?void 0:R.filter(Ne=>Ne.resource_id===Se.id))||[];f(Ae.map(Ne=>({id:Ne.id,title:Ne.title,video_url:Ne.video_url,sort_order:Ne.sort_order})));const Fe=(z==null?void 0:z.filter(Ne=>Ne.resource_id===Se.id))||[];y(Fe.map(Ne=>({id:Ne.id,title:Ne.title,canva_share_link:Ne.canva_share_link,sort_order:Ne.sort_order}))),n(!0)},Z=Se=>{var Ae;const Qe=(Ae=Se.target.files)==null?void 0:Ae[0];Qe&&(c(Qe),u(URL.createObjectURL(Qe)))},Q=()=>{m([...h,{name:"",file_url:"",sort_order:h.length}])},le=Se=>{m(h.filter((Qe,Ae)=>Ae!==Se))},ue=(Se,Qe,Ae)=>{const Fe=[...h];if(Qe==="file"&&Ae instanceof File){const Ne=Ae.name.replace(/\.[^/.]+$/,"");Fe[Se]={...Fe[Se],file:Ae,file_size:Ae.size,name:Fe[Se].name||Ne}}else Fe[Se]={...Fe[Se],[Qe]:Ae};m(Fe)},se=()=>{f([...p,{title:"",video_url:"",sort_order:p.length}])},ne=Se=>{f(p.filter((Qe,Ae)=>Ae!==Se))},ie=(Se,Qe,Ae)=>{const Fe=[...p];Qe==="file"&&Ae instanceof File?Fe[Se]={...Fe[Se],file:Ae}:Fe[Se]={...Fe[Se],[Qe]:Ae},f(Fe)},ce=()=>{y([...x,{title:"",canva_share_link:"",sort_order:x.length}])},je=Se=>{y(x.filter((Qe,Ae)=>Ae!==Se))},be=(Se,Qe,Ae)=>{const Fe=[...x];Fe[Se]={...Fe[Se],[Qe]:Ae},y(Fe)},he=async(Se,Qe)=>{try{const Ae=await q.functions.invoke("bunny-upload",{body:{action:"create",title:Se.name}});if(Ae.error)throw Ae.error;const{videoId:Fe,uploadUrl:Ne,libraryId:$e}=Ae.data,Ve=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Fe,libraryId:$e}});if(Ve.error)throw Ve.error;const{uploadUrl:qe,apiKey:Ze}=Ve.data,Ue=new XMLHttpRequest;return Ue.open("PUT",qe,!0),Ue.setRequestHeader("AccessKey",Ze),Ue.upload.onprogress=Ye=>{if(Ye.lengthComputable){const Ge=Math.round(Ye.loaded/Ye.total*100),He=[...p];He[Qe]={...He[Qe],uploadProgress:Ge},f(He)}},await new Promise((Ye,Ge)=>{Ue.onload=()=>Ue.status>=200&&Ue.status<300?Ye():Ge(new Error("Upload failed")),Ue.onerror=()=>Ge(new Error("Upload failed")),Ue.send(Se)}),`https://iframe.mediadelivery.net/embed/${$e}/${Fe}`}catch(Ae){throw console.error("Bunny upload error:",Ae),Ae}},ge=yt({mutationFn:async Se=>{const{data:Qe,error:Ae}=await q.from("brokerage_resource_categories").insert({name:Se,sort_order:($==null?void 0:$.length)||0}).select().single();if(Ae)throw Ae;return Qe},onSuccess:Se=>{s.invalidateQueries({queryKey:["brokerage-resource-categories"]}),l({...i,category_id:Se.id}),T(""),re.success("Category created")},onError:Se=>{re.error("Failed to create category: "+Se.message)}}),ke=yt({mutationFn:async()=>{b(!0);let Se=(r==null?void 0:r.preview_image_url)||null;if(o){const Fe=o.name.split(".").pop(),Ne=`${Date.now()}.${Fe}`,{error:$e}=await q.storage.from("brokerage-resources").upload(`previews/${Ne}`,o);if($e)throw $e;const{data:Ve}=q.storage.from("brokerage-resources").getPublicUrl(`previews/${Ne}`);Se=Ve.publicUrl}const Qe={title:i.title,description:i.description||null,preview_image_url:Se,publish_date:i.publish_date,is_published:i.is_published,category_id:i.category_id||null};let Ae;if(r){const{error:Fe}=await q.from("brokerage_resources").update(Qe).eq("id",r.id);if(Fe)throw Fe;Ae=r.id;const Ne=(I==null?void 0:I.filter(tt=>tt.resource_id===r.id).map(tt=>tt.id))||[],$e=h.filter(tt=>tt.id).map(tt=>tt.id),Ve=Ne.filter(tt=>!$e.includes(tt));Ve.length>0&&await q.from("brokerage_resource_pdfs").delete().in("id",Ve);const qe=(R==null?void 0:R.filter(tt=>tt.resource_id===r.id).map(tt=>tt.id))||[],Ze=p.filter(tt=>tt.id).map(tt=>tt.id),Ue=qe.filter(tt=>!Ze.includes(tt));Ue.length>0&&await q.from("brokerage_resource_videos").delete().in("id",Ue);const Ye=(z==null?void 0:z.filter(tt=>tt.resource_id===r.id).map(tt=>tt.id))||[],Ge=x.filter(tt=>tt.id).map(tt=>tt.id),He=Ye.filter(tt=>!Ge.includes(tt));He.length>0&&await q.from("brokerage_resource_links").delete().in("id",He)}else{const{data:Fe,error:Ne}=await q.from("brokerage_resources").insert(Qe).select().single();if(Ne)throw Ne;Ae=Fe.id}for(let Fe=0;Fe{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:Se=>{re.error("Failed to save resource: "+Se.message),b(!1)}}),Te=yt({mutationFn:async Se=>{const{error:Qe}=await q.from("brokerage_resources").delete().eq("id",Se);if(Qe)throw Qe},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:Se=>{re.error("Failed to delete: "+Se.message)}}),Me=Se=>{if(Se.preventDefault(),!i.title){re.error("Please enter a title");return}ke.mutate()},Oe=Se=>{const Qe=(I==null?void 0:I.filter(Ne=>Ne.resource_id===Se).length)||0,Ae=(R==null?void 0:R.filter(Ne=>Ne.resource_id===Se).length)||0,Fe=(z==null?void 0:z.filter(Ne=>Ne.resource_id===Se).length)||0;return{pdfCount:Qe,videoCount:Ae,linkCount:Fe}};return e.jsx(qs,{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(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Total Resources"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:(L==null?void 0:L.length)||0})})]}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:(L==null?void 0:L.filter(Se=>Se.is_published).length)||0})})]})]}),e.jsxs(U,{onClick:()=>{V(),n(!0)},children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Add Resource"]})]}),e.jsx(we,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Title"}),e.jsx(Lt,{children:"Category"}),e.jsx(Lt,{children:"Content"}),e.jsx(Lt,{children:"Publish Date"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:M?e.jsx(gn,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):(L==null?void 0:L.length)===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No brokerage resources yet. Create your first one!"})}):L==null?void 0:L.map(Se=>{const{pdfCount:Qe,videoCount:Ae,linkCount:Fe}=Oe(Se.id),Ne=$==null?void 0:$.find($e=>$e.id===Se.category_id);return e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Se.preview_image_url?e.jsx("img",{src:Se.preview_image_url,alt:Se.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(og,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Se.title}),Se.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:Se.description})]})]})}),e.jsx(gt,{children:Ne?e.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-muted",children:Ne.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ur,{className:"h-3.5 w-3.5"}),Qe]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Wr,{className:"h-3.5 w-3.5"}),Ae]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Rc,{className:"h-3.5 w-3.5"}),Fe]})]})}),e.jsx(gt,{children:Gs(new Date(Se.publish_date),"MMM d, yyyy")}),e.jsx(gt,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${Se.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:Se.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>{const $e=(I==null?void 0:I.filter(Ze=>Ze.resource_id===Se.id))||[],Ve=(R==null?void 0:R.filter(Ze=>Ze.resource_id===Se.id))||[],qe=(z==null?void 0:z.filter(Ze=>Ze.resource_id===Se.id))||[];S({...Se,pdfs:$e,videos:Ve,links:qe})},children:e.jsx(xa,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>K(Se),children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:async()=>{await Yi("Delete this resource?")&&Te.mutate(Se.id)},children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]})})]},Se.id)})})]})})}),e.jsx(zs,{open:t,onOpenChange:n,children:e.jsxs(Ds,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:r?"Edit Brokerage Resource":"Add Brokerage Resource"})}),e.jsxs("form",{onSubmit:Me,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{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(og,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(xe,{type:"file",accept:"image/*",onChange:Z})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"title",children:"Title *"}),e.jsx(xe,{id:"title",value:i.title,onChange:Se=>l({...i,title:Se.target.value}),placeholder:"Resource Title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{className:"flex items-center gap-2",children:[e.jsx(Cf,{className:"h-4 w-4"}),"Category"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ns,{value:i.category_id,onValueChange:Se=>l({...i,category_id:Se}),children:[e.jsx(ws,{className:"flex-1",children:e.jsx(ks,{placeholder:"Select a category"})}),e.jsx(js,{children:$==null?void 0:$.map(Se=>e.jsx(et,{value:Se.id,children:Se.name},Se.id))})]}),i.category_id&&e.jsx(U,{type:"button",variant:"ghost",size:"icon",onClick:()=>l({...i,category_id:""}),children:e.jsx(er,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{placeholder:"Or create new category...",value:A,onChange:Se=>T(Se.target.value),className:"flex-1"}),e.jsxs(U,{type:"button",variant:"outline",size:"sm",disabled:!A.trim()||ge.isPending,onClick:()=>ge.mutate(A.trim()),children:[e.jsx(an,{className:"h-4 w-4 mr-1"}),"Add"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Description"}),e.jsx(SN,{content:i.description,onChange:Se=>l({...i,description:Se}),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(te,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(xe,{id:"publish_date",type:"date",value:i.publish_date,onChange:Se=>l({...i,publish_date:Se.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(wn,{checked:i.is_published,onCheckedChange:Se=>l({...i,is_published:Se})}),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(te,{className:"flex items-center gap-2",children:[e.jsx(Ur,{className:"h-4 w-4"}),"PDF Documents (",h.length,")"]}),e.jsxs(U,{type:"button",variant:"outline",size:"sm",onClick:Q,children:[e.jsx(an,{className:"h-4 w-4 mr-1"}),"Add PDF"]})]}),h.map((Se,Qe)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(xe,{placeholder:"PDF Name",value:Se.name,onChange:Ae=>ue(Qe,"name",Ae.target.value),className:"flex-1"}),e.jsx(xe,{type:"file",accept:".pdf",onChange:Ae=>{var Ne;const Fe=(Ne=Ae.target.files)==null?void 0:Ne[0];Fe&&ue(Qe,"file",Fe)},className:"flex-1"}),Se.file_url&&!Se.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Uploaded"}),e.jsx(U,{type:"button",variant:"ghost",size:"icon",onClick:()=>le(Qe),children:e.jsx(er,{className:"h-4 w-4"})})]},Qe))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(te,{className:"flex items-center gap-2",children:[e.jsx(Wr,{className:"h-4 w-4"}),"Videos (",p.length,")"]}),e.jsxs(U,{type:"button",variant:"outline",size:"sm",onClick:se,children:[e.jsx(an,{className:"h-4 w-4 mr-1"}),"Add Video"]})]}),p.map((Se,Qe)=>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(xe,{placeholder:"Video Title",value:Se.title,onChange:Ae=>ie(Qe,"title",Ae.target.value),className:"flex-1"}),e.jsx(U,{type:"button",variant:"ghost",size:"icon",onClick:()=>ne(Qe),children:e.jsx(er,{className:"h-4 w-4"})})]}),e.jsx(xe,{type:"file",accept:"video/*",onChange:Ae=>{var Ne;const Fe=(Ne=Ae.target.files)==null?void 0:Ne[0];Fe&&ie(Qe,"file",Fe)}}),Se.uploadProgress!==void 0&&Se.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:`${Se.uploadProgress}%`}})}),Se.video_url&&!Se.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Video uploaded"})]},Qe))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(te,{className:"flex items-center gap-2",children:[e.jsx(Rc,{className:"h-4 w-4"}),"Canva Links (",x.length,")"]}),e.jsxs(U,{type:"button",variant:"outline",size:"sm",onClick:ce,children:[e.jsx(an,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),x.map((Se,Qe)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(xe,{placeholder:"Link Title",value:Se.title,onChange:Ae=>be(Qe,"title",Ae.target.value),className:"flex-1"}),e.jsx(xe,{placeholder:"Canva Share Link",value:Se.canva_share_link,onChange:Ae=>be(Qe,"canva_share_link",Ae.target.value),className:"flex-1"}),e.jsx(U,{type:"button",variant:"ghost",size:"icon",onClick:()=>je(Qe),children:e.jsx(er,{className:"h-4 w-4"})})]},Qe))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(U,{type:"submit",disabled:ke.isPending||v,children:ke.isPending||v?"Saving...":r?"Update":"Create"})]})]})]})}),e.jsx(zs,{open:!!N,onOpenChange:()=>S(null),children:e.jsxs(Ds,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:N==null?void 0:N.title})}),N&&e.jsxs("div",{className:"space-y-4",children:[N.preview_image_url&&e.jsx("img",{src:N.preview_image_url,alt:N.title,className:"w-full h-48 object-cover rounded-lg"}),N.description&&e.jsx("p",{className:"text-muted-foreground",children:N.description}),N.pdfs&&N.pdfs.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(Ur,{className:"h-4 w-4"}),"PDF Documents (",N.pdfs.length,")"]}),e.jsx("div",{className:"space-y-1",children:N.pdfs.map(Se=>e.jsx("a",{href:Se.file_url,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:Se.name},Se.id))})]}),N.videos&&N.videos.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(Wr,{className:"h-4 w-4"}),"Videos (",N.videos.length,")"]}),e.jsx("div",{className:"space-y-2",children:N.videos.map(Se=>e.jsx("div",{className:"p-2 border rounded",children:e.jsx("p",{className:"font-medium text-sm",children:Se.title})},Se.id))})]}),N.links&&N.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(Rc,{className:"h-4 w-4"}),"Canva Links (",N.links.length,")"]}),e.jsx("div",{className:"space-y-1",children:N.links.map(Se=>e.jsx("a",{href:Se.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:Se.title},Se.id))})]})]})]})})]})})}const aGt=[{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 OCn(){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,p]=j.useState(!1),[f,x]=j.useState(""),[y,v]=j.useState(""),[b,N]=j.useState(""),[S,A]=j.useState(""),[T,L]=j.useState("Learn More"),[M,I]=j.useState("top"),[R,z]=j.useState(""),[$,H]=j.useState(!0),[V,K]=j.useState(""),[Z,Q]=j.useState("");j.useEffect(()=>{le()},[]);const le=async()=>{try{const{data:ge,error:ke}=await q.from("dashboard_banners").select("*").order("placement").order("sort_order");if(ke)throw ke;t(ge||[])}catch(ge){re.error("Failed to load banners: "+ge.message)}finally{r(!1)}},ue=()=>{x(""),v(""),N(""),A(""),L("Learn More"),I("top"),z(""),H(!0),K(""),Q(""),d(null)},se=ge=>{d(ge),x(ge.title),v(ge.description||""),N(ge.image_url),A(ge.link_url||""),L(ge.link_text||"Learn More"),I(ge.placement),z(ge.section_after||""),H(ge.is_active),K(ge.start_date?Gs(new Date(ge.start_date),"yyyy-MM-dd'T'HH:mm"):""),Q(ge.end_date?Gs(new Date(ge.end_date),"yyyy-MM-dd'T'HH:mm"):""),i(!0)},ne=async ge=>{var Te;const ke=(Te=ge.target.files)==null?void 0:Te[0];if(ke){h(!0);try{const Me=ke.name.split(".").pop(),Oe=`${Date.now()}.${Me}`,{error:Se}=await q.storage.from("banner-images").upload(Oe,ke);if(Se)throw Se;const{data:{publicUrl:Qe}}=q.storage.from("banner-images").getPublicUrl(Oe);N(Qe),re.success("Image uploaded successfully")}catch(Me){re.error("Failed to upload image: "+Me.message)}finally{h(!1)}}},ie=async()=>{if(!f.trim()||!b){re.error("Please fill in required fields (title and image)");return}p(!0);try{const ge={title:f.trim(),description:y.trim()||null,image_url:b,link_url:S.trim()||null,link_text:T.trim()||"Learn More",placement:M,section_after:M==="between"?R:null,is_active:$,start_date:V?new Date(V).toISOString():null,end_date:Z?new Date(Z).toISOString():null};if(c){const{error:ke}=await q.from("dashboard_banners").update(ge).eq("id",c.id);if(ke)throw ke;re.success("Banner updated successfully")}else{const ke=s.filter(Me=>Me.placement===M).length,{error:Te}=await q.from("dashboard_banners").insert({...ge,sort_order:ke});if(Te)throw Te;re.success("Banner created successfully")}i(!1),ue(),le()}catch(ge){re.error("Failed to save banner: "+ge.message)}finally{p(!1)}},ce=async()=>{if(c)try{const{error:ge}=await q.from("dashboard_banners").delete().eq("id",c.id);if(ge)throw ge;re.success("Banner deleted successfully"),o(!1),d(null),le()}catch(ge){re.error("Failed to delete banner: "+ge.message)}},je=async ge=>{try{const{error:ke}=await q.from("dashboard_banners").update({is_active:!ge.is_active}).eq("id",ge.id);if(ke)throw ke;re.success(ge.is_active?"Banner deactivated":"Banner activated"),le()}catch(ke){re.error("Failed to update banner: "+ke.message)}},be=s.filter(ge=>ge.placement==="top"),he=s.filter(ge=>ge.placement==="between");return n?e.jsx(qs,{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(qs,{title:"Dashboard Management",description:"Configure dashboard modules and banners",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(pc,{className:"h-5 w-5"}),"Hero Banners (Top of Dashboard)"]}),e.jsx(Jn,{children:"These banners appear in a rotating carousel at the top of the dashboard"})]}),e.jsxs(zs,{open:a&&M==="top",onOpenChange:ge=>{ge||ue(),i(ge),ge&&I("top")},children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{onClick:()=>{ue(),I("top")},children:[e.jsx(an,{className:"mr-2 h-4 w-4"}),"Add Hero Banner"]})}),e.jsxs(Ds,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{children:[c?"Edit":"Create"," Banner"]}),e.jsx(Pr,{children:"Configure the banner's content and display settings"})]}),e.jsx(f_t,{title:f,setTitle:x,description:y,setDescription:v,imageUrl:b,linkUrl:S,setLinkUrl:A,linkText:T,setLinkText:L,placement:M,setPlacement:I,sectionAfter:R,setSectionAfter:z,isActive:$,setIsActive:H,startDate:V,setStartDate:K,endDate:Z,setEndDate:Q,handleImageUpload:ne,uploading:u,showPlacementOptions:!1}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>{i(!1),ue()},children:"Cancel"}),e.jsx(U,{onClick:ie,disabled:m,children:m?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Ie,{children:be.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:be.map(ge=>e.jsx(g_t,{banner:ge,onEdit:()=>se(ge),onDelete:()=>{d(ge),o(!0)},onToggleActive:()=>je(ge)},ge.id))})})]}),e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(pc,{className:"h-5 w-5"}),"Section Banners"]}),e.jsx(Jn,{children:"These banners appear between dashboard content sections"})]}),e.jsxs(zs,{open:a&&M==="between",onOpenChange:ge=>{ge||ue(),i(ge),ge&&I("between")},children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{onClick:()=>{ue(),I("between")},children:[e.jsx(an,{className:"mr-2 h-4 w-4"}),"Add Section Banner"]})}),e.jsxs(Ds,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{children:[c?"Edit":"Create"," Section Banner"]}),e.jsx(Pr,{children:"Configure where this banner appears between sections"})]}),e.jsx(f_t,{title:f,setTitle:x,description:y,setDescription:v,imageUrl:b,linkUrl:S,setLinkUrl:A,linkText:T,setLinkText:L,placement:M,setPlacement:I,sectionAfter:R,setSectionAfter:z,isActive:$,setIsActive:H,startDate:V,setStartDate:K,endDate:Z,setEndDate:Q,handleImageUpload:ne,uploading:u,showPlacementOptions:!0}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>{i(!1),ue()},children:"Cancel"}),e.jsx(U,{onClick:ie,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 section banners yet. Add your first banner above."}):e.jsx("div",{className:"space-y-3",children:he.map(ge=>e.jsx(g_t,{banner:ge,onEdit:()=>se(ge),onDelete:()=>{d(ge),o(!0)},onToggleActive:()=>je(ge),showSection:!0},ge.id))})})]})]}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(U,{variant:"destructive",onClick:ce,children:"Delete"})]})]})})]})}function f_t({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:p,setIsActive:f,startDate:x,setStartDate:y,endDate:v,setEndDate:b,handleImageUpload:N,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(te,{htmlFor:"title",children:"Title *"}),e.jsx(xe,{id:"title",placeholder:"Banner headline...",value:s,onChange:T=>t(T.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"description",children:"Description"}),e.jsx(Fs,{id:"description",placeholder:"Optional banner description...",value:n,onChange:T=>r(T.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Banner Image *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(xe,{type:"file",accept:"image/*",onChange:N,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(te,{htmlFor:"linkUrl",children:"Link URL (optional)"}),e.jsx(xe,{id:"linkUrl",placeholder:"https://...",value:i,onChange:T=>l(T.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"linkText",children:"Button Text"}),e.jsx(xe,{id:"linkText",placeholder:"Learn More",value:o,onChange:T=>c(T.target.value)})]})]}),A&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Placement"}),e.jsxs(Ns,{value:h,onValueChange:m,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select section placement..."})}),e.jsx(js,{children:aGt.map(T=>e.jsx(et,{value:T.value,children:T.label},T.value))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"startDate",className:"flex items-center gap-2",children:[e.jsx(pa,{className:"h-4 w-4"}),"Start Date (optional)"]}),e.jsx(xe,{id:"startDate",type:"datetime-local",value:x,onChange:T=>y(T.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"endDate",className:"flex items-center gap-2",children:[e.jsx(pa,{className:"h-4 w-4"}),"End Date (optional)"]}),e.jsx(xe,{id:"endDate",type:"datetime-local",value:v,onChange:T=>b(T.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(wn,{id:"isActive",checked:p,onCheckedChange:f}),e.jsx(te,{htmlFor:"isActive",children:"Active"})]})})]})}function g_t({banner:s,onEdit:t,onDelete:n,onToggleActive:r,showSection:a=!1}){var c;const i=(c=aGt.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(kf,{className:"h-5 w-5 text-muted-foreground cursor-grab"}),e.jsx("img",{src:s.image_url,alt:s.title,className:"w-24 h-14 object-cover rounded"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"font-medium truncate",children:s.title}),!s.is_active&&e.jsx(Be,{variant:"secondary",children:"Inactive"}),s.start_date&&new Date(s.start_date)>new Date&&e.jsx(Be,{variant:"outline",children:"Scheduled"})]}),s.description&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:s.description}),a&&i&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:i})]}),l!==null&&e.jsxs("div",{className:"flex items-center gap-1 text-destructive",title:"Button clicks",children:[e.jsx(Ch,{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(U,{variant:"ghost",size:"icon",children:e.jsx(Sr,{className:"h-4 w-4"})})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:r,children:s.is_active?e.jsx(xa,{className:"h-4 w-4"}):e.jsx(Vg,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:t,children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]})]})}const Lle={open:{label:"Open",icon:Yr,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:vu,color:"bg-blue-500"},resolved:{label:"Resolved",icon:Yo,color:"bg-green-500"},closed:{label:"Closed",icon:ou,color:"bg-muted-foreground"}},x_t={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function FCn(){var M,I;const{user:s}=vs(),t=Qt(),[n,r]=j.useState(null),[a,i]=j.useState(""),[l,o]=j.useState([]),[c,d]=j.useState("all"),[u,h]=j.useState("all"),[m,p]=j.useState(!1),{data:f=[],isLoading:x}=ct({queryKey:["admin-support-tickets",c,u],queryFn:async()=>{let R=q.from("support_tickets").select("*, profiles!support_tickets_user_id_fkey(name, email)").order("created_at",{ascending:!1});c!=="all"&&(R=R.eq("status",c)),u!=="all"&&(R=R.eq("category",u));const{data:z,error:$}=await R;if($)throw $;return z}}),{data:y=[]}=ct({queryKey:["admin-users-notifications"],queryFn:async()=>{const{data:R,error:z}=await q.from("user_roles").select("user_id").eq("role","admin");if(z)throw z;const $=R.map(le=>le.user_id),{data:H,error:V}=await q.from("profiles").select("id, name, email").in("id",$);if(V)throw V;const{data:K,error:Z}=await q.from("support_notification_settings").select("user_id, receive_notifications");if(Z)throw Z;const Q=new Map((K==null?void 0:K.map(le=>[le.user_id,le.receive_notifications]))||[]);return H.map(le=>({...le,receives_notifications:Q.get(le.id)||!1}))}}),{data:v=[]}=ct({queryKey:["admin-ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:R,error:z}=await q.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if(z)throw z;return R},enabled:!!n}),b=yt({mutationFn:async({userId:R,enabled:z})=>{const{data:$}=await q.from("support_notification_settings").select("id").eq("user_id",R).maybeSingle();if($){const{error:H}=await q.from("support_notification_settings").update({receive_notifications:z}).eq("user_id",R);if(H)throw H}else{const{error:H}=await q.from("support_notification_settings").insert({user_id:R,receive_notifications:z});if(H)throw H}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-users-notifications"]}),re.success("Notification settings updated")},onError:()=>{re.error("Failed to update settings")}}),N=yt({mutationFn:async({ticketId:R,status:z})=>{const{error:$}=await q.from("support_tickets").update({status:z}).eq("id",R);if($)throw $},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=yt({mutationFn:async({ticketId:R,assignedTo:z})=>{const{error:$}=await q.from("support_tickets").update({assigned_to:z}).eq("id",R);if($)throw $},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),re.success("Ticket assigned")},onError:()=>{re.error("Failed to assign ticket")}}),A=yt({mutationFn:async({content:R,attachments:z})=>{var H,V;if(!n||!s)throw new Error("Missing data");const{error:$}=await q.from("support_ticket_replies").insert({ticket_id:n.id,user_id:s.id,content:R,is_admin_reply:!0,attachments:z});if($)throw $;try{await q.functions.invoke("support-reply-notify",{body:{ticketId:n.id,ticketSubject:n.subject,replyContent:R,userEmail:(H=n.profiles)==null?void 0:H.email,userName:(V=n.profiles)==null?void 0:V.name}})}catch(K){console.error("Failed to send reply notification:",K)}},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")}}),T=()=>{!a.trim()&&l.length===0||A.mutate({content:a,attachments:l})};j.useEffect(()=>{const R=q.channel("admin-tickets").on("postgres_changes",{event:"*",schema:"public",table:"support_tickets"},()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]})}).subscribe();return()=>{q.removeChannel(R)}},[t]);const L=f.filter(R=>R.status==="open").length;return n?(Lle[n.status].icon,e.jsx(qs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>r(null),children:e.jsx(Aa,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:n.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Be,{variant:"secondary",children:x_t[n.category]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["from ",((M=n.profiles)==null?void 0:M.name)||"Unknown"," (",(I=n.profiles)==null?void 0:I.email,")"]})]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{className:"text-sm",children:"Status"})}),e.jsx(Ie,{children:e.jsxs(Ns,{value:n.status,onValueChange:R=>{N.mutate({ticketId:n.id,status:R}),r({...n,status:R})},children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"open",children:"Open"}),e.jsx(et,{value:"in_progress",children:"In Progress"}),e.jsx(et,{value:"resolved",children:"Resolved"}),e.jsx(et,{value:"closed",children:"Closed"})]})]})})]}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{className:"text-sm",children:"Assigned To"})}),e.jsx(Ie,{children:e.jsxs(Ns,{value:n.assigned_to||"unassigned",onValueChange:R=>{const z=R==="unassigned"?null:R;S.mutate({ticketId:n.id,assignedTo:z}),r({...n,assigned_to:z})},children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Unassigned"})}),e.jsxs(js,{children:[e.jsx(et,{value:"unassigned",children:"Unassigned"}),y.map(R=>e.jsx(et,{value:R.id,children:R.name},R.id))]})]})})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(Jn,{children:["Created on ",Gs(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(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-lg",children:"Conversation"})}),e.jsxs(Ie,{children:[e.jsx(Gi,{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(R=>{var z,$;return e.jsxs("div",{className:`p-4 rounded-lg ${R.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:R.is_admin_reply?`${((z=R.profiles)==null?void 0:z.name)||"Admin"} (Support)`:(($=R.profiles)==null?void 0:$.name)||"User"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Gs(new Date(R.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:R.content}),R.attachments&&R.attachments.length>0&&e.jsx(sqt,{attachments:R.attachments})]},R.id)})})}),e.jsx(hc,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Fs,{placeholder:"Type your reply...",value:a,onChange:R=>i(R.target.value),className:"min-h-[80px]"}),e.jsx(U,{onClick:T,disabled:!a.trim()&&l.length===0||A.isPending,className:"self-end",children:e.jsx($r,{className:"h-4 w-4"})})]}),e.jsx(tqt,{value:l,onChange:o,disabled:A.isPending})]})]})]})]})})):e.jsx(qs,{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",L>0&&e.jsxs(Be,{variant:"destructive",className:"ml-2",children:[L," open"]})]})]}),e.jsxs(zs,{open:m,onOpenChange:p,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{variant:"outline",children:[e.jsx(qc,{className:"h-4 w-4 mr-2"}),"Notification Settings"]})}),e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(R=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(So,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:R.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:R.email})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[R.receives_notifications?e.jsx(bx,{className:"h-4 w-4 text-primary"}):e.jsx(Zk,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(wn,{checked:R.receives_notifications,onCheckedChange:z=>b.mutate({userId:R.id,enabled:z})})]})]},R.id))})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsx(oa,{value:c,onValueChange:d,className:"w-auto",children:e.jsxs(la,{children:[e.jsx(Kt,{value:"all",children:"All"}),e.jsx(Kt,{value:"open",children:"Open"}),e.jsx(Kt,{value:"in_progress",children:"In Progress"}),e.jsx(Kt,{value:"resolved",children:"Resolved"}),e.jsx(Kt,{value:"closed",children:"Closed"})]})}),e.jsxs(Ns,{value:u,onValueChange:h,children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{placeholder:"All Categories"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Categories"}),e.jsx(et,{value:"general",children:"General Support"}),e.jsx(et,{value:"technology",children:"Technology Support"}),e.jsx(et,{value:"crm",children:"CRM Support"}),e.jsx(et,{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..."}):f.length===0?e.jsx(we,{children:e.jsxs(Ie,{className:"text-center py-12",children:[e.jsx(vu,{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:f.map(R=>{var $,H;const z=Lle[R.status].icon;return e.jsx(we,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(R),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:R.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsx(Be,{variant:"outline",className:"text-xs",children:x_t[R.category]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[($=R.profiles)==null?void 0:$.name," • ",Gs(new Date(R.created_at),"MMM d, yyyy")]}),R.assigned_to&&e.jsxs(Be,{variant:"secondary",className:"text-xs gap-1",children:[e.jsx(So,{className:"h-3 w-3"}),((H=y.find(V=>V.id===R.assigned_to))==null?void 0:H.name)||"Assigned"]})]})]}),e.jsxs(Be,{className:Lle[R.status].color,children:[e.jsx(z,{className:"h-3 w-3 mr-1"}),Lle[R.status].label]})]})})},R.id)})})})]})]})})}const iGt=wv.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 zCn({content:s,onChange:t,variables:n}){const r=wPe({extensions:[jPe,kPe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),SPe.configure({types:["heading","paragraph"]}),MJe,iGt],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(U,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleBold().run(),className:r.isActive("bold")?"bg-muted":"",children:e.jsx(wA,{className:"h-4 w-4"})}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleItalic().run(),className:r.isActive("italic")?"bg-muted":"",children:e.jsx(kA,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleBulletList().run(),className:r.isActive("bulletList")?"bg-muted":"",children:e.jsx(m0,{className:"h-4 w-4"})}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleOrderedList().run(),className:r.isActive("orderedList")?"bg-muted":"",children:e.jsx(sj,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("left").run(),className:r.isActive({textAlign:"left"})?"bg-muted":"",children:e.jsx(_M,{className:"h-4 w-4"})}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("center").run(),className:r.isActive({textAlign:"center"})?"bg-muted":"",children:e.jsx(bM,{className:"h-4 w-4"})}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("right").run(),className:r.isActive({textAlign:"right"})?"bg-muted":"",children:e.jsx(wM,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:i,className:r.isActive("link")?"bg-muted":"",children:e.jsx(Rc,{className:"h-4 w-4"})}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleCodeBlock().run(),className:r.isActive("codeBlock")?"bg-muted":"",children:e.jsx(jA,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().undo().run(),disabled:!r.can().undo(),children:e.jsx(RA,{className:"h-4 w-4"})}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().redo().run(),disabled:!r.can().redo(),children:e.jsx(LA,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex-1"}),n.length>0&&e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsxs(U,{type:"button",variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(kq,{className:"h-4 w-4"}),"Insert Variable"]})}),e.jsx(Eu,{align:"end",className:"w-64",children:n.map(l=>e.jsxs(La,{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(_Pe,{editor:r,className:"prose prose-sm max-w-none p-4 min-h-[300px] focus:outline-none [&_.ProseMirror]:outline-none [&_.ProseMirror]:min-h-[280px]"}),n.length>0&&e.jsxs("div",{className:"border-t p-3 bg-muted/20",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Available variables (click to copy):"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(l=>e.jsx(Be,{variant:"secondary",className:"cursor-pointer hover:bg-secondary/80 font-mono text-xs",onClick:()=>{navigator.clipboard.writeText(`{{${l.key}}}`)},children:`{{${l.key}}}`},l.key))})]})]}):null}function BCn(){const s=Qt(),[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),[p,f]=j.useState("visual"),{data:x,isLoading:y}=ct({queryKey:["email-templates"],queryFn:async()=>{const{data:A,error:T}=await q.from("email_templates").select("*").order("name");if(T)throw T;return A.map(L=>({...L,available_variables:L.available_variables||[]}))}}),v=yt({mutationFn:async A=>{const{error:T}=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(T)throw T},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),f("visual")},N=()=>{t&&v.mutate({id:t.id,subject:i,body_html:o,description:d,is_active:h})},S=(A,T)=>{let L=A;return T.forEach(M=>{const I=`{{${M.key}}}`,R=`[${M.label}]`;L=L.replace(new RegExp(I.replace(/[{}]/g,"\\$&"),"g"),R)}),L};return t?e.jsxs(qs,{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(U,{variant:"ghost",onClick:()=>n(null),children:[e.jsx(Aa,{className:"h-4 w-4 mr-2"}),"Back to Templates"]}),e.jsx("div",{className:"flex-1"}),e.jsxs(U,{variant:"outline",onClick:()=>a(t),children:[e.jsx(xa,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(U,{onClick:N,disabled:v.isPending,children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"}),v.isPending?"Saving...":"Save Changes"]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5"}),t.name]}),e.jsxs(Jn,{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(te,{htmlFor:"active-toggle",children:"Active"}),e.jsx(wn,{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(te,{htmlFor:"description",children:"Description"}),e.jsx(Fs,{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(te,{htmlFor:"subject",children:"Email Subject"}),e.jsx(xe,{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(te,{children:"Email Body"}),e.jsx(oa,{value:p,onValueChange:A=>f(A),children:e.jsxs(la,{className:"h-8",children:[e.jsxs(Kt,{value:"visual",className:"text-xs px-3 h-6",children:[e.jsx(X2,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Kt,{value:"html",className:"text-xs px-3 h-6",children:[e.jsx(jA,{className:"h-3 w-3 mr-1"}),"HTML"]})]})})]}),p==="visual"?e.jsx(zCn,{content:o,onChange:c,variables:t.available_variables}):e.jsx(Fs,{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(Ds,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(qs,{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,T)=>e.jsx(we,{children:e.jsxs(Tt,{children:[e.jsx(xn,{className:"h-5 w-48"}),e.jsx(xn,{className:"h-4 w-96"})]})},T))}):e.jsx("div",{className:"grid gap-4",children:x==null?void 0:x.map(A=>e.jsxs(we,{className:"hover:shadow-md transition-shadow",children:[e.jsx(Tt,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(It,{className:"flex items-center gap-2 text-lg",children:[e.jsx(ln,{className:"h-5 w-5 text-muted-foreground"}),A.name,!A.is_active&&e.jsx(Be,{variant:"secondary",children:"Inactive"})]}),e.jsx(Jn,{children:A.description})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>a(A),children:[e.jsx(xa,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(U,{size:"sm",onClick:()=>b(A),children:[e.jsx(sp,{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(T=>e.jsx(Be,{variant:"outline",className:"font-mono text-xs",children:`{{${T.key}}}`},T.key))})]})]})})]},A.id))}),e.jsx(zs,{open:!!r&&!t,onOpenChange:()=>a(null),children:e.jsxs(Ds,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{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 UCn(){const s=Qt(),[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}),[p,f]=j.useState({name:"",description:"",icon:"📧"}),{data:x=[]}=ct({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:R,error:z}=await q.from("email_template_categories").select("*").order("sort_order");if(z)throw z;return R}}),{data:y=[],isLoading:v}=ct({queryKey:["agent-email-templates-admin"],queryFn:async()=>{const{data:R,error:z}=await q.from("agent_email_templates").select("*, category:email_template_categories(*)").order("sort_order");if(z)throw z;return R}}),b=yt({mutationFn:async R=>{const z={title:R.title,subject:R.subject,body:R.body,description:R.description||null,tone:R.tone||null,category_id:R.category_id||null,is_active:R.is_active};if(R.id){const{error:$}=await q.from("agent_email_templates").update(z).eq("id",R.id);if($)throw $}else{const{error:$}=await q.from("agent_email_templates").insert(z);if($)throw $}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),c(!1),re.success(r?"Template updated":"Template created")},onError:()=>re.error("Failed to save template")}),N=yt({mutationFn:async R=>{const{error:z}=await q.from("agent_email_templates").delete().eq("id",R);if(z)throw z},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),re.success("Template deleted")}}),S=yt({mutationFn:async R=>{const z={name:R.name,description:R.description||null,icon:R.icon};if(R.id){const{error:$}=await q.from("email_template_categories").update(z).eq("id",R.id);if($)throw $}else{const $=x.length>0?Math.max(...x.map(V=>V.sort_order))+1:0,{error:H}=await q.from("email_template_categories").insert({...z,sort_order:$});if(H)throw H}},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=yt({mutationFn:async R=>{const{error:z}=await q.from("email_template_categories").delete().eq("id",R);if(z)throw z},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),re.success("Category deleted")}}),T=()=>{a(null),m({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),c(!0)},L=R=>{a(R),m({title:R.title,subject:R.subject,body:R.body,description:R.description||"",tone:R.tone||"",category_id:R.category_id||"",is_active:R.is_active}),c(!0)},M=()=>{l(null),f({name:"",description:"",icon:"📧"}),u(!0)},I=R=>{l(R),f({name:R.name,description:R.description||"",icon:R.icon}),u(!0)};return e.jsx(qs,{children:e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsx(Xh,{title:"Agent Email Templates",description:"Manage email templates that agents use when composing emails from Mission Control."}),e.jsxs(oa,{value:t,onValueChange:n,children:[e.jsxs(la,{children:[e.jsxs(Kt,{value:"templates",className:"gap-2",children:[e.jsx(ln,{className:"h-4 w-4"})," Templates"]}),e.jsxs(Kt,{value:"categories",className:"gap-2",children:[e.jsx(r1,{className:"h-4 w-4"})," Categories"]})]}),e.jsxs(Zt,{value:"templates",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(U,{onClick:T,className:"gap-2",children:[e.jsx(an,{className:"h-4 w-4"})," Add Template"]})}),e.jsx(we,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Template"}),e.jsx(Lt,{className:"hidden md:table-cell",children:"Category"}),e.jsx(Lt,{className:"hidden md:table-cell",children:"Tone"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:v?e.jsx(gn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:e.jsx(Et,{className:"h-6 w-6 animate-spin mx-auto"})})}):y.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No templates yet. Create your first one!"})}):y.map(R=>e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:R.title}),e.jsx("p",{className:"text-xs text-muted-foreground truncate max-w-[300px]",children:R.subject})]})}),e.jsx(gt,{className:"hidden md:table-cell",children:R.category?e.jsxs(Be,{variant:"outline",className:"gap-1",children:[R.category.icon," ",R.category.name]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(gt,{className:"hidden md:table-cell",children:R.tone?e.jsx(Be,{variant:"secondary",children:R.tone}):"—"}),e.jsx(gt,{children:e.jsx(Be,{variant:R.is_active?"default":"secondary",children:R.is_active?"Active":"Inactive"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>L(R),children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",onClick:async()=>{await Yi("Delete this template?")&&N.mutate(R.id)},children:e.jsx(In,{className:"h-4 w-4"})})]})})]},R.id))})]})})})]}),e.jsxs(Zt,{value:"categories",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(U,{onClick:M,className:"gap-2",children:[e.jsx(an,{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(R=>e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx("span",{className:"text-lg",children:R.icon})," ",R.name]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>I(R),children:e.jsx(ri,{className:"h-3.5 w-3.5"})}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:async()=>{await Yi("Delete this category?")&&A.mutate(R.id)},children:e.jsx(In,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Ie,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:R.description||"No description"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[y.filter(z=>z.category_id===R.id).length," templates"]})]})]},R.id))})]})]}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Ds,{className:"sm:max-w-[700px] max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:r?"Edit Template":"New Template"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Title"}),e.jsx(xe,{value:h.title,onChange:R=>m(z=>({...z,title:R.target.value})),placeholder:"e.g. Quick Check-in"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Category"}),e.jsxs(Ns,{value:h.category_id,onValueChange:R=>m(z=>({...z,category_id:R})),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select category"})}),e.jsx(js,{children:x.map(R=>e.jsxs(et,{value:R.id,children:[R.icon," ",R.name]},R.id))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Subject Line"}),e.jsx(xe,{value:h.subject,onChange:R=>m(z=>({...z,subject:R.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(te,{children:"Email Body"}),e.jsx(Fs,{value:h.body,onChange:R=>m(z=>({...z,body:R.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(te,{children:"Description (internal)"}),e.jsx(xe,{value:h.description,onChange:R=>m(z=>({...z,description:R.target.value})),placeholder:"Short description for admin reference"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Tone"}),e.jsx(xe,{value:h.tone,onChange:R=>m(z=>({...z,tone:R.target.value})),placeholder:"e.g. Warm & Casual"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wn,{checked:h.is_active,onCheckedChange:R=>m(z=>({...z,is_active:R}))}),e.jsx(te,{children:"Active"})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(U,{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(Et,{className:"h-4 w-4 mr-2 animate-spin"}),r?"Save Changes":"Create Template"]})]})]})}),e.jsx(zs,{open:d,onOpenChange:u,children:e.jsxs(Ds,{className:"sm:max-w-[450px]",children:[e.jsx(Vs,{children:e.jsx($s,{children:i?"Edit Category":"New Category"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-[60px_1fr] gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Icon"}),e.jsx(xe,{value:p.icon,onChange:R=>f(z=>({...z,icon:R.target.value})),className:"text-center text-lg"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Name"}),e.jsx(xe,{value:p.name,onChange:R=>f(z=>({...z,name:R.target.value})),placeholder:"e.g. Check-in & Stay in Touch"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Description"}),e.jsx(xe,{value:p.description,onChange:R=>f(z=>({...z,description:R.target.value})),placeholder:"Brief description of this category"})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsxs(U,{onClick:()=>S.mutate({...p,id:i==null?void 0:i.id}),disabled:S.isPending||!p.name,children:[S.isPending&&e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),i?"Save Changes":"Create Category"]})]})]})})]})})}const qCn=({brokerageId:s})=>{var ls,Is,ps;const{toast:t}=Ai(),n=Wn(),[r,a]=j.useState([]),[i,l]=j.useState(!0),[o,c]=j.useState(""),[d,u]=j.useState("all"),[h,m]=j.useState(new Set),[p,f]=j.useState(!1),[x,y]=j.useState({}),[v,b]=j.useState(!1),[N,S]=j.useState(!1),[A,T]=j.useState({email:"",name:"",password:"",phone:""}),[L,M]=j.useState(null),[I,R]=j.useState([]),[z,$]=j.useState("none"),[H,V]=j.useState(!1),[K,Z]=j.useState(null),[Q,le]=j.useState(!1),[ue,se]=j.useState(!1),[ne,ie]=j.useState(!1),[ce,je]=j.useState(""),[be,he]=j.useState(!1),[ge,ke]=j.useState([]),[Te,Me]=j.useState(!1),[Oe,Se]=j.useState(!1),[Qe,Ae]=j.useState(null),[Fe,Ne]=j.useState({name:"",phone:"",email:""}),[$e,Ve]=j.useState(!1),[qe,Ze]=j.useState(!1),[Ue,Ye]=j.useState(null),[Ge,He]=j.useState("asc"),[tt,pt]=j.useState(!1),[ft,qt]=j.useState(null),[Ut,Wt]=j.useState(!1),[us,zt]=j.useState(null),[bt,As]=j.useState(""),[vt,Ws]=j.useState(!1),[on,Ms]=j.useState(null);j.useEffect(()=>{br(),rn(),dn()},[s]);const dn=async()=>{try{const{data:Ht}=await q.from("partnership_programs").select("id, name, enabled").eq("brokerage_id",s).maybeSingle();if(!Ht||!Ht.enabled){M(null),R([]);return}const{data:Xs}=await q.from("partnership_packages").select("id, name, description, sort_order").eq("program_id",Ht.id).order("sort_order",{ascending:!0});M({id:Ht.id,name:Ht.name}),R(Xs||[]),Xs&&Xs.length>0&&$(Xs[0].id)}catch(Ht){console.error("Error loading partnership packages:",Ht)}},rn=async()=>{try{const{data:Ht,error:Xs}=await q.from("brokerage_manager_assignments").select("user_id").eq("brokerage_id",s);if(Xs)throw Xs;ke((Ht==null?void 0:Ht.map(Rs=>Rs.user_id))||[])}catch(Ht){console.error("Error loading brokerage managers:",Ht)}},br=async()=>{try{l(!0);const{data:Ht,error:Xs}=await q.functions.invoke("get-brokerage-agents",{body:{brokerageId:s}});if(Xs)throw Xs;const Rs=Ht.agents||[];if(a(Rs),Rs.length>0){const zn=Rs.map(ma=>ma.id),{data:Qr}=await q.from("agent_assistant_assignments").select("agent_id, assistant_id").in("agent_id",zn);if(Qr&&Qr.length>0){const ma=Qr.map(Jr=>Jr.assistant_id),{data:qr}=await q.from("profiles").select("id, name, email").in("id",ma),Zr={};for(const Jr of Qr){const ha=qr==null?void 0:qr.find(Fa=>Fa.id===Jr.assistant_id);ha&&(Zr[Jr.agent_id]={name:ha.name||"",email:ha.email||""})}y(Zr)}else y({})}}catch(Ht){console.error("Error loading agents:",Ht),t({title:"Error",description:"Failed to load agents",variant:"destructive"})}finally{l(!1)}},Gn=async()=>{var Ht;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:Xs}}=await q.auth.getSession(),Rs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Xs==null?void 0:Xs.access_token}`},body:JSON.stringify({...A,brokerageId:s,partnershipPackageId:L&&z!=="none"?z:void 0})}),zn=await Rs.json();if(!Rs.ok)throw new Error(zn.error||"Failed to create agent");t({title:"Success",description:`Agent ${A.email} created successfully`}),T({email:"",name:"",password:"",phone:""}),$(((Ht=I[0])==null?void 0:Ht.id)||"none"),b(!1),br()}catch(Xs){console.error("Error creating agent:",Xs),t({title:"Error",description:Xs.message||"Failed to create agent",variant:"destructive"})}finally{S(!1)}},On=async Ht=>{try{const{data:{session:Xs}}=await q.auth.getSession(),Rs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Xs==null?void 0:Xs.access_token}`},body:JSON.stringify({userId:Ht})}),zn=await Rs.json();if(!Rs.ok)throw new Error(zn.error||"Failed to resend welcome email");t({title:"Success",description:"Welcome email sent successfully"})}catch(Xs){console.error("Error resending welcome email:",Xs),t({title:"Error",description:Xs.message||"Failed to resend welcome email",variant:"destructive"})}},Rr=async(Ht,Xs)=>{try{const{error:Rs}=await q.functions.invoke("send-password-reset",{body:{email:Ht,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(Rs)throw Rs;t({title:"Password Reset Sent",description:`Password reset email sent to ${Xs}`})}catch(Rs){console.error("Error sending password reset:",Rs),t({title:"Error",description:Rs.message||"Failed to send password reset email",variant:"destructive"})}},cr=Ht=>{Z(Ht),V(!0)},Hs=Ht=>{Ae(Ht),Ne({name:Ht.name,phone:Ht.phone||"",email:Ht.email}),Se(!0)},_r=async()=>{if(!Qe)return;if(!Fe.name.trim()){t({title:"Error",description:"Name is required",variant:"destructive"});return}const Ht=Fe.email.trim().toLowerCase()!==Qe.email.toLowerCase();Ve(!0);try{if(Ht){if(!Fe.email.trim())throw new Error("Email is required");Ze(!0);const{data:{session:Rs}}=await q.auth.getSession(),zn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Rs==null?void 0:Rs.access_token}`},body:JSON.stringify({agentId:Qe.id,newEmail:Fe.email.trim(),brokerageId:s})}),Qr=await zn.json();if(Ze(!1),!zn.ok)throw new Error(Qr.error||"Failed to update email")}const{error:Xs}=await q.from("profiles").update({name:Fe.name.trim(),phone:Fe.phone.trim()||null}).eq("id",Qe.id);if(Xs)throw Xs;t({title:"Success",description:"Agent profile updated successfully"}),Se(!1),Ae(null),br()}catch(Xs){console.error("Error updating agent:",Xs),t({title:"Error",description:Xs.message||"Failed to update agent",variant:"destructive"})}finally{Ve(!1),Ze(!1)}},nn=async()=>{if(!ce){t({title:"Error",description:"Please select an agent to promote",variant:"destructive"});return}he(!0);try{const{data:{session:Ht}}=await q.auth.getSession(),Xs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ht==null?void 0:Ht.access_token}`},body:JSON.stringify({userId:ce,role:"brokerage_manager",action:"add",brokerageId:s})}),Rs=await Xs.json();if(!Xs.ok)throw new Error(Rs.error||"Failed to add brokerage manager");t({title:"Success",description:"Brokerage manager added successfully"}),ie(!1),je(""),rn()}catch(Ht){console.error("Error adding brokerage manager:",Ht),t({title:"Error",description:Ht.message||"Failed to add brokerage manager",variant:"destructive"})}finally{he(!1)}},Zn=async Ht=>{try{const{data:{session:Xs}}=await q.auth.getSession(),Rs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Xs==null?void 0:Xs.access_token}`},body:JSON.stringify({userId:Ht,role:"brokerage_manager",action:"remove",brokerageId:s})}),zn=await Rs.json();if(!Rs.ok)throw new Error(zn.error||"Failed to remove brokerage manager");t({title:"Success",description:"Brokerage manager role removed"}),rn()}catch(Xs){console.error("Error removing brokerage manager:",Xs),t({title:"Error",description:Xs.message||"Failed to remove brokerage manager",variant:"destructive"})}},es=Ht=>ge.includes(Ht),ar=Ht=>{zt(Ht),As(""),Wt(!0)},Hn=async()=>{if(!(!us||!bt)){if(bt.length<6){t({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}Ws(!0);try{const{data:{session:Ht}}=await q.auth.getSession(),Xs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ht==null?void 0:Ht.access_token}`},body:JSON.stringify({agentId:us.id,brokerageId:s,action:"set_password",newPassword:bt})}),Rs=await Xs.json();if(!Xs.ok)throw new Error(Rs.error||"Failed to set password");t({title:"Success",description:`Password set for ${us.name}`}),Wt(!1),zt(null),As("")}catch(Ht){console.error("Error setting password:",Ht),t({title:"Error",description:Ht.message||"Failed to set password",variant:"destructive"})}finally{Ws(!1)}}},kn=async Ht=>{Ms(Ht.id);try{const{data:{session:Xs}}=await q.auth.getSession(),Rs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Xs==null?void 0:Xs.access_token}`},body:JSON.stringify({agentId:Ht.id,brokerageId:s,action:"claim_account"})}),zn=await Rs.json();if(!Rs.ok)throw new Error(zn.error||"Failed to claim account");t({title:"Success",description:`Account claimed for ${Ht.name}`}),br()}catch(Xs){console.error("Error claiming account:",Xs),t({title:"Error",description:Xs.message||"Failed to claim account",variant:"destructive"})}finally{Ms(null)}},Un=async()=>{if(K){le(!0);try{const{data:{session:Ht}}=await q.auth.getSession(),Xs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/remove-agent",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ht==null?void 0:Ht.access_token}`},body:JSON.stringify({userId:K.id,brokerageId:s})}),Rs=await Xs.json();if(!Xs.ok)throw new Error(Rs.error||"Failed to remove agent");t({title:"Success",description:`${K.name} has been removed from your brokerage`}),V(!1),Z(null),br()}catch(Ht){console.error("Error removing agent:",Ht),t({title:"Error",description:Ht.message||"Failed to remove agent",variant:"destructive"})}finally{le(!1)}}},sn=Ht=>{const Xs=Ht.trim().split(" ");return Xs.length>1?Xs[Xs.length-1].toLowerCase():Ht.toLowerCase()},un=Ht=>{Ue===Ht?He(Ge==="asc"?"desc":"asc"):(Ye(Ht),He("asc"))},Ar=Ht=>Ue!==Ht?e.jsx(xx,{className:"ml-1 h-4 w-4"}):Ge==="asc"?e.jsx(cp,{className:"ml-1 h-4 w-4"}):e.jsx(ag,{className:"ml-1 h-4 w-4"}),fs=r.filter(Ht=>{if(d==="active"&&!Ht.claimed||d==="pending"&&Ht.claimed)return!1;if(!o)return!0;const Xs=o.toLowerCase();return Ht.name.toLowerCase().includes(Xs)||Ht.email.toLowerCase().includes(Xs)}),ot=[...fs].sort((Ht,Xs)=>{if(!Ue)return 0;let Rs=0;return Ue==="name"?Rs=sn(Ht.name).localeCompare(sn(Xs.name)):Ue==="status"&&(Rs=Ht.claimed===Xs.claimed?0:Ht.claimed?-1:1),Ge==="asc"?Rs:-Rs});fs.filter(Ht=>Ht.claimed&&!es(Ht.id));const mt=Ht=>{m(Xs=>{const Rs=new Set(Xs);return Rs.has(Ht)?Rs.delete(Ht):Rs.add(Ht),Rs})},Nt=()=>{h.size===ot.length?m(new Set):m(new Set(ot.map(Ht=>Ht.id)))},Pt=()=>{m(new Set)},ts=async()=>{const Ht=Array.from(h);if(Ht.length===0)return;f(!0);let Xs=0,Rs=0;try{const{data:{session:zn}}=await q.auth.getSession();for(const Qr of Ht)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${zn==null?void 0:zn.access_token}`},body:JSON.stringify({userId:Qr})})).ok?Xs++:Rs++}catch{Rs++}Xs>0?t({title:"Success",description:`Welcome emails sent to ${Xs} agent${Xs>1?"s":""}${Rs>0?` (${Rs} failed)`:""}`}):t({title:"Error",description:"Failed to send welcome emails",variant:"destructive"}),Pt()}catch(zn){console.error("Error bulk sending welcome emails:",zn),t({title:"Error",description:zn.message||"Failed to send welcome emails",variant:"destructive"})}finally{f(!1)}};return i?e.jsx(we,{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(we,{children:[e.jsx(Tt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Agents"}),e.jsx(Jn,{children:"Manage your brokerage's agents"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(U,{variant:"outline",onClick:()=>ie(!0),children:[e.jsx(Im,{className:"mr-2 h-4 w-4"}),"Add Brokerage Manager"]}),e.jsxs(U,{variant:"outline",onClick:()=>se(!0),children:[e.jsx(Qk,{className:"mr-2 h-4 w-4"}),"Import CSV"]}),e.jsxs(U,{onClick:()=>b(!0),children:[e.jsx(zl,{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(Fr,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search agents...",value:o,onChange:Ht=>c(Ht.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:d,onValueChange:Ht=>u(Ht),children:[e.jsx(ws,{className:"w-[160px]",children:e.jsx(ks,{placeholder:"Filter by status"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Agents"}),e.jsx(et,{value:"active",children:"Active"}),e.jsx(et,{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(U,{size:"sm",variant:"outline",onClick:()=>{const Xs=r.filter(Rs=>h.has(Rs.id)&&Rs.email).map(Rs=>({email:Rs.email,name:Rs.name}));sessionStorage.setItem("campaign_direct_recipients",JSON.stringify(Xs)),n("/admin/email-campaigns/new?directMode=1",{state:{directRecipients:Xs}})},disabled:p,children:[e.jsx(Th,{className:"mr-2 h-4 w-4"}),"Email Agents (",h.size,")"]}),e.jsxs(U,{size:"sm",variant:"outline",onClick:ts,disabled:p,children:[e.jsx(ln,{className:"mr-2 h-4 w-4"}),p?"Sending...":"Resend Welcome Email"]}),e.jsx(U,{size:"sm",variant:"ghost",onClick:Pt,children:"Clear"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{className:"w-[40px]",children:e.jsx(xi,{checked:ot.length>0&&h.size===ot.length,onCheckedChange:Nt,"aria-label":"Select all"})}),e.jsx(Lt,{children:e.jsxs(U,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>un("name"),children:["Name (Last)",Ar("name")]})}),e.jsx(Lt,{children:"Email"}),e.jsx(Lt,{children:e.jsxs(U,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>un("status"),children:["Status",Ar("status")]})}),e.jsx(Lt,{children:"Actions"})]})}),e.jsx(Xa,{children:ot.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:5,className:"text-center text-muted-foreground",children:"No agents found"})}):ot.map(Ht=>e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsx(xi,{checked:h.has(Ht.id),onCheckedChange:()=>mt(Ht.id),"aria-label":`Select ${Ht.name}`})}),e.jsx(gt,{className:"font-medium",children:Ht.name}),e.jsx(gt,{children:Ht.email}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[Ht.claimed?e.jsx(Be,{variant:"default",children:"Active"}):e.jsx(Be,{variant:"secondary",children:"Pending"}),es(Ht.id)&&e.jsxs(Be,{variant:"outline",className:"border-primary text-primary",children:[e.jsx(cg,{className:"mr-1 h-3 w-3"}),"Manager"]}),x[Ht.id]&&e.jsxs(Be,{variant:"outline",className:"text-xs",children:[e.jsx(Bn,{className:"mr-1 h-3 w-3"}),"Asst: ",x[Ht.id].name||x[Ht.id].email]})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>{qt(Ht),pt(!0)},title:"Send celebration",className:"text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",children:e.jsx(Wg,{className:"h-4 w-4"})}),e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>Hs(Ht),title:"Edit agent",children:e.jsx(ri,{className:"h-4 w-4"})}),!Ht.claimed&&e.jsxs(e.Fragment,{children:[e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>On(Ht.id),title:"Resend welcome email",children:e.jsx(ln,{className:"h-4 w-4"})}),e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>kn(Ht),title:"Claim account for agent",disabled:on===Ht.id,className:"text-green-600 hover:text-green-700 hover:bg-green-50",children:e.jsx(tN,{className:"h-4 w-4"})})]}),e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>ar(Ht),title:"Set password",className:"text-blue-600 hover:text-blue-700 hover:bg-blue-50",children:e.jsx(Ql,{className:"h-4 w-4"})}),e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>Rr(Ht.email,Ht.name),title:"Send password reset email",children:e.jsx(SA,{className:"h-4 w-4"})}),es(Ht.id)&&e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>Zn(Ht.id),title:"Remove manager role",className:"text-orange-500 hover:text-orange-600",children:e.jsx(Im,{className:"h-4 w-4"})}),e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>cr(Ht),className:"text-destructive hover:text-destructive",title:"Remove agent",children:e.jsx(In,{className:"h-4 w-4"})})]})})]},Ht.id))})]})})]})]}),e.jsx(zs,{open:v,onOpenChange:b,children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{htmlFor:"name",children:"Name"}),e.jsx(xe,{id:"name",value:A.name,onChange:Ht=>T({...A,name:Ht.target.value}),placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"email",children:"Email"}),e.jsx(xe,{id:"email",type:"email",value:A.email,onChange:Ht=>T({...A,email:Ht.target.value}),placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(xe,{id:"phone",type:"tel",value:A.phone,onChange:Ht=>T({...A,phone:Ht.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"password",children:"Temporary Password"}),e.jsx(xe,{id:"password",type:"password",value:A.password,onChange:Ht=>T({...A,password:Ht.target.value}),placeholder:"Temporary password"})]}),L&&I.length>0&&e.jsxs("div",{children:[e.jsxs(te,{htmlFor:"package",children:[L.name," Package"]}),e.jsxs(Ns,{value:z,onValueChange:$,children:[e.jsx(ws,{id:"package",children:e.jsx(ks,{placeholder:"Choose a package"})}),e.jsxs(js,{children:[I.map(Ht=>e.jsx(et,{value:Ht.id,children:Ht.name},Ht.id)),e.jsx(et,{value:"none",children:"No package (full access)"})]})]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:z==="none"?"Agent gets unrestricted LevelUp access.":((ls=I.find(Ht=>Ht.id===z))==null?void 0:ls.description)||"Their welcome email will list what is included in this package."})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx(U,{onClick:Gn,disabled:N,children:N?"Creating...":"Create Agent"})]})]})}),e.jsx(zs,{open:H,onOpenChange:V,children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Remove Agent"}),e.jsxs(Pr,{children:["Are you sure you want to remove ",e.jsx("strong",{children:K==null?void 0:K.name})," from your brokerage? This will revoke their access to the dashboard."]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>V(!1),children:"Cancel"}),e.jsx(U,{variant:"destructive",onClick:Un,disabled:Q,children:Q?"Removing...":"Remove Agent"})]})]})}),e.jsx(nqt,{open:ue,onOpenChange:se,fixedBrokerageId:s,onSuccess:br}),e.jsx(zs,{open:ne,onOpenChange:ie,children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{children:"Select Agent"}),e.jsxs(md,{open:Te,onOpenChange:Me,children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{variant:"outline",role:"combobox","aria-expanded":Te,className:"w-full justify-between",children:[ce?((Is=r.find(Ht=>Ht.id===ce))==null?void 0:Is.name)+" ("+((ps=r.find(Ht=>Ht.id===ce))==null?void 0:ps.email)+")":"Select an agent to promote...",e.jsx(Jw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(id,{className:"w-full p-0",align:"start",children:e.jsxs(pj,{children:[e.jsx(fj,{placeholder:"Search by name or email..."}),e.jsxs(gj,{className:"max-h-[200px]",children:[e.jsx(xj,{children:"No eligible agents found."}),e.jsx(I_,{children:r.filter(Ht=>!es(Ht.id)).map(Ht=>e.jsxs(e1,{value:`${Ht.name} ${Ht.email}`,onSelect:()=>{je(Ht.id),Me(!1)},children:[e.jsx(Xr,{className:`mr-2 h-4 w-4 ${ce===Ht.id?"opacity-100":"opacity-0"}`}),Ht.name," (",Ht.email,")"]},Ht.id))})]})]})})]}),r.filter(Ht=>!es(Ht.id)).length===0&&e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"All agents are already brokerage managers."})]})}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>ie(!1),children:"Cancel"}),e.jsx(U,{onClick:nn,disabled:be||!ce,children:be?"Adding...":"Add as Manager"})]})]})}),e.jsx(zs,{open:Oe,onOpenChange:Se,children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Edit Agent"}),e.jsxs(Pr,{children:["Update profile information for ",Qe==null?void 0:Qe.name]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{htmlFor:"edit-name",children:"Name"}),e.jsx(xe,{id:"edit-name",value:Fe.name,onChange:Ht=>Ne({...Fe,name:Ht.target.value}),placeholder:"Agent name"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"edit-email",children:"Email"}),e.jsx(xe,{id:"edit-email",type:"email",value:Fe.email,onChange:Ht=>Ne({...Fe,email:Ht.target.value}),placeholder:"agent@example.com"}),Fe.email.trim().toLowerCase()!==(Qe==null?void 0:Qe.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(te,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(xe,{id:"edit-phone",type:"tel",value:Fe.phone,onChange:Ht=>Ne({...Fe,phone:Ht.target.value}),placeholder:"555-123-4567"})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>Se(!1),children:"Cancel"}),e.jsx(U,{onClick:_r,disabled:$e||qe,children:qe?"Updating email...":$e?"Saving...":"Save Changes"})]})]})}),ft&&e.jsx(rqt,{open:tt,onOpenChange:Ht=>{pt(Ht),Ht||qt(null)},userId:ft.id,userName:ft.name}),e.jsx(zs,{open:Ut,onOpenChange:Wt,children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Set Password"}),e.jsxs(Pr,{children:["Set a new password for ",us==null?void 0:us.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(te,{htmlFor:"new-password",children:"New Password"}),e.jsx(xe,{id:"new-password",type:"password",value:bt,onChange:Ht=>As(Ht.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(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>Wt(!1),children:"Cancel"}),e.jsx(U,{onClick:Hn,disabled:vt||!bt||bt.length<6,children:vt?"Setting...":"Set Password"})]})]})})]})},$Cn={academy_video:"Academy Video",template:"Template",toolbox:"Toolbox Resource",newsletter:"Newsletter",social_swag:"Social Swag",event:"Event"},VCn={view:"Viewed",click_canva:"Opened Canva",click_pdf:"Downloaded PDF",click_video:"Watched Video",click_link:"Clicked Link",register:"Registered"},HCn=s=>{switch(s){case"academy_video":return e.jsx(Wr,{className:"h-4 w-4"});case"template":return e.jsx(Ur,{className:"h-4 w-4"});case"toolbox":return e.jsx(Ur,{className:"h-4 w-4"});case"newsletter":return e.jsx(Q2,{className:"h-4 w-4"});case"social_swag":return e.jsx(cn,{className:"h-4 w-4"});case"event":return e.jsx(pa,{className:"h-4 w-4"});default:return e.jsx(Sr,{className:"h-4 w-4"})}},GCn=({brokerageId:s})=>{const{toast:t}=Ai(),[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(z=>z.id),b=new Map(x.map(z=>[z.id,z]));if(v.length===0){r([]),i([]),o([]);return}const{data:N,error:S}=await q.from("activity_logs").select("*").in("user_id",v).order("launched_at",{ascending:!1});if(S)throw S;const A=N.map(z=>{var $,H;return{id:z.id,user_id:z.user_id,app_name:z.app_name,launched_at:z.launched_at,user_name:(($=b.get(z.user_id))==null?void 0:$.name)||"Unknown",user_email:((H=b.get(z.user_id))==null?void 0:H.email)||"Unknown"}});r(A);const{data:T,error:L}=await q.from("content_engagement_logs").select("*").in("user_id",v).order("created_at",{ascending:!1});if(L)throw L;const M=(T||[]).map(z=>{var $,H;return{id:z.id,user_id:z.user_id,resource_type:z.resource_type,resource_id:z.resource_id,resource_title:z.resource_title,action_type:z.action_type,created_at:z.created_at,user_name:(($=b.get(z.user_id))==null?void 0:$.name)||"Unknown",user_email:((H=b.get(z.user_id))==null?void 0:H.email)||"Unknown"}});i(M);const I=new Map;x.forEach(z=>{I.set(z.id,{user_id:z.id,user_name:z.name,user_email:z.email,app_launches:0,content_views:0,last_activity:""})}),A.forEach(z=>{const $=I.get(z.user_id);$&&($.app_launches++,(!$.last_activity||new Date(z.launched_at)>new Date($.last_activity))&&($.last_activity=z.launched_at))}),M.forEach(z=>{const $=I.get(z.user_id);$&&($.content_views++,(!$.last_activity||new Date(z.created_at)>new Date($.last_activity))&&($.last_activity=z.created_at))});const R=Array.from(I.values()).filter(z=>z.app_launches>0||z.content_views>0).sort((z,$)=>new Date($.last_activity).getTime()-new Date(z.last_activity).getTime());o(R)}catch(x){console.error("Error loading activity:",x),t({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{d(!1)}},p=x=>n.filter(y=>y.user_id===x),f=x=>a.filter(y=>y.user_id===x);return c?e.jsx(we,{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(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"Agent Activity"}),e.jsx(Jn,{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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Agent"}),e.jsx(Lt,{className:"text-center",children:"App Launches"}),e.jsx(Lt,{className:"text-center",children:"Content Views"}),e.jsx(Lt,{children:"Last Active"})]})}),e.jsx(Xa,{children:l.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:4,className:"text-center text-muted-foreground",children:"No activity yet"})}):l.map(x=>e.jsxs(gn,{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(gt,{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(gt,{className:"text-center",children:e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(lu,{className:"h-3 w-3"}),x.app_launches]})}),e.jsx(gt,{className:"text-center",children:e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Ur,{className:"h-3 w-3"}),x.content_views]})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:x.last_activity&&Nd(new Date(x.last_activity),{addSuffix:!0})})]},x.user_id))})]})})})]}),e.jsx(zs,{open:!!u,onOpenChange:x=>!x&&h(null),children:e.jsxs(Ds,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(Vs,{children:[e.jsxs($s,{children:[u==null?void 0:u.name,"'s Activity"]}),e.jsx(Pr,{children:u==null?void 0:u.email})]}),e.jsxs(oa,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(la,{className:"grid w-full grid-cols-2",children:[e.jsx(Kt,{value:"content",children:"Content Engagement"}),e.jsx(Kt,{value:"apps",children:"App Launches"})]}),e.jsx(Zt,{value:"content",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Resource"}),e.jsx(Lt,{children:"Type"}),e.jsx(Lt,{children:"Action"}),e.jsx(Lt,{children:"Time"})]})}),e.jsx(Xa,{children:u&&f(u.id).length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement yet"})}):u&&f(u.id).map(x=>e.jsxs(gn,{children:[e.jsx(gt,{className:"max-w-[200px] truncate font-medium",children:x.resource_title}),e.jsx(gt,{children:e.jsxs(Be,{variant:"outline",className:"gap-1",children:[HCn(x.resource_type),$Cn[x.resource_type]||x.resource_type]})}),e.jsx(gt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:VCn[x.action_type]||x.action_type})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Nd(new Date(x.created_at),{addSuffix:!0})})]},x.id))})]})})}),e.jsx(Zt,{value:"apps",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"App"}),e.jsx(Lt,{children:"Time"})]})}),e.jsx(Xa,{children:u&&p(u.id).length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches yet"})}):u&&p(u.id).map(x=>e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsx(Be,{variant:"outline",children:x.app_name})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Nd(new Date(x.launched_at),{addSuffix:!0})})]},x.id))})]})})})]})]})})]})},WCn=({brokerageId:s})=>{const{toast:t}=Ai(),[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:p}=await q.from("profiles").select("*",{count:"exact",head:!0}).eq("brokerage_id",s).not("last_login","is",null),f=p||0,x=u-f,{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()),N=new Date;N.setMonth(N.getMonth()-1);const{count:S}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",N.toISOString());r({totalAgents:u,activeAgents:f,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(we,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Total Agents"}),e.jsx(Bn,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Active Agents"}),e.jsx(Yo,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(Yr,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(Lm,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"This Week"}),e.jsx(Lm,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"This Month"}),e.jsx(Lm,{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"})]})]})]})},KCn=({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(),p=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)}},f=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(N=>N.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:N}=await q.from("invite_codes").update({is_active:!b}).eq("id",v);if(N)throw N;n(t.map(S=>S.id===v?{...S,is_active:!b}:S)),re.success(`Invite link ${b?"deactivated":"activated"}`)}catch(N){console.error("Error toggling invite code:",N),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(we,{children:e.jsx(Ie,{className:"flex items-center justify-center py-8",children:e.jsx(Et,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Rc,{className:"h-5 w-5"}),"Agent Invite Links"]}),e.jsx(Jn,{children:"Create shareable links for agents to join your brokerage"})]}),e.jsxs(zs,{open:o,onOpenChange:c,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{size:"sm",children:[e.jsx(an,{className:"mr-2 h-4 w-4"}),"Create Link"]})}),e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{htmlFor:"description",children:"Description (optional)"}),e.jsx(xe,{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(te,{htmlFor:"maxUses",children:"Max Uses (optional)"}),e.jsx(xe,{id:"maxUses",type:"number",placeholder:"Leave empty for unlimited",value:d.maxUses,onChange:v=>u({...d,maxUses:v.target.value})})]}),e.jsx(U,{onClick:p,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(Et,{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(Rc,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No invite links yet"}),e.jsx("p",{className:"text-sm",children:"Create one to start inviting agents"})]}):e.jsx("div",{className:"space-y-3",children:t.map(v=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"text-sm font-mono bg-muted px-2 py-0.5 rounded",children:v.code}),e.jsx(Be,{variant:v.is_active?"default":"secondary",children:v.is_active?"Active":"Inactive"})]}),v.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:v.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[v.uses_count," uses",v.max_uses&&` / ${v.max_uses} max`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>y(v.code),title:"Copy link",children:e.jsx(Pa,{className:"h-4 w-4"})}),e.jsx(U,{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(U,{variant:"ghost",size:"sm",onClick:()=>f(v.id),className:"text-destructive hover:text-destructive",title:"Delete",children:e.jsx(In,{className:"h-4 w-4"})})]})]},v.id))})})]})},YCn=({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(""),[p,f]=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())},N=async()=>{if(d.length===0){re.error("Please add at least one email address");return}f(!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{f(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"sm:max-w-[550px]",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(ln,{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(Ro,{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(te,{htmlFor:"email",children:"Email Addresses (up to 10)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{id:"email",type:"email",placeholder:"Enter email and press Enter",value:o,onChange:S=>c(S.target.value),onKeyDown:b,onBlur:y}),e.jsx(U,{type:"button",variant:"secondary",onClick:y,children:"Add"})]}),d.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:d.map(S=>e.jsxs(Be,{variant:"secondary",className:"flex items-center gap-1 pr-1",children:[S,e.jsx("button",{type:"button",onClick:()=>v(S),className:"ml-1 rounded-full p-0.5 hover:bg-muted",children:e.jsx(er,{className:"h-3 w-3"})})]},S))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"message",children:"Personal Message (optional)"}),e.jsx(Fs,{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(cn,{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(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(U,{onClick:N,disabled:d.length===0||p,children:p?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($r,{className:"h-4 w-4 mr-2"}),"Send ",d.length>0&&`(${d.length})`," Invite",d.length!==1?"s":""]})})]})]})})},ZCn=({brokerageId:s,refreshTrigger:t})=>{const[n,r]=j.useState([]),[a,i]=j.useState(!0);j.useEffect(()=>{l()},[s,t]);const l=async()=>{try{const{data:c,error:d}=await q.from("referral_invites").select("*").eq("referrer_brokerage_id",s).order("sent_at",{ascending:!1}).limit(20);if(d)throw d;r(c||[])}catch(c){console.error("Error fetching invites:",c)}finally{i(!1)}},o=c=>{switch(c){case"signed_up":return e.jsxs(Be,{className:"bg-green-100 text-green-800 gap-1",children:[e.jsx(Yo,{className:"h-3 w-3"}),"Signed Up"]});case"expired":return e.jsxs(Be,{variant:"outline",className:"text-muted-foreground gap-1",children:[e.jsx(ou,{className:"h-3 w-3"}),"Expired"]});default:return e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Yr,{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(ln,{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 ",Gs(new Date(c.sent_at),"MMM d, yyyy")]})]}),o(c.status)]},c.id))]})},XCn=()=>{const{brokerageId:s,user:t}=vs(),[n,r]=j.useState(null),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState([]),[u,h]=j.useState(!0),[m,p]=j.useState(!1),[f,x]=j.useState(0);j.useEffect(()=>{s&&y()},[s]);const y=async()=>{try{const[T,L]=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})]);T.data&&i(T.data.name),L.data&&o(L.data.name||"A LevelUp Member");const{data:M}=await q.from("referral_codes").select("code").eq("brokerage_id",s).single();if(M)r(M.code);else{const R=`REF${s==null?void 0:s.slice(0,8).toUpperCase()}`;await q.from("referral_codes").insert({brokerage_id:s,code:R}),r(R)}const{data:I}=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(I||[])}catch(T){console.error("Error fetching referral data:",T)}finally{h(!1)}},v=()=>{const T=`https://dashboard.relevelup.com/?ref=${n}`;navigator.clipboard.writeText(T),re.success("Referral link copied to clipboard!")},b=c.filter(T=>T.status==="qualified").length,N=c.filter(T=>T.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(we,{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(Ro,{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(Yo,{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(cn,{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(U,{onClick:()=>p(!0),className:"w-full",size:"lg",children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Invite Broker Friends"]}),e.jsxs(U,{onClick:v,variant:"outline",className:"w-full",size:"lg",children:[e.jsx(Pa,{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(yu,{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(Bn,{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(Yr,{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:N}),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(ZCn,{brokerageId:s,refreshTrigger:f}),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(T=>{var L,M;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:((L=T.referred_brokerage)==null?void 0:L.name)||((M=T.referred_user)==null?void 0:M.email)||"Pending setup"}),e.jsxs(Be,{variant:T.status==="qualified"?"default":T.status==="pending"?"secondary":"destructive",className:T.status==="qualified"?"bg-green-600":"",children:[T.status==="qualified"&&e.jsx(Yo,{className:"h-3 w-3 mr-1"}),T.status]})]},T.id)})]})]})]}),e.jsx(YCn,{open:m,onOpenChange:p,referralCode:n||"",brokerageId:s||"",senderName:l||"A LevelUp Member",brokerageName:a,onInvitesSent:()=>x(T=>T+1)})]})},QCn=({brokerageId:s})=>{const t=Wn(),{teams:n,isLoading:r}=_E(s),{data:a,isLoading:i}=ct({queryKey:["team-aggregate-stats",s,n.map(u=>u.id)],queryFn:async()=>{if(n.length===0)return[];const u=n.map(T=>T.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(T=>({team_id:T.id,team_name:T.name,member_count:0,leader_name:null,leader_avatar:null,total_contacts:0,total_deals:0,total_videos:0}));const m=h.map(T=>T.user_id),p=h.filter(T=>T.role==="team_leader").map(T=>T.user_id),{data:f}=await q.from("profiles").select("id, name, avatar_url").in("id",p),x=new Map((f||[]).map(T=>[T.id,T])),{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),N=new Map;(y||[]).forEach(T=>{N.set(T.owner_user_id,(N.get(T.owner_user_id)||0)+1)});const S=new Map;(v||[]).forEach(T=>{S.set(T.owner_user_id,(S.get(T.owner_user_id)||0)+1)});const A=new Map;return(b||[]).forEach(T=>{A.set(T.owner_user_id,(A.get(T.owner_user_id)||0)+1)}),n.map(T=>{const L=h.filter(V=>V.team_id===T.id),M=L.find(V=>V.role==="team_leader"),I=M?x.get(M.user_id):null,R=L.map(V=>V.user_id),z=R.reduce((V,K)=>V+(N.get(K)||0),0),$=R.reduce((V,K)=>V+(S.get(K)||0),0),H=R.reduce((V,K)=>V+(A.get(K)||0),0);return{team_id:T.id,team_name:T.name,member_count:L.length,leader_name:(I==null?void 0:I.name)||null,leader_avatar:(I==null?void 0:I.avatar_url)||null,total_contacts:z,total_deals:$,total_videos:H}})},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(we,{children:[e.jsx(Tt,{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(we,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Bn,{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(U,{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(we,{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(Bn,{className:"h-4 w-4"})," Teams"]}),e.jsx("p",{className:"text-2xl font-bold",children:n.length})]})}),e.jsx(we,{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(Bn,{className:"h-4 w-4"})," Total Members"]}),e.jsx("p",{className:"text-2xl font-bold",children:o})]})}),e.jsx(we,{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(SF,{className:"h-4 w-4"})," Total Contacts"]}),e.jsx("p",{className:"text-2xl font-bold",children:c.toLocaleString()})]})}),e.jsx(we,{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(og,{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(we,{className:"hover:shadow-md transition-shadow",children:[e.jsxs(Tt,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(It,{className:"text-lg",children:u.team_name}),e.jsxs(Be,{variant:"secondary",children:[u.member_count," members"]})]}),u.leader_name&&e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsxs(Ea,{className:"h-6 w-6",children:[e.jsx(Ci,{src:u.leader_avatar||""}),e.jsx(Ta,{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(h0,{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(U,{variant:"outline",onClick:()=>t("/brokerage/teams"),children:"Manage Teams →"})})]})},JCn=()=>{const{user:s,isBrokerageManager:t,brokerageId:n,isAdmin:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=vs(),o=Wn(),{toast:c}=Ai(),[d,u]=j.useState(""),[h,m]=j.useState(!0),p=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),p?f():a.length===0&&!n&&m(!1)},[s,t,r,p,o,a,i]);const f=async()=>{if(!p){m(!1);return}try{const{data:x,error:y}=await q.from("brokerages").select("name").eq("id",p).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(qs,{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"})})}):p?e.jsx(qs,{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(Ns,{value:i||"",onValueChange:l,children:[e.jsxs(ws,{className:"w-[280px]",children:[e.jsx(_i,{className:"mr-2 h-4 w-4"}),e.jsx(ks,{placeholder:"Select brokerage"})]}),e.jsx(js,{children:a.map(x=>e.jsx(et,{value:x.id,children:x.name},x.id))})]})]}),e.jsxs(oa,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(la,{className:"grid w-full grid-cols-4 md:grid-cols-8",children:[e.jsx(Kt,{value:"agents",children:"Agents"}),e.jsx(Kt,{value:"teams",children:"Teams"}),e.jsx(Kt,{value:"invite",children:"Invite Links"}),e.jsx(Kt,{value:"referrals",children:"Referrals"}),e.jsx(Kt,{value:"leaderboard",children:"Leaderboard"}),e.jsx(Kt,{value:"activity",children:"Activity"}),e.jsx(Kt,{value:"analytics",children:"Analytics"}),e.jsx(Kt,{value:"shares",children:"Shares"})]}),e.jsx(Zt,{value:"agents",className:"space-y-4",children:e.jsx(qCn,{brokerageId:p})}),e.jsx(Zt,{value:"teams",className:"space-y-4",children:e.jsx(QCn,{brokerageId:p})}),e.jsx(Zt,{value:"invite",className:"space-y-4",children:e.jsx(KCn,{brokerageId:p})}),e.jsx(Zt,{value:"referrals",className:"space-y-4",children:e.jsx(XCn,{})}),e.jsx(Zt,{value:"leaderboard",className:"space-y-4",children:e.jsx(Rzt,{brokerageId:p,title:`${d} Event Leaderboard`,showUserStats:!1})}),e.jsx(Zt,{value:"activity",className:"space-y-4",children:e.jsx(GCn,{brokerageId:p})}),e.jsx(Zt,{value:"analytics",className:"space-y-4",children:e.jsx(WCn,{brokerageId:p})}),e.jsx(Zt,{value:"shares",className:"space-y-4",children:e.jsx(hqt,{brokerageOnly:!0,brokerageId:p})})]})]})}):e.jsx(qs,{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(_i,{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 eAn({brokerageId:s,canManage:t}){const{user:n}=vs(),[r,a]=j.useState([]),[i,l]=j.useState(!0),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(null),[p,f]=j.useState(!1),[x,y]=j.useState(""),[v,b]=j.useState(""),[N,S]=j.useState(!1),A=async()=>{try{const{data:R,error:z}=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(z)throw z;const $=R;if($&&$.length>0){const H=[...new Set($.map(Q=>Q.created_by))],{data:V}=await q.from("profiles").select("id, name, avatar_url").in("id",H),K=new Map((V==null?void 0:V.map(Q=>[Q.id,Q]))||[]),Z=$.map(Q=>({...Q,author:K.get(Q.created_by)||{name:"Unknown",avatar_url:null}}));a(Z)}else a([])}catch(R){console.error("Error fetching announcements:",R)}finally{l(!1)}};j.useEffect(()=>{A()},[s]);const T=()=>{y(""),b(""),S(!1),u(null)},L=R=>{R?(u(R),y(R.title),b(R.content),S(R.is_pinned)):T(),c(!0)},M=async()=>{if(!x.trim()||!v.trim()){re.error("Please fill in all fields");return}f(!0);try{if(d){const{error:R}=await q.from("brokerage_announcements").update({title:x.trim(),content:v.trim(),is_pinned:N,pinned_at:N?new Date().toISOString():null}).eq("id",d.id);if(R)throw R;re.success("Announcement updated")}else{const{error:R}=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:N,pinned_at:N?new Date().toISOString():null});if(R)throw R;re.success("Announcement created")}c(!1),T(),A()}catch(R){console.error("Error saving announcement:",R),re.error("Failed to save announcement")}finally{f(!1)}},I=async()=>{if(h)try{const{error:R}=await q.from("brokerage_announcements").delete().eq("id",h);if(R)throw R;re.success("Announcement deleted"),A()}catch(R){console.error("Error deleting announcement:",R),re.error("Failed to delete announcement")}finally{m(null)}};return i?e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Th,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Th,{className:"h-5 w-5 text-primary"}),"Announcements"]}),t&&e.jsxs(U,{size:"sm",onClick:()=>L(),className:"gap-1",children:[e.jsx(an,{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(R=>{var z,$,H,V;return e.jsx("div",{className:`p-4 rounded-lg border ${R.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:[R.is_pinned&&e.jsx(MA,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("h4",{className:"font-semibold truncate",children:R.title})]}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:R.content}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 text-xs text-muted-foreground",children:[e.jsxs(Ea,{className:"h-5 w-5",children:[e.jsx(Ci,{src:((z=R.author)==null?void 0:z.avatar_url)||void 0}),e.jsx(Ta,{className:"text-[10px]",children:((H=($=R.author)==null?void 0:$.name)==null?void 0:H.charAt(0))||"?"})]}),e.jsx("span",{children:(V=R.author)==null?void 0:V.name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Gs(new Date(R.created_at),"MMM d, yyyy")})]})]}),t&&e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>L(R),children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>m(R.id),children:e.jsx(In,{className:"h-4 w-4"})})]})]})},R.id)})})})]}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:d?"Edit Announcement":"New Announcement"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"title",children:"Title"}),e.jsx(xe,{id:"title",value:x,onChange:R=>y(R.target.value),placeholder:"Announcement title..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"content",children:"Content"}),e.jsx(Fs,{id:"content",value:v,onChange:R=>b(R.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(wn,{id:"pinned",checked:N,onCheckedChange:S}),e.jsxs(te,{htmlFor:"pinned",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(MA,{className:"h-4 w-4"}),"Pin to top"]})]})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(U,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(U,{onClick:M,disabled:p,children:p?"Saving...":d?"Update":"Create"})]})]})]})}),e.jsx(Fl,{open:!!h,onOpenChange:()=>m(null),children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Delete Announcement"}),e.jsx(Ll,{children:"Are you sure you want to delete this announcement? This action cannot be undone."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:I,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function tAn({brokerageId:s,canManage:t=!1}){const{startImpersonation:n,isLoading:r}=$6e(),{user:a}=vs(),[i,l]=j.useState([]),[o,c]=j.useState(!0),[d,u]=j.useState(""),[h,m]=j.useState(new Set);j.useEffect(()=>{(async()=>{try{const{data:x,error:y}=await q.from("profiles").select("id, name, email, phone, avatar_url, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url").eq("brokerage_id",s).order("name");if(y)throw y;if(l(x||[]),x&&x.length>0){const v=x.map(N=>N.id),{data:b}=await q.from("agent_assistant_assignments").select("agent_id").in("agent_id",v);b&&m(new Set(b.map(N=>N.agent_id)))}}catch(x){console.error("Error fetching agents:",x)}finally{c(!1)}})()},[s]);const p=i.filter(f=>{var x,y;return f.name.toLowerCase().includes(d.toLowerCase())||f.email.toLowerCase().includes(d.toLowerCase())||((x=f.title)==null?void 0:x.toLowerCase().includes(d.toLowerCase()))||((y=f.areas_served)==null?void 0:y.toLowerCase().includes(d.toLowerCase()))});return o?e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Bn,{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(f=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-48 bg-muted rounded-lg"})},f))})})]}):e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Bn,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search agents...",value:d,onChange:f=>u(f.target.value),className:"pl-9"})]})]}),e.jsx(Ie,{children:p.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:p.map(f=>e.jsx(sAn,{agent:f,hasAssistant:h.has(f.id),canImpersonate:t&&f.id!==(a==null?void 0:a.id),onImpersonate:()=>n(f.id,"/my-brokerage"),impersonationLoading:r},f.id))})})]})}function sAn({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(Ea,{className:"h-20 w-20 mb-3 ring-2 ring-background shadow-md",children:[e.jsx(Ci,{src:s.avatar_url||void 0,alt:s.name}),e.jsx(Ta,{className:"text-lg bg-primary/10 text-primary",children:i})]}),e.jsx("h3",{className:"font-semibold text-sm leading-tight",children:s.name}),s.title&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:s.title}),t&&e.jsx(Be,{variant:"outline",className:"text-[10px] mt-1",children:"Has Assistant"})]}),s.bio&&e.jsx("p",{className:"text-xs text-muted-foreground text-center line-clamp-2 mb-3",children:s.bio}),e.jsxs("div",{className:"space-y-1.5 mb-3",children:[s.areas_served&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(ni,{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(Bg,{children:[e.jsx(Ug,{asChild:!0,children:e.jsx(U,{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(EM,{className:"h-4 w-4"})})}),e.jsxs(ng,{children:["Login as ",s.name]})]}),s.phone&&e.jsx(U,{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(ba,{className:"h-4 w-4"})})}),e.jsx(U,{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(ln,{className:"h-4 w-4"})})}),s.linkedin_url&&e.jsx(U,{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(Gg,{className:"h-4 w-4"})})}),s.instagram_url&&e.jsx(U,{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(gm,{className:"h-4 w-4"})})})]})]})}function nAn({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 p=new Map(c.map(x=>[x.id,x])),f=(h||[]).filter(x=>x.total_points>0).map(x=>{const y=p.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(f)}catch(c){console.error("Error fetching leaderboard:",c)}finally{a(!1)}})()},[s]),r)return e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Al,{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(CA,{className:Mt("h-5 w-5",i(o))}):e.jsx("span",{className:"w-5 text-center text-sm text-muted-foreground",children:o});return e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Al,{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:Mt("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(Ea,{className:"h-8 w-8",children:[e.jsx(Ci,{src:o.avatar_url||void 0}),e.jsx(Ta,{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 rAn({brokerageId:s}){const t=Wn(),[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:p}=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(p)throw p;const f=(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(f)}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(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(ra,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(ra,{className:"h-5 w-5 text-primary"}),"Brokerage Listings"]}),e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>t("/mission-control/listings"),className:"gap-1",children:[e.jsx(an,{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(ra,{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(U,{size:"sm",onClick:()=>t("/mission-control/listings/new"),className:"gap-1",children:[e.jsx(an,{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(ra,{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(U,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>t("/mission-control/listings"),children:["View All Listings",e.jsx(Sr,{className:"h-3 w-3 ml-1"})]})]})]})}const aAn={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 iAn({brokerageId:s,canManage:t}){const{user:n}=vs(),{toast:r}=Ai(),{data:a,isLoading:i}=wKs(s),l=jKs(s),[o,c]=j.useState({...aAn}),[d,u]=j.useState({show_equal_housing:!1,show_realtor_logo:!1,lock_colors:!1,lock_logo:!1}),[h,m]=j.useState(null),p={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 f=(b,N)=>c(S=>({...S,[b]:N})),x=async(b,N)=>{if(n){m(b);try{const S=await Lzt(n.id,N,`brokerage-${b}`);f(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,N])=>[b,N||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,N)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:N}),e.jsxs("div",{className:"flex items-center gap-3",children:[o[b]&&e.jsx("img",{src:o[b],alt:N,className:"h-12 w-auto rounded border bg-background p-1"}),e.jsx("input",{ref:p[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(U,{type:"button",variant:"outline",disabled:!t||h===b,onClick:()=>{var S;return(S=p[b].current)==null?void 0:S.click()},children:[h===b?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(qa,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Upload"})]}),o[b]&&t&&e.jsx(U,{type:"button",variant:"ghost",onClick:()=>f(b,""),children:"Remove"})]})]});return e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(_i,{className:"h-5 w-5"}),"Brokerage Brand"]}),e.jsx(Jn,{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(Et,{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,N,S])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:N}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{type:"color",className:"h-10 w-14 p-1",disabled:!t,value:o[b]||S,onChange:A=>f(b,A.target.value)}),e.jsx(xe,{disabled:!t,value:o[b],placeholder:S,onChange:A=>f(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(te,{children:"Heading font"}),e.jsx(xe,{disabled:!t,value:o.heading_font,placeholder:"Playfair Display",onChange:b=>f("heading_font",b.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Body font"}),e.jsx(xe,{disabled:!t,value:o.body_font,placeholder:"Inter",onChange:b=>f("body_font",b.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Legal brokerage name"}),e.jsx(xe,{disabled:!t,value:o.legal_name,placeholder:"Acme Realty, Inc.",onChange:b=>f("legal_name",b.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Brokerage license #"}),e.jsx(xe,{disabled:!t,value:o.license_number,placeholder:"DRE #01234567",onChange:b=>f("license_number",b.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"License state"}),e.jsx(xe,{disabled:!t,value:o.license_state,placeholder:"CA",onChange:b=>f("license_state",b.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Required disclaimer / compliance line"}),e.jsx(Fs,{disabled:!t,rows:2,value:o.compliance_line,placeholder:"Each office independently owned and operated. Information deemed reliable but not guaranteed.",onChange:b=>f("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,N])=>e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsx(te,{className:"text-sm font-normal",children:N}),e.jsx(wn,{disabled:!t,checked:d[b],onCheckedChange:S=>u(A=>({...A,[b]:S}))})]},b))}),t&&e.jsxs(U,{onClick:y,disabled:l.isPending,children:[l.isPending?e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ho,{className:"mr-2 h-4 w-4"}),"Save brokerage brand"]})]})})]})}function oAn(){const{user:s,isAdmin:t,isBrokerageManager:n}=vs(),r=Wn(),[a,i]=j.useState(!0),[l,o]=j.useState(null),[c,d]=j.useState(""),[u,h]=j.useState(0),[m,p]=j.useState(!1),[f,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:N}=await q.from("profiles").select("id",{count:"exact",head:!0}).eq("brokerage_id",v.brokerage_id);if(h(N||0),t)p(!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();p(!!S),x(!!S)}}catch(v){console.error("Error fetching brokerage info:",v)}finally{i(!1)}})()},[s,t,n]),a?e.jsx(qs,{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(qs,{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(Bn,{className:"h-5 w-5 text-primary"}),e.jsxs("span",{className:"font-medium",children:[u," ",u===1?"Agent":"Agents"]})]}),f&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{variant:"outline",onClick:()=>r("/brokerage-content"),children:[e.jsx(ig,{className:"h-4 w-4 mr-2"}),"Brokerage Content"]}),e.jsxs(U,{onClick:()=>r(`/mission-control/listings/new?brokerage=${l}`),children:[e.jsx(ra,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})]}),e.jsx(iAn,{brokerageId:l,canManage:m}),e.jsx(eAn,{brokerageId:l,canManage:m}),e.jsx(tAn,{brokerageId:l,canManage:m}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsx(nAn,{brokerageId:l}),e.jsx(rAn,{brokerageId:l})]})]})}):e.jsx(qs,{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(_i,{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 lAn(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 cAn(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 y_t={video:{icon:lu,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:Ur,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:ad,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:pa,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:$c,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function dAn({item:s,canManage:t}){const[n,r]=j.useState(!1),[a,i]=j.useState(null),l=hzs(),o=Wn(),c=y_t[s.content_type]||y_t.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"?lAn(s.url):null,[s]);j.useEffect(()=>{u||!s.url||s.content_type!=="video"||!cAn(s.url)||fetch(`https://www.youtube.com/oembed?url=${encodeURIComponent(s.url)}&format=json`).then(f=>f.ok?f.json():null).then(f=>{f!=null&&f.thumbnail_url&&i(f.thumbnail_url)}).catch(()=>{})},[s.url,s.content_type,u]);const h=u||a,m=()=>{o(`/brokerage-content/${s.id}`)},p=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(we,{className:"group overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30 cursor-pointer",onClick:m,children:[h?e.jsx("div",{className:"aspect-video bg-muted/50 overflow-hidden",children:e.jsx("img",{src:h,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300",referrerPolicy:"no-referrer"})}):e.jsx("div",{className:"aspect-video bg-muted/30 flex items-center justify-center",children:e.jsx(d,{className:"h-12 w-12 text-muted-foreground/30"})}),e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsxs(Be,{variant:"secondary",className:`text-[10px] px-1.5 py-0 ${c.color}`,children:[e.jsx(d,{className:"h-3 w-3 mr-1"}),c.label]}),s.category&&e.jsxs(Be,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:[s.category.icon," ",s.category.name]})]}),e.jsx("h3",{className:"font-semibold text-sm text-foreground group-hover:text-primary transition-colors truncate",children:s.title}),s.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:s.description}),s.content_type==="event"&&s.event_date&&e.jsxs("p",{className:"text-xs text-primary mt-2 font-medium",children:["📅 ",Gs(new Date(s.event_date),"MMM d, yyyy · h:mm a")]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-2",children:["Added ",Gs(new Date(s.created_at),"MMM d, yyyy")]})]}),t&&e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,onClick:f=>f.stopPropagation(),children:e.jsx(U,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",children:e.jsx(ey,{className:"h-4 w-4"})})}),e.jsx(Eu,{align:"end",children:e.jsxs(La,{onClick:f=>{f.stopPropagation(),r(!0)},className:"text-destructive",children:[e.jsx(In,{className:"h-4 w-4 mr-2"}),"Delete"]})})]})]})})]}),e.jsx(Fl,{open:n,onOpenChange:r,children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Delete Content"}),e.jsxs(Ll,{children:['Are you sure you want to delete "',s.title,'"? This cannot be undone.']})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:p,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function uAn(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 v_t=[{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 hAn({brokerageId:s,categories:t}){var ie;const{user:n}=vs(),[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(""),[d,u]=j.useState("📁"),[h,m]=j.useState(!1);j.useRef(null);const[p,f]=j.useState("video"),[x,y]=j.useState(""),[v,b]=j.useState(""),[N,S]=j.useState(""),[A,T]=j.useState(""),[L,M]=j.useState(""),[I,R]=j.useState(""),[z,$]=j.useState(""),H=uzs(),V=mzs(s),K=pzs(),Z=fzs(s),Q=()=>{f("video"),y(""),b(""),S(""),T(""),M(""),R(""),$("")},le=async(ce,je)=>{var he;const be=(he=ce.target.files)==null?void 0:he[0];if(be){m(!0);try{const ge=be.name.split(".").pop(),ke=`${s}/${Date.now()}-${Math.random().toString(36).slice(2)}.${ge}`,{error:Te}=await q.storage.from("brokerage-content").upload(ke,be);if(Te)throw Te;const{data:{publicUrl:Me}}=q.storage.from("brokerage-content").getPublicUrl(ke);je==="file"?(T(Me),p==="graphic"&&!L&&M(Me)):M(Me),re.success("File uploaded")}catch(ge){re.error(ge.message||"Upload failed")}finally{m(!1)}}},ue=async()=>{if(!x.trim()){re.error("Title is required");return}if(n)try{await H.mutateAsync({brokerage_id:s,category_id:z||null,content_type:p,title:x.trim(),description:v.trim()||null,url:N.trim()||null,file_url:A.trim()||null,thumbnail_url:L.trim()||null,event_date:I?new Date(I).toISOString():null,created_by:n.id}),re.success("Content added!"),Q(),a(!1)}catch(ce){re.error(ce.message||"Failed to add content")}},se=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")}},ne=async()=>{try{await Z.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(al,{asChild:!0,children:e.jsxs(U,{children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Add Content"]})}),e.jsxs(Ds,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Add Brokerage Content"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Content Type"}),e.jsxs(Ns,{value:p,onValueChange:f,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:v_t.map(ce=>e.jsx(et,{value:ce.value,children:ce.label},ce.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(ie=v_t.find(ce=>ce.value===p))==null?void 0:ie.hint})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Category"}),e.jsxs(Ns,{value:z,onValueChange:$,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select category (optional)"})}),e.jsx(js,{children:t.map(ce=>e.jsxs(et,{value:ce.id,children:[ce.icon," ",ce.name]},ce.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Title *"}),e.jsx(xe,{value:x,onChange:ce=>y(ce.target.value),placeholder:"Content title"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Description"}),e.jsx(Fs,{value:v,onChange:ce=>b(ce.target.value),placeholder:"Brief description...",rows:2})]}),["video","link","graphic","event"].includes(p)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:p==="video"?"Video URL":p==="graphic"?"Canva / Image URL":p==="event"?"Event Link (Zoom, etc.)":"URL"}),e.jsx(xe,{value:N,onChange:ce=>{const je=ce.target.value;if(S(je),p==="video"&&!L){const be=uAn(je);be&&M(be)}},placeholder:"https://..."})]}),["pdf","graphic"].includes(p)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:p==="pdf"?"Upload PDF":"Upload Image"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"file",accept:p==="pdf"?".pdf,.doc,.docx":"image/*",onChange:ce=>le(ce,"file"),disabled:h}),h&&e.jsx(Et,{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(te,{children:"Thumbnail Image (optional)"}),e.jsx(xe,{type:"file",accept:"image/*",onChange:ce=>le(ce,"thumbnail"),disabled:h}),L&&e.jsxs("div",{className:"relative w-20 h-20 rounded overflow-hidden",children:[e.jsx("img",{src:L,className:"w-full h-full object-cover",alt:"thumb"}),e.jsx("button",{onClick:()=>M(""),className:"absolute top-0 right-0 bg-background/80 rounded-bl p-0.5",children:e.jsx(er,{className:"h-3 w-3"})})]})]}),p==="event"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Event Date & Time"}),e.jsx(xe,{type:"datetime-local",value:I,onChange:ce=>R(ce.target.value)})]}),e.jsxs(U,{onClick:ue,disabled:H.isPending||!x.trim(),className:"w-full",children:[H.isPending?e.jsx(Et,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(an,{className:"h-4 w-4 mr-2"}),"Add Content"]})]})]})]}),e.jsxs(zs,{open:i,onOpenChange:l,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{variant:"outline",size:"sm",children:[e.jsx(qc,{className:"h-4 w-4 mr-2"}),"Categories"]})}),e.jsxs(Ds,{className:"max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Manage Categories"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[t.length===0&&e.jsxs("div",{className:"text-center py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No categories yet"}),e.jsxs(U,{variant:"outline",size:"sm",onClick:ne,disabled:Z.isPending,children:[Z.isPending?e.jsx(Et,{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(U,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:async()=>{await K.mutateAsync(ce.id),re.success("Category deleted")},children:e.jsx(er,{className:"h-4 w-4"})})]},ce.id)),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(xe,{value:d,onChange:ce=>u(ce.target.value),className:"w-14 text-center",maxLength:2}),e.jsx(xe,{value:o,onChange:ce=>c(ce.target.value),placeholder:"New category name",className:"flex-1",onKeyDown:ce=>ce.key==="Enter"&&se()}),e.jsx(U,{size:"sm",onClick:se,disabled:!o.trim(),children:"Add"})]})]})]})]})]})}function mAn(){const{user:s,isAdmin:t,isBrokerageManager:n}=vs(),[r,a]=j.useState(!0),[i,l]=j.useState(null),[o,c]=j.useState(""),[d,u]=j.useState(!1),[h,m]=j.useState(null),[p,f]=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:T}=await q.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",S.brokerage_id).maybeSingle();u(!!T)}}catch(S){console.error("Error fetching brokerage info:",S)}finally{a(!1)}})()},[s,t,n]);const{data:x=[]}=lzs(i),{data:y=[],isLoading:v}=czs(i,h),b=j.useMemo(()=>{if(!p.trim())return y;const N=p.toLowerCase();return y.filter(S=>{var A;return S.title.toLowerCase().includes(N)||((A=S.description)==null?void 0:A.toLowerCase().includes(N))||S.content_type.toLowerCase().includes(N)})},[y,p]);return r?e.jsx(qs,{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(qs,{title:`${o} Content`,description:"Brokerage Content Hub",children:e.jsxs("div",{className:"space-y-6",children:[d&&i&&e.jsx(hAn,{brokerageId:i,categories:x}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search content...",value:p,onChange:N=>f(N.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(U,{variant:h===null?"default":"outline",size:"sm",onClick:()=>m(null),children:"All"}),x.map(N=>e.jsxs(U,{variant:h===N.id?"default":"outline",size:"sm",onClick:()=>m(N.id),children:[e.jsx("span",{className:"mr-1",children:N.icon}),N.name]},N.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(we,{className:"bg-muted/30 border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(r1,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-muted-foreground font-medium",children:p.trim()?"No matching content found":"No content yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:p.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(N=>e.jsx(dAn,{item:N,canManage:d},N.id))})]})}):e.jsx(qs,{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(_i,{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 b_t={video:{icon:lu,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:Ur,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:ad,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:pa,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:$c,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function pAn(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 fAn(s){try{const t=new URL(s).hostname.replace("www.","");return["youtube.com","youtu.be","m.youtube.com"].includes(t)}catch{return!1}}function gAn(s){try{return new URL(s).hostname.includes("vimeo.com")}catch{return!1}}function xAn(s){try{const t=s.match(/vimeo\.com\/(\d+)/);if(t)return`https://player.vimeo.com/video/${t[1]}`}catch{}return null}function yAn(){const{contentId:s}=Di(),{data:t,isLoading:n}=ct({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(qs,{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(qs,{title:"Brokerage Content",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(_i,{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(U,{asChild:!0,className:"mt-4",children:e.jsx(xr,{to:"/brokerage-content",children:"Back to Content"})})]})});const r=b_t[t.content_type]||b_t.link,a=r.icon,i=t.url||t.file_url,l=i&&fAn(i)?pAn(i):null,o=i&&gAn(i)?xAn(i):null,c=l||o;return e.jsx(qs,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsx(U,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(xr,{to:"/brokerage-content",children:[e.jsx(Aa,{className:"h-4 w-4"}),"Back to Content"]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Be,{variant:"secondary",className:`text-xs px-2 py-0.5 ${r.color}`,children:[e.jsx(a,{className:"h-3 w-3 mr-1"}),r.label]}),t.category&&e.jsxs(Be,{variant:"outline",className:"text-xs px-2 py-0.5",children:[t.category.icon," ",t.category.name]}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-auto",children:["Added ",Gs(new Date(t.created_at),"MMMM d, yyyy")]})]}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),c&&e.jsx(we,{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(we,{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(we,{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(we,{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(we,{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(pa,{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:Gs(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(U,{asChild:!0,size:"lg",children:e.jsxs("a",{href:t.file_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(pi,{className:"h-4 w-4 mr-2"}),t.content_type==="pdf"?"Download Document":"Download File"]})}),t.url&&e.jsx(U,{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(Sr,{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 PEe={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 vAn(s="open"){const{user:t}=vs();return ct({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 bAn(s){return ct({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 _An(s){return ct({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 wAn(){const s=Qt(),{user:t,brokerageId:n}=vs();return yt({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 jAn(){const s=Qt(),{user:t}=vs();return yt({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 NAn(){const s=Qt();return yt({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 kAn(){const s=Qt();return yt({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 SAn(){const s=Qt();return yt({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 CAn(){const s=Qt();return yt({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 AAn(){const{user:s,brokerageId:t}=vs(),n=Qt(),r=ct({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=yt({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 EAn(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 TAn(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 MAn({req:s,onClick:t}){var i;const n=PEe[s.request_type],r=EAn(s.event_start_at,s.event_end_at),a=[s.address,s.city,s.state].filter(Boolean).join(", ");return e.jsx(we,{className:"cursor-pointer hover:shadow-md transition group",onClick:t,children:e.jsxs(Ie,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(Be,{variant:"secondary",className:"text-xs",children:[n.emoji," ",n.label]}),s.status!=="open"&&e.jsx(Be,{variant:"outline",className:"text-xs capitalize",children:s.status})]}),e.jsx(gi,{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(Yr,{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(ni,{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(yu,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:TAn(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 PAn(){var c;const s=Wn(),{brokerageId:t}=vs(),[n,r]=j.useState("open"),{data:a=[],isLoading:i}=vAn(n),l=AAn(),o=((c=l.data)==null?void 0:c.email_enabled)??!0;return t?e.jsx(qs,{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(oa,{value:n,onValueChange:d=>r(d),children:e.jsxs(la,{children:[e.jsx(Kt,{value:"open",children:"Open"}),e.jsx(Kt,{value:"mine",children:"My Posts"}),e.jsx(Kt,{value:"my_claims",children:"My Claims"}),e.jsx(Kt,{value:"filled",children:"Filled"})]})}),e.jsxs(U,{onClick:()=>s("/brokerage/help-board/new"),className:"gap-2",children:[e.jsx(an,{className:"h-4 w-4"})," Post Request"]})]}),e.jsx(we,{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(bx,{className:"h-4 w-4 text-primary"}):e.jsx(Zk,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx(te,{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(wn,{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(we,{className:"bg-muted/30 border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(e4,{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(MAn,{req:d,onClick:()=>s(`/brokerage/help-board/${d.id}`)},d.id))})]})}):e.jsx(qs,{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(e4,{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 LAn(){const s=Wn(),{toast:t}=Ai(),n=wAn(),[r,a]=j.useState("open_house"),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,f]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState(""),[N,S]=j.useState(""),[A,T]=j.useState(""),[L,M]=j.useState(""),[I,R]=j.useState("goodwill"),[z,$]=j.useState(""),[H,V]=j.useState(""),K=r==="open_house"||r==="showing_coverage",Z=r!=="general",Q=(ue,se)=>!ue||!se?null:`${ue}T${se}:00`,le=async ue=>{if(ue.preventDefault(),!i.trim()){t({title:"Add a title",description:"Tell teammates what you need help with.",variant:"destructive"});return}try{const se=Q(d,h),ne=Q(d,p);await n.mutateAsync({request_type:r,title:i.trim(),description:o.trim()||null,event_start_at:se,event_end_at:ne,address:K&&x.trim()||null,city:K&&v.trim()||null,state:K&&N.trim()||null,zip:K&&A.trim()||null,mls_number:L.trim()||null,compensation_type:I,compensation_amount:z?Number(z):null,compensation_notes:H.trim()||null}),t({title:"Posted!",description:"Your teammates have been notified."}),s("/brokerage/help-board")}catch(se){t({title:"Could not post",description:(se==null?void 0:se.message)??"Something went wrong.",variant:"destructive"})}};return e.jsx(qs,{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(U,{variant:"ghost",size:"sm",onClick:()=>s("/brokerage/help-board"),className:"mb-4 gap-2",children:[e.jsx(Aa,{className:"h-4 w-4"})," Back to board"]}),e.jsx("form",{onSubmit:le,children:e.jsx(we,{children:e.jsxs(Ie,{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"What do you need help with?"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Object.keys(PEe).map(ue=>{const se=PEe[ue],ne=ue===r;return e.jsxs("button",{type:"button",onClick:()=>a(ue),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:"text-lg",children:se.emoji}),e.jsx("div",{className:"font-medium text-sm mt-1",children:se.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:se.description})]},ue)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"title",children:"Title *"}),e.jsx(xe,{id:"title",value:i,onChange:ue=>l(ue.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(te,{htmlFor:"description",children:"Details"}),e.jsx(Fs,{id:"description",value:o,onChange:ue=>c(ue.target.value),placeholder:"Any context — lockbox code instructions later, what to expect, etc.",rows:3,maxLength:1e3})]}),Z&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"date",children:"Date"}),e.jsx(xe,{id:"date",type:"date",value:d,onChange:ue=>u(ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"start",children:"Start"}),e.jsx(xe,{id:"start",type:"time",value:h,onChange:ue=>m(ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"end",children:"End"}),e.jsx(xe,{id:"end",type:"time",value:p,onChange:ue=>f(ue.target.value)})]})]}),K&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"address",children:"Address"}),e.jsx(xe,{id:"address",value:x,onChange:ue=>y(ue.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(te,{htmlFor:"city",children:"City"}),e.jsx(xe,{id:"city",value:v,onChange:ue=>b(ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"state",children:"State"}),e.jsx(xe,{id:"state",value:N,onChange:ue=>S(ue.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(te,{htmlFor:"zip",children:"Zip"}),e.jsx(xe,{id:"zip",value:A,onChange:ue=>T(ue.target.value),maxLength:10})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"mls",children:"MLS # (optional)"}),e.jsx(xe,{id:"mls",value:L,onChange:ue=>M(ue.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsx(te,{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(ue=>{const se=I===ue.val;return e.jsxs("button",{type:"button",onClick:()=>R(ue.val),className:`text-left p-3 rounded-lg border-2 transition ${se?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"font-medium text-sm",children:ue.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:ue.sub})]},ue.val)})}),I!=="goodwill"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"amount",children:I==="flat_fee"?"Amount ($)":"Percent (%)"}),e.jsx(xe,{id:"amount",type:"number",min:"0",step:I==="referral_percent"?"1":"5",value:z,onChange:ue=>$(ue.target.value),placeholder:I==="flat_fee"?"100":"25"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"comp-notes",children:"Compensation notes"}),e.jsx(xe,{id:"comp-notes",value:H,onChange:ue=>V(ue.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(U,{type:"button",variant:"ghost",onClick:()=>s("/brokerage/help-board"),children:"Cancel"}),e.jsxs(U,{type:"submit",disabled:n.isPending,className:"gap-2",children:[n.isPending&&e.jsx(Et,{className:"h-4 w-4 animate-spin"}),"Post & Notify Brokerage"]})]})]})})})]})})}function IAn(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 M7e(s){return s?s.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"?"}function RAn(){var L,M,I,R,z,$,H,V;const{id:s}=Di(),t=Wn(),{user:n}=vs(),{toast:r}=Ai(),{data:a,isLoading:i}=bAn(s),{data:l=[]}=_An(s),o=jAn(),c=NAn(),d=kAn(),u=SAn(),h=CAn(),[m,p]=j.useState("");if(i)return e.jsx(qs,{title:"Loading...",description:"",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(Et,{className:"h-8 w-8 animate-spin text-primary"})})});if(!a)return e.jsxs(qs,{title:"Not Found",description:"",children:[e.jsxs(U,{variant:"ghost",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(Aa,{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 f=PEe[a.request_type],x=IAn(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(K=>K.claimant_user_id===(n==null?void 0:n.id)),N=l.find(K=>K.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)",T=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."}),p("")}catch(K){r({title:"Could not submit",description:K==null?void 0:K.message,variant:"destructive"})}};return e.jsx(qs,{title:a.title,description:`${f.emoji} ${f.label}`,children:e.jsxs("div",{className:"max-w-3xl mx-auto space-y-4",children:[e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(Aa,{className:"h-4 w-4"})," Back to board"]}),e.jsx(we,{children:e.jsxs(Ie,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(Be,{variant:"secondary",children:[f.emoji," ",f.label]}),e.jsx(Be,{variant:S?"default":"outline",className:"capitalize",children:a.status})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsxs(Ea,{className:"h-7 w-7",children:[e.jsx(Ci,{src:((L=a.requester)==null?void 0:L.avatar_url)||void 0}),e.jsx(Ta,{children:M7e((M=a.requester)==null?void 0:M.name)})]}),e.jsx("span",{children:((I=a.requester)==null?void 0:I.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(Yr,{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(ni,{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(yu,{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(CM,{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(we,{children:e.jsxs(Ie,{className:"p-6 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Offer to cover this"}),e.jsx(Fs,{placeholder:"Quick note — e.g. 'I'm 10 min away and free that day'",value:m,onChange:K=>p(K.target.value),rows:3,maxLength:400}),e.jsxs(U,{onClick:T,disabled:o.isPending,className:"gap-2",children:[o.isPending&&e.jsx(Et,{className:"h-4 w-4 animate-spin"}),"I can cover this"]})]})}),!v&&b&&e.jsx(we,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx(Xr,{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."]})]})]})}),N&&(v||N.claimant_user_id===(n==null?void 0:n.id))&&e.jsx(we,{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(Ea,{className:"h-10 w-10",children:[e.jsx(Ci,{src:((R=N.claimant)==null?void 0:R.avatar_url)||void 0}),e.jsx(Ta,{children:M7e((z=N.claimant)==null?void 0:z.name)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:($=N.claimant)==null?void 0:$.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:[((H=N.claimant)==null?void 0:H.email)&&e.jsxs("a",{href:`mailto:${N.claimant.email}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(ln,{className:"h-4 w-4"})," ",N.claimant.email]}),((V=N.claimant)==null?void 0:V.phone)&&e.jsxs("a",{href:`tel:${N.claimant.phone}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(ba,{className:"h-4 w-4"})," ",N.claimant.phone]})]})]})}),v&&e.jsx(we,{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(K=>{var Z,Q,le,ue,se;return e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg border",children:[e.jsxs(Ea,{className:"h-10 w-10",children:[e.jsx(Ci,{src:((Z=K.claimant)==null?void 0:Z.avatar_url)||void 0}),e.jsx(Ta,{children:M7e((Q=K.claimant)==null?void 0:Q.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:((le=K.claimant)==null?void 0:le.name)||"Teammate"}),e.jsx(Be,{variant:"outline",className:"capitalize text-xs",children:K.status})]}),K.note&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:['"',K.note,'"']}),K.status==="pending"&&S&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs(U,{size:"sm",onClick:()=>c.mutate({claim_id:K.id,request_id:a.id,claimant_user_id:K.claimant_user_id}),disabled:c.isPending,className:"gap-1",children:[e.jsx(Xr,{className:"h-3.5 w-3.5"})," Pick ",((se=(ue=K.claimant)==null?void 0:ue.name)==null?void 0:se.split(" ")[0])||"them"]}),e.jsxs(U,{size:"sm",variant:"ghost",onClick:()=>d.mutate({claim_id:K.id,request_id:a.id}),disabled:d.isPending,className:"gap-1",children:[e.jsx(er,{className:"h-3.5 w-3.5"})," Pass"]})]})]})]},K.id)}),v&&S&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx(U,{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(U,{size:"sm",onClick:()=>h.mutate(a.id),disabled:h.isPending,children:"Mark complete"})})]})})]})})}function oGt({onSelect:s,maxHeight:t="460px"}){const[n,r]=j.useState(""),[a,i]=j.useState("all"),{data:l=[],isLoading:o}=ct({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(Fr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(xe,{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(Gi,{style:{maxHeight:t},className:"rounded-md border",children:o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Et,{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(pc,{className:"h-8 w-8 text-muted-foreground/50 mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l.length===0?"No graphics available yet":"No graphics match your search"})]}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2 p-2",children:d.map(u=>e.jsxs("button",{onClick:()=>s(u),className:"group relative rounded-md overflow-hidden border bg-muted/30 hover:ring-2 hover:ring-primary hover:border-primary transition-all text-left",title:u.title,children:[e.jsx("div",{className:"aspect-video bg-muted overflow-hidden",children:e.jsx("img",{src:u.thumbnail_url||u.image_url,alt:u.title,loading:"lazy",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-200"})}),u.is_featured&&e.jsxs(Be,{className:"absolute top-1 left-1 h-5 px-1.5 gap-0.5 text-[10px] bg-amber-500 hover:bg-amber-500 text-white border-0",children:[e.jsx(Ua,{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 DAn=[{key:"search",label:"Search for Properties",icon:Fr,defaultText:"Search for Properties",placeholder:"https://your-website.com/search",helper:"Link to your home search page"},{key:"call",label:"Call Agent",icon:ba,defaultText:"Call Me",hrefPrefix:"tel:",placeholder:"+15555551234",helper:"Your phone number"},{key:"email",label:"Email Agent",icon:ln,defaultText:"Email Me",hrefPrefix:"mailto:",placeholder:"you@email.com",helper:"Your email address"},{key:"schedule",label:"Schedule a Call",icon:pa,defaultText:"Schedule a Call",placeholder:"https://calendly.com/you",helper:"Link to your booking page"},{key:"listings",label:"View My Listings",icon:ra,defaultText:"View My Listings",placeholder:"https://your-website.com/listings",helper:"Link to your listings page"},{key:"valuation",label:"Get Home Value",icon:yu,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:ni,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:jd,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:Ch,defaultText:"Learn More",placeholder:"https://...",helper:"Any link you want"}];function __t(s){const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/);return t?t[1]:null}function OAn(s){const t=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function lGt({html:s,onChange:t}){const{user:n}=vs(),r=j.useRef(null),a=j.useRef(""),i=j.useRef(t);i.current=t;const[l,o]=j.useState("desktop"),c=j.useRef(null),[d,u]=j.useState(!1),[h,m]=j.useState(""),[p,f]=j.useState(""),x=j.useRef(null),y=()=>{var vt;const bt=(vt=r.current)==null?void 0:vt.contentDocument,As=bt==null?void 0:bt.getSelection();As&&As.rangeCount>0&&(bt!=null&&bt.body.contains(As.anchorNode))&&(x.current=As.getRangeAt(0).cloneRange())},v=()=>{var Ms;const bt=c.current,As=(Ms=r.current)==null?void 0:Ms.contentDocument;if(!bt||!As)return;let vt=h.trim();vt&&!/^(https?:|mailto:|tel:|#|\/)/i.test(vt)&&(vt="https://"+vt),bt.setAttribute("href",vt),bt.setAttribute("target","_blank");const Ws=p.trim();Ws&&Ws!==(bt.textContent||"").trim()&&(bt.textContent=Ws);const on=` `+As.documentElement.outerHTML;a.current=on,i.current(on),u(!1)};j.useEffect(()=>{var vt,Ws;const bt=r.current;if(!bt||a.current===s)return;const As=()=>{const on=bt.contentDocument;if(!on)return;on.open(),on.write(s||""),on.close(),a.current=s;const Ms=on.body;if(!Ms)return;Ms.setAttribute("contenteditable","true"),Ms.style.outline="none",Ms.style.minHeight="400px",Ms.style.cursor="text";const dn=()=>{const br=` `+on.documentElement.outerHTML;a.current=br,i.current(br)};Ms.addEventListener("input",dn),Ms.addEventListener("blur",dn),Ms.addEventListener("mouseup",y),Ms.addEventListener("keyup",y),on.addEventListener("selectionchange",y);const rn=br=>{var _r;const Gn=br.target,On=Gn==null?void 0:Gn.closest("a");if(On){if(br.metaKey||br.ctrlKey||br.shiftKey)return;br.preventDefault(),br.stopPropagation(),c.current=On,m(On.getAttribute("href")||""),f((On.textContent||"").trim()),u(!0);return}const Rr=on.getSelection();if(!Rr)return;const cr=(_r=on.caretRangeFromPoint)==null?void 0:_r.call(on,br.clientX,br.clientY),Hs=cr==null?void 0:cr.startContainer;if(Hs&&Hs.nodeType===Node.TEXT_NODE){const nn=Hs.textContent||"",Zn=cr.startOffset,es=nn.lastIndexOf("[",Zn),ar=nn.indexOf("]",Zn);if(es!==-1&&ar!==-1&&ar>es){const Hn=on.createRange();Hn.setStart(Hs,es),Hn.setEnd(Hs,ar+1),Rr.removeAllRanges(),Rr.addRange(Hn),x.current=Hn.cloneRange()}}};Ms.addEventListener("click",rn,!0)};((vt=bt.contentDocument)==null?void 0:vt.readyState)==="complete"||(Ws=bt.contentDocument)!=null&&Ws.body?As():bt.addEventListener("load",As,{once:!0})},[s]);const b=(bt,As)=>{var on;const vt=(on=r.current)==null?void 0:on.contentDocument;if(!vt)return;vt.body.focus(),vt.execCommand(bt,!1,As);const Ws=` `+vt.documentElement.outerHTML;a.current=Ws,i.current(Ws)},N=()=>{const bt=window.prompt("Enter URL (https://...)");bt&&b("createLink",bt)},S=(bt,As)=>{var on;const vt=(on=r.current)==null?void 0:on.contentDocument;if(!vt)return;if(vt.body.focus(),As==="cursor"&&x.current&&vt.body.contains(x.current.startContainer)){const Ms=vt.getSelection();if(Ms){Ms.removeAllRanges(),Ms.addRange(x.current),vt.execCommand("insertHTML",!1,bt);const dn=` `+vt.documentElement.outerHTML;a.current=dn,i.current(dn);return}}As==="top"?vt.body.insertAdjacentHTML("afterbegin",bt):vt.body.insertAdjacentHTML("beforeend",bt);const Ws=` `+vt.documentElement.outerHTML;a.current=Ws,i.current(Ws)},[A,T]=j.useState(!1),[L,M]=j.useState(null),[I,R]=j.useState(""),[z,$]=j.useState(""),[H,V]=j.useState("#406E71"),[K,Z]=j.useState("cursor"),Q=bt=>{M(bt),R(bt.defaultText),$(""),T(!0)},le=()=>{if(!L)return;const bt=z.trim();if(!L.isForward&&!bt)return;let As=bt;if(L.isForward){const Ms=bt||"",dn=encodeURIComponent("You should see this newsletter"),rn=encodeURIComponent(Ms?`I thought you'd like this — take a look: ${Ms} `:`I thought you'd like this newsletter — take a look! `);As=`mailto:?subject=${dn}&body=${rn}`}else L.hrefPrefix==="tel:"?As="tel:"+bt.replace(/[^0-9+]/g,""):L.hrefPrefix==="mailto:"?As="mailto:"+bt:/^https?:\/\//i.test(bt)||(As="https://"+bt);const vt=(I||L.defaultText).replace(/[<>]/g,""),Ws=H||"#406E71",on=`
${vt}

 

`;S(on,K),T(!1)},[ue,se]=j.useState(!1),[ne,ie]=j.useState(""),[ce,je]=j.useState(""),[be,he]=j.useState(""),[ge,ke]=j.useState("cursor"),Te=(()=>{if(ce.trim())return ce.trim();const bt=__t(ne);return bt?`https://i.ytimg.com/vi/${bt}/hqdefault.jpg`:""})(),Me=()=>{ie(""),je(""),he(""),se(!0)},Oe=()=>{const bt=ne.trim();if(!bt)return;let As=bt;/^https?:\/\//i.test(As)||(As="https://"+As);const vt=__t(As),Ws=vt?null:OAn(As);let on=ce.trim();!on&&vt&&(on=`https://i.ytimg.com/vi/${vt}/hqdefault.jpg`),!on&&Ws&&(on=`https://vumbnail.com/${Ws}.jpg`),on||(on="https://placehold.co/600x340/406E71/ffffff?text=Watch+Video");const Ms=(be||"Watch the video").replace(/[<>]/g,""),dn=`
${Ms}
▶ ${Ms}

 

`.trim();S(dn,ge),se(!1)},[Se,Qe]=j.useState(!1),[Ae,Fe]=j.useState(""),[Ne,$e]=j.useState(""),[Ve,qe]=j.useState("full"),[Ze,Ue]=j.useState("cursor"),[Ye,Ge]=j.useState(!1),He=j.useRef(null),tt=()=>{Fe(""),$e(""),qe("full"),Qe(!0)},pt=async bt=>{var As;if(!n){re.error("You must be signed in to upload images");return}if(bt.size>10*1024*1024){re.error("Image must be under 10MB");return}Ge(!0);try{const vt=((As=bt.name.split(".").pop())==null?void 0:As.toLowerCase())||"png",Ws=`${n.id}/newsletters/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${vt}`,{error:on}=await q.storage.from("email-assets").upload(Ws,bt,{cacheControl:"3600",upsert:!1,contentType:bt.type});if(on)throw on;const{data:Ms}=q.storage.from("email-assets").getPublicUrl(Ws);Fe(Ms.publicUrl),re.success("Image uploaded")}catch(vt){re.error(vt.message||"Upload failed")}finally{Ge(!1)}},ft=()=>{if(!Ae.trim())return;const bt=(Ne||"").replace(/[<>"]/g,""),As=Ve==="half"?280:560,vt=`
${bt}

 

`.trim();S(vt,Ze),Qe(!1)},{data:qt,isLoading:Ut}=ct({queryKey:["newsletter-editor-videos",n==null?void 0:n.id],enabled:!!(n!=null&&n.id)&&ue,queryFn:async()=>{const{data:bt,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 bt||[]}}),Wt=bt=>{bt.share_token&&(ie(`https://video.relevelup.com/share/video/${bt.share_token}`),je(`https://video.relevelup.com/thumb/${bt.share_token}`),he(bt.title||"Watch the video"))},us=l==="mobile"?390:"100%",zt=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(U,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("bold"),title:"Bold",children:e.jsx(wA,{className:"h-3.5 w-3.5"})}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("italic"),title:"Italic",children:e.jsx(kA,{className:"h-3.5 w-3.5"})}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("underline"),title:"Underline",children:e.jsx(UF,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("insertUnorderedList"),title:"Bullet list",children:e.jsx(m0,{className:"h-3.5 w-3.5"})}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("insertOrderedList"),title:"Numbered list",children:e.jsx(sj,{className:"h-3.5 w-3.5"})}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:N,title:"Insert link",children:e.jsx(Rc,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("undo"),title:"Undo",children:e.jsx(RA,{className:"h-3.5 w-3.5"})}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("redo"),title:"Redo",children:e.jsx(LA,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsxs(U,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert CTA Button",children:[e.jsx(Ch,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"CTA Button"})]})}),e.jsxs(Eu,{align:"start",className:"w-56 bg-popover z-50",children:[e.jsx(DV,{children:"Insert a call-to-action"}),e.jsx(l1,{}),DAn.map(bt=>{const As=bt.icon;return e.jsxs(La,{onClick:()=>Q(bt),children:[e.jsx(As,{className:"h-4 w-4 mr-2"}),bt.label]},bt.key)})]})]}),e.jsxs(U,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert image",onClick:tt,children:[e.jsx(pc,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"Image"})]}),e.jsxs(U,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert video block",onClick:Me,children:[e.jsx(Wr,{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(Uq,{type:"single",value:l,onValueChange:bt=>bt&&o(bt),size:"sm",className:"h-7",children:[e.jsx(JF,{value:"desktop",className:"h-7 px-2",title:"Desktop preview",children:e.jsx(X2,{className:"h-3.5 w-3.5"})}),e.jsx(JF,{value:"mobile",className:"h-7 px-2",title:"Mobile preview",children:e.jsx(i1,{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(Ch,{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:us,maxWidth:zt,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(Ds,{className:"sm:max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Edit link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"link-edit-text",children:"Button / link text"}),e.jsx(xe,{id:"link-edit-text",value:p,onChange:bt=>f(bt.target.value),placeholder:"Click here"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"link-edit-href",children:"Where should this link go?"}),e.jsx(xe,{id:"link-edit-href",value:h,onChange:bt=>m(bt.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(Mr,{children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsx(U,{type:"button",onClick:v,disabled:!h.trim(),children:"Save link"})]})]})}),e.jsx(zs,{open:A,onOpenChange:T,children:e.jsxs(Ds,{className:"sm:max-w-md",children:[e.jsx(Vs,{children:e.jsxs($s,{children:["Insert ",(L==null?void 0:L.label)||"CTA Button"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"cta-text",children:"Button text"}),e.jsx(xe,{id:"cta-text",value:I,onChange:bt=>R(bt.target.value),placeholder:L==null?void 0:L.defaultText})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"cta-value",children:L==null?void 0:L.helper}),e.jsx(xe,{id:"cta-value",value:z,onChange:bt=>$(bt.target.value),placeholder:L==null?void 0:L.placeholder,autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"cta-color",children:"Button color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{id:"cta-color",type:"color",value:H,onChange:bt=>V(bt.target.value),className:"h-9 w-16 p-1 cursor-pointer"}),e.jsx(xe,{value:H,onChange:bt=>V(bt.target.value),className:"flex-1"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Position"}),e.jsxs(y_,{value:K,onValueChange:bt=>Z(bt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fh,{value:"cursor",id:"cta-cursor"}),e.jsxs(te,{htmlFor:"cta-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Ch,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fh,{value:"top",id:"cta-top"}),e.jsxs(te,{htmlFor:"cta-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(cp,{className:"h-3.5 w-3.5"}),"Top of newsletter"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fh,{value:"bottom",id:"cta-bottom"}),e.jsxs(te,{htmlFor:"cta-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(ag,{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:H,color:"#ffffff",borderRadius:6,padding:"14px 28px",fontFamily:"Arial, sans-serif",fontWeight:600,fontSize:16},children:I||(L==null?void 0:L.defaultText)})})]}),e.jsxs(Mr,{children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>T(!1),children:"Cancel"}),e.jsx(U,{type:"button",onClick:le,disabled:!(L!=null&&L.isForward)&&!z.trim(),children:"Insert Button"})]})]})}),e.jsx(zs,{open:ue,onOpenChange:se,children:e.jsxs(Ds,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Insert Video Block"})}),e.jsxs(oa,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(la,{className:"grid w-full grid-cols-3",children:[e.jsx(Kt,{value:"library",children:"My Library"}),e.jsx(Kt,{value:"url",children:"From URL"}),e.jsx(Kt,{value:"record",children:"Record New"})]}),e.jsxs(Zt,{value:"library",className:"space-y-3 mt-2",children:[Ut?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground",children:[e.jsx(Et,{className:"h-5 w-5 animate-spin mx-auto mb-2"}),"Loading your videos..."]}):!qt||qt.length===0?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground border rounded-md",children:[e.jsx(Wr,{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:qt.map(bt=>{const As=ne.includes(bt.share_token||"___"),vt=bt.share_token?`https://video.relevelup.com/thumb/${bt.share_token}`:bt.thumbnail_url||"";return e.jsxs("button",{type:"button",onClick:()=>Wt(bt),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:[vt?e.jsx("img",{src:vt,alt:bt.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(Wr,{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(lu,{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:bt.title||"Untitled"})})]},bt.id)})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"vid-title-lib",className:"text-xs",children:"Caption (optional)"}),e.jsx(xe,{id:"vid-title-lib",value:be,onChange:bt=>he(bt.target.value),placeholder:"Watch the video"})]})]}),e.jsxs(Zt,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"vid-url",children:"Video URL"}),e.jsx(xe,{id:"vid-url",value:ne,onChange:bt=>ie(bt.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(te,{htmlFor:"vid-title",children:"Caption (optional)"}),e.jsx(xe,{id:"vid-title",value:be,onChange:bt=>he(bt.target.value),placeholder:"Watch the video"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"vid-thumb",children:"Custom thumbnail URL (optional)"}),e.jsx(xe,{id:"vid-thumb",value:ce,onChange:bt=>je(bt.target.value),placeholder:"https://... (only if not YouTube/Vimeo)"})]})]}),e.jsx(Zt,{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(Wr,{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(U,{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(te,{children:"Position"}),e.jsxs(y_,{value:ge,onValueChange:bt=>ke(bt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fh,{value:"cursor",id:"vid-cursor"}),e.jsxs(te,{htmlFor:"vid-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Ch,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fh,{value:"top",id:"vid-top"}),e.jsxs(te,{htmlFor:"vid-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(cp,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fh,{value:"bottom",id:"vid-bottom"}),e.jsxs(te,{htmlFor:"vid-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(ag,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]}),Te&&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:Te,alt:"thumbnail",className:"w-full rounded-md",style:{maxHeight:180,objectFit:"cover"},onError:bt=>{bt.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(Mr,{children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>se(!1),children:"Cancel"}),e.jsx(U,{type:"button",onClick:Oe,disabled:!ne.trim(),children:"Insert Video"})]})]})}),e.jsx(zs,{open:Se,onOpenChange:Qe,children:e.jsxs(Ds,{className:"sm:max-w-md max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Insert Image"})}),e.jsxs(oa,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(la,{className:"grid w-full grid-cols-3",children:[e.jsx(Kt,{value:"library",children:"Library"}),e.jsx(Kt,{value:"upload",children:"Upload"}),e.jsx(Kt,{value:"url",children:"From URL"})]}),e.jsx(Zt,{value:"library",className:"mt-2",children:e.jsx(oGt,{maxHeight:"380px",onSelect:bt=>{Fe(bt.image_url),Ne||$e(bt.title)}})}),e.jsxs(Zt,{value:"upload",className:"space-y-3 mt-2",children:[e.jsx("input",{ref:He,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:bt=>{var vt;const As=(vt=bt.target.files)==null?void 0:vt[0];As&&pt(As),bt.target.value=""}}),Ae?e.jsxs("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:[e.jsx("img",{src:Ae,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(U,{type:"button",variant:"ghost",size:"sm",onClick:()=>Fe(""),children:"Replace"})]})]}):e.jsx("button",{type:"button",onClick:()=>{var bt;return(bt=He.current)==null?void 0:bt.click()},disabled:Ye,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:Ye?e.jsxs(e.Fragment,{children:[e.jsx(Et,{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(qa,{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(Zt,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"img-url",children:"Image URL"}),e.jsx(xe,{id:"img-url",value:Ae,onChange:bt=>Fe(bt.target.value),placeholder:"https://..."})]}),Ae&&/^https?:\/\//i.test(Ae)&&e.jsx("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:e.jsx("img",{src:Ae,alt:"Preview",className:"w-full max-h-48 object-contain",onError:bt=>{bt.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(te,{htmlFor:"img-alt",children:"Alt text (for accessibility)"}),e.jsx(xe,{id:"img-alt",value:Ne,onChange:bt=>$e(bt.target.value),placeholder:"Describe the image"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Size"}),e.jsxs(y_,{value:Ve,onValueChange:bt=>qe(bt),className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fh,{value:"full",id:"img-full"}),e.jsx(te,{htmlFor:"img-full",className:"cursor-pointer font-normal",children:"Full width"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fh,{value:"half",id:"img-half"}),e.jsx(te,{htmlFor:"img-half",className:"cursor-pointer font-normal",children:"Half width"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Position"}),e.jsxs(y_,{value:Ze,onValueChange:bt=>Ue(bt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fh,{value:"cursor",id:"img-cursor"}),e.jsxs(te,{htmlFor:"img-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Ch,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fh,{value:"top",id:"img-top"}),e.jsxs(te,{htmlFor:"img-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(cp,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Fh,{value:"bottom",id:"img-bottom"}),e.jsxs(te,{htmlFor:"img-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(ag,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>Qe(!1),children:"Cancel"}),e.jsx(U,{type:"button",onClick:ft,disabled:!Ae.trim()||Ye,children:"Insert Image"})]})]})})]})}const w_t="newsletter-content",FAn="inline-images";function zAn(s,t){const n=atob(s),r=new Array(n.length);for(let a=0;a{const{data:M}=await q.from("team_members").select("team_id, role").eq("user_id",a.id).maybeSingle();return M}}),A=(S==null?void 0:S.role)==="team_leader",T=(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)??""),p((n==null?void 0:n.html_content)??qAn()),x((n==null?void 0:n.is_template)??!1),v((n==null?void 0:n.share_scope)??"private"))},[s,n]);const L=async()=>{if(a){if(!c.trim()){re.error("Please enter a title");return}if(!m.trim()){re.error("Newsletter content is empty");return}N(!0);try{const M=await BAn(m);M!==m&&p(M);const I={user_id:a.id,title:c.trim(),description:u.trim()||null,html_content:M,is_template:f,share_scope:y,shared_team_id:y==="team"?T:null,shared_brokerage_id:y==="brokerage"?o:null};if(y==="team"&&!T){re.error("You must be a team leader to share with a team"),N(!1);return}if(y==="brokerage"&&!l){re.error("Only brokerage managers can share to a brokerage"),N(!1);return}if(y==="global"&&!i){re.error("Only admins can publish global starter templates"),N(!1);return}let R;if(n!=null&&n.id?{error:R}=await q.from("agent_custom_newsletters").update(I).eq("id",n.id):{error:R}=await q.from("agent_custom_newsletters").insert(I),R)throw R;re.success(n!=null&&n.id?"Saved":"Newsletter created"),r==null||r(),t(!1)}catch(M){re.error(M.message||"Failed to save")}finally{N(!1)}}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-6xl h-[92vh] flex flex-col p-0",children:[e.jsx(Vs,{className:"px-6 pt-6 pb-3 border-b",children:e.jsx($s,{children:n!=null&&n.id?"Edit Newsletter":"Create Newsletter"})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-4 space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(te,{htmlFor:"acn-title",children:"Title *"}),e.jsx(xe,{id:"acn-title",value:c,onChange:M=>d(M.target.value),placeholder:"e.g. June Market Update"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"acn-desc",children:"Description (optional)"}),e.jsx(xe,{id:"acn-desc",value:u,onChange:M=>h(M.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(wn,{id:"acn-template",checked:f,onCheckedChange:x}),e.jsx(te,{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(te,{className:"text-sm font-semibold",children:"Sharing"}),e.jsxs(y_,{value:y,onValueChange:M=>v(M),className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Fh,{value:"private",id:"s-private",className:"mt-0.5"}),e.jsxs(te,{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(Fh,{value:"team",id:"s-team",className:"mt-0.5"}),e.jsxs(te,{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(Fh,{value:"brokerage",id:"s-brokerage",className:"mt-0.5"}),e.jsxs(te,{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(Fh,{value:"global",id:"s-global",className:"mt-0.5"}),e.jsxs(te,{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(te,{className:"mb-2 block",children:"Content"}),e.jsx(lGt,{html:m,onChange:p})]})]}),e.jsxs(Mr,{className:"px-6 py-3 border-t",children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),disabled:b,children:"Cancel"}),e.jsxs(U,{onClick:L,disabled:b,children:[b?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-2"}),n!=null&&n.id?"Save Changes":"Create"]})]})]})})}function qAn(){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 Ttt=/\[[^\]\[<>]{2,80}\]/g,$An=/^\[\s*(?:\/?\s*if\b[^\]]*|endif|else|x-apple-[\w-]*|data-[\w-]*|object [^\]]*|cdata[^\]]*)\s*\]$/i;function Mtt(s){return!$An.test(s)}function VAn(s){return(s.match(Ttt)||[]).filter(Mtt)}function j_t(s){const t=s.toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function HAn(s){const t=[],n=new RegExp(Ttt.source,"g");let r;for(;(r=n.exec(s))!==null;)Mtt(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 · ${j_t(h)}`:`Date ${i[l.token]}`:(m=j_t(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 GAn({html:s,onChange:t,originalHtml:n}){const r=j.useMemo(()=>HAn(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(Ttt.source,"g");let b=0;const N=s.replace(v,S=>{if(!Mtt(S))return S;const A=(a[b]||"").trim();return b+=1,A||S});N!==s&&(o(S=>[...S,{html:s,values:a}]),d.current=!0,i({}),t(N))},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))},p=l.length>0,f=!!c.current&&c.current!==s,x=e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(U,{type:"button",size:"sm",variant:"outline",onClick:h,disabled:!p,children:[e.jsx(pQ,{className:"h-3.5 w-3.5 mr-1"}),"Undo last fill"]}),e.jsxs(U,{type:"button",size:"sm",variant:"ghost",onClick:m,disabled:!f,children:[e.jsx(Kg,{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(zr,{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."})]}),(p||f)&&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(tc,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-semibold",children:"Customize before you send"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["This template has ",r.length," field",r.length===1?"":"s"," that only you can fill in (local dates, events, favorite spots). Sending is locked until they're done."]})]})]}),e.jsxs(Be,{variant:"secondary",className:"shrink-0",children:[y,"/",r.length," ready"]})]}),e.jsx("div",{className:"grid grid-cols-1 gap-4",children:r.map(v=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:v.label}),e.jsx(xe,{value:a[v.index]||"",placeholder:v.hint,className:"h-10 text-sm",onChange:b=>i(N=>({...N,[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(U,{type:"button",size:"sm",onClick:u,children:[e.jsx(lq,{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 ZG(){const s=Sa();return ct({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 WAn(s){return ct({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 Ptt(){const s=Qt(),t=Sa();return yt({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 KAn(){const s=Qt();return yt({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 YAn(){const s=Qt();return yt({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 cGt(){const s=Qt();return yt({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 ZAn(){const s=Qt();return yt({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 DLe(){const s=Sa();return ct({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 Ltt(){const{user:s}=vs();return ct({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 dGt(){const s=Qt(),{user:t}=vs();return yt({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"]}),ka({title:"Smart filter saved"})},onError:n=>{ka({title:"Error saving smart filter",description:n.message,variant:"destructive"})}})}function uGt(){const s=Qt();return yt({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"]}),ka({title:"Smart filter deleted"})}})}const N_t=s=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""");function k_t(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(p=>p[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,(p,f)=>m[f]??`{{${f}}}`)}function XAn(s,t,n,r){const a=t.trim()?`
${N_t(t).replace(/\n/g,"
")}
`:"",i=n.trim()?`
${N_t(n).replace(/\n/g,"
")}
`:"",l=r?`
${r}
`:"";return`${a} ${s} ${i} ${l}`}function QAn(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 JAn=["free","act now","click here","limited time","urgent","$$$","100% free","guarantee","no obligation","risk-free","winner","cash bonus","make money","earn extra","amazing"];function eEn(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=JAn.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 Itt({open:s,onOpenChange:t,newsletterId:n,newsletterTitle:r,htmlCode:a}){const{user:i}=vs();Ax();const{isReady:l,settings:o}=AG(),{data:c}=dre(),[d,u]=j.useState(!1),h=Sa(),{data:m}=ct({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:sn}=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 sn}}),[p,f]=j.useState("visual"),[x,y]=j.useState("all"),[v,b]=j.useState(""),[N,S]=j.useState(""),[A,T]=j.useState(""),[L,M]=j.useState(""),[I,R]=j.useState(!0),[z,$]=j.useState([]),[H,V]=j.useState(null),[K,Z]=j.useState(new Set),[Q,le]=j.useState(""),[ue,se]=j.useState(!1),[ne,ie]=j.useState(!1),[ce,je]=j.useState(!1),[be,he]=j.useState({sent:0,failed:0,total:0,currentName:""}),[ge,ke]=j.useState(!0),[Te,Me]=j.useState(!1),[Oe,Se]=j.useState([]),[Qe,Ae]=j.useState(!1),[Fe,Ne]=j.useState(new Set),[$e,Ve]=j.useState("now"),[qe,Ze]=j.useState(""),{data:Ue=[]}=ZG(),{data:Ye=[]}=DLe(),{data:Ge=[]}=Ltt(),{data:He=[],isLoading:tt}=ct({queryKey:["newsletter-send-contacts",h],enabled:!!h&&s,queryFn:async()=>{const sn=[];let un=0;const Ar=1e3;for(;;){const{data:fs,error:ot}=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(un,un+Ar-1);if(ot)throw ot;if(!fs||fs.length===0||(sn.push(...fs),fs.length{const{data:sn}=await q.from("ses_suppressed_emails").select("email");return(sn||[]).map(un=>un.email.toLowerCase())}}),{data:ft}=ct({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:sn}=await q.from("profiles").select("brokerage_id").eq("id",i.id).maybeSingle();if(!(sn!=null&&sn.brokerage_id))return null;const{data:un}=await q.from("brokerages").select("name, city, state").eq("id",sn.brokerage_id).maybeSingle();return un}}),{data:qt}=ct({queryKey:["newsletter-active-lead-site",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{if(!h)return null;const{data:sn}=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 sn}}),Ut=!!(qt!=null&&qt.mls_provider_id),Wt=(qt==null?void 0:qt.mls_agent_id)||(qt==null?void 0:qt.mls_agent_key)||null,{data:us=[],isLoading:zt}=ct({queryKey:["newsletter-agent-listings",h,Wt],enabled:!!h&&!!Wt&&Qe,staleTime:60*1e3,queryFn:async()=>{if(!Wt)return[];const{data:sn}=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",Wt).eq("standard_status","Active").order("modification_timestamp",{ascending:!1}).limit(30);return sn||[]}}),{data:bt=[],isLoading:As}=ct({queryKey:["newsletter-exchange-listings",h],enabled:!!h&&Qe,staleTime:60*1e3,queryFn:async()=>{const{data:sn}=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),un=sn||[];if(un.length===0)return[];const Ar=un.map(Nt=>Nt.id),{data:fs}=await q.from("listing_photos").select("listing_id, photo_url, is_primary, sort_order").in("listing_id",Ar),ot=new Map,mt=new Map;for(const Nt of fs||[])Nt.is_primary&&!ot.has(Nt.listing_id)&&ot.set(Nt.listing_id,Nt.photo_url),mt.has(Nt.listing_id)||mt.set(Nt.listing_id,Nt.photo_url);return un.map(Nt=>({...Nt,_photo:ot.get(Nt.id)||mt.get(Nt.id)||""}))}}),{data:vt=!1}=ct({queryKey:["newsletter-exchange-listings-exists",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{const{count:sn}=await q.from("listings").select("id",{count:"exact",head:!0}).eq("agent_id",h).in("status",["active","coming_soon","office_exclusive","pre_market"]);return(sn||0)>0}}),Ws=j.useMemo(()=>{const sn=new Set(pt);return He.filter(un=>un.email&&un.email.includes("@")&&!sn.has(un.email.toLowerCase()))},[He,pt]),on=j.useMemo(()=>{if(z.length===0)return null;const sn=new Set;for(const un of Ye)z.includes(un.tag_id)&&sn.add(un.contact_id);return sn},[Ye,z]),Ms=j.useMemo(()=>Ge.find(sn=>sn.id===H)||null,[Ge,H]),dn=j.useMemo(()=>{var sn;if(x==="all")return Ws;if(x==="tags")return on?Ws.filter(un=>on.has(un.id)):[];if(x==="smartlists"){if(!Ms)return[];const un=(((sn=Ms.filters)==null?void 0:sn.search)||"").toLowerCase().trim();return un?Ws.filter(Ar=>`${Ar.first_name||""} ${Ar.last_name||""}`.toLowerCase().includes(un)||(Ar.email||"").toLowerCase().includes(un)):Ws}return Ws.filter(un=>K.has(un.id))},[x,Ws,on,Ms,K]),rn=j.useMemo(()=>{if(!Q.trim())return Ws;const sn=Q.toLowerCase();return Ws.filter(un=>`${un.first_name||""} ${un.last_name||""}`.toLowerCase().includes(sn))},[Ws,Q]);j.useEffect(()=>{s&&(b(""),S(`Hi {{first_name}}, Sharing this month's update — hope you find something useful!`),T(`As always, reach out anytime if I can help. Talk soon!`),M(a||""),f("light"),y("all"),$([]),V(null),Z(new Set),le(""),se(!1),R(!0),ke(!0),Se([]),Ve("now"),Ze(""),he({sent:0,failed:0,total:0,currentName:""}))},[s,r,a]);const br=l,Gn=j.useMemo(()=>VAn(L||a||""),[L,a]),On=!!(v.trim()&&br&&dn.length>0&&!ne&&Gn.length===0),Rr=sn=>{const un=L||a,Ar=I&&(m!=null&&m.email_signature)?m.email_signature:null;let fs;return p==="light"?fs=XAn(un,N,A,Ar):fs=Ar?`${un}
${Ar}
`:un,ge&&(fs+=QAn(m??null,ft??null,sn.email)),k_t(fs,sn,m??null,(ft==null?void 0:ft.name)??null)},cr=j.useMemo(()=>Rr({first_name:"Friend",last_name:"",email:"preview@example.com",phone:"",address:"",city:"",state:"",zip:""}),[p,N,A,L,a,I,m,ge,ft]),Hs=j.useMemo(()=>eEn(v,p==="advanced"||p==="visual"?L:a),[v,p,L,a]),_r=async()=>{Me(!0),Se([]);try{const sn=p==="advanced"||p==="visual"?L:a,{data:un,error:Ar}=await q.functions.invoke("generate-newsletter-subjects",{body:{newsletterTitle:r,bodyHtml:sn,currentSubject:v}});if(Ar)throw Ar;const fs=un==null?void 0:un.subjects;if(!Array.isArray(fs)||fs.length===0)throw new Error("No subjects returned");Se(fs)}catch(sn){const un=(sn==null?void 0:sn.message)||"Failed to generate subjects";un.includes("credits exhausted")||un.includes("402")?re.error("AI credits exhausted. Please add credits to your workspace."):un.includes("Rate limit")||un.includes("429")?re.error("Rate limit hit — try again in a moment."):re.error(un)}finally{Me(!1)}},nn=sn=>sn?"$"+Number(sn).toLocaleString("en-US"):"",Zn=()=>{var mt,Nt;if(Fe.size===0){re.error("Pick at least one listing first.");return}const sn=(qt==null?void 0:qt.subdomain_slug)||"",un=sn?`https://${sn}.relevelup.com`:"https://relevelup.com",Ar=[];for(const Pt of us){const ts=`mls:${Pt.listing_key}`;if(!Fe.has(ts))continue;const ls=Array.isArray(Pt.photos)&&Pt.photos.length>0?typeof Pt.photos[0]=="string"?Pt.photos[0]:((mt=Pt.photos[0])==null?void 0:mt.MediaURL)||((Nt=Pt.photos[0])==null?void 0:Nt.url)||"":"",Is=Pt.bedrooms?`${Pt.bedrooms} bd`:"",ps=Pt.bathrooms_total?`${Pt.bathrooms_total} ba`:"",Ht=Pt.living_area?`${Number(Pt.living_area).toLocaleString()} sqft`:"";Ar.push({url:`${un}/listings/${Pt.listing_key}`,photo:ls,price:nn(Pt.list_price),addr:`${Pt.address||""}${Pt.city?", "+Pt.city:""}`,stats:[Is,ps,Ht].filter(Boolean).join(" • ")})}for(const Pt of bt){const ts=`ex:${Pt.id}`;if(!Fe.has(ts))continue;const ls=Pt.bedrooms?`${Pt.bedrooms} bd`:"",Is=Pt.bathrooms?`${Pt.bathrooms} ba`:"",ps=Pt.square_footage?`${Number(Pt.square_footage).toLocaleString()} sqft`:"";Ar.push({url:`https://listings.relevelup.com/${Pt.slug||Pt.id}`,photo:Pt._photo||"",price:nn(Pt.price),addr:`${Pt.property_address||""}${Pt.city?", "+Pt.city:""}`,stats:[ls,Is,ps].filter(Boolean).join(" • ")})}const ot=`

Featured Listings

${Ar.map(Pt=>`
${Pt.photo?`${Pt.addr}`:""}
${Pt.price}
${Pt.addr}
${Pt.stats}
`.trim()).join(` `)}
`.trim();M(Pt=>(Pt||a||"")+` `+ot),f("visual"),Ne(new Set),Ae(!1),re.success(`Added ${Ar.length} listing${Ar.length===1?"":"s"} to your newsletter.`)},es=()=>Rr({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}}"),ar=()=>k_t(v,{first_name:"__FN__",last_name:"__LN__",email:"__EM__",name:"__NAME__",phone:"__PHONE__",address:"__ADDR__",city:"__CITY__",state:"__STATE__",zip:"__ZIP__"},m??null,(ft==null?void 0:ft.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}}"),Hn=()=>{if(Gn.length>0){re.error(`Fill in ${Gn.length} template field${Gn.length===1?"":"s"} before sending.`);return}if(On){if($e==="later"){if(!qe){re.error("Pick a date and time to schedule.");return}const sn=new Date(qe).getTime();if(Number.isNaN(sn)||sn{if(!(!On||!i)){je(!1),ie(!0),he({sent:0,failed:0,total:dn.length,currentName:"Preparing campaign…"});try{const un=`${((o==null?void 0:o.display_name)||"ReLevelUp").toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,Ar=es(),fs=ar(),ot=$e==="later",{data:mt,error:Nt}=await q.from("email_campaigns").insert({user_id:h||i.id,name:`Newsletter: ${r}`,subject:fs,body_html:Ar,from_email:un,reply_to_email:(o==null?void 0:o.reply_to_email)||null,total_recipients:dn.length,status:ot?"scheduled":"draft",scheduled_at:ot?new Date(qe).toISOString():null}).select("id").single();if(Nt)throw Nt;he(ts=>({...ts,currentName:"Adding recipients…"}));const Pt=dn.map(ts=>({campaign_id:mt.id,contact_id:ts.id,email:ts.email,name:[ts.first_name,ts.last_name].filter(Boolean).join(" ")||null,status:"pending"}));for(let ts=0;ts({...ps,sent:Math.min(ts+ls.length,Pt.length)}))}if(ot){const{error:ts}=await q.functions.invoke("ses-schedule-campaign",{body:{action:"schedule",campaign_id:mt.id}});if(ts)throw ts;re.success(`Newsletter scheduled for ${new Date(qe).toLocaleString()}.`)}else{const{error:ts}=await q.functions.invoke("ses-send-campaign",{body:{action:"send_campaign",campaign_id:mt.id}});if(ts)throw ts;re.success(`Sending to ${dn.length} contact${dn.length===1?"":"s"}! Open & click tracking will appear in Sent Emails.`)}t(!1)}catch(sn){console.error("Newsletter send failed:",sn),re.error(`Failed to send: ${sn.message||"Unknown error"}`)}finally{ie(!1)}}},Un=sn=>{Z(un=>{const Ar=new Set(un);return Ar.has(sn)?Ar.delete(sn):Ar.add(sn),Ar})};return e.jsxs(zs,{open:s,onOpenChange:sn=>!ne&&t(sn),children:[e.jsxs(Ds,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx($r,{className:"h-5 w-5"})," Send Newsletter"]})}),!br&&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(Vo,{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(U,{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(te,{children:"Subject"}),e.jsxs(U,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1 text-xs",onClick:_r,disabled:Te,title:"Generate subject lines with AI",children:[Te?e.jsx(Et,{className:"h-3 w-3 animate-spin"}):e.jsx(cn,{className:"h-3 w-3"}),"AI Suggestions"]})]}),e.jsx(xe,{value:v,onChange:sn=>b(sn.target.value),placeholder:"Newsletter subject"}),Oe.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:"}),Oe.map((sn,un)=>e.jsxs("button",{type:"button",onClick:()=>{b(sn),Se([])},className:"w-full text-left text-sm px-2 py-1.5 rounded hover:bg-primary/10 transition-colors",children:[e.jsx(cn,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),sn]},un))]}),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}}"})]})]}),Hs.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(fq,{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:Hs.map((sn,un)=>e.jsx("li",{children:sn},un))})]}),(Ut||vt)&&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(ra,{className:"h-3.5 w-3.5 text-primary"}),"Insert your active listings"]}),e.jsx("p",{className:"text-muted-foreground mt-0.5",children:Ut&&vt?"Pick from your live MLS listings or your Listing Exchange listings.":Ut?"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(U,{type:"button",size:"sm",variant:"outline",onClick:()=>Ae(!0),children:"Choose listings"})]}),e.jsx(GAn,{html:L||a||"",originalHtml:a||"",onChange:M}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Editing"}),e.jsxs(oa,{value:p,onValueChange:sn=>f(sn),children:[e.jsxs(la,{className:"grid grid-cols-3 w-full",children:[e.jsxs(Kt,{value:"visual",children:[e.jsx(Lg,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Kt,{value:"light",children:[e.jsx(Ur,{className:"h-3 w-3 mr-1"}),"Quick edit"]}),e.jsxs(Kt,{value:"advanced",children:[e.jsx(PC,{className:"h-3 w-3 mr-1"}),"HTML"]})]}),e.jsx(Zt,{value:"visual",className:"mt-3",children:e.jsx(lGt,{html:L,onChange:M})}),e.jsxs(Zt,{value:"light",className:"space-y-3 mt-3",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-muted-foreground",children:"Personal intro (above newsletter)"}),e.jsx(Fs,{value:N,onChange:sn=>S(sn.target.value),rows:4,placeholder:"Hi {{first_name}}, ..."})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-muted-foreground",children:"Personal outro (below newsletter)"}),e.jsx(Fs,{value:A,onChange:sn=>T(sn.target.value),rows:3,placeholder:"Talk soon!"})]})]}),e.jsxs(Zt,{value:"advanced",className:"mt-3",children:[e.jsx(te,{className:"text-xs text-muted-foreground",children:"Edit full HTML"}),e.jsx(Fs,{value:L,onChange:sn=>M(sn.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(wn,{checked:I&&!!(m!=null&&m.email_signature),disabled:!(m!=null&&m.email_signature),onCheckedChange:R})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Include unsubscribe footer"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Adds your brokerage info and a one-click unsubscribe link. Strongly recommended for deliverability."})]}),e.jsx(wn,{checked:ge,onCheckedChange:ke})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Recipients"}),e.jsxs(oa,{value:x,onValueChange:sn=>y(sn),children:[e.jsxs(la,{className:"grid grid-cols-4 w-full",children:[e.jsxs(Kt,{value:"all",children:[e.jsx(Bn,{className:"h-3 w-3 mr-1"}),"All"]}),e.jsxs(Kt,{value:"tags",children:[e.jsx(Cf,{className:"h-3 w-3 mr-1"}),"Tags"]}),e.jsxs(Kt,{value:"smartlists",children:[e.jsx(HX,{className:"h-3 w-3 mr-1"}),"Lists"]}),e.jsxs(Kt,{value:"individual",children:[e.jsx(So,{className:"h-3 w-3 mr-1"}),"Pick"]})]}),e.jsx(Zt,{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:Ws.length})," contact",Ws.length===1?"":"s"," with a valid, non-suppressed email."]})}),e.jsxs(Zt,{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(Gi,{className:"h-40 rounded-lg border p-2",children:Ue.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."}):Ue.map(sn=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(xi,{checked:z.includes(sn.id),onCheckedChange:un=>$(Ar=>un?[...Ar,sn.id]:Ar.filter(fs=>fs!==sn.id))}),e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{background:sn.color||"#406E71"}}),e.jsx("span",{className:"text-sm",children:sn.name})]},sn.id))})]}),e.jsxs(Zt,{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(Gi,{className:"h-40 rounded-lg border p-2",children:Ge.length===0?e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No smart lists yet. Save one from the contacts page."}):Ge.map(sn=>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:H===sn.id,onChange:()=>V(sn.id)}),e.jsx("span",{className:"text-sm",children:sn.name})]},sn.id))})]}),e.jsxs(Zt,{value:"individual",className:"mt-3 space-y-2",children:[e.jsx(xe,{placeholder:"Search contacts...",value:Q,onChange:sn=>le(sn.target.value)}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[K.size," selected"]}),e.jsx("button",{type:"button",className:"underline",onClick:()=>Z(new Set),children:"Clear"})]}),e.jsxs(Gi,{className:"h-48 rounded-lg border p-2",children:[tt&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"Loading contacts…"}),!tt&&rn.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No matching contacts."}),rn.slice(0,200).map(sn=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(xi,{checked:K.has(sn.id),onCheckedChange:()=>Un(sn.id)}),e.jsxs("div",{className:"text-sm flex-1 min-w-0",children:[e.jsxs("div",{className:"truncate",children:[sn.first_name," ",sn.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:sn.email})]})]},sn.id)),rn.length>200&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"Showing first 200 — refine search to see more."})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(zr,{className:"h-3 w-3"})," ",dn.length," recipient",dn.length===1?"":"s"]}),br&&e.jsxs(Be,{variant:"outline",className:"gap-1 text-xs",children:["via Mass Email",o!=null&&o.reply_to_email?` (${o.reply_to_email})`:""]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{children:"Preview"}),e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>se(sn=>!sn),children:ue?e.jsxs(e.Fragment,{children:[e.jsx(Vg,{className:"h-3 w-3 mr-1"}),"Hide"]}):e.jsxs(e.Fragment,{children:[e.jsx(xa,{className:"h-3 w-3 mr-1"}),"Show"]})})]}),ue?e.jsx("div",{className:"rounded-lg border overflow-hidden bg-white",children:e.jsx("iframe",{title:"newsletter-preview",srcDoc:cr,className:"w-full h-[560px] bg-white",sandbox:""})}):e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-6 text-center text-sm text-muted-foreground",children:["Click ",e.jsx("strong",{children:"Show"})," to preview how the email looks. Merge tags use sample data (Friend)."]})]})]}),ne&&e.jsxs("div",{className:"space-y-2 rounded-lg border p-3 bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Et,{className:"h-4 w-4 animate-spin"}),"Sending to ",be.currentName||"..."]}),e.jsxs("span",{className:"text-muted-foreground",children:[be.sent+be.failed," / ",be.total]})]}),e.jsx(ro,{value:be.total?(be.sent+be.failed)/be.total*100:0}),be.failed>0&&e.jsxs("p",{className:"text-xs text-destructive",children:[be.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(Yr,{className:"h-4 w-4"})," When to send"]}),e.jsxs(y_,{value:$e,onValueChange:sn=>Ve(sn),className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Fh,{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(Fh,{value:"later",id:"send-later"}),e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(ch,{className:"h-3.5 w-3.5"})," Schedule for later"]})]}),$e==="later"&&e.jsx(xe,{type:"datetime-local",value:qe,onChange:sn=>Ze(sn.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:Gn.length>0?`${Gn.length} template field${Gn.length===1?"":"s"} still need${Gn.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(U,{variant:"outline",onClick:()=>t(!1),disabled:ne,children:"Cancel"}),e.jsx(U,{onClick:Hn,disabled:!On,children:ne?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}),"Working…"]}):$e==="later"?e.jsxs(e.Fragment,{children:[e.jsx(ch,{className:"h-4 w-4 mr-1"}),"Schedule for ",dn.length]}):e.jsxs(e.Fragment,{children:[e.jsx($r,{className:"h-4 w-4 mr-1"}),"Send to ",dn.length]})})]})]})]})]}),e.jsx(Fl,{open:ce,onOpenChange:je,children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:$e==="later"?"Schedule newsletter?":"Send newsletter?"}),e.jsxs(Ll,{children:[$e==="later"?"Schedule ":"Send ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',v,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[dn.length," contact",dn.length===1?"":"s"]}),$e==="later"&&qe?` for ${new Date(qe).toLocaleString()}`:"","? Suppressed and unsubscribed contacts are skipped automatically."]})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:kn,children:$e==="later"?e.jsxs(e.Fragment,{children:[e.jsx(ch,{className:"h-4 w-4 mr-1"}),"Schedule"]}):e.jsxs(e.Fragment,{children:[e.jsx($r,{className:"h-4 w-4 mr-1"}),"Send to ",dn.length]})})]})]})}),e.jsx(zs,{open:Qe,onOpenChange:Ae,children:e.jsxs(Ds,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(ra,{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."}),(zt||As)&&e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center",children:[e.jsx(Et,{className:"h-4 w-4 animate-spin inline-block mr-2"}),"Loading your listings…"]}),!zt&&!As&&us.length===0&&bt.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."}),us.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:us.map(sn=>{var ot,mt;const un=`mls:${sn.listing_key}`,Ar=Fe.has(un),fs=Array.isArray(sn.photos)&&sn.photos.length>0?typeof sn.photos[0]=="string"?sn.photos[0]:((ot=sn.photos[0])==null?void 0:ot.MediaURL)||((mt=sn.photos[0])==null?void 0:mt.url)||"":"";return e.jsxs("button",{type:"button",onClick:()=>{Ne(Nt=>{const Pt=new Set(Nt);return Pt.has(un)?Pt.delete(un):Pt.size<6?Pt.add(un):re.error("Max 6 listings per newsletter"),Pt})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${Ar?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[fs&&e.jsx("img",{src:fs,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:sn.list_price?`$${Number(sn.list_price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:sn.address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[sn.city,sn.state?`, ${sn.state}`:""]})]}),Ar&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(zr,{className:"h-4 w-4"})})]},un)})})]}),bt.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:bt.map(sn=>{const un=`ex:${sn.id}`,Ar=Fe.has(un);return e.jsxs("button",{type:"button",onClick:()=>{Ne(fs=>{const ot=new Set(fs);return ot.has(un)?ot.delete(un):ot.size<6?ot.add(un):re.error("Max 6 listings per newsletter"),ot})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${Ar?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[sn._photo&&e.jsx("img",{src:sn._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:sn.price?`$${Number(sn.price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:sn.property_address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[sn.city,sn.state?`, ${sn.state}`:""]})]}),Ar&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(zr,{className:"h-4 w-4"})})]},un)})})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>Ae(!1),children:"Cancel"}),e.jsxs(U,{onClick:Zn,disabled:Fe.size===0,children:["Insert ",Fe.size>0?Fe.size:""," listing",Fe.size===1?"":"s"]})]})]})}),e.jsx(nPe,{open:d,onOpenChange:u,hasPending:!!(c!=null&&c.hasPendingSes),pendingEmails:c==null?void 0:c.pendingEmails})]})}function tEn(){const{user:s}=vs(),t=Qt(),[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:p}=ct({queryKey:["agent-custom-newsletters",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:L,error:M}=await q.from("agent_custom_newsletters").select("*").order("updated_at",{ascending:!1});if(M)throw M;return L||[]}}),f=()=>t.invalidateQueries({queryKey:["agent-custom-newsletters"]}),x=(m==null?void 0:m.filter(L=>L.user_id===(s==null?void 0:s.id)&&!L.is_template))??[],y=(m==null?void 0:m.filter(L=>L.user_id===(s==null?void 0:s.id)&&L.is_template))??[],v=(m==null?void 0:m.filter(L=>L.user_id!==(s==null?void 0:s.id)&&L.is_template&&(L.share_scope==="team"||L.share_scope==="brokerage"||L.share_scope==="global")))??[],b=(m==null?void 0:m.filter(L=>L.share_scope==="global"&&L.is_template))??[],N=n==="starters"?b:n==="mine"?x:n==="templates"?y:v.filter(L=>L.share_scope!=="global"),S=async L=>{if(!s)return;const{error:M}=await q.from("agent_custom_newsletters").insert({user_id:s.id,title:`${L.title} (Copy)`,description:L.description,html_content:L.html_content,is_template:!1,share_scope:"private"});if(M){re.error(M.message);return}re.success('Duplicated to "My Newsletters"'),f(),r("mine")},A=async L=>{const{error:M}=await q.from("agent_custom_newsletters").delete().eq("id",L);if(M){re.error(M.message);return}re.success("Deleted"),h(null),f()},T=L=>L.share_scope==="global"?e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(cn,{className:"h-3 w-3"}),"Starter"]}):L.share_scope==="brokerage"?e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(_i,{className:"h-3 w-3"}),"Brokerage"]}):L.share_scope==="team"?e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Bn,{className:"h-3 w-3"}),"Team"]}):e.jsxs(Be,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(Ql,{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(U,{variant:n==="starters"?"default":"outline",size:"sm",onClick:()=>r("starters"),className:"gap-1.5",children:[e.jsx(cn,{className:"h-3.5 w-3.5"}),"Starter Templates (",b.length,")"]}),e.jsxs(U,{variant:n==="mine"?"default":"outline",size:"sm",onClick:()=>r("mine"),children:["My Newsletters (",x.length,")"]}),e.jsxs(U,{variant:n==="templates"?"default":"outline",size:"sm",onClick:()=>r("templates"),children:["My Templates (",y.length,")"]}),e.jsxs(U,{variant:n==="shared"?"default":"outline",size:"sm",onClick:()=>r("shared"),children:["Shared with Me (",v.filter(L=>L.share_scope!=="global").length,")"]})]}),e.jsxs(U,{onClick:()=>{o(null),i(!0)},children:[e.jsx(an,{className:"h-4 w-4 mr-1.5"})," Create Newsletter"]})]}),p&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((L,M)=>e.jsx(xn,{className:"h-48 w-full"},M))}),n==="starters"&&!p&&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(cn,{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.']})]}),!p&&N.length===0&&e.jsx(we,{children:e.jsxs(Ie,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Ur,{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."})]})}),!p&&N.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:N.map(L=>{const M=L.user_id===(s==null?void 0:s.id);return e.jsxs(we,{className:"overflow-hidden hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"aspect-[3/2] bg-muted relative overflow-hidden",children:[L.thumbnail_url?e.jsx("img",{src:L.thumbnail_url,alt:L.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:`
${L.html_content}
`}}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[L.is_template&&e.jsx(Be,{className:"bg-primary/90",children:"Template"}),T(L)]})]}),e.jsxs(Ie,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:L.title}),L.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:L.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Updated ",Gs(new Date(L.updated_at||L.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[e.jsxs(U,{size:"sm",onClick:()=>d(L),className:"flex-1 min-w-[80px]",children:[e.jsx($r,{className:"h-3.5 w-3.5 mr-1"})," Send"]}),M?e.jsxs(e.Fragment,{children:[e.jsx(U,{size:"sm",variant:"outline",onClick:()=>{o(L),i(!0)},children:e.jsx(ri,{className:"h-3.5 w-3.5"})}),e.jsx(U,{size:"sm",variant:"outline",onClick:()=>S(L),children:e.jsx(Pa,{className:"h-3.5 w-3.5"})}),e.jsx(U,{size:"sm",variant:"outline",onClick:()=>h(L.id),children:e.jsx(In,{className:"h-3.5 w-3.5"})})]}):e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>S(L),children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1"})," Use"]})]})]})]},L.id)})}),e.jsx(UAn,{open:a,onOpenChange:i,initial:l,onSaved:f}),c&&e.jsx(Itt,{open:!!c,onOpenChange:L=>!L&&d(null),newsletterId:c.id,newsletterTitle:c.title,htmlCode:c.html_content}),e.jsx(Fl,{open:!!u,onOpenChange:L=>!L&&h(null),children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Delete this newsletter?"}),e.jsx(Ll,{children:"This cannot be undone."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>u&&A(u),children:"Delete"})]})]})})]})}function sEn(){const s=Wn(),[t,n]=j.useState(""),[r,a]=j.useState("grid"),[i,l]=j.useState(null),{data:o,isLoading:c}=ct({queryKey:["newsletters"],queryFn:async()=>{const{data:A,error:T}=await q.from("newsletter_content").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(T)throw T;return A}}),{data:d}=ct({queryKey:["newsletter-likes-all"],queryFn:async()=>{const{data:A}=await q.from("newsletter_likes").select("newsletter_id");return A||[]}}),{data:u}=ct({queryKey:["newsletter-comments-all"],queryFn:async()=>{const{data:A}=await q.from("newsletter_comments").select("newsletter_id");return A||[]}}),{data:h}=ct({queryKey:["newsletter-resource-counts"],queryFn:async()=>{const[A,T,L,M]=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:T.data||[],videos:L.data||[],drives:M.data||[]}}}),m=A=>(d==null?void 0:d.filter(T=>T.newsletter_id===A).length)||0,p=A=>(u==null?void 0:u.filter(T=>T.newsletter_id===A).length)||0,f=A=>{var T;return((T=h==null?void 0:h.canva)==null?void 0:T.filter(L=>L.newsletter_id===A).length)||0},x=A=>{var T;return((T=h==null?void 0:h.pdfs)==null?void 0:T.filter(L=>L.newsletter_id===A).length)||0},y=A=>{var T;return((T=h==null?void 0:h.videos)==null?void 0:T.filter(L=>L.newsletter_id===A).length)||0},v=A=>{var T;return((T=h==null?void 0:h.drives)==null?void 0:T.filter(L=>L.newsletter_id===A).length)||0},b=A=>f(A)+x(A)+y(A)+v(A),N=o==null?void 0:o.filter(A=>{var T;return A.title.toLowerCase().includes(t.toLowerCase())||((T=A.description)==null?void 0:T.toLowerCase().includes(t.toLowerCase()))}),S=A=>{s(`/newsletters/${A}`)};return e.jsx(qs,{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(oa,{defaultValue:"custom",className:"space-y-4",children:[e.jsxs(la,{children:[e.jsx(Kt,{value:"custom",children:"Build & Send"}),e.jsx(Kt,{value:"curated",children:"Curated Monthly"})]}),e.jsx(Zt,{value:"custom",className:"mt-2",children:e.jsx(tEn,{})}),e.jsxs(Zt,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{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(U,{variant:"outline",size:"sm",onClick:()=>n(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(U,{variant:r==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(Hg,{className:"h-4 w-4"})}),e.jsx(U,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(m0,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[(N==null?void 0:N.length)||0," item",(N==null?void 0:N.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,T)=>e.jsx(we,{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"})]})]})},T))}),!c&&(N==null?void 0:N.length)===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Ur,{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(U,{variant:"outline",onClick:()=>n(""),children:"Clear Search"})]}),!c&&N&&N.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:N.map(A=>{const T=b(A.id),L=f(A.id),M=x(A.id),I=y(A.id);return r==="grid"?e.jsxs(we,{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(Ur,{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(pa,{className:"h-3 w-3"}),Gs(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,"")}),T>0&&e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[L>0&&e.jsxs(Be,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx($c,{className:"h-3 w-3"})," ",L," Template",L>1?"s":""]}),M>0&&e.jsxs(Be,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(pi,{className:"h-3 w-3"})," ",M," PDF",M>1?"s":""]}),I>0&&e.jsxs(Be,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(lu,{className:"h-3 w-3"})," ",I," Video",I>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(wx,{className:"h-3 w-3"})," ",m(A.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(vu,{className:"h-3 w-3"})," ",p(A.id)]})]}),A.html_code&&e.jsxs(U,{size:"sm",className:"w-full bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:R=>{R.stopPropagation(),l(A)},children:[e.jsx($r,{className:"h-4 w-4 mr-1.5"}),"Send Newsletter"]})]})]},A.id):e.jsx(we,{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(Ur,{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(pa,{className:"h-3 w-3"}),Gs(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:[T>0&&e.jsxs("span",{children:[T," resource",T>1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(wx,{className:"h-3 w-3"})," ",m(A.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(vu,{className:"h-3 w-3"})," ",p(A.id)]})]})]}),A.html_code&&e.jsx("div",{className:"p-3 flex items-center shrink-0",children:e.jsxs(U,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:R=>{R.stopPropagation(),l(A)},children:[e.jsx($r,{className:"h-4 w-4 mr-1.5"}),"Send"]})})]})},A.id)})})]})]}),(i==null?void 0:i.html_code)&&e.jsx(Itt,{open:!!i,onOpenChange:A=>!A&&l(null),newsletterId:i.id,newsletterTitle:i.title,htmlCode:i.html_code})]})})}function nEn({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(we,{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 rEn(){const{id:s}=Di(),t=Wn(),{user:n}=vs(),{toast:r}=Ai(),a=Qt(),{trackEngagement:i}=EG(),[l,o]=j.useState(""),[c,d]=j.useState(!1),{data:u,isLoading:h}=ct({queryKey:["newsletter",s],queryFn:async()=>{const{data:L,error:M}=await q.from("newsletter_content").select("*").eq("id",s).single();if(M)throw M;return L},enabled:!!s});j.useEffect(()=>{u&&i("newsletter",u.id,u.title,"view")},[u==null?void 0:u.id]);const{data:m}=ct({queryKey:["newsletter-drives",s],queryFn:async()=>{const{data:L}=await q.from("newsletter_drive_links").select("*").eq("newsletter_id",s).order("sort_order");return L||[]},enabled:!!s}),{data:p}=ct({queryKey:["newsletter-pdfs",s],queryFn:async()=>{const{data:L}=await q.from("newsletter_pdfs").select("*").eq("newsletter_id",s).order("sort_order");return L||[]},enabled:!!s}),{data:f}=ct({queryKey:["newsletter-videos",s],queryFn:async()=>{const{data:L}=await q.from("newsletter_videos").select("*").eq("newsletter_id",s).order("sort_order");return L||[]},enabled:!!s}),{data:x}=ct({queryKey:["newsletter-canva-links",s],queryFn:async()=>{const{data:L}=await q.from("newsletter_canva_links").select("*").eq("newsletter_id",s).order("sort_order");return L||[]},enabled:!!s}),{data:y}=ct({queryKey:["newsletter-likes",s],queryFn:async()=>{const{data:L}=await q.from("newsletter_likes").select("*").eq("newsletter_id",s);return L||[]},enabled:!!s}),{data:v}=ct({queryKey:["newsletter-comments",s],queryFn:async()=>{const{data:L}=await q.from("newsletter_comments").select("*, profiles:user_id(name)").eq("newsletter_id",s).order("created_at",{ascending:!1});return L||[]},enabled:!!s}),b=y==null?void 0:y.some(L=>L.user_id===(n==null?void 0:n.id)),N=yt({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=yt({mutationFn:async L=>{const{error:M}=await q.from("newsletter_comments").insert({newsletter_id:s,user_id:n==null?void 0:n.id,content:L});if(M)throw M},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),o(""),r({title:"Comment added"})}}),A=yt({mutationFn:async L=>{const{error:M}=await q.from("newsletter_comments").delete().eq("id",L);if(M)throw M},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),r({title:"Comment deleted"})}}),T=L=>{if(L.includes("player.mediadelivery.net")||L.includes("iframe.mediadelivery.net")){const M=L.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(M)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://iframe.mediadelivery.net/embed/${M[1]}/${M[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(L.includes("youtube.com")||L.includes("youtu.be")){const M=L.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([^&\s]+)/);if(M)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://www.youtube.com/embed/${M[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:L,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(lu,{className:"h-4 w-4"})," Watch Video"]})};return h?e.jsx(qs,{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(qs,{title:"",description:"",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(U,{variant:"ghost",onClick:()=>t("/newsletters"),className:"mb-4",children:[e.jsx(Aa,{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:Gs(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(nEn,{rows:u.content_blocks||[]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx(PG,{resourceType:"newsletter",resourceId:u.id,resourceTitle:u.title}),e.jsxs(U,{variant:b?"default":"outline",size:"sm",onClick:()=>N.mutate(),children:[e.jsx(ko,{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(U,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:()=>d(!0),children:[e.jsx($r,{className:"h-4 w-4 mr-1"}),"Send Newsletter"]})]}),u.html_code&&e.jsx(Itt,{open:c,onOpenChange:d,newsletterId:u.id,newsletterTitle:u.title,htmlCode:u.html_code}),x&&x.length>0&&e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-lg",children:"Canva Templates"})}),e.jsx(Ie,{className:"space-y-2",children:x.map(L=>e.jsxs("a",{href:L.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($c,{className:"h-5 w-5 text-purple-500"}),e.jsx("span",{className:"font-medium",children:L.title}),e.jsx(Sr,{className:"h-4 w-4 text-muted-foreground ml-auto"})]},L.id))})]}),m&&m.length>0&&e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-lg",children:"Google Drive Files"})}),e.jsx(Ie,{className:"space-y-2",children:m.map(L=>e.jsxs("a",{href:L.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(Sr,{className:"h-5 w-5 text-primary"}),e.jsx("span",{className:"font-medium",children:L.title})]},L.id))})]}),p&&p.length>0&&e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-lg",children:"PDF Downloads"})}),e.jsx(Ie,{className:"space-y-2",children:p.map(L=>e.jsxs("a",{href:L.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(Ur,{className:"h-5 w-5 text-red-500"}),e.jsx("span",{className:"font-medium flex-1",children:L.name}),e.jsx(pi,{className:"h-4 w-4 text-muted-foreground"})]},L.id))})]}),f&&f.length>0&&e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-lg",children:"Videos"})}),e.jsx(Ie,{className:"space-y-6",children:f.map(L=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:L.title}),T(L.video_url)]},L.id))})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{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(Fs,{placeholder:"Write a comment...",value:l,onChange:L=>o(L.target.value),className:"flex-1"}),e.jsx(U,{onClick:()=>l.trim()&&S.mutate(l),disabled:!l.trim()||S.isPending,children:e.jsx($r,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-4",children:v==null?void 0:v.map(L=>{var M,I,R;return e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ea,{className:"h-8 w-8",children:e.jsx(Ta,{children:((I=(M=L.profiles)==null?void 0:M.name)==null?void 0:I[0])||"U"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-sm",children:((R=L.profiles)==null?void 0:R.name)||"User"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:Gs(new Date(L.created_at),"MMM d, yyyy")}),L.user_id===(n==null?void 0:n.id)&&e.jsx(U,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>A.mutate(L.id),children:e.jsx(In,{className:"h-3 w-3"})})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:L.content})]})]},L.id)})})]})]})]})}):e.jsx(qs,{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(U,{variant:"link",onClick:()=>t("/newsletters"),children:"Back to Newsletters"})]})})}function aEn({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,p)=>p!==h))},c=(h,m,p,f)=>{const x=[...s];x[h]={...x[h],columns:x[h].columns.map((y,v)=>v===m?{...y,[p]:f}:y)},t(x)},d=async(h,m,p)=>{var y;const f=(y=p.target.files)==null?void 0:y[0];if(!f)return;const x=`${h}-${m}`;r(x);try{const v=`content-blocks/${Date.now()}-${f.name}`,{error:b}=await q.storage.from("newsletter-content").upload(v,f);if(!b){const{data:N}=q.storage.from("newsletter-content").getPublicUrl(v);c(h,m,"image_url",N.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(te,{className:"text-base font-medium",children:"Content Blocks (3-Column Rows)"}),e.jsxs(U,{type:"button",variant:"outline",size:"sm",onClick:l,children:[e.jsx(an,{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(we,{className:"relative",children:[e.jsx(U,{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(er,{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(kf,{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((p,f)=>{const x=`${m}-${f}`;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 ",f+1]}),p.image_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:p.image_url,alt:"",className:"w-full h-20 object-cover rounded"}),e.jsx(U,{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,f),children:e.jsx(er,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[e.jsx(xe,{type:"file",accept:"image/*",className:"hidden",id:`block-img-${x}`,onChange:y=>d(m,f,y)}),e.jsx(U,{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(pc,{className:"h-3 w-3 mr-1"})," Upload"]})})}),e.jsxs(U,{type:"button",variant:"outline",size:"sm",className:"text-xs h-8",onClick:()=>i({row:m,col:f}),children:[e.jsx(tj,{className:"h-3 w-3 mr-1"})," Library"]})]}),e.jsx(xe,{placeholder:"Title",value:p.title,onChange:y=>c(m,f,"title",y.target.value),className:"h-8 text-sm"}),e.jsx(Fs,{placeholder:"Description",value:p.description,onChange:y=>c(m,f,"description",y.target.value),className:"text-sm min-h-[60px] resize-none"})]},f)})})]})]},m)),e.jsx(zs,{open:!!a,onOpenChange:h=>!h&&i(null),children:e.jsxs(Ds,{className:"sm:max-w-2xl",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Choose a Graphic"})}),e.jsx(oGt,{onSelect:h=>{a&&(c(a.row,a.col,"image_url",h.image_url),i(null))}})]})})]})}function iEn(){const{toast:s}=Ai(),t=Qt(),[n,r]=j.useState(!1),[a,i]=j.useState(null),[l,o]=j.useState({title:"",description:"",publish_date:Gs(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),[c,d]=j.useState(null),[u,h]=j.useState(null),[m,p]=j.useState([]),[f,x]=j.useState([]),[y,v]=j.useState([]),[b,N]=j.useState([]),[S,A]=j.useState([]),[T,L]=j.useState(""),[M,I]=j.useState([]),[R,z]=j.useState(!1),{data:$,isLoading:H}=ct({queryKey:["admin-newsletters"],queryFn:async()=>{const{data:ge,error:ke}=await q.from("newsletter_content").select("*").order("publish_date",{ascending:!1});if(ke)throw ke;return ge}}),V=yt({mutationFn:async ge=>{const{data:ke,error:Te}=await q.from("newsletter_content").insert({title:ge.title,description:ge.description||null,preview_image_url:ge.preview_image_url,publish_date:ge.publish_date,is_published:ge.is_published,content_blocks:ge.content_blocks,html_code:ge.html_code}).select().single();if(Te)throw Te;return ke},onSuccess:async ge=>{await Q(ge.id),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter created successfully"}),ge.is_published&&Lrn(ge.title,ge.id),se()},onError:ge=>{s({title:"Error creating newsletter",description:ge.message,variant:"destructive"})}}),K=yt({mutationFn:async ge=>{const{error:ke}=await q.from("newsletter_content").update({title:ge.title,description:ge.description||null,preview_image_url:ge.preview_image_url,publish_date:ge.publish_date,is_published:ge.is_published,content_blocks:ge.content_blocks,html_code:ge.html_code}).eq("id",ge.id);if(ke)throw ke;return ge.id},onSuccess:async ge=>{await Q(ge),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter updated successfully"}),se()},onError:ge=>{s({title:"Error updating newsletter",description:ge.message,variant:"destructive"})}}),Z=yt({mutationFn:async ge=>{const{error:ke}=await q.from("newsletter_content").delete().eq("id",ge);if(ke)throw ke},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter deleted successfully"})},onError:ge=>{s({title:"Error deleting newsletter",description:ge.message,variant:"destructive"})}}),Q=async ge=>{await q.from("newsletter_drive_links").delete().eq("newsletter_id",ge),await q.from("newsletter_pdfs").delete().eq("newsletter_id",ge),await q.from("newsletter_videos").delete().eq("newsletter_id",ge),await q.from("newsletter_canva_links").delete().eq("newsletter_id",ge);for(const ke of M){const Te=`${ge}/${Date.now()}-${ke.file.name}`,{error:Me}=await q.storage.from("newsletter-content").upload(Te,ke.file);if(!Me){const{data:Oe}=q.storage.from("newsletter-content").getPublicUrl(Te);f.push({name:ke.name,file_url:Oe.publicUrl,file_size:ke.file.size,sort_order:f.length})}}m.length>0&&await q.from("newsletter_drive_links").insert(m.map((ke,Te)=>({newsletter_id:ge,title:ke.title,drive_url:ke.drive_url,sort_order:Te}))),f.length>0&&await q.from("newsletter_pdfs").insert(f.map((ke,Te)=>({newsletter_id:ge,name:ke.name,file_url:ke.file_url,file_size:ke.file_size||null,sort_order:Te}))),y.length>0&&await q.from("newsletter_videos").insert(y.map((ke,Te)=>({newsletter_id:ge,title:ke.title,video_url:ke.video_url,sort_order:Te}))),b.length>0&&await q.from("newsletter_canva_links").insert(b.map((ke,Te)=>({newsletter_id:ge,title:ke.title,canva_share_link:ke.canva_share_link,sort_order:Te})))},le=async ge=>{i(ge),o({title:ge.title,description:ge.description||"",publish_date:Gs(new Date(ge.publish_date),"yyyy-MM-dd'T'HH:mm"),is_published:ge.is_published}),h(ge.preview_image_url),A(ge.content_blocks||[]),L(ge.html_code||"");const[ke,Te,Me,Oe]=await Promise.all([q.from("newsletter_drive_links").select("*").eq("newsletter_id",ge.id).order("sort_order"),q.from("newsletter_pdfs").select("*").eq("newsletter_id",ge.id).order("sort_order"),q.from("newsletter_videos").select("*").eq("newsletter_id",ge.id).order("sort_order"),q.from("newsletter_canva_links").select("*").eq("newsletter_id",ge.id).order("sort_order")]);p(ke.data||[]),x(Te.data||[]),v(Me.data||[]),N(Oe.data||[]),I([]),r(!0)},ue=async ge=>{const[ke,Te,Me,Oe]=await Promise.all([q.from("newsletter_drive_links").select("*").eq("newsletter_id",ge.id).order("sort_order"),q.from("newsletter_pdfs").select("*").eq("newsletter_id",ge.id).order("sort_order"),q.from("newsletter_videos").select("*").eq("newsletter_id",ge.id).order("sort_order"),q.from("newsletter_canva_links").select("*").eq("newsletter_id",ge.id).order("sort_order")]);i(null),o({title:`${ge.title} (Copy)`,description:ge.description||"",publish_date:Gs(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),h(ge.preview_image_url),A(ge.content_blocks||[]),L(ge.html_code||""),p((ke.data||[]).map(({id:Se,...Qe})=>Qe)),x((Te.data||[]).map(({id:Se,...Qe})=>Qe)),v((Me.data||[]).map(({id:Se,...Qe})=>Qe)),N((Oe.data||[]).map(({id:Se,...Qe})=>Qe)),I([]),r(!0)},se=()=>{r(!1),i(null),o({title:"",description:"",publish_date:Gs(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),d(null),h(null),p([]),x([]),v([]),N([]),A([]),L(""),I([])},ne=async ge=>{var Te;const ke=(Te=ge.target.files)==null?void 0:Te[0];ke&&(d(ke),h(URL.createObjectURL(ke)))},ie=async()=>{if(!l.title){s({title:"Title is required",variant:"destructive"});return}z(!0);let ge=u;if(c){const ke=`previews/${Date.now()}-${c.name}`,{error:Te}=await q.storage.from("newsletter-content").upload(ke,c);if(!Te){const{data:Me}=q.storage.from("newsletter-content").getPublicUrl(ke);ge=Me.publicUrl}}a?K.mutate({id:a.id,...l,preview_image_url:ge,content_blocks:S,html_code:T||null}):V.mutate({...l,preview_image_url:ge,content_blocks:S,html_code:T||null}),z(!1)},ce=()=>p([...m,{title:"",drive_url:"",sort_order:m.length}]),je=()=>v([...y,{title:"",video_url:"",sort_order:y.length}]),be=()=>N([...b,{title:"",canva_share_link:"",sort_order:b.length}]),he=ge=>{const ke=ge.target.files;if(!ke)return;const Te=Array.from(ke).map(Me=>({file:Me,name:Me.name.replace(/\.[^/.]+$/,"")}));I([...M,...Te])};return e.jsx(qs,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{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(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Total"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:($==null?void 0:$.length)||0})})]}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:($==null?void 0:$.filter(ge=>ge.is_published).length)||0})})]})]}),e.jsxs(zs,{open:n,onOpenChange:ge=>!ge&&se(),children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{onClick:()=>r(!0),children:[e.jsx(an,{className:"mr-2 h-4 w-4"})," Add Newsletter"]})}),e.jsxs(Ds,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:a?"Edit Newsletter":"Add Newsletter"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Title *"}),e.jsx(xe,{value:l.title,onChange:ge=>o({...l,title:ge.target.value}),placeholder:"Newsletter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Publish Date"}),e.jsx(xe,{type:"datetime-local",value:l.publish_date,onChange:ge=>o({...l,publish_date:ge.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Description"}),e.jsx(SN,{content:l.description,onChange:ge=>o({...l,description:ge}),placeholder:"Newsletter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{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(U,{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(er,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx(xe,{type:"file",accept:"image/*",onChange:ne,className:"hidden",id:"preview-upload"}),e.jsx(U,{variant:"outline",asChild:!0,children:e.jsxs("label",{htmlFor:"preview-upload",className:"cursor-pointer",children:[e.jsx(qa,{className:"mr-2 h-4 w-4"})," Upload Image"]})})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wn,{checked:l.is_published,onCheckedChange:ge=>o({...l,is_published:ge})}),e.jsx(te,{children:"Published"})]}),e.jsx(aEn,{rows:S,onChange:A}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{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:T,onChange:ge=>L(ge.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(te,{className:"text-base font-medium",children:"Canva Links"}),e.jsxs(U,{type:"button",variant:"outline",size:"sm",onClick:be,children:[e.jsx(an,{className:"mr-1 h-3 w-3"})," Add Canva Link"]})]}),b.map((ge,ke)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(xe,{placeholder:"Link title",value:ge.title,onChange:Te=>{const Me=[...b];Me[ke].title=Te.target.value,N(Me)},className:"w-1/3"}),e.jsx(xe,{placeholder:"Canva share link",value:ge.canva_share_link,onChange:Te=>{const Me=[...b];Me[ke].canva_share_link=Te.target.value,N(Me)},className:"flex-1"}),e.jsx(U,{type:"button",variant:"ghost",size:"icon",onClick:()=>N(b.filter((Te,Me)=>Me!==ke)),children:e.jsx(er,{className:"h-4 w-4"})})]},ke))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{className:"text-base font-medium",children:"Google Drive Links"}),e.jsxs(U,{type:"button",variant:"outline",size:"sm",onClick:ce,children:[e.jsx(an,{className:"mr-1 h-3 w-3"})," Add Link"]})]}),m.map((ge,ke)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(xe,{placeholder:"Link title",value:ge.title,onChange:Te=>{const Me=[...m];Me[ke].title=Te.target.value,p(Me)},className:"w-1/3"}),e.jsx(xe,{placeholder:"Google Drive URL",value:ge.drive_url,onChange:Te=>{const Me=[...m];Me[ke].drive_url=Te.target.value,p(Me)},className:"flex-1"}),e.jsx(U,{type:"button",variant:"ghost",size:"icon",onClick:()=>p(m.filter((Te,Me)=>Me!==ke)),children:e.jsx(er,{className:"h-4 w-4"})})]},ke))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{className:"text-base font-medium",children:"PDF Files"}),e.jsxs("div",{children:[e.jsx(xe,{type:"file",accept:".pdf",multiple:!0,onChange:he,className:"hidden",id:"pdf-upload"}),e.jsx(U,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{htmlFor:"pdf-upload",className:"cursor-pointer",children:[e.jsx(qa,{className:"mr-1 h-3 w-3"})," Upload PDF"]})})]})]}),f.map((ge,ke)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(Ur,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm",children:ge.name}),e.jsx(U,{type:"button",variant:"ghost",size:"icon",onClick:()=>x(f.filter((Te,Me)=>Me!==ke)),children:e.jsx(er,{className:"h-4 w-4"})})]},`existing-${ke}`)),M.map((ge,ke)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(Ur,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:ge.name,onChange:Te=>{const Me=[...M];Me[ke].name=Te.target.value,I(Me)},className:"flex-1 h-8",placeholder:"PDF name"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"(new)"}),e.jsx(U,{type:"button",variant:"ghost",size:"icon",onClick:()=>I(M.filter((Te,Me)=>Me!==ke)),children:e.jsx(er,{className:"h-4 w-4"})})]},`pending-${ke}`))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{className:"text-base font-medium",children:"Video Links"}),e.jsxs(U,{type:"button",variant:"outline",size:"sm",onClick:je,children:[e.jsx(an,{className:"mr-1 h-3 w-3"})," Add Video"]})]}),y.map((ge,ke)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(xe,{placeholder:"Video title",value:ge.title,onChange:Te=>{const Me=[...y];Me[ke].title=Te.target.value,v(Me)},className:"w-1/3"}),e.jsx(xe,{placeholder:"Video URL",value:ge.video_url,onChange:Te=>{const Me=[...y];Me[ke].video_url=Te.target.value,v(Me)},className:"flex-1"}),e.jsx(U,{type:"button",variant:"ghost",size:"icon",onClick:()=>v(y.filter((Te,Me)=>Me!==ke)),children:e.jsx(er,{className:"h-4 w-4"})})]},ke))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(U,{variant:"outline",onClick:se,children:"Cancel"}),e.jsx(U,{onClick:ie,disabled:R||V.isPending||K.isPending,children:R?"Uploading...":a?"Update":"Create"})]})]})]})]})]}),e.jsx(we,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Name"}),e.jsx(Lt,{children:"Publish Date"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:H?e.jsx(gn,{children:e.jsx(gt,{colSpan:4,className:"text-center py-8",children:"Loading..."})}):($==null?void 0:$.length)===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:4,className:"text-center py-8 text-muted-foreground",children:"No newsletters yet. Create your first one!"})}):$==null?void 0:$.map(ge=>e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[ge.preview_image_url?e.jsx("img",{src:ge.preview_image_url,alt:ge.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(Ur,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ge.title}),ge.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:ge.description.replace(/<[^>]*>/g,"")})]})]})}),e.jsx(gt,{children:Gs(new Date(ge.publish_date),"MMM d, yyyy")}),e.jsx(gt,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${ge.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:ge.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>le(ge),title:"Edit",children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>ue(ge),title:"Duplicate",children:e.jsx(Pa,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",title:"Delete",onClick:async()=>{await Yi("Are you sure you want to delete this newsletter?")&&Z.mutate(ge.id)},children:e.jsx(In,{className:"h-4 w-4"})})]})})]},ge.id))})]})})})]})})}const oEn={status:"all",billing:"all",role:"all",brokerage:"all",joinedWithinDays:null};function lEn({brokerages:s}){var A;const{toast:t}=Ai(),[n,r]=j.useState(oEn),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(null),[m,p]=j.useState(!1),[f,x]=j.useState(!1),[y,v]=j.useState(null),b=(T,L)=>r(M=>({...M,[T]:L}));j.useEffect(()=>{const T=setTimeout(async()=>{p(!0);try{const{data:L,error:M}=await q.functions.invoke("admin-broadcast-sms",{body:{action:"preview",filters:n,sms_body:a||"Sample message"}});if(M)throw M;h(L)}catch{h(null)}finally{p(!1)}},450);return()=>clearTimeout(T)},[n,a]);const N=async()=>{if(!c||!a.trim()){t({title:"Add a test number and message",variant:"destructive"});return}x(!0);const{data:T,error:L}=await q.functions.invoke("admin-broadcast-sms",{body:{action:"test",to:c,sms_body:a}});if(x(!1),L||T!=null&&T.error){t({title:"Test failed",description:(T==null?void 0:T.error)||(L==null?void 0:L.message),variant:"destructive"});return}t({title:"Test text sent",description:`Sent to ${c}`})},S=async()=>{const T=(u==null?void 0:u.count)||0;if(!(!a.trim()||T===0||!await Yi({title:"Send text broadcast?",description:`This will text ${T} member${T===1?"":"s"} who have a recorded SMS opt-in. Texts cannot be recalled.`,confirmText:"Send broadcast"}))){x(!0),v({total:T,sent:0,failed:0});try{const{data:M,error:I}=await q.functions.invoke("admin-broadcast-sms",{body:{action:"queue",name:l||a.slice(0,60),sms_body:a,filters:n}});if(I||M!=null&&M.error)throw new Error((M==null?void 0:M.error)||(I==null?void 0:I.message));let R=0,z=0,$=M.total,H=0;for(;$>0&&H++<400;){const{data:V,error:K}=await q.functions.invoke("admin-broadcast-sms",{body:{action:"process",broadcast_id:M.broadcast_id,limit:40}});if(K||V!=null&&V.error)throw new Error((V==null?void 0:V.error)||(K==null?void 0:K.message));if(V.deferred){t({title:"Paused for quiet hours",description:V.reason});break}R+=V.sent||0,z+=V.failed||0,$=V.remaining||0,v({total:T,sent:R,failed:z})}t({title:"Broadcast complete",description:`${R} sent${z?`, ${z} failed`:""}.`})}catch(M){t({title:"Broadcast failed",description:M.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(we,{children:[e.jsxs(Tt,{className:"pb-3",children:[e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx(cg,{className:"h-4 w-4"})," SMS Audience"]}),e.jsx(Jn,{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(te,{className:"text-xs",children:"Account status"}),e.jsxs(Ns,{value:n.status,onValueChange:T=>b("status",T),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All members"}),e.jsx(et,{value:"active",children:"Signed in before"}),e.jsx(et,{value:"pending",children:"Never signed in"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Billing"}),e.jsxs(Ns,{value:n.billing,onValueChange:T=>b("billing",T),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All"}),e.jsx(et,{value:"trial",children:"On trial"}),e.jsx(et,{value:"paid",children:"Paid"}),e.jsx(et,{value:"grandfathered",children:"Grandfathered"}),e.jsx(et,{value:"canceled",children:"Canceled / past due"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Role"}),e.jsxs(Ns,{value:n.role,onValueChange:T=>b("role",T),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All roles"}),e.jsx(et,{value:"user",children:"Agents"}),e.jsx(et,{value:"brokerage_manager",children:"Brokerage managers"}),e.jsx(et,{value:"coach",children:"Coaches"}),e.jsx(et,{value:"admin",children:"Admins"})]})]})]}),!!(s!=null&&s.length)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Brokerage"}),e.jsxs(Ns,{value:n.brokerage,onValueChange:T=>b("brokerage",T),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All brokerages"}),e.jsx(et,{value:"none",children:"No brokerage"}),s.map(T=>e.jsx(et,{value:T.id,children:T.name},T.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(Et,{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(T=>T.name||T.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(Yr,{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(we,{children:[e.jsxs(Tt,{className:"pb-3",children:[e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ki,{className:"h-4 w-4"})," Text message"]}),e.jsxs(Jn,{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(te,{htmlFor:"sms-broadcast-name",className:"text-xs",children:"Internal name"}),e.jsx(xe,{id:"sms-broadcast-name",value:l,onChange:T=>o(T.target.value),placeholder:"August member update"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"sms-broadcast-body",className:"text-xs",children:"Message"}),e.jsx(Fs,{id:"sms-broadcast-body",value:a,onChange:T=>i(T.target.value),rows:5,maxLength:480,placeholder:"Hi {{first_name}} — join us Thursday at 11am ET for the LevelUp Live session on listing videos."}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[(u==null?void 0:u.length)??a.length," characters"]}),e.jsxs(Be,{variant:((u==null?void 0:u.segments)??1)>2?"destructive":"secondary",children:[(u==null?void 0:u.segments)??1," segment",((u==null?void 0:u.segments)??1)===1?"":"s"]})]})]}),(u==null?void 0:u.composed)&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3",children:[e.jsx("p",{className:"mb-1 text-xs font-medium text-muted-foreground",children:"Preview as delivered"}),e.jsx("p",{className:"whitespace-pre-wrap text-sm",children:u.composed})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-2",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",style:{minWidth:200},children:[e.jsx(te,{htmlFor:"sms-test-phone",className:"text-xs",children:"Send a test to"}),e.jsx(xe,{id:"sms-test-phone",value:c,onChange:T=>d(T.target.value),placeholder:"(555) 123-4567",type:"tel"})]}),e.jsxs(U,{variant:"outline",onClick:N,disabled:f,children:[f&&e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"})," Send test"]})]}),y&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ro,{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(zr,{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(Vo,{className:"h-3 w-3"})," ",y.failed," failed"]}),e.jsxs("span",{children:["of ",y.total]})]})]}),e.jsxs(U,{onClick:S,disabled:f||!a.trim()||!(u!=null&&u.count),className:"w-full",children:[f?e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx($r,{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 P7e={status:"all",billing:"all",role:"all",brokerage:"all",joinedWithinDays:null,respectOptOut:!0,program:"all",programStatus:"active"},cEn=["{{first_name}}","{{name}}","{{email}}"];function dEn(s){return`${s||'

Your email preview will appear here…

'}`}function uEn(){var He;const{toast:s}=Ai(),{user:t}=vs(),n=Qt(),[r,a]=j.useState("filters"),[i,l]=j.useState([]),[o,c]=j.useState(""),[d,u]=j.useState([]),[h,m]=j.useState(!1),[p,f]=j.useState(""),[x,y]=j.useState(!1),[v,b]=j.useState(P7e),[N,S]=j.useState(null),[A,T]=j.useState(!1),[L,M]=j.useState(""),[I,R]=j.useState(""),[z,$]=j.useState(""),[H,V]=j.useState(""),[K,Z]=j.useState("rich"),[Q,le]=j.useState(""),[ue,se]=j.useState(""),[ne,ie]=j.useState(""),[ce,je]=j.useState(!1),[be,he]=j.useState(null),ge=K==="rich"?Q:ue;j.useEffect(()=>{t!=null&&t.email&&($(tt=>tt||t.email),V(tt=>tt||t.email),ie(tt=>tt||t.email))},[t==null?void 0:t.email]);const{data:ke}=ct({queryKey:["broadcast-brokerages"],queryFn:async()=>{const{data:tt}=await q.from("brokerages").select("id, name").order("name");return tt||[]}}),{data:Te}=ct({queryKey:["broadcast-programs"],queryFn:async()=>{const{data:tt}=await q.from("programs").select("id, name").order("created_at",{ascending:!1});return tt||[]}}),{data:Me}=ct({queryKey:["admin-broadcasts"],queryFn:async()=>{const{data:tt,error:pt}=await q.from("admin_broadcasts").select("*").order("created_at",{ascending:!1}).limit(30);if(pt)throw pt;return tt}}),{data:Oe}=ct({queryKey:["admin-broadcast-templates"],queryFn:async()=>{const{data:tt,error:pt}=await q.from("admin_broadcast_templates").select("*").order("updated_at",{ascending:!1});if(pt)throw pt;return tt}}),Se=async tt=>{T(!0);try{const{data:pt,error:ft}=await q.functions.invoke("admin-broadcast",{body:{action:"preview",filters:tt}});if(ft)throw ft;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{T(!1)}};j.useEffect(()=>{if(r!=="filters")return;const tt=setTimeout(()=>Se(v),400);return()=>clearTimeout(tt)},[v,r]),j.useEffect(()=>{if(r!=="manual")return;const tt=setTimeout(async()=>{m(!0);try{const{data:pt,error:ft}=await q.functions.invoke("admin-broadcast",{body:{action:"search_members",query:o}});if(ft)throw ft;u((pt==null?void 0:pt.members)||[])}catch{u([])}finally{m(!1)}},350);return()=>clearTimeout(tt)},[o,r]);const Qe=(tt,pt)=>b(ft=>({...ft,[tt]:pt})),Ae=r==="manual"?i.length:(N==null?void 0:N.count)||0,Fe=()=>r==="manual"?{recipient_mode:"manual",manual_emails:i.map(tt=>tt.email)}:{recipient_mode:"filters",filters:v},Ne=tt=>l(pt=>pt.some(ft=>ft.email.toLowerCase()===tt.email.toLowerCase())?pt.filter(ft=>ft.email.toLowerCase()!==tt.email.toLowerCase()):[...pt,tt]),$e=async()=>{const tt=(p||L||I).trim();if(!tt||!ge.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:tt,subject:I,body_html:ge,editor_mode:K,from_email:z||null,reply_to_email:H||null,filters:v});if(pt)throw pt;f(""),s({title:"Template saved",description:`"${tt}" 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)}},Ve=tt=>{M(tt.name||""),R(tt.subject||""),tt.from_email&&$(tt.from_email),tt.reply_to_email&&V(tt.reply_to_email);const pt=tt.editor_mode==="html"?"html":"rich";Z(pt),pt==="html"?se(tt.body_html||""):le(tt.body_html||""),tt.filters&&Object.keys(tt.filters).length&&b({...P7e,...tt.filters}),s({title:"Template loaded",description:"Edit and send when ready."})},qe=async tt=>{if(!await Yi(`Delete template "${tt.name}"?`))return;const{error:pt}=await q.from("admin_broadcast_templates").delete().eq("id",tt.id);if(pt){s({title:"Delete failed",description:pt.message,variant:"destructive"});return}n.invalidateQueries({queryKey:["admin-broadcast-templates"]})},Ze=j.useMemo(()=>!!I.trim()&&!!ge.trim()&&!!z.trim()&&Ae>0,[I,ge,z,Ae]),Ue=async()=>{if(!ne||!I.trim()||!ge.trim()){s({title:"Add a subject, content and test address first",variant:"destructive"});return}try{const{data:tt,error:pt}=await q.functions.invoke("admin-broadcast",{body:{action:"test",to:ne,subject:I,html:ge,from_email:z,reply_to:H||void 0}});if(pt)throw pt;if(tt!=null&&tt.error)throw new Error(tt.error);s({title:"Test sent",description:`Check ${ne}`})}catch(tt){s({title:"Test failed",description:tt.message,variant:"destructive"})}},Ye=async()=>{const tt=Ae;if(await Yi({title:"Send this broadcast?",description:`"${I}" will be emailed to ${tt} member${tt===1?"":"s"}. Sent emails can't be recalled.`,confirmText:"Send broadcast",cancelText:"Cancel",destructive:!1})){je(!0),he({total:tt,sent:0,failed:0});try{const{data:ft,error:qt}=await q.functions.invoke("admin-broadcast",{body:{action:"queue",name:L||I,subject:I,html:ge,from_email:z,reply_to:H||void 0,...Fe()}});if(qt)throw qt;if(ft!=null&&ft.error)throw new Error(ft.error);let Ut=0,Wt=0,us=ft.total,zt=0;for(;us>0;){const{data:bt,error:As}=await q.functions.invoke("admin-broadcast",{body:{action:"process",broadcast_id:ft.broadcast_id,limit:40}});if(As)throw As;if(bt!=null&&bt.error)throw new Error(bt.error);if(Ut+=bt.sent,Wt+=bt.failed,us=bt.remaining,he({total:ft.total,sent:Ut,failed:Wt}),bt.throttled){const vt=Math.min(Math.max(Number(bt.retry_after_ms)||15e3,5e3),45e3);await new Promise(Ws=>setTimeout(Ws,vt));continue}if(bt.sent===0&&bt.failed===0){if(++zt>=3)break;await new Promise(vt=>setTimeout(vt,5e3))}else zt=0}s({title:"Broadcast complete",description:`${Ut} sent${Wt?`, ${Wt} failed`:""}`}),n.invalidateQueries({queryKey:["admin-broadcasts"]})}catch(ft){s({title:"Send failed",description:ft.message,variant:"destructive"})}finally{je(!1)}}},Ge=async tt=>{je(!0);try{const{data:pt,error:ft}=await q.functions.invoke("admin-broadcast",{body:{action:"retry_failed",broadcast_id:tt}});if(ft)throw ft;if(pt!=null&&pt.error)throw new Error(pt.error);let qt=0,Ut=0,Wt=pt.requeued,us=0;for(he({total:Wt,sent:0,failed:0});Wt>0;){const{data:zt,error:bt}=await q.functions.invoke("admin-broadcast",{body:{action:"process",broadcast_id:tt,limit:25}});if(bt)throw bt;if(zt!=null&&zt.error)throw new Error(zt.error);if(qt+=zt.sent,Ut+=zt.failed,Wt=zt.remaining,he({total:pt.requeued,sent:qt,failed:Ut}),zt.throttled){await new Promise(As=>setTimeout(As,Math.min(Math.max(Number(zt.retry_after_ms)||15e3,5e3),45e3)));continue}if(zt.sent===0&&zt.failed===0){if(++us>=3)break;await new Promise(As=>setTimeout(As,5e3))}else us=0}s({title:"Retry complete",description:`${qt} sent${Ut?`, ${Ut} still failed`:""}`}),n.invalidateQueries({queryKey:["admin-broadcasts"]})}catch(pt){s({title:"Retry failed",description:pt.message,variant:"destructive"})}finally{je(!1)}};return e.jsx(qs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Xh,{title:"Member Broadcasts",description:"Send a one-off email to a filtered slice of LevelUp members"}),e.jsxs(oa,{defaultValue:"compose",className:"space-y-6",children:[e.jsxs(la,{children:[e.jsxs(Kt,{value:"compose",className:"gap-2",children:[e.jsx(ln,{className:"h-4 w-4"})," Compose"]}),e.jsxs(Kt,{value:"sms",className:"gap-2",children:[e.jsx(Ki,{className:"h-4 w-4"})," Text (SMS)"]}),e.jsxs(Kt,{value:"templates",className:"gap-2",children:[e.jsx(ej,{className:"h-4 w-4"})," Templates"]}),e.jsxs(Kt,{value:"history",className:"gap-2",children:[e.jsx(Y2,{className:"h-4 w-4"})," History"]})]}),e.jsx(Zt,{value:"sms",className:"space-y-6",children:e.jsx(lEn,{brokerages:ke})}),e.jsx(Zt,{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(we,{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(Bn,{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?"—":(N==null?void 0:N.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(oa,{value:r,onValueChange:tt=>a(tt),children:e.jsxs(la,{className:"grid w-full grid-cols-2",children:[e.jsxs(Kt,{value:"filters",className:"gap-1.5 text-xs",children:[e.jsx(Bn,{className:"h-3.5 w-3.5"})," Filters"]}),e.jsxs(Kt,{value:"manual",className:"gap-1.5 text-xs",children:[e.jsx(zl,{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(te,{children:"Find members"}),e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"pointer-events-none absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:o,onChange:tt=>c(tt.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(tt=>e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx("span",{className:"max-w-[150px] truncate",children:tt.name||tt.email}),e.jsx("button",{type:"button",onClick:()=>Ne(tt),"aria-label":`Remove ${tt.email}`,children:e.jsx(er,{className:"h-3 w-3"})})]},tt.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(tt=>{const pt=i.some(ft=>ft.email.toLowerCase()===tt.email.toLowerCase());return e.jsxs("button",{type:"button",onClick:()=>Ne(tt),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:tt.name||"Member"}),e.jsx("span",{className:"block truncate text-muted-foreground",children:tt.email})]}),pt&&e.jsx(zr,{className:"h-4 w-4 shrink-0 text-primary"})]},tt.id)})})]}),r==="filters"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Account status"}),e.jsxs(Ns,{value:v.status,onValueChange:tt=>Qe("status",tt),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All members"}),e.jsx(et,{value:"active",children:"Active (signed in)"}),e.jsx(et,{value:"pending",children:"Pending (never signed in)"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Membership"}),e.jsxs(Ns,{value:v.billing,onValueChange:tt=>Qe("billing",tt),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"Any membership"}),e.jsx(et,{value:"trial",children:"On trial"}),e.jsx(et,{value:"paid",children:"Paid subscribers"}),e.jsx(et,{value:"grandfathered",children:"Grandfathered"}),e.jsx(et,{value:"canceled",children:"Canceled / past due"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Role"}),e.jsxs(Ns,{value:v.role,onValueChange:tt=>Qe("role",tt),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"Any role"}),e.jsx(et,{value:"user",children:"Members"}),e.jsx(et,{value:"brokerage_manager",children:"Brokerage managers"}),e.jsx(et,{value:"coach",children:"Coaches"}),e.jsx(et,{value:"assistant",children:"Assistants"}),e.jsx(et,{value:"admin",children:"Admins"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Brokerage"}),e.jsxs(Ns,{value:v.brokerage,onValueChange:tt=>Qe("brokerage",tt),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{className:"max-h-72",children:[e.jsx(et,{value:"all",children:"All brokerages"}),e.jsx(et,{value:"none",children:"No brokerage"}),(ke||[]).map(tt=>e.jsx(et,{value:tt.id,children:tt.name},tt.id))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Program enrollment"}),e.jsxs(Ns,{value:v.program,onValueChange:tt=>Qe("program",tt),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{className:"max-h-72",children:[e.jsx(et,{value:"all",children:"Not filtered by program"}),e.jsx(et,{value:"any",children:"Enrolled in any program"}),(Te||[]).map(tt=>e.jsx(et,{value:tt.id,children:tt.name},tt.id))]})]})]}),v.program!=="all"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Enrollment status"}),e.jsxs(Ns,{value:v.programStatus,onValueChange:tt=>Qe("programStatus",tt),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"active",children:"Active enrollees (paid, reserved, completed)"}),e.jsx(et,{value:"any",children:"Any enrollment status"}),e.jsx(et,{value:"paid",children:"Paid"}),e.jsx(et,{value:"reserved",children:"Reserved"}),e.jsx(et,{value:"scheduled_for_charge",children:"Scheduled for charge"}),e.jsx(et,{value:"pending_payment_method",children:"Pending payment method"}),e.jsx(et,{value:"payment_failed",children:"Payment failed"}),e.jsx(et,{value:"completed",children:"Completed"}),e.jsx(et,{value:"canceled",children:"Canceled"}),e.jsx(et,{value:"refunded",children:"Refunded"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Joined within"}),e.jsxs(Ns,{value:v.joinedWithinDays?String(v.joinedWithinDays):"all",onValueChange:tt=>Qe("joinedWithinDays",tt==="all"?null:Number(tt)),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"Any time"}),e.jsx(et,{value:"30",children:"Last 30 days"}),e.jsx(et,{value:"60",children:"Last 60 days"}),e.jsx(et,{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(wn,{checked:v.respectOptOut,onCheckedChange:tt=>Qe("respectOptOut",tt)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>b(P7e),children:"Reset"}),e.jsxs(U,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>Se(v),disabled:A,children:[A?e.jsx(Et,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(no,{className:"h-3.5 w-3.5"}),"Refresh"]})]}),(He=N==null?void 0:N.sample)!=null&&He.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:N.sample.map(tt=>e.jsxs("p",{className:"truncate text-xs",children:[e.jsx("span",{className:"font-medium",children:tt.name||"Member"})," ",e.jsx("span",{className:"text-muted-foreground",children:tt.email})]},tt.email))})]}):null]})]})]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(we,{children:[e.jsxs(Tt,{className:"pb-4",children:[e.jsx(It,{className:"text-base",children:"Message"}),e.jsxs(Jn,{children:["Personalize with merge tags: ",cEn.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(te,{children:"Internal name"}),e.jsx(xe,{value:L,onChange:tt=>M(tt.target.value),placeholder:"August product update"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Subject line"}),e.jsx(xe,{value:I,onChange:tt=>R(tt.target.value),placeholder:"Big news for LevelUp members"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"From (must be a verified sender)"}),e.jsx(xe,{value:z,onChange:tt=>$(tt.target.value),placeholder:"hello@relevelup.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Reply-to"}),e.jsx(xe,{value:H,onChange:tt=>V(tt.target.value),placeholder:"support@relevelup.com"})]})]}),e.jsxs(oa,{value:K,onValueChange:tt=>Z(tt),children:[e.jsxs(la,{children:[e.jsxs(Kt,{value:"rich",className:"gap-2",children:[e.jsx(cn,{className:"h-3.5 w-3.5"})," Rich text"]}),e.jsxs(Kt,{value:"html",className:"gap-2",children:[e.jsx(jA,{className:"h-3.5 w-3.5"})," Paste HTML"]})]}),e.jsx(Zt,{value:"rich",className:"mt-3",children:e.jsx(SN,{content:Q,onChange:le,minHeight:"320px",placeholder:"Write your message…"})}),e.jsxs(Zt,{value:"html",className:"mt-3 space-y-2",children:[e.jsx(Fs,{value:ue,onChange:tt=>se(tt.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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx(xa,{className:"h-4 w-4"})," Preview"]}),e.jsx(Be,{variant:"secondary",children:K==="html"?"Raw HTML":"Rich text"})]}),e.jsx(Ie,{children:e.jsx("iframe",{title:"Email preview",srcDoc:dEn(ge),className:"h-[420px] w-full rounded-lg border bg-white"})})]}),e.jsx(we,{children:e.jsxs(Ie,{className:"space-y-4 pt-6",children:[be&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:[be.sent+be.failed," of ",be.total," processed"]}),e.jsxs("span",{className:"text-muted-foreground",children:[be.sent," sent",be.failed?` • ${be.failed} failed`:""]})]}),e.jsx(ro,{value:be.total?(be.sent+be.failed)/be.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(te,{children:"Send a test to"}),e.jsx(xe,{value:ne,onChange:tt=>ie(tt.target.value),className:"w-64"})]}),e.jsx(U,{variant:"outline",onClick:Ue,disabled:ce,children:"Send test"}),e.jsx("div",{className:"flex-1"}),e.jsxs(U,{onClick:Ye,disabled:!Ze||ce,size:"lg",className:"gap-2",children:[ce?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx($r,{className:"h-4 w-4"}),ce?"Sending…":`Send to ${Ae} member${Ae===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(te,{children:"Save as template"}),e.jsx(xe,{value:p,onChange:tt=>f(tt.target.value),placeholder:L||I||"Template name",className:"w-64"})]}),e.jsxs(U,{variant:"outline",className:"gap-2",onClick:$e,disabled:x,children:[x?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(NM,{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(Zt,{value:"templates",className:"space-y-3",children:(Oe||[]).length===0?e.jsx(we,{children:e.jsxs(Ie,{className:"flex flex-col items-center py-14 text-center",children:[e.jsx(ej,{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.'})]})}):(Oe||[]).map(tt=>e.jsx(we,{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:tt.name}),e.jsx(Be,{variant:"secondary",className:"text-xs",children:tt.editor_mode==="html"?"Raw HTML":"Rich text"})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:["Subject: ",tt.subject||"—"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Updated ",Gs(new Date(tt.updated_at),"MMM d, yyyy h:mm a")]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{size:"sm",className:"gap-2",onClick:()=>Ve(tt),children:[e.jsx(Ho,{className:"h-3.5 w-3.5"})," Use template"]}),e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>qe(tt),children:e.jsx(In,{className:"h-3.5 w-3.5"})})]})]})},tt.id))}),e.jsx(Zt,{value:"history",className:"space-y-3",children:(Me||[]).length===0?e.jsx(we,{children:e.jsxs(Ie,{className:"flex flex-col items-center py-14 text-center",children:[e.jsx(ln,{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."})]})}):(Me||[]).map(tt=>e.jsx(we,{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:tt.name}),e.jsxs(Be,{variant:tt.status==="sent"?"default":tt.status==="sending"?"secondary":"outline",className:"gap-1 text-xs",children:[tt.status==="sent"?e.jsx(zr,{className:"h-3 w-3"}):e.jsx(Vo,{className:"h-3 w-3"}),tt.status]})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:["Subject: ",tt.subject]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Gs(new Date(tt.created_at),"MMM d, yyyy h:mm a")," • from ",tt.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:tt.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:tt.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:tt.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:[tt.open_count??0,tt.sent_count>0&&e.jsxs("span",{className:"ml-1 text-xs font-medium text-muted-foreground",children:[Math.round((tt.open_count??0)/tt.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:[tt.click_count??0,tt.sent_count>0&&e.jsxs("span",{className:"ml-1 text-xs font-medium text-muted-foreground",children:[Math.round((tt.click_count??0)/tt.sent_count*100),"%"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Clicks"})]}),tt.failed_count>0&&e.jsx("div",{className:"flex items-center",children:e.jsx(U,{size:"sm",variant:"outline",disabled:ce,onClick:()=>Ge(tt.id),children:"Retry failed"})})]})]})},tt.id))})]})]})})}const hEn=["Headers","Footers","Seasonal","Holidays","Market Updates","Just Sold","Just Listed","Open House","Buyer Tips","Seller Tips","Testimonials","CTAs & Buttons","Dividers","General"];function mEn(){const s=Qt(),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,p]=j.useState({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),{data:f=[],isLoading:x}=ct({queryKey:["admin-newsletter-graphics"],queryFn:async()=>{const{data:z,error:$}=await q.from("newsletter_graphics").select("*").order("is_featured",{ascending:!1}).order("created_at",{ascending:!1});if($)throw $;return z||[]}}),y=j.useMemo(()=>{const z=new Set(hEn);return f.forEach($=>z.add($.category)),Array.from(z).sort()},[f]),v=j.useMemo(()=>{const z=n.trim().toLowerCase();return f.filter($=>a!=="all"&&$.category!==a?!1:z?$.title.toLowerCase().includes(z)||($.description||"").toLowerCase().includes(z)||$.tags.some(H=>H.toLowerCase().includes(z)):!0)},[f,n,a]),b=()=>{p({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),o(null)},N=()=>{b(),d(!0)},S=z=>{o(z),p({title:z.title,description:z.description||"",image_url:z.image_url,category:z.category,tags:z.tags.join(", "),is_active:z.is_active,is_featured:z.is_featured}),d(!0)},A=async z=>{var $;if(!z.type.startsWith("image/")){re.error("Please choose an image file");return}if(z.size>15*1024*1024){re.error("Image must be under 15MB");return}h(!0);try{const H=(($=z.name.split(".").pop())==null?void 0:$.toLowerCase())||"png",V=`graphics-library/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${H}`,{error:K}=await q.storage.from("newsletter-content").upload(V,z,{cacheControl:"31536000",upsert:!1,contentType:z.type});if(K)throw K;const{data:Z}=q.storage.from("newsletter-content").getPublicUrl(V);p(Q=>({...Q,image_url:Z.publicUrl,title:Q.title||z.name.replace(/\.[^.]+$/,"").replace(/[-_]/g," ")})),re.success("Uploaded")}catch(H){re.error(H.message||"Upload failed")}finally{h(!1),t.current&&(t.current.value="")}},T=yt({mutationFn:async()=>{var H;if(!m.image_url)throw new Error("Please upload an image");if(!m.title.trim())throw new Error("Please add a title");const z=m.tags.split(",").map(V=>V.trim()).filter(Boolean),$={title:m.title.trim(),description:m.description.trim()||null,image_url:m.image_url,category:m.category||"General",tags:z,is_active:m.is_active,is_featured:m.is_featured};if(l){const{error:V}=await q.from("newsletter_graphics").update($).eq("id",l.id);if(V)throw V}else{const{data:V}=await q.auth.getUser(),{error:K}=await q.from("newsletter_graphics").insert({...$,created_by:(H=V.user)==null?void 0:H.id});if(K)throw K}},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:z=>re.error(z.message||"Save failed")}),L=yt({mutationFn:async z=>{const{error:$}=await q.from("newsletter_graphics").delete().eq("id",z);if($)throw $},onSuccess:()=>{re.success("Deleted"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]})},onError:z=>re.error(z.message||"Delete failed")}),M=async z=>{const{error:$}=await q.from("newsletter_graphics").update({is_active:!z.is_active}).eq("id",z.id);$?re.error($.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},I=async z=>{const{error:$}=await q.from("newsletter_graphics").update({is_featured:!z.is_featured}).eq("id",z.id);$?re.error($.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},R=z=>{navigator.clipboard.writeText(z),re.success("URL copied")};return e.jsxs(qs,{children:[e.jsxs("div",{className:"p-4 md:p-6 max-w-7xl mx-auto space-y-5",children:[e.jsx(Xh,{title:"Newsletter Graphics Library",description:"Upload branded graphics agents can drop into their newsletters and email campaigns."}),e.jsx(we,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:n,onChange:z=>r(z.target.value),placeholder:"Search graphics by title, tag, description...",className:"pl-9"})]}),e.jsxs(Ns,{value:a,onValueChange:i,children:[e.jsx(ws,{className:"w-full md:w-56",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All categories"}),y.map(z=>e.jsx(et,{value:z,children:z},z))]})]}),e.jsxs(U,{onClick:N,className:"gap-1.5 whitespace-nowrap",children:[e.jsx(ly,{className:"h-4 w-4"})," Add Graphic"]})]})}),x?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Et,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):v.length===0?e.jsx(we,{children:e.jsxs(Ie,{className:"py-16 text-center",children:[e.jsx(pc,{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:f.length===0?"No graphics uploaded yet — add your first one to get started.":"No graphics match your filters."}),f.length===0&&e.jsxs(U,{onClick:N,className:"gap-1.5",children:[e.jsx(ly,{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(z=>e.jsxs(we,{className:`overflow-hidden group ${z.is_active?"":"opacity-60"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative overflow-hidden",children:[e.jsx("img",{src:z.image_url,alt:z.title,loading:"lazy",className:"w-full h-full object-cover"}),z.is_featured&&e.jsxs(Be,{className:"absolute top-2 left-2 gap-0.5 bg-amber-500 hover:bg-amber-500 text-white border-0",children:[e.jsx(Ua,{className:"h-3 w-3 fill-current"})," Featured"]}),!z.is_active&&e.jsx(Be,{variant:"secondary",className:"absolute top-2 right-2",children:"Hidden"})]}),e.jsxs(Ie,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm truncate",children:z.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:z.category})]}),z.tags.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:z.tags.slice(0,3).map($=>e.jsx(Be,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:$},$))}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t",children:[e.jsxs("div",{className:"flex gap-1",children:[e.jsx(U,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>S(z),title:"Edit",children:e.jsx(ri,{className:"h-3.5 w-3.5"})}),e.jsx(U,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>I(z),title:z.is_featured?"Unfeature":"Feature",children:e.jsx(Ua,{className:`h-3.5 w-3.5 ${z.is_featured?"fill-amber-500 text-amber-500":""}`})}),e.jsx(U,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>R(z.image_url),title:"Copy URL",children:e.jsx(Pa,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wn,{checked:z.is_active,onCheckedChange:()=>M(z)}),e.jsx(U,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:async()=>{await Yi(`Delete "${z.title}"?`)&&L.mutate(z.id)},children:e.jsx(In,{className:"h-3.5 w-3.5"})})]})]})]})]},z.id))})]}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Ds,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:l?"Edit Graphic":"Add New Graphic"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Image"}),e.jsx("input",{ref:t,type:"file",accept:"image/*",className:"hidden",onChange:z=>{var H;const $=(H=z.target.files)==null?void 0:H[0];$&&A($)}}),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(U,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>p(z=>({...z,image_url:""})),children:e.jsx(er,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{type:"button",onClick:()=>{var z;return(z=t.current)==null?void 0:z.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(Et,{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(qa,{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(te,{htmlFor:"g-title",children:"Title *"}),e.jsx(xe,{id:"g-title",value:m.title,onChange:z=>p($=>({...$,title:z.target.value})),placeholder:"e.g. Fall Market Update Banner"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"g-desc",children:"Description"}),e.jsx(Fs,{id:"g-desc",value:m.description,onChange:z=>p($=>({...$,description:z.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(te,{children:"Category"}),e.jsxs(Ns,{value:m.category,onValueChange:z=>p($=>({...$,category:z})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:y.map(z=>e.jsx(et,{value:z,children:z},z))})]})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"g-tags",children:"Tags (comma-separated)"}),e.jsx(xe,{id:"g-tags",value:m.tags,onChange:z=>p($=>({...$,tags:z.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(wn,{checked:m.is_featured,onCheckedChange:z=>p($=>({...$,is_featured:z}))})]}),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(wn,{checked:m.is_active,onCheckedChange:z=>p($=>({...$,is_active:z}))})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(U,{onClick:()=>T.mutate(),disabled:T.isPending,children:[T.isPending&&e.jsx(Et,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),l?"Save Changes":"Add to Library"]})]})]})})]})}const S_t={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 pEn(){const{user:s}=vs(),{toast:t}=Ai(),n=Wn(),r=Qt(),[a,i]=j.useState(""),[l,o]=j.useState("popular"),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,p]=j.useState(""),[f,x]=j.useState(!1),{data:y=[],isLoading:v}=ct({queryKey:["wishlist-items",l,f],queryFn:async()=>{let T=q.from("wishlist_items").select("*");f&&s&&(T=T.eq("user_id",s.id)),l==="latest"?T=T.order("created_at",{ascending:!1}):l==="popular"?T=T.order("vote_count",{ascending:!1}):l==="trending"&&(T=T.order("vote_count",{ascending:!1}));const{data:L,error:M}=await T;if(M)throw M;const I=[...new Set((L==null?void 0:L.map(Z=>Z.user_id))||[])],{data:R}=await q.from("profiles").select("id, name").in("id",I),z=new Map((R==null?void 0:R.map(Z=>[Z.id,Z]))||[]);let $=[];if(s){const{data:Z}=await q.from("wishlist_votes").select("item_id").eq("user_id",s.id);$=(Z==null?void 0:Z.map(Q=>Q.item_id))||[]}const H=(L==null?void 0:L.map(Z=>Z.id))||[],{data:V}=await q.from("wishlist_comments").select("item_id").in("item_id",H),K=new Map;return V==null||V.forEach(Z=>{K.set(Z.item_id,(K.get(Z.item_id)||0)+1)}),L==null?void 0:L.map(Z=>{const Q=z.get(Z.user_id),le=(Q==null?void 0:Q.name)||"Unknown";return{...Z,user_name:le,user_initials:le.split(" ").map(ue=>ue[0]).join("").toUpperCase().slice(0,2),has_voted:$.includes(Z.id),comment_count:K.get(Z.id)||0}})}}),b=yt({mutationFn:async({title:T,description:L})=>{const{error:M}=await q.from("wishlist_items").insert({user_id:s.id,title:T,description:L});if(M)throw M},onSuccess:()=>{r.invalidateQueries({queryKey:["wishlist-items"]}),d(!1),h(""),p(""),t({title:"Idea submitted!",description:"Your idea has been added to the wishlist."})},onError:T=>{t({title:"Error",description:T.message,variant:"destructive"})}}),N=yt({mutationFn:async({itemId:T,hasVoted:L})=>{if(L){const{error:M}=await q.from("wishlist_votes").delete().eq("item_id",T).eq("user_id",s.id);if(M)throw M;return{itemId:T,wasAdded:!1}}else{const{error:M}=await q.from("wishlist_votes").insert({item_id:T,user_id:s.id});if(M)throw M;return{itemId:T,wasAdded:!0}}},onSuccess:async T=>{if(r.invalidateQueries({queryKey:["wishlist-items"]}),T!=null&&T.wasAdded){const L=y.find(I=>I.id===T.itemId),M=((L==null?void 0:L.vote_count)||0)+1;q.functions.invoke("wishlist-notify",{body:{itemId:T.itemId,voteCount:M}}).catch(console.error)}},onError:T=>{t({title:"Error",description:T.message,variant:"destructive"})}}),S=y.filter(T=>T.title.toLowerCase().includes(a.toLowerCase())||T.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(qs,{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(eS,{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(al,{asChild:!0,children:e.jsxs(U,{className:"gap-2",children:[e.jsx(an,{className:"h-4 w-4"}),"Add Idea"]})}),e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Submit a New Idea"})}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"title",children:"Title"}),e.jsx(xe,{id:"title",placeholder:"Give your idea a clear title...",value:u,onChange:T=>h(T.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"description",children:"Description"}),e.jsx(Fs,{id:"description",placeholder:"Describe your idea in detail. What problem does it solve? How would it help agents?",value:m,onChange:T=>p(T.target.value),rows:4})]}),e.jsx(U,{onClick:A,className:"w-full",disabled:b.isPending,children:b.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Et,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search ideas...",value:a,onChange:T=>i(T.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(oa,{value:l,onValueChange:T=>o(T),children:e.jsxs(la,{children:[e.jsx(Kt,{value:"popular",children:"Most Popular"}),e.jsx(Kt,{value:"latest",children:"Latest"}),e.jsx(Kt,{value:"trending",children:"Trending"})]})})})]}),e.jsx("div",{className:"flex items-center gap-2 mb-4",children:e.jsx(U,{variant:f?"default":"outline",size:"sm",onClick:()=>x(!f),children:f?"Show All Ideas":"My Ideas"})}),v?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Et,{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(eS,{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(U,{onClick:()=>d(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Add Idea"]})]}):e.jsx("div",{className:"space-y-3",children:S.map(T=>e.jsx("div",{className:"bg-card border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>n(`/wishlist/${T.id}`),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("button",{onClick:L=>{L.stopPropagation(),N.mutate({itemId:T.id,hasVoted:T.has_voted||!1})},className:Mt("flex flex-col items-center justify-center min-w-[50px] py-2 px-3 rounded-lg border transition-colors",T.has_voted?"bg-primary/10 border-primary text-primary":"bg-muted/50 border-border hover:bg-muted"),children:[e.jsx(cp,{className:Mt("h-4 w-4",T.has_voted&&"fill-current")}),e.jsx("span",{className:"text-sm font-semibold",children:T.vote_count})]}),e.jsx(Ea,{className:"h-10 w-10 bg-primary/20",children:e.jsx(Ta,{className:"bg-primary/20 text-primary text-sm font-medium",children:T.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:T.title}),e.jsx(Be,{className:Mt("text-xs",S_t[T.status].color),children:S_t[T.status].label})]}),e.jsx("p",{className:"text-muted-foreground text-sm line-clamp-2",children:T.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:T.user_name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:new Date(T.created_at).toLocaleDateString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Ki,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:T.comment_count})]})]})},T.id))})]})})}const C_t={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 fEn(){const{itemId:s}=Di(),t=Wn(),{user:n}=vs(),{toast:r}=Ai(),a=Qt(),[i,l]=j.useState(""),{data:o=!1}=ct({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}=ct({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 N=!1;if(n){const{data:S}=await q.from("wishlist_votes").select("id").eq("item_id",s).eq("user_id",n.id).maybeSingle();N=!!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:N}}}),{data:u=[],isLoading:h}=ct({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:N}=await q.from("profiles").select("id, name").in("id",b),S=new Map((N==null?void 0:N.map(A=>[A.id,A]))||[]);return y==null?void 0:y.map(A=>{const T=S.get(A.user_id),L=(T==null?void 0:T.name)||"Unknown";return{...A,user_name:L,user_initials:L.split(" ").map(M=>M[0]).join("").toUpperCase().slice(0,2)}})}}),m=yt({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"})}}),p=yt({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"})}}),f=yt({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()&&p.mutate(i.trim())};return d?e.jsx(qs,{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(qs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>t("/wishlist"),className:"mb-4",children:[e.jsx(Aa,{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:Mt("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(cp,{className:Mt("h-5 w-5",c.has_voted&&"fill-current")}),e.jsx("span",{className:"text-lg font-bold",children:c.vote_count}),e.jsx("span",{className:"text-xs",children:"votes"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("h1",{className:"text-xl font-bold",children:c.title}),e.jsx(Be,{className:Mt("text-xs",C_t[c.status].color),children:C_t[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(Ea,{className:"h-6 w-6",children:e.jsx(Ta,{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(EAe,{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(U,{onClick:x,disabled:!i.trim()||p.isPending,size:"icon",className:"h-auto",children:p.isPending?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx($r,{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(Ea,{className:"h-8 w-8",children:e.jsx(Ta,{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(get,{content:y.content,className:"text-sm text-foreground"})]}),(n==null?void 0:n.id)===y.user_id&&e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>f.mutate(y.id),children:e.jsx(In,{className:"h-4 w-4"})})]},y.id))})]})]})}):e.jsx(qs,{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(U,{variant:"link",onClick:()=>t("/wishlist"),children:"Go back to Wishlist"})]})})}const A_t={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"}},E_t=["open","under_review","planned","in_progress","launched","declined"];function gEn(){const{toast:s}=Ai(),t=Wn(),n=Qt(),[r,a]=j.useState(""),[i,l]=j.useState("all"),[o,c]=j.useState(!1),[d,u]=j.useState(null),{data:h=[],isLoading:m}=ct({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 N=[...new Set((v==null?void 0:v.map(I=>I.user_id))||[])],{data:S}=await q.from("profiles").select("id, name, email").in("id",N),A=new Map((S==null?void 0:S.map(I=>[I.id,I]))||[]),T=(v==null?void 0:v.map(I=>I.id))||[],{data:L}=await q.from("wishlist_comments").select("item_id").in("item_id",T),M=new Map;return L==null||L.forEach(I=>{M.set(I.item_id,(M.get(I.item_id)||0)+1)}),v==null?void 0:v.map(I=>{const R=A.get(I.user_id);return{...I,user_name:(R==null?void 0:R.name)||"Unknown",user_email:(R==null?void 0:R.email)||"",comment_count:M.get(I.id)||0}})}}),p=yt({mutationFn:async({itemId:v,status:b})=>{const{error:N}=await q.from("wishlist_items").update({status:b}).eq("id",v);if(N)throw N},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),s({title:"Status updated!"})},onError:v=>{s({title:"Error",description:v.message,variant:"destructive"})}}),f=yt({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()),N=i==="all"||v.status===i;return b&&N}),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(qs,{title:"Admin - Wishlist",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>t("/admin"),children:e.jsx(Aa,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search ideas, users...",value:r,onChange:v=>a(v.target.value),className:"pl-10"})]}),e.jsxs(Ns,{value:i,onValueChange:v=>l(v),children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{placeholder:"Filter by status"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Statuses"}),E_t.map(v=>e.jsx(et,{value:v,children:A_t[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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{className:"w-[60px]",children:"Votes"}),e.jsx(Lt,{children:"Title"}),e.jsx(Lt,{className:"hidden md:table-cell",children:"Submitted By"}),e.jsx(Lt,{className:"hidden sm:table-cell",children:"Comments"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(Xa,{children:x.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No items found"})}):x.map(v=>e.jsxs(gn,{className:Mt(v.vote_count>=10&&"bg-primary/5"),children:[e.jsx(gt,{children:e.jsx(Be,{variant:v.vote_count>=10?"default":"secondary",children:v.vote_count})}),e.jsx(gt,{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(gt,{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(gt,{className:"hidden sm:table-cell",children:v.comment_count}),e.jsx(gt,{children:e.jsxs(Ns,{value:v.status,onValueChange:b=>p.mutate({itemId:v.id,status:b}),children:[e.jsx(ws,{className:"w-[140px] h-8",children:e.jsx(ks,{})}),e.jsx(js,{children:E_t.map(b=>e.jsx(et,{value:b,children:A_t[b].label},b))})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>window.open(`/wishlist/${v.id}`,"_blank"),children:e.jsx(Sr,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{u(v.id),c(!0)},children:e.jsx(In,{className:"h-4 w-4"})})]})})]},v.id))})]})}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Delete Wishlist Item"})}),e.jsx("p",{className:"text-muted-foreground",children:"Are you sure you want to delete this idea? This will also delete all votes and comments."}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx(U,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(U,{variant:"destructive",onClick:()=>d&&f.mutate(d),disabled:f.isPending,children:f.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})})}function xEn(){const{user:s}=vs(),[t,n]=j.useState([]),[r,a]=j.useState(!0),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(null),[p,f]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState(""),[N,S]=j.useState(""),[A,T]=j.useState(""),[L,M]=j.useState(!1),[I,R]=j.useState(""),[z,$]=j.useState("once"),[H,V]=j.useState([]),[K,Z]=j.useState([]),[Q,le]=j.useState(!1),[ue,se]=j.useState(!1),[ne,ie]=j.useState([]),[ce,je]=j.useState({total:0,dismissed:0});j.useEffect(()=>{be()},[]);const be=async()=>{const{data:Ge,error:He}=await q.from("levelup_briefs").select("*").order("created_at",{ascending:!1});He?(re.error("Failed to fetch briefs"),console.error(He)):n(Ge||[]),a(!1)},he=()=>{f(""),y(""),b(""),S(""),T(""),M(!1),R(new Date().toISOString().slice(0,16)),$("once"),V([]),Z([]),c(null)},ge=()=>{he(),l(!0)},ke=async Ge=>{c(Ge),f(Ge.title),y(Ge.description||""),b(Ge.video_url||""),S(Ge.graphic_url||""),T(Ge.graphic_link_url||""),M(Ge.is_published),R(Ge.publish_date.slice(0,16)),$(Ge.show_frequency);const{data:He}=await q.from("levelup_brief_links").select("*").eq("brief_id",Ge.id).order("sort_order");V((He==null?void 0:He.map(pt=>({title:pt.title,url:pt.url})))||[]);const{data:tt}=await q.from("levelup_brief_polls").select("*").eq("brief_id",Ge.id).order("sort_order");if(tt){const pt=[];for(const ft of tt){const{data:qt}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",ft.id).order("sort_order");pt.push({question:ft.question,poll_type:ft.poll_type,options:(qt==null?void 0:qt.map(Ut=>Ut.option_text))||[]})}Z(pt)}l(!0)},Te=async Ge=>{var tt;const He=(tt=Ge.target.files)==null?void 0:tt[0];if(He){le(!0);try{const pt=await q.functions.invoke("bunny-upload",{body:{action:"create",title:He.name.replace(/\.[^/.]+$/,"")}});if(pt.error)throw pt.error;const{videoId:ft,libraryId:qt}=pt.data,Ut=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:ft}});if(Ut.error)throw Ut.error;const{uploadUrl:Wt,apiKey:us}=Ut.data,zt=new XMLHttpRequest;await new Promise((As,vt)=>{zt.upload.addEventListener("progress",Ws=>{if(Ws.lengthComputable){const on=Math.round(Ws.loaded/Ws.total*100);console.log("Upload progress:",on)}}),zt.addEventListener("load",()=>{zt.status>=200&&zt.status<300?As():vt(new Error(`Upload failed with status ${zt.status}`))}),zt.addEventListener("error",()=>vt(new Error("Upload failed"))),zt.open("PUT",Wt),zt.setRequestHeader("AccessKey",us),zt.send(He)});const bt=`https://player.mediadelivery.net/embed/${qt}/${ft}`;b(bt),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{le(!1)}}},Me=async()=>{if(!p.trim()){re.error("Title is required");return}try{let Ge;if(o){const{error:He}=await q.from("levelup_briefs").update({title:p,description:x||null,video_url:v||null,graphic_url:N||null,graphic_link_url:A||null,is_published:L,publish_date:I,show_frequency:z}).eq("id",o.id);if(He)throw He;Ge=o.id,await q.from("levelup_brief_links").delete().eq("brief_id",Ge);const{data:tt}=await q.from("levelup_brief_polls").select("id").eq("brief_id",Ge);if(tt)for(const pt of tt)await q.from("levelup_brief_poll_options").delete().eq("poll_id",pt.id);await q.from("levelup_brief_polls").delete().eq("brief_id",Ge)}else{const{data:He,error:tt}=await q.from("levelup_briefs").insert({title:p,description:x||null,video_url:v||null,graphic_url:N||null,graphic_link_url:A||null,is_published:L,publish_date:I,show_frequency:z,created_by:s==null?void 0:s.id}).select().single();if(tt)throw tt;Ge=He.id}if(H.length>0){const He=H.map((tt,pt)=>({brief_id:Ge,title:tt.title,url:tt.url,sort_order:pt}));await q.from("levelup_brief_links").insert(He)}for(let He=0;He0){const qt=tt.options.map((Ut,Wt)=>({poll_id:pt.id,option_text:Ut,sort_order:Wt}));await q.from("levelup_brief_poll_options").insert(qt)}}re.success(o?"Brief updated":"Brief created"),l(!1),he(),be()}catch(Ge){console.error("Error saving brief:",Ge),re.error("Failed to save brief")}},Oe=async Ge=>{if(await Yi("Are you sure you want to delete this brief?"))try{const{error:He}=await q.from("levelup_briefs").delete().eq("id",Ge);if(He)throw He;re.success("Brief deleted"),be()}catch(He){console.error("Error deleting brief:",He),re.error("Failed to delete brief")}},Se=async Ge=>{m(Ge);const{count:He}=await q.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",Ge.id),{count:tt}=await q.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",Ge.id).not("dismissed_at","is",null);je({total:He||0,dismissed:tt||0});const{data:pt}=await q.from("levelup_brief_polls").select("*").eq("brief_id",Ge.id).order("sort_order");if(pt){const ft=[];for(const qt of pt){const{data:Ut}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",qt.id).order("sort_order"),{data:Wt}=await q.from("levelup_brief_poll_responses").select("option_id, user_id").eq("poll_id",qt.id),us=[...new Set((Wt==null?void 0:Wt.map(Ws=>Ws.user_id))||[])];let zt={};if(us.length>0){const{data:Ws}=await q.from("profiles").select("id, name, email").in("id",us);Ws&&Ws.forEach(on=>{zt[on.id]=on.name||on.email||"Unknown"})}const bt=(Wt||[]).map(Ws=>({optionId:Ws.option_id,userName:zt[Ws.user_id]||"Unknown",userId:Ws.user_id})),As={};let vt=0;Ut&&Ut.forEach(Ws=>{const on=(Wt==null?void 0:Wt.filter(Ms=>Ms.option_id===Ws.id).length)||0;As[Ws.id]=on,vt+=on}),ft.push({...qt,options:Ut||[],results:As,respondents:bt,totalResponses:qt.poll_type==="single"?new Set(Wt==null?void 0:Wt.map(Ws=>Ws.user_id)).size:vt})}ie(ft)}u(!0)},Qe=()=>{V([...H,{title:"",url:""}])},Ae=(Ge,He,tt)=>{const pt=[...H];pt[Ge][He]=tt,V(pt)},Fe=Ge=>{V(H.filter((He,tt)=>tt!==Ge))},Ne=()=>{Z([...K,{question:"",poll_type:"single",options:["",""]}])},$e=(Ge,He)=>{const tt=[...K];tt[Ge].question=He,Z(tt)},Ve=(Ge,He)=>{const tt=[...K];tt[Ge].poll_type=He,Z(tt)},qe=Ge=>{const He=[...K];He[Ge].options.push(""),Z(He)},Ze=(Ge,He,tt)=>{const pt=[...K];pt[Ge].options[He]=tt,Z(pt)},Ue=(Ge,He)=>{const tt=[...K];tt[Ge].options=tt[Ge].options.filter((pt,ft)=>ft!==He),Z(tt)},Ye=Ge=>{Z(K.filter((He,tt)=>tt!==Ge))};return e.jsxs(qs,{title:"The LevelUp Brief",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{title:"The LevelUp Brief",description:"Create engaging popup briefs for your agents",children:e.jsxs(U,{onClick:ge,children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Create Brief"]})}),e.jsx(we,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Title"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{children:"Frequency"}),e.jsx(Lt,{children:"Publish Date"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:r?e.jsx(gn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):t.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No briefs created yet"})}):t.map(Ge=>e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium",children:Ge.title}),e.jsx(gt,{children:e.jsx(Be,{variant:Ge.is_published?"default":"secondary",children:Ge.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"capitalize",children:Ge.show_frequency.replace("_"," ")}),e.jsx(gt,{children:Gs(new Date(Ge.publish_date),"MMM d, yyyy h:mm a")}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>Se(Ge),children:e.jsx(Cl,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>ke(Ge),children:e.jsx(sp,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>Oe(Ge.id),children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]})})]},Ge.id))})]})})})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Ds,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:o?"Edit Brief":"Create New Brief"})}),e.jsxs(oa,{defaultValue:"content",className:"w-full",children:[e.jsxs(la,{className:"grid w-full grid-cols-4",children:[e.jsx(Kt,{value:"content",children:"Content"}),e.jsx(Kt,{value:"media",children:"Media"}),e.jsx(Kt,{value:"links",children:"Links"}),e.jsx(Kt,{value:"polls",children:"Polls"})]}),e.jsxs(Zt,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Title *"}),e.jsx(xe,{value:p,onChange:Ge=>f(Ge.target.value),placeholder:"What's happening at LevelUp..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Description"}),e.jsx(SN,{content:x,onChange:Ge=>y(Ge),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(te,{children:"Publish Date"}),e.jsx(xe,{type:"datetime-local",value:I,onChange:Ge=>R(Ge.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Show Frequency"}),e.jsxs(Ns,{value:z,onValueChange:$,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"once",children:"Once (until dismissed)"}),e.jsx(et,{value:"every_login",children:"Every login"}),e.jsx(et,{value:"daily",children:"Daily"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(wn,{checked:L,onCheckedChange:M}),e.jsx(te,{children:"Publish immediately"})]})]}),e.jsxs(Zt,{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(te,{children:"Upload Video to Bunny.net"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(xe,{type:"file",accept:"video/*",onChange:Te,disabled:Q})}),Q&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Or paste embed URL"}),e.jsx(xe,{value:v,onChange:Ge=>b(Ge.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(te,{children:"Upload Image"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(xe,{type:"file",accept:"image/*",onChange:async Ge=>{var tt;const He=(tt=Ge.target.files)==null?void 0:tt[0];if(He){se(!0);try{const pt=He.name.split(".").pop(),ft=`brief-graphics/${Date.now()}.${pt}`,{error:qt}=await q.storage.from("banner-images").upload(ft,He,{upsert:!0});if(qt)throw qt;const{data:Ut}=q.storage.from("banner-images").getPublicUrl(ft);S(Ut.publicUrl),re.success("Image uploaded!")}catch(pt){console.error(pt),re.error("Failed to upload image")}finally{se(!1)}}},disabled:ue})}),ue&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Or paste Image URL"}),e.jsx(xe,{value:N,onChange:Ge=>S(Ge.target.value),placeholder:"https://example.com/image.png"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Click-through Link (optional)"}),e.jsx(xe,{value:A,onChange:Ge=>T(Ge.target.value),placeholder:"https://example.com/landing-page"})]}),N&&e.jsx("div",{className:"rounded-lg overflow-hidden bg-muted border",children:e.jsx("img",{src:N,alt:"Brief graphic preview",className:"w-full object-contain max-h-64"})})]})]}),e.jsxs(Zt,{value:"links",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(te,{children:"Quick Links"}),e.jsxs(U,{variant:"outline",size:"sm",onClick:Qe,children:[e.jsx(an,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),H.map((Ge,He)=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx(xe,{value:Ge.title,onChange:tt=>Ae(He,"title",tt.target.value),placeholder:"Link title",className:"flex-1"}),e.jsx(xe,{value:Ge.url,onChange:tt=>Ae(He,"url",tt.target.value),placeholder:"https://...",className:"flex-[2]"}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>Fe(He),children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]},He)),H.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No links added yet"})]}),e.jsxs(Zt,{value:"polls",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(te,{children:"Polls"}),e.jsxs(U,{variant:"outline",size:"sm",onClick:Ne,children:[e.jsx(an,{className:"h-4 w-4 mr-1"}),"Add Poll"]})]}),K.map((Ge,He)=>e.jsx(we,{className:"p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(xe,{value:Ge.question,onChange:tt=>$e(He,tt.target.value),placeholder:"Poll question...",className:"flex-1 mr-2"}),e.jsxs(Ns,{value:Ge.poll_type,onValueChange:tt=>Ve(He,tt),children:[e.jsx(ws,{className:"w-32",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"single",children:"Single"}),e.jsx(et,{value:"multi",children:"Multi-select"})]})]}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>Ye(He),children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]}),e.jsxs("div",{className:"space-y-2 pl-4",children:[Ge.options.map((tt,pt)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:tt,onChange:ft=>Ze(He,pt,ft.target.value),placeholder:`Option ${pt+1}`}),Ge.options.length>2&&e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>Ue(He,pt),children:e.jsx(In,{className:"h-4 w-4 text-muted-foreground"})})]},pt)),e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>qe(He),children:[e.jsx(an,{className:"h-4 w-4 mr-1"}),"Add Option"]})]})]})},He)),K.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(U,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(U,{onClick:Me,children:o?"Update Brief":"Create Brief"})]})]})}),e.jsx(zs,{open:d,onOpenChange:u,children:e.jsxs(Ds,{className:"max-w-2xl",children:[e.jsx(Vs,{children:e.jsxs($s,{children:["Results: ",h==null?void 0:h.title]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{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(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{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})})]})]}),ne.length>0?e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"font-semibold",children:"Poll Results"}),ne.map(Ge=>e.jsxs(we,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:Ge.question}),e.jsx("div",{className:"space-y-2",children:Ge.options.map(He=>{const tt=Ge.results[He.id]||0,pt=Ge.totalResponses>0?Math.round(tt/Ge.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:He.option_text}),e.jsxs("span",{className:"text-muted-foreground",children:[tt," (",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}%`}})}),tt>0&&e.jsx("div",{className:"flex flex-wrap gap-1 pt-1",children:(Ge.respondents||[]).filter(ft=>ft.optionId===He.id).map((ft,qt)=>e.jsx(Be,{variant:"secondary",className:"text-xs font-normal",children:ft.userName},qt))})]},He.id)})})]},Ge.id))]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls in this brief"})]})]})})]})}const yEn=()=>{const{user:s}=vs(),{toast:t}=Ai(),n=Qt(),[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:p=[],isLoading:f}=ct({queryKey:["additional-services-admin"],queryFn:async()=>{const{data:A,error:T}=await q.from("additional_services").select("*").order("publish_date",{ascending:!1});if(T)throw T;return A}}),x=yt({mutationFn:async A=>{let T=A.existingImageUrl;if(A.image){const M=A.image.name.split(".").pop(),I=`${Date.now()}-${Math.random().toString(36).substring(7)}.${M}`,{error:R}=await q.storage.from("service-images").upload(I,A.image);if(R)throw R;const{data:z}=q.storage.from("service-images").getPublicUrl(I);T=z.publicUrl}const L={name:A.item.name,description:A.item.description||null,preview_image_url:T,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:M}=await q.from("additional_services").update(L).eq("id",A.itemId);if(M)throw M}else{const{error:M}=await q.from("additional_services").insert(L);if(M)throw M}},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=yt({mutationFn:async A=>{const{error:T}=await q.from("additional_services").delete().eq("id",A);if(T)throw T},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)},N=A=>{var L;const T=(L=A.target.files)==null?void 0:L[0];T&&(u(T),m(URL.createObjectURL(T)))},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(qs,{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(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Total Services"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.length})})]}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.filter(A=>A.is_published).length})})]})]}),e.jsxs(zs,{open:r,onOpenChange:A=>{a(A),A||v()},children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{className:"gap-2",children:[e.jsx(an,{className:"h-4 w-4"}),"Add Service"]})}),e.jsxs(Ds,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:i?"Edit Service":"Add New Service"})}),e.jsxs("form",{onSubmit:S,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"name",children:"Name *"}),e.jsx(xe,{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(te,{children:"Description"}),e.jsx(SN,{content:o.description,onChange:A=>c({...o,description:A}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"signup_link_url",children:"Signup Link URL *"}),e.jsx(xe,{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(te,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(xe,{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(wn,{id:"is_published",checked:o.is_published,onCheckedChange:A=>c({...o,is_published:A})}),e.jsx(te,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{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(U,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),m("")},children:e.jsx(er,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(pc,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(xe,{type:"file",accept:"image/*",onChange:N,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(U,{type:"submit",disabled:x.isPending,children:x.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(we,{children:e.jsx(Ie,{className:"p-0",children:f?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"})}):p.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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{className:"w-16",children:"Preview"}),e.jsx(Lt,{children:"Name"}),e.jsx(Lt,{children:"Signup Link"}),e.jsx(Lt,{children:"Publish Date"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:p.map(A=>e.jsxs(gn,{children:[e.jsx(gt,{children:A.preview_image_url?e.jsx("img",{src:A.preview_image_url,alt:"",className:"w-12 h-12 object-cover rounded"}):e.jsx("div",{className:"w-12 h-12 bg-muted rounded flex items-center justify-center",children:e.jsx(pc,{className:"h-5 w-5 text-muted-foreground"})})}),e.jsx(gt,{className:"font-medium",children:A.name}),e.jsx(gt,{children:e.jsxs("a",{href:A.signup_link_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline flex items-center gap-1",children:[e.jsx(Sr,{className:"h-3 w-3"}),"Link"]})}),e.jsx(gt,{children:new Date(A.publish_date).toLocaleDateString()}),e.jsx(gt,{children:e.jsx(Be,{variant:A.is_published?"default":"secondary",children:A.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>b(A),children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:async()=>{await Yi("Are you sure you want to delete this service?")&&y.mutate(A.id)},children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]})})]},A.id))})]})})})]})})};function vEn(){const{toast:s}=Ai(),[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)}},p=async y=>{if(await Yi("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"})}},f=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(qs,{title:"Subscription Discounts",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{title:"Subscription Discounts",description:"Create and manage discount coupons for subscriptions",children:e.jsxs(zs,{open:o,onOpenChange:c,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{children:[e.jsx(an,{className:"mr-2 h-4 w-4"}),"Create Coupon"]})}),e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{children:"Promotion Code (what users will type)"}),e.jsx(xe,{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(te,{children:"Coupon Name (internal label)"}),e.jsx(xe,{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(te,{children:"Discount Type"}),e.jsxs(Ns,{value:d.discountType,onValueChange:y=>{const v=y==="amount"&&d.duration==="forever"?"once":d.duration;u({...d,discountType:y,duration:v})},children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"percent",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(PM,{className:"mr-2 h-4 w-4"}),"Percentage Off"]})}),e.jsx(et,{value:"amount",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(yu,{className:"mr-2 h-4 w-4"}),"Fixed Amount Off"]})})]})]})]}),d.discountType==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Percent Off"}),e.jsxs("div",{className:"relative",children:[e.jsx(xe,{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(te,{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(xe,{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(te,{children:"Duration"}),e.jsxs(Ns,{value:d.duration,onValueChange:y=>u({...d,duration:y}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"once",children:"Once (first payment only)"}),e.jsx(et,{value:"repeating",children:"Multiple months"}),e.jsxs(et,{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(te,{children:"Number of Months"}),e.jsx(xe,{type:"number",min:"1",placeholder:"3",value:d.durationInMonths,onChange:y=>u({...d,durationInMonths:y.target.value})})]}),e.jsx(U,{onClick:m,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Coupon"})]})]})]})}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"Active Coupons"}),e.jsx(Jn,{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(Et,{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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Promo Code"}),e.jsx(Lt,{children:"Name"}),e.jsx(Lt,{children:"Discount"}),e.jsx(Lt,{children:"Duration"}),e.jsx(Lt,{children:"Redemptions"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:t.map(y=>{var v;return e.jsxs(gn,{children:[e.jsx(gt,{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(gt,{children:y.name||"-"}),e.jsx(gt,{children:f(y)}),e.jsx(gt,{children:x(y)}),e.jsx(gt,{children:y.times_redeemed}),e.jsx(gt,{children:e.jsx(Be,{variant:y.valid?"default":"secondary",children:y.valid?"Active":"Inactive"})}),e.jsx(gt,{className:"text-right",children:e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>p(y.id),children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})})]},y.id)})})]})})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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 L7e={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 bEn(){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}=ct({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}=ct({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:T}=await q.from("user_roles").select("user_id").eq("role","brokerage_manager"),L=(T==null?void 0:T.map(R=>R.user_id))||[],M=(A==null?void 0:A.filter(R=>L.includes(R.id)))||[],I=(A==null?void 0:A.length)||0;return{...S,managers:M,agentCount:I}}))}}),{data:m}=ct({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}}),p=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=L7e[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"}},f=c==null?void 0:c.filter(v=>{var N,S;if(!(((N=v.name)==null?void 0:N.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(p(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(qs,{title:"Subscription Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{title:"Subscription Management",description:"Track and manage all subscriptions",children:e.jsxs(U,{onClick:()=>u(),variant:"outline",size:"sm",children:[e.jsx(no,{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(we,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bn,{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(we,{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(oy,{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(we,{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(Yr,{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(we,{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(h0,{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(we,{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(_i,{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(we,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(tN,{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(we,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_i,{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(oa,{defaultValue:"users",className:"space-y-4",children:[e.jsxs(la,{children:[e.jsx(Kt,{value:"users",children:"All Users"}),e.jsx(Kt,{value:"brokerages",children:"Brokerages"}),e.jsxs(Kt,{value:"websites",className:"gap-2",children:[e.jsx(fl,{className:"h-4 w-4"}),"Website Subscriptions",m&&m.length>0&&e.jsx(Be,{variant:"secondary",className:"ml-1",children:m.length})]})]}),e.jsxs(Zt,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name or email...",value:s,onChange:v=>t(v.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:a,onValueChange:v=>i(v),children:[e.jsx(ws,{className:"w-[200px]",children:e.jsx(ks,{placeholder:"Source"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Sources"}),e.jsx(et,{value:"platform",children:"Platform"}),e.jsx(et,{value:"local_move_website",children:"Local Move Website"})]})]}),e.jsxs(Ns,{value:n,onValueChange:v=>r(v),children:[e.jsx(ws,{className:"w-[200px]",children:e.jsx(ks,{placeholder:"Filter by status"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Statuses"}),e.jsx(et,{value:"active",children:"Active Subscriptions"}),e.jsx(et,{value:"trialing",children:"Trials"}),e.jsx(et,{value:"grandfathered",children:"Grandfathered"}),e.jsx(et,{value:"brokerage",children:"Brokerage Members"}),e.jsx(et,{value:"expired",children:"Expired/Canceled"}),e.jsx(et,{value:"none",children:"No Subscription"})]})]})]}),e.jsx(we,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"User"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{children:"Plan"}),e.jsx(Lt,{children:"Brokerage"}),e.jsx(Lt,{children:"End Date"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:d?e.jsx(gn,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8",children:"Loading subscriptions..."})}):(f==null?void 0:f.length)===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):f==null?void 0:f.map(v=>{var S,A;const b=p(v),N=L7e[v.subscription_product_id];return e.jsxs(gn,{children:[e.jsx(gt,{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(gt,{children:e.jsx(Be,{variant:b.variant,children:b.badge})}),e.jsx(gt,{children:e.jsx("span",{className:"text-sm",children:v.is_grandfathered?"Legacy Access":v.brokerage_id&&!v.subscription_product_id?"Brokerage Subscription":(N==null?void 0:N.name)||b.status})}),e.jsx(gt,{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(gt,{children:v.subscription_end_date?e.jsx("span",{className:"text-sm",children:Gs(new Date(v.subscription_end_date),"MMM d, yyyy")}):v.trial_expires_at?e.jsxs("span",{className:"text-sm text-blue-600",children:["Trial: ",Gs(new Date(v.trial_expires_at),"MMM d, yyyy")]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[v.stripe_customer_id&&e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>y(v.stripe_customer_id),children:e.jsx(Sr,{className:"h-4 w-4"})}),e.jsxs(zs,{children:[e.jsx(al,{asChild:!0,children:e.jsx(U,{variant:"outline",size:"sm",onClick:()=>o(v),children:"Details"})}),e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(Be,{variant:b.variant,className:"mt-1",children:b.badge})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Plan"}),e.jsx("p",{className:"font-medium",children:v.is_grandfathered?"Grandfathered (Legacy)":v.brokerage_id&&!v.subscription_product_id?"Brokerage Subscription":(N==null?void 0:N.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:Gs(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:Gs(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(U,{className:"w-full",onClick:()=>y(v.stripe_customer_id),children:[e.jsx(Sr,{className:"h-4 w-4 mr-2"}),"View in Stripe Dashboard"]})]})]})]})]})})]},v.id)})})]})})})]}),e.jsx(Zt,{value:"brokerages",className:"space-y-4",children:e.jsx("div",{className:"grid gap-4",children:h==null?void 0:h.map(v=>{var N,S;const b=(N=v.managers)==null?void 0:N.some(A=>A.subscription_status==="active"&&(A.subscription_product_id==="prod_Tc08MupgoVySDG"||A.subscription_product_id==="prod_Tc09N1tJ4RrAFn"));return e.jsxs(we,{children:[e.jsx(Tt,{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(_i,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(It,{className:"text-lg",children:v.name}),e.jsxs(Jn,{children:[v.agentCount," agents"]})]})]}),e.jsx(Be,{variant:b?"default":"outline",children:b?"Active Subscription":"No Active Subscription"})]})}),e.jsx(Ie,{children:((S=v.managers)==null?void 0:S.length)>0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Managers:"}),v.managers.map(A=>{const T=L7e[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:T?e.jsxs("div",{children:[e.jsx(Be,{variant:"default",children:T.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:T.price})]}):e.jsx(Be,{variant:"outline",children:"No Subscription"})})]},A.id)})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No managers assigned"})})]},v.id)})})}),e.jsx(Zt,{value:"websites",className:"space-y-4",children:e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(fl,{className:"h-5 w-5 text-primary"}),"Local Move Website Subscriptions"]}),e.jsx(Jn,{children:"$249 setup fee + $99/mo subscriptions from TheLocalMove.com agent websites"})]}),e.jsx(Ie,{className:"p-0",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Agent"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{children:"Setup Fee"}),e.jsx(Lt,{children:"Monthly"}),e.jsx(Lt,{children:"Next Renewal"}),e.jsx(Lt,{children:"Started"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:m?m.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No website subscriptions yet"})}):m.map(v=>e.jsxs(gn,{children:[e.jsx(gt,{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(gt,{children:e.jsx(Be,{variant:v.status==="active"?"default":v.status==="canceled"?"destructive":"outline",children:v.status})}),e.jsx(gt,{children:v.setup_fee_paid?e.jsxs(Be,{variant:"secondary",children:["Paid · $",(v.setup_fee_amount_cents/100).toFixed(0)]}):e.jsx(Be,{variant:"outline",children:"Unpaid"})}),e.jsxs(gt,{className:"font-medium",children:["$",(v.monthly_amount_cents/100).toFixed(0),"/mo"]}),e.jsx(gt,{children:v.current_period_end?e.jsx("span",{className:"text-sm",children:Gs(new Date(v.current_period_end),"MMM d, yyyy")}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(gt,{children:e.jsx("span",{className:"text-sm",children:Gs(new Date(v.created_at),"MMM d, yyyy")})}),e.jsx(gt,{className:"text-right",children:v.stripe_customer_id&&e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>y(v.stripe_customer_id),children:e.jsx(Sr,{className:"h-4 w-4"})})})]},v.id)):e.jsx(gn,{children:e.jsx(gt,{colSpan:7,className:"text-center py-8",children:"Loading…"})})})]})})]})})]})]})})}function _En(){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:f,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(f||[]);const y=(f==null?void 0:f.filter(N=>N.status==="qualified").length)||0,v=(f==null?void 0:f.filter(N=>N.status==="pending").length)||0,b=(f==null?void 0:f.filter(N=>N.status==="cancelled").length)||0;d({total:(f==null?void 0:f.length)||0,qualified:y,pending:v,cancelled:b,totalDiscounts:y*25})}catch(f){console.error("Error fetching referrals:",f),re.error("Failed to load referrals")}finally{r(!1)}},h=async()=>{try{re.loading("Processing qualifications...");const{error:f}=await q.functions.invoke("process-referral-qualifications");if(f)throw f;re.dismiss(),re.success("Qualifications processed successfully"),u()}catch(f){re.dismiss(),console.error("Error processing qualifications:",f),re.error("Failed to process qualifications")}},m=s.filter(f=>{var v,b,N,S,A,T;const x=((b=(v=f.referrer_brokerage)==null?void 0:v.name)==null?void 0:b.toLowerCase().includes(a.toLowerCase()))||((S=(N=f.referred_brokerage)==null?void 0:N.name)==null?void 0:S.toLowerCase().includes(a.toLowerCase()))||((T=(A=f.referred_user)==null?void 0:A.email)==null?void 0:T.toLowerCase().includes(a.toLowerCase())),y=l==="all"||f.status===l;return x&&y}),p=f=>{switch(f){case"qualified":return e.jsxs(Be,{className:"bg-green-100 text-green-800",children:[e.jsx(Yo,{className:"h-3 w-3 mr-1"}),"Qualified"]});case"pending":return e.jsxs(Be,{variant:"secondary",children:[e.jsx(Yr,{className:"h-3 w-3 mr-1"}),"Pending"]});case"cancelled":return e.jsxs(Be,{variant:"destructive",children:[e.jsx(ou,{className:"h-3 w-3 mr-1"}),"Cancelled"]});default:return e.jsx(Be,{children:f})}};return e.jsx(qs,{title:"Referral Program",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{title:"Referral Program",description:"Track and manage brokerage referrals",children:e.jsxs(U,{onClick:h,variant:"outline",children:[e.jsx(no,{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(we,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bn,{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(we,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yo,{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(we,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yr,{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(we,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ou,{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(we,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yu,{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(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"All Referrals"}),e.jsx(Jn,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by brokerage or email...",value:a,onChange:f=>i(f.target.value),className:"pl-10"})]}),e.jsxs(Ns,{value:l,onValueChange:o,children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{placeholder:"Filter by status"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Statuses"}),e.jsx(et,{value:"pending",children:"Pending"}),e.jsx(et,{value:"qualified",children:"Qualified"}),e.jsx(et,{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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Referrer"}),e.jsx(Lt,{children:"Referred"}),e.jsx(Lt,{children:"Signup Date"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{children:"Qualified Date"}),e.jsx(Lt,{children:"Discount"})]})}),e.jsx(Xa,{children:m.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No referrals found"})}):m.map(f=>{var x,y,v,b;return e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium",children:((x=f.referrer_brokerage)==null?void 0:x.name)||"Unknown"}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{children:((y=f.referred_brokerage)==null?void 0:y.name)||((v=f.referred_user)==null?void 0:v.name)||"Pending setup"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(b=f.referred_user)==null?void 0:b.email})]})}),e.jsx(gt,{children:Gs(new Date(f.signup_date),"MMM d, yyyy")}),e.jsx(gt,{children:p(f.status)}),e.jsx(gt,{children:f.qualified_date?Gs(new Date(f.qualified_date),"MMM d, yyyy"):"-"}),e.jsx(gt,{children:f.discount_applied?e.jsx(Be,{variant:"outline",className:"text-green-600",children:"$25/mo applied"}):e.jsx("span",{className:"text-muted-foreground",children:"-"})})]},f.id)})})]})]})]})]})})}const I7e=[{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"}],wEn=[{value:"brokerage_manager",label:"Brokerage Manager"},{value:"agent",label:"Agent"}];function jEn(){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:N}=await q.from("onboarding_checklist_items").select("*").order("target_role").order("sort_order");if(N)throw N;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)},p=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:N}=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(N)throw N;re.success("Checklist item created")}i(!1),u()}catch(b){console.error("Error saving checklist item:",b),re.error("Failed to save checklist item")}},f=async b=>{if(await Yi("Are you sure you want to delete this checklist item?"))try{const{error:N}=await q.from("onboarding_checklist_items").delete().eq("id",b);if(N)throw N;re.success("Checklist item deleted"),u()}catch(N){console.error("Error deleting checklist item:",N),re.error("Failed to delete checklist item")}},x=async b=>{try{const{error:N}=await q.from("onboarding_checklist_items").update({is_active:!b.is_active}).eq("id",b.id);if(N)throw N;re.success(b.is_active?"Item deactivated":"Item activated"),u()}catch(N){console.error("Error toggling item:",N),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(qs,{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(U,{onClick:h,className:"gap-2",children:[e.jsx(an,{className:"h-4 w-4"}),"Add Item"]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Be,{variant:"secondary",children:"Brokerage Manager"}),"Checklist Items"]})}),e.jsx(Ie,{children:y.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for brokerage managers"}):e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{className:"w-12",children:"#"}),e.jsx(Lt,{children:"Title"}),e.jsx(Lt,{children:"Action Type"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:y.map((b,N)=>{var S;return e.jsxs(gn,{children:[e.jsx(gt,{className:"text-muted-foreground",children:N+1}),e.jsx(gt,{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(gt,{children:e.jsx(Be,{variant:"outline",children:((S=I7e.find(A=>A.value===b.action_type))==null?void 0:S.label)||b.action_type})}),e.jsx(gt,{children:e.jsx(wn,{checked:b.is_active,onCheckedChange:()=>x(b)})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>m(b),children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>f(b.id),children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]})})]},b.id)})})]})})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Be,{variant:"secondary",children:"Agent"}),"Checklist Items"]})}),e.jsx(Ie,{children:v.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for agents"}):e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{className:"w-12",children:"#"}),e.jsx(Lt,{children:"Title"}),e.jsx(Lt,{children:"Action Type"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:v.map((b,N)=>{var S;return e.jsxs(gn,{children:[e.jsx(gt,{className:"text-muted-foreground",children:N+1}),e.jsx(gt,{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(gt,{children:e.jsx(Be,{variant:"outline",children:((S=I7e.find(A=>A.value===b.action_type))==null?void 0:S.label)||b.action_type})}),e.jsx(gt,{children:e.jsx(wn,{checked:b.is_active,onCheckedChange:()=>x(b)})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>m(b),children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>f(b.id),children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]})})]},b.id)})})]})})]})]}),e.jsx(zs,{open:a,onOpenChange:i,children:e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:l?"Edit Checklist Item":"Add Checklist Item"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"title",children:"Title *"}),e.jsx(xe,{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(te,{htmlFor:"description",children:"Description"}),e.jsx(Fs,{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(te,{children:"Target Role"}),e.jsxs(Ns,{value:c.target_role,onValueChange:b=>d({...c,target_role:b}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:wEn.map(b=>e.jsx(et,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Action Type"}),e.jsxs(Ns,{value:c.action_type,onValueChange:b=>d({...c,action_type:b}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:I7e.map(b=>e.jsx(et,{value:b.value,children:b.label},b.value))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wn,{id:"is_active",checked:c.is_active,onCheckedChange:b=>d({...c,is_active:b})}),e.jsx(te,{htmlFor:"is_active",children:"Active"})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(U,{onClick:p,children:l?"Save Changes":"Create Item"})]})]})})]})}function NEn(){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,p]=j.useState(""),[f,x]=j.useState(""),{data:y}=ct({queryKey:["admin-brokerages"],queryFn:async()=>{const{data:R,error:z}=await q.from("brokerages").select("id, name").order("name");if(z)throw z;return R}}),v=async R=>{let $=[],H=0,V=!0;for(;V;){const{data:K,error:Z}=await R(H,H+1e3-1);if(Z)throw Z;K&&K.length>0?($=[...$,...K],H+=1e3,V=K.length===1e3):V=!1}return $},{data:b,isLoading:N}=ct({queryKey:["admin-agent-os-user-stats"],queryFn:async()=>{const R=await v((ke,Te)=>q.from("profiles").select("id, name, email, brokerage_id, created_at").range(ke,Te)),{data:z}=await q.from("brokerages").select("id, name"),$=new Map((z==null?void 0:z.map(ke=>[ke.id,ke.name]))||[]),[{data:H},{data:V},{data:K},{data:Z},{data:Q},{data:le},{data:ue}]=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")]),se=new Map;H==null||H.forEach(ke=>se.set(ke.owner_user_id,ke.contact_count));const ne=new Map;V==null||V.forEach(ke=>ne.set(ke.owner_user_id,ke.video_count));const ie=new Map;K==null||K.forEach(ke=>ie.set(ke.owner_user_id,ke.popby_count));const ce=new Map;Z==null||Z.forEach(ke=>ce.set(ke.agent_id,ke.listing_count));const je=new Map;Q==null||Q.forEach(ke=>je.set(ke.owner_user_id,ke.deal_count));const be=new Map;le==null||le.forEach(ke=>be.set(ke.owner_user_id,{total:ke.portal_count,active:ke.active_portal_count}));const he=new Map;return ue==null||ue.forEach(ke=>he.set(ke.owner_user_id,{total:ke.card_count,sent:ke.sent_card_count,views:ke.total_card_views})),R.map(ke=>{const Te=be.get(ke.id),Me=he.get(ke.id);return{id:ke.id,name:ke.name||"Unknown",email:ke.email||"",brokerage_id:ke.brokerage_id,brokerage_name:ke.brokerage_id&&$.get(ke.brokerage_id)||null,contact_count:se.get(ke.id)||0,video_count:ne.get(ke.id)||0,popby_count:ie.get(ke.id)||0,listing_count:ce.get(ke.id)||0,deal_count:je.get(ke.id)||0,portal_count:(Te==null?void 0:Te.total)||0,active_portal_count:(Te==null?void 0:Te.active)||0,card_count:(Me==null?void 0:Me.total)||0,sent_card_count:(Me==null?void 0:Me.sent)||0,total_card_views:(Me==null?void 0:Me.views)||0,created_at:ke.created_at}})}}),S=j.useMemo(()=>{if(!b)return[];let R=b.filter(z=>{const $=s.toLowerCase(),H=!s||z.name.toLowerCase().includes($)||z.email.toLowerCase().includes($),V=n==="all"||n==="none"&&!z.brokerage_id||z.brokerage_id===n,K=parseInt(c)||0,Z=parseInt(u)||0,Q=parseInt(m)||0,le=parseInt(f)||0,ue=z.contact_count>=K&&z.video_count>=Z&&z.popby_count>=Q&&z.listing_count>=le;return H&&V&&ue});return R.sort((z,$)=>{let H=0;return a==="name"?H=z.name.localeCompare($.name):H=z[a]-$[a],l==="asc"?H:-H}),R},[b,s,n,a,l,c,u,m,f]),A=R=>{a===R?o(l==="asc"?"desc":"asc"):(i(R),o("desc"))},T=()=>{const R=["Name","Email","Brokerage","Contacts","Videos","Popbys","Listings","Deals","Portals (Active)","Cards Created","Cards Sent","Card Views"],z=S.map(Z=>[Z.name,Z.email,Z.brokerage_name||"None",Z.contact_count,Z.video_count,Z.popby_count,Z.listing_count,Z.deal_count,`${Z.portal_count} (${Z.active_portal_count})`,Z.card_count,Z.sent_card_count,Z.total_card_views]),$=[R.join(","),...z.map(Z=>Z.map(Q=>`"${Q}"`).join(","))].join(` `),H=new Blob([$],{type:"text/csv"}),V=URL.createObjectURL(H),K=document.createElement("a");K.href=V,K.download=`agent-os-user-stats-${new Date().toISOString().split("T")[0]}.csv`,K.click(),URL.revokeObjectURL(V)},L=j.useMemo(()=>S.length?S.reduce((R,z)=>({contacts:R.contacts+z.contact_count,videos:R.videos+z.video_count,popbys:R.popbys+z.popby_count,listings:R.listings+z.listing_count,deals:R.deals+z.deal_count,portals:R.portals+z.portal_count,activePortals:R.activePortals+z.active_portal_count,cards:R.cards+z.card_count,sentCards:R.sentCards+z.sent_card_count,cardViews:R.cardViews+z.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]),M=j.useMemo(()=>S.length?{portals:S.filter(R=>R.portal_count>0).length,cards:S.filter(R=>R.card_count>0).length}:{portals:0,cards:0},[S]),I=({field:R,children:z})=>e.jsx(Lt,{className:"cursor-pointer hover:bg-muted/50 select-none",onClick:()=>A(R),children:e.jsxs("div",{className:"flex items-center gap-1",children:[z,e.jsx(xx,{className:`h-3 w-3 ${a===R?"text-primary":"text-muted-foreground"}`})]})});return e.jsx(wN,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(we,{className:"border-blue-500/20 bg-gradient-to-br from-blue-500/5 to-transparent",children:[e.jsx(Tt,{className:"pb-2",children:e.jsxs(It,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(G2,{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:M.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:L.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:L.activePortals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Active Portals"})]})]})})]}),e.jsxs(we,{className:"border-violet-500/20 bg-gradient-to-br from-violet-500/5 to-transparent",children:[e.jsx(Tt,{className:"pb-2",children:e.jsxs(It,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(ln,{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:M.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:L.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:L.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:L.cardViews}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Views"})]})]})})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-5 w-5"}),"User Activity Analytics"]}),e.jsx(Jn,{children:"View all users and their Agent OS usage metrics"})]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:T,children:[e.jsx(pi,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name or email...",value:s,onChange:R=>t(R.target.value),className:"pl-9"})]})}),e.jsx("div",{children:e.jsxs(Ns,{value:n,onValueChange:r,children:[e.jsxs(ws,{children:[e.jsx(_i,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(ks,{placeholder:"Brokerage"})]}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Brokerages"}),e.jsx(et,{value:"none",children:"No Brokerage"}),y==null?void 0:y.map(R=>e.jsx(et,{value:R.id,children:R.name},R.id))]})]})}),e.jsx("div",{children:e.jsx(xe,{type:"number",placeholder:"Min contacts",value:c,onChange:R=>d(R.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(xe,{type:"number",placeholder:"Min videos",value:u,onChange:R=>h(R.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(xe,{type:"number",placeholder:"Min popbys",value:m,onChange:R=>p(R.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:L.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:L.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:L.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:L.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:L.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:L.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:L.cards.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Cards"})]})]}),N?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Et,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(I,{field:"name",children:"Name"}),e.jsx(Lt,{children:"Email"}),e.jsx(Lt,{children:"Brokerage"}),e.jsx(I,{field:"contact_count",children:"Contacts"}),e.jsx(I,{field:"video_count",children:"Videos"}),e.jsx(I,{field:"popby_count",children:"Popbys"}),e.jsx(I,{field:"listing_count",children:"Listings"}),e.jsx(I,{field:"deal_count",children:"Deals"}),e.jsx(I,{field:"portal_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(G2,{className:"h-3 w-3 text-blue-500"}),"Portals"]})}),e.jsx(I,{field:"card_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ln,{className:"h-3 w-3 text-violet-500"}),"Cards"]})})]})}),e.jsx(Xa,{children:S.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:"No users found matching your filters"})}):S.map(R=>e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium",children:R.name}),e.jsx(gt,{className:"text-muted-foreground",children:R.email}),e.jsx(gt,{children:R.brokerage_name?e.jsx(Be,{variant:"secondary",children:R.brokerage_name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{children:e.jsx(Be,{variant:R.contact_count>0?"default":"outline",children:R.contact_count})}),e.jsx(gt,{children:e.jsx(Be,{variant:R.video_count>0?"default":"outline",children:R.video_count})}),e.jsx(gt,{children:e.jsx(Be,{variant:R.popby_count>0?"default":"outline",children:R.popby_count})}),e.jsx(gt,{children:e.jsx(Be,{variant:R.listing_count>0?"default":"outline",children:R.listing_count})}),e.jsx(gt,{children:e.jsx(Be,{variant:R.deal_count>0?"default":"outline",children:R.deal_count})}),e.jsx(gt,{children:R.portal_count>0?e.jsxs(Bg,{children:[e.jsx(Ug,{children:e.jsxs(Be,{variant:"default",className:"bg-blue-600 hover:bg-blue-700",children:[R.portal_count,R.active_portal_count>0&&e.jsxs("span",{className:"ml-1 opacity-75",children:["(",R.active_portal_count," active)"]})]})}),e.jsxs(ng,{children:[e.jsxs("p",{children:[R.portal_count," total portals"]}),e.jsxs("p",{children:[R.active_portal_count," currently active"]})]})]}):e.jsx(Be,{variant:"outline",children:"0"})}),e.jsx(gt,{children:R.card_count>0?e.jsxs(Bg,{children:[e.jsx(Ug,{children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Be,{variant:"default",className:"bg-violet-600 hover:bg-violet-700",children:R.card_count}),R.sent_card_count>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-emerald-600",children:[e.jsx($r,{className:"h-3 w-3"}),R.sent_card_count]}),R.total_card_views>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-muted-foreground",children:[e.jsx(xa,{className:"h-3 w-3"}),R.total_card_views]})]})}),e.jsxs(ng,{children:[e.jsxs("p",{children:[R.card_count," cards created"]}),e.jsxs("p",{children:[R.sent_card_count," sent"]}),e.jsxs("p",{children:[R.total_card_views," total views"]})]})]}):e.jsx(Be,{variant:"outline",children:"0"})})]},R.id))})]})})]})]})]})})}function kEn(){Ai(),Qt();const[s,t]=j.useState("user-analytics"),{data:n}=ct({queryKey:["admin-feature-flags"],queryFn:async()=>{const{data:p,error:f}=await q.from("feature_flags").select("*").order("key");if(f)throw f;return p}}),{data:r,isLoading:a}=ct({queryKey:["admin-relationship-types"],queryFn:async()=>{const{data:p,error:f}=await q.from("relationship_types").select("*").order("sort_order");if(f)throw f;return p}}),{data:i,isLoading:l}=ct({queryKey:["admin-action-types"],queryFn:async()=>{const{data:p,error:f}=await q.from("action_types").select("*").order("sort_order");if(f)throw f;return p}}),{data:o,isLoading:c}=ct({queryKey:["admin-action-scripts"],queryFn:async()=>{const{data:p,error:f}=await q.from("action_scripts").select("*, action_type:action_types(*)");if(f)throw f;return p}}),{data:d,isLoading:u}=ct({queryKey:["admin-touchpoint-plans"],queryFn:async()=>{const{data:p,error:f}=await q.from("touchpoint_plans").select("*").order("name");if(f)throw f;return p}}),{data:h,isLoading:m}=ct({queryKey:["admin-popby-items"],queryFn:async()=>{const{data:p,error:f}=await q.from("popby_items").select("*").is("owner_user_id",null).order("name");if(f)throw f;return p}});return e.jsx(qs,{title:"Agent OS Control Center",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{title:"Agent OS Control Center",description:"Manage InnerCircle settings, scripts, and touchpoint plans"}),e.jsxs(oa,{value:s,onValueChange:t,children:[e.jsxs(la,{className:"grid w-full grid-cols-9",children:[e.jsxs(Kt,{value:"user-analytics",className:"gap-2",children:[e.jsx(Cl,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(Kt,{value:"relationship-types",className:"gap-2",children:[e.jsx(Bn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Relationships"})]}),e.jsxs(Kt,{value:"action-types",className:"gap-2",children:[e.jsx(ba,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(Kt,{value:"scripts",className:"gap-2",children:[e.jsx(Ur,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Scripts"})]}),e.jsxs(Kt,{value:"video-scripts",className:"gap-2",children:[e.jsx(Gh,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Video Scripts"})]}),e.jsxs(Kt,{value:"plans",className:"gap-2",children:[e.jsx(pa,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Plans"})]}),e.jsxs(Kt,{value:"popbys",className:"gap-2",children:[e.jsx(Ro,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Popbys"})]}),e.jsxs(Kt,{value:"settings",className:"gap-2",children:[e.jsx(qc,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Settings"})]}),e.jsxs(Kt,{value:"feature-flags",className:"gap-2",children:[e.jsx(NA,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Flags"})]})]}),e.jsx(Zt,{value:"user-analytics",className:"mt-6",children:e.jsx(NEn,{})}),e.jsx(Zt,{value:"relationship-types",className:"mt-6",children:e.jsx(SEn,{types:r||[],isLoading:a})}),e.jsx(Zt,{value:"action-types",className:"mt-6",children:e.jsx(CEn,{types:i||[],isLoading:l})}),e.jsx(Zt,{value:"scripts",className:"mt-6",children:e.jsx(AEn,{scripts:o||[],actionTypes:i||[],isLoading:c})}),e.jsx(Zt,{value:"video-scripts",className:"mt-6",children:e.jsx(PEn,{})}),e.jsx(Zt,{value:"plans",className:"mt-6",children:e.jsx(EEn,{plans:d||[],actionTypes:i||[],scripts:o||[],isLoading:u})}),e.jsx(Zt,{value:"popbys",className:"mt-6",children:e.jsx(MEn,{items:h||[],isLoading:m})}),e.jsx(Zt,{value:"settings",className:"mt-6",children:e.jsx(LEn,{})}),e.jsx(Zt,{value:"feature-flags",className:"mt-6",children:e.jsx(TEn,{flags:n||[]})})]})]})})}function SEn({types:s,isLoading:t}){const{toast:n}=Ai(),r=Qt(),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=yt({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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Relationship Types"}),e.jsx(Jn,{children:"Define the relationship categories for InnerCircle contacts"})]}),e.jsxs(U,{onClick:()=>{i(null),o(!0)},children:[e.jsx(an,{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(Et,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{className:"w-12"}),e.jsx(Lt,{children:"Name"}),e.jsx(Lt,{children:"Description"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{className:"w-24",children:"Actions"})]})}),e.jsx(Xa,{children:s.map(u=>e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsx(kf,{className:"h-4 w-4 text-muted-foreground cursor-grab"})}),e.jsx(gt,{className:"font-medium",children:u.name}),e.jsx(gt,{className:"text-muted-foreground",children:u.description}),e.jsx(gt,{children:e.jsx(wn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(gt,{children:e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(ri,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsxs($s,{children:[a?"Edit":"Add"," Relationship Type"]})}),e.jsxs("form",{onSubmit:u=>{u.preventDefault();const h=new FormData(u.currentTarget);c.mutate({id:a==null?void 0:a.id,name:h.get("name"),description:h.get("description"),icon:h.get("icon")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{htmlFor:"name",children:"Name"}),e.jsx(xe,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"description",children:"Description"}),e.jsx(Fs,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"icon",children:"Icon"}),e.jsx(xe,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., star, heart, user"})]})]}),e.jsxs(Mr,{className:"mt-4",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(U,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function CEn({types:s,isLoading:t}){const{toast:n}=Ai(),r=Qt(),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=yt({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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Action Types"}),e.jsx(Jn,{children:"Define the types of touchpoint actions agents can take"})]}),e.jsxs(U,{onClick:()=>{i(null),o(!0)},children:[e.jsx(an,{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(Et,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Name"}),e.jsx(Lt,{children:"Description"}),e.jsx(Lt,{children:"Color"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{className:"w-24",children:"Actions"})]})}),e.jsx(Xa,{children:s.map(u=>e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium",children:u.name}),e.jsx(gt,{className:"text-muted-foreground",children:u.description}),e.jsx(gt,{children:u.color&&e.jsx("div",{className:"w-6 h-6 rounded",style:{backgroundColor:u.color}})}),e.jsx(gt,{children:e.jsx(wn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(gt,{children:e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(ri,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsxs($s,{children:[a?"Edit":"Add"," Action Type"]})}),e.jsxs("form",{onSubmit:u=>{u.preventDefault();const h=new FormData(u.currentTarget);c.mutate({id:a==null?void 0:a.id,name:h.get("name"),description:h.get("description"),icon:h.get("icon"),color:h.get("color")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{htmlFor:"name",children:"Name"}),e.jsx(xe,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"description",children:"Description"}),e.jsx(Fs,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"icon",children:"Icon"}),e.jsx(xe,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., phone, message"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"color",children:"Color"}),e.jsx(xe,{id:"color",name:"color",type:"color",defaultValue:(a==null?void 0:a.color)||"#6366f1"})]})]}),e.jsxs(Mr,{className:"mt-4",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(U,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function AEn({scripts:s,actionTypes:t,isLoading:n}){const{toast:r}=Ai(),a=Qt(),[i,l]=j.useState(null),[o,c]=j.useState(!1),d=yt({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=yt({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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Script Library"}),e.jsx(Jn,{children:"Create and manage scripts for each action type"})]}),e.jsxs(U,{onClick:()=>{l(null),c(!0)},children:[e.jsx(an,{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(Et,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Title"}),e.jsx(Lt,{children:"Action Type"}),e.jsx(Lt,{children:"Tone"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{className:"w-24",children:"Actions"})]})}),e.jsx(Xa,{children:s.map(h=>{var m;return e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium",children:h.title}),e.jsx(gt,{children:e.jsx(Be,{variant:"outline",children:((m=h.action_type)==null?void 0:m.name)||"Unknown"})}),e.jsx(gt,{className:"text-muted-foreground",children:h.tone}),e.jsx(gt,{children:e.jsx(Be,{variant:h.active?"default":"secondary",children:h.active?"Active":"Inactive"})}),e.jsxs(gt,{className:"flex gap-1",children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>{l(h),c(!0)},children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>u.mutate(h.id),children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]})]},h.id)})})]})}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Ds,{className:"max-w-2xl",children:[e.jsx(Vs,{children:e.jsxs($s,{children:[i?"Edit":"Add"," Script"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const m=new FormData(h.currentTarget);d.mutate({id:i==null?void 0:i.id,title:m.get("title"),action_type_id:m.get("action_type_id"),tone:m.get("tone"),script_body:m.get("script_body"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(te,{htmlFor:"title",children:"Title"}),e.jsx(xe,{id:"title",name:"title",defaultValue:i==null?void 0:i.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"action_type_id",children:"Action Type"}),e.jsxs(Ns,{name:"action_type_id",defaultValue:i==null?void 0:i.action_type_id,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select action type"})}),e.jsx(js,{children:t.map(h=>e.jsx(et,{value:h.id,children:h.name},h.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"tone",children:"Tone (optional)"}),e.jsx(xe,{id:"tone",name:"tone",defaultValue:(i==null?void 0:i.tone)||"",placeholder:"e.g., Friendly, Professional, Casual"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"script_body",children:"Script Body"}),e.jsx(Fs,{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(Mr,{className:"mt-4",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(U,{type:"submit",disabled:d.isPending,children:[d.isPending&&e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function EEn({plans:s,actionTypes:t,scripts:n,isLoading:r}){const{toast:a}=Ai(),i=Qt(),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,p]=j.useState(!1),[f,x]=j.useState(null),[y,v]=j.useState(null),{data:b}=ct({queryKey:["plan-items",u],queryFn:async()=>{if(!u)return[];const{data:I,error:R}=await q.from("touchpoint_plan_items").select("*").eq("plan_id",u).order("month_number");if(R)throw R;return I},enabled:!!u}),N=yt({mutationFn:async I=>{if(I.id){const{error:R}=await q.from("touchpoint_plans").update({name:I.name,description:I.description,active:I.active}).eq("id",I.id);if(R)throw R}else{const{error:R}=await q.from("touchpoint_plans").insert([{name:I.name,description:I.description,active:!0}]);if(R)throw R}},onSuccess:()=>{i.invalidateQueries({queryKey:["admin-touchpoint-plans"]}),d(!1),o(null),a({title:"Saved successfully"})},onError:I=>{a({title:"Error",description:I.message,variant:"destructive"})}}),S=yt({mutationFn:async I=>{if(I.id){const{error:R}=await q.from("touchpoint_plan_items").update({action_type_id:I.action_type_id,default_script_id:I.default_script_id,notes:I.notes}).eq("id",I.id);if(R)throw R}else{const{error:R}=await q.from("touchpoint_plan_items").insert([{plan_id:I.plan_id,month_number:I.month_number,action_type_id:I.action_type_id,default_script_id:I.default_script_id,notes:I.notes}]);if(R)throw R}},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]}),a({title:"Item saved"})}}),A=yt({mutationFn:async I=>{const{error:R}=await q.from("touchpoint_plan_items").delete().eq("id",I);if(R)throw R},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]})}}),T=yt({mutationFn:async I=>{const{data:R,error:z}=await q.from("action_scripts").insert([{...I,active:!0}]).select().single();if(z)throw z;return R},onSuccess:async I=>{i.invalidateQueries({queryKey:["admin-action-scripts"]}),f&&await S.mutateAsync({id:f.itemId,plan_id:u,month_number:f.month,action_type_id:f.actionTypeId,default_script_id:I.id}),p(!1),x(null),a({title:"Script created and assigned"})},onError:I=>{a({title:"Error",description:I.message,variant:"destructive"})}}),L=(I,R,z)=>{x({month:I,actionTypeId:R,itemId:z}),p(!0)},M=I=>n.find(R=>R.id===I);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Touchpoint Plans"}),e.jsx(Jn,{children:"Create annual touchpoint plans that agents can apply to their contacts"})]}),e.jsxs(U,{onClick:()=>{o(null),d(!0)},children:[e.jsx(an,{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(Et,{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(I=>e.jsxs(we,{className:`cursor-pointer transition-colors ${u===I.id?"border-primary":""}`,onClick:()=>h(I.id),children:[e.jsx(Tt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(It,{className:"text-base",children:I.name}),e.jsx(U,{variant:"ghost",size:"icon",onClick:R=>{R.stopPropagation(),o(I),d(!0)},children:e.jsx(ri,{className:"h-4 w-4"})})]})}),e.jsxs(Ie,{children:[e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:I.description}),e.jsx(Be,{variant:I.active?"default":"secondary",className:"mt-2",children:I.active?"Active":"Inactive"})]})]},I.id))})})]}),u&&e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"Plan Schedule"}),e.jsx(Jn,{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},(I,R)=>R+1).map(I=>{const R=b==null?void 0:b.find(H=>H.month_number===I),z=R!=null&&R.default_script_id?M(R.default_script_id):null,$=n.filter(H=>H.action_type_id===(R==null?void 0:R.action_type_id)&&H.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 ",I]}),e.jsxs(Ns,{value:(R==null?void 0:R.action_type_id)||"none",onValueChange:H=>{H==="none"&&R?A.mutate(R.id):H!=="none"&&S.mutate({id:R==null?void 0:R.id,plan_id:u,month_number:I,action_type_id:H,default_script_id:null})},children:[e.jsx(ws,{className:"w-40",children:e.jsx(ks,{placeholder:"No action"})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"No action"}),t.filter(H=>H.active).map(H=>e.jsx(et,{value:H.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[H.color&&e.jsx("span",{className:"w-3 h-3 rounded-full",style:{backgroundColor:H.color}}),H.name]})},H.id))]})]}),R&&e.jsxs(e.Fragment,{children:[e.jsxs(Ns,{value:R.default_script_id||"none",onValueChange:H=>{v(null),S.mutate({id:R.id,default_script_id:H==="none"?null:H})},children:[e.jsx(ws,{className:"w-56",children:e.jsx(ks,{placeholder:"Select script"})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"No default script"}),$.map(H=>e.jsxs(et,{value:H.id,children:[H.title," ",H.tone&&`(${H.tone})`]},H.id))]})]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>L(I,R.action_type_id,R.id),children:[e.jsx(an,{className:"h-3 w-3 mr-1"}),"New Script"]}),z&&e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>v((y==null?void 0:y.id)===z.id?null:z),children:(y==null?void 0:y.id)===z.id?"Hide":"Preview"})]})]}),y&&(R==null?void 0:R.default_script_id)===y.id&&e.jsxs("div",{className:"ml-24 p-3 bg-muted rounded-lg text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Be,{variant:"outline",children:y.title}),y.tone&&e.jsx(Be,{variant:"secondary",children:y.tone})]}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:y.script_body})]})]},I)})})})]}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsxs($s,{children:[l?"Edit":"Add"," Touchpoint Plan"]})}),e.jsxs("form",{onSubmit:I=>{I.preventDefault();const R=new FormData(I.currentTarget);N.mutate({id:l==null?void 0:l.id,name:R.get("name"),description:R.get("description"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{htmlFor:"name",children:"Name"}),e.jsx(xe,{id:"name",name:"name",defaultValue:l==null?void 0:l.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"description",children:"Description"}),e.jsx(Fs,{id:"description",name:"description",defaultValue:(l==null?void 0:l.description)||"",rows:3})]})]}),e.jsxs(Mr,{className:"mt-4",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(U,{type:"submit",disabled:N.isPending,children:[N.isPending&&e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})}),e.jsx(zs,{open:m,onOpenChange:p,children:e.jsxs(Ds,{className:"max-w-2xl",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Create New Script"}),e.jsxs(Pr,{children:["Create a script for Month ",f==null?void 0:f.month,". Use ","{{FirstName}}",", ","{{LastName}}",", and ","{{AgentName}}"," as placeholders."]})]}),e.jsxs("form",{onSubmit:I=>{I.preventDefault();const R=new FormData(I.currentTarget);T.mutate({title:R.get("title"),action_type_id:f.actionTypeId,tone:R.get("tone"),script_body:R.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(te,{htmlFor:"script_title",children:"Title"}),e.jsx(xe,{id:"script_title",name:"title",placeholder:"e.g., Warm Check-In",required:!0})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"script_tone",children:"Tone"}),e.jsx(xe,{id:"script_tone",name:"tone",placeholder:"e.g., Friendly, Professional"})]})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"script_body",children:"Script Body"}),e.jsx(Fs,{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(Mr,{className:"mt-4",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>p(!1),children:"Cancel"}),e.jsxs(U,{type:"submit",disabled:T.isPending,children:[T.isPending&&e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Create & Assign"]})]})]})]})})]})}function TEn({flags:s}){const{toast:t}=Ai(),n=Qt(),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(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"Feature Flags"}),e.jsx(Jn,{children:"Control which features are enabled for members"})]}),e.jsx(Ie,{children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Flag"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{children:"Notes"}),e.jsx(Lt,{children:"Last Updated"})]})}),e.jsx(Xa,{children:s.map(a=>e.jsxs(gn,{children:[e.jsx(gt,{className:"font-mono text-sm",children:a.key}),e.jsx(gt,{children:e.jsx(wn,{checked:a.enabled,onCheckedChange:i=>r(a,{enabled:i})})}),e.jsx(gt,{children:e.jsx(xe,{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(gt,{className:"text-muted-foreground text-sm",children:new Date(a.updated_at).toLocaleDateString()})]},a.id))})]})})]})}function MEn({items:s,isLoading:t}){const{toast:n}=Ai(),r=Qt(),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=yt({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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Popby Ideas"}),e.jsx(Jn,{children:"Manage global popby ideas that all agents can see"})]}),e.jsxs(U,{onClick:()=>{i(null),o(!0)},children:[e.jsx(an,{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(Et,{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(Ro,{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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Name"}),e.jsx(Lt,{children:"Description"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{className:"w-24",children:"Actions"})]})}),e.jsx(Xa,{children:s.map(h=>e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium",children:h.name}),e.jsx(gt,{className:"text-muted-foreground",children:h.description}),e.jsx(gt,{children:e.jsx(wn,{checked:h.is_active,onCheckedChange:()=>d(h)})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>{i(h),o(!0)},children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>u(h.id),children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]})})]},h.id))})]})}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsxs($s,{children:[a?"Edit":"Add"," Popby Idea"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const m=new FormData(h.currentTarget);c.mutate({id:a==null?void 0:a.id,name:m.get("name"),description:m.get("description")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{htmlFor:"name",children:"Name"}),e.jsx(xe,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0,placeholder:"e.g., Homemade Cookies"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"description",children:"Description"}),e.jsx(Fs,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||"",placeholder:"Brief description of the popby idea..."})]})]}),e.jsxs(Mr,{className:"mt-4",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(U,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function PEn(){var p;const{toast:s}=Ai(),t=Qt(),[n,r]=j.useState(null),[a,i]=j.useState(!1),{data:l,isLoading:o}=ct({queryKey:["admin-video-script-categories"],queryFn:async()=>{const{data:f,error:x}=await q.from("video_script_categories").select("*").order("sort_order");if(x)throw x;return f}}),{data:c,isLoading:d}=ct({queryKey:["admin-video-scripts"],queryFn:async()=>{const{data:f,error:x}=await q.from("video_scripts").select("*, category:video_script_categories(*)").order("title");if(x)throw x;return f}}),u=yt({mutationFn:async f=>{var x,y;if(f.id){const{error:v}=await q.from("video_scripts").update({title:f.title,script_text:f.script_text,category_id:f.category_id,tags:((x=f.tags)==null?void 0:x.split(",").map(b=>b.trim()).filter(Boolean))||[]}).eq("id",f.id);if(v)throw v}else{const{error:v}=await q.from("video_scripts").insert([{title:f.title,script_text:f.script_text,category_id:f.category_id||null,tags:((y=f.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:f=>s({title:"Error",description:f.message,variant:"destructive"})}),h=async f=>{await q.from("video_scripts").update({is_active:!f.is_active}).eq("id",f.id),t.invalidateQueries({queryKey:["admin-video-scripts"]})},m=async f=>{await Yi("Delete this video script?")&&(await q.from("video_scripts").delete().eq("id",f),t.invalidateQueries({queryKey:["admin-video-scripts"]}),s({title:"Script deleted"}))};return e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Video Scripts"}),e.jsx(Jn,{children:"Manage teleprompter scripts for Quick Video Touch"})]}),e.jsxs(U,{onClick:()=>{r(null),i(!0)},children:[e.jsx(an,{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(Et,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Title"}),e.jsx(Lt,{children:"Category"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{className:"w-24",children:"Actions"})]})}),e.jsx(Xa,{children:c==null?void 0:c.map(f=>{var x;return e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium",children:f.title}),e.jsx(gt,{className:"text-muted-foreground",children:((x=f.category)==null?void 0:x.name)||"Uncategorized"}),e.jsx(gt,{children:e.jsx(wn,{checked:f.is_active,onCheckedChange:()=>h(f)})}),e.jsxs(gt,{className:"flex gap-1",children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>{r(f),i(!0)},children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>m(f.id),children:e.jsx(In,{className:"h-4 w-4"})})]})]},f.id)})})]})}),e.jsx(zs,{open:a,onOpenChange:i,children:e.jsxs(Ds,{className:"max-w-2xl",children:[e.jsx(Vs,{children:e.jsxs($s,{children:[n?"Edit":"Add"," Video Script"]})}),e.jsxs("form",{onSubmit:f=>{f.preventDefault();const x=new FormData(f.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(te,{htmlFor:"title",children:"Title"}),e.jsx(xe,{id:"title",name:"title",defaultValue:n==null?void 0:n.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"category_id",children:"Category"}),e.jsxs(Ns,{name:"category_id",defaultValue:(n==null?void 0:n.category_id)||"",children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select category"})}),e.jsx(js,{children:l==null?void 0:l.map(f=>e.jsx(et,{value:f.id,children:f.name},f.id))})]})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"script_text",children:"Script Text"}),e.jsx(Fs,{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(te,{htmlFor:"tags",children:"Tags (comma-separated)"}),e.jsx(xe,{id:"tags",name:"tags",defaultValue:((p=n==null?void 0:n.tags)==null?void 0:p.join(", "))||"",placeholder:"birthday, follow-up, thank-you"})]})]}),e.jsxs(Mr,{className:"mt-4",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsxs(U,{type:"submit",disabled:u.isPending,children:[u.isPending&&e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function LEn(){const{toast:s}=Ai(),[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(we,{children:e.jsx(Ie,{className:"flex justify-center py-8",children:e.jsx(Et,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}):e.jsx("div",{className:"space-y-6",children:e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(ni,{className:"h-5 w-5"}),"Popby Map Settings"]}),e.jsx(Jn,{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(te,{htmlFor:"mapbox-token",children:"Mapbox Public Token"}),e.jsx(xe,{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(U,{onClick:o,disabled:i,children:[i&&e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Token"]}),t&&e.jsx(Be,{variant:"secondary",className:"ml-2",children:"Token configured"})]})]})})}const IEn=()=>{const[s,t]=j.useState(""),[n,r]=j.useState("grid"),a=Wn(),{data:i=[],isLoading:l}=ct({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(qs,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{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(U,{variant:"outline",size:"sm",onClick:()=>t(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(U,{variant:n==="grid"?"secondary":"outline",size:"icon",onClick:()=>r("grid"),className:"rounded-full",children:e.jsx(Hg,{className:"h-4 w-4"})}),e.jsx(U,{variant:n==="list"?"secondary":"outline",size:"icon",onClick:()=>r("list"),className:"rounded-full",children:e.jsx(m0,{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(we,{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(U,{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(we,{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(cn,{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:KJ(c.description)})]})]},c.id))})]})})},REn=()=>{const{serviceId:s}=Di(),t=Wn(),{data:n,isLoading:r}=ct({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(qs,{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(qs,{title:n.name,children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(U,{variant:"ghost",onClick:()=>t("/additional-services"),className:"gap-2",children:[e.jsx(Aa,{className:"h-4 w-4"}),"Back to Services"]}),e.jsx(we,{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(cn,{className:"h-16 w-16"})})})}),e.jsx(we,{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(pa,{className:"h-4 w-4 mr-1"}),"Published ",Gs(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(U,{size:"lg",className:"gap-2",onClick:()=>window.open(n.signup_link_url,"_blank"),children:[e.jsx(Sr,{className:"h-5 w-5"}),"Sign Up Now"]})})]})})]})}):e.jsx(qs,{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(U,{onClick:()=>t("/additional-services"),children:[e.jsx(Aa,{className:"h-4 w-4 mr-2"}),"Back to Services"]})]})})},_Y=[{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 DEn(){const[s,t]=j.useState(_Y[0].id),n=_Y.find(r=>r.id===s)||_Y[0];return e.jsx(qs,{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(Ns,{value:s,onValueChange:t,children:[e.jsx(ws,{className:"w-full",children:e.jsx(ks,{placeholder:"Select a tool"})}),e.jsx(js,{children:_Y.map(r=>e.jsx(et,{value:r.id,children:r.name},r.id))})]})}),e.jsx("div",{className:"hidden md:block",children:e.jsx(oa,{value:s,onValueChange:t,className:"w-full",children:e.jsx(la,{className:"w-full flex-wrap h-auto gap-1 bg-muted p-1",children:_Y.map(r=>e.jsx(Kt,{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 OEn(s,t){const n={};return(s[s.length-1]===""?[...s,""]:s).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const FEn=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,zEn=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,BEn={};function T_t(s,t){return(BEn.jsx?zEn:FEn).test(s)}const UEn=/[ \t\n\f\r]/g;function qEn(s){return typeof s=="object"?s.type==="text"?M_t(s.value):!1:M_t(s)}function M_t(s){return s.replace(UEn,"")===""}class Dre{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}Dre.prototype.normal={};Dre.prototype.property={};Dre.prototype.space=void 0;function hGt(s,t){const n={},r={};for(const a of s)Object.assign(n,a.property),Object.assign(r,a.normal);return new Dre(n,r,t)}function zHe(s){return s.toLowerCase()}class B_{constructor(t,n){this.attribute=n,this.property=t}}B_.prototype.attribute="";B_.prototype.booleanish=!1;B_.prototype.boolean=!1;B_.prototype.commaOrSpaceSeparated=!1;B_.prototype.commaSeparated=!1;B_.prototype.defined=!1;B_.prototype.mustUseProperty=!1;B_.prototype.number=!1;B_.prototype.overloadedBoolean=!1;B_.prototype.property="";B_.prototype.spaceSeparated=!1;B_.prototype.space=void 0;let $En=0;const cc=E9(),cx=E9(),BHe=E9(),ei=E9(),cm=E9(),n7=E9(),mw=E9();function E9(){return 2**++$En}const UHe=Object.freeze(Object.defineProperty({__proto__:null,boolean:cc,booleanish:cx,commaOrSpaceSeparated:mw,commaSeparated:n7,number:ei,overloadedBoolean:BHe,spaceSeparated:cm},Symbol.toStringTag,{value:"Module"})),R7e=Object.keys(UHe);class Rtt extends B_{constructor(t,n,r,a){let i=-1;if(super(t,n),P_t(this,"space",a),typeof r=="number")for(;++i4&&n.slice(0,4)==="data"&&KEn.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(L_t,XEn);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!L_t.test(i)){let l=i.replace(WEn,ZEn);l.charAt(0)!=="-"&&(l="-"+l),t="data"+l}}a=Rtt}return new a(r,t)}function ZEn(s){return"-"+s.toLowerCase()}function XEn(s){return s.charAt(1).toUpperCase()}const QEn=hGt([mGt,VEn,gGt,xGt,yGt],"html"),Dtt=hGt([mGt,HEn,gGt,xGt,yGt],"svg");function JEn(s){return s.join(" ").trim()}var Ott={},I_t=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,eTn=/\n/g,tTn=/^\s*/,sTn=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,nTn=/^:\s*/,rTn=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,aTn=/^[;\s]*/,iTn=/^\s+|\s+$/g,oTn=` `,R_t="/",D_t="*",LD="",lTn="comment",cTn="declaration";function dTn(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(f){var x=f.match(eTn);x&&(n+=x.length);var y=f.lastIndexOf(oTn);r=~y?f.length-y:r+f.length}function i(){var f={line:n,column:r};return function(x){return x.position=new l(f),d(),x}}function l(f){this.start=f,this.end={line:n,column:r},this.source=t.source}l.prototype.content=s;function o(f){var x=new Error(t.source+":"+n+":"+r+": "+f);if(x.reason=f,x.filename=t.source,x.line=n,x.column=r,x.source=s,!t.silent)throw x}function c(f){var x=f.exec(s);if(x){var y=x[0];return a(y),s=s.slice(y.length),x}}function d(){c(tTn)}function u(f){var x;for(f=f||[];x=h();)x!==!1&&f.push(x);return f}function h(){var f=i();if(!(R_t!=s.charAt(0)||D_t!=s.charAt(1))){for(var x=2;LD!=s.charAt(x)&&(D_t!=s.charAt(x)||R_t!=s.charAt(x+1));)++x;if(x+=2,LD===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,f({type:lTn,comment:y})}}function m(){var f=i(),x=c(sTn);if(x){if(h(),!c(nTn))return o("property missing ':'");var y=c(rTn),v=f({type:cTn,property:O_t(x[0].replace(I_t,LD)),value:y?O_t(y[0].replace(I_t,LD)):LD});return c(aTn),v}}function p(){var f=[];u(f);for(var x;x=m();)x!==!1&&(f.push(x),u(f));return f}return d(),p()}function O_t(s){return s?s.replace(iTn,LD):LD}var uTn=dTn,hTn=op&&op.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Ott,"__esModule",{value:!0});Ott.default=pTn;const mTn=hTn(uTn);function pTn(s,t){let n=null;if(!s||typeof s!="string")return n;const r=(0,mTn.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 OLe={};Object.defineProperty(OLe,"__esModule",{value:!0});OLe.camelCase=void 0;var fTn=/^--[a-zA-Z0-9_-]+$/,gTn=/-([a-z])/g,xTn=/^[^-]+$/,yTn=/^-(webkit|moz|ms|o|khtml)-/,vTn=/^-(ms)-/,bTn=function(s){return!s||xTn.test(s)||fTn.test(s)},_Tn=function(s,t){return t.toUpperCase()},F_t=function(s,t){return"".concat(t,"-")},wTn=function(s,t){return t===void 0&&(t={}),bTn(s)?s:(s=s.toLowerCase(),t.reactCompat?s=s.replace(vTn,F_t):s=s.replace(yTn,F_t),s.replace(gTn,_Tn))};OLe.camelCase=wTn;var jTn=op&&op.__importDefault||function(s){return s&&s.__esModule?s:{default:s}},NTn=jTn(Ott),kTn=OLe;function qHe(s,t){var n={};return!s||typeof s!="string"||(0,NTn.default)(s,function(r,a){r&&a&&(n[(0,kTn.camelCase)(r,t)]=a)}),n}qHe.default=qHe;var STn=qHe;const CTn=od(STn),vGt=bGt("end"),Ftt=bGt("start");function bGt(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 ATn(s){const t=Ftt(s),n=vGt(s);if(t&&n)return{start:t,end:n}}function sJ(s){return!s||typeof s!="object"?"":"position"in s||"type"in s?z_t(s.position):"start"in s||"end"in s?z_t(s):"line"in s||"column"in s?$He(s):""}function $He(s){return B_t(s&&s.line)+":"+B_t(s&&s.column)}function z_t(s){return $He(s&&s.start)+"-"+$He(s&&s.end)}function B_t(s){return s&&typeof s=="number"?s:1}class g1 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=sJ(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}}g1.prototype.file="";g1.prototype.name="";g1.prototype.reason="";g1.prototype.message="";g1.prototype.stack="";g1.prototype.column=void 0;g1.prototype.line=void 0;g1.prototype.ancestors=void 0;g1.prototype.cause=void 0;g1.prototype.fatal=void 0;g1.prototype.place=void 0;g1.prototype.ruleId=void 0;g1.prototype.source=void 0;const ztt={}.hasOwnProperty,ETn=new Map,TTn=/[A-Z]/g,MTn=new Set(["table","tbody","thead","tfoot","tr"]),PTn=new Set(["td","th"]),_Gt="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function LTn(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=UTn(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=BTn(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"?Dtt:QEn,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=wGt(a,s,void 0);return i&&typeof i!="string"?i:a.create(s,a.Fragment,{children:i||void 0},void 0)}function wGt(s,t,n){if(t.type==="element")return ITn(s,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return RTn(s,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return OTn(s,t,n);if(t.type==="mdxjsEsm")return DTn(s,t);if(t.type==="root")return FTn(s,t,n);if(t.type==="text")return zTn(s,t)}function ITn(s,t,n){const r=s.schema;let a=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(a=Dtt,s.schema=a),s.ancestors.push(t);const i=NGt(s,t.tagName,!1),l=qTn(s,t);let o=Utt(s,t);return MTn.has(t.tagName)&&(o=o.filter(function(c){return typeof c=="string"?!qEn(c):!0})),jGt(s,l,i,t),Btt(l,o),s.ancestors.pop(),s.schema=r,s.create(t,i,l,n)}function RTn(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)}yte(s,t.position)}function DTn(s,t){if(t.data&&t.data.estree&&s.evaluater)return s.evaluater.evaluateProgram(t.data.estree);yte(s,t.position)}function OTn(s,t,n){const r=s.schema;let a=r;t.name==="svg"&&r.space==="html"&&(a=Dtt,s.schema=a),s.ancestors.push(t);const i=t.name===null?s.Fragment:NGt(s,t.name,!0),l=$Tn(s,t),o=Utt(s,t);return jGt(s,l,i,t),Btt(l,o),s.ancestors.pop(),s.schema=r,s.create(t,i,l,n)}function FTn(s,t,n){const r={};return Btt(r,Utt(s,t)),s.create(t,s.Fragment,r,n)}function zTn(s,t){return t.value}function jGt(s,t,n,r){typeof n!="string"&&n!==s.Fragment&&s.passNode&&(t.node=r)}function Btt(s,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(s.children=n)}}function BTn(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 UTn(s,t){return n;function n(r,a,i,l){const o=Array.isArray(i.children),c=Ftt(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 qTn(s,t){const n={};let r,a;for(a in t.properties)if(a!=="children"&&ztt.call(t.properties,a)){const i=VTn(s,a,t.properties[a]);if(i){const[l,o]=i;s.tableCellAlignToStyle&&l==="align"&&typeof o=="string"&&PTn.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 $Tn(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 yte(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 yte(s,t.position);else i=r.value===null?!0:r.value;n[a]=i}return n}function Utt(s,t){const n=[];let r=-1;const a=s.passKeys?new Map:ETn;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?(t3(s,s.length,0,t),s):t}const $_t={}.hasOwnProperty;function QTn(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 Gq(s){return s.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const c4=lL(/[A-Za-z]/),Vw=lL(/[\dA-Za-z]/),t6n=lL(/[#-'*+\--9=?A-Z^-~]/);function VHe(s){return s!==null&&(s<32||s===127)}const HHe=lL(/\d/),s6n=lL(/[\dA-Fa-f]/),n6n=lL(/[!-/:-@[-`{-~]/);function Xl(s){return s!==null&&s<-2}function P_(s){return s!==null&&(s<0||s===32)}function Vu(s){return s===-2||s===-1||s===32}const r6n=lL(new RegExp("\\p{P}|\\p{S}","u")),a6n=lL(/\s/);function lL(s){return t;function t(n){return n!==null&&n>-1&&s.test(String.fromCharCode(n))}}function QG(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 Mm(s,t,n,r){const a=r?r-1:Number.POSITIVE_INFINITY;let i=0;return l;function l(c){return Vu(c)?(s.enter(n),o(c)):t(c)}function o(c){return Vu(c)&&i++l))return;const L=t.events.length;let M=L,I,R;for(;M--;)if(t.events[M][0]==="exit"&&t.events[M][1].type==="chunkFlow"){if(I){R=t.events[M][1].end;break}I=!0}for(v(r),T=L;TN;){const A=n[S];t.containerState=A[1],A[0].exit.call(t,s)}n.length=N}function b(){a.write([null]),i=void 0,a=void 0,t.containerState._closeFlow=void 0}}function d6n(s,t,n){return Mm(s,s.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function H_t(s){if(s===null||P_(s)||a6n(s))return 1;if(r6n(s))return 2}function $tt(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};G_t(h,-c),G_t(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=A2(d,[["enter",s[r][1],t],["exit",s[r][1],t]])),d=A2(d,[["enter",a,t],["enter",l,t],["exit",l,t],["enter",i,t]]),d=A2(d,$tt(t.parser.constructs.insideSpan.null,s.slice(r+1,n),t)),d=A2(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=A2(d,[["enter",s[n][1],t],["exit",s[n][1],t]])):u=0,t3(s,r-1,n-r+3,d),n=r+d.length-u-2;break}}for(n=-1;++n0&&Vu(T)?Mm(s,b,"linePrefix",i+1)(T):b(T)}function b(T){return T===null||Xl(T)?s.check(W_t,x,S)(T):(s.enter("codeFlowValue"),N(T))}function N(T){return T===null||Xl(T)?(s.exit("codeFlowValue"),b(T)):(s.consume(T),N)}function S(T){return s.exit("codeFenced"),t(T)}function A(T,L,M){let I=0;return R;function R(K){return T.enter("lineEnding"),T.consume(K),T.exit("lineEnding"),z}function z(K){return T.enter("codeFencedFence"),Vu(K)?Mm(T,$,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(K):$(K)}function $(K){return K===o?(T.enter("codeFencedFenceSequence"),H(K)):M(K)}function H(K){return K===o?(I++,T.consume(K),H):I>=l?(T.exit("codeFencedFenceSequence"),Vu(K)?Mm(T,V,"whitespace")(K):V(K)):M(K)}function V(K){return K===null||Xl(K)?(T.exit("codeFencedFence"),L(K)):M(K)}}}function w6n(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 O7e={name:"codeIndented",tokenize:N6n},j6n={partial:!0,tokenize:k6n};function N6n(s,t,n){const r=this;return a;function a(d){return s.enter("codeIndented"),Mm(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):Xl(d)?s.attempt(j6n,l,c)(d):(s.enter("codeFlowValue"),o(d))}function o(d){return d===null||Xl(d)?(s.exit("codeFlowValue"),l(d)):(s.consume(d),o)}function c(d){return s.exit("codeIndented"),t(d)}}function k6n(s,t,n){const r=this;return a;function a(l){return r.parser.lazy[r.now().line]?n(l):Xl(l)?(s.enter("lineEnding"),s.consume(l),s.exit("lineEnding"),a):Mm(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):Xl(l)?a(l):n(l)}}const S6n={name:"codeText",previous:A6n,resolve:C6n,tokenize:E6n};function C6n(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&&wY(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),wY(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),wY(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 MGt(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||VHe(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"}),p(v))}function p(v){return v===62?(s.exit("chunkString"),s.exit(o),m(v)):v===null||v===60||Xl(v)?n(v):(s.consume(v),v===92?f:p)}function f(v){return v===60||v===62||v===92?(s.consume(v),p):p(v)}function x(v){return!u&&(v===null||v===41||P_(v))?(s.exit("chunkString"),s.exit(o),s.exit(l),s.exit(r),t(v)):u999||p===null||p===91||p===93&&!c||p===94&&!o&&"_hiddenFootnoteSupport"in l.parser.constructs?n(p):p===93?(s.exit(i),s.enter(a),s.consume(p),s.exit(a),s.exit(r),t):Xl(p)?(s.enter("lineEnding"),s.consume(p),s.exit("lineEnding"),u):(s.enter("chunkString",{contentType:"string"}),h(p))}function h(p){return p===null||p===91||p===93||Xl(p)||o++>999?(s.exit("chunkString"),u(p)):(s.consume(p),c||(c=!Vu(p)),p===92?m:h)}function m(p){return p===91||p===92||p===93?(s.consume(p),o++,h):h(p)}}function LGt(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):Xl(m)?(s.enter("lineEnding"),s.consume(m),s.exit("lineEnding"),Mm(s,d,"linePrefix")):(s.enter("chunkString",{contentType:"string"}),u(m))}function u(m){return m===l||m===null||Xl(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 nJ(s,t){let n;return r;function r(a){return Xl(a)?(s.enter("lineEnding"),s.consume(a),s.exit("lineEnding"),n=!0,r):Vu(a)?Mm(s,r,n?"linePrefix":"lineSuffix")(a):t(a)}}const O6n={name:"definition",tokenize:z6n},F6n={partial:!0,tokenize:B6n};function z6n(s,t,n){const r=this;let a;return i;function i(p){return s.enter("definition"),l(p)}function l(p){return PGt.call(r,s,o,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function o(p){return a=Gq(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),p===58?(s.enter("definitionMarker"),s.consume(p),s.exit("definitionMarker"),c):n(p)}function c(p){return P_(p)?nJ(s,d)(p):d(p)}function d(p){return MGt(s,u,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function u(p){return s.attempt(F6n,h,h)(p)}function h(p){return Vu(p)?Mm(s,m,"whitespace")(p):m(p)}function m(p){return p===null||Xl(p)?(s.exit("definition"),r.parser.defined.push(a),t(p)):n(p)}}function B6n(s,t,n){return r;function r(o){return P_(o)?nJ(s,a)(o):n(o)}function a(o){return LGt(s,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function i(o){return Vu(o)?Mm(s,l,"whitespace")(o):l(o)}function l(o){return o===null||Xl(o)?t(o):n(o)}}const U6n={name:"hardBreakEscape",tokenize:q6n};function q6n(s,t,n){return r;function r(i){return s.enter("hardBreakEscape"),s.consume(i),a}function a(i){return Xl(i)?(s.exit("hardBreakEscape"),t(i)):n(i)}}const $6n={name:"headingAtx",resolve:V6n,tokenize:H6n};function V6n(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"},t3(s,r,n-r+1,[["enter",a,t],["enter",i,t],["exit",i,t],["exit",a,t]])),s}function H6n(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||P_(u)?(s.exit("atxHeadingSequence"),o(u)):n(u)}function o(u){return u===35?(s.enter("atxHeadingSequence"),c(u)):u===null||Xl(u)?(s.exit("atxHeading"),t(u)):Vu(u)?Mm(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||P_(u)?(s.exit("atxHeadingText"),o(u)):(s.consume(u),d)}}const G6n=["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"],Y_t=["pre","script","style","textarea"],W6n={concrete:!0,name:"htmlFlow",resolveTo:Z6n,tokenize:X6n},K6n={partial:!0,tokenize:J6n},Y6n={partial:!0,tokenize:Q6n};function Z6n(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 X6n(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:se):c4(ce)?(s.consume(ce),l=String.fromCharCode(ce),y):n(ce)}function m(ce){return ce===45?(s.consume(ce),a=2,p):ce===91?(s.consume(ce),a=5,o=0,f):c4(ce)?(s.consume(ce),a=4,r.interrupt?t:se):n(ce)}function p(ce){return ce===45?(s.consume(ce),r.interrupt?t:se):n(ce)}function f(ce){const je="CDATA[";return ce===je.charCodeAt(o++)?(s.consume(ce),o===je.length?r.interrupt?t:$:f):n(ce)}function x(ce){return c4(ce)?(s.consume(ce),l=String.fromCharCode(ce),y):n(ce)}function y(ce){if(ce===null||ce===47||ce===62||P_(ce)){const je=ce===47,be=l.toLowerCase();return!je&&!i&&Y_t.includes(be)?(a=1,r.interrupt?t(ce):$(ce)):G6n.includes(l.toLowerCase())?(a=6,je?(s.consume(ce),v):r.interrupt?t(ce):$(ce)):(a=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(ce):i?b(ce):N(ce))}return ce===45||Vw(ce)?(s.consume(ce),l+=String.fromCharCode(ce),y):n(ce)}function v(ce){return ce===62?(s.consume(ce),r.interrupt?t:$):n(ce)}function b(ce){return Vu(ce)?(s.consume(ce),b):R(ce)}function N(ce){return ce===47?(s.consume(ce),R):ce===58||ce===95||c4(ce)?(s.consume(ce),S):Vu(ce)?(s.consume(ce),N):R(ce)}function S(ce){return ce===45||ce===46||ce===58||ce===95||Vw(ce)?(s.consume(ce),S):A(ce)}function A(ce){return ce===61?(s.consume(ce),T):Vu(ce)?(s.consume(ce),A):N(ce)}function T(ce){return ce===null||ce===60||ce===61||ce===62||ce===96?n(ce):ce===34||ce===39?(s.consume(ce),c=ce,L):Vu(ce)?(s.consume(ce),T):M(ce)}function L(ce){return ce===c?(s.consume(ce),c=null,I):ce===null||Xl(ce)?n(ce):(s.consume(ce),L)}function M(ce){return ce===null||ce===34||ce===39||ce===47||ce===60||ce===61||ce===62||ce===96||P_(ce)?A(ce):(s.consume(ce),M)}function I(ce){return ce===47||ce===62||Vu(ce)?N(ce):n(ce)}function R(ce){return ce===62?(s.consume(ce),z):n(ce)}function z(ce){return ce===null||Xl(ce)?$(ce):Vu(ce)?(s.consume(ce),z):n(ce)}function $(ce){return ce===45&&a===2?(s.consume(ce),Z):ce===60&&a===1?(s.consume(ce),Q):ce===62&&a===4?(s.consume(ce),ne):ce===63&&a===3?(s.consume(ce),se):ce===93&&a===5?(s.consume(ce),ue):Xl(ce)&&(a===6||a===7)?(s.exit("htmlFlowData"),s.check(K6n,ie,H)(ce)):ce===null||Xl(ce)?(s.exit("htmlFlowData"),H(ce)):(s.consume(ce),$)}function H(ce){return s.check(Y6n,V,ie)(ce)}function V(ce){return s.enter("lineEnding"),s.consume(ce),s.exit("lineEnding"),K}function K(ce){return ce===null||Xl(ce)?H(ce):(s.enter("htmlFlowData"),$(ce))}function Z(ce){return ce===45?(s.consume(ce),se):$(ce)}function Q(ce){return ce===47?(s.consume(ce),l="",le):$(ce)}function le(ce){if(ce===62){const je=l.toLowerCase();return Y_t.includes(je)?(s.consume(ce),ne):$(ce)}return c4(ce)&&l.length<8?(s.consume(ce),l+=String.fromCharCode(ce),le):$(ce)}function ue(ce){return ce===93?(s.consume(ce),se):$(ce)}function se(ce){return ce===62?(s.consume(ce),ne):ce===45&&a===2?(s.consume(ce),se):$(ce)}function ne(ce){return ce===null||Xl(ce)?(s.exit("htmlFlowData"),ie(ce)):(s.consume(ce),ne)}function ie(ce){return s.exit("htmlFlow"),t(ce)}}function Q6n(s,t,n){const r=this;return a;function a(l){return Xl(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 J6n(s,t,n){return r;function r(a){return s.enter("lineEnding"),s.consume(a),s.exit("lineEnding"),s.attempt(FLe,t,n)}}const eMn={name:"htmlText",tokenize:tMn};function tMn(s,t,n){const r=this;let a,i,l;return o;function o(se){return s.enter("htmlText"),s.enter("htmlTextData"),s.consume(se),c}function c(se){return se===33?(s.consume(se),d):se===47?(s.consume(se),A):se===63?(s.consume(se),N):c4(se)?(s.consume(se),M):n(se)}function d(se){return se===45?(s.consume(se),u):se===91?(s.consume(se),i=0,f):c4(se)?(s.consume(se),b):n(se)}function u(se){return se===45?(s.consume(se),p):n(se)}function h(se){return se===null?n(se):se===45?(s.consume(se),m):Xl(se)?(l=h,Q(se)):(s.consume(se),h)}function m(se){return se===45?(s.consume(se),p):h(se)}function p(se){return se===62?Z(se):se===45?m(se):h(se)}function f(se){const ne="CDATA[";return se===ne.charCodeAt(i++)?(s.consume(se),i===ne.length?x:f):n(se)}function x(se){return se===null?n(se):se===93?(s.consume(se),y):Xl(se)?(l=x,Q(se)):(s.consume(se),x)}function y(se){return se===93?(s.consume(se),v):x(se)}function v(se){return se===62?Z(se):se===93?(s.consume(se),v):x(se)}function b(se){return se===null||se===62?Z(se):Xl(se)?(l=b,Q(se)):(s.consume(se),b)}function N(se){return se===null?n(se):se===63?(s.consume(se),S):Xl(se)?(l=N,Q(se)):(s.consume(se),N)}function S(se){return se===62?Z(se):N(se)}function A(se){return c4(se)?(s.consume(se),T):n(se)}function T(se){return se===45||Vw(se)?(s.consume(se),T):L(se)}function L(se){return Xl(se)?(l=L,Q(se)):Vu(se)?(s.consume(se),L):Z(se)}function M(se){return se===45||Vw(se)?(s.consume(se),M):se===47||se===62||P_(se)?I(se):n(se)}function I(se){return se===47?(s.consume(se),Z):se===58||se===95||c4(se)?(s.consume(se),R):Xl(se)?(l=I,Q(se)):Vu(se)?(s.consume(se),I):Z(se)}function R(se){return se===45||se===46||se===58||se===95||Vw(se)?(s.consume(se),R):z(se)}function z(se){return se===61?(s.consume(se),$):Xl(se)?(l=z,Q(se)):Vu(se)?(s.consume(se),z):I(se)}function $(se){return se===null||se===60||se===61||se===62||se===96?n(se):se===34||se===39?(s.consume(se),a=se,H):Xl(se)?(l=$,Q(se)):Vu(se)?(s.consume(se),$):(s.consume(se),V)}function H(se){return se===a?(s.consume(se),a=void 0,K):se===null?n(se):Xl(se)?(l=H,Q(se)):(s.consume(se),H)}function V(se){return se===null||se===34||se===39||se===60||se===61||se===96?n(se):se===47||se===62||P_(se)?I(se):(s.consume(se),V)}function K(se){return se===47||se===62||P_(se)?I(se):n(se)}function Z(se){return se===62?(s.consume(se),s.exit("htmlTextData"),s.exit("htmlText"),t):n(se)}function Q(se){return s.exit("htmlTextData"),s.enter("lineEnding"),s.consume(se),s.exit("lineEnding"),le}function le(se){return Vu(se)?Mm(s,ue,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(se):ue(se)}function ue(se){return s.enter("htmlTextData"),l(se)}}const Vtt={name:"labelEnd",resolveAll:aMn,resolveTo:iMn,tokenize:oMn},sMn={tokenize:lMn},nMn={tokenize:cMn},rMn={tokenize:dMn};function aMn(s){let t=-1;const n=[];for(;++t=3&&(d===null||Xl(d))?(s.exit("thematicBreak"),t(d)):n(d)}function c(d){return d===a?(s.consume(d),r++,c):(s.exit("thematicBreakSequence"),Vu(d)?Mm(s,o,"whitespace")(d):o(d))}}const e_={continuation:{tokenize:bMn},exit:wMn,name:"list",tokenize:vMn},xMn={partial:!0,tokenize:jMn},yMn={partial:!0,tokenize:_Mn};function vMn(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(p){const f=r.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(f==="listUnordered"?!r.containerState.marker||p===r.containerState.marker:HHe(p)){if(r.containerState.type||(r.containerState.type=f,s.enter(f,{_container:!0})),f==="listUnordered")return s.enter("listItemPrefix"),p===42||p===45?s.check(Q5e,n,d)(p):d(p);if(!r.interrupt||p===49)return s.enter("listItemPrefix"),s.enter("listItemValue"),c(p)}return n(p)}function c(p){return HHe(p)&&++l<10?(s.consume(p),c):(!r.interrupt||l<2)&&(r.containerState.marker?p===r.containerState.marker:p===41||p===46)?(s.exit("listItemValue"),d(p)):n(p)}function d(p){return s.enter("listItemMarker"),s.consume(p),s.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||p,s.check(FLe,r.interrupt?n:u,s.attempt(xMn,m,h))}function u(p){return r.containerState.initialBlankLine=!0,i++,m(p)}function h(p){return Vu(p)?(s.enter("listItemPrefixWhitespace"),s.consume(p),s.exit("listItemPrefixWhitespace"),m):n(p)}function m(p){return r.containerState.size=i+r.sliceSerialize(s.exit("listItemPrefix"),!0).length,t(p)}}function bMn(s,t,n){const r=this;return r.containerState._closeFlow=void 0,s.check(FLe,a,i);function a(o){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,Mm(s,t,"listItemIndent",r.containerState.size+1)(o)}function i(o){return r.containerState.furtherBlankLines||!Vu(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(yMn,t,l)(o))}function l(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,Mm(s,s.attempt(e_,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function _Mn(s,t,n){const r=this;return Mm(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 wMn(s){s.exit(this.containerState.type)}function jMn(s,t,n){const r=this;return Mm(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!Vu(i)&&l&&l[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const Z_t={name:"setextUnderline",resolveTo:NMn,tokenize:kMn};function NMn(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 kMn(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"),Vu(d)?Mm(s,c,"lineSuffix")(d):c(d))}function c(d){return d===null||Xl(d)?(s.exit("setextHeadingLine"),t(d)):n(d)}}const SMn={tokenize:CMn};function CMn(s){const t=this,n=s.attempt(FLe,r,s.attempt(this.parser.constructs.flowInitial,a,Mm(s,s.attempt(this.parser.constructs.flow,a,s.attempt(P6n,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 AMn={resolveAll:RGt()},EMn=IGt("string"),TMn=IGt("text");function IGt(s){return{resolveAll:RGt(s==="text"?MMn: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 VMn(s,t){let n=-1;const r=[];let a;for(;++n0){const us=qt.tokenStack[qt.tokenStack.length-1];(us[1]||Q_t).call(qt,void 0,us[0])}for(ft.position={start:oT(pt.length>0?pt[0][1].start:{line:1,column:1,offset:0}),end:oT(pt.length>0?pt[pt.length-2][1].end:{line:1,column:1,offset:0})},Wt=-1;++Wt0&&(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 rPn(s,t){const n={type:"element",tagName:"del",properties:{},children:s.all(t)};return s.patch(t,n),s.applyData(t,n)}function aPn(s,t){const n={type:"element",tagName:"em",properties:{},children:s.all(t)};return s.patch(t,n),s.applyData(t,n)}function iPn(s,t){const n=typeof s.options.clobberPrefix=="string"?s.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),a=QG(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 oPn(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 lPn(s,t){if(s.options.allowDangerousHtml){const n={type:"raw",value:t.value};return s.patch(t,n),s.applyData(t,n)}}function FGt(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 cPn(s,t){const n=String(t.identifier).toUpperCase(),r=s.definitionById.get(n);if(!r)return FGt(s,t);const a={src:QG(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 dPn(s,t){const n={src:QG(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 uPn(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 hPn(s,t){const n=String(t.identifier).toUpperCase(),r=s.definitionById.get(n);if(!r)return FGt(s,t);const a={href:QG(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 mPn(s,t){const n={href:QG(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 pPn(s,t,n){const r=s.all(t),a=n?fPn(n):zGt(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 gPn(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=Ftt(t.children[1]),c=vGt(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 _Pn(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(twt(t.slice(a),a>0,!1)),i.join("")}function twt(s,t,n){let r=0,a=s.length;if(t){let i=s.codePointAt(r);for(;i===J_t||i===ewt;)r++,i=s.codePointAt(r)}if(n){let i=s.codePointAt(a-1);for(;i===J_t||i===ewt;)a--,i=s.codePointAt(a-1)}return a>r?s.slice(r,a):""}function NPn(s,t){const n={type:"text",value:jPn(String(t.value))};return s.patch(t,n),s.applyData(t,n)}function kPn(s,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return s.patch(t,n),s.applyData(t,n)}const SPn={blockquote:tPn,break:sPn,code:nPn,delete:rPn,emphasis:aPn,footnoteReference:iPn,heading:oPn,html:lPn,imageReference:cPn,image:dPn,inlineCode:uPn,linkReference:hPn,link:mPn,listItem:pPn,list:gPn,paragraph:xPn,root:yPn,strong:vPn,table:bPn,tableCell:wPn,tableRow:_Pn,text:NPn,thematicBreak:kPn,toml:Ile,yaml:Ile,definition:Ile,footnoteDefinition:Ile};function Ile(){}const BGt=-1,zLe=0,rJ=1,LEe=2,Htt=3,Gtt=4,Wtt=5,Ktt=6,UGt=7,qGt=8,$Gt=typeof self=="object"?self:globalThis,swt=(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 $Gt[s](t)},CPn=(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 zLe:case BGt:return n(l,a);case rJ:{const o=n([],a);for(const c of l)o.push(r(c));return o}case LEe:{const o=n({},a);for(const[c,d]of l)o[r(c)]=r(d);return o}case Htt:return n(new Date(l),a);case Gtt:{const{source:o,flags:c}=l;return n(new RegExp(o,c),a)}case Wtt:{const o=n(new Map,a);for(const[c,d]of l)o.set(r(c),r(d));return o}case Ktt:{const o=n(new Set,a);for(const c of l)o.add(r(c));return o}case UGt:{const{name:o,message:c}=l;return n(typeof $Gt[o]=="function"?swt(o,c):new Error(c),a)}case qGt: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)}}return n(swt(i,l),a)};return r},nwt=s=>CPn(new Map,s)(0),bD="",{toString:APn}={},{keys:EPn}=Object,jY=s=>{const t=typeof s;if(t!=="object"||!s)return[zLe,t];const n=APn.call(s).slice(8,-1);switch(n){case"Array":return[rJ,bD];case"Object":return[LEe,bD];case"Date":return[Htt,bD];case"RegExp":return[Gtt,bD];case"Map":return[Wtt,bD];case"Set":return[Ktt,bD];case"DataView":return[rJ,n]}return n.includes("Array")?[rJ,n]:s instanceof Error?[UGt,s.name||"Error"]:[LEe,n]},Rle=([s,t])=>s===zLe&&(t==="function"||t==="symbol"),TPn=(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]=jY(l);switch(o){case zLe:{let u=l;switch(c){case"bigint":o=qGt,u=l.toString();break;case"function":case"symbol":if(s)throw new TypeError("unable to serialize "+c);u=null;break;case"undefined":return a([BGt],l)}return a([o,u],l)}case rJ:{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 LEe:{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 EPn(l))(s||!Rle(jY(l[m])))&&u.push([i(m),i(l[m])]);return h}case Htt:return a([o,isNaN(l.getTime())?bD:l.toISOString()],l);case Gtt:{const{source:u,flags:h}=l;return a([o,{source:u,flags:h}],l)}case Wtt:{const u=[],h=a([o,u],l);for(const[m,p]of l)(s||!(Rle(jY(m))||Rle(jY(p))))&&u.push([i(m),i(p)]);return h}case Ktt:{const u=[],h=a([o,u],l);for(const m of l)(s||!Rle(jY(m)))&&u.push(i(m));return h}}const{message:d}=l;return a([o,{name:c,message:d}],l)};return i},rwt=(s,{json:t,lossy:n}={})=>{const r=[];return TPn(!(t||n),!!t,new Map,r)(s),r},IEe=typeof structuredClone=="function"?(s,t)=>t&&("json"in t||"lossy"in t)?nwt(rwt(s,t)):structuredClone(s):(s,t)=>nwt(rwt(s,t));function MPn(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 PPn(s,t){return"Back to reference "+(s+1)+(t>1?"-"+t:"")}function LPn(s){const t=typeof s.options.clobberPrefix=="string"?s.options.clobberPrefix:"user-content-",n=s.options.footnoteBackContent||MPn,r=s.options.footnoteBackLabel||PPn,a=s.options.footnoteLabel||"Footnotes",i=s.options.footnoteLabelTagName||"h2",l=s.options.footnoteLabelProperties||{className:["sr-only"]},o=[];let c=-1;for(;++c0&&f.push({type:"text",value:" "});let b=typeof n=="string"?n:n(c,p);typeof b=="string"&&(b={type:"text",value:b}),f.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+m+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(c,p),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(...f)}else u.push(...f);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:{...IEe(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 VGt=function(s){if(s==null)return OPn;if(typeof s=="function")return BLe(s);if(typeof s=="object")return Array.isArray(s)?IPn(s):RPn(s);if(typeof s=="string")return DPn(s);throw new Error("Expected function, string, or object as test")};function IPn(s){const t=[];let n=-1;for(;++n":""))+")"})}return m;function m(){let p=HGt,f,x,y;if((!t||i(c,d,u[u.length-1]||void 0))&&(p=qPn(n(c,u)),p[0]===awt))return p;if("children"in c&&c.children){const v=c;if(v.children&&p[0]!==BPn)for(x=(r?v.children.length:-1)+l,y=u.concat(v);x>-1&&x0&&n.push({type:"text",value:` `}),n}function iwt(s){let t=0,n=s.charCodeAt(t);for(;n===9||n===32;)t++,n=s.charCodeAt(t);return s.slice(t)}function owt(s,t){const n=VPn(s,t),r=n.one(s,void 0),a=LPn(n),i=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return a&&i.children.push({type:"text",value:` `},a),i}function YPn(s,t){return s&&"run"in s?async function(n,r){const a=owt(n,{file:r,...t});await s.run(a,r)}:function(n,r){return owt(n,{file:r,...s||t})}}function lwt(s){if(s)throw s}var J5e=Object.prototype.hasOwnProperty,WGt=Object.prototype.toString,cwt=Object.defineProperty,dwt=Object.getOwnPropertyDescriptor,uwt=function(t){return typeof Array.isArray=="function"?Array.isArray(t):WGt.call(t)==="[object Array]"},hwt=function(t){if(!t||WGt.call(t)!=="[object Object]")return!1;var n=J5e.call(t,"constructor"),r=t.constructor&&t.constructor.prototype&&J5e.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!n&&!r)return!1;var a;for(a in t);return typeof a>"u"||J5e.call(t,a)},mwt=function(t,n){cwt&&n.name==="__proto__"?cwt(t,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):t[n.name]=n.newValue},pwt=function(t,n){if(n==="__proto__")if(J5e.call(t,n)){if(dwt)return dwt(t,n).value}else return;return t[n]},ZPn=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 E5={basename:JPn,dirname:eLn,extname:tLn,join:sLn,sep:"/"};function JPn(s,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Ore(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 eLn(s){if(Ore(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 tLn(s){Ore(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 sLn(...s){let t=-1,n;for(;++t0&&s.codePointAt(s.length-1)===47&&(n+="/"),t?"/"+n:n}function rLn(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 Ore(s){if(typeof s!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(s))}const aLn={cwd:iLn};function iLn(){return"/"}function YHe(s){return!!(s!==null&&typeof s=="object"&&"href"in s&&s.href&&"protocol"in s&&s.protocol&&s.auth===void 0)}function oLn(s){if(typeof s=="string")s=new URL(s);else if(!YHe(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 lLn(s)}function lLn(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[p,...f]=u;const x=r[m][1];KHe(x)&&KHe(p)&&(p=z7e(!0,x,p)),r[m]=[d,p,...f]}}}}const hLn=new Ytt().freeze();function $7e(s,t){if(typeof t!="function")throw new TypeError("Cannot `"+s+"` without `parser`")}function V7e(s,t){if(typeof t!="function")throw new TypeError("Cannot `"+s+"` without `compiler`")}function H7e(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 gwt(s){if(!KHe(s)||typeof s.type!="string")throw new TypeError("Expected node, got `"+s+"`")}function xwt(s,t,n){if(!n)throw new Error("`"+s+"` finished async. Use `"+t+"` instead")}function Dle(s){return mLn(s)?s:new KGt(s)}function mLn(s){return!!(s&&typeof s=="object"&&"message"in s&&"messages"in s)}function pLn(s){return typeof s=="string"||fLn(s)}function fLn(s){return!!(s&&typeof s=="object"&&"byteLength"in s&&"byteOffset"in s)}const gLn="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",ywt=[],vwt={allowDangerousHtml:!0},xLn=/^(https?|ircs?|mailto|xmpp)$/i,yLn=[{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 vLn(s){const t=bLn(s),n=_Ln(s);return wLn(t.runSync(t.parse(n),n),s)}function bLn(s){const t=s.rehypePlugins||ywt,n=s.remarkPlugins||ywt,r=s.remarkRehypeOptions?{...s.remarkRehypeOptions,...vwt}:vwt;return hLn().use(ePn).use(n).use(YPn,r).use(t)}function _Ln(s){const t=s.children||"",n=new KGt;return typeof t=="string"&&(n.value=t),n}function wLn(s,t){const n=t.allowedElements,r=t.allowElement,a=t.components,i=t.disallowedElements,l=t.skipHtml,o=t.unwrapDisallowed,c=t.urlTransform||jLn;for(const u of yLn)Object.hasOwn(t,u.from)&&(""+u.from+(u.to?"use `"+u.to+"` instead":"remove it")+gLn+u.id,void 0);return GGt(s,d),LTn(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 p;for(p in D7e)if(Object.hasOwn(D7e,p)&&Object.hasOwn(u.properties,p)){const f=u.properties[p],x=D7e[p];(x===null||x.includes(u.tagName))&&(u.properties[p]=c(String(f||""),p,u))}}if(u.type==="element"){let p=n?!n.includes(u.tagName):i?i.includes(u.tagName):!1;if(!p&&r&&typeof h=="number"&&(p=!r(u,h,m)),p&&m&&typeof h=="number")return o&&u.children?m.children.splice(h,1,...u.children):m.children.splice(h,1),h}}}function jLn(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||xLn.test(s.slice(0,t))?s:""}const NLn={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(xr,{to:n,className:a,children:[t,e.jsx(bF,{className:"h-3 w-3"})]}):e.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:a,children:[t,e.jsx(bF,{className:"h-3 w-3"})]})}},kLn=["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 SLn(){var h,m,p;const{user:s}=vs(),[t,n]=j.useState([]),[r,a]=j.useState(""),[i,l]=j.useState(!1),o=j.useRef(null),c=j.useRef(null),d=((h=s==null?void 0:s.user_metadata)==null?void 0:h.first_name)||((p=(m=s==null?void 0:s.user_metadata)==null?void 0:m.full_name)==null?void 0:p.split(" ")[0])||"";j.useEffect(()=>{var f;(f=c.current)==null||f.scrollTo({top:c.current.scrollHeight,behavior:"smooth"})},[t,i]);const u=async f=>{var b;const x=f.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:N}=await q.auth.getSession(),S=(b=N.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 R=await A.json().catch(()=>({error:"Something went wrong."}));throw new Error(R.error||"Something went wrong.")}const T=A.body.getReader(),L=new TextDecoder;let M="",I="";for(;;){const{done:R,value:z}=await T.read();if(R)break;M+=L.decode(z,{stream:!0});const $=M.split(` `);M=$.pop()||"";for(const H of $){const V=H.trim();if(!V.startsWith("data:"))continue;const K=V.slice(5).trim();if(!(!K||K==="[DONE]"))try{const Z=JSON.parse(K);Z.delta&&(I+=Z.delta,n(Q=>{const le=[...Q];return le[le.length-1]={role:"assistant",content:I},le}))}catch{}}}I||n(R=>{const z=[...R];return z[z.length-1]={role:"assistant",content:"I didn't catch that — mind asking again?"},z})}catch(N){N.name==="AbortError"?n(S=>S.filter((A,T)=>!(T===S.length-1&&!A.content))):(re.error(N.message||"The assistant is unavailable right now."),n(S=>S.slice(0,-1)))}finally{l(!1),o.current=null}};return e.jsx(qs,{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(U,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>n([]),children:[e.jsx(Kg,{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:kLn.map(f=>e.jsx("button",{onClick:()=>u(f),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:f},f))})]}):t.map((f,x)=>e.jsx("div",{className:Mt("flex",f.role==="user"?"justify-end":"justify-start"),children:f.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:f.content})}):e.jsx("div",{className:"max-w-full text-sm leading-relaxed text-foreground",children:f.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(vLn,{components:NLn,children:f.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(Fs,{value:r,onChange:f=>a(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.shiftKey&&(f.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(U,{size:"icon",variant:"secondary",onClick:()=>{var f;return(f=o.current)==null?void 0:f.abort()},children:e.jsx(db,{className:"h-4 w-4"})}):e.jsx(U,{size:"icon",disabled:!r.trim(),onClick:()=>u(r),children:e.jsx($r,{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 CLn({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 Ole({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:Mt("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(gi,{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 ALn({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(),p=m<12?"Good morning":m<17?"Good afternoon":"Good evening",f=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:[p,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(cn,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),e.jsx("span",{children:r})]})]}),e.jsx(CLn,{done:t,total:n})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Ole,{icon:e.jsx(Gu,{className:"h-3.5 w-3.5"}),label:"Weekly goal",value:`${a}/${i}`,hint:`${f}% 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(qc,{className:"h-3.5 w-3.5"})})}),e.jsx(Ole,{icon:e.jsx(Xd,{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(Ole,{icon:e.jsx(Yr,{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(Ole,{icon:e.jsx(Bn,{className:"h-3.5 w-3.5"}),label:"Your sphere",value:String(c),hint:"People in your database",onClick:h})]})]})}const bwt="agent-os-onboarding-completed",Fle=[{icon:pv,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:Af,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:Bn,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:nc,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:Ro,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:Cl,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"]}],ELn=()=>{const[s,t]=j.useState(!1),[n,r]=j.useState(0),[a,i]=j.useState(!1);j.useEffect(()=>{if(!localStorage.getItem(bwt)){const f=setTimeout(()=>t(!0),500);return()=>clearTimeout(f)}},[]);const l=()=>{n{r(n+1),i(!1)},150)):c()},o=()=>{c()},c=()=>{localStorage.setItem(bwt,"true"),t(!1)},d=Fle[n],u=d.icon,h=n===Fle.length-1,m=p=>{p||c(),t(p)};return e.jsx(zs,{open:s,onOpenChange:m,children:e.jsxs(Ds,{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(cn,{className:"h-3 w-3"}),"Beta"]})]}),e.jsxs("div",{className:"p-6 pt-4",children:[e.jsxs(Vs,{className:"text-center sm:text-center pb-2",children:[e.jsx($s,{className:`text-2xl font-bold transition-all duration-300 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.title}),e.jsx(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((p,f)=>e.jsxs("div",{className:"flex items-center gap-3 group",style:{transitionDelay:`${150+f*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(Xr,{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:p})]},f))}),e.jsx("div",{className:"flex justify-center gap-2 py-4",children:Fle.map((p,f)=>e.jsx("button",{onClick:()=>{f!==n&&(i(!0),setTimeout(()=>{r(f),i(!1)},150))},className:`h-2 rounded-full transition-all duration-300 ${f===n?"w-8 bg-gradient-to-r "+d.bgGradient:f{const{user:s}=vs();return ct({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})},MLn=()=>{const s=Qt(),{user:t}=vs();return yt({mutationFn:async({contactId:n,days:r})=>{if(!(t!=null&&t.id))throw new Error("Not authenticated");const a=jh(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"]}),ka({title:"Touch snoozed!",description:"Contact has been snoozed."})},onError:n=>{ka({title:"Error snoozing contact",description:n.message,variant:"destructive"})}})},PLn=()=>{const s=Qt();return yt({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"]}),ka({title:"Snooze cancelled"})},onError:t=>{ka({title:"Error cancelling snooze",description:t.message,variant:"destructive"})}})},LLn=[{label:"1 week",days:7},{label:"2 weeks",days:14},{label:"1 month",days:30}];function ULe({open:s,onOpenChange:t,contactId:n,contactName:r}){const[a,i]=j.useState(null),l=MLn(),o=async()=>{a&&(await l.mutateAsync({contactId:n,days:a}),i(null),t(!1))},c=d=>Gs(jh(new Date,d),"MMM d, yyyy");return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Yr,{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:LLn.map(d=>e.jsxs("button",{type:"button",onClick:()=>i(d.days),className:Mt("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(pa,{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(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(U,{onClick:o,disabled:!a||l.isPending,children:l.isPending?"Snoozing...":"Snooze Touch"})]})]})})}const ILn={Crown:h0,FileText:Ur,Users:Bn,Globe:fl,Star:Ua,Phone:ba,MessageSquare:Ki,PenTool:TA,Video:Wr,Gift:Ro};function RLn({actions:s,onMarkComplete:t,onViewScript:n,isLoading:r,buildSmsLink:a,buildEmailLink:i,onGmailCompose:l}){const o=Wn(),[c,d]=j.useState("name"),[u,h]=j.useState("asc"),[m,p]=j.useState(null),[f,x]=j.useState(""),y=A=>{c===A?h(T=>T==="asc"?"desc":"asc"):(d(A),h("asc"))},v=j.useMemo(()=>[...s].sort((A,T)=>{var M,I;let L=0;switch(c){case"name":{const R=`${A.contact.first_name} ${A.contact.last_name||""}`.toLowerCase(),z=`${T.contact.first_name} ${T.contact.last_name||""}`.toLowerCase();L=R.localeCompare(z);break}case"relationship_type":L=(A.relationshipTypeName||"").localeCompare(T.relationshipTypeName||"");break;case"action_type":L=(((M=A.actionType)==null?void 0:M.name)||"").localeCompare(((I=T.actionType)==null?void 0:I.name)||"");break;case"last_touch":L=(A.monthNumber||0)-(T.monthNumber||0);break}return u==="asc"?L:-L}),[s,c,u]),b=A=>ILn[A||"Phone"]||ba,N=({field:A,children:T})=>e.jsxs(U,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>y(A),children:[T,c===A?u==="asc"?e.jsx(cp,{className:"ml-2 h-4 w-4"}):e.jsx(ag,{className:"ml-2 h-4 w-4"}):e.jsx(xx,{className:"ml-2 h-4 w-4 opacity-50"})]}),S=(A,T,L)=>{p(A),x(`${T} ${L||""}`.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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{className:"bg-muted/50",children:[e.jsx(Lt,{className:"w-[180px]",children:e.jsx(N,{field:"name",children:"Contact"})}),e.jsx(Lt,{className:"w-[130px]",children:e.jsx(N,{field:"relationship_type",children:"Type"})}),e.jsx(Lt,{className:"w-[120px]",children:e.jsx(N,{field:"action_type",children:"Action"})}),e.jsx(Lt,{className:"w-[130px]",children:"Phone"}),e.jsx(Lt,{className:"w-[200px]",children:"Quick Actions"})]})}),e.jsx(Xa,{children:v.map((A,T)=>{var $,H,V,K,Z,Q;const L=A.isSpecialDate,M=A.specialDateType,I=L?M==="birthday"?lg:ra:b((($=A.actionType)==null?void 0:$.icon)||null),R=A.contact.phone,z=A.contact.email;return e.jsxs(gn,{className:Mt("hover:bg-muted/50 transition-colors",L&&M==="birthday"&&"bg-pink-50/50 dark:bg-pink-950/20",L&&M==="anniversary"&&"bg-purple-50/50 dark:bg-purple-950/20"),children:[e.jsx(gt,{className:"font-medium",children:e.jsx("div",{children:e.jsxs("button",{onClick:()=>o(`/mission-control/contacts/${A.contact.id}`),className:"truncate max-w-[160px] text-left hover:text-primary hover:underline transition-colors",children:[A.contact.first_name," ",A.contact.last_name]})})}),e.jsx(gt,{children:A.relationshipTypeName?e.jsx(Be,{variant:"secondary",className:"text-xs",children:A.relationshipTypeName}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(gt,{children:e.jsx("div",{className:"flex items-center gap-1.5",children:L?e.jsx(Be,{className:Mt("gap-1",M==="birthday"&&"bg-pink-500 hover:bg-pink-600",M==="anniversary"&&"bg-purple-500 hover:bg-purple-600"),children:M==="birthday"?e.jsxs(e.Fragment,{children:[e.jsx(lg,{className:"h-3 w-3"})," Birthday"]}):e.jsxs(e.Fragment,{children:[e.jsx(ra,{className:"h-3 w-3"})," Anniversary"]})}):e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(I,{className:"h-3 w-3"}),(H=A.actionType)==null?void 0:H.name]})})}),e.jsx(gt,{children:R?e.jsx("span",{className:"text-sm font-mono",children:A.contact.phone}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[R&&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(ba,{className:"h-3.5 w-3.5"})}),R&&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(Ki,{className:"h-3.5 w-3.5"})}),z&&(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(ln,{className:"h-3.5 w-3.5"})}):e.jsx("a",{href:i(A.contact.email,(K=A.script)==null?void 0:K.script_body,(Z=A.script)==null?void 0:Z.email_subject,(Q=A.actionType)==null?void 0:Q.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(ln,{className:"h-3.5 w-3.5"})})),L&&e.jsxs("button",{onClick:()=>{const le=`${A.contact.first_name}${A.contact.last_name?" "+A.contact.last_name:""}`,ue=M==="birthday"?"birthday":"home_anniversary",se=new URLSearchParams({cardType:ue,contactId:A.contact.id,name:le,...A.contact.address?{address:A.contact.address}:{},...M==="anniversary"&&A.contact.home_anniversary?{date:A.contact.home_anniversary}:{}});o(`/mission-control/card-studio?${se.toString()}`)},className:Mt("h-7 px-2 rounded text-xs font-semibold flex items-center gap-1 transition-colors",M==="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 ${M==="birthday"?"Birthday":"Anniversary"} Card`,children:[e.jsx(ln,{className:"h-3.5 w-3.5"}),"Send Card"]}),e.jsx(U,{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(uv,{className:"h-3.5 w-3.5"})}),e.jsxs(U,{variant:"default",size:"sm",className:"h-7 px-2 text-xs ml-1",onClick:()=>{var le;return t(A.contact.id,A.actionType.id,(le=A.script)==null?void 0:le.id)},disabled:r,children:[e.jsx(zr,{className:"h-3.5 w-3.5 mr-1"}),"Done"]})]})})]},`${A.contact.id}-${T}`)})})]})}),e.jsx(ULe,{open:!!m,onOpenChange:A=>!A&&p(null),contactId:m||"",contactName:f})]})}function DLn(){const s=Wn(),{data:t}=t7t(),{data:n}=cre(),r=tPe(),{isGmailConnected:a,gmailEmail:i}=Ax(),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(new Set),m=vf(new Date),p=jh(m,30),f=A=>{if(!A)return null;const T=A.split(/[-/T]/);if(T.length<3)return null;const L=parseInt(T[1],10)-1,M=parseInt(T[2],10);return isNaN(L)||isNaN(M)?null:new Date(m.getFullYear(),L,M)},x=j.useMemo(()=>{if(!t)return[];const A=[];for(const T of t){if(T.birthday){const L=f(T.birthday);L&&(Hh(L,m)||F4(L,m)&&rS(L,p))&&A.push({contact:T,type:"birthday",date:L,daysUntil:nv(L,m),dateStr:T.birthday})}if(T.home_anniversary){const L=f(T.home_anniversary);L&&(Hh(L,m)||F4(L,m)&&rS(L,p))&&A.push({contact:T,type:"anniversary",date:L,daysUntil:nv(L,m),dateStr:T.home_anniversary})}if(T.wedding_anniversary){const L=f(T.wedding_anniversary);L&&(Hh(L,m)||F4(L,m)&&rS(L,p))&&A.push({contact:T,type:"wedding_anniversary",date:L,daysUntil:nv(L,m),dateStr:T.wedding_anniversary})}}return A.sort((T,L)=>T.daysUntil-L.daysUntil),A},[t]),y=A=>A==="birthday"?"Birthday":A==="wedding_anniversary"?"Wedding Anniversary":"Home Anniversary",v=async A=>{const T=(n==null?void 0:n.find(L=>L.name==="Call"))||(n==null?void 0:n[0]);if(T)try{await r.mutateAsync({contactId:A.contact.id,actionTypeId:T.id,notes:`${y(A.type)} outreach`}),h(L=>new Set(L).add(`${A.contact.id}-${A.type}`)),ka({title:"Touch logged!",description:`Logged outreach for ${A.contact.first_name}`})}catch{ka({title:"Error",description:"Failed to log touch",variant:"destructive"})}},b=A=>{const T=`${A.contact.first_name}${A.contact.last_name?" "+A.contact.last_name:""}`,L=A.type==="birthday"?"birthday":A.type==="wedding_anniversary"?"wedding_anniversary":"home_anniversary",M=new URLSearchParams({cardType:L,contactId:A.contact.id,name:T,...A.contact.address?{address:A.contact.address}:{},...(A.type==="anniversary"||A.type==="wedding_anniversary")&&A.dateStr?{date:A.dateStr}:{}});s(`/mission-control/card-studio?${M.toString()}`)},N=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(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(It,{className:"text-lg flex items-center gap-2",children:[e.jsx(nc,{className:"h-5 w-5 text-primary"}),"Upcoming Milestones",e.jsx(Be,{variant:"secondary",className:"text-xs font-normal",children:"Next 30 days"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[x.length," event",x.length!==1?"s":""]})]})}),e.jsxs(Ie,{className:"space-y-2",children:[x.length===0&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(lg,{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,T)=>{var R,z;const L=`${A.contact.id}-${A.type}`,M=u.has(L),I=`${((R=A.contact.first_name)==null?void 0:R[0])||""}${((z=A.contact.last_name)==null?void 0:z[0])||""}`.toUpperCase();return e.jsxs("div",{className:Mt("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(Ea,{className:Mt("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(Ta,{className:Mt("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:I})}),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(Be,{variant:"outline",className:Mt("text-[10px] shrink-0 whitespace-nowrap",S(A.daysUntil)),children:N(A.daysUntil)})]}),e.jsxs("div",{className:Mt("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(lg,{className:"h-3 w-3"})," Birthday"]}):A.type==="wedding_anniversary"?e.jsxs(e.Fragment,{children:[e.jsx(ko,{className:"h-3 w-3"})," Wedding Anniversary"]}):e.jsxs(e.Fragment,{children:[e.jsx(ra,{className:"h-3 w-3"})," Home Anniversary"]}),e.jsx("span",{children:"·"}),e.jsx("span",{children:Gs(A.date,"MMM d")})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 mt-2 pl-[52px]",children:[A.contact.phone&&e.jsx(U,{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(ba,{className:"h-3.5 w-3.5"})})}),A.contact.phone&&e.jsx(U,{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(Ki,{className:"h-3.5 w-3.5"})})}),A.contact.email&&e.jsx(U,{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(ln,{className:"h-3.5 w-3.5"})}),e.jsx(U,{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(Wr,{className:"h-3.5 w-3.5"})}),e.jsxs(U,{variant:"ghost",size:"sm",className:Mt("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(cn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Card"})]}),e.jsx(U,{variant:"ghost",size:"icon",className:Mt("h-7 w-7",M&&"text-green-600"),title:"Log a touch",disabled:M||r.isPending,onClick:()=>v(A),children:e.jsx(zr,{className:"h-3.5 w-3.5"})}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"View contact",onClick:()=>s(`/mission-control/contacts/${A.contact.id}`),children:e.jsx(xa,{className:"h-3.5 w-3.5"})})]})]},`${L}-${T}`)})]})]}),a&&l&&e.jsx(wS,{open:c,onOpenChange:d,contact:l,gmailEmail:i})]})}function OLn(s){const[t,n]=j.useState([]),[r,a]=j.useState(!1),{data:i,isLoading:l}=ct({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(f=>f.contact_id).filter(Boolean);let m={};if(h.length>0){const{data:f}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",h);(f||[]).forEach(x=>{m[x.id]=x})}const p=u.map(f=>f.auth_user_id).filter(Boolean);if(p.length>0){const{data:f}=await q.from("lead_site_consumer_profiles").select("user_id, name, phone, contact_id").eq("lead_site_id",s).in("user_id",p);(f||[]).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(f=>{var x,y;return{...f,contact_name:m[f.contact_id||f.auth_user_id||""]?`${m[f.contact_id||f.auth_user_id||""].first_name} ${m[f.contact_id||f.auth_user_id||""].last_name||""}`.trim():null,contact_email:((x=m[f.contact_id||f.auth_user_id||""])==null?void 0:x.email)||null,contact_phone:((y=m[f.contact_id||f.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(f=>f.id===h.new.id)?m:[h.new,...m]):h.eventType==="UPDATE"?n(m=>m.map(p=>p.id===h.new.id?{...p,...h.new}:p)):h.eventType==="DELETE"&&n(m=>m.filter(p=>p.id!==h.old.id))}).subscribe(h=>{h==="SUBSCRIBED"&&a(!0)});return()=>{q.removeChannel(u)}},[s]);const o=r&&t.length>0?FLn([...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 FLn(s){const t=new Set;return s.filter(n=>t.has(n.id)?!1:(t.add(n.id),!0))}const zLn={property_view:{label:"Viewed",icon:xa,color:"text-blue-500",bgColor:"bg-blue-500/10"},new_lead:{label:"New Lead",icon:zl,color:"text-emerald-500",bgColor:"bg-emerald-500/10"},saved_listing:{label:"Saved",icon:ko,color:"text-rose-500",bgColor:"bg-rose-500/10"}};function BLn(){const{user:s}=vs(),t=Wn(),{isGmailConnected:n,gmailEmail:r}=Ax(),{leadSite:a}=$p(),{count:i}=OLn(a==null?void 0:a.id),[l,o]=j.useState(!1),[c,d]=j.useState(null),{data:u,isLoading:h}=ct({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"),p=m.filter(v=>v.activity_type==="new_lead"),f=(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(fl,{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(U,{variant:"ghost",size:"sm",className:"text-primary gap-1",onClick:()=>t("/mission-control/website-activity"),children:["View All",e.jsx(Oa,{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(zl,{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:p.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(xa,{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:f}),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(ko,{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 N=zLn[v.activity_type],S=N.icon,A=Nd(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 ${N.bgColor}`,children:e.jsx(S,{className:`h-3.5 w-3.5 ${N.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:N.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(U,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>y(v),children:e.jsx(ln,{className:"h-3.5 w-3.5"})}),v.visitor_phone&&e.jsxs(e.Fragment,{children:[e.jsx(U,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`tel:${v.visitor_phone}`,children:e.jsx(ba,{className:"h-3.5 w-3.5"})}),e.jsx(U,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`sms:${v.visitor_phone}`,children:e.jsx(Ki,{className:"h-3.5 w-3.5"})})]}),v.contact_id&&e.jsx(U,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>t(`/mission-control/contacts/${v.contact_id}`),children:e.jsx(gi,{className:"h-3.5 w-3.5"})})]})]},`${v.activity_type}-${v.occurred_at}-${b}`)}),m.length>5&&e.jsxs(U,{variant:"outline",className:"w-full text-xs",onClick:()=>t("/mission-control/website-activity"),children:["View ",m.length-5," more activities",e.jsx(Oa,{className:"h-3.5 w-3.5 ml-1"})]})]}):e.jsx(we,{children:e.jsxs(Ie,{className:"p-6 text-center",children:[e.jsx(Lm,{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:f>0?`${f} anonymous listing views recorded.`:"Lead engagement will appear here as visitors interact with your site."}),e.jsxs(U,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>t("/mission-control/website-activity"),children:["View Full Activity",e.jsx(Oa,{className:"h-3.5 w-3.5 ml-1"})]})]})}),n&&c&&e.jsx(wS,{open:l,onOpenChange:o,contact:c,gmailEmail:r})]})}const _wt={Crown:h0,FileText:Ur,Users:Bn,Globe:fl,Star:Ua,Phone:ba,MessageSquare:Ki,PenTool:TA,Video:Wr,Gift:Ro},ULn={"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 qLn(){var pt,ft,qt,Ut,Wt,us;const s=Wn(),{user:t}=vs(),{data:n}=F_(),{data:r}=s7t(),{data:a}=Cb(),{data:i}=cre(),{data:l}=BQe(),o=B7s(),c=sPe(),d=O7s(90),u=tPe(),[h,m]=j.useState(null),[p,f]=j.useState(null),[x,y]=j.useState(!1),[v,b]=j.useState(""),[N,S]=j.useState(!1),[A,T]=j.useState(""),[L,M]=j.useState(i7t()),[I,R]=j.useState("cards"),[z,$]=j.useState(!1),[H,V]=j.useState(null),[K,Z]=j.useState(null),[Q,le]=j.useState(""),{isGmailConnected:ue,gmailEmail:se}=Ax(),ne=()=>{const zt=parseInt(A,10);if(isNaN(zt)||zt<1){ka({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}M(zt),F7s(zt),S(!1),ka({title:"Goal updated",description:`Weekly touch goal set to ${zt}`})},ie=()=>{T(L.toString()),S(!0)};j.useEffect(()=>{(async()=>{if(!(t!=null&&t.id))return;const{data:bt}=await q.from("profiles").select("name").eq("id",t.id).single();bt!=null&&bt.name&&b(bt.name.split(" ")[0])})()},[t==null?void 0:t.id]),j.useEffect(()=>{o.mutate()},[]);const ce=vf(new Date),je=jh(ce,7),be=zt=>{if(!zt)return null;const bt=zt.split(/[-/T]/);if(bt.length<3)return null;const As=parseInt(bt[1],10)-1,vt=parseInt(bt[2],10);return isNaN(As)||isNaN(vt)?null:new Date(ce.getFullYear(),As,vt)},he=(a==null?void 0:a.filter(zt=>{const bt=be(zt.birthday),As=be(zt.home_anniversary);return bt&&Hh(bt,ce)||As&&Hh(As,ce)}))||[],ge=(a==null?void 0:a.filter(zt=>{if(!zt.birthday&&!zt.home_anniversary)return!1;const bt=As=>{if(!As)return!1;const vt=be(As);return vt?F4(vt,ce)&&rS(vt,je):!1};return bt(zt.birthday)||bt(zt.home_anniversary)}).slice(0,5))||[],ke=[],Te=(i==null?void 0:i.find(zt=>zt.name==="Call"))||(i==null?void 0:i[0]);for(const zt of he){const bt=be(zt.birthday),As=be(zt.home_anniversary),vt=bt&&Hh(bt,ce),Ws=As&&Hh(As,ce);vt&&ke.push({contact:zt,actionType:Te||{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:((qt=(ft=(pt=zt.tags)==null?void 0:pt[0])==null?void 0:ft.relationship_type)==null?void 0:qt.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"birthday"}),Ws&&ke.push({contact:zt,actionType:Te||{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:((us=(Wt=(Ut=zt.tags)==null?void 0:Ut[0])==null?void 0:Wt.relationship_type)==null?void 0:us.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"anniversary"})}const Oe=l!==void 0?l||[]:(a==null?void 0:a.slice(0,5).map((zt,bt)=>{var vt,Ws,on;const As=i==null?void 0:i[bt%((i==null?void 0:i.length)||1)];return As?{contact:zt,actionType:As,planName:"Quick Touch",relationshipTypeName:((on=(Ws=(vt=zt.tags)==null?void 0:vt[0])==null?void 0:Ws.relationship_type)==null?void 0:on.name)||"",monthNumber:0}:null}).filter(Boolean))||[],Se=[...ke,...Oe],{data:Qe}=CG(7),Ae=(Qe||[]).filter(zt=>Hh(new Date(zt.completed_at),ce)).length,Fe=Ae+Se.length,Ne=(a==null?void 0:a.length)??0,$e=ke.length>0?`${ke.length} celebration${ke.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.`:ge.length>0?`${ge.length} milestone${ge.length===1?"":"s"} coming up this week — get ahead of them.`:"Consistency beats intensity. A few real conversations today is a win.",Ve=async(zt,bt,As)=>{await u.mutateAsync({contactId:zt,actionTypeId:bt,scriptUsedId:As}),y(!1),f(null)},qe=zt=>{zt.script?(f(zt),y(!0)):Ve(zt.contact.id,zt.actionType.id)},Ze=zt=>_wt[zt||"Phone"]||ba,Ue=zt=>_wt[zt||"Users"]||Bn,Ye=(zt,bt)=>zt.replace(/\{\{FirstName\}\}/g,bt.first_name).replace(/\{\{LastName\}\}/g,bt.last_name||"").replace(/\{\{AgentName\}\}/g,v||"there"),Ge=(zt,bt)=>({Call:`Thinking of you, ${bt}!`,Text:`Quick hello, ${bt}`,Email:`Checking in, ${bt}`,"Handwritten Note":`A note for ${bt}`,Video:`Video message for ${bt}`,Gift:`Something special for you, ${bt}`})[zt]||`Hello ${bt}!`,He=(zt,bt,As)=>{const vt=`sms:${zt}`;if(bt&&As){const Ws=Ye(bt,As);return`${vt}?body=${encodeURIComponent(Ws)}`}return vt},tt=(zt,bt,As,vt,Ws)=>{const on=`mailto:${zt}`,Ms=[];if(Ws){const dn=As||Ge(vt||"Email",Ws.first_name);if(Ms.push(`subject=${encodeURIComponent(dn)}`),bt){const rn=Ye(bt,Ws);Ms.push(`body=${encodeURIComponent(rn)}`)}}return Ms.length>0?`${on}?${Ms.join("&")}`:on};return e.jsxs(e.Fragment,{children:[e.jsxs(qs,{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(U,{size:"sm",onClick:()=>s("/mission-control/video/record"),className:"gap-1.5 bg-gradient-to-r from-primary to-primary/80",children:[e.jsx(Gh,{className:"h-4 w-4"}),"Quick Video"]}),e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/contacts"),className:"gap-1.5",children:[e.jsx(Bn,{className:"h-4 w-4"}),"Contacts"]}),e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/video-library"),className:"gap-1.5",children:[e.jsx(Wr,{className:"h-4 w-4"}),"Library"]}),e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/plans"),className:"gap-1.5",children:[e.jsx(qc,{className:"h-4 w-4"}),"Plans"]})]})]}),e.jsx(ALn,{agentName:v,todayDone:Ae,todayTotal:Fe,focusLine:$e,weekDone:c.actionsThisWeek,weekGoal:L,streak:c.streak,staleCount:d.count,sphereCount:Ne,onEditGoal:ie,onStaleClick:()=>s("/mission-control/contacts?filter=not-touched-90"),onSphereClick:()=>s("/mission-control/contacts")}),e.jsx(BLn,{}),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(gi,{className:"h-3 w-3"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n==null?void 0:n.filter(zt=>zt.active).map(zt=>{const bt=Ue(zt.icon),As=(r==null?void 0:r[zt.id])||0,vt=h===zt.id,Ws=ULn[zt.name]||"bg-secondary text-secondary-foreground";return e.jsxs("button",{onClick:()=>{vt?(m(null),s("/mission-control/contacts")):(m(zt.id),s(`/mission-control/contacts?type=${zt.id}`))},className:` inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition-all ${vt?Ws:"bg-card hover:bg-accent"} `,children:[e.jsx(bt,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"font-medium",children:zt.name}),e.jsx("span",{className:`rounded-full px-1.5 py-0.5 text-[11px] tabular-nums ${vt?"bg-black/15":"bg-muted text-muted-foreground"}`,children:As})]},zt.id)})})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Today in Your InnerCircle"}),l!==void 0&&e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(cn,{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(U,{variant:I==="cards"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>R("cards"),title:"Card view",children:e.jsx(Hg,{className:"h-4 w-4"})}),e.jsx(U,{variant:I==="table"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>R("table"),title:"Table view",children:e.jsx(m0,{className:"h-4 w-4"})})]})]}),e.jsx(we,{children:e.jsx(Ie,{className:"p-4",children:Se.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(U,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/plans"),children:"Manage Plans"})]}):I==="table"?e.jsx(RLn,{actions:Se,onMarkComplete:Ve,onViewScript:qe,isLoading:u.isPending,buildSmsLink:He,buildEmailLink:tt,onGmailCompose:ue?zt=>{V(zt),$(!0)}:void 0}):e.jsxs("div",{className:"flex gap-3 overflow-x-auto pb-2",children:[Se.map((zt,bt)=>{var br,Gn,On,Rr,cr,Hs,_r;const As=zt.isSpecialDate,vt=zt.specialDateType,Ws=As?vt==="birthday"?lg:ra:Ze(((br=zt.actionType)==null?void 0:br.icon)||null),on=zt.contact.phone,Ms=zt.contact.email,dn=As?vt==="birthday"?"#EC4899":"#8B5CF6":((Gn=zt.actionType)==null?void 0:Gn.color)||"#3B82F6",rn=As?vt==="birthday"?"🎂 Birthday Today!":"🏠 Home Anniversary!":(On=zt.actionType)==null?void 0:On.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":dn}:void 0,children:[e.jsxs("div",{className:"p-3 text-white flex items-center gap-2",style:{backgroundColor:dn},children:[e.jsx(Ws,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-sm",children:rn})]}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("button",{onClick:()=>s(`/mission-control/contacts/${zt.contact.id}`),className:"font-medium text-sm hover:text-primary hover:underline transition-colors text-left",children:[zt.contact.first_name," ",zt.contact.last_name]}),e.jsxs("div",{className:"flex gap-1.5",children:[on&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${zt.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(ba,{className:"h-3 w-3"}),"Call"]}),e.jsxs("a",{href:He(zt.contact.phone,(Rr=zt.script)==null?void 0:Rr.script_body,zt.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(Ki,{className:"h-3 w-3"}),"Text"]})]}),Ms&&(ue?e.jsxs("button",{onClick:()=>{V({id:zt.contact.id,first_name:zt.contact.first_name,last_name:zt.contact.last_name,email:zt.contact.email}),$(!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(ln,{className:"h-3 w-3"}),"Email"]}):e.jsxs("a",{href:tt(zt.contact.email,(cr=zt.script)==null?void 0:cr.script_body,(Hs=zt.script)==null?void 0:Hs.email_subject,(_r=zt.actionType)==null?void 0:_r.name,zt.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(ln,{className:"h-3 w-3"}),"Email"]}))]}),As&&e.jsxs("button",{onClick:()=>{const nn=`${zt.contact.first_name}${zt.contact.last_name?" "+zt.contact.last_name:""}`,Zn=vt==="birthday"?"birthday":"home_anniversary",es=new URLSearchParams({cardType:Zn,contactId:zt.contact.id,name:nn,...zt.contact.address?{address:zt.contact.address}:{},...vt==="anniversary"&&zt.contact.home_anniversary?{date:zt.contact.home_anniversary}:{}});s(`/mission-control/card-studio?${es.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(ln,{className:"h-3 w-3"}),"Send ",vt==="birthday"?"Birthday":"Anniversary"," Card"]}),!on&&!Ms&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No contact info"}),e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[zt.relationshipTypeName&&e.jsx(Be,{variant:"secondary",className:"text-xs",children:zt.relationshipTypeName}),zt.monthNumber>0&&e.jsxs(Be,{variant:"outline",className:"text-xs",children:["Month ",zt.monthNumber]})]}),zt.script&&e.jsx(U,{size:"sm",variant:"outline",className:"w-full",onClick:()=>qe(zt),children:"View Script"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsxs(U,{size:"sm",variant:"outline",className:"flex-1 gap-1",onClick:()=>{Z(zt.contact.id),le(`${zt.contact.first_name} ${zt.contact.last_name||""}`.trim())},children:[e.jsx(uv,{className:"h-3.5 w-3.5"}),"Snooze"]}),e.jsx(U,{size:"sm",className:"flex-1",onClick:()=>{var nn;return Ve(zt.contact.id,zt.actionType.id,(nn=zt.script)==null?void 0:nn.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]},zt.contact.id+bt)}),e.jsx("div",{className:"flex-shrink-0 w-[100px] border rounded-lg flex items-center justify-center",children:e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsxs(U,{variant:"ghost",className:"h-full w-full",children:[e.jsx(Z1,{className:"h-5 w-5 mr-2"}),"More"]})}),e.jsx(Eu,{children:e.jsx(La,{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(Xd,{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 ",L," touches"]})]}),e.jsx(ro,{value:Math.min(c.actionsThisWeek/L*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>=L?"Goal hit for the week — anything else is bonus.":`${L-c.actionsThisWeek} more to hit your goal.`})]}),e.jsx(zs,{open:N,onOpenChange:S,children:e.jsxs(Ds,{className:"sm:max-w-[360px]",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{htmlFor:"weekly-goal-ic",children:"Weekly touch goal"}),e.jsx(xe,{id:"weekly-goal-ic",type:"number",min:"1",value:A,onChange:zt=>T(zt.target.value),placeholder:"20",onKeyDown:zt=>{zt.key==="Enter"&&ne()}})]}),e.jsx(U,{onClick:ne,className:"w-full",children:"Save Goal"})]})]})}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsx(N7t,{}),e.jsx(DLn,{})]})]}),e.jsx(zs,{open:x,onOpenChange:y,children:e.jsxs(Ds,{className:"max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{className:"flex items-center gap-2",children:p&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:p.actionType.color||"#3B82F6"}}),p.actionType.name," Script"]})})}),p&&p.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:[p.contact.first_name," ",p.contact.last_name]})]}),e.jsx("div",{className:"bg-muted p-4 rounded-lg",children:e.jsx("p",{className:"whitespace-pre-wrap",children:Ye(p.script.script_body,p.contact)})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{variant:"outline",className:"flex-1",onClick:()=>y(!1),children:"Close"}),e.jsx(U,{className:"flex-1",onClick:()=>{var zt;return Ve(p.contact.id,p.actionType.id,(zt=p.script)==null?void 0:zt.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]})}),e.jsx(ELn,{})]}),ue&&H&&e.jsx(wS,{open:z,onOpenChange:$,contact:H,gmailEmail:se}),e.jsx(ULe,{open:!!K,onOpenChange:zt=>!zt&&Z(null),contactId:K||"",contactName:Q})]})}const $Ln=[{value:"bidirectional",label:"Two-Way",icon:xx,tooltip:"Sync contacts in both directions"},{value:"push_only",label:"Push Only",icon:cp,tooltip:"Only push Agent OS → BoldTrail"},{value:"pull_only",label:"Pull Only",icon:ag,tooltip:"Only pull BoldTrail → Agent OS"}];function REe({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(Uq,{type:"single",value:s,onValueChange:a=>{a&&t(a)},className:"justify-start",children:$Ln.map(a=>e.jsxs(Bg,{children:[e.jsx(Ug,{asChild:!0,children:e.jsxs(JF,{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(ng,{children:a.tooltip})]},a.value))})]})}function VLn(){const s=Qt(),[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),[p,f]=j.useState(0),x=j.useRef(!1),{data:y}=ct({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:I,error:R}=await q.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(R)throw R;return I}}),v=(y==null?void 0:y.sync_direction)||"bidirectional",b=d??v,N=yt({mutationFn:async()=>{const{data:I,error:R}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(R)throw R;if(I!=null&&I.error)throw new Error(I.error);return I},onSuccess:I=>{u(null),a(I),n(!0)},onError:I=>{re.error(I.message||"Failed to generate sync preview")}}),S=yt({mutationFn:async()=>{x.current=!1,m("Initializing sync..."),f(5);const{data:I,error:R}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:b}});if(R)throw R;if(I!=null&&I.error)throw new Error(I.error);const z=I;let $=z.sync_log_id,H=z.next_phase,V=z.next_offset,K=z.push_total||0,Z=z.pull_total||0,Q=z.update_total||0,le=0,ue=0,se=0;for(;H!=="finalize"&&!x.current;){const ce=K+Z+Q;H==="fetch_bt"?m("Fetching BoldTrail contacts..."):H==="analyze"?(m("Analyzing contacts..."),f(15)):H==="push"?(m(`Pushing contacts to BoldTrail... (${le}/${K})`),f(ce>0?le/ce*90:0)):H==="pull"?(m(`Pulling contacts from BoldTrail... (${ue}/${Z})`),f(ce>0?(K+ue)/ce*90:0)):H==="update"&&(m(`Updating existing contacts... (${se}/${Q})`),f(ce>0?(K+Z+se)/ce*90:0));const{data:je,error:be}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:H,offset:V,sync_log_id:$,sync_direction:b}});if(be)throw be;if(je!=null&&je.error)throw new Error(je.error);const he=je;le+=he.chunk_pushed||0,ue+=he.chunk_pulled||0,se+=he.chunk_updated||0,he.push_total!==void 0&&(K=he.push_total||0),he.pull_total!==void 0&&(Z=he.pull_total||0),he.update_total!==void 0&&(Q=he.update_total||0),he.progress&&m(he.progress),H=he.next_phase,V=he.next_offset}m("Finalizing sync..."),f(95);const{data:ne,error:ie}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:$,sync_direction:b}});if(ie)throw ie;return f(100),ne},onSuccess:I=>{m(null),f(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 R=[`Pushed ${I.contacts_pushed||0}`,`pulled ${I.contacts_pulled||0}`,`updated ${I.contacts_updated||0}`,`skipped ${I.contacts_skipped||0} duplicates`];re.success(`Sync complete! ${R.join(", ")}.`)},onError:I=>{m(null),f(0),re.error(I.message||"Sync failed")}});if(!(y!=null&&y.connected))return null;const A=b==="pull_only"?0:(r==null?void 0:r.to_push)??0,T=b==="push_only"?0:(r==null?void 0:r.to_pull)??0,L=(r==null?void 0:r.to_update)??0,M=A>0||T>0||L>0;return e.jsxs(e.Fragment,{children:[e.jsxs(Bg,{children:[e.jsx(Ug,{asChild:!0,children:e.jsx(U,{variant:"outline",size:"icon",onClick:()=>N.mutate(),disabled:N.isPending,className:"shrink-0",children:N.isPending?e.jsx(no,{className:"h-4 w-4 animate-spin"}):e.jsx(xx,{className:"h-4 w-4 text-emerald-600"})})}),e.jsx(ng,{children:"Sync with BoldTrail"})]}),e.jsx(zs,{open:t,onOpenChange:I=>{S.isPending||n(I)},children:e.jsxs(Ds,{className:"sm:max-w-lg",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(xx,{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(REe,{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(cp,{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:T}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(ag,{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:L}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(dq,{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(Bn,{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"]}),L>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(dq,{className:"h-3 w-3 inline mr-1"}),L," contacts have missing fields that will be filled from the other system"]}),A>0&&e.jsxs(ub,{open:i,onOpenChange:l,children:[e.jsx(hb,{asChild:!0,children:e.jsxs(U,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(cp,{className:"h-3 w-3 text-emerald-600"}),A," contacts to push to BoldTrail"]}),e.jsx(rl,{className:`h-3 w-3 transition-transform ${i?"rotate-180":""}`})]})}),e.jsx(mb,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[r.push_preview.map((I,R)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:I.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:I.email})]},R)),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"]})]})})]}),T>0&&e.jsxs(ub,{open:o,onOpenChange:c,children:[e.jsx(hb,{asChild:!0,children:e.jsxs(U,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ag,{className:"h-3 w-3 text-blue-600"}),T," contacts to pull from BoldTrail"]}),e.jsx(rl,{className:`h-3 w-3 transition-transform ${o?"rotate-180":""}`})]})}),e.jsx(mb,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[r.pull_preview.map((I,R)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:I.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:I.email})]},R)),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"]})]})})]}),!M&&!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(ro,{value:p||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(U,{variant:"outline",onClick:()=>n(!1),disabled:S.isPending,children:"Cancel"}),e.jsxs(U,{onClick:()=>S.mutate(),disabled:S.isPending||!M,className:"gap-2",children:[S.isPending?e.jsx(no,{className:"h-4 w-4 animate-spin"}):e.jsx(xx,{className:"h-4 w-4"}),S.isPending?"Syncing...":"Sync Now"]})]})]})]})})]})}const HLn=()=>{const{user:s}=vs();return ct({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})},qLe=s=>{const{user:t}=vs();return ct({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})},Ztt=()=>{const{user:s}=vs();return ct({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})},YGt=()=>{const{user:s}=vs();return ct({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})},GLn=()=>{const{data:s}=Cb();F_();const{data:t}=qLe(),{data:n}=YGt(),{data:r}=Ztt(),a=new Map;t==null||t.forEach(d=>{const u=a.get(d.contact_id);(!u||new Date(d.completed_at)>new Date(u))&&a.set(d.contact_id,d.completed_at)});const i=new Map;r==null||r.forEach(d=>i.set(d.relationship_type_id,d.frequency_days));const l=new Map;n==null||n.filter(d=>d.is_active).forEach(d=>{l.set(d.contact_id,d.frequency_days)});const o=vf(new Date);return(s||[]).map(d=>{let u=90;if(l.has(d.id))u=l.get(d.id);else if(d.tags&&d.tags.length>0){const x=d.tags.map(y=>i.get(y.relationship_type_id)).filter(y=>y!==void 0);x.length>0&&(u=Math.min(...x))}const h=a.get(d.id)||null,m=h?hN(o,vf(new Date(h))):null,p=m===null||m>=u,f=p&&m!==null?m-u:0;return{...d,lastPopby:h,daysSinceLastPopby:m,frequencyDays:u,isDue:p,daysOverdue:f}}).sort((d,u)=>u.daysOverdue-d.daysOverdue)},ZGt=()=>GLn().filter(t=>t.isDue),WLn=()=>{const s=Qt(),{user:t}=vs();return yt({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"]}),ka({title:"Popby item created!"})},onError:n=>{ka({title:"Error creating popby item",description:n.message,variant:"destructive"})}})},KLn=()=>{const s=Qt(),{user:t}=vs();return yt({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"]}),ka({title:"Popby logged!"})},onError:n=>{ka({title:"Error logging popby",description:n.message,variant:"destructive"})}})},YLn=()=>{const s=Qt(),{user:t}=vs();return yt({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"]}),ka({title:"Frequency updated!"})},onError:n=>{ka({title:"Error updating frequency",description:n.message,variant:"destructive"})}})},ZLn=()=>{const{data:s}=qLe(30),t=ZGt(),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 XLn(){const{user:s}=vs();return ct({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 XGt(s){const{data:t}=XLn(),{data:n}=YGt(),{data:r}=Ztt(),{data:a}=TLn();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=vf(new Date);if(l&&!rS(l,o))return{nextTouchDate:l,daysUntil:hN(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(N=>N.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 p=jh(vf(u),h),f=hN(p,o);let x;return f<0?x="overdue":f<=7?x="due-soon":x="on-track",{nextTouchDate:p,daysUntil:f,status:x,frequencyDays:h,lastTouchDate:u,snoozedUntil:null}},[s,t,n,r,a])}function wwt({contact:s}){const t=XGt(s),r=(()=>{switch(t.status){case"overdue":return{variant:"destructive",icon:Vo,text:`${Math.abs(t.daysUntil)} days overdue`,className:""};case"due-soon":return{variant:"secondary",icon:Yr,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:zr,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:uv,text:`Snoozed until ${Gs(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:pa,text:"Never touched",className:"border-dashed"}}})(),a=r.icon;return e.jsxs(Be,{variant:r.variant,className:Mt("gap-1",r.className),children:[e.jsx(a,{className:"h-3 w-3"}),r.text]})}function QLn({contact:s,onLogTouch:t,onSnooze:n}){const r=XGt(s),a=PLn(),[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(Vo,{className:"h-5 w-5 text-destructive"});case"due-soon":return e.jsx(Yr,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"});case"on-track":return e.jsx(zr,{className:"h-5 w-5 text-emerald-600 dark:text-emerald-400"});case"snoozed":return e.jsx(uv,{className:"h-5 w-5 text-slate-600 dark:text-slate-400"});case"never-touched":return e.jsx(pa,{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(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsxs(It,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(pa,{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:Mt("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:"})," ",Gs(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:"})," ",Gs(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:"})," ",Gs(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(U,{size:"sm",variant:"outline",className:"flex-1",onClick:u,disabled:a.isPending,children:[e.jsx(er,{className:"h-4 w-4 mr-1"}),"Cancel Snooze"]}),t&&e.jsx(U,{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(U,{size:"sm",variant:"outline",className:"flex-1",onClick:()=>l(!0),children:[e.jsx(uv,{className:"h-4 w-4 mr-1"}),"Snooze"]}),(r.status==="overdue"||r.status==="due-soon"||r.status==="never-touched")&&t&&e.jsx(U,{size:"sm",className:"flex-1",variant:r.status==="overdue"?"default":"outline",onClick:t,children:"Log Touch"})]})]})]}),e.jsx(ULe,{open:i,onOpenChange:l,contactId:s.id,contactName:`${s.first_name} ${s.last_name||""}`.trim()})]})}const G7e=768;function JG(){const[s,t]=j.useState(void 0);return j.useEffect(()=>{const n=window.matchMedia(`(max-width: ${G7e-1}px)`),r=()=>{t(window.innerWidthn.removeEventListener("change",r)},[]),!!s}function JLn(){const{user:s}=vs(),{hasLeadSite:t,leadSite:n}=$p(),{data:r,isLoading:a}=ct({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 eIn={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"}},tIn={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 ZHe({score:s,showScore:t=!1,showTooltip:n=!0,size:r="sm",className:a}){const i=eIn[s.status],l=tIn[r],o=e.jsxs("div",{className:Mt("inline-flex items-center rounded-full font-medium",i.bgLightClass,i.textClass,l.badge,l.text,a),children:[e.jsx("span",{className:Mt("rounded-full",i.bgClass,l.dot)}),t?e.jsx("span",{children:s.score}):e.jsx("span",{children:i.label})]});return n?e.jsx(wN,{children:e.jsxs(Bg,{children:[e.jsx(Ug,{asChild:!0,children:o}),e.jsx(ng,{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:Mt("font-bold",i.textClass),children:[s.score,"/100"]})]}),e.jsx(ro,{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 sIn=[{key:"first_name",label:"First Name",required:!0},{key:"last_name",label:"Last Name",required:!1},{key:"email",label:"Email",required:!1},{key:"phone",label:"Phone",required:!1},{key:"address",label:"Street Address",required:!1},{key:"city",label:"City",required:!1},{key:"state",label:"State",required:!1},{key:"zip",label:"Zip Code",required:!1},{key:"spouse_name",label:"Spouse Name",required:!1},{key:"spouse_email",label:"Spouse Email",required:!1},{key:"company_name",label:"Company",required:!1},{key:"job_title",label:"Job Title",required:!1},{key:"birthday",label:"Birthday",required:!1},{key:"home_anniversary",label:"Home Anniversary",required:!1},{key:"notes",label:"Notes",required:!1}],zle=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]},nIn=({open:s,onOpenChange:t,relationshipTypes:n,onSuccess:r})=>{const{user:a}=vs(),{toast:i}=Ai(),l=j.useRef(null),[o,c]=j.useState("upload"),[d,u]=j.useState([]),[h,m]=j.useState([]),[p,f]=j.useState({}),[x,y]=j.useState([]),[v,b]=j.useState([]),[N,S]=j.useState([]),[A,T]=j.useState(""),[L,M]=j.useState(!1),[I,R]=j.useState([]),[z,$]=j.useState(!1),[H,V]=j.useState(null);j.useEffect(()=>{!s||!(a!=null&&a.id)||(async()=>{const{data:Me}=await q.from("contact_custom_tags").select("id, name, color").eq("owner_user_id",a.id).order("name");b(Me||[])})()},[s,a==null?void 0:a.id]);const K=Me=>{S(Oe=>Oe.includes(Me)?Oe.filter(Se=>Se!==Me):[...Oe,Me])},Z=async()=>{const Me=A.trim();if(!(!Me||!(a!=null&&a.id))){M(!0);try{const{data:Oe,error:Se}=await q.from("contact_custom_tags").insert({owner_user_id:a.id,name:Me}).select("id, name, color").single();if(Se)throw Se;Oe&&(b(Qe=>[...Qe,Oe].sort((Ae,Fe)=>Ae.name.localeCompare(Fe.name))),S(Qe=>[...Qe,Oe.id]),T(""))}catch(Oe){i({title:"Could not create tag",description:Oe.message||"Try a different name.",variant:"destructive"})}finally{M(!1)}}},Q=()=>{c("upload"),u([]),m([]),f({}),y([]),S([]),T(""),R([]),V(null),l.current&&(l.current.value="")},le=()=>{Q(),t(!1)},ue=Me=>{const Oe=Me.split(` `).map($e=>$e.trim()).filter($e=>$e);if(Oe.length===0)return{headers:[],data:[]};const Se=$e=>{const Ve=[];let qe="",Ze=!1;for(let Ue=0;Ue<$e.length;Ue++){const Ye=$e[Ue];Ye==='"'?Ze=!Ze:(Ye===","||Ye===" ")&&!Ze?(Ve.push(qe.trim()),qe=""):qe+=Ye}return Ve.push(qe.trim()),Ve},Qe=Se(Oe[0]);Qe.length>0&&(Qe[0]=Qe[0].replace(/^\uFEFF/,""));const Ae=new Map,Fe=Qe.map(($e,Ve)=>{let qe=($e||"").trim();qe||(qe=`Column ${Ve+1}`);const Ze=Ae.get(qe)||0;return Ae.set(qe,Ze+1),Ze===0?qe:`${qe} (${Ze+1})`}),Ne=Oe.slice(1).map(Se);return{headers:Fe,data:Ne}},se=Me=>{var Qe;const Oe=(Qe=Me.target.files)==null?void 0:Qe[0];if(!Oe)return;const Se=new FileReader;Se.onload=Ae=>{var qe;const Fe=(qe=Ae.target)==null?void 0:qe.result,{headers:Ne,data:$e}=ue(Fe);if(Ne.length===0){i({title:"No data found",description:"The CSV file appears to be empty.",variant:"destructive"});return}u(Ne),m($e);const Ve={};Ne.forEach(Ze=>{const Ue=Ze.toLowerCase().replace(/[_\s-]/g,"");Ue.includes("firstname")||Ue==="first"?Ve.first_name=Ze:Ue.includes("lastname")||Ue==="last"?Ve.last_name=Ze:Ue.includes("spouse")&&Ue.includes("email")?Ve.spouse_email=Ze:Ue.includes("spouse")||Ue.includes("partner")?Ve.spouse_name=Ze:Ue.includes("email")?Ve.email=Ze:Ue.includes("phone")||Ue.includes("mobile")||Ue.includes("cell")?Ve.phone=Ze:Ue.includes("address")||Ue.includes("street")?Ve.address=Ze:Ue==="city"?Ve.city=Ze:Ue==="state"||Ue==="province"?Ve.state=Ze:Ue==="zip"||Ue==="zipcode"||Ue==="postalcode"?Ve.zip=Ze:Ue.includes("company")||Ue.includes("organization")||Ue.includes("business")?Ve.company_name=Ze:Ue.includes("jobtitle")||Ue.includes("title")&&!Ue.includes("spouse")?Ve.job_title=Ze:Ue.includes("birthday")||Ue.includes("dob")||Ue.includes("birthdate")?Ve.birthday=Ze:Ue.includes("anniversary")||Ue.includes("homeanniversary")?Ve.home_anniversary=Ze:(Ue.includes("notes")||Ue.includes("comment"))&&(Ve.notes=Ze)}),f(Ve),c("mapping")},Se.readAsText(Oe)},ne=(Me,Oe)=>{f(Se=>{if(Oe==="none"){const{[Me]:Qe,...Ae}=Se;return Ae}return{...Se,[Me]:Oe}})},ie=Me=>{y(Oe=>Oe.includes(Me)?Oe.filter(Se=>Se!==Me):[...Oe,Me])},ce=async()=>{if(!(a!=null&&a.id))return;const{data:Me}=await q.from("innercircle_contacts").select("id, email, phone").eq("owner_user_id",a.id),Oe=new Set((Me||[]).filter(Ae=>Ae.email).map(Ae=>Ae.email.toLowerCase())),Se=new Set((Me||[]).filter(Ae=>Ae.phone).map(Ae=>Ae.phone.replace(/[^0-9]/g,""))),Qe=h.map(Ae=>{const Fe=Ue=>{const Ye=p[Ue];if(!Ye)return"";const Ge=d.indexOf(Ye);return Ge>=0?(Ae[Ge]||"").trim():""},Ne=Fe("first_name"),$e=Fe("email"),Ve=Fe("phone"),qe=Ne.length>0,Ze=!!($e&&Oe.has($e.toLowerCase())||Ve&&Se.has(Ve.replace(/[^0-9]/g,"")));return{first_name:Ne,last_name:Fe("last_name"),email:$e,phone:Ve,address:Fe("address"),city:Fe("city"),state:Fe("state"),zip:Fe("zip"),spouse_name:Fe("spouse_name"),spouse_email:Fe("spouse_email"),company_name:Fe("company_name"),job_title:Fe("job_title"),birthday:Fe("birthday"),home_anniversary:Fe("home_anniversary"),notes:Fe("notes"),isValid:qe,isDuplicate:Ze,error:qe?void 0:"First name is required"}});R(Qe),c("preview")},je=Me=>{const Oe=Me.trim().split(/\s+/);return{first_name:Oe[0],last_name:Oe.length>1?Oe.slice(1).join(" "):null}},be=async()=>{if(!(a!=null&&a.id))return;const Me=I.filter(Ae=>Ae.isValid);if(Me.length===0){i({title:"No valid contacts",description:"There are no valid contacts to import.",variant:"destructive"});return}$(!0);let Oe=0,Se=0,Qe=0;try{for(const Ae of Me)try{let Fe=null;if(Ae.email){const{data:Ve}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",Ae.email).maybeSingle();Fe=Ve}if(!Fe&&Ae.phone){const Ve=Ae.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 Ze=qe.find(Ue=>Ue.phone&&Ue.phone.replace(/[^0-9]/g,"")===Ve);Ze&&(Fe={id:Ze.id})}}const Ne={owner_user_id:a.id,first_name:Ae.first_name,last_name:Ae.last_name||null,email:Ae.email||null,phone:Ae.phone||null,address:Ae.address||null,city:Ae.city||null,state:Ae.state||null,zip:Ae.zip||null,spouse_name:Ae.spouse_name||null,spouse_email:Ae.spouse_email||null,company_name:Ae.company_name||null,job_title:Ae.job_title||null,birthday:zle(Ae.birthday),home_anniversary:zle(Ae.home_anniversary),notes:Ae.notes||null};let $e=null;if(Fe){const{data:Ve}=await q.from("innercircle_contacts").select("*").eq("id",Fe.id).single();if(Ve){const qe={},Ze=["last_name","email","phone","address","city","state","zip","spouse_name","spouse_email","company_name","job_title","birthday","home_anniversary","notes"];for(const Ue of Ze){const Ye=Ve[Ue],Ge=Ne[Ue];(!Ye||Ye==="")&&Ge&&(qe[Ue]=Ge)}Object.keys(qe).length>0&&await q.from("innercircle_contacts").update(qe).eq("id",Fe.id)}$e=Fe.id,Se++}else{const{data:Ve,error:qe}=await q.from("innercircle_contacts").insert(Ne).select("id").single();qe?(console.error("Insert error for contact:",Ae.first_name,qe),Qe++):Ve?($e=Ve.id,x.length>0&&await q.from("innercircle_contact_tags").insert(x.map(Ze=>({contact_id:Ve.id,relationship_type_id:Ze}))),Oe++):Qe++}if($e&&N.length>0&&await q.from("contact_custom_tag_assignments").upsert(N.map(Ve=>({contact_id:$e,tag_id:Ve})),{onConflict:"contact_id,tag_id",ignoreDuplicates:!0}),$e&&Ae.spouse_name){const Ve=je(Ae.spouse_name);let qe=null;if(Ae.spouse_email){const{data:Ue}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",Ae.spouse_email).maybeSingle();qe=Ue}if(!qe){const{data:Ue}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("first_name",Ve.first_name).eq("last_name",Ve.last_name||Ae.last_name||"").maybeSingle();qe=Ue}let Ze=null;if(qe){Ze=qe.id;const Ue=zle(Ae.home_anniversary);Ue&&await q.from("innercircle_contacts").update({home_anniversary:Ue}).eq("id",qe.id).is("home_anniversary",null)}else{const{data:Ue}=await q.from("innercircle_contacts").insert({owner_user_id:a.id,first_name:Ve.first_name,last_name:Ve.last_name||Ae.last_name||null,email:Ae.spouse_email||null,address:Ae.address||null,city:Ae.city||null,state:Ae.state||null,zip:Ae.zip||null,home_anniversary:zle(Ae.home_anniversary),spouse_name:`${Ae.first_name}${Ae.last_name?" "+Ae.last_name:""}`,spouse_email:Ae.email||null,notes:`Spouse of ${Ae.first_name} ${Ae.last_name||""} (imported via CSV)`.trim()}).select("id").single();Ue&&(Ze=Ue.id,Oe++)}Ze&&(await q.from("innercircle_contacts").update({spouse_contact_id:Ze}).eq("id",$e),await q.from("innercircle_contacts").update({spouse_contact_id:$e}).eq("id",Ze))}}catch(Fe){console.error("Error importing contact:",Fe),Qe++}V({created:Oe,updated:Se,failed:Qe}),c("result"),(Oe>0||Se>0)&&r(),i({title:"Import Complete",description:`${Oe} created, ${Se} updated${Qe>0?`, ${Qe} failed`:""}.`})}catch(Ae){console.error("Import error:",Ae),i({title:"Import Failed",description:Ae.message||"Failed to import contacts",variant:"destructive"})}finally{$(!1)}},he=I.filter(Me=>Me.isValid).length,ge=I.filter(Me=>!Me.isValid).length,ke=I.filter(Me=>Me.isValid&&Me.isDuplicate).length,Te=he-ke;return e.jsx(zs,{open:s,onOpenChange:le,children:e.jsxs(Ds,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Qk,{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:se,className:"hidden"}),e.jsx(qa,{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(U,{onClick:()=>{var Me;return(Me=l.current)==null?void 0:Me.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(U,{variant:"outline",size:"sm",onClick:()=>{const Me=`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`,Oe=new Blob([Me],{type:"text/csv"}),Se=URL.createObjectURL(Oe),Qe=document.createElement("a");Qe.href=Se,Qe.download="contact_import_template.csv",Qe.click(),URL.revokeObjectURL(Se)},children:[e.jsx(pi,{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(te,{className:"text-base font-medium",children:"Map CSV Columns to Contact Fields"}),e.jsx("div",{className:"grid gap-3",children:sIn.map(Me=>e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(te,{className:"w-40 text-sm",children:[Me.label,Me.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(Ns,{value:p[Me.key]||"none",onValueChange:Oe=>ne(Me.key,Oe),children:[e.jsx(ws,{className:"w-48",children:e.jsx(ks,{placeholder:"Select column..."})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"-- Not mapped --"}),d.map(Oe=>e.jsx(et,{value:Oe,children:Oe},Oe))]})]})]},Me.key))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(te,{className:"text-base font-medium",children:"Apply Relationship Types (optional)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(Me=>e.jsx(Be,{variant:x.includes(Me.id)?"default":"outline",className:"cursor-pointer",onClick:()=>ie(Me.id),children:Me.name},Me.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(te,{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(Me=>{const Oe=N.includes(Me.id);return e.jsxs(Be,{variant:Oe?"default":"outline",className:"cursor-pointer gap-1",style:Oe&&Me.color?{backgroundColor:Me.color,borderColor:Me.color}:void 0,onClick:()=>K(Me.id),children:[Me.name,Oe&&e.jsx(er,{className:"h-3 w-3"})]},Me.id)})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{placeholder:"Create a new tag (e.g. Open House Oct 2026)",value:A,onChange:Me=>T(Me.target.value),onKeyDown:Me=>{Me.key==="Enter"&&(Me.preventDefault(),Z())},className:"max-w-xs"}),e.jsxs(U,{type:"button",variant:"outline",size:"sm",onClick:Z,disabled:!A.trim()||L,children:[L?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(an,{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(zr,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{children:[Te," new"]})]}),ke>0&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Vo,{className:"h-4 w-4"}),e.jsxs("span",{children:[ke," existing (will merge gaps)"]})]}),ge>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Vo,{className:"h-4 w-4"}),e.jsxs("span",{children:[ge," invalid"]})]})]}),ke>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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{className:"bg-muted/30",children:[e.jsx(Lt,{children:"First Name"}),e.jsx(Lt,{children:"Last Name"}),e.jsx(Lt,{children:"Email"}),e.jsx(Lt,{children:"Phone"}),e.jsx(Lt,{children:"Status"})]})}),e.jsx(Xa,{children:I.slice(0,100).map((Me,Oe)=>e.jsxs(gn,{children:[e.jsx(gt,{children:Me.first_name}),e.jsx(gt,{children:Me.last_name}),e.jsx(gt,{children:Me.email}),e.jsx(gt,{children:Me.phone}),e.jsx(gt,{children:Me.isValid?Me.isDuplicate?e.jsx(Be,{variant:"outline",className:"bg-accent text-accent-foreground",children:"Merge"}):e.jsx(Be,{variant:"secondary",className:"bg-primary/10 text-primary",children:"New"}):e.jsx(Be,{variant:"destructive",children:Me.error||"Invalid"})})]},Oe))})]}),I.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",I.length," contacts"]})]})]}),o==="result"&&H&&e.jsxs("div",{className:"space-y-4 py-4 text-center",children:[e.jsx(zr,{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:[H.created," created, ",H.updated," merged"]}),H.failed>0&&e.jsxs("p",{className:"text-destructive",children:[H.failed," failed to import"]})]}),e.jsxs(Mr,{children:[o==="upload"&&e.jsx(U,{variant:"outline",onClick:le,children:"Cancel"}),o==="mapping"&&e.jsxs(e.Fragment,{children:[e.jsx(U,{variant:"outline",onClick:Q,children:"Back"}),e.jsx(U,{onClick:ce,disabled:!p.first_name,children:"Continue"})]}),o==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(U,{variant:"outline",onClick:()=>c("mapping"),children:"Back"}),e.jsx(U,{onClick:be,disabled:z||he===0,children:z?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${he} Contact${he!==1?"s":""}`})]}),o==="result"&&e.jsx(U,{onClick:le,children:"Done"})]})]})})};function rIn(){return"contacts"in navigator&&"ContactsManager"in window}function aIn(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 p=h.substring(h.indexOf(":")+1).split(";");l=(p[0]||"").trim(),i=(p[1]||"").trim()}if((h.startsWith("FN:")||h.startsWith("FN;"))&&!i){const p=h.substring(h.indexOf(":")+1).trim().split(" ");i=p[0]||"",l=p.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(f=>f.trim()).filter(Boolean).join(", "))}(i||l)&&t.push({first_name:i,last_name:l,email:o,phone:c,address:d})}return t}function iIn({open:s,onOpenChange:t,onComplete:n}){vs();const{data:r}=Cb(),a=ePe(),i=j.useRef(null),[l,o]=j.useState("choose"),[c,d]=j.useState([]),[u,h]=j.useState(new Set),[m,p]=j.useState(0),[f,x]=j.useState(0),y=rIn(),v=j.useCallback(R=>{if(!r)return R;const z=new Set(r.filter(H=>H.email).map(H=>H.email.toLowerCase())),$=new Set(r.filter(H=>H.phone).map(H=>H.phone.replace(/\D/g,"")));return R.map(H=>{var Z,Q;const V=(Z=H.email)==null?void 0:Z.toLowerCase(),K=(Q=H.phone)==null?void 0:Q.replace(/\D/g,"");return V&&z.has(V)?{...H,isDuplicate:!0,duplicateField:"email"}:K&&K.length>=7&&$.has(K)?{...H,isDuplicate:!0,duplicateField:"phone"}:H})},[r]),b=async()=>{try{const R=["name","email","tel","address"],z=await navigator.contacts.select(R,{multiple:!0});if(!z||z.length===0)return;const $=z.map(K=>{var le,ue,se,ne;const Q=(((le=K.name)==null?void 0:le[0])||"").split(" ");return{first_name:Q[0]||"",last_name:Q.slice(1).join(" "),email:((ue=K.email)==null?void 0:ue[0])||"",phone:((se=K.tel)==null?void 0:se[0])||"",address:(ne=K.address)!=null&&ne[0]?[K.address[0].streetAddress,K.address[0].city,K.address[0].region,K.address[0].postalCode].filter(Boolean).join(", "):""}}),H=v($);d(H);const V=new Set;H.forEach((K,Z)=>{K.isDuplicate||V.add(Z)}),h(V),o("preview")}catch(R){console.error("Contact Picker error:",R),ka({title:"Could not access contacts",description:"Please try the file upload option instead.",variant:"destructive"})}},N=R=>{var H;const z=(H=R.target.files)==null?void 0:H[0];if(!z)return;const $=new FileReader;$.onload=V=>{var ue;const K=(ue=V.target)==null?void 0:ue.result,Z=aIn(K);if(Z.length===0){ka({title:"No contacts found",description:"The file didn't contain any valid contacts.",variant:"destructive"});return}const Q=v(Z);d(Q);const le=new Set;Q.forEach((se,ne)=>{se.isDuplicate||le.add(ne)}),h(le),o("preview")},$.readAsText(z),i.current&&(i.current.value="")},S=async()=>{const R=c.filter(($,H)=>u.has(H));if(R.length===0)return;o("importing");let z=0;for(const $ of R)try{await a.mutateAsync({first_name:$.first_name,last_name:$.last_name||void 0,email:$.email||void 0,phone:$.phone||void 0,address:$.address||void 0}),z++,x(Math.round(z/R.length*100))}catch(H){console.error(`Failed to import ${$.first_name} ${$.last_name}:`,H)}p(z),o("done")},A=R=>{h(z=>{const $=new Set(z);return $.has(R)?$.delete(R):$.add(R),$})},T=()=>{u.size===c.length?h(new Set):h(new Set(c.map((R,z)=>z)))},L=R=>{R||(o("choose"),d([]),h(new Set),p(0),x(0),l==="done"&&n()),t(R)},M=c.filter(R=>R.isDuplicate).length,I=u.size;return e.jsx(zs,{open:s,onOpenChange:L,children:e.jsxs(Ds,{className:"sm:max-w-lg max-h-[90vh]",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(i1,{className:"h-5 w-5 text-primary"}),l==="choose"&&"Import Phone Contacts",l==="preview"&&"Select Contacts to Import",l==="importing"&&"Importing Contacts...",l==="done"&&"Import Complete"]}),l==="choose"&&e.jsx(Pr,{children:"Add contacts from your phone directly into Agent OS."})]}),l==="choose"&&e.jsxs("div",{className:"space-y-4 pt-2",children:[y&&e.jsxs(U,{onClick:b,className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(i1,{className:"h-6 w-6"}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold",children:"Select from Phone"}),e.jsx("div",{className:"text-xs opacity-80",children:"Pick contacts directly from your device"})]})]}),e.jsxs("div",{className:"relative",children:[y&&e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),y&&e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-background px-2 text-muted-foreground",children:"or"})})]}),e.jsxs(U,{variant:y?"outline":"default",onClick:()=>{var R;return(R=i.current)==null?void 0:R.click()},className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(qa,{className:"h-6 w-6"}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold",children:"Upload Contact File"}),e.jsx("div",{className:"text-xs opacity-80",children:y?"Import a .vcf file exported from your Contacts app":"Export contacts from your phone as a .vcf file, then upload here"})]})]}),e.jsx("input",{ref:i,type:"file",accept:".vcf,.vcard",onChange:N,className:"hidden"}),!y&&e.jsxs("div",{className:"rounded-lg bg-muted p-3 text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{className:"font-medium",children:"How to export contacts:"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-xs",children:"iPhone:"}),e.jsx("p",{className:"text-xs",children:'Open Contacts → select contacts → Share → choose "Export vCard"'})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-xs",children:"Android:"}),e.jsx("p",{className:"text-xs",children:"Open Contacts → Menu → Export → save as .vcf file"})]})]})]}),l==="preview"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{children:[c.length," contact",c.length!==1?"s":""," found",M>0&&e.jsxs("span",{className:"text-amber-600 ml-1",children:["(",M," already exist)"]})]}),e.jsx(U,{variant:"ghost",size:"sm",onClick:T,children:u.size===c.length?"Deselect All":"Select All"})]}),e.jsx(Gi,{className:"h-[350px] rounded-md border",children:e.jsx("div",{className:"divide-y",children:c.map((R,z)=>e.jsxs("div",{className:`flex items-start gap-3 p-3 cursor-pointer hover:bg-accent/50 transition-colors ${R.isDuplicate?"opacity-60":""}`,onClick:()=>A(z),children:[e.jsx(xi,{checked:u.has(z),onCheckedChange:()=>A(z),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:[R.first_name," ",R.last_name]}),R.isDuplicate&&e.jsxs(Be,{variant:"secondary",className:"text-[10px] px-1.5 py-0 bg-amber-500/10 text-amber-600 border-amber-200",children:["Exists (",R.duplicateField,")"]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5 mt-0.5",children:[R.phone&&e.jsx("div",{children:R.phone}),R.email&&e.jsx("div",{className:"truncate",children:R.email})]})]})]},z))})}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>o("choose"),children:"Back"}),e.jsxs(U,{onClick:S,disabled:I===0,children:["Import ",I," Contact",I!==1?"s":""]})]})]}),l==="importing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx(Et,{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:[f,"% 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:`${f}%`}})})]}),l==="done"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-emerald-500/10 flex items-center justify-center",children:e.jsx(Xr,{className:"h-6 w-6 text-emerald-600"})}),e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"font-semibold text-lg",children:[m," contact",m!==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(U,{onClick:()=>L(!1),className:"mt-2",children:"Done"})]})]})})}function oIn(s){return ct({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 lIn(){const{user:s}=vs();return ct({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 cIn(){const{user:s}=vs();return ct({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 QGt(){const{user:s}=vs(),t=Qt();return yt({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 JGt(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=open`}function eWt(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=click`}const dIn=100;function uIn({open:s,onOpenChange:t,contacts:n,isGmailConnected:r,isMassEmailReady:a,onSendComplete:i}){const l=Wn(),o=Sa(),c=QGt(),[d,u]=j.useState([]),[h,m]=j.useState(!1),[p,f]=j.useState(""),[x,y]=j.useState(null),[v,b]=j.useState(""),[N,S]=j.useState(""),[A,T]=j.useState(!1),[L,M]=j.useState({done:0,total:0,failed:0}),I=n.filter(Q=>!!Q.email),R=n.length-I.length,z=I.length>dIn;j.useEffect(()=>{s&&(y(null),f(""),M({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:Q})=>{u(Q||[]),m(!1)}))},[s,o]),j.useEffect(()=>{if(!x)return;const Q=x.title||"a quick video";b(`I recorded a video for you — ${Q}`),S("Hey {{first_name}}! I recorded a quick video just for you. Click below to watch it:")},[x]);const $=d.filter(Q=>!p||(Q.title||"").toLowerCase().includes(p.toLowerCase())),H=(Q,le)=>{if(!x)return"";const ue=x.share_token?`https://video.relevelup.com/share/video/${x.share_token}`:"",se=x.share_token?`https://video.relevelup.com/thumb/${x.share_token}`:x.thumbnail_url||"",ne=x.title||"Video Message",ce=N.replace(/\{\{first_name\}\}/gi,Q).split(/\n\n+/).map(he=>`

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

`).join(""),je=le?eWt(le):ue,be=le?``:"";return`
${ce}

▶ Watch Video

${be}
`},V=async()=>{if(!x)return;T(!0),M({done:0,total:I.length,failed:0});let Q=0,le=0;for(const ue of I)try{let se;try{se=(await c.mutateAsync({video_id:x.id,recipient_email:ue.email,recipient_name:`${ue.first_name} ${ue.last_name||""}`.trim(),contact_id:ue.id,sent_via:"gmail"})).share_token}catch(be){console.warn("Tracking record failed for",ue.email,be)}const ne=H(ue.first_name,se),ie=v.replace(/\{\{first_name\}\}/gi,ue.first_name),{data:ce,error:je}=await q.functions.invoke("gmail-send",{body:{to:ue.email,subject:ie,body:ne,contactId:ue.id}});if(je||!(ce!=null&&ce.success))throw new Error((ce==null?void 0:ce.error)||(je==null?void 0:je.message)||"Send failed");Q+=1}catch(se){console.error("Failed to send to",ue.email,se),le+=1}finally{M({done:Q+le,total:I.length,failed:le}),await new Promise(se=>setTimeout(se,250))}T(!1),le===0?re.success(`Video sent to ${Q} ${Q===1?"contact":"contacts"}!`):re.warning(`Sent to ${Q}, ${le} failed. Check console for details.`),t(!1),i==null||i()},K=()=>{if(!x)return;const Q=H("there",void 0);l("/admin/email-campaigns/new",{state:{directRecipients:I.map(le=>({email:le.email,name:`${le.first_name} ${le.last_name||""}`.trim()})),initialSubject:v,initialBodyHtml:Q}}),t(!1)},Z=!!x&&!!v.trim()&&I.length>0&&(z?a:r);return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"sm:max-w-[640px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Wr,{className:"h-5 w-5 text-primary"}),"Send Video to ",I.length," ",I.length===1?"Contact":"Contacts"]}),e.jsxs(Pr,{children:[z?e.jsxs("span",{className:"flex items-center gap-1.5 text-amber-600",children:[e.jsx(Th,{className:"h-3.5 w-3.5"}),I.length," recipients — will be sent as a Mass Email campaign"]}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ln,{className:"h-3.5 w-3.5"}),"Sent individually via your connected Gmail"]}),R>0&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",R," skipped — no email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[z&&!a&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(Vo,{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 ",I.length," recipients."]})]}),!z&&!r&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(Vo,{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(te,{children:"Choose a video"}),e.jsxs(U,{type:"button",variant:"ghost",size:"sm",className:"gap-1",onClick:()=>l("/innercircle/videos/record"),children:[e.jsx(an,{className:"h-3.5 w-3.5"})," Record new"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search your video library...",value:p,onChange:Q=>f(Q.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"})]}):$.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."}):$.map(Q=>{const le=(x==null?void 0:x.id)===Q.id;return e.jsxs("button",{type:"button",onClick:()=>y(Q),className:`w-full flex items-center gap-3 p-2 rounded-md border text-left transition-colors ${le?"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:[Q.thumbnail_url?e.jsx("img",{src:Q.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx(Gh,{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(lu,{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:Q.title||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Q.duration_seconds?`${Math.round(Q.duration_seconds)}s`:"",Q.created_at?` · ${new Date(Q.created_at).toLocaleDateString()}`:""]})]})]},Q.id)})})]}),e.jsx(hc,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"bulk-video-subject",children:"Subject"}),e.jsx(xe,{id:"bulk-video-subject",value:v,onChange:Q=>b(Q.target.value),placeholder:"I recorded a video for you"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(te,{htmlFor:"bulk-video-message",children:["Personal message ",e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(use ","{{first_name}}"," to personalize)"]})]}),e.jsx(Fs,{id:"bulk-video-message",value:N,onChange:Q=>S(Q.target.value),rows:4,className:"resize-y"})]}),A&&L.total>0&&e.jsxs("div",{className:"p-3 rounded-md bg-muted text-sm",children:["Sending… ",L.done," / ",L.total,L.failed>0&&e.jsxs("span",{className:"text-destructive ml-2",children:["(",L.failed," failed)"]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),disabled:A,children:"Cancel"}),z?e.jsxs(U,{onClick:K,disabled:!Z,className:"gap-2",children:[e.jsx(Th,{className:"h-4 w-4"}),"Continue in Mass Email"]}):e.jsxs(U,{onClick:V,disabled:!Z||A,className:"gap-2",children:[A?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx($r,{className:"h-4 w-4"}),A?"Sending…":`Send to ${I.length}`]})]})]})]})})}function Fre(){const s=Sa();return ct({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 hIn(s){return ct({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 mIn(){const s=Sa(),t=Qt();return yt({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 tWt(){const s=Qt();return yt({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 pIn(){const s=Qt();return yt({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 Xtt(){const s=Sa(),t=Qt();return yt({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 sWt(s){return ct({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 fIn(){const s=Qt();return yt({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 gIn(){const s=Qt();return yt({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 xIn(){const s=Qt();return yt({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 yIn(s){return ct({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 vIn(s){return ct({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 Qtt(){const s=Qt();return yt({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 bIn(){const s=Qt();return yt({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 _In=[{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"}],$Le={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"},wIn={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 jIn({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,p]=j.useState("desktop"),[f,x]=j.useState(""),[y,v]=j.useState(!1);j.useEffect(()=>{if(!s)return;let N=!1;return(async()=>{var S,A;o(!0);try{const{data:T}=await q.auth.getSession();f||x(((A=(S=T==null?void 0:T.session)==null?void 0:S.user)==null?void 0:A.email)||"");const{data:L,error:M}=await q.functions.invoke("process-drip-campaigns",{body:{action:"preview",subject:n,body:r,owner_user_id:a||void 0}});if(M)throw M;if(N)return;d((L==null?void 0:L.html)||""),h((L==null?void 0:L.subject)||n)}catch{N||re.error("Could not build preview")}finally{N||o(!1)}})(),()=>{N=!0}},[s,n,r,a]);const b=async()=>{if(f.trim()){v(!0);try{const{data:N,error:S}=await q.functions.invoke("process-drip-campaigns",{body:{action:"test_send",subject:n,body:r,to:f.trim(),owner_user_id:a||void 0}});if(S)throw S;N!=null&&N.success?re.success(`Test email sent to ${f.trim()}`):re.error((N==null?void 0:N.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(Ds,{className:"sm:max-w-3xl max-h-[92vh] flex flex-col p-0 gap-0",children:[e.jsxs(Vs,{className:"p-5 pb-3 border-b shrink-0",children:[e.jsxs($s,{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(U,{variant:m==="desktop"?"secondary":"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>p("desktop"),children:[e.jsx(X2,{className:"h-3.5 w-3.5 mr-1"})," Desktop"]}),e.jsxs(U,{variant:m==="mobile"?"secondary":"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>p("mobile"),children:[e.jsx(i1,{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(Et,{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(te,{className:"text-xs",children:"Send a test to"}),e.jsx(xe,{type:"email",value:f,onChange:N=>x(N.target.value),placeholder:"you@email.com",className:"h-9",onKeyDown:N=>N.key==="Enter"&&b()})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(U,{onClick:b,disabled:y||!f.trim(),children:[y?e.jsx(Et,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx($r,{className:"h-4 w-4 mr-1.5"}),"Send test"]})]})]})]})})}function T9({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),[p,f]=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=>!p||(y.title||y.recipient_name||"").toLowerCase().includes(p.toLowerCase()));return e.jsxs(zs,{open:o,onOpenChange:c,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{variant:i,size:a,className:l||"gap-1.5 shrink-0",children:[e.jsx(Gh,{className:"h-3.5 w-3.5"}),r]})}),e.jsxs(Ds,{className:"max-w-lg max-h-[70vh] flex flex-col",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Select from Video Library"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose a video from your library"})]}),e.jsxs("div",{className:"relative mb-3",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search videos...",value:p,onChange:y=>f(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 N=document.createElement("span");N.innerHTML="🎬",N.className="text-lg",b.appendChild(N)}}}):e.jsx(Wr,{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 NIn(){return ct({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 kIn(s){return ct({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 SIn(){const{user:s}=vs();return ct({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 CIn(){const{user:s}=vs(),t=Qt();return yt({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 AIn(s){const{user:t}=vs();return ct({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 EIn(s){return ct({queryKey:["agent-video",s],queryFn:async()=>{const{data:t,error:n}=await q.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function f3(){const{user:s}=vs(),t=Qt();return yt({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 TIn(){const s=Qt();return yt({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 MIn(){const s=Qt();return yt({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 VLe(){const{user:s}=vs();return ct({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 nWt(){const{data:s,isLoading:t}=VLe(),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 cL(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 dL(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 fN(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 PIn(){const{user:s}=vs(),t=Qt();return yt({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 rWt({open:s,onOpenChange:t,onUploadComplete:n}){const{data:r}=Cb(),{data:a}=VLe(),i=f3(),l=j.useRef(null),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,f]=j.useState(""),[x,y]=j.useState(!1),[v,b]=j.useState(0),[N,S]=j.useState("idle"),A=(a==null?void 0:a.total_storage_mb)||0,L=((a==null?void 0:a.max_storage_mb)||1024)-A,M=$=>{var K;const H=(K=$.target.files)==null?void 0:K[0];if(!H)return;if(!H.type.startsWith("video/")){re.error("Please select a video file");return}const V=H.size/(1024*1024);if(V>500){re.error("Video file must be less than 500MB");return}if(V>L){re.error(`Not enough storage. You have ${L.toFixed(1)} MB remaining.`);return}c(H),d||u(H.name.replace(/\.[^/.]+$/,""))},I=async()=>{if(!o){re.error("Please select a video file");return}y(!0),b(0),S("creating");try{const{data:$,error:H}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:d||o.name,isAgentVideo:!0}});if(H)throw new Error(H.message);const{videoId:V,libraryId:K}=$;S("uploading");const{data:Z,error:Q}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:V,isAgentVideo:!0}});if(Q)throw new Error(Q.message);await new Promise((se,ne)=>{const ie=new XMLHttpRequest;ie.upload.addEventListener("progress",ce=>{if(ce.lengthComputable){const je=Math.round(ce.loaded/ce.total*100);b(je)}}),ie.addEventListener("load",()=>{ie.status>=200&&ie.status<300?se():ne(new Error(`Upload failed with status ${ie.status}`))}),ie.addEventListener("error",()=>ne(new Error("Upload failed"))),ie.open("PUT",Z.uploadUrl),ie.setRequestHeader("AccessKey",Z.apiKey),ie.send(o)}),S("processing");const le=o.size/(1024*1024),ue=`https://iframe.mediadelivery.net/embed/${K}/${V}`;await i.mutateAsync({bunny_video_id:V,playback_url:ue,file_size_mb:le,title:d||o.name,notes:h||void 0,contact_id:p||void 0,status:"processing",touch_type:"video_upload"}),re.success("Video uploaded successfully! Processing may take a few minutes."),n==null||n(ue),R()}catch($){console.error("Upload error:",$),re.error($ instanceof Error?$.message:"Failed to upload video")}finally{y(!1),S("idle")}},R=()=>{x||(c(null),u(""),m(""),f(""),b(0),S("idle"),t(!1))},z=()=>{switch(N){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${v}%`;case"processing":return"Saving video...";default:return""}};return e.jsx(zs,{open:s,onOpenChange:R,children:e.jsxs(Ds,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{children:"Video File"}),o?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(Wr,{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(U,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:$=>{$.stopPropagation(),c(null)},children:e.jsx(er,{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 $;return($=l.current)==null?void 0:$.click()},children:[e.jsx(qa,{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:M,disabled:x})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"title",children:"Title"}),e.jsx(xe,{id:"title",value:d,onChange:$=>u($.target.value),placeholder:"Enter video title",disabled:x})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Associate with Contact (optional)"}),e.jsxs(Ns,{value:p||"__none__",onValueChange:$=>f($==="__none__"?"":$),disabled:x,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select a contact"})}),e.jsxs(js,{children:[e.jsx(et,{value:"__none__",children:"No contact"}),r==null?void 0:r.map($=>e.jsxs(et,{value:$.id,children:[$.first_name," ",$.last_name||""]},$.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"notes",children:"Notes (optional)"}),e.jsx(Fs,{id:"notes",value:h,onChange:$=>m($.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(Et,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:z()})]}),e.jsx(ro,{value:N==="uploading"?v:N==="processing"?100:10})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:R,disabled:x,children:"Cancel"}),e.jsx(U,{onClick:I,disabled:!o||x,children:x?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qa,{className:"h-4 w-4 mr-2"}),"Upload Video"]})})]})]})})}const LIn=["🌱","💎","🏠","🔑","📧","💌","🎂","🥂","🤝","⭐","🎉","📞"],IIn={" ":" ","&":"&","<":"<",">":">",""":'"',"'":"'"},jwt=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=>IIn[t.toLowerCase()]||t).replace(/\n{3,}/g,` `).replace(/[ \t]+\n/g,` `).trim():s:"";function aWt({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}=hIn(o||void 0),{data:u,isLoading:h}=sWt(o||void 0),m=mIn(),p=tWt(),f=fIn(),[x,y]=j.useState(""),[v,b]=j.useState(""),[N,S]=j.useState("nurture"),[A,T]=j.useState("🌱"),[L,M]=j.useState("");j.useEffect(()=>{d?(y(d.name),b(d.description||""),S(d.category),T(d.icon),M(d.goal||"")):c||(y(""),b(""),S("nurture"),T("🌱"),M(""))},[d,c,s]);const I=wIn[N],R=async()=>{if(!x.trim()){re.error("Give your campaign a name");return}try{if(c&&o)await p.mutateAsync({id:o,name:x,description:v,category:N,icon:A,goal:L,cover_color:I}),re.success("Campaign updated");else{const $=await m.mutateAsync({name:x,description:v,category:N,icon:A,goal:L,cover_color:I});return re.success("Campaign created — now add your first step!"),a($.id),l("steps"),$}}catch($){re.error($.message||"Failed to save")}},z=async()=>{if(!o){re.error("Save the campaign first, then add steps");return}const $=((u==null?void 0:u.length)||0)+1;try{await f.mutateAsync({campaign_id:o,step_order:$,channel:"email",subject:"",body:"",delay_type:"relative",delay_days:$===1?0:2,delay_hours:0})}catch{re.error("Failed to add step")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-3xl max-h-[90vh] flex flex-col p-0 overflow-hidden",children:[e.jsx("div",{className:`bg-gradient-to-br ${I} p-5 text-white shrink-0`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-4xl drop-shadow-sm",children:A}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx($s,{className:"text-lg font-bold text-white",children:c?"Edit Campaign":"Create New Campaign"}),e.jsx(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(oa,{value:i,onValueChange:$=>l($),className:"flex-1 flex flex-col overflow-hidden min-h-0",children:[e.jsxs(la,{className:"mx-5 mt-4 grid grid-cols-2 w-fit",children:[e.jsx(Kt,{value:"details",children:"Details"}),e.jsxs(Kt,{value:"steps",disabled:!c,children:["Steps ",u&&u.length>0&&e.jsx(Be,{variant:"secondary",className:"ml-1.5 text-[10px]",children:u.length})]})]}),e.jsx(Zt,{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(te,{className:"text-xs",children:"Campaign Name *"}),e.jsx(xe,{value:x,onChange:$=>y($.target.value),placeholder:"e.g. New Buyer Lead — 7 Touch Nurture",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Description"}),e.jsx(Fs,{value:v,onChange:$=>b($.target.value),placeholder:"What's this campaign for? When should you use it?",rows:2,className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Goal (optional)"}),e.jsx(xe,{value:L,onChange:$=>M($.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(te,{className:"text-xs",children:"Category"}),e.jsxs(Ns,{value:N,onValueChange:$=>S($),children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{})}),e.jsx(js,{children:Object.entries($Le).map(([$,H])=>e.jsx(et,{value:$,children:H},$))})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Icon"}),e.jsx("div",{className:"flex gap-1.5 flex-wrap mt-1",children:LIn.map($=>e.jsx("button",{type:"button",onClick:()=>T($),className:`h-8 w-8 rounded-md text-lg flex items-center justify-center transition-all ${A===$?"bg-primary/15 ring-2 ring-primary":"hover:bg-muted"}`,children:$},$))})]})]}),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(Zt,{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(cn,{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(U,{size:"sm",onClick:z,disabled:f.isPending,children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1.5"})," Add first step"]})]}):e.jsxs(e.Fragment,{children:[u.map(($,H)=>e.jsx(RIn,{step:$,index:H,totalSteps:u.length},$.id)),e.jsxs(U,{variant:"outline",size:"sm",onClick:z,disabled:f.isPending,className:"w-full",children:[f.isPending?e.jsx(Et,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(an,{className:"h-3.5 w-3.5 mr-1.5"}),"Add another step"]})]})})})})]}),e.jsxs(Mr,{className:"border-t p-4 shrink-0",children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:c?"Done":"Cancel"}),e.jsxs(U,{onClick:R,disabled:m.isPending||p.isPending,children:[(m.isPending||p.isPending)&&e.jsx(Et,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),c?"Save Changes":"Create Campaign"]})]})]})})}function RIn({step:s,index:t,totalSteps:n}){const r=gIn(),a=xIn(),i=Sa(),[l,o]=j.useState(!1),[c,d]=j.useState(()=>({...s,body:jwt(s.body)})),[u,h]=j.useState(!1),[m,p]=j.useState(!1),[f,x]=j.useState(""),[y,v]=j.useState(!1),[b,N]=j.useState(!1);j.useEffect(()=>{d({...s,body:jwt(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)}},T=async()=>{if(await Yi(`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")}},L=I=>{d({...c,body:c.body+I})},M=()=>{if(c.delay_type==="calendar_anchor"){const R=c.anchor_field==="birthday"?"birthday":"home anniversary",z=c.anchor_offset_days||0;return z===0?`On their ${R}`:z<0?`${Math.abs(z)}d before ${R}`:`${z}d after ${R}`}if(t===0&&!c.delay_days&&!c.delay_hours)return"Sends immediately";const I=[];return c.delay_days&&I.push(`${c.delay_days}d`),c.delay_hours&&I.push(`${c.delay_hours}h`),t===0?`After ${I.join(" ")||"0"}`:`+${I.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(pa,{className:"h-3 w-3"}):e.jsx(Yr,{className:"h-3 w-3"}),e.jsx("span",{children:M()}),e.jsx("span",{children:"·"}),c.channel==="email"?e.jsx(ln,{className:"h-3 w-3"}):e.jsx(Ki,{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(dv,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(rl,{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(te,{className:"text-xs",children:"Channel"}),e.jsxs(Ns,{value:c.channel,onValueChange:I=>d({...c,channel:I}),children:[e.jsx(ws,{className:"mt-1 h-9",children:e.jsx(ks,{})}),e.jsx(js,{children:e.jsx(et,{value:"email",children:"📧 Email"})})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Timing Type"}),e.jsxs(Ns,{value:c.delay_type,onValueChange:I=>d({...c,delay_type:I}),children:[e.jsx(ws,{className:"mt-1 h-9",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"relative",children:"⏱ Relative delay"}),e.jsx(et,{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(te,{className:"text-xs",children:"Days delay"}),e.jsx(xe,{type:"number",min:0,value:c.delay_days,onChange:I=>d({...c,delay_days:parseInt(I.target.value)||0}),className:"mt-1 h-9"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Hours delay"}),e.jsx(xe,{type:"number",min:0,max:23,value:c.delay_hours,onChange:I=>d({...c,delay_hours:parseInt(I.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(te,{className:"text-xs",children:"Anchor"}),e.jsxs(Ns,{value:c.anchor_field||"birthday",onValueChange:I=>d({...c,anchor_field:I}),children:[e.jsx(ws,{className:"mt-1 h-9",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"birthday",children:"🎂 Birthday"}),e.jsx(et,{value:"home_anniversary",children:"🏠 Home Anniversary"})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Offset (days, negative = before)"}),e.jsx(xe,{type:"number",value:c.anchor_offset_days||0,onChange:I=>d({...c,anchor_offset_days:parseInt(I.target.value)||0}),className:"mt-1 h-9",placeholder:"0 = on the day, -7 = week before"})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Subject Line"}),e.jsx(xe,{value:c.subject,onChange:I=>d({...c,subject:I.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(te,{className:"text-xs",children:"Email Body"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[c.body.length," chars"]})]}),e.jsx(Fs,{value:c.body,onChange:I=>d({...c,body:I.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:"}),_In.map(I=>e.jsx("button",{type:"button",onClick:()=>L(I.key),className:"text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary hover:bg-primary/20",children:I.label},I.key))]})]}),e.jsxs("div",{children:[e.jsx(te,{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(Wr,{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(U,{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(T9,{userId:i||void 0,onSelect:I=>d({...c,video_url:I}),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1 min-w-[120px]"}),e.jsxs(U,{variant:"outline",size:"sm",className:"gap-1 text-xs flex-1 min-w-[120px]",onClick:()=>v(!0),children:[e.jsx(qa,{className:"h-3 w-3"})," Upload"]}),e.jsxs(U,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1 min-w-[120px]",onClick:()=>{x(""),p(!0)},children:[e.jsx(Rc,{className:"h-3 w-3"})," Paste URL"]}),e.jsx(rWt,{open:y,onOpenChange:v,onUploadComplete:I=>d({...c,video_url:I})}),e.jsx(zs,{open:m,onOpenChange:p,children:e.jsxs(Ds,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Add video URL"}),e.jsx(Pr,{children:"Paste a YouTube, Loom, or direct video URL."})]}),e.jsx(xe,{value:f,onChange:I=>x(I.target.value),placeholder:"https://...",autoFocus:!0,onKeyDown:I=>{I.key==="Enter"&&f.trim()&&(d({...c,video_url:f.trim()}),p(!1))}}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"ghost",onClick:()=>p(!1),children:"Cancel"}),e.jsx(U,{disabled:!f.trim(),onClick:()=>{d({...c,video_url:f.trim()}),p(!1)},children:"Add video"})]})]})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(U,{variant:"ghost",size:"sm",onClick:T,className:"text-destructive hover:text-destructive",children:[e.jsx(In,{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(U,{variant:"outline",size:"sm",onClick:()=>N(!0),children:[e.jsx(xa,{className:"h-3.5 w-3.5 mr-1.5"})," Preview"]}),e.jsxs(U,{size:"sm",onClick:A,disabled:!S||u,children:[u&&e.jsx(Et,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save step"]})]})]}),e.jsx(jIn,{open:b,onOpenChange:N,subject:c.subject||"",body:c.body||"",ownerUserId:i,stepLabel:`Step ${t+1}`})]})]})}function DIn({open:s,onOpenChange:t,contactIds:n,onSuccess:r}){const{data:a,isLoading:i}=Fre(),l=Qtt(),[o,c]=j.useState(""),[d,u]=j.useState(null),[h,m]=j.useState(!1),p=(a||[]).filter(y=>!y.is_starter),f=p.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(Ds,{className:"max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(cn,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search campaigns...",value:o,onChange:y=>c(y.target.value),className:"pl-9 h-9"})]}),e.jsx(Gi,{className:"h-[320px] -mx-1 px-1",children:i?e.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:"Loading..."}):f.length===0?e.jsx("div",{className:"text-center py-8",children:p.length===0?e.jsxs(e.Fragment,{children:[e.jsx(cn,{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(U,{size:"sm",onClick:()=>m(!0),children:[e.jsx(an,{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:f.map(y=>e.jsxs("button",{onClick:()=>u(y.id),className:`w-full flex items-start gap-3 p-3 rounded-lg border text-left transition-all ${d===y.id?"border-primary bg-primary/5 ring-1 ring-primary":"border-border hover:border-primary/40 hover:bg-muted/30"}`,children:[e.jsx("div",{className:`shrink-0 h-9 w-9 rounded-lg bg-gradient-to-br ${y.cover_color} flex items-center justify-center text-lg`,children:y.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:y.name}),y.is_active&&e.jsx(Be,{variant:"outline",className:"text-[9px] bg-emerald-500/10 text-emerald-600 border-emerald-200 px-1 py-0",children:"Active"})]}),y.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-0.5",children:y.description})]}),d===y.id&&e.jsx(Xr,{className:"h-4 w-4 text-primary shrink-0 mt-1"})]},y.id))})})]}),e.jsxs(Mr,{className:"gap-2 sm:gap-2",children:[p.length>0&&e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>m(!0),className:"mr-auto text-xs",children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1"})," New campaign"]}),e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{onClick:x,disabled:!d||l.isPending,children:[l.isPending&&e.jsx(Et,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Enroll ",n.length," contact",n.length!==1?"s":""]})]})]}),e.jsx(aWt,{open:h,onOpenChange:m})]})}function OIn({selectedIds:s,contacts:t,onClearSelection:n,onSendToLeadPond:r,showLeadPondAction:a,onTransfer:i,showTransferAction:l}){const o=Wn(),{data:c}=F_(),d=zQe(),u=Qt(),{isGmailConnected:h}=Ax(),{isReady:m}=AG(),{data:p}=ZG(),f=Ptt(),x=cGt(),[y,v]=j.useState(!1),[b,N]=j.useState(!1),[S,A]=j.useState(!1),[T,L]=j.useState(!1),[M,I]=j.useState(!1),[R,z]=j.useState(""),$=s.size;if($===0)return null;const H=async se=>{v(!0);try{const ie=Array.from(s).map(je=>({contact_id:je,relationship_type_id:se})),{error:ce}=await q.from("innercircle_contact_tags").upsert(ie,{onConflict:"contact_id,relationship_type_id",ignoreDuplicates:!0});if(ce)throw ce;u.invalidateQueries({queryKey:["innercircle-contacts"]}),u.invalidateQueries({queryKey:["innercircle-contact-counts"]}),ka({title:`Assigned type to ${$} contacts`}),n()}catch(ne){ka({title:"Error assigning type",description:ne.message,variant:"destructive"})}finally{v(!1)}},V=async se=>{v(!0);try{const ne=Array.from(s);for(const ie of ne)try{await x.mutateAsync({contactId:ie,tagId:se})}catch{}u.invalidateQueries({queryKey:["all-contact-custom-tags"]}),ka({title:`Tagged ${$} contacts`}),I(!1),z("")}catch(ne){ka({title:"Error adding tags",description:ne.message,variant:"destructive"})}finally{v(!1)}},K=async()=>{if(R.trim()){v(!0);try{const se=await f.mutateAsync({name:R.trim()});await V(se.id)}catch(se){ka({title:"Error creating tag",description:se.message,variant:"destructive"}),v(!1)}}},Z=(p==null?void 0:p.filter(se=>se.name.toLowerCase().includes(R.toLowerCase())))||[],Q=p==null?void 0:p.find(se=>se.name.toLowerCase()===R.trim().toLowerCase()),le=()=>{const se=t.filter(ge=>s.has(ge.id)),ne=["First Name","Last Name","Email","Phone","Street Address","City","State","ZIP","Full Address","Birthday","Home Anniversary","Notes","Relationship Types"],ie=se.map(ge=>{var Fe;const ke=ge,Te=ke.address||"",Me=ke.city||"",Oe=ke.state||"",Se=ke.zip||ke.zip_code||"",Qe=[Me,[Oe,Se].filter(Boolean).join(" ")].filter(Boolean).join(", "),Ae=[Te,Qe].filter(Boolean).join(", ");return[ge.first_name,ge.last_name||"",ge.email||"",ge.phone||"",Te,Me,Oe,Se,Ae,ge.birthday||"",ge.home_anniversary||"",ge.notes||"",((Fe=ge.tags)==null?void 0:Fe.map(Ne=>{var $e;return($e=Ne.relationship_type)==null?void 0:$e.name}).join("; "))||""]}),ce=[ne.join(","),...ie.map(ge=>ge.map(ke=>`"${(ke||"").replace(/"/g,'""')}"`).join(","))].join(` `),je=new Blob([ce],{type:"text/csv"}),be=URL.createObjectURL(je),he=document.createElement("a");he.href=be,he.download=`contacts-export-${new Date().toISOString().slice(0,10)}.csv`,he.click(),URL.revokeObjectURL(be),ka({title:`Exported ${$} contacts`})},ue=async()=>{if(await Yi(`Are you sure you want to delete ${$} contacts? This cannot be undone.`)){v(!0);try{const se=Array.from(s);for(const ne of se)await d.mutateAsync(ne);n()}catch(se){ka({title:"Error deleting contacts",description:se.message,variant:"destructive"})}finally{v(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-primary/5 border border-primary/20 rounded-lg",children:[e.jsxs(Be,{variant:"secondary",className:"font-semibold",children:[$," selected"]}),e.jsxs(Ns,{onValueChange:H,disabled:y,children:[e.jsx(ws,{className:"w-[180px] h-8",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Cf,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm",children:"Assign Type"})]})}),e.jsx(js,{children:c==null?void 0:c.filter(se=>se.active).map(se=>e.jsx(et,{value:se.id,children:se.name},se.id))})]}),e.jsxs(md,{open:M,onOpenChange:I,children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{variant:"outline",size:"sm",disabled:y,children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1"}),"Add Tag"]})}),e.jsxs(id,{className:"w-56 p-2",align:"start",children:[e.jsx(xe,{placeholder:"Search or create tag...",value:R,onChange:se=>z(se.target.value),onKeyDown:se=>{se.key==="Enter"&&R.trim()&&!Q?(se.preventDefault(),K()):se.key==="Enter"&&Q&&(se.preventDefault(),V(Q.id))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[Z.map(se=>e.jsxs("button",{onClick:()=>V(se.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:se.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:se.name})]},se.id)),R.trim()&&!Q&&e.jsxs("button",{onClick:K,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(an,{className:"h-3.5 w-3.5"}),'Create "',R.trim(),'"']}),Z.length===0&&!R.trim()&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Type to create a tag"})]})]})]}),h&&e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>N(!0),disabled:y,children:[e.jsx(ln,{className:"h-3.5 w-3.5 mr-1"}),"Email"]}),m&&e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>{const se=Array.from(s).join(",");o(`/admin/email-campaigns/new?contactIds=${se}`)},disabled:y,children:[e.jsx(Th,{className:"h-3.5 w-3.5 mr-1"}),"Mass Email"]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>A(!0),disabled:y,children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1"}),"Send Video"]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>L(!0),disabled:y,children:[e.jsx(cn,{className:"h-3.5 w-3.5 mr-1"}),"Enroll in Campaign"]}),a&&r&&e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>r(Array.from(s)),disabled:y,children:[e.jsx(cb,{className:"h-3.5 w-3.5 mr-1"}),"Send to Lead Pond"]}),l&&i&&e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>i(Array.from(s)),disabled:y,children:[e.jsx(S4,{className:"h-3.5 w-3.5 mr-1"}),"Transfer"]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:le,disabled:y,children:[e.jsx(pi,{className:"h-3.5 w-3.5 mr-1"}),"Export"]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:ue,disabled:y,className:"text-destructive hover:text-destructive",children:[e.jsx(In,{className:"h-3.5 w-3.5 mr-1"}),"Delete"]}),e.jsxs(U,{variant:"ghost",size:"sm",onClick:n,className:"ml-auto",children:[e.jsx(er,{className:"h-3.5 w-3.5 mr-1"}),"Clear"]})]}),e.jsx(DIn,{open:T,onOpenChange:L,contactIds:Array.from(s),onSuccess:n}),e.jsx(wS,{open:b,onOpenChange:N,bulkContacts:Array.from(s).map(se=>{const ne=t.find(ie=>ie.id===se);return ne?{id:ne.id,first_name:ne.first_name,last_name:ne.last_name,email:ne.email||""}:null}).filter(se=>se!==null&&se.email!==""),onSendComplete:()=>{N(!1),n()}}),e.jsx(uIn,{open:S,onOpenChange:A,contacts:Array.from(s).map(se=>t.find(ne=>ne.id===se)).filter(se=>!!se).map(se=>({id:se.id,first_name:se.first_name,last_name:se.last_name,email:se.email})),isGmailConnected:!!h,isMassEmailReady:!!m,onSendComplete:()=>{A(!1),n()}})]})}function Nwt({contact:s,onEdit:t,onDelete:n,onSnooze:r,onSendToLeadPond:a,showLeadPondAction:i,onTransfer:l,showTransferAction:o}){const c=Wn(),{isReady:d}=AG(),u=`${s.first_name} ${s.last_name||""}`.trim();return e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:h=>h.stopPropagation(),children:e.jsx(Z1,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",onClick:h=>h.stopPropagation(),children:[e.jsxs(La,{onClick:()=>c(`/mission-control/contacts/${s.id}?tab=activity&action=log`),children:[e.jsx(ba,{className:"h-4 w-4 mr-2"}),"Log Touch"]}),e.jsxs(La,{onClick:()=>c(`/mission-control/video?contactId=${s.id}`),children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Send Video"]}),e.jsxs(La,{onClick:()=>c(`/mission-control/popbys?contactId=${s.id}`),children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Schedule Pop-by"]}),d&&s.email&&e.jsxs(La,{onClick:()=>c(`/admin/email-campaigns/new?contactIds=${s.id}`),children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Mass Email"]}),e.jsxs(La,{onClick:()=>r(s.id,u),children:[e.jsx(uv,{className:"h-4 w-4 mr-2"}),"Snooze"]}),i&&a&&e.jsxs(La,{onClick:()=>a(s.id),children:[e.jsx(cb,{className:"h-4 w-4 mr-2"}),"Send to Lead Pond"]}),o&&l&&e.jsxs(La,{onClick:()=>l(s.id),children:[e.jsx(S4,{className:"h-4 w-4 mr-2"}),"Transfer to Team Member"]}),e.jsxs(La,{onClick:()=>t(s),children:[e.jsx(ri,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(La,{onClick:()=>n(s.id),className:"text-destructive focus:text-destructive",children:[e.jsx(In,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})}function kwt({currentFilters:s,currentSortBy:t,onApplySmartList:n}){const{data:r}=Ltt(),a=dGt(),i=uGt(),[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(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsxs(U,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(K2,{className:"h-3.5 w-3.5"}),"Smart Filters",r&&r.length>0&&e.jsx(Be,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:r.length}),e.jsx(rl,{className:"h-3.5 w-3.5"})]})}),e.jsxs(Eu,{align:"start",className:"w-56",children:[r&&r.length>0?e.jsxs(e.Fragment,{children:[r.map(m=>e.jsxs(La,{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(U,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:p=>{p.stopPropagation(),i.mutate(m.id)},children:e.jsx(In,{className:"h-3 w-3 text-destructive"})})]},m.id)),e.jsx(l1,{})]}):e.jsx(La,{disabled:!0,className:"text-muted-foreground text-xs",children:"No saved filters yet"}),u&&e.jsxs(La,{onClick:()=>o(!0),children:[e.jsx(NM,{className:"h-4 w-4 mr-2"}),"Save Current Filter"]})]})]}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Ds,{className:"max-w-sm",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Save Smart Filter"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(xe,{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(U,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(U,{onClick:h,disabled:!c.trim()||a.isPending,children:"Save"})]})]})]})})]})}const DEe=[{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"}],iWt=[{value:"home_anniversary",label:"Home anniversary"},{value:"wedding_anniversary",label:"Wedding anniversary"}],FIn=[{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 zIn({open:s,onOpenChange:t,hasLeadSite:n,behavior:r,onApply:a,selectedType:i,onSelectedTypeChange:l,relationshipTypes:o}){const[c,d]=j.useState(r),[u,h]=j.useState(n?"behavior":"contact"),{data:m}=g9();j.useEffect(()=>{s&&d(r)},[s,r]);const p=x=>d(y=>({...y,...x})),f=Object.entries(c).filter(([,x])=>x!==void 0&&x!==!1&&x!=="").length;return e.jsx(my,{open:s,onOpenChange:t,children:e.jsxs(g0,{side:"right",className:"w-full sm:max-w-lg overflow-y-auto",children:[e.jsxs(vv,{children:[e.jsxs(bv,{className:"flex items-center gap-2",children:[e.jsx(cn,{className:"h-4 w-4 text-primary"}),"Advanced Filters"]}),e.jsx(pG,{children:"Slice your database by website activity, contact details, and engagement."})]}),e.jsxs(oa,{value:u,onValueChange:x=>h(x),className:"mt-4",children:[e.jsxs(la,{className:"grid w-full grid-cols-3",children:[e.jsxs(Kt,{value:"contact",className:"gap-1.5",children:[e.jsx(Bn,{className:"h-3.5 w-3.5"})," Contact"]}),e.jsxs(Kt,{value:"behavior",disabled:!n,className:"gap-1.5",children:[e.jsx(Lm,{className:"h-3.5 w-3.5"})," Behavior"]}),e.jsx(Kt,{value:"engagement",children:"Engagement"})]}),e.jsxs(Zt,{value:"contact",className:"space-y-6 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Contact Type"}),e.jsxs(Ns,{value:i,onValueChange:l,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"All types"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Types"}),o==null?void 0:o.map(x=>e.jsx(et,{value:x.id,children:x.name},x.id))]})]})]}),e.jsxs(nC,{title:"Contact Info Present",children:[e.jsx(Ov,{label:"Has email",checked:c.hasEmail===!0,onChange:x=>p({hasEmail:x||void 0})}),e.jsx(Ov,{label:"Has phone",checked:c.hasPhone===!0,onChange:x=>p({hasPhone:x||void 0})}),e.jsx(Ov,{label:"Has address",checked:c.hasAddress===!0,onChange:x=>p({hasAddress:x||void 0})}),e.jsx(Ov,{label:"Has birthday",checked:c.hasBirthday===!0,onChange:x=>p({hasBirthday:x||void 0})}),e.jsx(Ov,{label:"Has spouse",checked:c.hasSpouse===!0,onChange:x=>p({hasSpouse:x||void 0})}),e.jsx(Ov,{label:"Has company / job",checked:c.hasCompany===!0,onChange:x=>p({hasCompany:x||void 0})}),e.jsx(Ov,{label:"Has notes",checked:c.hasNotes===!0,onChange:x=>p({hasNotes:x||void 0})})]}),e.jsxs(nC,{title:"Location",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(W7e,{label:"City",value:c.city||"",onChange:x=>p({city:x||void 0}),placeholder:"Any city"}),e.jsx(W7e,{label:"State",value:c.state||"",onChange:x=>p({state:x||void 0}),placeholder:"Any state"})]}),e.jsx(W7e,{label:"ZIP / Postal",value:c.zip||"",onChange:x=>p({zip:x||void 0}),placeholder:"Any ZIP"})]}),e.jsxs(nC,{title:"Important Dates",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Birthday month"}),e.jsxs(Ns,{value:c.birthdayMonth?String(c.birthdayMonth):"all",onValueChange:x=>p({birthdayMonth:x==="all"?void 0:Number(x)}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Any month"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"Any month"}),DEe.map(x=>e.jsx(et,{value:String(x.value),children:x.label},x.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{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(Ns,{value:c.anniversaryField||"home_anniversary",onValueChange:x=>p({anniversaryField:x}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Field"})}),e.jsx(js,{children:iWt.map(x=>e.jsx(et,{value:x.value,children:x.label},x.value))})]}),e.jsxs(Ns,{value:c.anniversaryMonth?String(c.anniversaryMonth):"all",onValueChange:x=>p({anniversaryMonth:x==="all"?void 0:Number(x)}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Any month"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"Any month"}),DEe.map(x=>e.jsx(et,{value:String(x.value),children:x.label},x.value))]})]})]})]})]}),e.jsx(nC,{title:"Date Added",children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(Swt,{label:"From",value:c.dateAddedFrom,onChange:x=>p({dateAddedFrom:x||void 0})}),e.jsx(Swt,{label:"To",value:c.dateAddedTo,onChange:x=>p({dateAddedTo:x||void 0})})]})}),e.jsx(nC,{title:"Lead Source",children:e.jsxs(Ns,{value:c.leadSourceId||"all",onValueChange:x=>p({leadSourceId:x==="all"?void 0:x}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"All sources"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All sources"}),e.jsx(et,{value:"none",children:"No source"}),m==null?void 0:m.map(x=>e.jsx(et,{value:x.id,children:x.name},x.id))]})]})})]}),e.jsx(Zt,{value:"behavior",className:"space-y-6 mt-4",children:n?e.jsxs(e.Fragment,{children:[e.jsxs(nC,{title:"Last Active On Site",children:[e.jsx(y_,{value:c.lastActive||"",onValueChange:x=>p({lastActive:x||void 0}),className:"grid grid-cols-2 gap-2",children:FIn.map(x=>e.jsxs("label",{className:"flex items-center gap-2 rounded-md border px-3 py-2 cursor-pointer hover:bg-accent",children:[e.jsx(Fh,{value:x.value}),e.jsx("span",{className:"text-sm",children:x.label})]},x.value))}),c.lastActive&&e.jsx(U,{variant:"ghost",size:"sm",className:"mt-1 h-7 px-2 text-xs",onClick:()=>p({lastActive:void 0}),children:"Clear"})]}),e.jsxs(nC,{title:"Registration",children:[e.jsx(Ov,{label:"Registered on lead site",checked:c.registered==="yes",onChange:x=>p({registered:x?"yes":void 0})}),e.jsx(Ov,{label:"Anonymous visitors only",checked:c.registered==="no",onChange:x=>p({registered:x?"no":void 0})})]}),e.jsxs(nC,{title:"Property Activity",children:[e.jsx(Ov,{label:"Viewed any listing",checked:c.viewedListing==="any",onChange:x=>p({viewedListing:x?"any":void 0})}),e.jsx(Ov,{label:"Hot buyer — 3+ views in last 7 days",checked:c.viewedListing==="multiple7d",onChange:x=>p({viewedListing:x?"multiple7d":void 0})}),e.jsx(Ov,{label:"Saved a property",checked:!!c.savedProperty,onChange:x=>p({savedProperty:x||void 0})}),e.jsx(Ov,{label:"Has an active saved search / alert",checked:!!c.hasSavedSearch,onChange:x=>p({hasSavedSearch:x||void 0})})]}),e.jsxs(nC,{title:"Requests",children:[e.jsx(Ov,{label:"Requested a showing / asked a question",checked:!!c.requestedShowing,onChange:x=>p({requestedShowing:x||void 0})}),e.jsx(Ov,{label:"Requested a home valuation",checked:!!c.requestedValuation,onChange:x=>p({requestedValuation:x||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(Zt,{value:"engagement",className:"space-y-4 mt-4",children:[e.jsx(Ov,{label:"Any website activity",checked:!!c.websiteActiveOnly,onChange:x=>p({websiteActiveOnly:x||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($Pt,{className:"mt-6 flex-row gap-2 sm:justify-between",children:[e.jsx(U,{variant:"ghost",onClick:()=>d({}),disabled:f===0,children:"Clear behavior filters"}),e.jsx(U,{onClick:()=>{a(c),t(!1)},children:"Apply"})]})]})})}function nC({title:s,children:t}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("div",{className:"space-y-2",children:t})]})}function Ov({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(wn,{checked:t,onCheckedChange:n})]})}function W7e({label:s,value:t,onChange:n,placeholder:r}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsxs("div",{className:"relative",children:[e.jsx(xe,{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(er,{className:"h-3 w-3"})})]})]})}function Swt({label:s,value:t,onChange:n}){const[r,a]=j.useState(!1),i=t?ty(t):void 0;return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsxs(md,{open:r,onOpenChange:a,children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{variant:"outline",className:Mt("w-full justify-start text-left font-normal h-8",!i&&"text-muted-foreground"),children:[e.jsx(pa,{className:"mr-2 h-3.5 w-3.5"}),i?Gs(i,"MMM d, yyyy"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(id,{className:"w-auto p-0",align:"start",children:e.jsx(yj,{mode:"single",selected:i,onSelect:l=>{n(l?Gs(l,"yyyy-MM-dd"):void 0),a(!1)},initialFocus:!0})})]})]})}function BIn({behavior:s,onRemove:t,onClearAll:n}){const r=UIn(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 UIn(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=DEe.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=DEe.find(i=>i.value===s.anniversaryMonth),a=((n=iWt.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 ${Gs(ty(s.dateAddedFrom),"MMM d, yyyy")}`}),s.dateAddedTo&&t.push({key:"dateAddedTo",label:`Added on/before ${Gs(ty(s.dateAddedTo),"MMM d, yyyy")}`}),s.leadSourceId&&t.push({key:"leadSourceId",label:s.leadSourceId==="none"?"No lead source":"Lead source"}),t}async function oB(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 NY(){return{lastActiveAt:null,registered:!1,propertyViewCount:0,propertyViewCount7d:0,savedListingCount:0,activeSavedSearchCount:0,showingRequests:0,valuationRequests:0,viewedCities:[],viewedZips:[]}}function qIn(){const{user:s}=vs(),{leadSite:t,hasLeadSite:n}=$p(),{data:r,isLoading:a}=ct({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 N=i.get(v)||NY();i.set(v,{...N,...b})},o=await oB((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 oB((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 oB((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 N=i.get(b)||NY();N.propertyViewCount+=1,v.viewed_at>=m&&(N.propertyViewCount7d+=1),i.set(b,N)}),(await oB((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 N=i.get(b)||NY();N.savedListingCount+=1,i.set(b,N)}),(await oB((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 N=i.get(b)||NY();N.activeSavedSearchCount+=1,i.set(b,N)}),(await oB((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 N=i.get(b)||NY(),S=(v.lead_type||"").toLowerCase();(S.includes("showing")||S.includes("question")||S==="contact")&&(N.showingRequests+=1),(S.includes("valuation")||S.includes("cma")||S.includes("home_value"))&&(N.valuationRequests+=1),i.set(b,N)}),i},enabled:!!s&&n,staleTime:5*60*1e3});return{behaviorMap:r??new Map,hasLeadSite:n,isLoading:a}}const oWt="innercircle_geocode_cache_v1";function $In(){try{return JSON.parse(localStorage.getItem(oWt)||"{}")}catch{return{}}}function VIn(s){try{localStorage.setItem(oWt,JSON.stringify(s))}catch{}}function HIn(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 GIn({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,p]=j.useState({done:0,total:0}),[f,x]=j.useState(!1),[y,v]=j.useState("heat");j.useEffect(()=>{if(!s)return;let N=!1;return(async()=>{d(!0);const{data:S}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();N||(o((S==null?void 0:S.value)||""),d(!1))})(),()=>{N=!0}},[s]),j.useEffect(()=>{if(!s||!l)return;let N=!1;return(async()=>{const A=$In(),T=n.map(V=>({c:V,addr:HIn(V)})).filter(V=>V.addr),L=[],M=[];for(const{c:V,addr:K}of T){const Z=A[K];Z!==null&&(Z?L.push({id:V.id,name:`${V.first_name||""} ${V.last_name||""}`.trim(),city:V.city||null,state:V.state||null,zip:V.zip||V.zip_code||null,lat:Z.lat,lng:Z.lng}):M.push({c:V,addr:K}))}if(N||h(L),p({done:L.length,total:T.length}),M.length===0)return;x(!0);const I=6;let R=0;const z={...A},$=[...L],H=async()=>{var V;for(;R{N=!0}},[s,l,n]);const b=j.useMemo(()=>{const N=new Map;for(const S of n){const A=(S.city||"").trim();if(!A)continue;const T=(S.state||"").trim()||null,L=`${A.toLowerCase()}|${T||""}`,M=N.get(L);M?M.count++:N.set(L,{city:A,state:T,count:1})}return Array.from(N.values()).sort((S,A)=>A.count-S.count)},[n]);return j.useEffect(()=>{if(!(!s||!l||!a.current||i.current))return bd.accessToken=l,i.current=new bd.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[-98.5795,39.8283],zoom:3.5}),i.current.addControl(new bd.NavigationControl,"top-right"),()=>{var N;(N=i.current)==null||N.remove(),i.current=null}},[s,l]),j.useEffect(()=>{const N=i.current;if(!N||u.length===0)return;const S=()=>{const T={type:"FeatureCollection",features:u.map(M=>({type:"Feature",properties:{id:M.id,name:M.name},geometry:{type:"Point",coordinates:[M.lng,M.lat]}}))},L=N.getSource("contacts-src");if(L?L.setData(T):(N.addSource("contacts-src",{type:"geojson",data:T}),N.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]}}),N.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}}),N.on("click","contacts-points",M=>{var z;const I=(z=M.features)==null?void 0:z[0];if(!I)return;const R=I.geometry.coordinates.slice();new bd.Popup({offset:12}).setLngLat(R).setHTML(`
${I.properties.name||"Contact"}
`).addTo(N)}),N.on("mouseenter","contacts-points",()=>{N.getCanvas().style.cursor="pointer"}),N.on("mouseleave","contacts-points",()=>{N.getCanvas().style.cursor=""})),N.getLayer("contacts-heat")&&N.setLayoutProperty("contacts-heat","visibility",y==="heat"?"visible":"none"),N.getLayer("contacts-points")&&(N.setPaintProperty("contacts-points","circle-opacity",y==="points"?.9:0),N.setLayoutProperty("contacts-points","visibility","visible")),u.length>0&&!N._fitDone){const M=new bd.LngLatBounds;u.forEach(I=>M.extend([I.lng,I.lat]));try{N.fitBounds(M,{padding:60,maxZoom:11,duration:600}),N._fitDone=!0}catch{}}};N.isStyleLoaded()?S():N.once("load",S)},[u,y]),e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-6xl w-[95vw] h-[90vh] p-0 flex flex-col",children:[e.jsx(Vs,{className:"p-4 pb-2 border-b",children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Xd,{className:"h-5 w-5 text-orange-500"}),"Geographic Heat Map",e.jsxs(Be,{variant:"secondary",className:"ml-2",children:[u.length," mapped · ",b.length," cities"]})]})}),e.jsxs("div",{className:"flex-1 flex flex-col md:flex-row min-h-0",children:[e.jsx("div",{className:"flex-1 relative min-h-[300px]",children:c?e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsx(Et,{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(U,{size:"sm",variant:y==="heat"?"default":"ghost",onClick:()=>v("heat"),className:"h-8",children:[e.jsx(Xd,{className:"h-3.5 w-3.5 mr-1"})," Heat"]}),e.jsxs(U,{size:"sm",variant:y==="points"?"default":"ghost",onClick:()=>v("points"),className:"h-8",children:[e.jsx(L4,{className:"h-3.5 w-3.5 mr-1"})," Pins"]})]}),f&&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(Et,{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(Vo,{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(ni,{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(Gi,{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((N,S)=>{var L;const A=((L=b[0])==null?void 0:L.count)||1,T=N.count/A*100;return e.jsx(we,{className:"cursor-pointer hover:border-primary transition-colors overflow-hidden",onClick:()=>{r==null||r(N.city,N.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:`${T}%`}}),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:[N.city,N.state?`, ${N.state}`:""]}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:S===0?"🔥 Hottest market":`Rank #${S+1}`})]}),e.jsx(Be,{variant:"secondary",className:"shrink-0",children:N.count})]})]})},`${N.city}-${N.state}-${S}`)})]})})]})]})]})})}function _D(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 Cwt({birthday:s,homeAnniversary:t,weddingAnniversary:n,className:r,contactId:a,contactName:i,contactAddress:l}){const o=Wn(),c=K7e(s,"birthday",7),d=K7e(t,"anniversary",7),u=K7e(n||null,"anniversary",7);if(!c&&!d&&!u)return null;const h=(m,p,f)=>{f.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")&&p&&x.set("date",p),x.set("cardType",m),o(`/mission-control/card-studio?${x.toString()}`)};return e.jsxs("div",{className:Mt("flex flex-wrap gap-1",r),children:[c&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(Be,{variant:"secondary",className:Mt("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(ln,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),d&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(Be,{variant:"secondary",className:Mt("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(ln,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),u&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs(Be,{variant:"secondary",className:Mt("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(ln,{className:"h-2.5 w-2.5"}),"Send Card"]})]})]})}function Awt({deal:s}){if(!s||!s.stage)return null;const{stage:t}=s;return e.jsxs(Be,{variant:"outline",className:"text-[10px] gap-1 font-medium whitespace-nowrap",style:{borderColor:t.color,color:t.color,backgroundColor:`${t.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:t.color}}),t.name]})}function Ewt({count:s,className:t}){return!s||s<=0?null:e.jsxs(Be,{variant:"outline",className:Mt("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(RM,{className:"h-2.5 w-2.5"}),s===1?"In drip":`${s} drips`]})}function WIn(){const s=Sa();return ct({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 KIn(){const s=Sa();return ct({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 YIn="#6366F1";function Twt(s,t){return`color-mix(in srgb, ${s} ${t}%, transparent)`}function ZIn(s){return`color-mix(in oklab, ${s} 78%, hsl(var(--foreground)))`}function lWt({label:s,color:t,className:n,onClick:r,title:a}){const i=t||YIn,l=r?"button":"span";return e.jsxs(l,{type:r?"button":void 0,onClick:r,title:a??s,style:{backgroundColor:Twt(i,14),color:ZIn(i),boxShadow:`inset 0 0 0 1px ${Twt(i,22)}`},className:Mt("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 XIn({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:Mt("flex flex-wrap items-center gap-1.5",n),children:[i.map(o=>{var c,d;return e.jsx(lWt,{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 Mwt({contactId:s,compact:t=!1}){const{data:n}=ZG(),{data:r}=WAn(s),a=Ptt(),i=cGt(),l=ZAn(),[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))||[]),p=(n==null?void 0:n.filter(v=>v.name.toLowerCase().includes(d.toLowerCase())))||[],f=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()||f))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,N,S;return e.jsxs(Be,{variant:"outline",className:"text-xs gap-1 pr-1",style:{borderColor:((b=v.tag)==null?void 0:b.color)||"#6366F1",color:((N=v.tag)==null?void 0:N.color)||"#6366F1"},children:[e.jsx(Cf,{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(er,{className:"h-2.5 w-2.5"})})]},v.id)}),e.jsxs(md,{open:o,onOpenChange:c,children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{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(an,{className:"h-3 w-3"}),!t&&e.jsx("span",{className:"ml-1",children:"Tag"})]})}),e.jsxs(id,{className:"w-56 p-2",align:"start",onClick:v=>v.stopPropagation(),children:[e.jsx(xe,{ref:h,placeholder:"Search or create tag...",value:d,onChange:v=>u(v.target.value),onKeyDown:v=>{v.key==="Enter"&&d.trim()&&!f?(v.preventDefault(),y()):v.key==="Enter"&&f&&!m.has(f.id)&&(v.preventDefault(),x(f))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[p.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(Xr,{className:"h-3.5 w-3.5 text-primary shrink-0"})]},v.id)),d.trim()&&!f&&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(an,{className:"h-3.5 w-3.5"}),'Create "',d.trim(),'"']}),p.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 Pwt({contactId:s,tags:t,max:n=2}){return!t||t.length===0?null:e.jsx(XIn,{tags:t,max:n})}const Ble=["#6366F1","#8B5CF6","#EC4899","#EF4444","#F97316","#F59E0B","#10B981","#14B8A6","#06B6D4","#3B82F6","#6B7280","#1F2937"];function QIn({open:s,onOpenChange:t}){const{data:n,isLoading:r}=ZG(),a=Ptt(),i=YAn(),l=KAn(),[o,c]=j.useState(""),[d,u]=j.useState(Ble[0]),[h,m]=j.useState(null),[p,f]=j.useState(""),[x,y]=j.useState(""),v=async()=>{if(o.trim())try{await a.mutateAsync({name:o.trim(),color:d}),c(""),u(Ble[0]),ka({title:"Tag created"})}catch(A){ka({title:"Error",description:A.message,variant:"destructive"})}},b=async A=>{if(p.trim())try{await i.mutateAsync({id:A,name:p.trim(),color:x}),m(null),ka({title:"Tag updated"})}catch(T){ka({title:"Error",description:T.message,variant:"destructive"})}},N=async(A,T)=>{if(await Yi(`Delete tag "${T}"? It will be removed from all contacts.`))try{await l.mutateAsync(A),ka({title:"Tag deleted"})}catch(L){ka({title:"Error",description:L.message,variant:"destructive"})}},S=A=>{m(A.id),f(A.name),y(A.color)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Manage Tags"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{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(U,{size:"sm",onClick:v,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(an,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Ble.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:Ble.map(T=>e.jsx("button",{onClick:()=>y(T),className:`h-5 w-5 rounded-full border-2 ${x===T?"border-foreground":"border-transparent"}`,style:{backgroundColor:T}},T))}),e.jsx(xe,{value:p,onChange:T=>f(T.target.value),onKeyDown:T=>T.key==="Enter"&&b(A.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx(U,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>b(A.id),children:e.jsx(Xr,{className:"h-4 w-4 text-primary"})}),e.jsx(U,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(null),children:e.jsx(er,{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(U,{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(ri,{className:"h-3.5 w-3.5"})}),e.jsx(U,{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:()=>N(A.id,A.name),children:e.jsx(In,{className:"h-3.5 w-3.5"})})]})},A.id))]})]})})}function JIn({open:s,onOpenChange:t}){const{data:n,isLoading:r}=g9(),a=WQe(),i=Czs(),l=Azs(),[o,c]=j.useState(""),[d,u]=j.useState(null),[h,m]=j.useState(""),p=async()=>{if(o.trim())try{await a.mutateAsync(o.trim()),c("")}catch(v){re.error(v.message||"Failed to add lead source")}},f=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 Yi(`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(N){re.error(N.message||"Failed to remove")}},y=v=>{u(v.id),m(v.name)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Manage Lead Sources"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{placeholder:"New lead source name...",value:o,onChange:v=>c(v.target.value),onKeyDown:v=>v.key==="Enter"&&p(),className:"flex-1 h-9"}),e.jsxs(U,{size:"sm",onClick:p,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(an,{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(xe,{value:h,onChange:b=>m(b.target.value),onKeyDown:b=>b.key==="Enter"&&f(v.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx(U,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>f(v.id),children:e.jsx(Xr,{className:"h-4 w-4 text-primary"})}),e.jsx(U,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(null),children:e.jsx(er,{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(U,{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(ri,{className:"h-3.5 w-3.5"})}),e.jsx(U,{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(In,{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 cWt({value:s,onChange:t,label:n="Lead Source"}){const{data:r}=g9(),a=WQe(),[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(te,{children:n}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ns,{value:s||"_none",onValueChange:u=>t(u==="_none"?"":u),children:[e.jsx(ws,{className:"flex-1",children:e.jsx(ks,{placeholder:"Select lead source"})}),e.jsxs(js,{children:[e.jsx(et,{value:"_none",children:"No source"}),r==null?void 0:r.map(u=>e.jsx(et,{value:u.id,children:u.name},u.id))]})]}),e.jsx(U,{type:"button",variant:"outline",size:"icon",className:"shrink-0",onClick:()=>l(!i),children:i?e.jsx(er,{className:"h-4 w-4"}):e.jsx(an,{className:"h-4 w-4"})})]}),i&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{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(U,{type:"button",size:"sm",onClick:d,disabled:!o.trim()||a.isPending,children:"Add"})]})]})}function XHe({contactId:s,currentSpouseContactId:t,currentSpouseName:n,currentSpouseEmail:r,onLink:a,onUnlink:i,isEditing:l}){const o=Wn(),c=Sa(),[d,u]=j.useState(!1),[h,m]=j.useState(""),{data:p}=ct({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:f}=ct({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&&p){const x=`${p.first_name} ${p.last_name||""}`.trim();return e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{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(So,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("button",{onClick:()=>o(`/mission-control/contacts/${p.id}`),className:"text-sm font-medium text-primary hover:underline truncate block",children:x}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[p.phone,p.email].filter(Boolean).join(" · ")||"No contact info"})]}),l&&e.jsxs(U,{variant:"ghost",size:"sm",onClick:i,className:"shrink-0 h-7 px-2",children:[e.jsx(qF,{className:"h-3.5 w-3.5 mr-1"}),"Unlink"]}),!l&&e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>o(`/mission-control/contacts/${p.id}`),className:"shrink-0 h-7 px-2",children:e.jsx(Oa,{className:"h-3.5 w-3.5"})})]})]})}return!t&&(n||r)?e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{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(So,{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(md,{open:d,onOpenChange:u,children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{variant:"outline",size:"sm",className:"shrink-0 h-7 px-2",children:[e.jsx(ad,{className:"h-3.5 w-3.5 mr-1"}),"Link Contact"]})}),e.jsx(id,{className:"w-72 p-2",align:"end",children:e.jsx(Lwt,{search:h,setSearch:m,results:f,onSelect:x=>{a(x),u(!1),m("")}})})]})]})]}):l?e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs(md,{open:d,onOpenChange:u,children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{variant:"outline",className:"w-full justify-start text-muted-foreground font-normal h-10",children:[e.jsx(ad,{className:"h-4 w-4 mr-2"}),"Link an existing contact as spouse..."]})}),e.jsx(id,{className:"w-72 p-2",align:"start",children:e.jsx(Lwt,{search:h,setSearch:m,results:f,onSelect:x=>{a(x),u(!1),m("")}})})]})]}):null}function Lwt({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(Fr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(xe,{value:s,onChange:a=>t(a.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(Gi,{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 e8n={warm:"stroke-emerald-500",cooling:"stroke-amber-500","at-risk":"stroke-red-500"},t8n={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 s8n({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:Mt("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:e8n[t]})]}),e.jsx("span",{className:Mt("absolute inset-0 flex items-center justify-center font-semibold tabular-nums",t8n[t],n>=56?"text-lg":"text-[11px]"),children:o})]})}const Ule=new Map;async function n8n(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 r8n(s,t=256){const n=s.trim().toLowerCase();if(!n||!n.includes("@"))return null;const r=`${n}|${t}`;if(Ule.has(r))return Ule.get(r)??null;try{const i=`https://gravatar.com/avatar/${await n8n(n)}?s=${t}&d=404`;return Ule.set(r,i),i}catch{return Ule.set(r,null),null}}function a8n(s,t=256){const[n,r]=j.useState(null);return j.useEffect(()=>{let a=!0;if(!s){r(null);return}return r8n(s,t).then(i=>{a&&r(i)}),()=>{a=!1}},[s,t]),n}function Jtt({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=a8n(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:Mt("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 i8n({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(Bg,{children:[e.jsx(Ug,{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(Bn,{className:"h-3 w-3"})})}),e.jsx(ng,{children:r})]})}function o8n({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:p}){const f=!!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(an,{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(Xd,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Heat Map"]}),e.jsxs(Ku,{children:[e.jsx(Yu,{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(qa,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Import",e.jsx(rl,{className:"h-3.5 w-3.5 opacity-70"})]})}),e.jsxs(Eu,{align:"end",children:[e.jsxs(La,{onClick:i,children:[e.jsx(qa,{className:"mr-2 h-4 w-4"})," Import CSV"]}),e.jsxs(La,{onClick:l,children:[e.jsx(i1,{className:"mr-2 h-4 w-4"})," Import from Phone"]}),e.jsxs(La,{onClick:o,children:[e.jsx(Cf,{className:"mr-2 h-4 w-4"})," Manage Tags"]})]})]}),p]})]}),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(Fr,{className:"pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 opacity-70"}),e.jsx(xe,{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"})]}),f&&e.jsx("div",{className:"hub-glass inline-flex shrink-0 items-center gap-1 rounded-xl p-1",children:[{key:"my",label:"Mine",icon:Bn,show:!0},{key:"team",label:"Team",icon:Bn,show:!!h},{key:"lead-pond",label:"Pond",icon:cb,show:!!m}].filter(x=>x.show).map(x=>e.jsxs("button",{onClick:()=>u==null?void 0:u(x.key),className:Mt("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:Mt("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 l8n({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 c8n({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 Iwt({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 dWt(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 Rwt(s){if(!s)return null;const t=Su(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:zl,color:"text-violet-600 dark:text-violet-400",match:s=>s.relationshipScore.daysSinceTouch===null},{key:"stale-90",title:"Stale 90+ Days",icon:Yr,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:$w,color:"text-cyan-600 dark:text-cyan-400",match:s=>s.relationshipScore.status==="cooling"},{key:"birthdays-soon",title:"Birthdays Soon",icon:lg,color:"text-pink-600 dark:text-pink-400",match:(s,t)=>t.daysToBirthday!==null&&t.daysToBirthday<=30},{key:"anniversary-soon",title:"Home Anniversary",icon:ra,color:"text-emerald-600 dark:text-emerald-400",match:(s,t)=>t.daysToAnniv!==null&&t.daysToAnniv<=30},{key:"has-deal",title:"Active Deal",icon:og,color:"text-teal-700 dark:text-teal-400",match:(s,t)=>t.hasDeal},{key:"website-active",title:"Active on Site",icon:fl,color:"text-indigo-600 dark:text-indigo-400",match:()=>!1},{key:"vips",title:"VIPs",icon:cn,color:"text-amber-600 dark:text-amber-300",match:s=>s.relationshipScore.score>=80},{key:"active-buyers",title:"Active Buyers",icon:Fr,color:"text-sky-600 dark:text-sky-400",match:(s,t)=>t.hasCriteria},{key:"missing-criteria",title:"No Home Search",icon:pq,color:"text-orange-600 dark:text-orange-400",match:(s,t)=>!t.hasCriteria},{key:"missing-info",title:"Missing Info",icon:tc,color:"text-slate-600 dark:text-slate-400",match:s=>dWt(s)}];function d8n({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}=Ltt(),p=dGt(),f=uGt(),[x,y]=j.useState(!1),[v,b]=j.useState(""),N=j.useMemo(()=>{const L={"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 L;for(const M of s){const I={hasDeal:!!(t&&t[M.id]),daysToBirthday:Rwt(M.birthday),daysToAnniv:Rwt(M.home_anniversary),hasCriteria:!!(r!=null&&r.has(M.id))};for(const R of Dwt)R.key!=="website-active"&&R.match(M,I)&&L[R.key]++}return L},[s,t,n,r]),S=!!o.search||!!o.type&&o.type!=="all"||!!o.status&&o.status!=="all"||!!o.behavior&&Object.values(o.behavior).some(L=>L!==void 0&&L!==!1),A=async()=>{v.trim()&&(await p.mutateAsync({name:v.trim(),filters:o,sort_by:c}),b(""),y(!1))},T="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:Mt(T,!i&&!d?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border"),children:[e.jsx(Bn,{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(L=>{const M=d===L.id;return e.jsxs("div",{className:Mt(T,"group pr-1",M?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border"),children:[e.jsx("button",{type:"button",onClick:()=>u(L.id,L.filters,L.sort_by),children:L.name}),e.jsx("button",{type:"button","aria-label":`Delete view ${L.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:()=>{f.mutate(L.id),M&&h()},children:e.jsx(er,{className:"h-3 w-3"})})]},L.id)}),e.jsx("div",{className:"h-5 w-px bg-border shrink-0"}),Dwt.map(L=>{const M=L.icon,I=N[L.key],R=i===L.key;return e.jsxs("button",{type:"button",onClick:()=>l(R?null:L.key),"aria-pressed":R,className:Mt(T,R?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border",!R&&I===0&&"opacity-55"),children:[e.jsx(M,{className:Mt("h-3.5 w-3.5",R?"":L.color)}),L.title,e.jsx("span",{className:"tabular-nums opacity-70",children:I.toLocaleString()})]},L.key)}),e.jsxs(U,{variant:"ghost",size:"sm",className:"h-8 gap-1.5 text-xs shrink-0",disabled:!S,onClick:()=>y(!0),children:[e.jsx(NM,{className:"h-3.5 w-3.5"}),"Save view"]})]}),e.jsx(zs,{open:x,onOpenChange:y,children:e.jsxs(Ds,{className:"sm:max-w-sm",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Save this view"}),e.jsx(Pr,{children:"Your current search, filters, and sorting are saved as a one-click chip."})]}),e.jsx(xe,{autoFocus:!0,placeholder:"e.g. Past clients cooling off",value:v,onChange:L=>b(L.target.value),onKeyDown:L=>L.key==="Enter"&&A()}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx(U,{onClick:A,disabled:!v.trim()||p.isPending,children:"Save view"})]})]})})]})}const Owt=[{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"}],Y7e={relationship:!0,buyerCriteria:!0,stage:!0,leadSource:!0,tags:!0,lastTouch:!0,nextAction:!0,dealValue:!0,email:!1,phone:!1,address:!1,birthday:!1},Fwt="innercircle:contact-columns:v1";function u8n(){const[s,t]=j.useState(()=>{try{const a=localStorage.getItem(Fwt);if(a)return{...Y7e,...JSON.parse(a)}}catch{}return Y7e});j.useEffect(()=>{try{localStorage.setItem(Fwt,JSON.stringify(s))}catch{}},[s]);const n=j.useCallback(a=>{t(i=>({...i,[a]:!i[a]}))},[]),r=j.useCallback(()=>t(Y7e),[]);return{columns:s,toggle:n,reset:r}}function h8n({columns:s,onToggle:t,onReset:n}){const r=Owt.filter(a=>s[a.key]).length;return e.jsxs(md,{children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{variant:"outline",size:"sm",className:"h-8 gap-1.5 rounded-lg text-xs",children:[e.jsx(zT,{className:"h-3.5 w-3.5"}),"Columns",e.jsx(Be,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:r})]})}),e.jsxs(id,{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(Kg,{className:"h-3 w-3"}),"Reset"]})]}),e.jsx("div",{className:"max-h-[320px] overflow-y-auto space-y-0.5",children:Owt.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(xi,{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 Wq=1e3;function uWt(){const s=Sa();return ct({queryKey:["contact-criteria-map",s],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{const t=[];for(let r=0;;r+=Wq){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+Wq-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+=Wq){const{data:c,error:d}=await q.from("contact_property_alerts").select("id, contact_id").eq("owner_user_id",t).range(o,o+Wq-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 f8n(){const s=Qt();return yt({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 TU=s=>String(s??"").trim().toLowerCase();function g8n(s,t){const n=TU(s).replace(/[\s_-]+/g,""),r=TU(t).replace(/[\s_-]+/g,"");return!n||!r?!1:n===r||n.includes(r)||r.includes(n)}function x8n(s,t){var m,p,f;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||(((p=s.zip_codes)==null?void 0:p.length)||0)>0){const x=!!t.city&&(s.cities||[]).some(v=>TU(v)===TU(t.city)),y=!!t.zip&&(s.zip_codes||[]).some(v=>TU(v)===TU(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")),(((f=s.property_types)==null?void 0:f.length)||0)>0&&t.propertyType&&(s.property_types.some(y=>g8n(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 y8n(s,t,n,r={}){const a=[];for(const i of s){const l=t[i.id];if(!l)continue;const o=x8n(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 qle=s=>s>=1e3?`$${Math.round(s/1e3)}k`:`$${s}`;function hWt(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 v8n(s){var r;if(!s)return"";const t=[];s.min_price&&s.max_price?t.push(`${qle(s.min_price)}–${qle(s.max_price)}`):s.max_price?t.push(`up to ${qle(s.max_price)}`):s.min_price&&t.push(`${qle(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 zwt({criteria:s,onEdit:t,showAlertState:n,matchCount:r,className:a,compact:i}){const l=v8n(s);return hWt(s)?e.jsxs("button",{type:"button",onClick:t?c=>{c.stopPropagation(),t()}:void 0,className:Mt("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(bx,{className:"h-3.5 w-3.5 shrink-0 text-emerald-600 dark:text-emerald-400"}):e.jsx(Zk,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):e.jsx(Fr,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:Mt("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:Mt("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(an,{className:"h-3 w-3"}),"Add home search"]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}const mWt=["Single Family","Condo","Townhouse","Multi-Family","Land","Commercial"];function b8n(){const s=Sa();return ct({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 Bwt({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(xe,{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(U,{type:"button",variant:"outline",size:"sm",onClick:()=>n(s),children:e.jsx(an,{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(ni,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),h]},h))})]})}function pWt({value:s,onChange:t,hasIdx:n=!0,idxNote:r}){const[a,i]=j.useState(""),[l,o]=j.useState(""),{data:c}=b8n(),d=((c==null?void 0:c.cities)||[]).filter(f=>{var x;return!((x=s.cities)!=null&&x.includes(f))}),u=((c==null?void 0:c.zipCodes)||[]).filter(f=>{var x;return!((x=s.zip_codes)!=null&&x.includes(f))}),h=f=>{var y;const x=f.trim();x&&!((y=s.cities)!=null&&y.includes(x))&&t(v=>({...v,cities:[...v.cities||[],x]})),i("")},m=f=>{var y;const x=f.trim();x&&!((y=s.zip_codes)!=null&&y.includes(x))&&t(v=>({...v,zip_codes:[...v.zip_codes||[],x]})),o("")},p=f=>{t(x=>{const y=x.property_types||[];return{...x,property_types:y.includes(f)?y.filter(v=>v!==f):[...y,f]}})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs(te,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(yu,{className:"h-3.5 w-3.5"})," Price Range"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(xe,{type:"number",placeholder:"Min price",value:s.min_price??"",onChange:f=>t(x=>({...x,min_price:f.target.value?Number(f.target.value):null}))}),e.jsx(xe,{type:"number",placeholder:"Max price",value:s.max_price??"",onChange:f=>t(x=>({...x,max_price:f.target.value?Number(f.target.value):null}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs(te,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(C4,{className:"h-3.5 w-3.5"})," Min Beds"]}),e.jsxs(Ns,{value:s.min_beds?String(s.min_beds):"any",onValueChange:f=>t(x=>({...x,min_beds:f==="any"?null:Number(f)})),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Any"})}),e.jsxs(js,{children:[e.jsx(et,{value:"any",children:"Any"}),[1,2,3,4,5].map(f=>e.jsxs(et,{value:String(f),children:[f,"+"]},f))]})]})]}),e.jsxs("div",{children:[e.jsxs(te,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(d0,{className:"h-3.5 w-3.5"})," Min Baths"]}),e.jsxs(Ns,{value:s.min_baths?String(s.min_baths):"any",onValueChange:f=>t(x=>({...x,min_baths:f==="any"?null:Number(f)})),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Any"})}),e.jsxs(js,{children:[e.jsx(et,{value:"any",children:"Any"}),[1,1.5,2,2.5,3,4].map(f=>e.jsxs(et,{value:String(f),children:[f,"+"]},f))]})]})]})]}),e.jsxs("div",{children:[e.jsxs(te,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(I4,{className:"h-3.5 w-3.5"})," Square Feet"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(xe,{type:"number",placeholder:"Min sqft",value:s.min_sqft??"",onChange:f=>t(x=>({...x,min_sqft:f.target.value?Number(f.target.value):null}))}),e.jsx(xe,{type:"number",placeholder:"Max sqft",value:s.max_sqft??"",onChange:f=>t(x=>({...x,max_sqft:f.target.value?Number(f.target.value):null}))})]})]}),e.jsxs("div",{children:[e.jsxs(te,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(ni,{className:"h-3.5 w-3.5"})," Cities"]}),e.jsx(Bwt,{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(f=>e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[f,e.jsx("button",{type:"button",onClick:()=>t(x=>{var y;return{...x,cities:(y=x.cities)==null?void 0:y.filter(v=>v!==f)}}),children:e.jsx(er,{className:"h-3 w-3"})})]},f))})]}),e.jsxs("div",{children:[e.jsx(te,{className:"mb-1.5",children:"Zip Codes"}),e.jsx(Bwt,{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(f=>e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[f,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!==f)}}),children:e.jsx(er,{className:"h-3 w-3"})})]},f))})]}),e.jsxs("div",{children:[e.jsxs(te,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(ra,{className:"h-3.5 w-3.5"})," Property Types"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:mWt.map(f=>{var x;return e.jsx(Be,{variant:(x=s.property_types)!=null&&x.includes(f)?"default":"outline",className:"cursor-pointer",onClick:()=>p(f),children:f},f)})})]}),n?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Email new matching listings"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Automatic alerts from your MLS feed"})]}),e.jsx(wn,{checked:s.is_active??!0,onCheckedChange:f=>t(x=>({...x,is_active:f}))})]}),e.jsxs("div",{children:[e.jsx(te,{className:"mb-1.5",children:"Frequency"}),e.jsxs(Ns,{value:s.frequency||"daily",onValueChange:f=>t(x=>({...x,frequency:f})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"daily",children:"Daily"}),e.jsx(et,{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(Jk,{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 _8n({open:s,onOpenChange:t,contactId:n,contactName:r,existing:a}){const{hasIdx:i}=$p(),l=p8n(),o=f8n(),[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(Ds,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{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(pWt,{value:c,onChange:d,hasIdx:i,idxNote:e.jsx(U,{asChild:!0,variant:"link",size:"sm",className:"h-auto p-0 text-xs",children:e.jsx(xr,{to:"/mission-control/website",children:"Explore IDX websites"})})}),e.jsxs(Mr,{className:"gap-2 sm:gap-2",children:[(a==null?void 0:a.id)&&e.jsxs(U,{variant:"ghost",onClick:h,disabled:o.isPending,className:"text-destructive hover:text-destructive mr-auto",children:[o.isPending?e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(In,{className:"h-4 w-4 mr-1"}),"Remove"]}),e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{onClick:u,disabled:l.isPending,children:[l.isPending?e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-1"}),"Save"]})]})]})})}const w8n={city:"",state:"",zip:"",price:null,bedrooms:null,bathrooms:null,sqft:null,propertyType:"",address:""};function j8n({open:s,onOpenChange:t,contacts:n}){const r=Wn(),{data:a}=uWt(),{data:i}=TQe(),[l,o]=j.useState(w8n),[c,d]=j.useState(!0),[u,h]=j.useState(""),m=v=>o(b=>({...b,...v})),p=v=>{h(v);const b=(i||[]).find(N=>N.id===v);b&&m({address:b.property_address||"",city:b.city||"",state:b.state||"",zip:"",price:b.price??null,bedrooms:b.bedrooms??null,bathrooms:b.bathrooms??null,sqft:b.square_footage??null,propertyType:b.property_type||""})},f=!!(l.city||l.zip||l.price),x=j.useMemo(()=>!a||!f?[]:y8n(n,a,l,{includeNearMatches:c}),[n,a,l,c,f]),y=j.useMemo(()=>Object.keys(a||{}).length,[a]);return e.jsx(my,{open:s,onOpenChange:t,children:e.jsxs(g0,{side:"right",className:"w-full sm:max-w-xl overflow-y-auto",children:[e.jsxs(vv,{children:[e.jsxs(bv,{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4 text-primary"}),"Who wants this house?"]}),e.jsx(pG,{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(oa,{defaultValue:i!=null&&i.length?"listing":"manual",children:[e.jsxs(la,{className:"grid w-full grid-cols-2",children:[e.jsx(Kt,{value:"listing",children:"My listings"}),e.jsx(Kt,{value:"manual",children:"Enter a property"})]}),e.jsx(Zt,{value:"listing",className:"pt-3",children:i!=null&&i.length?e.jsxs(Ns,{value:u,onValueChange:p,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Choose a listing…"})}),e.jsx(js,{children:i.map(v=>e.jsxs(et,{value:v.id,children:[[v.property_address,v.city].filter(Boolean).join(", "),v.price?` — ${Uh(Number(v.price))}`:""]},v.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(Zt,{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(te,{className:"mb-1.5 text-xs",children:"Address (optional)"}),e.jsx(xe,{value:l.address||"",onChange:v=>m({address:v.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"mb-1.5 text-xs",children:"City"}),e.jsx(xe,{value:l.city||"",onChange:v=>m({city:v.target.value}),placeholder:"Cypress"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"mb-1.5 text-xs",children:"Zip"}),e.jsx(xe,{value:l.zip||"",onChange:v=>m({zip:v.target.value}),placeholder:"90630"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"mb-1.5 text-xs",children:"Price"}),e.jsx(xe,{type:"number",value:l.price??"",onChange:v=>m({price:v.target.value?Number(v.target.value):null}),placeholder:"750000"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"mb-1.5 text-xs",children:"Sqft"}),e.jsx(xe,{type:"number",value:l.sqft??"",onChange:v=>m({sqft:v.target.value?Number(v.target.value):null}),placeholder:"1800"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"mb-1.5 text-xs",children:"Beds"}),e.jsx(xe,{type:"number",value:l.bedrooms??"",onChange:v=>m({bedrooms:v.target.value?Number(v.target.value):null}),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"mb-1.5 text-xs",children:"Baths"}),e.jsx(xe,{type:"number",step:"0.5",value:l.bathrooms??"",onChange:v=>m({bathrooms:v.target.value?Number(v.target.value):null}),placeholder:"2"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(te,{className:"mb-1.5 text-xs",children:"Property type"}),e.jsxs(Ns,{value:l.propertyType||"any",onValueChange:v=>m({propertyType:v==="any"?"":v}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"any",children:"Any"}),mWt.map(v=>e.jsx(et,{value:v,children:v},v))]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-3",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:[y," ",y===1?"contact has":"contacts have"," a saved home search"]}),e.jsx(U,{variant:c?"secondary":"outline",size:"sm",className:"h-7 text-xs",onClick:()=>d(v=>!v),children:c?"Including close matches":"Exact matches only"})]}),f?x.length===0?e.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-center text-sm text-muted-foreground",children:[e.jsx(ra,{className:"h-5 w-5 mx-auto mb-2 opacity-60"}),"No contacts match this property yet. Add home searches to your buyers so matches show up here."]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[x.length," ",x.length===1?"match":"matches"]}),x.map(({contact:v,result:b})=>{const N=`${v.first_name} ${v.last_name||""}`.trim();return e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border p-3",children:[e.jsx(Jtt,{firstName:v.first_name,lastName:v.last_name||void 0,avatarUrl:v.avatar_url||void 0,email:v.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/${v.id}`),children:N}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-1",children:[b.reasons.slice(0,4).map(S=>e.jsx(Be,{variant:"secondary",className:"text-[10px]",children:S},S)),b.misses.map(S=>e.jsx(Be,{variant:"outline",className:"text-[10px] text-muted-foreground",children:S},S))]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[v.email&&e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8",title:`Email ${N}`,asChild:!0,children:e.jsx("a",{href:`mailto:${v.email}?subject=${encodeURIComponent(`Thought of you: ${l.address||l.city||"this home"}`)}`,children:e.jsx(ln,{className:"h-4 w-4"})})}),v.phone&&e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8",title:`Text ${N}`,asChild:!0,children:e.jsx("a",{href:`sms:${v.phone}`,children:e.jsx(Ki,{className:"h-4 w-4"})})})]})]},v.id)})]}):e.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-center text-sm text-muted-foreground",children:[e.jsx(Fr,{className:"h-5 w-5 mx-auto mb-2 opacity-60"}),"Add a city, zip, or price to see matches."]})]})]})})}function N8n(){var gl;const s=Wn(),[t,n]=fc(),{user:r}=vs(),a=JG(),i=Qt(),{columns:l,toggle:o,reset:c}=u8n(),d=t.get("type"),u=t.get("filter")??t.get("status"),h=t.get("new")==="true",{contactsWithScores:m,isLoading:p}=hre(),{activeContactIds:f,hasLeadSite:x}=JLn(),{data:y}=WIn(),{data:v}=F_(),{data:b}=KIn(),{data:N}=ZG(),{data:S}=DLe(),{hasIdx:A}=$p(),{data:T}=uWt(),{data:L}=m8n(!!A),M=j.useMemo(()=>new Set(Object.entries(T||{}).filter(([,ds])=>hWt(ds)).map(([ds])=>ds)),[T]),[I,R]=j.useState(null),[z,$]=j.useState(!1),[H,V]=j.useState(new Set),[K,Z]=j.useState("any"),Q=ePe(),le=FQe(),ue=zQe(),se=n7t(),[ne,ie]=j.useState(""),[ce,je]=j.useState(!1),[be,he]=j.useState(d||"all"),[ge,ke]=j.useState(u||"all"),[Te,Me]=j.useState("date-added"),[Oe,Se]=j.useState("all"),[Qe,Ae]=j.useState({}),Fe=j.useMemo(()=>Object.values(Qe).filter(ds=>ds!==void 0&&ds!==!1&&ds!=="").length,[Qe]),[Ne,$e]=j.useState(!1),{behaviorMap:Ve,hasLeadSite:qe}=qIn(),[Ze,Ue]=j.useState(h),[Ye,Ge]=j.useState(null),[He,tt]=j.useState(!1),[pt,ft]=j.useState(!1),[qt,Ut]=j.useState(null),[Wt,us]=j.useState(""),[zt,bt]=j.useState(new Set),[As,vt]=j.useState(!1),Ws=Math.max(1,parseInt(t.get("page")||"1",10)||1),[on,Ms]=j.useState(Ws),dn=j.useCallback(ds=>{Ms(Gr=>{const ji=typeof ds=="function"?ds(Gr):ds;return n(ya=>{const Wi=new URLSearchParams(ya);return ji<=1?Wi.delete("page"):Wi.set("page",String(ji)),Wi},{replace:!0}),ji})},[]),[rn,br]=j.useState(50),[Gn,On]=j.useState("my"),[Rr,cr]=j.useState(!1),[Hs,_r]=j.useState(!1),{data:nn}=Sj(),{addToLeadPond:Zn}=iqt(nn==null?void 0:nn.teamId),{ponds:es}=xet(nn==null?void 0:nn.teamId),ar=es.filter(ds=>ds.has_access),[Hn,kn]=j.useState(null),[Un,sn]=j.useState(""),un=!!((gl=nn==null?void 0:nn.team)!=null&&gl.lead_pond_enabled&&(nn!=null&&nn.teamId)),Ar=!!(nn!=null&&nn.teamId),[fs,ot]=j.useState([]),[mt,Nt]=j.useState(!1),Pt=ds=>{ot([ds]),Nt(!0)},ts=ds=>{ot(ds),Nt(!0)},ls=(ds,Gr)=>{nn!=null&&nn.teamId&&ds.forEach(ji=>{Zn.mutate({contact_id:ji,team_id:nn.teamId,pond_id:Gr||null})})},Is=ds=>{var Gr;if(nn!=null&&nn.teamId){if(ar.length>1){sn(ar[0].id),kn(ds);return}ls(ds,((Gr=ar[0])==null?void 0:Gr.id)||null)}},ps=ds=>Is([ds]),Ht=ds=>Is(ds),Xs=j.useCallback(ds=>{vt(!1),bt(Gr=>{const ji=new Set(Gr);return ji.has(ds)?ji.delete(ds):ji.add(ds),ji})},[]);j.useEffect(()=>{if(!(r!=null&&r.id))return;const ds=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(ds)}},[i,r==null?void 0:r.id]),j.useEffect(()=>{u&&ke(u)},[u]);const[Rs,zn]=j.useState({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]});j.useEffect(()=>{h&&Ue(!0)},[h]),j.useEffect(()=>{var ds;Ye&&zn({first_name:Ye.first_name||"",last_name:Ye.last_name||"",email:Ye.email||"",phone:Ye.phone||"",address:Ye.address||"",city:Ye.city||"",state:Ye.state||"",zip_code:Ye.zip_code||"",birthday:Ye.birthday||"",home_anniversary:Ye.home_anniversary||"",spouse_name:Ye.spouse_name||"",spouse_email:Ye.spouse_email||"",lead_source_id:Ye.lead_source_id||"",notes:Ye.notes||"",tagIds:((ds=Ye.tags)==null?void 0:ds.map(Gr=>Gr.relationship_type_id))||[]})},[Ye]);const Qr=j.useMemo(()=>{const ds=new Set;return N==null||N.forEach(Gr=>{(Gr.name==="Recruits"||Gr.name==="Brokerage Agents")&&ds.add(Gr.id)}),ds},[N]),ma=j.useMemo(()=>Array.from(H).some(ds=>Qr.has(ds)),[H,Qr]),qr=j.useMemo(()=>{const ds={};return(m||[]).forEach(Gr=>{ds[Gr.id]=`${Gr.first_name||""} ${Gr.last_name||""}`.trim()}),ds},[m]),Zr=j.useMemo(()=>{if(!m)return[];let ds=m.filter(ya=>{var fg,Lh,by,qo,bo,Ex,dp,up,gg,Vl,hp;const Wi=ya.synced_source;if(!ma&&(Wi==="recruit"||Wi==="brokerage_agent"))return!1;const di=ne===""||`${ya.first_name} ${ya.last_name}`.toLowerCase().includes(ne.toLowerCase())||((fg=ya.email)==null?void 0:fg.toLowerCase().includes(ne.toLowerCase()))||((Lh=ya.phone)==null?void 0:Lh.includes(ne))||((by=ya.city)==null?void 0:by.toLowerCase().includes(ne.toLowerCase()))||((qo=ya.state)==null?void 0:qo.toLowerCase().includes(ne.toLowerCase()))||((bo=ya.address)==null?void 0:bo.toLowerCase().includes(ne.toLowerCase()))||((Ex=ya.zip_code)==null?void 0:Ex.toLowerCase().includes(ne.toLowerCase())),Dc=be==="all"||((dp=ya.tags)==null?void 0:dp.some(Jd=>Jd.relationship_type_id===be)),fd=H.size===0||(()=>{const Jd=(S==null?void 0:S.filter(Mu=>Mu.contact_id===ya.id).map(Mu=>Mu.tag_id))||[];return K==="any"?Jd.some(Mu=>H.has(Mu)):Array.from(H).every(Mu=>Jd.includes(Mu))})(),Vp=!!((up=ya.address)!=null&&up.trim()||(gg=ya.city)!=null&&gg.trim()||(Vl=ya.state)!=null&&Vl.trim()||(hp=ya.zip_code)!=null&&hp.trim()),vy=Oe==="all"||Oe==="has-address"&&Vp||Oe==="no-address"&&!Vp,Jo=ya,il=Qe,Hp=(il.hasEmail===void 0||!!Jo.email===il.hasEmail)&&(il.hasPhone===void 0||!!Jo.phone===il.hasPhone)&&(il.hasAddress===void 0||Vp===il.hasAddress)&&(il.hasBirthday===void 0||!!Jo.birthday===il.hasBirthday)&&(il.hasSpouse===void 0||!!(Jo.spouse_name||Jo.spouse_contact_id||Jo.spouse_email)===il.hasSpouse)&&(il.hasCompany===void 0||!!(Jo.company_name||Jo.job_title)===il.hasCompany)&&(il.hasNotes===void 0||!!(Jo.notes&&Jo.notes.trim())===il.hasNotes)&&(!il.city||(Jo.city||"").toLowerCase().includes(il.city.toLowerCase()))&&(!il.state||(Jo.state||"").toLowerCase().includes(il.state.toLowerCase()))&&(!il.zip||((Jo.zip||"")+(Jo.zip_code||"")).toLowerCase().includes(il.zip.toLowerCase()))&&(!il.birthdayMonth||!!Jo.birthday&&Su(Jo.birthday).getMonth()+1===il.birthdayMonth)&&(!il.anniversaryMonth||((il.anniversaryField||"home_anniversary")==="home_anniversary"?!!Jo.home_anniversary&&Su(Jo.home_anniversary).getMonth()+1===il.anniversaryMonth:!!Jo.wedding_anniversary&&Su(Jo.wedding_anniversary).getMonth()+1===il.anniversaryMonth))&&(!il.dateAddedFrom||!!Jo.created_at&&Jo.created_at.slice(0,10)>=il.dateAddedFrom)&&(!il.dateAddedTo||!!Jo.created_at&&Jo.created_at.slice(0,10)<=il.dateAddedTo)&&(!il.leadSourceId||Jo.lead_source_id===il.leadSourceId||!Jo.lead_source_id&&il.leadSourceId==="none");return di&&Dc&&fd&&vy&&Hp});ge==="not-touched-90"?ds=ds.filter(ya=>{const Wi=ya.relationshipScore.daysSinceTouch;return Wi===null||Wi>90}):ge==="at-risk"?ds=ds.filter(ya=>ya.relationshipScore.status==="at-risk"):ge==="cooling"?ds=ds.filter(ya=>ya.relationshipScore.status==="cooling"):ge==="warm"?ds=ds.filter(ya=>ya.relationshipScore.status==="warm"):ge==="has-deal"?ds=ds.filter(ya=>b&&b[ya.id]):ge==="no-deal"?ds=ds.filter(ya=>!b||!b[ya.id]):ge==="open-house"?ds=ds.filter(ya=>{var wi;return(((wi=ya.lead_source_ref)==null?void 0:wi.name)||ya.lead_source)==="Open House"}):ge==="website-active"?ds=ds.filter(ya=>f.has(ya.id)):ge==="never-contacted"?ds=ds.filter(ya=>ya.relationshipScore.daysSinceTouch===null):ge==="vips"?ds=ds.filter(ya=>ya.relationshipScore.score>=80):ge==="missing-info"?ds=ds.filter(ya=>dWt(ya)):ge==="birthdays-soon"?ds=ds.filter(ya=>{const Wi=_D(ya.birthday);return Wi!==null&&Wi<=30}):ge==="anniversary-soon"?ds=ds.filter(ya=>{const Wi=_D(ya.home_anniversary);return Wi!==null&&Wi<=30}):ge==="in-drip"?ds=ds.filter(ya=>((y==null?void 0:y[ya.id])??0)>0):ge==="not-in-drip"?ds=ds.filter(ya=>((y==null?void 0:y[ya.id])??0)===0):ge==="active-buyers"?ds=ds.filter(ya=>M.has(ya.id)):ge==="missing-criteria"&&(ds=ds.filter(ya=>!M.has(ya.id)));const Gr=Qe;if(Gr.lastActive||Gr.registered||Gr.viewedListing||Gr.savedProperty||Gr.hasSavedSearch||Gr.requestedShowing||Gr.requestedValuation||Gr.websiteActiveOnly){const ya=Date.now(),Wi={today:24*60*60*1e3,"7d":7*24*60*60*1e3,"30d":30*24*60*60*1e3,"90d":90*24*60*60*1e3};ds=ds.filter(wi=>{const di=Ve.get(wi.id);if(Gr.lastActive==="never"){if(di!=null&&di.lastActiveAt)return!1}else if(Gr.lastActive){const Dc=ya-Wi[Gr.lastActive];if(!(di!=null&&di.lastActiveAt)||new Date(di.lastActiveAt).getTime()0)||Gr.viewedListing==="multiple7d"&&!(di&&di.propertyViewCount7d>=3)||Gr.savedProperty&&!(di&&di.savedListingCount>0)||Gr.hasSavedSearch&&!(di&&di.activeSavedSearchCount>0)||Gr.requestedShowing&&!(di&&di.showingRequests>0)||Gr.requestedValuation&&!(di&&di.valuationRequests>0)||Gr.websiteActiveOnly&&!f.has(wi.id))})}return ds=[...ds].sort((ya,Wi)=>{switch(Te){case"important-dates":{const wi=_D(ya.birthday),di=_D(Wi.birthday),Dc=_D(ya.home_anniversary),fd=_D(Wi.home_anniversary),Vp=[wi,Dc].filter(Jo=>Jo!==null).sort((Jo,il)=>(Jo??1/0)-(il??1/0))[0]??1/0,vy=[di,fd].filter(Jo=>Jo!==null).sort((Jo,il)=>(Jo??1/0)-(il??1/0))[0]??1/0;return Vp-vy}case"last-touched":{const wi=ya.relationshipScore.lastTouchDate,di=Wi.relationshipScore.lastTouchDate;return!wi&&!di?0:wi?di?new Date(wi).getTime()-new Date(di).getTime():1:-1}case"next-touch":{const wi=ya.relationshipScore.daysSinceTouch,di=Wi.relationshipScore.daysSinceTouch;return wi===null&&di===null?0:wi===null?-1:di===null?1:di-wi}case"score":return ya.relationshipScore.score-Wi.relationshipScore.score;case"date-added":{const wi=ya.created_at,di=Wi.created_at;return!wi&&!di?0:wi?di?new Date(di).getTime()-new Date(wi).getTime():-1:1}case"last-name":{const wi=(ya.last_name||"").toLowerCase(),di=(Wi.last_name||"").toLowerCase();if(wi!==di)return wi.localeCompare(di);const Dc=(ya.first_name||"").toLowerCase(),fd=(Wi.first_name||"").toLowerCase();return Dc.localeCompare(fd)}case"name":default:{const wi=`${ya.first_name||""} ${ya.last_name||""}`.toLowerCase(),di=`${Wi.first_name||""} ${Wi.last_name||""}`.toLowerCase();return wi.localeCompare(di)}}}),ds},[m,ne,be,H,K,ge,Te,b,S,f,y,Oe,Qe,Ve,ma,M]),Jr=Zr.length,ha=Math.max(1,Math.ceil(Jr/rn)),Fa=Math.min(on,ha),Fo=j.useMemo(()=>{const ds=(Fa-1)*rn;return Zr.slice(ds,ds+rn)},[Zr,Fa,rn]),Xo=j.useMemo(()=>{const ds=(m||[]).length;return{total:ds,label:ds===0?"Build your database — add or import your first contacts.":`${ds.toLocaleString()} ${ds===1?"person":"people"} in your database`}},[m]),Vi=j.useMemo(()=>{const ds=m||[],Gr=ds.filter(wi=>{var di;return((di=wi.relationshipScore)==null?void 0:di.status)==="at-risk"}).length,ji=ds.filter(wi=>{var Dc;const di=(Dc=wi.relationshipScore)==null?void 0:Dc.daysSinceTouch;return typeof di=="number"&&di<=7}).length,ya=new Date().getMonth()+1,Wi=ds.filter(wi=>wi.birthday?String(wi.birthday).split(/[-/T]/).map(Number)[1]===ya:!1).length;return[{label:"Total contacts",value:Xo.total.toLocaleString(),onClick:()=>{ke("all"),dn(1)},active:ge==="all"},{label:"Needs attention",value:Gr,onClick:()=>{ke("at-risk"),dn(1)},active:ge==="at-risk"},{label:"Touched this week",value:ji,onClick:()=>{ke("warm"),dn(1)},active:ge==="warm"},{label:"Birthdays this month",value:Wi,onClick:()=>{ke("birthdays-soon"),dn(1)},active:ge==="birthdays-soon"}]},[m,Xo.total,ge,dn]),Ja=j.useCallback(ds=>{const Gr=new URLSearchParams;ne&&Gr.set("search",ne),be!=="all"&&Gr.set("type",be),ge!=="all"&&Gr.set("filter",ge),H.size>0&&(Gr.set("tags",Array.from(H).join(",")),Gr.set("tagMode",K));const ji=Gr.toString();s(`/mission-control/contacts/${ds}${ji?`?${ji}`:""}`)},[s,ne,be,ge,H,K]),Co=j.useRef(!1);j.useEffect(()=>{if(!Co.current){Co.current=!0;return}dn(1)},[ne,be,H,K,ge,Te,Oe,Qe]);const Go=j.useCallback(()=>{vt(!1),bt(ds=>ds.size>0?new Set:new Set(Fo.map(Gr=>Gr.id)))},[Fo]),hi=j.useCallback(()=>{vt(!0),bt(new Set(Zr.map(ds=>ds.id)))},[Zr]),[Qo,Ao]=j.useState(null),_a=j.useCallback((ds,Gr)=>{ie(ds.search||""),he(ds.type||"all"),ke(ds.status||"all"),Ae(ds.behavior||{}),Me(Gr||"name")},[]),ir=()=>{zn({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]})},li=async ds=>{ds.preventDefault();const Gr={...Rs,lead_source_id:Rs.lead_source_id||null};Ye?(await le.mutateAsync({id:Ye.id,...Gr}),Ge(null)):(await Q.mutateAsync(Gr),Ue(!1)),ir()},Eo=async ds=>{await Yi("Are you sure you want to delete this contact?")&&await ue.mutateAsync(ds)};return e.jsx(qs,{title:"Contacts",description:"Manage your InnerCircle contacts",children:e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsx(o8n,{totalLabel:Xo.label,stats:Vi,search:ne,onSearchChange:ie,onAddContact:()=>Ue(!0),onImportCsv:()=>tt(!0),onImportPhone:()=>ft(!0),onManageTags:()=>cr(!0),onHeatMap:()=>je(!0),viewMode:Gn,onViewModeChange:ds=>On(ds),showTeamTab:!!nn&&(nn.team.contact_visibility==="full_team"||nn.team.contact_visibility==="leader_only"&&nn.role==="team_leader"),showLeadPondTab:!!(nn!=null&&nn.team.lead_pond_enabled),extraActions:e.jsxs(e.Fragment,{children:[e.jsxs(U,{variant:"secondary",size:"sm",className:"h-9 gap-1.5",onClick:()=>$(!0),children:[e.jsx(Fr,{className:"h-4 w-4"}),"Match a listing"]}),e.jsx(VLn,{})]})}),e.jsx(j8n,{open:z,onOpenChange:$,contacts:m||[]}),I&&e.jsx(_8n,{open:!!I,onOpenChange:ds=>{ds||R(null)},contactId:I.id,contactName:I.name,existing:(T==null?void 0:T[I.id])??null}),Gn==="team"?e.jsx(yet,{}):Gn==="lead-pond"&&nn?e.jsx(vet,{teamId:nn.teamId}):e.jsxs(e.Fragment,{children:[e.jsx(d8n,{contacts:m,contactDealsMap:b,websiteActiveIds:f,criteriaContactIds:M,totalCount:(m||[]).length,activeViewId:Qo,currentFilters:{search:ne,type:be,status:ge,behavior:Qe},currentSortBy:Te,onApplyView:(ds,Gr,ji)=>{Ao(ds),_a(Gr,ji),dn(1)},onClearAll:()=>{Ao(null),_a({search:"",type:"all",status:"all",behavior:{}},"name"),dn(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"}[ge]??null,onSelectSegment:ds=>{const ji=ds?{"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"}[ds]:"all";ke(ji),dn(1)}}),e.jsxs(we,{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(my,{children:[e.jsx($ne,{asChild:!0,children:e.jsxs(U,{variant:"outline",className:"h-10 flex-1 rounded-xl relative gap-2","aria-label":"Filters",children:[e.jsx(LM,{className:"h-4 w-4"}),"Filters & Views",(()=>{const ds=(be!=="all"?1:0)+(ge!=="all"?1:0)+(Oe!=="all"?1:0)+H.size+Fe;return ds>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:ds}):null})()]})}),e.jsxs(g0,{side:"bottom",className:"h-[85vh] rounded-t-2xl overflow-y-auto",children:[e.jsx(vv,{className:"text-left",children:e.jsx(bv,{children:"Filters & Views"})}),e.jsxs("div",{className:"space-y-5 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsxs(Ns,{value:be,onValueChange:he,children:[e.jsx(ws,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(ks,{placeholder:"All Types"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Types"}),v==null?void 0:v.filter(ds=>ds.active).map(ds=>e.jsx(et,{value:ds.id,children:ds.name},ds.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsxs(Ns,{value:ge,onValueChange:ke,children:[e.jsx(ws,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(ks,{placeholder:"All Status"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Status"}),e.jsx(et,{value:"warm",children:"🟢 Warm"}),e.jsx(et,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(et,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(et,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(et,{value:"no-deal",children:"📭 No Deal"}),e.jsx(et,{value:"open-house",children:"🏠 Open House"}),x&&e.jsx(et,{value:"website-active",children:"🌐 Website Active"}),e.jsx(et,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(et,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsxs(Ns,{value:Oe,onValueChange:ds=>Se(ds),children:[e.jsx(ws,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(ks,{placeholder:"All Addresses"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Addresses"}),e.jsx(et,{value:"has-address",children:"Has Address"}),e.jsx(et,{value:"no-address",children:"No Address"})]})]})]}),N&&N.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Tags"}),e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-md p-0.5",children:[e.jsx("button",{onClick:()=>Z("any"),className:`px-2 py-0.5 rounded text-xs font-medium ${K==="any"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>Z("all"),className:`px-2 py-0.5 rounded text-xs font-medium ${K==="all"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:N.map(ds=>{const Gr=H.has(ds.id);return e.jsxs("button",{onClick:()=>{V(ji=>{const ya=new Set(ji);return ya.has(ds.id)?ya.delete(ds.id):ya.add(ds.id),ya})},className:`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs border transition-colors ${Gr?"bg-primary text-primary-foreground border-primary":"bg-background border-border"}`,children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:ds.color}}),ds.name]},ds.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Sort by"}),e.jsxs(Ns,{value:Te,onValueChange:Me,children:[e.jsx(ws,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"name",children:"Name (A-Z)"}),e.jsx(et,{value:"last-name",children:"Last Name (A-Z)"}),e.jsx(et,{value:"important-dates",children:"Important Dates"}),e.jsx(et,{value:"last-touched",children:"Last Touched"}),e.jsx(et,{value:"next-touch",children:"Next Touch Due"}),e.jsx(et,{value:"score",children:"Relationship Score"}),e.jsx(et,{value:"date-added",children:"Date Added"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-2",children:[e.jsxs(U,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>$e(!0),children:[e.jsx(cn,{className:"h-4 w-4"})," Advanced"]}),e.jsxs(U,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>cr(!0),children:[e.jsx(Cf,{className:"h-4 w-4"})," Manage Tags"]})]}),e.jsx("div",{children:e.jsx(kwt,{currentFilters:{search:ne,type:be,status:ge,behavior:Qe},currentSortBy:Te,onApplySmartList:_a})}),e.jsx(U,{variant:"ghost",className:"w-full h-11 rounded-xl text-muted-foreground",onClick:()=>{he("all"),ke("all"),Se("all"),V(new Set),Ae({})},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:[Jr.toLocaleString()," ",Jr===1?"contact":"contacts"," shown"]}),e.jsxs(md,{children:[e.jsx(pd,{asChild:!0,children:e.jsx(U,{variant:"outline",size:"icon",className:"h-10 w-10 rounded-xl",title:"Sort contacts",children:e.jsx(sj,{className:"h-4 w-4"})})}),e.jsxs(id,{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(ds=>e.jsx("button",{onClick:()=>Me(ds.v),className:`w-full text-left px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors ${Te===ds.v?"bg-accent font-medium text-primary":""}`,children:ds.l},ds.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(Ns,{value:be,onValueChange:he,children:[e.jsx(ws,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(ks,{placeholder:"All Types"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Types"}),v==null?void 0:v.filter(ds=>ds.active).map(ds=>e.jsx(et,{value:ds.id,children:ds.name},ds.id))]})]}),e.jsxs(Ns,{value:ge,onValueChange:ke,children:[e.jsx(ws,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(ks,{placeholder:"All Status"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Status"}),e.jsx(et,{value:"warm",children:"🟢 Warm"}),e.jsx(et,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(et,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(et,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(et,{value:"no-deal",children:"📭 No Deal"}),e.jsx(et,{value:"open-house",children:"🏠 Open House"}),x&&e.jsx(et,{value:"website-active",children:"🌐 Website Active"}),e.jsx(et,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(et,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]}),e.jsxs(Ns,{value:Oe,onValueChange:ds=>Se(ds),children:[e.jsx(ws,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(ks,{placeholder:"All Addresses"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Addresses"}),e.jsx(et,{value:"has-address",children:"Has Address"}),e.jsx(et,{value:"no-address",children:"No Address"})]})]}),N&&N.length>0&&e.jsxs("div",{className:"inline-flex items-center bg-background border rounded-lg overflow-hidden h-8",children:[e.jsxs(md,{children:[e.jsx(pd,{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(Cf,{className:"h-3.5 w-3.5"}),H.size===0?"Filter by Tags":`${H.size} tag${H.size>1?"s":""}`]})}),e.jsx(id,{className:"w-60 p-3",align:"start",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Tags"}),e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-md p-0.5",children:[e.jsx("button",{onClick:()=>Z("any"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${K==="any"?"bg-background text-foreground shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>Z("all"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${K==="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:N.map(ds=>{const Gr=H.has(ds.id);return e.jsxs("button",{onClick:()=>{V(ji=>{const ya=new Set(ji);return ya.has(ds.id)?ya.delete(ds.id):ya.add(ds.id),ya})},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(xi,{checked:Gr,className:"pointer-events-none"}),e.jsx("div",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:ds.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:ds.name})]},ds.id)})}),H.size>0&&e.jsx(U,{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(Ku,{children:[e.jsx(Yu,{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(qc,{className:"h-3.5 w-3.5"})})}),e.jsxs(Eu,{align:"end",children:[e.jsxs(La,{onClick:()=>cr(!0),children:[e.jsx(Cf,{className:"h-4 w-4 mr-2"}),"Manage Tags"]}),e.jsxs(La,{onClick:()=>_r(!0),children:[e.jsx(cb,{className:"h-4 w-4 mr-2"}),"Manage Lead Sources"]})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kwt,{currentFilters:{search:ne,type:be,status:ge,behavior:Qe},currentSortBy:Te,onApplySmartList:_a}),e.jsx("div",{className:"h-5 w-px bg-border"}),e.jsxs(U,{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:()=>$e(!0),children:[e.jsx(cn,{className:"h-3.5 w-3.5"}),"Advanced Filters",Fe>0&&e.jsx(Be,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:Fe})]}),e.jsx(h8n,{columns:l,onToggle:o,onReset:c})]})]}),Fe>0&&e.jsx("div",{className:"px-3 sm:px-4 py-3 border-t bg-background",children:e.jsx(BIn,{behavior:Qe,onRemove:ds=>Ae(Gr=>{const ji={...Gr};return delete ji[ds],ji}),onClearAll:()=>Ae({})})})]}),e.jsx(zIn,{open:Ne,onOpenChange:$e,hasLeadSite:qe||x,behavior:Qe,onApply:Ae,selectedType:be,onSelectedTypeChange:he,relationshipTypes:v}),e.jsx(OIn,{selectedIds:zt,contacts:Zr,onClearSelection:()=>{bt(new Set),vt(!1)},showLeadPondAction:un,onSendToLeadPond:Ht,showTransferAction:Ar,onTransfer:ts}),zt.size>0&&zt.size===Fo.length&&!As&&Jr>rn&&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 ",Fo.length," contacts on this page are selected."]}),e.jsxs(U,{variant:"link",size:"sm",className:"h-auto p-0 font-semibold",onClick:hi,children:["Select all ",Jr.toLocaleString()," matching contacts"]})]}),As&&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 ",Jr.toLocaleString()," matching contacts are selected.",e.jsx(U,{variant:"link",size:"sm",className:"h-auto p-0",onClick:()=>{bt(new Set),vt(!1)},children:"Clear selection"})]}),Jr>rn&&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 ",(Fa-1)*rn+1,"–",Math.min(Fa*rn,Jr)," of ",Jr.toLocaleString()," contacts"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(U,{variant:"outline",size:"sm",disabled:Fa<=1,onClick:()=>dn(1),children:"First"}),e.jsx(U,{variant:"outline",size:"sm",disabled:Fa<=1,onClick:()=>dn(ds=>ds-1),children:e.jsx(rd,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",Fa," of ",ha]}),e.jsx(U,{variant:"outline",size:"sm",disabled:Fa>=ha,onClick:()=>dn(ds=>ds+1),children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx(U,{variant:"outline",size:"sm",disabled:Fa>=ha,onClick:()=>dn(ha),children:"Last"})]})]}),a?e.jsx("div",{className:"space-y-3",children:p?e.jsx(c8n,{}):Zr.length===0?e.jsx(we,{children:e.jsx(Iwt,{filtered:!!ne||be!=="all"||ge!=="all"||Oe!=="all"||H.size>0,onAdd:()=>Ue(!0),onImport:()=>tt(!0),onClearFilters:()=>{ie(""),he("all"),ke("all"),Se("all"),V(new Set),Ae({})}})}):Fo.map(ds=>{var ji,ya,Wi;const{relationshipScore:Gr}=ds;return e.jsx(we,{className:"cursor-pointer hover:bg-accent/50 transition-colors",onClick:()=>Ja(ds.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:[ds.first_name," ",ds.last_name]}),e.jsx(Ewt,{count:(y==null?void 0:y[ds.id])??0}),e.jsx(gi,{className:"h-4 w-4 text-muted-foreground shrink-0 ml-auto"})]}),e.jsxs("div",{className:"space-y-1 text-sm mb-3",children:[ds.email&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ln,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:ds.email})]}),ds.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ba,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:ds.phone})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mb-2",children:[e.jsx(ZHe,{score:Gr,size:"sm"}),e.jsx(wwt,{contact:ds}),(((ji=ds.lead_source_ref)==null?void 0:ji.name)||ds.lead_source)&&e.jsx(Be,{variant:"outline",className:"text-xs gap-1 border-primary/30 text-primary",children:((ya=ds.lead_source_ref)==null?void 0:ya.name)||ds.lead_source}),(Wi=ds.tags)==null?void 0:Wi.map(wi=>{var di;return e.jsx(Be,{variant:"secondary",className:"text-xs",children:(di=wi.relationship_type)==null?void 0:di.name},wi.id)}),e.jsx(Pwt,{contactId:ds.id,tags:S==null?void 0:S.filter(wi=>wi.contact_id===ds.id)}),e.jsx(Awt,{deal:b==null?void 0:b[ds.id]})]}),e.jsx("div",{className:"mb-2",children:e.jsx(zwt,{criteria:T==null?void 0:T[ds.id],onEdit:()=>R({id:ds.id,name:`${ds.first_name}${ds.last_name?" "+ds.last_name:""}`}),showAlertState:!!A,matchCount:L==null?void 0:L[ds.id],compact:!0})}),e.jsx(Cwt,{birthday:ds.birthday,homeAnniversary:ds.home_anniversary,weddingAnniversary:ds.wedding_anniversary,className:"mb-2",contactId:ds.id,contactName:`${ds.first_name}${ds.last_name?" "+ds.last_name:""}`,contactAddress:[ds.address,ds.city,ds.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[Gr.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Yr,{className:"h-3 w-3"}),Gs(new Date(Gr.lastTouchDate),"MMM d")]}):e.jsx("span",{className:"italic",children:"Never contacted"}),ds.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(pa,{className:"h-3 w-3"}),Gs(Su(ds.birthday),"MMM d")]}),ds.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ra,{className:"h-3 w-3"}),Gs(Su(ds.home_anniversary),"MMM d")]}),ds.created_at&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(an,{className:"h-3 w-3"}),"Added ",Gs(new Date(ds.created_at),"MMM d, yyyy")]})]})]}),e.jsx("div",{className:"ml-2",onClick:wi=>wi.stopPropagation(),children:e.jsx(Nwt,{contact:ds,onEdit:Ge,onDelete:Eo,onSnooze:(wi,di)=>{Ut(wi),us(di)},showLeadPondAction:un,onSendToLeadPond:ps,showTransferAction:Ar,onTransfer:Pt})})]})})},ds.id)})}):e.jsx(we,{children:e.jsx(Ie,{className:"p-0 overflow-x-auto",children:e.jsxs(Ya,{className:"min-w-[800px]",children:[e.jsx(Za,{className:"sticky top-0 z-10 bg-card/95 backdrop-blur supports-[backdrop-filter]:bg-card/80",children:e.jsxs(gn,{className:"hover:bg-transparent",children:[e.jsx(Lt,{className:"w-[40px]",children:e.jsx(xi,{checked:Fo.length>0&&Fo.every(ds=>zt.has(ds.id)),onCheckedChange:()=>Go()})}),e.jsx(Lt,{children:e.jsxs("button",{onClick:()=>Me(ds=>ds==="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",Te==="name"&&e.jsx(gi,{className:"h-3 w-3 rotate-90 text-primary"}),Te==="last-name"&&e.jsx(gi,{className:"h-3 w-3 -rotate-90 text-primary"})]})}),l.relationship&&e.jsx(Lt,{children:"Relationship"}),l.buyerCriteria&&e.jsx(Lt,{className:"min-w-[170px] whitespace-nowrap",children:"Looking For"}),l.stage&&e.jsx(Lt,{children:"Stage"}),l.leadSource&&e.jsx(Lt,{children:"Lead Source"}),l.tags&&e.jsx(Lt,{children:"Tags"}),l.lastTouch&&e.jsx(Lt,{children:"Last Touch"}),l.nextAction&&e.jsx(Lt,{children:"Next Action"}),l.dealValue&&e.jsx(Lt,{title:"Total value of deals linked to this contact in your pipeline",children:"Pipeline Value"}),l.email&&e.jsx(Lt,{children:"Email"}),l.phone&&e.jsx(Lt,{children:"Phone"}),l.address&&e.jsx(Lt,{children:"Address"}),l.birthday&&e.jsx(Lt,{children:"Birthday"}),e.jsx(Lt,{className:"w-[50px]"})]})}),e.jsx(Xa,{children:p?e.jsx(l8n,{columns:2+Object.values(l).filter(Boolean).length}):Zr.length===0?e.jsx(gn,{className:"hover:bg-transparent",children:e.jsx(gt,{colSpan:3+Object.values(l).filter(Boolean).length,className:"p-0",children:e.jsx(Iwt,{filtered:!!ne||be!=="all"||ge!=="all"||Oe!=="all"||H.size>0,onAdd:()=>Ue(!0),onImport:()=>tt(!0),onClearFilters:()=>{ie(""),he("all"),ke("all"),Se("all"),V(new Set),Ae({})}})})}):Fo.map(ds=>{var ya;const{relationshipScore:Gr}=ds,ji=b==null?void 0:b[ds.id];return e.jsxs(gn,{className:`group cursor-pointer border-border/60 transition-colors hover:bg-accent/40 [&>td]:py-3.5 ${zt.has(ds.id)?"bg-accent/30":""}`,onClick:()=>Ja(ds.id),children:[e.jsx(gt,{onClick:Wi=>Wi.stopPropagation(),children:e.jsx(xi,{checked:zt.has(ds.id),onCheckedChange:()=>Xs(ds.id)})}),e.jsx(gt,{className:"min-w-[220px]",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Jtt,{firstName:ds.first_name,lastName:ds.last_name,avatarUrl:ds.avatar_url,email:ds.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:[ds.first_name," ",ds.last_name]}),e.jsx(i8n,{linked:!!ds.spouse_contact_id||!!ds.spouse_name,spouseName:ds.spouse_contact_id&&qr[ds.spouse_contact_id]||ds.spouse_name||null}),e.jsx(Ewt,{count:(y==null?void 0:y[ds.id])??0})]}),ds.email&&!l.email&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:ds.email}),ds.phone&&!l.phone&&e.jsx("p",{className:"text-xs text-muted-foreground",children:ds.phone})]})]})}),l.relationship&&e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(s8n,{score:Gr.score,status:Gr.status}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:Gr.status==="warm"?"Strong":Gr.status==="cooling"?"Cooling":"At Risk"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Gr.daysSinceTouch===null?"Never contacted":Gr.daysSinceTouch===0?"Touched today":`${Gr.daysSinceTouch}d since touch`})]})]})}),l.buyerCriteria&&e.jsx(gt,{className:"min-w-[170px] max-w-[240px]",children:e.jsx(zwt,{criteria:T==null?void 0:T[ds.id],onEdit:()=>R({id:ds.id,name:`${ds.first_name}${ds.last_name?" "+ds.last_name:""}`}),showAlertState:!!A,matchCount:L==null?void 0:L[ds.id]})}),l.stage&&e.jsx(gt,{children:e.jsx(Awt,{deal:ji})}),l.leadSource&&e.jsx(gt,{className:"text-sm text-muted-foreground max-w-[160px] truncate",children:((ya=ds.lead_source_ref)==null?void 0:ya.name)||ds.lead_source||"—"}),l.tags&&e.jsx(gt,{children:e.jsx("div",{className:"flex flex-wrap items-center gap-1 max-w-[220px]",children:e.jsx(Pwt,{contactId:ds.id,tags:S==null?void 0:S.filter(Wi=>Wi.contact_id===ds.id)})})}),l.lastTouch&&e.jsx(gt,{children:Gr.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(Yr,{className:"h-3.5 w-3.5"}),Gs(new Date(Gr.lastTouchDate),"MMM d, yyyy")]}):e.jsx("span",{className:"text-xs italic text-muted-foreground",children:"No activity"})}),l.nextAction&&e.jsx(gt,{children:e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(wwt,{contact:ds}),e.jsx(Cwt,{birthday:ds.birthday,homeAnniversary:ds.home_anniversary,weddingAnniversary:ds.wedding_anniversary,contactId:ds.id,contactName:`${ds.first_name}${ds.last_name?" "+ds.last_name:""}`,contactAddress:[ds.address,ds.city,ds.state].filter(Boolean).join(", ")})]})}),l.dealValue&&e.jsx(gt,{children:(()=>{const Wi=(ji==null?void 0:ji.sale_price)??(ji==null?void 0:ji.expected_price);return Wi?e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:Uh(Number(Wi))}),(ji==null?void 0:ji.deal_type)&&e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:String(ji.deal_type).replace(/_/g," ")})]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})})()}),l.email&&e.jsx(gt,{className:"text-sm text-muted-foreground max-w-[220px] truncate",children:ds.email||"—"}),l.phone&&e.jsx(gt,{className:"text-sm text-muted-foreground whitespace-nowrap",children:ds.phone||"—"}),l.address&&e.jsx(gt,{className:"text-sm text-muted-foreground max-w-[220px] truncate",children:[ds.address,ds.city,ds.state].filter(Boolean).join(", ")||"—"}),l.birthday&&e.jsx(gt,{className:"text-sm text-muted-foreground whitespace-nowrap",children:ds.birthday?(()=>{const[Wi,wi,di]=String(ds.birthday).split(/[-/T]/).map(Number);return wi&&di?`${wi}/${di}${Wi&&Wi>1900?`/${Wi}`:""}`:"—"})():"—"}),e.jsx(gt,{onClick:Wi=>Wi.stopPropagation(),children:e.jsx(Nwt,{contact:ds,onEdit:Ge,onDelete:Eo,onSnooze:(Wi,wi)=>{Ut(Wi),us(wi)},showLeadPondAction:un,onSendToLeadPond:ps,showTransferAction:Ar,onTransfer:Pt})})]},ds.id)})})]})})}),Jr>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 ",(Fa-1)*rn+1,"–",Math.min(Fa*rn,Jr)," of ",Jr.toLocaleString()," contacts"]}),e.jsxs(Ns,{value:String(rn),onValueChange:ds=>{br(Number(ds)),dn(1)},children:[e.jsx(ws,{className:"w-[80px] h-8",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"50",children:"50"}),e.jsx(et,{value:"100",children:"100"}),e.jsx(et,{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(U,{variant:"outline",size:"sm",disabled:Fa<=1,onClick:()=>dn(1),children:"First"}),e.jsx(U,{variant:"outline",size:"sm",disabled:Fa<=1,onClick:()=>dn(ds=>ds-1),children:e.jsx(rd,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",Fa," of ",ha]}),e.jsx(U,{variant:"outline",size:"sm",disabled:Fa>=ha,onClick:()=>dn(ds=>ds+1),children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx(U,{variant:"outline",size:"sm",disabled:Fa>=ha,onClick:()=>dn(ha),children:"Last"})]})]}),e.jsx(zs,{open:Ze||!!Ye,onOpenChange:ds=>{ds||(Ue(!1),Ge(null),ir())},children:e.jsxs(Ds,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:Ye?"Edit Contact":"Add Contact"})}),e.jsxs("form",{onSubmit:li,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(te,{htmlFor:"first_name",children:"First Name *"}),e.jsx(xe,{id:"first_name",value:Rs.first_name,onChange:ds=>zn({...Rs,first_name:ds.target.value}),required:!0})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"last_name",children:"Last Name"}),e.jsx(xe,{id:"last_name",value:Rs.last_name,onChange:ds=>zn({...Rs,last_name:ds.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"email",children:"Email"}),e.jsx(xe,{id:"email",type:"email",value:Rs.email,onChange:ds=>zn({...Rs,email:ds.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"phone",children:"Phone"}),e.jsx(xe,{id:"phone",value:Rs.phone,onChange:ds=>zn({...Rs,phone:ds.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"address",children:"Address"}),e.jsx(xe,{id:"address",value:Rs.address,onChange:ds=>zn({...Rs,address:ds.target.value}),placeholder:"Street address"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(te,{htmlFor:"city",children:"City"}),e.jsx(xe,{id:"city",value:Rs.city,onChange:ds=>zn({...Rs,city:ds.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"state",children:"State"}),e.jsx(xe,{id:"state",value:Rs.state,onChange:ds=>zn({...Rs,state:ds.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"zip_code",children:"Zip"}),e.jsx(xe,{id:"zip_code",value:Rs.zip_code,onChange:ds=>zn({...Rs,zip_code:ds.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(te,{htmlFor:"birthday",children:"Birthday"}),e.jsx(xe,{id:"birthday",type:"date",value:Rs.birthday,onChange:ds=>zn({...Rs,birthday:ds.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(xe,{id:"home_anniversary",type:"date",value:Rs.home_anniversary,onChange:ds=>zn({...Rs,home_anniversary:ds.target.value})})]})]}),Ye&&e.jsx(XHe,{contactId:Ye.id,currentSpouseContactId:(Ye==null?void 0:Ye.spouse_contact_id)||null,currentSpouseName:(Ye==null?void 0:Ye.spouse_name)||null,currentSpouseEmail:(Ye==null?void 0:Ye.spouse_email)||null,onLink:ds=>se.mutate({contactId:Ye.id,spouseContactId:ds}),onUnlink:()=>se.mutate({contactId:Ye.id,spouseContactId:null}),isEditing:!0}),e.jsx(cWt,{value:Rs.lead_source_id,onChange:ds=>zn({...Rs,lead_source_id:ds})}),e.jsxs("div",{children:[e.jsx(te,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:v==null?void 0:v.filter(ds=>ds.active).map(ds=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(xi,{checked:Rs.tagIds.includes(ds.id),onCheckedChange:Gr=>{zn(Gr?{...Rs,tagIds:[...Rs.tagIds,ds.id]}:{...Rs,tagIds:Rs.tagIds.filter(ji=>ji!==ds.id)})}}),e.jsx("span",{className:"text-sm",children:ds.name})]},ds.id))})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"notes",children:"Notes"}),e.jsx(Fs,{id:"notes",value:Rs.notes,onChange:ds=>zn({...Rs,notes:ds.target.value}),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>{Ue(!1),Ge(null),ir()},children:"Cancel"}),e.jsxs(U,{type:"submit",disabled:Q.isPending||le.isPending,children:[Ye?"Update":"Create"," Contact"]})]})]})]})}),e.jsx(nIn,{open:He,onOpenChange:tt,relationshipTypes:(v==null?void 0:v.filter(ds=>ds.active))||[],onSuccess:()=>{tt(!1)}}),e.jsx(iIn,{open:pt,onOpenChange:ft,onComplete:()=>ft(!1)}),e.jsx(ULe,{open:!!qt,onOpenChange:ds=>{ds||Ut(null)},contactId:qt||"",contactName:Wt}),e.jsx(QIn,{open:Rr,onOpenChange:cr}),e.jsx(JIn,{open:Hs,onOpenChange:_r}),e.jsx(GIn,{open:ce,onOpenChange:je,contacts:m||[],onCitySelect:ds=>{ie(ds),dn(1)}}),e.jsx(oqt,{open:mt,onOpenChange:Nt,contactIds:fs,contactNames:fs.map(ds=>{const Gr=Zr.find(ji=>ji.id===ds);return Gr?`${Gr.first_name} ${Gr.last_name||""}`.trim():""}),onComplete:()=>{ot([]),bt(new Set),vt(!1)}}),e.jsx(zs,{open:!!Hn,onOpenChange:ds=>!ds&&kn(null),children:e.jsxs(Ds,{className:"sm:max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Choose a Lead Pond"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Sharing ",(Hn==null?void 0:Hn.length)||0," contact",((Hn==null?void 0:Hn.length)||0)===1?"":"s"," with your team."]}),e.jsxs(Ns,{value:Un,onValueChange:sn,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select a pond"})}),e.jsx(js,{children:ar.map(ds=>e.jsx(et,{value:ds.id,children:ds.name},ds.id))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(U,{variant:"outline",onClick:()=>kn(null),children:"Cancel"}),e.jsx(U,{onClick:()=>{Hn&&ls(Hn,Un),kn(null)},disabled:!Un,children:"Share to Pond"})]})]})]})})]})]})})}const k8n=5*1024*1024;function S8n({contactId:s,firstName:t,lastName:n,avatarUrl:r,email:a,size:i=88}){const l=j.useRef(null),o=Qt(),[c,d]=j.useState(!1),u=()=>{o.invalidateQueries({queryKey:["innercircle-contacts"]}),o.invalidateQueries({queryKey:["innercircle-contact"]}),o.invalidateQueries({queryKey:["contact",s]})},h=async f=>{const{error:x}=await q.from("innercircle_contacts").update({avatar_url:f}).eq("id",s);if(x)throw x;u()},m=async f=>{var x;if(!f.type.startsWith("image/")){ka({title:"Please choose an image file",variant:"destructive"});return}if(f.size>k8n){ka({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=(f.name.split(".").pop()||"jpg").toLowerCase(),N=`contacts/${v}/${s}-${Date.now()}.${b}`,{error:S}=await q.storage.from("avatars").upload(N,f,{upsert:!0,contentType:f.type});if(S)throw S;const{data:A}=q.storage.from("avatars").getPublicUrl(N);await h(A.publicUrl),ka({title:"Photo updated"})}catch(y){ka({title:"Upload failed",description:y.message,variant:"destructive"})}finally{d(!1),l.current&&(l.current.value="")}},p=async()=>{d(!0);try{await h(null),ka({title:"Photo removed"})}catch(f){ka({title:"Could not remove photo",description:f.message,variant:"destructive"})}finally{d(!1)}};return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>{var f;return(f=l.current)==null?void 0:f.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(Jtt,{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(Et,{className:"h-5 w-5 text-background animate-spin"}):e.jsx(_x,{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(Et,{className:"h-5 w-5 text-background animate-spin"})})]}),r&&e.jsxs(U,{variant:"ghost",size:"sm",className:"text-muted-foreground gap-1.5",onClick:p,disabled:c,children:[e.jsx(In,{className:"h-3.5 w-3.5"}),"Remove"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",className:"hidden",onChange:f=>{var y;const x=(y=f.target.files)==null?void 0:y[0];x&&m(x)}})]})}const C8n={job_title:"Job title",company_name:"Company",city:"City",state:"State",avatar_url:"Profile photo"},A8n=4e3,E8n=5*60*1e3;function T8n({open:s,onOpenChange:t,contactId:n,contactName:r,hasEmail:a}){var H;const{toast:i}=Ai(),l=Qt(),[o,c]=j.useState(""),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[p,f]=j.useState(null),[x,y]=j.useState(!1),[v,b]=j.useState(null),[N,S]=j.useState(null),[A,T]=j.useState(0),L=j.useRef(null),[M,I]=j.useState({job_title:!0,company_name:!0,city:!0,state:!0,avatar_url:!1});j.useEffect(()=>{if(!N||!s)return;L.current=Date.now(),T(0);let V=!1,K=null,Z=null;const Q=async()=>{if(!V)try{const{data:le,error:ue}=await q.functions.invoke("enrich-contact",{body:{contact_id:n,batch_id:N}});if(ue)throw ue;if((le==null?void 0:le.status)==="pending"){T(Date.now()-(L.current||Date.now()));return}le!=null&&le.ok&&le.found?(f(le.profile),b(le.matched_on??null),S(null)):(y(!0),S(null))}catch(le){i({title:"Enrichment status check failed",description:(le==null?void 0:le.message)??"Please try again.",variant:"destructive"}),S(null)}};return Q(),K=setInterval(Q,A8n),Z=setTimeout(()=>{V||(S(null),i({title:"Enrichment is taking longer than expected",description:"The provider has not finished processing yet. You can close this dialog and try again later.",variant:"default"}))},E8n),()=>{V=!0,K&&clearInterval(K),Z&&clearTimeout(Z)}},[N,s,n,i]);const R=async()=>{u(!0),y(!1),f(null),S(null);try{const{data:V,error:K}=await q.functions.invoke("enrich-contact",{body:{contact_id:n,linkedin_url:o.trim()||void 0}});if(K)throw K;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}f(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)}},z=()=>{if(!p)return[];const V=[];return p.job_title&&V.push({key:"job_title",value:p.job_title}),p.company_name&&V.push({key:"company_name",value:p.company_name}),p.city&&V.push({key:"city",value:p.city}),p.state&&V.push({key:"state",value:p.state}),p.photo_url&&V.push({key:"avatar_url",value:p.photo_url}),V},$=async()=>{const V={};for(const K of z())M[K.key]&&(V[K.key==="avatar_url"?"avatar_url":K.key]=K.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:K}=await q.from("innercircle_contacts").update(V).eq("id",n);if(K)throw K;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(K){i({title:"Could not save",description:(K==null?void 0:K.message)??"Please try again.",variant:"destructive"})}finally{m(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(cn,{className:"h-4 w-4 text-primary"}),"Enrich ",r]}),e.jsx(Pr,{children:"Look up public professional details for this contact and choose what to save."})]}),e.jsxs("div",{className:"space-y-4",children:[!p&&!N&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"li-url",children:"LinkedIn URL (optional)"}),e.jsx(xe,{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."})]}),N&&e.jsxs("div",{className:"rounded-lg border border-dashed p-4 text-sm text-center space-y-2",children:[e.jsx(Et,{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."}),p&&e.jsx(Gi,{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:[p.photo_url&&e.jsx("img",{src:p.photo_url,alt:p.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:p.full_name||r}),v&&e.jsxs(Be,{variant:"secondary",className:"text-[10px]",children:["matched via ",v]})]}),p.headline&&e.jsx("p",{className:"text-sm text-muted-foreground",children:p.headline}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-3 text-xs text-muted-foreground",children:[p.company_name&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(_i,{className:"h-3 w-3"}),p.company_name]}),p.location&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ni,{className:"h-3 w-3"}),p.location]}),p.industry&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(og,{className:"h-3 w-3"}),p.industry]})]}),p.linkedin_url&&e.jsxs("a",{href:p.linkedin_url,target:"_blank",rel:"noreferrer",className:"mt-2 inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Gg,{className:"h-3 w-3"})," LinkedIn ",e.jsx(Sr,{className:"h-3 w-3"})]})]})]}),p.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-line",children:p.summary}),!!((H=p.experience)!=null&&H.length)&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Experience"}),p.experience.map((V,K)=>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]},K))]}),z().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"}),z().map(V=>e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx(xi,{checked:M[V.key],onCheckedChange:K=>I(Z=>({...Z,[V.key]:K===!0}))}),e.jsxs("span",{className:"min-w-0",children:[e.jsxs("span",{className:"font-medium",children:[C8n[V.key],": "]}),e.jsx("span",{className:"text-muted-foreground break-all",children:V.value})]})]},V.key))]})]})})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Close"}),!p&&!N?e.jsxs(U,{onClick:R,disabled:d,children:[d?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(cn,{className:"h-4 w-4 mr-2"}),d?"Searching…":"Find profile"]}):N?e.jsxs(U,{disabled:!0,children:[e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Searching…"]}):e.jsxs(U,{onClick:$,disabled:h,children:[h&&e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Save selected"]})]})]})})}const M8n=["jeremy@relevelup.com"];function P8n(){const{user:s}=vs(),t=((s==null?void 0:s.email)||"").toLowerCase();return M8n.includes(t)}const Uwt="America/New_York";function L8n(s){const t=new Date(s),n=new Intl.DateTimeFormat("en-US",{timeZone:Uwt,month:"short",day:"numeric",year:"numeric"}).format(t),r=new Intl.DateTimeFormat("en-US",{timeZone:Uwt,hour:"numeric",minute:"2-digit"}).format(t);return`${n} · ${r}`}function I8n(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 R8n({contactId:s,ownerUserId:t,legacyNote:n}){const r=Qt(),[a,i]=j.useState(""),{data:l=[],isLoading:o}=ct({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=yt({mutationFn:async u=>{var x,y,v;const{data:h}=await q.auth.getUser(),m=h.user,p=((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:f}=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:p,source:"agent",body:u});if(f)throw f},onSuccess:()=>{i(""),r.invalidateQueries({queryKey:["contact-notes",s]}),ka({title:"Note added"})},onError:u=>ka({title:"Could not add note",description:u.message,variant:"destructive"})}),d=yt({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(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ki,{className:"h-4 w-4 text-primary"}),"Notes",l.length>0&&e.jsx(Be,{variant:"secondary",className:"ml-1 rounded-full text-[11px]",children:l.length})]})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Fs,{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(U,{size:"sm",disabled:!a.trim()||c.isPending,onClick:()=>c.mutate(a.trim()),children:[c.isPending?e.jsx(Et,{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(Yr,{className:"h-3 w-3"}),L8n(u.created_at)]}),e.jsxs("span",{children:["· ",I8n(u.created_at)]}),u.source!=="agent"?e.jsxs(Be,{variant:"outline",className:"gap-1 text-[10px]",children:[e.jsx(cn,{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(In,{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 D8n="9a88a47c-cb2a-4401-a2b5-111a76b19f9d";function O8n({open:s,onOpenChange:t,contact:n}){var H;const{user:r}=vs(),a=Wn(),i=Qt(),{intakePage:l,isLoading:o}=rPe(),{isGmailConnected:c,gmailEmail:d}=Ax(),u=tPe(),{data:h}=ct({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)||((H=r==null?void 0:r.email)==null?void 0:H.split("@")[0])||"Your Agent",p=m.split(" ")[0],f=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,N]=j.useState(""),[S,A]=j.useState(""),[T,L]=j.useState(!1);j.useEffect(()=>{s&&(N(`Quick favor, ${n.first_name} — can you update your info?`),A(x),v(c?"gmail":"system"))},[s,x,n.first_name,c]);const M=j.useMemo(()=>S.split(/\n\n+/).map(V=>`

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

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

A note from ${m}

${M}

Update Your Info

Takes about a minute — promise

Share My Info →

${V}

Sent with care by ${m}

Powered by ReLevelUp

`,z=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}L(!0);const V=await I(),K=R(V),Z=async()=>{const{data:Q,error:le}=await q.functions.invoke("send-connect-invite",{body:{contactEmail:n.email,subject:b,htmlBody:K,replyToEmail:(h==null?void 0:h.email)||(r==null?void 0:r.email),agentName:m}});if(le)throw le;if(!(Q!=null&&Q.success))throw new Error((Q==null?void 0:Q.error)||"Failed to send")};try{if(y==="gmail"&&c){const{data:Q,error:le}=await q.functions.invoke("gmail-send",{body:{to:n.email,subject:b,body:K,contactId:n.id}});let ue=Q&&Q.error?Q:null;if(le){ue={error:"send_failed",message:le.message};const se=le.context;if(se&&typeof se.json=="function")try{ue=await se.clone().json()}catch{}}if(ue)if(ue.error==="insufficient_scope")await Z(),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(ue.message||ue.error||"Failed to send");else if(!(Q!=null&&Q.success))throw new Error("Failed to send")}else await Z();try{await u.mutateAsync({contactId:n.id,actionTypeId:D8n,notes:`Sent Connect Page invite — Subject: "${b}"`})}catch(Q){console.warn("Failed to log activity:",Q)}i.invalidateQueries({queryKey:["contact-touch-logs"]}),re.success("Connect Page invite sent!"),t(!1)}catch(Q){console.error("Send error:",Q),re.error(Q instanceof Error?Q.message:"Failed to send invite")}finally{L(!1)}},$=S.split(/\n\n+/).filter(Boolean);return e.jsx(zs,{open:s,onOpenChange:V=>!T&&t(V),children:e.jsxs(Ds,{className:"sm:max-w-[720px] max-h-[92vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(cn,{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(Et,{className:"h-6 w-6 animate-spin text-primary"})}):l?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Send From"}),e.jsx(oa,{value:y,onValueChange:V=>v(V),className:"mt-1.5",children:e.jsxs(la,{className:"grid w-full grid-cols-2",children:[e.jsxs(Kt,{value:"gmail",disabled:!c,children:[e.jsx(ln,{className:"h-3.5 w-3.5 mr-1.5"}),c?`Gmail (${d})`:"Gmail (not connected)"]}),e.jsxs(Kt,{value:"system",children:[e.jsx(cn,{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(te,{htmlFor:"invite-subject",children:"Subject"}),e.jsx(xe,{id:"invite-subject",value:b,onChange:V=>N(V.target.value),className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"invite-message",children:"Personal Message"}),e.jsx(Fs,{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(te,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Preview"}),e.jsxs("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:["Open Connect Page ",e.jsx(Sr,{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:p.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:$.map((V,K)=>e.jsx("p",{className:"text-[13px] leading-relaxed text-slate-600 whitespace-pre-line",children:V},K))}),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:[f,"?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(U,{variant:"outline",onClick:()=>t(!1),disabled:T,children:"Cancel"}),e.jsx(U,{onClick:z,disabled:T,children:T?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-1.5 animate-spin"})," Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx($r,{className:"h-4 w-4 mr-1.5"})," Send Invite"]})})]})]}):e.jsxs("div",{className:"space-y-4 py-6 text-center",children:[e.jsx(Vo,{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(U,{onClick:()=>a("/mission-control/connect-page"),children:[e.jsx(ad,{className:"h-4 w-4 mr-1"})," Set Up Connect Page"]})]})]})})}function F8n(){const{user:s}=vs();return ct({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 z8n(s){return ct({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 B8n(s){return ct({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 fWt(){const s=Qt(),{user:t}=vs(),{leadSite:n}=$p();return yt({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 U8n(){const s=Qt();return yt({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 q8n(){const s=Qt();return yt({mutationFn:async t=>{const{error:n}=await q.from("cmas").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["cmas"]})})}function $8n(){const{leadSite:s}=$p();return yt({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 V8n(){const{leadSite:s}=$p();return yt({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 H8n(){const s=Qt();return yt({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 qwt(s,t){const n=t.filter(h=>{var m,p;return h.selected!==!1&&(((m=h.snapshot)==null?void 0:m.sqft)||h.sqft)&&(((p=h.snapshot)==null?void 0:p.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 G8n(s){return ct({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 W8n(s){return ct({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 est(){const s=Sa(),t=Qt();return yt({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 eW(){const s=Qt();return yt({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 gWt(){const s=Qt();return yt({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 xWt(){const s=Qt();return yt({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 yWt(){const s=Qt();return yt({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 K8n(s){return ct({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 vWt(){const s=Qt();return yt({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 Y8n(){const s=Sa();return ct({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 Z8n(){const s=Sa(),t=Qt();return yt({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 X8n(){const s=Qt();return yt({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 Q8n(){const s=Qt();return yt({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 lS(s){const t=window.location.hostname;return t==="localhost"||t.includes("lovable.app")?`${window.location.origin}/portal/${s}`:`https://clients.relevelup.com/${s}`}function J8n({contactId:s}){const t=Wn(),n=Qt(),[r,a]=j.useState(null),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,f]=j.useState(null),x=eW(),y=vWt(),{data:v,isLoading:b}=ct({queryKey:["contact-portals",s],queryFn:async()=>{const{data:M,error:I}=await q.from("deal_pipeline").select("id, deal_name, deal_type").eq("contact_id",s);if(I)throw I;if(!M||M.length===0)return[];const R=M.map(H=>H.id),{data:z,error:$}=await q.from("client_portals").select("*").in("deal_id",R).is("archived_at",null);if($)throw $;return(z||[]).map(H=>({...H,deal:M.find(V=>V.id===H.deal_id)}))},enabled:!!s}),N=(v==null?void 0:v.map(M=>M.id))||[],{data:S}=ct({queryKey:["contact-portal-updates",N],queryFn:async()=>{if(N.length===0)return{};const{data:M,error:I}=await q.from("portal_updates").select("*").in("portal_id",N).order("created_at",{ascending:!1});if(I)throw I;const R={};return(M||[]).forEach(z=>{R[z.portal_id]||(R[z.portal_id]=z)}),R},enabled:N.length>0}),A=M=>{navigator.clipboard.writeText(lS(M)),a(M),re.success("Portal link copied!"),setTimeout(()=>a(null),2e3)},T=async(M,I)=>{if(!d.trim())return;const R=d.trim(),z=h.trim();await y.mutateAsync({portal_id:M,title:R,content:z||void 0}),c(!1),u(""),m(""),n.invalidateQueries({queryKey:["contact-portal-updates"]});try{const{data:$,error:H}=await q.functions.invoke("send-portal-notification",{body:{portal_id:M,update_title:R,update_content:z||null,portal_url:I?lS(I):void 0,force:!0}});if(H)throw H;$!=null&&$.emailSent?re.success("Update posted & client emailed"):re.success(`Update posted (${($==null?void 0:$.reason)||"no email sent"})`)}catch($){console.error("Portal notification failed:",$),re.success("Update posted (notification failed to send)")}},L=async()=>{p&&(await x.mutateAsync({id:p.id,welcome_message:p.welcome_message,next_step_text:p.next_step_text,is_enabled:p.is_enabled,show_post_close_tips:p.show_post_close_tips,review_url:p.review_url}),l(!1),f(null),n.invalidateQueries({queryKey:["contact-portals",s]}),re.success("Portal settings updated!"))};return b||!v||v.length===0?null:e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(fl,{className:"h-4 w-4"}),"Client Portal"]})}),e.jsx(Ie,{className:"space-y-3",children:v.map(M=>{var $,H,V;const I=(($=M.stage_mapping)==null?void 0:$.length)>0?M.stage_mapping:RMe(((H=M.deal)==null?void 0:H.deal_type)||"buyer"),R=I==null?void 0:I[M.current_stage_index??0],z=S==null?void 0:S[M.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=M.deal)==null?void 0:V.deal_name)||"Portal"}),R&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Stage: ",R.label||R.name]})]}),e.jsx(Be,{variant:M.is_enabled?"default":"secondary",className:"text-[10px] flex-shrink-0",children:M.is_enabled?"Active":"Disabled"})]}),z&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-2",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:z.title}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Gs(new Date(z.created_at),"MMM d, yyyy")})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsxs(U,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>A(M.slug),children:[r===M.slug?e.jsx(Xr,{className:"h-3 w-3 mr-1"}):e.jsx(Pa,{className:"h-3 w-3 mr-1"}),"Copy Link"]}),e.jsxs(U,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>window.open(lS(M.slug),"_blank"),children:[e.jsx(Sr,{className:"h-3 w-3 mr-1"}),"View"]}),e.jsxs(zs,{open:o,onOpenChange:c,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>c(!0),children:[e.jsx(Ki,{className:"h-3 w-3 mr-1"}),"Post Update"]})}),e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Title"}),e.jsx(xe,{value:d,onChange:K=>u(K.target.value),placeholder:"e.g. Inspection completed!"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Details (optional)"}),e.jsx(Fs,{value:h,onChange:K=>m(K.target.value),placeholder:"Add more details...",rows:3})]}),e.jsxs(U,{onClick:()=>T(M.id,M.slug),disabled:!d.trim()||y.isPending,className:"w-full",children:[e.jsx($r,{className:"h-4 w-4 mr-1"}),"Post Update"]})]})]})]}),e.jsxs(zs,{open:i,onOpenChange:l,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>{f({...M}),l(!0)},children:[e.jsx(qc,{className:"h-3 w-3 mr-1"}),"Settings"]})}),e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Portal Settings"})}),p&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{children:"Portal Enabled"}),e.jsx(wn,{checked:p.is_enabled,onCheckedChange:K=>f({...p,is_enabled:K})})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Welcome Message"}),e.jsx(Fs,{value:p.welcome_message||"",onChange:K=>f({...p,welcome_message:K.target.value}),placeholder:"Welcome to your home journey!",rows:2})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Next Step"}),e.jsx(xe,{value:p.next_step_text||"",onChange:K=>f({...p,next_step_text:K.target.value}),placeholder:"What your client should do next..."})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Review URL"}),e.jsx(xe,{value:p.review_url||"",onChange:K=>f({...p,review_url:K.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{children:"Show Post-Close Tips"}),e.jsx(wn,{checked:p.show_post_close_tips,onCheckedChange:K=>f({...p,show_post_close_tips:K})})]}),e.jsx(hc,{}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{onClick:L,disabled:x.isPending,className:"flex-1",children:"Save Settings"}),e.jsxs(U,{variant:"outline",onClick:()=>t(`/mission-control/pipeline?deal=${M.deal_id}`),children:[e.jsx(Oa,{className:"h-4 w-4 mr-1"}),"Full Settings"]})]})]})]})]})]}),v.length>1&&e.jsx(hc,{})]},M.id)})})]})}function eRn({contactId:s}){const{data:t}=ct({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}=ct({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(we,{className:"overflow-hidden",children:[e.jsx(Tt,{className:"pb-2",children:e.jsxs(It,{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(xa,{className:"h-4 w-4 text-primary"})}),"Property Activity",e.jsxs(Be,{variant:"secondary",className:"text-xs ml-auto",children:[r.length," ",r.length===1?"property":"properties"]})]})}),e.jsx(Ie,{className:"pt-0",children:e.jsx("div",{className:"space-y-1",children:r.map(l=>{const o=i(l),c=l.property_address||`MLS# ${l.mls_number}`;return e.jsxs("a",{href:o||"#",target:"_blank",rel:"noopener noreferrer",onClick:d=>{o||d.preventDefault()},className:"group flex items-center gap-3 p-2.5 rounded-lg hover:bg-muted/60 transition-colors",children:[l.photo_url?e.jsx("div",{className:"h-10 w-10 rounded-lg overflow-hidden flex-shrink-0 bg-muted",children:e.jsx("img",{src:l.photo_url,alt:c,className:"w-full h-full object-cover"})}):e.jsx("div",{className:"h-9 w-9 rounded-lg bg-gradient-to-br from-primary/15 to-primary/5 flex items-center justify-center flex-shrink-0",children:e.jsx(ra,{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(Yr,{className:"h-3 w-3"}),e.jsx("span",{title:Gs(new Date(l.viewed_at),"PPp"),children:Nd(new Date(l.viewed_at),{addSuffix:!0})})]})]}),o&&e.jsx(Sr,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]},l.mls_number)})})})]})}function tRn({contactId:s,contactName:t}){var z,$,H;const{user:n}=vs(),r=Sa(),{hasIdx:a}=$p(),i=Qt(),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,p]=j.useState(null),[f,x]=j.useState(!1),[y,v]=j.useState(!1),{data:b,isLoading:N}=ct({queryKey:["contact-property-alert",s],queryFn:async()=>{const{data:V,error:K}=await q.from("contact_property_alerts").select("*").eq("contact_id",s).maybeSingle();if(K)throw K;return V},enabled:!!s&&!!n}),[S,A]=j.useState({}),T=()=>{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)},L=yt({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:K}=await q.from("contact_property_alerts").update(V).eq("id",b.id);if(K)throw K}else{const{error:K}=await q.from("contact_property_alerts").insert(V);if(K)throw K}},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")}}),M=yt({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")}}),I=async()=>{if(b!=null&&b.id){x(!0),d(!0),h(""),p(null);try{const{data:V,error:K}=await q.functions.invoke("process-property-alerts",{body:{alert_id:b.id,mode:"preview"}});if(K)throw K;V!=null&&V.html?(h(V.html),p({count:V.listings_count||0,recipient:V.recipient,subject:V.subject})):p({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)}}},R=async()=>{if(b!=null&&b.id&&await Yi(`Send property alert email to ${t} now?`)){v(!0);try{const{data:V,error:K}=await q.functions.invoke("process-property-alerts",{body:{alert_id:b.id,mode:"send"}});if(K)throw K;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 N?null:b&&!l?e.jsxs(e.Fragment,{children:[e.jsxs(we,{className:"overflow-hidden",children:[e.jsx(Tt,{className:"pb-2",children:e.jsxs(It,{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(bx,{className:"h-4 w-4 text-green-600"}):e.jsx(Zk,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Fr,{className:"h-4 w-4 text-muted-foreground"})}),a?"Property Alerts":"Home Search",a&&e.jsxs(Be,{variant:b.is_active?"default":"secondary",className:"text-xs ml-auto",children:[b.is_active?"Active":"Paused"," · ",b.frequency]})]})}),e.jsxs(Ie,{className:"pt-0 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 text-xs",children:[b.min_price||b.max_price?e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(yu,{className:"h-3 w-3"}),b.min_price?`$${(b.min_price/1e3).toFixed(0)}k`:"$0"," - ",b.max_price?`$${(b.max_price/1e3).toFixed(0)}k`:"Any"]}):null,b.min_beds?e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(C4,{className:"h-3 w-3"}),b.min_beds,"+ beds"]}):null,b.min_baths?e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(d0,{className:"h-3 w-3"}),b.min_baths,"+ baths"]}):null,(z=b.cities)==null?void 0:z.map(V=>e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(ni,{className:"h-3 w-3"}),V]},V)),($=b.zip_codes)==null?void 0:$.map(V=>e.jsx(Be,{variant:"outline",children:V},V)),(H=b.property_types)==null?void 0:H.map(V=>e.jsx(Be,{variant:"outline",children:V},V))]}),a&&b.last_sent_at&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sent: ",new Date(b.last_sent_at).toLocaleDateString()]}),!a&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Automatic new-listing emails need an IDX website —"," ",e.jsx(xr,{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(U,{variant:"outline",size:"sm",onClick:I,disabled:f,children:[f?e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(xa,{className:"h-4 w-4 mr-1"}),"Preview Email"]}),e.jsxs(U,{size:"sm",onClick:R,disabled:y||!b.is_active,title:b.is_active?"Send this alert email now":"Activate alert to send",children:[y?e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx($r,{className:"h-4 w-4 mr-1"}),"Send Now"]})]}),e.jsx(U,{variant:"outline",size:"sm",onClick:T,children:"Edit Search"}),e.jsxs(U,{variant:"destructive",size:"sm",onClick:()=>M.mutate(),disabled:M.isPending,children:[M.isPending?e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(er,{className:"h-4 w-4 mr-1"}),"Remove"]})]})]})]}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Ds,{className:"max-w-3xl max-h-[90vh] flex flex-col",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Property Alert Email Preview"}),(m==null?void 0:m.subject)&&e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5 pt-1",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"To:"})," ",m.recipient]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Subject:"})," ",m.subject]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Listings:"})," ",m.count]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden border rounded-md bg-muted/30",children:f?e.jsxs("div",{className:"flex items-center justify-center h-96 text-muted-foreground",children:[e.jsx(Et,{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(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>d(!1),children:"Close"}),u&&e.jsxs(U,{onClick:()=>{d(!1),R()},disabled:y||!b.is_active,children:[e.jsx($r,{className:"h-4 w-4 mr-1"}),"Send to ",t]})]})]})})]}):l?e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[a?e.jsx(bx,{className:"h-4 w-4 text-primary"}):e.jsx(Fr,{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(pWt,{value:S,onChange:A,hasIdx:a,idxNote:e.jsx(U,{asChild:!0,variant:"link",size:"sm",className:"h-auto p-0 text-xs",children:e.jsx(xr,{to:"/mission-control/website",children:"Explore IDX websites"})})}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(U,{onClick:()=>L.mutate(),disabled:L.isPending,className:"flex-1",children:[L.isPending?e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-1"}),"Save"]}),e.jsx(U,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),b&&e.jsx(U,{variant:"destructive",size:"icon",onClick:()=>M.mutate(),disabled:M.isPending,children:e.jsx(er,{className:"h-4 w-4"})})]})]})]}):e.jsx(we,{className:"overflow-hidden",children:e.jsx(Ie,{className:"p-4",children:e.jsxs("button",{onClick:T,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(bx,{className:"h-4 w-4 text-primary"}):e.jsx(Fr,{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 sRn({contactId:s,contactName:t}){var Z;const{user:n}=vs(),r=Sa(),{hasLeadSite:a}=$p(),i=Qt(),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState([]),[m,p]=j.useState(!1),[f,x]=j.useState(!1),[y,v]=j.useState(!1),[b,N]=j.useState(""),S=j.useRef(null),A=j.useRef(null),{data:T}=ct({queryKey:["agent-lead-site-cities",r],queryFn:async()=>{const{data:Q,error:le}=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(le||!Q)return[];const ue=Q.theme_config||{},se=Array.isArray(ue.searchCities)?ue.searchCities:[];return Q.mls_market_area&&!se.includes(Q.mls_market_area)&&se.unshift(Q.mls_market_area),se},enabled:!!r}),{data:L,isLoading:M}=ct({queryKey:["contact-market-report",s],queryFn:async()=>{const{data:Q,error:le}=await q.from("innercircle_contacts").select("market_report_enabled, market_report_cities").eq("id",s).single();if(le)throw le;return Q},enabled:!!s&&!!n});j.useEffect(()=>{const Q=le=>{A.current&&!A.current.contains(le.target)&&S.current&&!S.current.contains(le.target)&&x(!1)};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[]);const I=()=>{p((L==null?void 0:L.market_report_enabled)??!1),h((L==null?void 0:L.market_report_cities)??[]),o(!0)},R=Q=>{const le=(Q||c).trim();le&&!u.includes(le)&&h([...u,le]),d(""),x(!1)},z=(T||[]).filter(Q=>!u.includes(Q)&&Q.toLowerCase().includes(c.toLowerCase())),$=yt({mutationFn:async()=>{const{data:Q,error:le}=await q.functions.invoke("send-market-report",{body:{action:"preview",agentId:r,cities:(L==null?void 0:L.market_report_cities)??[]}});if(le)throw new Error(le.message||"Failed to generate preview");if(Q&&!Q.ok&&Q.error)throw new Error(Q.error);return Q},onSuccess:Q=>{N(Q.html),v(!0)},onError:Q=>{re.error(Q.message||"Failed to generate preview")}}),H=yt({mutationFn:async()=>{const{data:Q,error:le}=await q.functions.invoke("send-market-report",{body:{action:"send",agentId:r,cities:(L==null?void 0:L.market_report_cities)??[],contactIds:[s]}});if(le)throw new Error(le.message||"Failed to send report");if(Q&&!Q.ok&&Q.error)throw new Error(Q.error);return Q},onSuccess:()=>{re.success(`Market report sent to ${t}!`)},onError:Q=>{re.error(Q.message||"Failed to send report")}}),V=yt({mutationFn:async()=>{const{error:Q}=await q.from("innercircle_contacts").update({market_report_enabled:m,market_report_cities:u}).eq("id",s);if(Q)throw Q},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),re.success(m?"Monthly market report enabled!":"Market report disabled")},onError:Q=>{re.error(Q.message||"Failed to save")}}),K=yt({mutationFn:async()=>{const{error:Q}=await q.from("innercircle_contacts").update({market_report_enabled:!1,market_report_cities:[]}).eq("id",s);if(Q)throw Q},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),p(!1),h([]),re.success("Market report removed")},onError:Q=>{re.error(Q.message||"Failed to remove market report")}});return!a||M?null:L!=null&&L.market_report_enabled&&!l?e.jsxs(we,{className:"overflow-hidden",children:[e.jsx(Tt,{className:"pb-2",children:e.jsxs(It,{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(Cl,{className:"h-4 w-4 text-primary"})}),"Monthly Market Report",e.jsx(Be,{variant:"default",className:"text-xs ml-auto",children:"Active"})]})}),e.jsxs(Ie,{className:"pt-0 space-y-2",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5 text-xs",children:((Z=L.market_report_cities)==null?void 0:Z.length)>0?L.market_report_cities.map(Q=>e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(ni,{className:"h-3 w-3"}),Q]},Q)):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(U,{variant:"outline",size:"sm",onClick:()=>$.mutate(),disabled:$.isPending,className:"flex-1",children:[$.isPending?e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(xa,{className:"h-4 w-4 mr-1"}),"Preview"]}),e.jsxs(U,{variant:"default",size:"sm",onClick:()=>H.mutate(),disabled:H.isPending,className:"flex-1",children:[H.isPending?e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx($r,{className:"h-4 w-4 mr-1"}),"Send Now"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{variant:"outline",size:"sm",onClick:I,className:"flex-1",children:"Manage"}),e.jsxs(U,{variant:"destructive",size:"sm",onClick:()=>K.mutate(),disabled:K.isPending,className:"flex-1",children:[K.isPending?e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(er,{className:"h-4 w-4 mr-1"}),"Remove"]})]}),e.jsx(zs,{open:y,onOpenChange:v,children:e.jsxs(Ds,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Cl,{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(U,{onClick:()=>{v(!1),H.mutate()},disabled:H.isPending,className:"flex-1",children:[H.isPending?e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx($r,{className:"h-4 w-4 mr-1"}),"Send to ",t]}),e.jsx(U,{variant:"outline",onClick:()=>v(!1),children:"Close"})]})]})})]})]}):l?e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(Cl,{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(te,{children:"Send Monthly Report"}),e.jsx(wn,{checked:m,onCheckedChange:p})]}),m&&e.jsxs("div",{children:[e.jsxs(te,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(ni,{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(xe,{ref:S,value:c,onChange:Q=>{d(Q.target.value),x(!0)},onFocus:()=>x(!0),placeholder:"Type to search cities...",onKeyDown:Q=>{Q.key==="Enter"&&(Q.preventDefault(),z.length>0?R(z[0]):R())}}),e.jsx(rl,{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(U,{type:"button",variant:"outline",size:"sm",onClick:()=>R(),children:e.jsx(an,{className:"h-4 w-4"})})]}),f&&z.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:z.map(Q=>e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors flex items-center gap-2",onClick:()=>R(Q),children:[e.jsx(ni,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),Q]},Q))})]}),u.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:u.map(Q=>e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[Q,e.jsx("button",{onClick:()=>h(u.filter(le=>le!==Q)),children:e.jsx(er,{className:"h-3 w-3"})})]},Q))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(U,{onClick:()=>V.mutate(),disabled:V.isPending,className:"flex-1",children:[V.isPending?e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-1"}),"Save"]}),e.jsx(U,{variant:"outline",onClick:()=>o(!1),children:"Cancel"})]})]})]}):e.jsx(we,{className:"overflow-hidden",children:e.jsx(Ie,{className:"p-4",children:e.jsxs("button",{onClick:I,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(Cl,{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 nRn({contactId:s,contactName:t}){const n=Qt(),[r,a]=j.useState(""),{data:i,isLoading:l}=ct({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=yt({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(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx(TM,{className:"h-4 w-4"}),"Email Preferences",c&&e.jsx(Be,{variant:"destructive",className:"ml-1",children:"Opted out"})]})}),e.jsx(Ie,{className:"space-y-4",children:l?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Et,{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(te,{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(wn,{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(te,{htmlFor:"opt-out-reason",className:"text-xs",children:"Reason (optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{id:"opt-out-reason",value:r,placeholder:"e.g. Asked to stop monthly newsletter",onChange:d=>a(d.target.value)}),e.jsx(U,{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 ",Gs(new Date(i.email_opt_out_at),"MMM d, yyyy")]})]})]})})]})}function rRn(s){return ct({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 aRn(s){switch(s){case"active":return e.jsx(Be,{variant:"secondary",className:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",children:"Active"});case"paused":return e.jsx(Be,{variant:"secondary",className:"bg-amber-500/10 text-amber-600 border-amber-500/20",children:"Paused"});case"completed":return e.jsx(Be,{variant:"secondary",className:"bg-sky-500/10 text-sky-600 border-sky-500/20",children:"Completed"});case"exited":return e.jsx(Be,{variant:"outline",children:"Exited"});default:return e.jsx(Be,{variant:"outline",children:s})}}function $wt(s){return s==="sent"?e.jsx(zr,{className:"h-4 w-4 text-emerald-500"}):s==="failed"?e.jsx(tc,{className:"h-4 w-4 text-destructive"}):s==="skipped"?e.jsx(uv,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Yr,{className:"h-4 w-4 text-muted-foreground"})}function iRn({contactId:s}){const t=Wn(),{data:n,isLoading:r}=rRn(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(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx(RM,{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(RM,{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"}),aRn(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: ",Nd(new Date(c.next_send_at),{addSuffix:!0})]}),c.completed_at&&e.jsxs(e.Fragment,{children:[" · Completed ",Nd(new Date(c.completed_at),{addSuffix:!0})]}),c.exited_at&&!c.completed_at&&e.jsxs(e.Fragment,{children:[" · ",c.exit_reason||"Exited"," ",Nd(new Date(c.exited_at),{addSuffix:!0})]})]})]}),e.jsx(gi,{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(al,{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:$wt(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(Ki,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}):e.jsx(ln,{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"," · ",Gs(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(Ds,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[$wt(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:Gs(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(U,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>t("/mission-control/smart-drips"),children:"View all in Smart Drips"})]})]})]})]})}function bWt({contactId:s}={}){const{user:t}=vs();return ct({queryKey:["sent-emails",t==null?void 0:t.id,s??"all"],enabled:!!t,queryFn:async()=>{const n=t.id;let r=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}).limit(1e3);s&&(r=r.eq("contact_id",s));let a=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}).limit(1e3);s&&(a=a.eq("contact_id",s));const i=await q.from("email_campaigns").select("id, subject").eq("user_id",n),l=(i.data||[]).map(x=>x.id),o=new Map((i.data||[]).map(x=>[x.id,x.subject]));let c=[];if(l.length>0){let x=q.from("email_campaign_recipients").select("id, contact_id, email, sent_at, campaign_id, opened_at, clicked_at").in("campaign_id",l).eq("status","sent").not("sent_at","is",null).order("sent_at",{ascending:!1}).limit(1e3);s&&(x=x.eq("contact_id",s)),c=(await x).data||[]}const[d,u]=await Promise.all([r,a]),h=(d.data||[]).map(x=>({id:`g-${x.id}`,channel:x.source==="portal_invite"?"Client Portal Invite":"Gmail",subject:x.subject,to_email:x.to_email,contact_id:x.contact_id,sent_at:x.sent_at,source:x.source})),m=(u.data||[]).map(x=>({id:`b-${x.id}`,channel:"Mass Email",subject:x.subject,to_email:x.contact_email,contact_id:x.contact_id,sent_at:x.sent_at,source:x.source,opened_at:x.opened_at,clicked_at:x.clicked_at})),p=c.map(x=>({id:`c-${x.id}`,channel:"Campaign",subject:o.get(x.campaign_id)||"(campaign)",to_email:x.email,contact_id:x.contact_id,sent_at:x.sent_at,source:null,campaign_id:x.campaign_id,opened_at:x.opened_at,clicked_at:x.clicked_at})),f=[...h,...m,...p];return f.sort((x,y)=>x.sent_at0&&e.jsx(Be,{variant:"secondary",className:"ml-1",children:t.length})]})}),e.jsx(Ie,{children:n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."}):t.length===0?e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(ln,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No emails sent to this contact yet."]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2",children:i.map(l=>e.jsx("div",{className:"flex items-start justify-between gap-3 p-3 rounded-lg border hover:bg-muted/30",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Be,{variant:"outline",className:`text-xs ${oRn[l.channel]}`,children:l.channel}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Gs(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(U,{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(xr,{to:"/mission-control/sent-emails",className:"text-xs text-primary hover:underline",children:"View all sent emails →"})})]})})]})}function cRn({videoId:s}){var l;const{data:t,isLoading:n,error:r}=EIn(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(tc,{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 dRn({contactId:s}){const t=Wn(),[n,r]=j.useState(!1),{data:a,isLoading:i}=ct({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 p=m==="done"?"todo":"done";await q.from("deal_tasks").update({status:p,completed_at:p==="done"?new Date().toISOString():null}).eq("id",h),window.dispatchEvent(new CustomEvent("refetch-contact-tasks"))},{refetch:o}=ct({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(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(Xr,{className:"h-4 w-4"}),"Tasks",d.length>0&&e.jsx(Be,{variant:"secondary",className:"text-xs",children:d.length})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/tasks"),children:"View All"}),e.jsx(U,{variant:"outline",size:"sm",onClick:()=>r(!0),children:e.jsx(an,{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:Gs(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(uRn,{contactId:s,open:n,onOpenChange:h=>{r(h),h||o()}})]})}function uRn({contactId:s,open:t,onOpenChange:n}){const[r,a]=j.useState(""),[i,l]=j.useState("medium"),[o,c]=j.useState(),{data:d}=ct({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?Gs(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(Ds,{className:"sm:max-w-[400px]",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Add Task"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Title"}),e.jsx(xe,{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(te,{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(te,{children:"Due Date"}),e.jsx(xe,{type:"date",value:o?Gs(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(U,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(U,{onClick:u,disabled:!r.trim(),children:"Create Task"})]})]})]})})}function hRn({contactId:s}){const t=Wn(),{data:n,isLoading:r}=ct({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(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(og,{className:"h-4 w-4"}),"Linked Deals"]})}),e.jsx(Ie,{className:"space-y-2",children:n.map(a=>{const i=a.stage;return e.jsx("button",{onClick:()=>t(`/mission-control/pipeline?deal=${a.id}`),className:"w-full text-left p-3 rounded-lg border hover:bg-accent transition-colors group",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.deal_name}),a.property_address&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:a.property_address}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Be,{variant:"outline",className:"text-[10px] capitalize",children:a.deal_type}),i&&e.jsxs(Be,{variant:"outline",className:"text-[10px] gap-1",style:{borderColor:i.color,color:i.color,backgroundColor:`${i.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:i.color}}),i.name]})]})]}),e.jsx(Oa,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors flex-shrink-0"})]})},a.id)})})]})}function mRn(){var Gn,On,Rr,cr;const{contactId:s}=Di(),{hasIdx:t}=$p(),n=Wn(),[r]=fc(),a=r.get("search")||"",i=r.get("type")||"all",l=r.get("status")||r.get("filter")||"all",o=r.get("tags")||"",c=r.get("tagMode")==="all"?"all":"any",d=j.useMemo(()=>new Set(o.split(",").map(Hs=>Hs.trim()).filter(Boolean)),[o]),{data:u,isLoading:h}=S7s(s||""),{data:m}=F_(),{data:p}=cre(),{data:f}=CG(3650),{data:x}=qLe(365),{data:y}=G8n(s),{contactsWithScores:v}=hre(),{data:b}=DLe(),{score:N}=zzs(s||""),S=FQe(),A=zQe(),T=tPe(),L=n7t(),[M,I]=j.useState(!1),[R,z]=j.useState("overview"),[$,H]=j.useState(!1),V=P8n(),[K,Z]=j.useState({}),[Q,le]=j.useState(!1),[ue,se]=j.useState(null),[ne,ie]=j.useState(""),[ce,je]=j.useState(void 0),[be,he]=j.useState(""),[ge,ke]=j.useState(null),[Te,Me]=j.useState(!1),[Oe,Se]=j.useState(null),[Qe,Ae]=j.useState(!1),{isGmailConnected:Fe,gmailEmail:Ne}=Ax(),{isReady:$e}=AG(),Ve=$e||Fe,qe=fWt(),[Ze,Ue]=j.useState(!1),{data:Ye}=ct({queryKey:["cma-eligible"],queryFn:async()=>{const{data:{user:Hs}}=await q.auth.getUser();if(!Hs)return!1;const{data:_r}=await q.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",Hs.id);return(_r||[]).some(nn=>nn.is_active&&nn.mls_provider_id&&!nn.no_mls_mode)}}),Ge=async()=>{var es,ar,Hn,kn;if(!u)return;const Hs=(es=u.address)==null?void 0:es.trim(),_r=(ar=u.city)==null?void 0:ar.trim(),nn=(Hn=u.state)==null?void 0:Hn.trim().toUpperCase(),Zn=((kn=u.zip_code)==null?void 0:kn.trim())||"";if(!Hs||!_r||!nn){re.error("Add a full address (street, city, state) before creating a CMA.");return}try{Ue(!0);const Un=await qe.mutateAsync({subject:{address:Hs,city:_r,state:nn,zip:Zn},contactId:u.id,title:`${u.first_name||""} ${u.last_name||""}`.trim()+" — "+Hs});n(`/mission-control/cma/${Un.id}`)}catch(Un){re.error("Could not create CMA: "+((Un==null?void 0:Un.message)||"unknown error"))}finally{Ue(!1)}},{data:He}=ct({queryKey:["gmail-sent-emails",s],queryFn:async()=>{const{data:Hs,error:_r}=await q.from("gmail_sent_emails").select("*").eq("contact_id",s).order("sent_at",{ascending:!1});if(_r)throw _r;return Hs},enabled:!!s}),tt=Hs=>{if(!Hs)return null;const _r=Hs.match(/Video ID:\s*([a-f0-9-]+)/i);return _r?_r[1]:null},pt=j.useMemo(()=>{if(!v)return[];const Hs=new Map;if(d.size>0&&b)for(const nn of b)Hs.has(nn.contact_id)||Hs.set(nn.contact_id,new Set),Hs.get(nn.contact_id).add(nn.tag_id);let _r=v.filter(nn=>{var Hn,kn,Un;const Zn=a===""||`${nn.first_name} ${nn.last_name}`.toLowerCase().includes(a.toLowerCase())||((Hn=nn.email)==null?void 0:Hn.toLowerCase().includes(a.toLowerCase()))||((kn=nn.phone)==null?void 0:kn.includes(a)),es=i==="all"||((Un=nn.tags)==null?void 0:Un.some(sn=>sn.relationship_type_id===i));let ar=!0;if(d.size>0){const sn=Hs.get(nn.id)||new Set;c==="all"?ar=Array.from(d).every(un=>sn.has(un)):ar=Array.from(d).some(un=>sn.has(un))}return Zn&&es&&ar});return l==="not-touched-90"?_r=_r.filter(nn=>{const Zn=nn.relationshipScore.daysSinceTouch;return Zn===null||Zn>90}):l==="at-risk"?_r=_r.filter(nn=>nn.relationshipScore.status==="at-risk"):l==="cooling"?_r=_r.filter(nn=>nn.relationshipScore.status==="cooling"):l==="warm"&&(_r=_r.filter(nn=>nn.relationshipScore.status==="warm")),_r.map(nn=>nn.id)},[v,a,i,l,d,c,b]),ft=pt.indexOf(s||""),qt=ft>0?pt[ft-1]:null,Ut=ft1&&ft!==-1,us=Hs=>{const _r=new URLSearchParams;a&&_r.set("search",a),i!=="all"&&_r.set("type",i),l!=="all"&&_r.set("status",l),d.size>0&&(_r.set("tags",Array.from(d).join(",")),_r.set("tagMode",c));const nn=_r.toString();return`/mission-control/contacts/${Hs}${nn?`?${nn}`:""}`},zt=j.useMemo(()=>{const Hs=((f==null?void 0:f.filter(nn=>nn.contact_id===s))||[]).map(nn=>{var Hn,kn,Un;const Zn=tt(nn.notes);let es=((Hn=nn.action_type)==null?void 0:Hn.name)||"Touch",ar=nn.notes;if(es==="Other"&&((kn=nn.notes)!=null&&kn.startsWith("["))){const sn=nn.notes.indexOf("]");sn>0&&(es=nn.notes.substring(1,sn),ar=nn.notes.substring(sn+1).replace(/^\s*—\s*/,"").trim()||null)}return{id:nn.id,type:"touch",completed_at:nn.completed_at,name:es,color:((Un=nn.action_type)==null?void 0:Un.color)||"#3B82F6",notes:ar,videoId:Zn}}),_r=((x==null?void 0:x.filter(nn=>nn.contact_id===s))||[]).map(nn=>({id:nn.id,type:"popby",completed_at:nn.completed_at,name:"Pop-by",color:"#F97316",notes:nn.notes,videoId:null}));return[...Hs,..._r].sort((nn,Zn)=>new Date(Zn.completed_at).getTime()-new Date(nn.completed_at).getTime())},[f,x,s]),bt=Hs=>{var _r;return{first_name:Hs.first_name||"",last_name:Hs.last_name||"",email:Hs.email||"",phone:Hs.phone||"",address:Hs.address||"",city:Hs.city||"",state:Hs.state||"",zip_code:Hs.zip_code||"",birthday:Hs.birthday||"",home_anniversary:Hs.home_anniversary||"",wedding_anniversary:Hs.wedding_anniversary||"",spouse_birthday:Hs.spouse_birthday||"",spouse_name:Hs.spouse_name||"",spouse_email:Hs.spouse_email||"",company_name:Hs.company_name||"",job_title:Hs.job_title||"",lead_source_id:Hs.lead_source_id||"",notes:Hs.notes||"",tagIds:((_r=Hs.tags)==null?void 0:_r.map(nn=>nn.relationship_type_id))||[]}};j.useEffect(()=>{I(!1),Z({})},[s]);const As=j.useRef(null);j.useEffect(()=>{u!=null&&u.id&&As.current!==u.id&&(As.current=u.id,Z(bt(u)))},[u==null?void 0:u.id,u]);const vt=()=>{u&&(Z(bt(u)),I(!0))},Ws=async()=>{await S.mutateAsync({id:s,...K,lead_source_id:K.lead_source_id||null}),I(!1)},on=async()=>{await Yi("Are you sure you want to delete this contact?")&&(await A.mutateAsync(s),n("/mission-control/contacts"))},dn=((Gn=p==null?void 0:p.find(Hs=>Hs.id===ue))==null?void 0:Gn.name)==="Other",rn=async()=>{if(!ue||dn&&!be.trim())return;const Hs=ce?new Date(ce.getFullYear(),ce.getMonth(),ce.getDate(),12,0,0).toISOString():void 0,_r=dn?`[${be.trim()}]${ne?" — "+ne:""}`:ne;await T.mutateAsync({contactId:s,actionTypeId:ue,notes:_r,completedAt:Hs}),le(!1),se(null),ie(""),je(void 0),he("")},br=(Hs,_r)=>{Ve&&u?(Se({email:Hs,name:_r||`${u.first_name} ${u.last_name||""}`.trim()}),Me(!0)):window.location.href=`mailto:${Hs}`};return h?e.jsx(qs,{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"})})}):u?e.jsxs(e.Fragment,{children:[e.jsx(qs,{title:`${u.first_name} ${u.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(U,{variant:"ghost",size:"sm",className:"-ml-2",onClick:()=>{window.history.length>1?n(-1):n("/mission-control/contacts")},children:[e.jsx(rd,{className:"h-4 w-4 mr-1"}),"Back to Contacts"]}),Wt&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(U,{variant:"outline",size:"sm",className:"h-8 px-2",onClick:()=>qt&&n(us(qt)),disabled:!qt,children:e.jsx(rd,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-1 text-xs text-muted-foreground whitespace-nowrap",children:[ft+1," of ",pt.length]}),e.jsx(U,{variant:"outline",size:"sm",className:"h-8 px-2",onClick:()=>Ut&&n(us(Ut)),disabled:!Ut,children:e.jsx(gi,{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(S8n,{contactId:u.id,firstName:u.first_name,lastName:u.last_name,avatarUrl:u.avatar_url,email:u.email,size:72})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h1",{className:"truncate text-2xl font-bold sm:text-3xl",children:[u.first_name," ",u.last_name||""]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:[N&&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:N.status==="warm"?"#22c55e":N.status==="cooling"?"#f59e0b":"#ef4444"}}),N.status==="at-risk"?"At risk":N.status," · ",N.score]}),u.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(TM,{className:"h-3 w-3"}),"Emails opted out"]}),(((On=u.lead_source_ref)==null?void 0:On.name)||u.lead_source)&&e.jsx("span",{className:"hub-glass rounded-full px-2.5 py-1 text-[11px] font-medium",children:((Rr=u.lead_source_ref)==null?void 0:Rr.name)||u.lead_source}),(cr=u.tags)==null?void 0:cr.map(Hs=>{const _r=m==null?void 0:m.find(nn=>nn.id===Hs.relationship_type_id);return _r?e.jsx("span",{className:"hub-glass rounded-full px-2.5 py-1 text-[11px] font-medium",children:_r.name},Hs.id):null})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-1.5 text-sm sm:flex-row sm:flex-wrap sm:items-center sm:gap-4",children:[u.email&&e.jsxs("button",{onClick:()=>br(u.email),className:"inline-flex min-w-0 items-center gap-1.5 hub-ink-muted transition-opacity hover:opacity-100",children:[e.jsx(ln,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:u.email})]}),u.phone&&e.jsxs("a",{href:`tel:${u.phone}`,className:"inline-flex items-center gap-1.5 hub-ink-muted",children:[e.jsx(ba,{className:"h-3.5 w-3.5"}),u.phone]}),(u.address||u.city)&&e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 hub-ink-muted",children:[e.jsx(ni,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:[u.address,u.city,u.state].filter(Boolean).join(", ")})]})]})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[V&&e.jsxs("button",{onClick:()=>H(!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 for this contact",children:[e.jsx(cn,{className:"h-4 w-4"}),"Enrich"]}),e.jsxs("button",{onClick:()=>{vt(),z("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(sp,{className:"h-4 w-4"}),"Edit"]}),e.jsx("button",{onClick:on,className:"hub-glass inline-flex h-9 w-9 items-center justify-center rounded-full",title:"Delete contact",children:e.jsx(In,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 sm:flex sm:flex-wrap",children:[u.phone&&e.jsxs("a",{href:`tel:${u.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(ba,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Call"]}),u.phone&&e.jsxs("button",{onClick:()=>window.location.href=`sms:${u.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(Ki,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Text"]}),u.email&&e.jsxs("button",{onClick:()=>br(u.email,`${u.first_name} ${u.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(ln,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Email"]}),e.jsxs("button",{onClick:()=>n(`/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(Wr,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Video"]}),e.jsxs("button",{onClick:()=>le(!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(an,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Log Action"]}),u.email&&e.jsxs("button",{onClick:()=>Ae(!0),className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(cn,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Connect Page"]})]})]})}),e.jsxs(oa,{value:R,onValueChange:Hs=>{Hs==="details"&&!M&&vt(),z(Hs)},children:[e.jsx("div",{className:"-mx-1 overflow-x-auto px-1",children:e.jsxs(la,{className:"inline-flex h-10 w-auto",children:[e.jsx(Kt,{value:"overview",children:"Overview"}),e.jsx(Kt,{value:"details",children:"Details"}),e.jsx(Kt,{value:"activity",children:"Activity"}),e.jsx(Kt,{value:"marketing",children:"Marketing"})]})}),e.jsx(Zt,{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(QLn,{contact:u,onLogTouch:()=>le(!0)}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx(pa,{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:Ro,label:"Birthday",value:u.birthday},{icon:ra,label:"Home Anniversary",value:u.home_anniversary},{icon:ko,label:"Wedding Anniversary",value:u.wedding_anniversary},{icon:ko,label:"Spouse Birthday",value:u.spouse_birthday}].map(({icon:Hs,label:_r,value:nn})=>e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-border/70 bg-muted/30 px-3 py-2.5",children:[e.jsx(Hs,{className:"h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:_r}),e.jsx("p",{className:"truncate text-sm font-medium",children:nn?Gs(Su(nn),Su(nn).getFullYear()===1900?"MMMM d":"MMMM d, yyyy"):"—"})]})]},_r))}),zt.length>0&&e.jsxs("p",{className:"mt-3 text-xs text-muted-foreground",children:["Last contacted ",Gs(new Date(zt[0].completed_at),"MMM d, yyyy")," (",zt[0].name,")",u.created_at&&` · Added ${Gs(new Date(u.created_at),"MMM d, yyyy")}`]})]})]}),(u.address||u.city)&&e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx(ra,{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(ni,{className:"mt-0.5 h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"text-sm",children:[u.address&&e.jsx("div",{children:u.address}),e.jsxs("div",{className:"text-muted-foreground",children:[[u.city,u.state].filter(Boolean).join(", "),u.zip_code?` ${u.zip_code}`:""]})]})]}),Ye&&u.address&&u.city&&u.state&&e.jsxs(U,{size:"sm",variant:"outline",onClick:Ge,disabled:Ze,children:[Ze?e.jsx(Et,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(Qw,{className:"mr-1 h-4 w-4"}),"Create CMA"]})]})]}),e.jsx(R8n,{contactId:u.id,ownerUserId:u.owner_user_id,legacyNote:u.notes}),e.jsx(dRn,{contactId:s})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsx(It,{className:"text-base",children:"Tags"})}),e.jsx(Ie,{children:e.jsx(Mwt,{contactId:s})})]}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx(So,{className:"h-4 w-4 text-primary"}),"People & Work"]})}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsx(XHe,{contactId:s,currentSpouseContactId:(u==null?void 0:u.spouse_contact_id)||null,currentSpouseName:u.spouse_name||null,currentSpouseEmail:u.spouse_email||null,onLink:Hs=>L.mutate({contactId:s,spouseContactId:Hs}),onUnlink:()=>L.mutate({contactId:s,spouseContactId:null}),isEditing:!1}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(_i,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:Mt(!u.company_name&&!u.job_title&&"text-muted-foreground"),children:u.job_title&&u.company_name?`${u.job_title} at ${u.company_name}`:u.job_title||u.company_name||"No company on file"})]})]})]}),e.jsx(hRn,{contactId:s}),e.jsx(J8n,{contactId:s})]})]})}),e.jsx(Zt,{value:"details",className:"mt-4",children:e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsx(It,{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(te,{htmlFor:"first_name",children:"First Name"}),e.jsx(xe,{id:"first_name",value:K.first_name||"",onChange:Hs=>Z({...K,first_name:Hs.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"last_name",children:"Last Name"}),e.jsx(xe,{id:"last_name",value:K.last_name||"",onChange:Hs=>Z({...K,last_name:Hs.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"email",children:"Email"}),e.jsx(xe,{id:"email",type:"email",value:K.email||"",onChange:Hs=>Z({...K,email:Hs.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"phone",children:"Phone"}),e.jsx(xe,{id:"phone",value:K.phone||"",onChange:Hs=>Z({...K,phone:Hs.target.value})})]})]})]}),e.jsx(hc,{}),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(te,{htmlFor:"address",children:"Street Address"}),e.jsx(xe,{id:"address",value:K.address||"",onChange:Hs=>Z({...K,address:Hs.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-4",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(te,{htmlFor:"city",children:"City"}),e.jsx(xe,{id:"city",value:K.city||"",onChange:Hs=>Z({...K,city:Hs.target.value}),placeholder:"City"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"state",children:"State"}),e.jsx(xe,{id:"state",value:K.state||"",onChange:Hs=>Z({...K,state:Hs.target.value}),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"zip_code",children:"Zip Code"}),e.jsx(xe,{id:"zip_code",value:K.zip_code||"",onChange:Hs=>Z({...K,zip_code:Hs.target.value}),placeholder:"12345"})]})]})]}),e.jsx(hc,{}),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(te,{htmlFor:"birthday",children:"Birthday"}),e.jsx(xe,{id:"birthday",type:"date",value:K.birthday||"",onChange:Hs=>Z({...K,birthday:Hs.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(xe,{id:"home_anniversary",type:"date",value:K.home_anniversary||"",onChange:Hs=>Z({...K,home_anniversary:Hs.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"wedding_anniversary",children:"Wedding Anniversary"}),e.jsx(xe,{id:"wedding_anniversary",type:"date",value:K.wedding_anniversary||"",onChange:Hs=>Z({...K,wedding_anniversary:Hs.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"spouse_birthday",children:"Spouse Birthday"}),e.jsx(xe,{id:"spouse_birthday",type:"date",value:K.spouse_birthday||"",onChange:Hs=>Z({...K,spouse_birthday:Hs.target.value})})]})]})]}),e.jsx(hc,{}),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(XHe,{contactId:s,currentSpouseContactId:(u==null?void 0:u.spouse_contact_id)||null,currentSpouseName:(u==null?void 0:u.spouse_name)||null,currentSpouseEmail:(u==null?void 0:u.spouse_email)||null,onLink:Hs=>L.mutate({contactId:s,spouseContactId:Hs}),onUnlink:()=>L.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(te,{htmlFor:"company_name",children:"Company"}),e.jsx(xe,{id:"company_name",value:K.company_name||"",onChange:Hs=>Z({...K,company_name:Hs.target.value}),placeholder:"Enter company name"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"job_title",children:"Job Title"}),e.jsx(xe,{id:"job_title",value:K.job_title||"",onChange:Hs=>Z({...K,job_title:Hs.target.value}),placeholder:"Enter job title"})]})]}),e.jsx(cWt,{value:K.lead_source_id||"",onChange:Hs=>Z({...K,lead_source_id:Hs})})]}),e.jsx(hc,{}),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:m==null?void 0:m.filter(Hs=>Hs.active).map(Hs=>{var nn;const _r=!!((nn=K.tagIds)!=null&&nn.includes(Hs.id));return e.jsxs("label",{className:Mt("inline-flex cursor-pointer items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition-colors",_r?"border-primary bg-primary/10 text-primary":"border-border hover:bg-accent"),children:[e.jsx(xi,{checked:_r,onCheckedChange:Zn=>{var es;Z(Zn?{...K,tagIds:[...K.tagIds||[],Hs.id]}:{...K,tagIds:(es=K.tagIds)==null?void 0:es.filter(ar=>ar!==Hs.id)})}}),Hs.name]},Hs.id)})}),e.jsxs("div",{children:[e.jsx(te,{children:"Tags"}),e.jsx("div",{className:"mt-2",children:e.jsx(Mwt,{contactId:s})})]})]}),e.jsx(hc,{}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"notes",children:"Notes"}),e.jsx(Fs,{id:"notes",value:K.notes||"",onChange:Hs=>Z({...K,notes:Hs.target.value}),rows:5})]}),e.jsxs("div",{className:"sticky bottom-0 -mx-6 flex flex-wrap items-center justify-end gap-2 border-t bg-card/95 px-6 py-3 backdrop-blur",children:[e.jsx(U,{variant:"outline",onClick:()=>{I(!1),z("overview")},children:"Cancel"}),e.jsxs(U,{onClick:Ws,disabled:S.isPending,children:[S.isPending?e.jsx(Et,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(Xr,{className:"mr-1 h-4 w-4"}),"Save Changes"]})]})]})]})}),e.jsx(Zt,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between gap-2 pb-3",children:[e.jsx(It,{className:"text-base",children:"Activity Log"}),e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>le(!0),children:[e.jsx(an,{className:"mr-1 h-3.5 w-3.5"})," Log Action"]})]}),e.jsx(Ie,{children:zt.length>0?e.jsx("div",{className:"space-y-4",children:zt.map(Hs=>{var _r;return e.jsxs("div",{className:"flex items-start gap-3 border-b pb-3 last:border-0",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-full text-xs text-white",style:{backgroundColor:Hs.color},children:Hs.type==="popby"?e.jsx(Ro,{className:"h-4 w-4"}):(_r=Hs.name)==null?void 0:_r.charAt(0)}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:Hs.name}),Hs.videoId&&e.jsxs(U,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>ke(Hs.videoId),children:[e.jsx(lu,{className:"mr-1 h-3 w-3"}),"Preview"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Gs(new Date(Hs.completed_at),"MMM d, yyyy h:mm a")}),Hs.notes&&!Hs.videoId&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:Hs.notes})]})]},Hs.id)})}):e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"No activity logged yet"})})]})}),e.jsxs("div",{className:"space-y-5",children:[y&&y.length>0&&e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ki,{className:"h-4 w-4 text-primary"}),"Video Replies"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"space-y-4",children:y.map(Hs=>{var _r,nn;return e.jsxs("div",{className:"flex items-start gap-3 border-b pb-3 last:border-0",children:[(_r=Hs.video)!=null&&_r.thumbnail_url?e.jsx("img",{src:Hs.video.thumbnail_url,alt:Hs.video.title||"Video",className:"h-12 w-16 cursor-pointer rounded object-cover transition-opacity hover:opacity-80",onClick:()=>ke(Hs.video_id)}):e.jsx("div",{className:"flex h-12 w-16 cursor-pointer items-center justify-center rounded bg-muted transition-colors hover:bg-muted/80",onClick:()=>ke(Hs.video_id),children:e.jsx(Wr,{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: ",((nn=Hs.video)==null?void 0:nn.title)||"Untitled Video"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Gs(new Date(Hs.created_at),"MMM d, yyyy h:mm a")}),Hs.message&&e.jsxs("p",{className:"mt-1 line-clamp-2 text-sm text-muted-foreground",children:['"',Hs.message,'"']})]})]},Hs.id)})})})]}),He&&He.length>0&&e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx($r,{className:"h-4 w-4 text-sky-500"}),"Sent Emails"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"space-y-3",children:He.map(Hs=>e.jsxs(zs,{children:[e.jsx(al,{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(ln,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:Hs.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["To: ",Hs.to_email," · ",Gs(new Date(Hs.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx(gi,{className:"mt-1 h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(Ds,{className:"flex max-h-[85vh] max-w-2xl flex-col",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5 text-sky-500"}),Hs.subject]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["To: ",Hs.to_email," · ",Gs(new Date(Hs.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-hidden rounded-lg border bg-white",children:e.jsx("iframe",{srcDoc:Hs.body,className:"h-[400px] w-full border-0",sandbox:"",title:`Email: ${Hs.subject}`})})]})]},Hs.id))})})]}),e.jsx(lRn,{contactId:s})]})]})}),e.jsx(Zt,{value:"marketing",className:"mt-4",children:e.jsxs("div",{className:"grid gap-5 lg:grid-cols-2",children:[e.jsx(nRn,{contactId:s,contactName:u.first_name}),e.jsx(eRn,{contactId:s}),t&&e.jsxs(e.Fragment,{children:[e.jsx(tRn,{contactId:s,contactName:u.first_name}),e.jsx(sRn,{contactId:s,contactName:u.first_name})]}),e.jsx(iRn,{contactId:s})]})})]}),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:[u.phone&&e.jsx("a",{href:`tel:${u.phone}`,className:"flex-1",children:e.jsxs(U,{variant:"outline",className:"w-full",children:[e.jsx(ba,{className:"mr-1 h-4 w-4"})," Call"]})}),u.phone&&e.jsxs(U,{variant:"outline",className:"flex-1",onClick:()=>window.location.href=`sms:${u.phone}`,children:[e.jsx(Ki,{className:"mr-1 h-4 w-4"})," Text"]}),e.jsxs(U,{className:"flex-1",onClick:()=>le(!0),children:[e.jsx(an,{className:"mr-1 h-4 w-4"})," Log"]})]}),e.jsx(zs,{open:Q,onOpenChange:le,children:e.jsxs(Ds,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Log an Action"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Action Type"}),e.jsx("div",{className:"mt-2 grid grid-cols-2 gap-2",children:p==null?void 0:p.filter(Hs=>Hs.active).map(Hs=>e.jsxs("button",{onClick:()=>se(Hs.id),className:Mt("rounded-lg border p-3 text-left transition-all",ue===Hs.id?"border-primary bg-primary/10":"hover:bg-accent"),children:[e.jsx("div",{className:"font-medium",children:Hs.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Hs.description})]},Hs.id))}),dn&&e.jsxs("div",{className:"mt-3",children:[e.jsx(te,{htmlFor:"custom-action-name",children:"What did you do?"}),e.jsx(xe,{id:"custom-action-name",value:be,onChange:Hs=>he(Hs.target.value),placeholder:"e.g. Met a client for lunch, Dropped off a gift...",className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Date (optional — backdate if needed)"}),e.jsxs(md,{children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{variant:"outline",className:Mt("mt-2 w-full justify-start text-left font-normal",!ce&&"text-muted-foreground"),children:[e.jsx(pa,{className:"mr-2 h-4 w-4"}),ce?Gs(ce,"PPP"):"Today (default)"]})}),e.jsx(id,{className:"w-auto p-0",align:"start",children:e.jsx(yj,{mode:"single",selected:ce,onSelect:je,disabled:Hs=>Hs>new Date,initialFocus:!0,className:Mt("p-3 pointer-events-auto")})})]})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"action-notes",children:"Notes (optional)"}),e.jsx(Fs,{id:"action-notes",value:ne,onChange:Hs=>ie(Hs.target.value),placeholder:"Add any notes about this interaction...",rows:3})]}),e.jsxs(U,{onClick:rn,disabled:!ue||dn&&!be.trim()||T.isPending,className:"w-full",children:[e.jsx(Xr,{className:"mr-1 h-4 w-4"}),"Complete Action"]})]})]})}),e.jsx(zs,{open:!!ge,onOpenChange:Hs=>!Hs&&ke(null),children:e.jsxs(Ds,{className:"max-w-2xl",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Video Preview"})}),ge&&e.jsx(cRn,{videoId:ge})]})})]})}),V&&u&&e.jsx(T8n,{open:$,onOpenChange:H,contactId:u.id,contactName:`${u.first_name} ${u.last_name||""}`.trim(),hasEmail:!!u.email}),Ve&&u&&Oe&&e.jsx(wS,{open:Te,onOpenChange:Me,contact:{id:u.id,first_name:u.first_name,last_name:u.last_name,email:Oe.email},gmailEmail:Ne}),u&&u.email&&e.jsx(O8n,{open:Qe,onOpenChange:Ae,contact:{id:u.id,first_name:u.first_name,last_name:u.last_name,email:u.email}})]}):e.jsx(qs,{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(U,{onClick:()=>n("/mission-control/contacts"),children:"Back to Contacts"})]})})}function pRn({rangeDays:s}){const{user:t}=vs(),n=Qt(),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(!1),{data:d=[],isLoading:u}=ct({queryKey:["newsletter-campaigns",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let p=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();p=p.gte("created_at",y)}const{data:f,error:x}=await p;if(x)throw x;return f||[]}}),{data:h}=ct({queryKey:["newsletter-campaign-recipients",r],enabled:!!r,queryFn:async()=>{const{data:p,error:f}=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(f)throw f;return p||[]}}),m=async()=>{if(!(!i||!t)){c(!0);try{const{data:p,error:f}=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(f)throw f;if(!p||p.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:p.length,status:"draft"}).select("id").single();if(v)throw v;const b=p.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 f=p.sent_count||0,x=f>0?p.open_count/f*100:0,y=f>0?p.click_count/f*100:0,v=p.sent_at?hN(new Date,new Date(p.sent_at)):0,b=p.status==="sent"&&v>=3&&f>0&&p.open_counta(p.id),children:[e.jsx(xa,{className:"h-3.5 w-3.5 mr-1"})," Details"]}),b&&e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>l(p),children:[e.jsx(RF,{className:"h-3.5 w-3.5 mr-1"})," Resend"]})]})]}),p.status==="sent"&&f>0&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mt-3",children:[e.jsx($le,{icon:e.jsx($r,{className:"h-3.5 w-3.5"}),label:"Sent",value:f,sub:`of ${p.total_recipients}`}),e.jsx($le,{icon:e.jsx(xa,{className:"h-3.5 w-3.5 text-blue-600"}),label:"Opens",value:p.open_count,sub:`${x.toFixed(1)}%`,children:e.jsx(ro,{value:x,className:"h-1 mt-1"})}),e.jsx($le,{icon:e.jsx(Ch,{className:"h-3.5 w-3.5 text-purple-600"}),label:"Clicks",value:p.click_count,sub:`${y.toFixed(1)}%`,children:e.jsx(ro,{value:y,className:"h-1 mt-1"})}),e.jsx($le,{icon:e.jsx(TM,{className:"h-3.5 w-3.5 text-orange-600"}),label:"Bounces",value:p.bounce_count,sub:p.bounce_count>0?"review":"none"})]})]},p.id)})})]})}),e.jsx(my,{open:!!r,onOpenChange:p=>!p&&a(null),children:e.jsxs(g0,{className:"w-full sm:max-w-2xl overflow-y-auto",children:[e.jsx(vv,{children:e.jsx(bv,{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(p=>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:p.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[180px]",children:p.email})]}),e.jsx("td",{className:"py-2 text-xs",children:p.opened_at?e.jsx(Be,{variant:"default",className:"text-xs",children:Gs(new Date(p.opened_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-2 text-xs",children:p.clicked_at?e.jsx(Be,{variant:"default",className:"text-xs bg-purple-600",children:Gs(new Date(p.clicked_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsxs("td",{className:"py-2 text-xs",children:[p.status==="sent"&&e.jsx(Be,{variant:"outline",className:"text-xs",children:"sent"}),p.status==="pending"&&e.jsx(Be,{variant:"secondary",className:"text-xs",children:"queued"}),p.status==="failed"&&e.jsx(Be,{variant:"destructive",className:"text-xs",title:p.error_message||"",children:"failed"}),p.status==="suppressed"&&e.jsx(Be,{variant:"outline",className:"text-xs",children:"suppressed"})]})]},p.id))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"})})]})}),e.jsx(Fl,{open:!!i,onOpenChange:p=>!p&&l(null),children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Resend to non-openers?"}),e.jsxs(Ll,{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(Ml,{children:[e.jsx(Il,{disabled:o,children:"Cancel"}),e.jsx(_l,{onClick:m,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}),"Resending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(RF,{className:"h-4 w-4 mr-1"}),"Resend"]})})]})]})})]})}function $le({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 vte(){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 fRn(){const{user:s}=vs(),t=Wn(),n=Qt(),{data:r=[],isLoading:a}=ct({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 vte(),p=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(!p.success)throw new Error(p.error||`Failed to ${d}`);return p},l=yt({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=yt({mutationFn:d=>i("delete",d),onSuccess:()=>{re.success("Scheduled email deleted"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>re.error(d.message)}),c=yt({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(we,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Yr,{className:"h-12 w-12 text-muted-foreground mb-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(gRn,{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 gRn({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"),p=()=>{if(!d)return re.error("Pick a date");const f=new Date(`${Gs(d,"yyyy-MM-dd")}T${h}:00`).toISOString();if(new Date(f).getTime()fm(f.target.value)})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(U,{onClick:p,disabled:i,children:[i&&e.jsx(Et,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save new time"]})]})]})]}),e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsxs(U,{size:"sm",variant:"outline",disabled:i,children:[e.jsx(ou,{className:"h-3.5 w-3.5 mr-1.5"})," Cancel Send"]})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Cancel this scheduled send?"}),e.jsxs(Ll,{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(Ml,{children:[e.jsx(Il,{children:"Keep scheduled"}),e.jsx(_l,{onClick:n,children:"Cancel send"})]})]})]}),e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsxs(U,{size:"sm",variant:"ghost",className:"text-destructive hover:text-destructive",disabled:i,children:[e.jsx(In,{className:"h-3.5 w-3.5 mr-1.5"})," Delete"]})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Delete this scheduled email?"}),e.jsx(Ll,{children:"This permanently removes the scheduled email and all its recipient records. This can't be undone."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Keep"}),e.jsx(_l,{onClick:r,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete permanently"})]})]})]})]})]})})})}function xRn({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 Vle({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:Mt("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(gi,{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 yRn({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(xRn,{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(Vle,{icon:e.jsx(zr,{className:"h-3.5 w-3.5"}),label:"Delivered",value:s.toLocaleString(),hint:"All sends completed"}),e.jsx(Vle,{icon:e.jsx(xa,{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(Vle,{icon:e.jsx(Ch,{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(Vle,{icon:e.jsx(Yr,{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 Vwt=["Gmail","Mass Email","Campaign","Client Portal Invite"],vRn={Gmail:"bg-red-100 text-red-700 border-red-200","Mass Email":"bg-blue-100 text-blue-700 border-blue-200",Campaign:"bg-purple-100 text-purple-700 border-purple-200","Client Portal Invite":"bg-emerald-100 text-emerald-700 border-emerald-200"};function bRn(){const{user:s}=vs(),[t,n]=fc(),{data:r=[],isLoading:a}=bWt(),[i,l]=j.useState(""),[o,c]=j.useState("all"),[d,u]=j.useState("30"),[h,m]=j.useState(!1),[p,f]=j.useState(t.get("tab")==="scheduled"?"scheduled":"sent"),{gmailEmail:x}=Ax(),{data:y=0}=ct({queryKey:["scheduled-email-count",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{count:L}=await q.from("email_campaigns").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("status","scheduled");return L||0},refetchInterval:3e4});j.useEffect(()=>{const L=new URLSearchParams(t);p==="scheduled"?L.set("tab","scheduled"):L.delete("tab"),n(L,{replace:!0})},[p]);const v=j.useMemo(()=>Array.from(new Set(r.map(L=>L.contact_id).filter(Boolean))),[r]),{data:b}=ct({queryKey:["sent-emails-contact-names",s==null?void 0:s.id,v.length],enabled:v.length>0,queryFn:async()=>{const{data:L}=await q.from("innercircle_contacts").select("id, first_name, last_name").in("id",v),M=new Map;return(L||[]).forEach(I=>{M.set(I.id,[I.first_name,I.last_name].filter(Boolean).join(" ")||"Contact")}),M}}),N=j.useMemo(()=>{const L=d==="all"?null:Date.now()-parseInt(d)*864e5,M=i.trim().toLowerCase();return r.filter(I=>{if(o!=="all"&&I.channel!==o||L&&new Date(I.sent_at).getTime(){const L={};let M=0,I=0,R=0;return N.forEach(z=>{L[z.channel]=(L[z.channel]||0)+1,(z.channel==="Campaign"||z.channel==="Mass Email")&&(R++,z.opened_at&&M++,z.clicked_at&&I++)}),{byChannel:L,opened:M,clicked:I,trackable:R}},[N]),A=d==="all"?"All time":`Last ${d} days`,T=Vwt.map(L=>S.byChannel[L]?`${S.byChannel[L]} ${L}`:null).filter(Boolean).join(" · ");return e.jsx(qs,{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($r,{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:()=>f("sent"),className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm transition-colors ${p==="sent"?"bg-background shadow-sm font-medium":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx($r,{className:"h-3.5 w-3.5"})," Sent"]}),e.jsxs("button",{onClick:()=>f("scheduled"),className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm transition-colors ${p==="scheduled"?"bg-background shadow-sm font-medium":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Yr,{className:"h-3.5 w-3.5"})," Scheduled",y>0&&e.jsx(Be,{variant:"secondary",className:"ml-0.5 h-5 min-w-5 px-1.5 text-xs",children:y})]})]}),e.jsxs(U,{onClick:()=>m(!0),className:"rounded-full",children:[e.jsx(ln,{className:"h-4 w-4 mr-2"})," Send Email"]})]})]}),e.jsxs(oa,{value:p,onValueChange:L=>f(L),className:"space-y-5",children:[e.jsxs(Zt,{value:"sent",className:"space-y-5 mt-0",children:[e.jsx(yRn,{total:N.length,opened:S.opened,clicked:S.clicked,trackable:S.trackable,scheduled:y,rangeLabel:A,channelSummary:T,onScheduledClick:()=>f("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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search subject, recipient, contact...",value:i,onChange:L=>l(L.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(Ns,{value:o,onValueChange:c,children:[e.jsx(ws,{className:"w-[170px] rounded-full h-9",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Channels"}),Vwt.map(L=>e.jsx(et,{value:L,children:L},L))]})]}),e.jsxs(Ns,{value:d,onValueChange:u,children:[e.jsx(ws,{className:"w-[150px] rounded-full h-9",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"7",children:"Last 7 days"}),e.jsx(et,{value:"30",children:"Last 30 days"}),e.jsx(et,{value:"90",children:"Last 90 days"}),e.jsx(et,{value:"365",children:"Last year"}),e.jsx(et,{value:"all",children:"All time"})]})]})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground -mt-3 px-1",children:[e.jsx(Jk,{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(pRn,{rangeDays:d==="all"?null:parseInt(d)}),a?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):N.length===0?e.jsx(we,{className:"rounded-2xl",children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(ln,{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(we,{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(wN,{children:e.jsxs(Bg,{children:[e.jsxs(Ug,{className:"inline-flex items-center gap-1",children:["Engagement ",e.jsx(Jk,{className:"h-3 w-3"})]}),e.jsx(ng,{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:N.slice(0,500).map(L=>{const M=L.contact_id?b==null?void 0:b.get(L.contact_id):null,I=L.channel==="Campaign"||L.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:Gs(new Date(L.sent_at),"MMM d, yyyy h:mm a")}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(Be,{variant:"outline",className:vRn[L.channel],children:L.channel})}),e.jsx("td",{className:"py-3 px-4 max-w-xs truncate font-medium",children:L.subject}),e.jsx("td",{className:"py-3 px-4 text-muted-foreground",children:L.to_email}),e.jsx("td",{className:"py-3 px-4",children:L.contact_id&&M?e.jsx(xr,{to:`/mission-control/contacts/${L.contact_id}`,className:"text-primary hover:underline",children:M}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-3 px-4",children:I?e.jsxs("div",{className:"flex flex-wrap gap-1",children:[e.jsxs(Be,{variant:"outline",className:"bg-slate-50 text-slate-700 border-slate-200 gap-1",children:[e.jsx(zr,{className:"h-3 w-3"})," Delivered"]}),L.opened_at&&e.jsxs(Be,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200 gap-1",children:[e.jsx(xa,{className:"h-3 w-3"})," Opened"]}),L.clicked_at&&e.jsxs(Be,{variant:"outline",className:"bg-emerald-50 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(Ch,{className:"h-3 w-3"})," Clicked"]})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Not tracked"})})]},L.id)})})]}),N.length>500&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center py-3 border-t",children:["Showing first 500 of ",N.length," — narrow your filters to see more."]})]})})})]}),e.jsx(Zt,{value:"scheduled",className:"mt-0",children:e.jsx(fRn,{})})]}),e.jsx(wS,{open:h,onOpenChange:m,gmailEmail:x})]})})}const Hwt={Crown:h0,FileText:Ur,Users:Bn,Globe:fl,Star:Ua,Phone:ba,MessageSquare:Ki,PenTool:TA,Video:Wr,Gift:Ro},Hle=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function _Rn(){var ft,qt;const s=Wn(),{user:t}=vs(),{data:n}=F_(),{data:r}=A7s(),{data:a}=R7s(),{data:i}=s7t(),{data:l}=cre(),{data:o}=C7s(),c=D7s(),d=E7s(),u=M7s(),h=P7s(),m=L7s(),p=I7s(),f=T7s(),[x,y]=j.useState(null),[v,b]=j.useState(!1),[N,S]=j.useState(null),[A,T]=j.useState(""),[L,M]=j.useState(""),[I,R]=j.useState([]),[z,$]=j.useState(null),[H,V]=j.useState(null),[K,Z]=j.useState(null),[Q,le]=j.useState(!1),[ue,se]=j.useState(""),[ne,ie]=j.useState(""),[ce,je]=j.useState(""),[be,he]=j.useState(""),ge=(Ut,Wt)=>a==null?void 0:a.some(us=>us.plan_id===Ut&&us.relationship_type_id===Wt&&us.active),ke=Ut=>a==null?void 0:a.find(Wt=>Wt.relationship_type_id===Ut&&Wt.active),Te=async(Ut,Wt)=>{const us=ge(Ut,Wt);await c.mutateAsync({planId:Ut,relationshipTypeId:Wt,active:!us})},Me=(r==null?void 0:r.filter(Ut=>Ut.active&&!Ut.owner_user_id))||[],Oe=(r==null?void 0:r.filter(Ut=>Ut.owner_user_id===(t==null?void 0:t.id)))||[],Se=n==null?void 0:n.find(Ut=>Ut.id===x),Qe=x?ke(x):null,Ae=r==null?void 0:r.find(Ut=>Ut.id===(Qe==null?void 0:Qe.plan_id)),Fe=async()=>{if(!A.trim())return;const Ut=await d.mutateAsync({name:A,description:L});Ut&&I.length>0&&await m.mutateAsync({planId:Ut.id,items:I}),qe()},Ne=async()=>{!A.trim()||!N||(await u.mutateAsync({id:N,name:A,description:L}),await m.mutateAsync({planId:N,items:I}),qe())},$e=Ut=>{var Wt;S(Ut.id),T(Ut.name),M(Ut.description||""),R(((Wt=Ut.items)==null?void 0:Wt.map(us=>({month_number:us.month_number,action_type_id:us.action_type_id,default_script_id:us.default_script_id||void 0,notes:us.notes||void 0})))||[]),b(!0)},Ve=async(Ut,Wt)=>{if(Ut.owner_user_id===(t==null?void 0:t.id)){$e(Ut);return}try{const us=await f.mutateAsync({sourcePlanId:Ut.id,newName:`${Ut.name} (My Copy)`});if(!us)return;await c.mutateAsync({planId:Ut.id,relationshipTypeId:Wt,active:!1}),await c.mutateAsync({planId:us.id,relationshipTypeId:Wt,active:!0}),S(us.id),T(us.name),M(us.description||""),R((Ut.items||[]).map(zt=>({month_number:zt.month_number,action_type_id:zt.action_type_id,default_script_id:zt.default_script_id||void 0,notes:zt.notes||void 0}))),b(!0)}catch{}},qe=()=>{b(!1),S(null),T(""),M(""),R([])},Ze=(Ut,Wt)=>{V(Wt)},Ue=(Ut,Wt,us)=>{R(zt=>[...zt.filter(As=>As.month_number!==Ut),{month_number:Ut,action_type_id:Wt,default_script_id:us}]),$(null),V(null)},Ye=Ut=>{R(Wt=>Wt.filter(us=>us.month_number!==Ut))},Ge=async()=>{if(!ue.trim()||!ne.trim()||!H)return;const Ut=await p.mutateAsync({actionTypeId:H,title:ue,scriptBody:ne,emailSubject:ce||void 0,tone:be||void 0});Ut&&z!==null&&Ue(z,H,Ut.id),le(!1),se(""),ie(""),je(""),he("")},He=H?o==null?void 0:o.filter(Ut=>Ut.action_type_id===H&&Ut.active):[],tt=Ut=>Hwt[Ut||"Phone"]||ba,pt=Ut=>Hwt[Ut||"Users"]||Bn;return e.jsxs(qs,{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(U,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control"),children:[e.jsx(rd,{className:"h-4 w-4 mr-1"}),"Back"]}),e.jsxs(U,{onClick:()=>b(!0),className:"w-full sm:w-auto",children:[e.jsx(an,{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(Ut=>Ut.active).map(Ut=>{const Wt=pt(Ut.icon),us=(i==null?void 0:i[Ut.id])||0,zt=ke(Ut.id),bt=r==null?void 0:r.find(vt=>vt.id===(zt==null?void 0:zt.plan_id)),As=x===Ut.id;return e.jsxs("button",{onClick:()=>y(Ut.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(Wt,{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:Ut.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[us," contacts"]})]}),bt?e.jsxs(Be,{variant:"secondary",className:"text-xs",children:[e.jsx(Yo,{className:"h-3 w-3 mr-1"}),bt.name.split(" ")[0]]}):e.jsx(Be,{variant:"outline",className:"text-xs text-muted-foreground",children:"No plan"})]},Ut.id)})]}),e.jsx("div",{className:"lg:col-span-2",children:x&&Se?e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[(()=>{const Ut=pt(Se.icon);return e.jsx(Ut,{className:"h-5 w-5"})})(),Se.name," Touchpoint Plan"]}),e.jsxs(Jn,{children:["Choose a plan for your ",Se.name," contacts"]})]}),e.jsxs(Ie,{className:"space-y-6",children:[Ae&&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(Yo,{className:"h-4 w-4 text-green-500"}),"Currently using: ",Ae.name]}),Ae.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ae.description})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{variant:"outline",size:"sm",disabled:f.isPending||c.isPending,onClick:()=>Ve(Ae,x),children:[e.jsx(C2,{className:"h-4 w-4 mr-1"}),"Edit Steps"]}),e.jsx(U,{variant:"outline",size:"sm",onClick:()=>Te(Ae.id,x),children:"Disable"})]})]}),Ae.items&&Ae.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(pa,{className:"h-4 w-4"}),"12-Month Schedule"]}),e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:Hle.map((Ut,Wt)=>{var As,vt;const us=((As=Ae.items)==null?void 0:As.filter(Ws=>Ws.month_number===Wt+1))||[],zt=(vt=us[0])==null?void 0:vt.action_type,bt=zt?tt(zt.icon):null;return e.jsxs("div",{className:` p-2 rounded border text-center ${us.length>0?"bg-primary/10 border-primary":"bg-muted"} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:Ut}),bt&&e.jsx(bt,{className:"h-4 w-4 mx-auto mt-1",style:{color:(zt==null?void 0:zt.color)||"#3B82F6"}})]},Wt)})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:Ae?"Switch to a Different Plan":"Choose a Plan"}),Me.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"}),Me.map(Ut=>{var us;const Wt=(Ae==null?void 0:Ae.id)===Ut.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${Wt?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ut.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((us=Ut.items)==null?void 0:us.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>Z(Ut.id),children:e.jsx(xa,{className:"h-4 w-4"})}),e.jsx(U,{size:"sm",variant:"ghost",title:"Duplicate as my own plan",disabled:f.isPending,onClick:()=>{const zt=`${Ut.name} (Copy)`;f.mutate({sourcePlanId:Ut.id,newName:zt})},children:e.jsx(Pa,{className:"h-4 w-4"})}),e.jsx(U,{size:"sm",variant:Wt?"outline":"default",disabled:Wt||c.isPending,onClick:()=>Te(Ut.id,x),children:Wt?"Active":"Use This"})]})]},Ut.id)})]}),Oe.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"My Custom Plans"}),Oe.map(Ut=>{var us;const Wt=(Ae==null?void 0:Ae.id)===Ut.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${Wt?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ut.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((us=Ut.items)==null?void 0:us.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>Z(Ut.id),children:e.jsx(xa,{className:"h-4 w-4"})}),e.jsx(U,{size:"sm",variant:"ghost",title:"Edit plan",onClick:()=>$e(Ut),children:e.jsx(C2,{className:"h-4 w-4"})}),e.jsx(U,{size:"sm",variant:"ghost",title:"Delete plan",onClick:()=>h.mutate(Ut.id),children:e.jsx(In,{className:"h-4 w-4 text-destructive"})}),e.jsx(U,{size:"sm",variant:Wt?"outline":"default",disabled:Wt||c.isPending,onClick:()=>Te(Ut.id,x),children:Wt?"Active":"Use This"})]})]},Ut.id)})]}),Me.length===0&&Oe.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(we,{children:e.jsxs(Ie,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(pa,{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(we,{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:Ut=>{Ut?b(!0):qe()},children:e.jsxs(Ds,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:N?"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(te,{htmlFor:"plan-name",children:"Plan Name"}),e.jsx(xe,{id:"plan-name",value:A,onChange:Ut=>T(Ut.target.value),placeholder:"e.g., My VIP Plan"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"plan-description",children:"Description (optional)"}),e.jsx(Fs,{id:"plan-description",value:L,onChange:Ut=>M(Ut.target.value),placeholder:"Describe your plan...",rows:2})]})]}),e.jsxs("div",{children:[e.jsx(te,{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:Hle.map((Ut,Wt)=>{const us=Wt+1,zt=I.find(vt=>vt.month_number===us),bt=zt?l==null?void 0:l.find(vt=>vt.id===zt.action_type_id):null,As=bt?tt(bt.icon):null;return e.jsxs("div",{className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>$(z===us?null:us),className:` w-full p-3 rounded-lg border text-center transition-all ${zt?"bg-primary/10 border-primary":"bg-muted hover:bg-accent"} ${z===us?"ring-2 ring-primary":""} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground font-medium",children:Ut}),As?e.jsx(As,{className:"h-5 w-5 mx-auto mt-1",style:{color:(bt==null?void 0:bt.color)||"#3B82F6"}}):e.jsx(an,{className:"h-5 w-5 mx-auto mt-1 text-muted-foreground/50"})]}),zt&&e.jsx("button",{type:"button",onClick:vt=>{vt.stopPropagation(),Ye(us)},className:"absolute -top-1 -right-1 p-1 bg-destructive text-destructive-foreground rounded-full",children:e.jsx(er,{className:"h-3 w-3"})})]},Wt)})}),z!==null&&!H&&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 ",Hle[z-1],":"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l==null?void 0:l.filter(Ut=>Ut.active).map(Ut=>{const Wt=tt(Ut.icon);return e.jsxs("button",{type:"button",onClick:()=>Ze(z,Ut.id),className:"flex items-center gap-2 px-3 py-2 rounded-lg border bg-background hover:bg-accent transition-colors",children:[e.jsx(Wt,{className:"h-4 w-4",style:{color:Ut.color||"#3B82F6"}}),e.jsx("span",{className:"text-sm",children:Ut.name})]},Ut.id)})})]}),z!==null&&H&&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(U,{variant:"ghost",size:"sm",onClick:()=>V(null),children:[e.jsx(rd,{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:()=>Ue(z,H),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"})]})}),He==null?void 0:He.map(Ut=>e.jsx("button",{type:"button",onClick:()=>Ue(z,H,Ut.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:Ut.title}),Ut.tone&&e.jsx(Be,{variant:"secondary",className:"text-xs mt-1",children:Ut.tone}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:[Ut.script_body.substring(0,100),"..."]})]})},Ut.id)),e.jsxs("button",{type:"button",onClick:()=>le(!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(an,{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"})]})]})]})]})]}),I.length>0&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[I.length," touchpoint",I.length!==1?"s":""," per year"]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:qe,children:"Cancel"}),e.jsxs(U,{onClick:N?Ne:Fe,disabled:!A.trim()||d.isPending||u.isPending,children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"}),N?"Save Changes":"Create Plan"]})]})]})}),e.jsx(zs,{open:Q,onOpenChange:le,children:e.jsxs(Ds,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Create Custom Script"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{htmlFor:"script-title",children:"Script Title"}),e.jsx(xe,{id:"script-title",value:ue,onChange:Ut=>se(Ut.target.value),placeholder:"e.g., Friendly Check-in Call"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"script-tone",children:"Tone (optional)"}),e.jsxs(Ns,{value:be,onValueChange:he,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select tone..."})}),e.jsxs(js,{children:[e.jsx(et,{value:"friendly",children:"Friendly"}),e.jsx(et,{value:"professional",children:"Professional"}),e.jsx(et,{value:"casual",children:"Casual"}),e.jsx(et,{value:"formal",children:"Formal"})]})]})]}),((qt=(ft=l==null?void 0:l.find(Ut=>Ut.id===H))==null?void 0:ft.name)==null?void 0:qt.toLowerCase().includes("email"))&&e.jsxs("div",{children:[e.jsx(te,{htmlFor:"script-email-subject",children:"Email Subject"}),e.jsx(xe,{id:"script-email-subject",value:ce,onChange:Ut=>je(Ut.target.value),placeholder:"e.g., Quick Hello!"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"script-body",children:"Script Content"}),e.jsx(Fs,{id:"script-body",value:ne,onChange:Ut=>ie(Ut.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(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>le(!1),children:"Cancel"}),e.jsxs(U,{onClick:Ge,disabled:!ue.trim()||!ne.trim()||p.isPending,children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"}),"Create & Use Script"]})]})]})}),e.jsx(zs,{open:!!K,onOpenChange:Ut=>{Ut||Z(null)},children:e.jsx(Ds,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:(()=>{const Ut=r==null?void 0:r.find(zt=>zt.id===K);if(!Ut)return null;const Wt=Ut.owner_user_id===(t==null?void 0:t.id),us=[...Ut.items||[]].sort((zt,bt)=>zt.month_number-bt.month_number);return e.jsxs(e.Fragment,{children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[Ut.name,!Wt&&e.jsx(Be,{variant:"secondary",children:"Template"})]}),Ut.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:Ut.description})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[us.length," touchpoint",us.length!==1?"s":""," per year"]}),e.jsx("div",{className:"space-y-2",children:Array.from({length:12},(zt,bt)=>bt+1).map(zt=>{const bt=us.find(on=>on.month_number===zt),As=bt?l==null?void 0:l.find(on=>on.id===bt.action_type_id):null,vt=bt!=null&&bt.default_script_id?o==null?void 0:o.find(on=>on.id===bt.default_script_id):null,Ws=As?tt(As.icon):null;return e.jsxs("div",{className:`p-3 rounded-lg border flex items-start gap-3 ${bt?"bg-muted/30":"opacity-60"}`,children:[e.jsx("div",{className:"w-16 shrink-0 font-medium text-sm",children:Hle[zt-1]}),bt&&As?e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[Ws&&e.jsx(Ws,{className:"h-4 w-4",style:{color:As.color||"#3B82F6"}}),e.jsx("span",{className:"font-medium text-sm",children:As.name}),vt&&e.jsx(Be,{variant:"outline",className:"text-xs",children:vt.title})]}),vt&&e.jsx("div",{className:"mt-2 text-sm text-muted-foreground whitespace-pre-wrap bg-background p-2 rounded border",children:vt.script_body}),bt.notes&&e.jsx("div",{className:"mt-1 text-xs text-muted-foreground italic",children:bt.notes})]}):e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:"No touchpoint scheduled"})]},zt)})})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>Z(null),children:"Close"}),Wt?e.jsxs(U,{onClick:()=>{const zt=r==null?void 0:r.find(bt=>bt.id===K);zt&&(Z(null),$e(zt))},children:[e.jsx(C2,{className:"h-4 w-4 mr-2"}),"Edit Plan"]}):e.jsxs(U,{disabled:f.isPending,onClick:()=>{f.mutate({sourcePlanId:Ut.id,newName:`${Ut.name} (Copy)`}),Z(null)},children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Duplicate to Edit"]})]})]})})()})})]})}const Z7e="https://cma.relevelup.com";function _Wt({open:s,onOpenChange:t,cma:n}){var Z;const{user:r}=vs(),{toast:a}=Ai(),[i,l]=j.useState([]),[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(""),[p,f]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState(!1),[N,S]=j.useState(null),[A,T]=j.useState(!1),[L,M]=j.useState(!1),[I,R]=j.useState(null);j.useEffect(()=>{!s||!r||(async()=>{var je;const[Q,le,ue,se,ne]=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()]),ie=(Q.data||[]).filter(be=>be.email&&be.email.includes("@"));l(ie),S(le.data||null),T(!!((je=ue.data)!=null&&je.is_active)),M(!!(se.data&&se.data.length>0)),R(ne.data||null);const ce=n.contact_id?ie.find(be=>be.id===n.contact_id):null;ce&&(c(ce),m(ce.email))})()},[s,r,n.contact_id]),j.useEffect(()=>{var se;if(!s)return;const Q=((se=n.subject)==null?void 0:se.address)||"your home",le=((N==null?void 0:N.name)||"").split(" ")[0]||"your agent",ue=(o==null?void 0:o.first_name)||"there";f(`Your home value report for ${Q}`),y(`Hi ${ue}, I put together a fresh market analysis for ${Q}. 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, ${(N==null?void 0:N.name)||le}`)},[s,o==null?void 0:o.id,N==null?void 0:N.name,(Z=n.subject)==null?void 0:Z.address]);const z=j.useMemo(()=>A?"Gmail (your inbox)":L?"Amazon SES":null,[A,L]),$=!!(h.trim()&&p.trim()&&x.trim()&&z&&!v),H=Q=>{c(Q),m(Q.email||""),u(!1)},V=Q=>{const le=`${Z7e}/${n.share_token}?e=${Q}`,ne=x.replace(/&/g,"&").replace(//g,">").replace(/\{\{cma_link\}\}/g,`View Your Home Value Report`).split(/\n{2,}/).map(je=>`

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

`).join(""),ie=N!=null&&N.use_email_signature&&(N!=null&&N.email_signature)?`
${N.email_signature}
`:`
${N!=null&&N.name?`
${N.name}
`:""} ${N!=null&&N.brokerage_name?`
${N.brokerage_name}
`:""} ${N!=null&&N.phone?`
${N.phone}
`:""} ${N!=null&&N.email?``:""}
`,ce=``;return`
${ne} ${ie}
Prepared with LevelUp · ReLevelUp Real Estate
${ce}
`},K=async()=>{if(!(!r||!$)){b(!0);try{const{data:Q,error:le}=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:p.trim(),sent_via:A?"gmail":"ses"}).select("id").single();if(le)throw le;const ue=V(Q.id);if(A){const{data:se,error:ne}=await q.functions.invoke("gmail-send",{body:{to:h.trim(),subject:p.trim(),body:ue}});if(ne)throw ne;if(!(se!=null&&se.success))throw new Error((se==null?void 0:se.error)||"Gmail send failed")}else if(L){const se=(I==null?void 0:I.display_name)||(N==null?void 0:N.name)||"ReLevelUp",ne=`${se.toLowerCase().replace(/[^a-z]/g,".").replace(/^\.+|\.+$/g,"")||"noreply"}@send.relevelup.com`,{data:ie,error:ce}=await q.functions.invoke("ses-send-campaign",{body:{action:"test_send",to:h.trim(),from_email:`${se} <${ne}>`,subject:p.trim(),body_html:ue,reply_to:(I==null?void 0:I.reply_to_email)||(N==null?void 0:N.email)||void 0}});if(ce)throw ce;if(!(ie!=null&&ie.success))throw new Error((ie==null?void 0:ie.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(Q){console.error("Send CMA error:",Q),a({title:"Send failed",description:Q.message||"Could not send email",variant:"destructive"})}finally{b(!1)}}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"w-5 h-5"}),"Send CMA to contact"]})}),z?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:z})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Contact"}),e.jsxs(md,{open:d,onOpenChange:u,children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{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(Jw,{className:"w-4 h-4 opacity-50"})]})}),e.jsx(id,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(pj,{children:[e.jsx(fj,{placeholder:"Search contacts…"}),e.jsxs(gj,{children:[e.jsx(xj,{children:"No contacts with email found."}),e.jsx(I_,{children:i.map(Q=>e.jsxs(e1,{value:`${Q.first_name} ${Q.last_name||""} ${Q.email}`,onSelect:()=>H(Q),children:[e.jsx(Xr,{className:Mt("w-4 h-4 mr-2",(o==null?void 0:o.id)===Q.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium",children:[Q.first_name," ",Q.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Q.email})]})]},Q.id))})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"To email"}),e.jsx(xe,{type:"email",value:h,onChange:Q=>m(Q.target.value),placeholder:"client@example.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Subject"}),e.jsx(xe,{value:p,onChange:Q=>f(Q.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Message"}),e.jsx(Fs,{rows:10,value:x,onChange:Q=>y(Q.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(Sr,{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:`${Z7e}/${n.share_token}`,target:"_blank",rel:"noreferrer",children:`${Z7e}/${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(Mr,{children:[e.jsx(U,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{onClick:K,disabled:!$,children:[v?e.jsx(Et,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx($r,{className:"w-4 h-4 mr-2"}),"Send CMA"]})]})]})})}function wRn(s){const{user:t}=vs(),n=Qt(),{data:r}=ct({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=yt({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 jRn="free_luxury",NRn="free_beta";function wWt(s){const t=s==null?void 0:s.planTier;return t===jRn||t===NRn}const kRn={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 SRn({featureKey:s,siteId:t,bullets:n}){const r=kRn[s],{requestUpgrade:a,hasRequested:i,isSending:l}=wRn(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(Ql,{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(cn,{className:"h-4 w-4 mt-0.5 text-amber-500 shrink-0"}),c]},c))}):null,e.jsx(U,{className:"mt-5",disabled:o||l,onClick:()=>a.mutate({featureKey:s}),children:o?e.jsxs(e.Fragment,{children:[e.jsx(Xr,{className:"h-4 w-4 mr-2"})," Upgrade requested"]}):"Request this upgrade"})]})]})})}function CRn({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=$8n(),m=fWt(),{toast:p}=Ai(),[f,x]=j.useState([]),y=async()=>{var N;x([]);try{const S=await h.mutateAsync({address:r,city:i,state:o,zip:d});x(S.matches||[]),(N=S.matches)!=null&&N.length||p({title:"No MLS match",description:'Use "Create from manual entry" below.'})}catch(S){p({title:"Search failed",description:S.message,variant:"destructive"})}},v=async N=>{const S=await m.mutateAsync({subject:N});n(!1),s(S.id)},b=async()=>{if(!r||!i||!o){p({title:"Address, city, state required"});return}const N=await m.mutateAsync({subject:{address:r,city:i,state:o,zip:d}});n(!1),s(N.id)};return e.jsxs(zs,{open:t,onOpenChange:n,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{children:[e.jsx(an,{className:"w-4 h-4 mr-2"}),"New CMA"]})}),e.jsxs(Ds,{className:"max-w-2xl",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Start a CMA"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-2",children:[e.jsx(xe,{className:"md:col-span-2",placeholder:"Street address",value:r,onChange:N=>a(N.target.value)}),e.jsx(xe,{placeholder:"City",value:i,onChange:N=>l(N.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{placeholder:"ST",maxLength:2,value:o,onChange:N=>c(N.target.value.toUpperCase())}),e.jsx(xe,{placeholder:"ZIP",value:d,onChange:N=>u(N.target.value)})]})]}),e.jsxs(U,{onClick:y,disabled:!r||h.isPending,className:"w-full",children:[h.isPending?e.jsx(Et,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Fr,{className:"w-4 h-4 mr-2"}),"Find in MLS"]}),f.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:[f.length," match(es) — pick the subject property:"]}),f.map((N,S)=>{var A;return e.jsxs("button",{onClick:()=>v(N),className:"w-full text-left p-3 border rounded hover:bg-accent transition",children:[e.jsx("div",{className:"font-medium",children:N.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[N.city,", ",N.state," ",N.zip," · ",N.bedrooms??"?"," bd / ",N.bathrooms??"?"," ba · ",((A=N.sqft)==null?void 0:A.toLocaleString())??"?"," sqft",N.mlsNumber?` · MLS# ${N.mlsNumber}`:""," · ",N.source_provider]})]},S)})]}),e.jsx("div",{className:"border-t pt-3",children:e.jsxs(U,{variant:"outline",onClick:b,disabled:m.isPending,className:"w-full",children:[e.jsx(ra,{className:"w-4 h-4 mr-2"}),"Create from manual entry"]})})]})]})]})}function ARn(){const{data:s,isLoading:t}=F8n(),n=q8n(),r=Wn(),{toast:a}=Ai(),[i,l]=j.useState(null),{isFreePlan:o,leadSite:c}=$p();return o?e.jsx(qs,{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(Ur,{className:"w-7 h-7"})," CMAs"]}),e.jsx(SRn,{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(qs,{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(Ur,{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(CRn,{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(we,{className:"hover:shadow-md transition",children:e.jsxs(Ie,{className:"p-4 flex flex-wrap items-center gap-3 justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-[200px]",children:[e.jsx("div",{className:"font-semibold",children:d.title||((u=d.subject)==null?void 0:u.address)||"Untitled CMA"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[(h=d.subject)==null?void 0:h.city,", ",(m=d.subject)==null?void 0:m.state," · ",d.buyer_mode?"Buyer":"Seller"," ·"," ",e.jsx(Be,{variant:d.status==="shared"?"default":"secondary",className:"ml-1",children:d.status})]}),d.price_likely?e.jsxs("div",{className:"text-sm mt-1",children:["Suggested: ",e.jsxs("span",{className:"font-medium",children:["$",d.price_likely.toLocaleString()]}),d.price_low&&d.price_high?e.jsxs("span",{className:"text-muted-foreground",children:[" · $",d.price_low.toLocaleString(),"–$",d.price_high.toLocaleString()]}):null]}):null]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{variant:"outline",size:"sm",onClick:()=>r(`/mission-control/cma/${d.id}`),children:"Open"}),d.status==="shared"&&e.jsxs(e.Fragment,{children:[e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>{const p=`https://cma.relevelup.com/${d.share_token}`;navigator.clipboard.writeText(p),a({title:"Share link copied"})},children:e.jsx(Sr,{className:"w-4 h-4"})}),e.jsxs(U,{variant:"secondary",size:"sm",onClick:()=>l(d),children:[e.jsx(ln,{className:"w-4 h-4 mr-1"}),"Send"]})]}),e.jsx(U,{variant:"ghost",size:"sm",onClick:async()=>{await Yi("Delete this CMA?")&&n.mutate(d.id)},children:e.jsx(In,{className:"w-4 h-4"})})]})]})},d.id)})}):e.jsx(we,{children:e.jsx(Ie,{className:"py-12 text-center text-muted-foreground",children:"No CMAs yet. Start one above."})}),i&&e.jsx(_Wt,{open:!!i,onOpenChange:d=>!d&&l(null),cma:i})]})})}function ERn(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 Gwt(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 TRn({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;bd.accessToken=o;const u=new bd.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[d.lng,d.lat],zoom:12});return u.addControl(new bd.NavigationControl({showCompass:!1}),"top-right"),u.on("load",()=>{u.addSource("radius",{type:"geojson",data:Gwt(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(Gwt(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 bd.Marker({element:h}).setLngLat([d.lng,d.lat]).setPopup(new bd.Popup({offset:18}).setHTML(`Subject
${s.address??""}`)).addTo(u);l.current.push(m);const p=new bd.LngLatBounds;p.extend([d.lng,d.lat]),t.forEach((y,v)=>{const b=Number(y.latitude),N=Number(y.longitude);if(!Number.isFinite(b)||!Number.isFinite(N))return;const S=ERn(y.status),A=document.createElement("div");A.style.cssText="width:22px;height:22px;";const T=document.createElement("div");T.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; `,T.onmouseenter=()=>{T.style.transform="scale(1.25)"},T.onmouseleave=()=>{T.style.transform="scale(1)"},r&&(T.onclick=()=>r(v)),A.appendChild(T);const L=y.soldPrice||y.price,M=new bd.Popup({offset:14}).setHTML(`
${y.address??""}
${y.status??""}`+(L?` · $${L.toLocaleString()}`:"")+"
"),I=new bd.Marker({element:A}).setLngLat([N,b]).setPopup(M).addTo(u);l.current.push(I),p.extend([N,b])});const x=n*1.60934/110.574;p.extend([d.lng,d.lat+x]),p.extend([d.lng,d.lat-x]);try{u.fitBounds(p,{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 Yb=null;function jWt(){if(Yb)return Yb;try{const s=document.createElement("canvas"),t=s.getContext("webgl2")||s.getContext("webgl");if(!t)return Yb={canRunVirtualBg:!1,reason:"WebGL is not supported on this device"},Yb;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 Yb={canRunVirtualBg:!1,reason:"Your device uses a software renderer which may cause lag",renderer:r},Yb;const o=performance;return o.memory&&o.memory.jsHeapSizeLimit<256*1024*1024?(Yb={canRunVirtualBg:!1,reason:"Limited device memory detected",renderer:r},Yb):navigator.hardwareConcurrency&&navigator.hardwareConcurrency<2?(Yb={canRunVirtualBg:!1,reason:"Single-core device detected — virtual backgrounds may cause lag",renderer:r},Yb):(Yb={canRunVirtualBg:!0,renderer:r},Yb)}catch{return Yb={canRunVirtualBg:!0},Yb}}const MRn=[{type:"none",label:"Off"},{type:"blur",label:"Blur"}];function PRn({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(()=>jWt()),h=!u.canRunVirtualBg,{data:m=[],refetch:p}=ct({queryKey:["video-backgrounds"],queryFn:async()=>{const{data:{user:N}}=await q.auth.getUser();if(!N)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(T=>({...T,__ownerId:N.id}))}}),f=m.map(N=>({type:"image",label:N.name,imageUrl:N.image_url,thumbnail:N.thumbnail_url||N.image_url,id:N.id,deletable:!N.is_stock&&N.user_id===N.__ownerId})),x=[...MRn,...f],y=N=>N.type!==s.type?!1:N.type==="image"?N.imageUrl===s.imageUrl:!0,v=async N=>{if(!(!N.id||!N.imageUrl)&&window.confirm(`Delete the background "${N.label}"? This can't be undone.`)){d(N.id);try{const{error:S}=await q.from("video_backgrounds").delete().eq("id",N.id);if(S)throw S;const A="/video-backgrounds/",T=N.imageUrl.indexOf(A);if(T!==-1){const L=decodeURIComponent(N.imageUrl.slice(T+A.length).split("?")[0]);await q.storage.from("video-backgrounds").remove([L])}s.type==="image"&&s.imageUrl===N.imageUrl&&t({type:"none",mirror:s.mirror}),await p(),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 N=>{var A;const S=(A=N.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:T}}=await q.auth.getUser();if(!T)throw new Error("Not authenticated");const L=S.name.split(".").pop()||"jpg",M=`${T.id}/${crypto.randomUUID()}.${L}`,{error:I}=await q.storage.from("video-backgrounds").upload(M,S,{contentType:S.type});if(I)throw I;const{data:R}=q.storage.from("video-backgrounds").getPublicUrl(M),z=R.publicUrl,{error:$}=await q.from("video_backgrounds").insert({name:S.name.replace(/\.[^.]+$/,""),image_url:z,thumbnail_url:z,category:"custom",is_stock:!1,user_id:T.id});if($)throw $;await p(),t({type:"image",imageUrl:z,blurRadius:15}),re.success("Background uploaded!")}catch(T){console.error("Upload error:",T),re.error("Failed to upload background")}finally{o(!1),i.current&&(i.current.value="")}}};return e.jsxs("div",{className:Mt("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(tc,{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(Et,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{children:"Loading…"})]}),x.map((N,S)=>{const A=y(N);return e.jsxs("div",{className:"relative flex-shrink-0 group",children:[e.jsxs("button",{type:"button",disabled:r,onClick:()=>t({type:N.type,imageUrl:N.imageUrl,blurRadius:15,mirror:s.mirror}),className:Mt("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:[N.type==="none"&&e.jsx(_F,{className:"h-4 w-4 text-muted-foreground"}),N.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"})}),N.type==="image"&&N.thumbnail&&e.jsx("img",{src:N.thumbnail,alt:N.label,className:"w-full h-full object-cover"})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground truncate max-w-14",children:N.label})]}),N.deletable&&e.jsx("button",{type:"button","aria-label":`Delete background ${N.label}`,disabled:r||c===N.id,onClick:T=>{T.stopPropagation(),v(N)},className:Mt("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===N.id?e.jsx(Et,{className:"h-3 w-3 animate-spin"}):e.jsx(er,{className:"h-3 w-3"})})]},`${N.type}-${N.imageUrl||S}`)}),e.jsxs("button",{type:"button",disabled:r||l,onClick:()=>{var N;return(N=i.current)==null?void 0:N.click()},className:Mt("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(Et,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(an,{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:Mt("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(zX,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Mirror"})]})]})]})}var AH=typeof self<"u"?self:{};function NWt(s,t){e:{for(var n=["CLOSURE_FLAGS"],r=AH,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 SWt(s){AH.setTimeout(()=>{throw s},0)}var QHe,DRn=NWt(610401301,!1),Kwt=NWt(748402147,!0);function Ywt(){var s=AH.navigator;return s&&(s=s.userAgent)?s:""}const Zwt=AH.navigator;function HLe(s){return HLe[" "](s),s}QHe=Zwt&&Zwt.userAgentData||null,HLe[" "]=function(){};const CWt={};let IZ=null;function ORn(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 AWt(){if(!IZ){IZ={};var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"];for(let n=0;n<5;n++){const r=s.concat(t[n].split(""));CWt[n]=r;for(let a=0;a0)&&(Ywt().indexOf("Trident")!=-1||Ywt().indexOf("MSIE")!=-1))&&typeof btoa=="function";const Xwt=/[-_.]/g,zRn={"-":"+",_:"/",".":"="};function BRn(s){return zRn[s]||""}function TWt(s){if(!EWt)return ORn(s);s=Xwt.test(s)?s.replace(Xwt,BRn):s,s=atob(s);const t=new Uint8Array(s.length);for(let n=0;n=t||(n[s]=r+1,PWt(s=Error(),"incident"),SWt(s))}}function tW(){return typeof BigInt=="function"}var sW=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 $Rn=g3("jas",void 0,!0),Qwt=g3(void 0,"0di"),kY=g3(void 0,"1oa"),lj=g3(void 0,Symbol()),VRn=g3(void 0,"0ub"),HRn=g3(void 0,"0ubs"),eGe=g3(void 0,"0ubsb"),GRn=g3(void 0,"0actk"),MH=g3("m_m","Pa",!0),Jwt=g3();const LWt={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},IWt=Object.defineProperties,Do=sW?$Rn:"Ga";var M9;const ejt=[];function zre(s,t){sW||Do in s||IWt(s,LWt),s[Do]|=t}function x0(s,t){sW||Do in s||IWt(s,LWt),s[Do]=t}function Bre(s){return zre(s,34),s}function bte(s){return zre(s,8192),s}x0(ejt,7),M9=Object.freeze(ejt);var PH={};function vj(s,t){return t===void 0?s.h!==H7&&!!(2&(0|s.v[Do])):!!(2&t)&&s.h!==H7}const H7={};function nst(s,t){if(s!=null){if(typeof s=="string")s=s?new V4(s,EH):V7();else if(s.constructor!==V4)if(tst(s))s=s.length?new V4(new Uint8Array(s),EH):V7();else{if(!t)throw Error();s=void 0}}return s}let tjt=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 WRn=Object.freeze({});function RWt(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"),sjt=GLe(s=>typeof s=="string"),YRn=GLe(s=>typeof s=="boolean"),WLe=typeof AH.BigInt=="function"&&typeof AH.BigInt(0)=="bigint";function cj(s){var t=s;if(sjt(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(KRn(t)&&!Number.isSafeInteger(t))throw Error(String(t));return WLe?BigInt(s):s=YRn(s)?s?"1":"0":sjt(s)?s.trim()||"0":String(s)}var tGe=GLe(s=>WLe?s>=XRn&&s<=JRn:s[0]==="-"?njt(s,ZRn):njt(s,QRn));const ZRn=Number.MIN_SAFE_INTEGER.toString(),XRn=WLe?BigInt(Number.MIN_SAFE_INTEGER):void 0,QRn=Number.MAX_SAFE_INTEGER.toString(),JRn=WLe?BigInt(Number.MAX_SAFE_INTEGER):void 0;function njt(s,t){if(s.length>t.length)return!1;if(s.lengtha)return!1;if(r>>0;pf=t,mx=(s-t)/4294967296>>>0}function LH(s){if(s<0){rjt(-s);const[t,n]=ist(pf,mx);pf=t>>>0,mx=n>>>0}else rjt(s)}function rst(s){const t=tDn||(tDn=new DataView(new ArrayBuffer(8)));t.setFloat32(0,+s,!0),mx=0,pf=t.getUint32(0,!0)}function OWt(s,t){const n=4294967296*t+(s>>>0);return Number.isSafeInteger(n)?n:_te(s,t)}function sDn(s,t){return cj(tW()?BigInt.asUintN(64,(BigInt(t>>>0)<>>0)):_te(s,t))}function FWt(s,t){return tW()?cj(BigInt.asIntN(64,(BigInt.asUintN(32,BigInt(t))<>>=0,(t>>>=0)<=2097151)var n=""+(4294967296*t+s);else tW()?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+ajt(n)+ajt(s));return n}function ajt(s){return s=String(s),"0000000".slice(s.length)+s}function ast(s,t){if(2147483648&t)if(tW())s=""+(BigInt(0|t)<>>0));else{const[n,r]=ist(s,t);s="-"+_te(n,r)}else s=_te(s,t);return s}function KLe(s){if(s.length<16)LH(Number(s));else if(tW())s=BigInt(s),pf=Number(s&BigInt(4294967295))>>>0,mx=Number(s>>BigInt(32)&BigInt(4294967295));else{const t=+(s[0]==="-");mx=pf=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));mx*=1e6,pf=1e6*pf+i,pf>=4294967296&&(mx+=Math.trunc(pf/4294967296),mx>>>=0,pf>>>=0)}if(t){const[r,a]=ist(pf,mx);pf=r,mx=a}}}function ist(s,t){return t=~t,s?s=1+~s:t+=1,[s,t]}function cS(s){return Array.prototype.slice.call(s)}const Ure=typeof BigInt=="function"?BigInt.asIntN:void 0,nDn=typeof BigInt=="function"?BigInt.asUintN:void 0,G7=Number.isSafeInteger,YLe=Number.isFinite,IH=Math.trunc,rDn=cj(0);function RZ(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 wte(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 zWt(s){return s==null||typeof s=="boolean"?s:typeof s=="number"?!!s:void 0}const aDn=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function qre(s){switch(typeof s){case"bigint":return!0;case"number":return YLe(s);case"string":return aDn.test(s);default:return!1}}function rW(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return YLe(s)?0|s:void 0}function BWt(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return YLe(s)?s>>>0:void 0}function UWt(s){const t=s.length;return(s[0]==="-"?t<20||t===20&&s<="-9223372036854775808":t<19||t===19&&s<="9223372036854775807")?s:(KLe(s),ast(pf,mx))}function ost(s){if(s=IH(s),!G7(s)){LH(s);var t=pf,n=mx;(s=2147483648&n)&&(n=~n>>>0,(t=1+~t>>>0)==0&&(n=n+1>>>0)),s=typeof(t=OWt(t,n))=="number"?s?-t:t:s?"-"+t:t}return s}function qWt(s){var t=IH(Number(s));return G7(t)?String(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),UWt(s))}function $Wt(s){var t=IH(Number(s));return G7(t)?cj(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),tW()?cj(Ure(64,BigInt(s))):cj(UWt(s)))}function VWt(s){return G7(s)?s=cj(ost(s)):(s=IH(s),G7(s)?s=String(s):(LH(s),s=ast(pf,mx)),s=cj(s)),s}function OEe(s){const t=typeof s;return s==null?s:t==="bigint"?cj(Ure(64,s)):qre(s)?t==="string"?$Wt(s):VWt(s):void 0}function HWt(s){if(typeof s!="string")throw Error();return s}function $re(s){if(s!=null&&typeof s!="string")throw Error();return s}function fv(s){return s==null||typeof s=="string"?s:void 0}function lst(s,t,n,r){return s!=null&&s[MH]===PH?s:Array.isArray(s)?((r=(n=0|s[Do])|32&r|2&r)!==n&&x0(s,r),new t(s)):(n?2&r?((s=t[Qwt])||(Bre((s=new t).v),s=t[Qwt]=s),t=s):t=new t:t=void 0,t)}function iDn(s,t,n){if(t)e:{if(!qre(t=s))throw JHe("int64");switch(typeof t){case"string":t=$Wt(t);break e;case"bigint":t=cj(Ure(64,t));break e;default:t=VWt(t)}}else t=OEe(s);return(s=t)==null?n?rDn:void 0:s}const oDn={};let lDn=function(){try{return HLe(new class extends Map{constructor(){super()}}),!1}catch{return!0}}(),Q7e=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 cDn=lDn?(Object.setPrototypeOf(Q7e.prototype,Map.prototype),Object.defineProperties(Q7e.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),Q7e):class extends Map{constructor(){super()}};function ijt(s){return s}function J7e(s){if(2&s.J)throw Error("Cannot mutate an immutable Map")}var oE=class extends cDn{constructor(s,t,n=ijt,r=ijt){super(),this.J=0|s[Do],this.K=t,this.S=n,this.fa=this.K?dDn:r;for(let a=0;a{s.call(t,a.get(r),r,a)}):super.forEach(s,t)}set(s,t){return J7e(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 dDn(s,t,n,r,a,i){return s=lst(s,r,n,i),a&&(s=dst(s)),s}function uDn(s){return[s,this.get(s)]}let hDn;function ojt(){return hDn||(hDn=new oE(Bre([]),void 0,void 0,void 0,oDn))}function ZLe(s){return lj?s[lj]:void 0}function FEe(s,t){for(const n in s)!isNaN(n)&&t(s,+n,s[n])}oE.prototype.toJSON=void 0;var sGe=class{};const mDn={Ka:!0};function pDn(s,t){t<100||TH(HRn,1)}function XLe(s,t,n,r){const a=r!==void 0;r=!!r;var i,l=lj;!a&&sW&&l&&(i=s[l])&&FEe(i,pDn),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 f=m-h;(t??(t={}))[f]=p}else l[m]=p}if(c)for(let p in c){if((o=c[p])==null||(o=n(o,r))==null)continue;let f;m=+p,u&&!Number.isNaN(m)&&(f=m+h){f[y]=cS(v)}),f.da=p.da,f}(s)),l}function fDn(s){return s[0]=jte(s[0]),s[1]=jte(s[1]),s}function jte(s){switch(typeof s){case"number":return Number.isFinite(s)?s:""+s;case"bigint":return tGe(s)?Number(s):""+s;case"boolean":return s?1:0;case"object":if(Array.isArray(s)){var t=0|s[Do];return s.length===0&&1&t?void 0:XLe(s,t,jte)}if(s!=null&&s[MH]===PH)return GWt(s);if(s instanceof V4){if((t=s.g)==null)s="";else if(typeof t=="string")s=t;else{if(EWt){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 oE?s=s.size!==0?s.V(fDn):void 0:void 0}return s}let gDn,xDn;function GWt(s){return XLe(s=s.v,0|s[Do],jte)}function r7(s,t){return WWt(s,t[0],t[1])}function WWt(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[Do],Kwt&&1&a)throw Error("rfarr");if(2048&a&&!(2&a)&&function(){if(Kwt)throw Error("carr");TH(GRn,5)}(),256&a)throw Error("farr");if(64&a)return(a|r)!==a&&x0(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 x0(s,64|a|r),s}function yDn(s,t){if(typeof s!="object")return s;if(Array.isArray(s)){var n=0|s[Do];return s.length===0&&1&n?void 0:ljt(s,n,t)}if(s!=null&&s[MH]===PH)return cjt(s);if(s instanceof oE){if(2&(t=s.J))return s;if(!s.size)return;if(n=Bre(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 Vh(s,t,n,r){oW(s),p0(s=s.v,0|s[Do],t,n,r)}function p0(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[Do]))>>14&1023||536870912)?r!=null&&(s[l+(a?0:-1)]={[n]:r}):s[i]=r),t)}function nO(){return WRn===void 0?2:4}function rO(s,t,n,r,a){let i=s.v,l=0|i[Do];r=vj(s,l)?1:r,a=!!a||r===3,r===2&&iW(s)&&(i=s.v,l=0|i[Do]);let o=(s=hst(i,t))===M9?7:0|s[Do],c=mst(o,l);var d=!(4&c);if(d){4&c&&(s=cS(s),o=0,c=i7(c,l),l=p0(i,l,t,s));let u=0,h=0;for(;u{const o=lst(l,n,!1,t);return i=o!==l&&o!=null,o}))!=null)return i&&!vj(r)&&P9(s,t),r}function Cu(s,t,n,r){let a=s.v,i=0|a[Do];if((t=JWt(a,i,t,n,r))==null)return t;if(i=0|a[Do],!vj(s,i)){const l=dst(t);l!==t&&(iW(s)&&(a=s.v,i=0|a[Do]),i=p0(a,i,n,t=l,r),P9(a,i))}return t}function eKt(s,t,n,r,a,i,l,o){var c=vj(s,n);i=c?1:i,l=!!l||i===3,c=o&&!c,(i===2||c)&&iW(s)&&(n=0|(t=s.v)[Do]);var d=(s=hst(t,a))===M9?7:0|s[Do],u=mst(d,n);if(o=!(4&u)){var h=s,m=n;const p=!!(2&u);p&&(m|=2);let f=!p,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 bst(s){let t=0,n=s.g;const r=n+10,a=s.h;for(;n>>0}function BEe(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],o7(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 vDn(s){return xP(s)}function o7(s,t){if(s.g=t,t>s.l)throw Error()}function sKt(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 nKt(s,t){if(t==0)return V7();var n=sKt(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):eDn?s.slice(n,t):new Uint8Array(s.subarray(n,t))),n.length==0?V7():new V4(n,EH)}var djt=[];function rKt(s,t,n,r){if(UEe.length){const a=UEe.pop();return a.o(r),a.g.init(s,t,n,r),a}return new bDn(s,t,n,r)}function aKt(s){s.g.clear(),s.l=-1,s.h=-1,UEe.length<100&&UEe.push(s)}function iKt(s){var t=s.g;if(t.g==t.l)return!1;s.m=s.g.g;var n=s3(s.g);if(t=n>>>3,!((n&=7)>=0&&n<=5)||t<1)throw Error();return s.l=t,s.h=n,!0}function e4e(s){switch(s.h){case 0:s.h!=0?e4e(s):bst(s.g);break;case 1:o7(s=s.g,s.g+8);break;case 2:if(s.h!=2)e4e(s);else{var t=s3(s.g);o7(s=s.g,s.g+t)}break;case 5:o7(s=s.g,s.g+4);break;case 3:for(t=s.l;;){if(!iKt(s))throw Error();if(s.h==4){if(s.l!=t)throw Error();break}e4e(s)}break;default:throw Error()}}function Vre(s,t,n){const r=s.g.l;var a=s3(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 _st(s){var t=s3(s.g),n=sKt(s=s.g,t);if(s=s.h,LRn){var r,a=s;(r=X7e)||(r=X7e=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(Gle===void 0){try{r.decode(new Uint8Array([128]))}catch{}try{r.decode(new Uint8Array([97])),Gle=!0}catch{Gle=!1}}throw!Gle&&(X7e=void 0),o}}else{t=(i=n)+t,n=[];let o,c=null;for(;i=t?nI():(o=s[i++],l<194||(192&o)!=128?(i--,nI()):n.push((31&l)<<6|63&o)):l<240?i>=t-1?nI():(o=s[i++],(192&o)!=128||l===224&&o<160||l===237&&o>=160||(192&(r=s[i++]))!=128?(i--,nI()):n.push((15&l)<<12|(63&o)<<6|63&r)):l<=244?i>=t-2?nI():(o=s[i++],(192&o)!=128||o-144+(l<<28)>>30||(192&(r=s[i++]))!=128||(192&(a=s[i++]))!=128?(i--,nI()):(l=(7&l)<<18|(63&o)<<12|(63&r)<<6|63&a,l-=65536,n.push(55296+(l>>10&1023),56320+(1023&l)))):nI(),n.length>=8192&&(c=Wwt(c,n),n.length=0)}i=Wwt(c,n)}return i}function oKt(s){const t=s3(s.g);return nKt(s.g,t)}function JLe(s,t,n){var r=s3(s.g);for(r=s.g.g+r;s.g.g>>0,this.g=t>>>0}};let _Dn;function hjt(s){return s?/^-?\d+$/.test(s)?(KLe(s),new rGe(pf,mx)):null:wDn||(wDn=new rGe(0,0))}var rGe=class{constructor(s,t){this.h=s>>>0,this.g=t>>>0}};let wDn;function Kq(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 cW(s,t){for(;t>127;)s.g.push(127&t|128),t>>>=7;s.g.push(t)}function eIe(s,t){if(t>=0)cW(s,t);else{for(let n=0;n<9;n++)s.g.push(127&t|128),t>>=7;s.g.push(1)}}function wst(s){var t=pf;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 RH(s,t){t.length!==0&&(s.l.push(t),s.h+=t.length)}function EN(s,t,n){cW(s.g,8*t+n)}function jst(s,t){return EN(s,t,2),t=s.g.end(),RH(s,t),t.push(s.h),t}function Nst(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 tIe(s,t,n){EN(s,t,2),cW(s.g,n.length),RH(s,s.g.end()),RH(s,n)}function qEe(s,t,n,r){n!=null&&(t=jst(s,t),r(n,s),Nst(s,t))}function x3(){const s=class{constructor(){throw Error()}};return Object.setPrototypeOf(s,s.prototype),s}var kst=x3(),lKt=x3(),Sst=x3(),Cst=x3(),Ast=x3(),cKt=x3(),jDn=x3(),sIe=x3(),dKt=x3(),uKt=x3();function y3(s,t,n){var r=s.v;lj&&lj in r&&(r=r[lj])&&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 Oo=class{constructor(s,t){this.v=WWt(s,t,void 0,2048)}toJSON(){return GWt(this)}j(){var a;var s=rOn,t=this.v,n=s.g,r=lj;if(sW&&r&&((a=t[r])==null?void 0:a[n])!=null&&TH(VRn,3),t=s.g,Jwt&&lj&&Jwt===void 0&&(r=(n=this.v)[lj])&&(r=r.da))try{r(n,t,mDn)}catch(i){SWt(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[Do];return ust(this,s,t)?cst(this,s,!0):new this.constructor(aW(s,t,!1))}};Oo.prototype[MH]=PH,Oo.prototype.toString=function(){return this.v.toString()};var dW=class{constructor(s,t,n){this.g=s,this.h=t,s=kst,this.l=!!s&&n===s||!1}};function nIe(s,t){return new dW(s,t,kst)}function hKt(s,t,n,r,a){qEe(s,n,gKt(t,r),a)}const NDn=nIe(function(s,t,n,r,a){return s.h===2&&(Vre(s,gst(t,r,n),a),!0)},hKt),kDn=nIe(function(s,t,n,r,a){return s.h===2&&(Vre(s,gst(t,r,n),a),!0)},hKt);var rIe=Symbol(),aIe=Symbol(),aGe=Symbol(),mjt=Symbol(),pjt=Symbol();let mKt,pKt;function L9(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 gDn||(gDn=[0,void 0,!0]);case"number":return h>0?void 0:h===0?xDn||(xDn=[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,mKt??(mKt=i),pKt??(pKt=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 Tst(s,t,n,r,a){const i=n.g;let l,o;s[t]=(c,d,u)=>i(c,d,u,o||(o=L9(aIe,Est,Tst,r).T),l||(l=Mst(r)),a)}function Mst(s){let t=s[aGe];if(t!=null)return t;const n=L9(aIe,Est,Tst,s);return t=n.ma?(r,a)=>mKt(r,a,n):(r,a)=>{for(;iKt(a)&&a.h!=4;){var i=a.l,l=n[i];if(l==null){var o=n.ba;o&&(o=o[i])&&(o=CDn(o))!=null&&(l=n[i]=o)}if(l==null||!l(a,r,i)){if(l=(o=a).m,e4e(o),o.ha)var c=void 0;else c=o.g.g-l,o.g.g=l,c=nKt(o.g,c);l=void 0,o=r,c&&((l=o[lj]??(o[lj]=new sGe))[i]??(l[i]=[])).push(c)}}return(r=ZLe(r))&&(r.da=n.qa[pjt]),!0},s[aGe]=t,s[pjt]=SDn.bind(s),t}function SDn(s,t,n,r){var a=this[aIe];const i=this[aGe],l=r7(void 0,a.T),o=ZLe(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 p of m){u=rKt(p);try{c=!0,i(l,u)}finally{aKt(u)}}else r==null||r(s,h,m)},t==null)FEe(o,a);else if(o!=null){const u=o[t];u&&a(o,t,u)}if(c){let u=0|s[Do];if(2&u&&2048&u&&!(n!=null&&n.Ka))throw Error();const h=nW(u),m=(p,f)=>{if(lE(s,p,h)!=null){if((n==null?void 0:n.Qa)===1)return;throw Error()}f!=null&&(u=p0(s,u,p,f,h)),delete o[p]};t==null?RWt(l,0|l[Do],(p,f)=>{m(p,f)}):m(t,lE(l,t,h))}}}}function CDn(s){const t=(s=fKt(s))[0].g;if(s=s[1]){const n=Mst(s),r=L9(aIe,Est,Tst,s).T;return(a,i,l)=>t(a,i,l,r,n)}return t}function iIe(s,t,n){s[t]=n.h}function oIe(s,t,n,r){let a,i;const l=n.h;s[t]=(o,c,d)=>l(o,c,d,i||(i=L9(rIe,iIe,oIe,r).T),a||(a=xKt(r)))}function xKt(s){let t=s[mjt];if(!t){const n=L9(rIe,iIe,oIe,s);t=(r,a)=>yKt(r,a,n),s[mjt]=t}return t}function yKt(s,t,n){RWt(s,0|s[Do],(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=fKt(c))[0].h;if(c=c[1]){const u=xKt(c),h=L9(rIe,iIe,oIe,c).T;c=l.ma?pKt(h,u):(m,p,f)=>d(m,p,f,h,u)}else c=d;return l[o]=c}}(n,r);i?i(t,a,r):r<500||TH(eGe,3)}}),(s=ZLe(s))&&FEe(s,(r,a,i)=>{for(RH(t,t.g.end()),r=0;r{qEe(s,n,r7([l,i],r),a)});else if(Array.isArray(t)){for(let i=0;i>BigInt(32))),Kq(s.g,n.h,n.g);break;default:n=hjt(t),Kq(s.g,n.h,n.g)}}function _Kt(s,t,n){(t=rW(t))!=null&&t!=null&&(EN(s,n,0),eIe(s.g,t))}function wKt(s,t,n){(t=zWt(t))!=null&&(EN(s,n,0),s.g.g.push(t?1:0))}function jKt(s,t,n){(t=fv(t))!=null&&tIe(s,n,kWt(t))}function NKt(s,t,n,r,a){qEe(s,n,gKt(t,r),a)}function kKt(s,t,n){(t=t==null||typeof t=="string"||t instanceof V4?t:void 0)!=null&&tIe(s,n,yst(t,!0).buffer)}function SKt(s,t,n){(t=BWt(t))!=null&&t!=null&&(EN(s,n,0),cW(s.g,t))}function CKt(s,t,n){return(s.h===5||s.h===2)&&(t=lW(t,0|t[Do],n),s.h==2?JLe(s,BEe,t):t.push(BEe(s.g)),!0)}var vx=x1(function(s,t,n){return s.h===5&&(y1(t,n,BEe(s.g)),!0)},vKt,sIe),TDn=hW(CKt,function(s,t,n){if((t=uW(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"))||(KLe(r),r=_te(pf,mx))),r;if(a==="number")return(r=IH(r))>=0&&G7(r)||(LH(r),r=OWt(pf,mx)),r}}(t),t!=null&&(typeof t=="string"&&ujt(t),t!=null))switch(EN(s,n,0),typeof t){case"number":s=s.g,LH(t),Kq(s,pf,mx);break;case"bigint":n=BigInt.asUintN(64,t),n=new nGe(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),Kq(s.g,n.h,n.g);break;default:n=ujt(t),Kq(s.g,n.h,n.g)}},jDn),l0=x1(function(s,t,n){return s.h===0&&(y1(t,n,xP(s.g)),!0)},_Kt,Cst),Hre=hW(function(s,t,n){return(s.h===0||s.h===2)&&(t=lW(t,0|t[Do],n),s.h==2?JLe(s,xP,t):t.push(xP(s.g)),!0)},function(s,t,n){if((t=uW(rW,t))!=null&&t.length){n=jst(s,n);for(let r=0;r{{const i={ea:!0};r&&Object.assign(i,r),n=rKt(n,void 0,void 0,i);try{const l=new s,o=l.v;Mst(t)(o,n);var a=l}finally{aKt(n)}}return a}}function lIe(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}}}};yKt(this.v,t,L9(rIe,iIe,oIe,s)),RH(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=xjt.createPolicy("goog#html",{createHTML:r,createScript:r,createScriptURL:r})}catch{}return n}()),s=(t=s9e)?t.createScriptURL(s):s,new class{constructor(n){this.g=n}toString(){return this.g+""}}(s)}function Wle(s,...t){if(t.length===0)return yjt(s[0]);let n=s[0];for(let r=0;r({index:q2(r,1)??0??-1,score:Eg(r,2)??0,categoryName:fv(bf(r,3))??""??"",displayName:fv(bf(r,4))??""??""})),headIndex:t,headName:n}}function lOn(s){const t={classifications:cE(s,$Dn,1).map(n=>{var r;return Bst(((r=Cu(n,DKt,4))==null?void 0:r.g())??[],q2(n,2)??0,fv(bf(n,3))??"")})};return function(n){return n==null?n:typeof n=="bigint"?(tGe(n)?n=Number(n):(n=Ure(64,n),n=tGe(n)?Number(n):String(n)),n):qre(n)?typeof n=="number"?ost(n):qWt(n):void 0}(bf(s,2,void 0,void 0,OEe))!=null&&(t.timestampMs=cYt(bf(s,2,void 0,void 0,OEe)??KWt)),t}function dYt(s){var l,o;var t=rO(s,3,v4,nO()),n=rO(s,2,rW,nO()),r=rO(s,1,fv,nO()),a=rO(s,9,fv,nO());const i={categories:[],keypoints:[]};for(let c=0;ct>127?t-256:t)}function Tjt(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 Mjt(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;await self.import(s.toString())}}function mYt(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 Bo(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 Pjt(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]=mYt(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 Ljt(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 l5(s,t,n){s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=n}function cT(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)}}qB.forVisionTasks=function(s,t=!1){return Yle("vision",s??Wle``,t)},qB.forTextTasks=function(s,t=!1){return Yle("text",s??Wle``,t)},qB.forGenAiTasks=function(s,t=!1){return Yle("genai",s??Wle``,t)},qB.forAudioTasks=function(s,t=!1){return Yle("audio",s??Wle``,t)},qB.isSimdSupported=function(s=!1){return uYt(s)};async function dOn(s,t,n,r){return s=await(async(a,i,l,o,c)=>{if(i&&await Mjt(i),!self.ModuleFactory||l&&(await Mjt(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 a9e(s,t){const n=Cu(s.baseOptions,$Ee,1)||new $Ee;typeof t=="string"?(Vh(n,2,$re(t)),Vh(n,1)):t instanceof Uint8Array&&(Vh(n,1,nst(t,!1)),Vh(n,2)),bl(s.baseOptions,0,1,n)}function Ijt(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 yo(s,t){s.C=Math.max(s.C,t)}function hIe(s,t){s.B=new U_,bj(s.B,2,"PassThroughCalculator"),Bp(s.B,"free_memory"),iu(s.B,"free_memory_unused_out"),Tf(t,"free_memory"),TN(t,s.B)}function DH(s,t){Bp(s.B,t),iu(s.B,t+"_unused_out")}function mIe(s){s.g.addBoolToStream(!0,"free_memory",s.C)}var dGe=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=Cu(this.baseOptions,$Ee,1))!=null&&a.g()||(i=Cu(this.baseOptions,$Ee,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=Cu(d.baseOptions,kjt,3);if(!h){var m=h=new kjt,p=new vjt;aJ(m,4,t4e,p)}"delegate"in u&&(u.delegate==="GPU"?(u=h,m=new DDn,aJ(u,2,t4e,m)):(u=h,m=new vjt,aJ(u,4,t4e,m))),bl(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),a9e(this,"/model.dat"),this.m(),this.L()});if(c.modelAssetBuffer instanceof Uint8Array)a9e(this,c.modelAssetBuffer);else if(c.modelAssetBuffer)return async function(d){const u=[];for(var h=0;;){const{done:m,value:p}=await d.read();if(m)break;u.push(p),h+=p.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=>{a9e(this,d),this.m(),this.L()})}return this.m(),this.L(),Promise.resolve()}L(){}ca(){let s;if(this.g.ca(t=>{s=ODn(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,Ijt(this)}finishProcessing(){this.g.finishProcessing(),Ijt(this)}close(){this.B=void 0,this.g.closeGraph()}};function KM(s,t){if(!s)throw Error(`Unable to obtain required WebGL resource: ${t}`);return s}dGe.prototype.close=dGe.prototype.close;class uOn{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 Rjt(s,t,n){const r=s.g;if(n=KM(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 Djt(s,t){const n=s.g,r=KM(n.createVertexArray(),"Failed to create vertex array");n.bindVertexArray(r);const a=KM(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=KM(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 uOn(n,r,a,i)}function Ust(s,t){if(s.g){if(t!==s.g)throw Error("Cannot change GL context once initialized")}else s.g=t}function hOn(s,t,n,r){return Ust(s,t),s.h||(s.m(),s.D()),n?(s.u||(s.u=Djt(s,!0)),n=s.u):(s.A||(s.A=Djt(s,!1)),n=s.A),t.useProgram(s.h),n.bind(),s.l(),s=r(),n.g.bindVertexArray(null),s}function pYt(s,t,n){return Ust(s,t),s=KM(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 fYt(s,t,n){Ust(s,t),s.B||(s.B=KM(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 mOn(s){var t;(t=s.g)==null||t.bindFramebuffer(s.g.FRAMEBUFFER,null)}var gYt=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=KM(s.createProgram(),"Failed to create WebGL program"),this.X=Rjt(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=Rjt(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 dA(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 uGe(s){var t=dA(s,1);if(!t){if(t=dA(s,0))t=new Float32Array(t).map(r=>r/255);else{t=new Float32Array(s.width*s.height);const r=OH(s);var n=qst(s);if(fYt(n,r,xYt(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 uGe(this)}N(){return xYt(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=OH(this),a=qst(this);r.activeTexture(r.TEXTURE1),n=pYt(a,r,this.m?r.LINEAR:r.NEAREST),r.bindTexture(r.TEXTURE_2D,n);const i=yYt(this);r.texImage2D(r.TEXTURE_2D,0,i,this.width,this.height,0,r.RED,r.FLOAT,null),r.bindTexture(r.TEXTURE_2D,null),fYt(a,r,n),hOn(a,r,!1,()=>{vYt(this),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLE_FAN,0,4),hGe(this)}),mOn(a),hGe(this)}}s.push(n)}return new U0(s,this.m,this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&OH(this).deleteTexture(dA(this,2)),Ojt=-1}};U0.prototype.close=U0.prototype.close,U0.prototype.clone=U0.prototype.clone,U0.prototype.getAsWebGLTexture=U0.prototype.N,U0.prototype.getAsFloat32Array=U0.prototype.ia,U0.prototype.getAsUint8Array=U0.prototype.ja,U0.prototype.hasWebGLTexture=U0.prototype.R,U0.prototype.hasFloat32Array=U0.prototype.ka,U0.prototype.hasUint8Array=U0.prototype.Fa;var Ojt=250;function AS(...s){return s.map(([t,n])=>({start:t,end:n}))}const pOn=function(s){return class extends s{Ja(){this.i._registerModelResourcesGraphService()}}}((Fjt=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:hYt()?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?'),Bo(this,r||"input_audio",i=>{Bo(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){l5(this,"__graph_config__",t=>{s(t)}),Bo(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),Bo(this,r,l=>{this.i._addAudioToInputStream(this.g,t,n,l,a)})}addGpuBufferToStream(s,t,n){Bo(this,t,r=>{const[a,i]=Pjt(this,s,r);this.i._addBoundTextureToStream(r,a,i,n)})}addBoolToStream(s,t,n){Bo(this,t,r=>{this.i._addBoolToInputStream(s,r,n)})}addDoubleToStream(s,t,n){Bo(this,t,r=>{this.i._addDoubleToInputStream(s,r,n)})}addFloatToStream(s,t,n){Bo(this,t,r=>{this.i._addFloatToInputStream(s,r,n)})}addIntToStream(s,t,n){Bo(this,t,r=>{this.i._addIntToInputStream(s,r,n)})}addUintToStream(s,t,n){Bo(this,t,r=>{this.i._addUintToInputStream(s,r,n)})}addStringToStream(s,t,n){Bo(this,t,r=>{Bo(this,s,a=>{this.i._addStringToInputStream(a,r,n)})})}addStringRecordToStream(s,t,n){Bo(this,t,r=>{Ljt(this,Object.keys(s),a=>{Ljt(this,Object.values(s),i=>{this.i._addFlatHashMapToInputStream(a,i,Object.keys(s).length,r,n)})})})}addProtoToStream(s,t,n,r){Bo(this,n,a=>{Bo(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){Bo(this,s,n=>{this.i._addEmptyPacketToInputStream(n,t)})}addBoolVectorToStream(s,t,n){Bo(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){Bo(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){Bo(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){Bo(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){Bo(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){Bo(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)Bo(this,i,l=>{this.i._addStringVectorEntry(a,l)});this.i._addStringVectorToInputStream(a,r,n)})}addBoolToInputSidePacket(s,t){Bo(this,t,n=>{this.i._addBoolToInputSidePacket(s,n)})}addDoubleToInputSidePacket(s,t){Bo(this,t,n=>{this.i._addDoubleToInputSidePacket(s,n)})}addFloatToInputSidePacket(s,t){Bo(this,t,n=>{this.i._addFloatToInputSidePacket(s,n)})}addIntToInputSidePacket(s,t){Bo(this,t,n=>{this.i._addIntToInputSidePacket(s,n)})}addUintToInputSidePacket(s,t){Bo(this,t,n=>{this.i._addUintToInputSidePacket(s,n)})}addStringToInputSidePacket(s,t){Bo(this,t,n=>{Bo(this,s,r=>{this.i._addStringToInputSidePacket(r,n)})})}addProtoToInputSidePacket(s,t,n){Bo(this,n,r=>{Bo(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){Bo(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){Bo(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){Bo(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){Bo(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){Bo(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){Bo(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)Bo(this,a,i=>{this.i._addStringVectorEntry(r,i)});this.i._addStringVectorToInputSidePacket(r,n)})}attachBoolListener(s,t){l5(this,s,t),Bo(this,s,n=>{this.i._attachBoolListener(n)})}attachBoolVectorListener(s,t){cT(this,s,t),Bo(this,s,n=>{this.i._attachBoolVectorListener(n)})}attachIntListener(s,t){l5(this,s,t),Bo(this,s,n=>{this.i._attachIntListener(n)})}attachIntVectorListener(s,t){cT(this,s,t),Bo(this,s,n=>{this.i._attachIntVectorListener(n)})}attachUintListener(s,t){l5(this,s,t),Bo(this,s,n=>{this.i._attachUintListener(n)})}attachUintVectorListener(s,t){cT(this,s,t),Bo(this,s,n=>{this.i._attachUintVectorListener(n)})}attachDoubleListener(s,t){l5(this,s,t),Bo(this,s,n=>{this.i._attachDoubleListener(n)})}attachDoubleVectorListener(s,t){cT(this,s,t),Bo(this,s,n=>{this.i._attachDoubleVectorListener(n)})}attachFloatListener(s,t){l5(this,s,t),Bo(this,s,n=>{this.i._attachFloatListener(n)})}attachFloatVectorListener(s,t){cT(this,s,t),Bo(this,s,n=>{this.i._attachFloatVectorListener(n)})}attachStringListener(s,t){l5(this,s,t),Bo(this,s,n=>{this.i._attachStringListener(n)})}attachStringVectorListener(s,t){cT(this,s,t),Bo(this,s,n=>{this.i._attachStringVectorListener(n)})}attachProtoListener(s,t,n){l5(this,s,t),Bo(this,s,r=>{this.i._attachProtoListener(r,n||!1)})}attachProtoVectorListener(s,t,n){cT(this,s,t),Bo(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?'),l5(this,s,(r,a)=>{r=new Float32Array(r.buffer,r.byteOffset,r.length/4),t(r,a)}),Bo(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 Fjt{get ga(){return this.i}pa(s,t,n){Bo(this,t,r=>{const[a,i]=Pjt(this,s,r);this.ga._addBoundTextureAsImageToStream(r,a,i,n)})}Z(s,t){l5(this,s,t),Bo(this,s,n=>{this.ga._attachImageListener(n)})}aa(s,t){cT(this,s,t),Bo(this,s,n=>{this.ga._attachImageVectorListener(n)})}}));var Fjt,ES=class extends pOn{};async function bu(s,t,n){return async function(r,a,i,l){return dOn(r,a,i,l)}(s,n.canvas??(hYt()?void 0:document.createElement("canvas")),t,n)}function bYt(s,t,n,r){if(s.U){const i=new UKt;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].");Ko(i,1,(a.left+a.right)/2),Ko(i,2,(a.top+a.bottom)/2),Ko(i,4,a.right-a.left),Ko(i,3,a.bottom-a.top)}else Ko(i,1,.5),Ko(i,2,.5),Ko(i,4,1),Ko(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(Ko(i,5,-Math.PI*n.rotationDegrees/180),(n==null?void 0:n.rotationDegrees)%180!=0){const[l,o]=mYt(t);n=Eg(i,3)*o/l,a=Eg(i,4)*l/o,Ko(i,4,n),Ko(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 TS(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'.");bYt(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'.");bYt(s,t,n,r)}function FH(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 U0([a],n,!1,s.g.i.canvas,s.P,i,t),r?s.clone():s}var _j=class extends dGe{constructor(s,t,n,r){super(s),this.g=s,this.X=t,this.U=n,this.oa=r,this.P=new gYt}l(s,t=!0){if("runningMode"in s&&Vh(this.baseOptions,2,wte(!!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()}};_j.prototype.close=_j.prototype.close;var i2=class extends _j{constructor(s,t){super(new ES(s,t),"image_in","norm_rect_in",!1),this.j={detections:[]},bl(s=this.h=new dIe,0,1,t=new hg),Ko(this.h,2,.5),Ko(this.h,3,.3)}get baseOptions(){return Cu(this.h,hg,1)}set baseOptions(s){bl(this.h,0,1,s)}o(s){return"minDetectionConfidence"in s&&Ko(this.h,2,s.minDetectionConfidence??.5),"minSuppressionThreshold"in s&&Ko(this.h,3,s.minSuppressionThreshold??.3),this.l(s)}F(s,t){return this.j={detections:[]},TS(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},b3(this,s,n,t),this.j}m(){var s=new Aj;Tf(s,"image_in"),Tf(s,"norm_rect_in"),qu(s,"detections");const t=new Cj;y3(t,YDn,this.h);const n=new U_;bj(n,2,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),Bp(n,"IMAGE:image_in"),Bp(n,"NORM_RECT:norm_rect_in"),iu(n,"DETECTIONS:detections"),n.o(t),TN(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=FKt(i),this.j.detections.push(dYt(r));yo(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{yo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};i2.prototype.detectForVideo=i2.prototype.G,i2.prototype.detect=i2.prototype.F,i2.prototype.setOptions=i2.prototype.o,i2.createFromModelPath=async function(s,t){return bu(i2,s,{baseOptions:{modelAssetPath:t}})},i2.createFromModelBuffer=function(s,t){return bu(i2,s,{baseOptions:{modelAssetBuffer:t}})},i2.createFromOptions=function(s,t){return bu(i2,s,t)};var $st=AS([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]),Vst=AS([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]),Hst=AS([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),_Yt=AS([474,475],[475,476],[476,477],[477,474]),Gst=AS([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]),Wst=AS([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),wYt=AS([469,470],[470,471],[471,472],[472,469]),Kst=AS([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]),jYt=[...$st,...Vst,...Hst,...Gst,...Wst,...Kst],NYt=AS([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 zjt(s){s.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var Hf=class extends _j{constructor(s,t){super(new ES(s,t),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,bl(s=this.h=new GKt,0,1,t=new hg),this.A=new HKt,bl(this.h,0,3,this.A),this.u=new dIe,bl(this.h,0,2,this.u),dE(this.u,4,1),Ko(this.u,2,.5),Ko(this.A,2,.5),Ko(this.h,4,.5)}get baseOptions(){return Cu(this.h,hg,1)}set baseOptions(s){bl(this.h,0,1,s)}o(s){return"numFaces"in s&&dE(this.u,4,s.numFaces??1),"minFaceDetectionConfidence"in s&&Ko(this.u,2,s.minFaceDetectionConfidence??.5),"minTrackingConfidence"in s&&Ko(this.h,4,s.minTrackingConfidence??.5),"minFacePresenceConfidence"in s&&Ko(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 zjt(this),TS(this,s,t),this.j}G(s,t,n){return zjt(this),b3(this,s,n,t),this.j}m(){var s=new Aj;Tf(s,"image_in"),Tf(s,"norm_rect"),qu(s,"face_landmarks");const t=new Cj;y3(t,XDn,this.h);const n=new U_;bj(n,2,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),Bp(n,"IMAGE:image_in"),Bp(n,"NORM_RECT:norm_rect"),iu(n,"NORM_LANDMARKS:face_landmarks"),n.o(t),TN(s,n),this.g.attachProtoVectorListener("face_landmarks",(r,a)=>{for(const i of r)r=Gre(i),this.j.faceLandmarks.push(uIe(r));yo(this,a)}),this.g.attachEmptyPacketListener("face_landmarks",r=>{yo(this,r)}),this.outputFaceBlendshapes&&(qu(s,"blendshapes"),iu(n,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(r,a)=>{if(this.outputFaceBlendshapes)for(const i of r)r=cIe(i),this.j.faceBlendshapes.push(Bst(r.g()??[]));yo(this,a)}),this.g.attachEmptyPacketListener("blendshapes",r=>{yo(this,r)})),this.outputFacialTransformationMatrixes&&(qu(s,"face_geometry"),iu(n,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(r,a)=>{if(this.outputFacialTransformationMatrixes)for(const i of r)(r=Cu(r=ZDn(i),UDn,2))&&this.j.facialTransformationMatrixes.push({rows:q2(r,1)??0??0,columns:q2(r,2)??0??0,data:rO(r,3,v4,nO()).slice()??[]});yo(this,a)}),this.g.attachEmptyPacketListener("face_geometry",r=>{yo(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Hf.prototype.detectForVideo=Hf.prototype.G,Hf.prototype.detect=Hf.prototype.F,Hf.prototype.setOptions=Hf.prototype.o,Hf.createFromModelPath=function(s,t){return bu(Hf,s,{baseOptions:{modelAssetPath:t}})},Hf.createFromModelBuffer=function(s,t){return bu(Hf,s,{baseOptions:{modelAssetBuffer:t}})},Hf.createFromOptions=function(s,t){return bu(Hf,s,t)},Hf.FACE_LANDMARKS_LIPS=$st,Hf.FACE_LANDMARKS_LEFT_EYE=Vst,Hf.FACE_LANDMARKS_LEFT_EYEBROW=Hst,Hf.FACE_LANDMARKS_LEFT_IRIS=_Yt,Hf.FACE_LANDMARKS_RIGHT_EYE=Gst,Hf.FACE_LANDMARKS_RIGHT_EYEBROW=Wst,Hf.FACE_LANDMARKS_RIGHT_IRIS=wYt,Hf.FACE_LANDMARKS_FACE_OVAL=Kst,Hf.FACE_LANDMARKS_CONTOURS=jYt,Hf.FACE_LANDMARKS_TESSELATION=NYt;var Yst=AS([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 Bjt(s){s.gestures=[],s.landmarks=[],s.worldLandmarks=[],s.handedness=[]}function Ujt(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 qjt(s,t=!0){const n=[];for(const a of s){var r=cIe(a);s=[];for(const i of r.g())r=t&&q2(i,1)!=null?q2(i,1)??0:-1,s.push({score:Eg(i,2)??0,index:r,categoryName:fv(bf(i,3))??""??"",displayName:fv(bf(i,4))??""??""});n.push(s)}return n}var aw=class extends _j{constructor(s,t){super(new ES(s,t),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],bl(s=this.j=new YKt,0,1,t=new hg),this.u=new Dst,bl(this.j,0,2,this.u),this.D=new Rst,bl(this.u,0,3,this.D),this.A=new KKt,bl(this.u,0,2,this.A),this.h=new QDn,bl(this.j,0,3,this.h),Ko(this.A,2,.5),Ko(this.u,4,.5),Ko(this.D,2,.5)}get baseOptions(){return Cu(this.j,hg,1)}set baseOptions(s){bl(this.j,0,1,s)}o(s){var a,i,l,o;if(dE(this.A,3,s.numHands??1),"minHandDetectionConfidence"in s&&Ko(this.A,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Ko(this.u,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Ko(this.D,2,s.minHandPresenceConfidence??.5),s.cannedGesturesClassifierOptions){var t=new cB,n=t,r=cGe(s.cannedGesturesClassifierOptions,(a=Cu(this.h,cB,3))==null?void 0:a.l());bl(n,0,2,r),bl(this.h,0,3,t)}else s.cannedGesturesClassifierOptions===void 0&&((i=Cu(this.h,cB,3))==null||i.g());return s.customGesturesClassifierOptions?(bl(n=t=new cB,0,2,r=cGe(s.customGesturesClassifierOptions,(l=Cu(this.h,cB,4))==null?void 0:l.l())),bl(this.h,0,4,t)):s.customGesturesClassifierOptions===void 0&&((o=Cu(this.h,cB,4))==null||o.g()),this.l(s)}Ha(s,t){return Bjt(this),TS(this,s,t),Ujt(this)}Ia(s,t,n){return Bjt(this),b3(this,s,n,t),Ujt(this)}m(){var s=new Aj;Tf(s,"image_in"),Tf(s,"norm_rect"),qu(s,"hand_gestures"),qu(s,"hand_landmarks"),qu(s,"world_hand_landmarks"),qu(s,"handedness");const t=new Cj;y3(t,JDn,this.j);const n=new U_;bj(n,2,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),Bp(n,"IMAGE:image_in"),Bp(n,"NORM_RECT:norm_rect"),iu(n,"HAND_GESTURES:hand_gestures"),iu(n,"LANDMARKS:hand_landmarks"),iu(n,"WORLD_LANDMARKS:world_hand_landmarks"),iu(n,"HANDEDNESS:handedness"),n.o(t),TN(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r){r=Gre(i);const l=[];for(const o of cE(r,BKt,1))l.push({x:Eg(o,1)??0,y:Eg(o,2)??0,z:Eg(o,3)??0,visibility:Eg(o,4)??0});this.landmarks.push(l)}yo(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{yo(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r){r=Yq(i);const l=[];for(const o of cE(r,zKt,1))l.push({x:Eg(o,1)??0,y:Eg(o,2)??0,z:Eg(o,3)??0,visibility:Eg(o,4)??0});this.worldLandmarks.push(l)}yo(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{yo(this,r)}),this.g.attachProtoVectorListener("hand_gestures",(r,a)=>{this.gestures.push(...qjt(r,!1)),yo(this,a)}),this.g.attachEmptyPacketListener("hand_gestures",r=>{yo(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{this.handedness.push(...qjt(r)),yo(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{yo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};function $jt(s){return{landmarks:s.landmarks,worldLandmarks:s.worldLandmarks,handednesses:s.handedness,handedness:s.handedness}}aw.prototype.recognizeForVideo=aw.prototype.Ia,aw.prototype.recognize=aw.prototype.Ha,aw.prototype.setOptions=aw.prototype.o,aw.createFromModelPath=function(s,t){return bu(aw,s,{baseOptions:{modelAssetPath:t}})},aw.createFromModelBuffer=function(s,t){return bu(aw,s,{baseOptions:{modelAssetBuffer:t}})},aw.createFromOptions=function(s,t){return bu(aw,s,t)},aw.HAND_CONNECTIONS=Yst;var iw=class extends _j{constructor(s,t){super(new ES(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],bl(s=this.h=new Dst,0,1,t=new hg),this.u=new Rst,bl(this.h,0,3,this.u),this.j=new KKt,bl(this.h,0,2,this.j),dE(this.j,3,1),Ko(this.j,2,.5),Ko(this.u,2,.5),Ko(this.h,4,.5)}get baseOptions(){return Cu(this.h,hg,1)}set baseOptions(s){bl(this.h,0,1,s)}o(s){return"numHands"in s&&dE(this.j,3,s.numHands??1),"minHandDetectionConfidence"in s&&Ko(this.j,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Ko(this.h,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Ko(this.u,2,s.minHandPresenceConfidence??.5),this.l(s)}F(s,t){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],TS(this,s,t),$jt(this)}G(s,t,n){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],b3(this,s,n,t),$jt(this)}m(){var s=new Aj;Tf(s,"image_in"),Tf(s,"norm_rect"),qu(s,"hand_landmarks"),qu(s,"world_hand_landmarks"),qu(s,"handedness");const t=new Cj;y3(t,eOn,this.h);const n=new U_;bj(n,2,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),Bp(n,"IMAGE:image_in"),Bp(n,"NORM_RECT:norm_rect"),iu(n,"LANDMARKS:hand_landmarks"),iu(n,"WORLD_LANDMARKS:world_hand_landmarks"),iu(n,"HANDEDNESS:handedness"),n.o(t),TN(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r)r=Gre(i),this.landmarks.push(uIe(r));yo(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{yo(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r)r=Yq(i),this.worldLandmarks.push(oJ(r));yo(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{yo(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{var i=this.handedness,l=i.push;const o=[];for(const c of r){r=cIe(c);const d=[];for(const u of r.g())d.push({score:Eg(u,2)??0,index:q2(u,1)??0??-1,categoryName:fv(bf(u,3))??""??"",displayName:fv(bf(u,4))??""??""});o.push(d)}l.call(i,...o),yo(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{yo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};iw.prototype.detectForVideo=iw.prototype.G,iw.prototype.detect=iw.prototype.F,iw.prototype.setOptions=iw.prototype.o,iw.createFromModelPath=function(s,t){return bu(iw,s,{baseOptions:{modelAssetPath:t}})},iw.createFromModelBuffer=function(s,t){return bu(iw,s,{baseOptions:{modelAssetBuffer:t}})},iw.createFromOptions=function(s,t){return bu(iw,s,t)},iw.HAND_CONNECTIONS=Yst;var kYt=AS([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 Vjt(s){s.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function Hjt(s){try{if(!s.D)return s.h;s.D(s.h)}finally{mIe(s)}}function Xle(s,t){s=Gre(s),t.push(uIe(s))}var Sp=class extends _j{constructor(s,t){super(new ES(s,t),"input_frames_image",null,!1),this.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,bl(s=this.j=new eYt,0,1,t=new hg),this.I=new Rst,bl(this.j,0,2,this.I),this.W=new tOn,bl(this.j,0,3,this.W),this.u=new dIe,bl(this.j,0,4,this.u),this.O=new HKt,bl(this.j,0,5,this.O),this.A=new QKt,bl(this.j,0,6,this.A),this.M=new JKt,bl(this.j,0,7,this.M),Ko(this.u,2,.5),Ko(this.u,3,.3),Ko(this.O,2,.5),Ko(this.A,2,.5),Ko(this.A,3,.3),Ko(this.M,2,.5),Ko(this.I,2,.5)}get baseOptions(){return Cu(this.j,hg,1)}set baseOptions(s){bl(this.j,0,1,s)}o(s){return"minFaceDetectionConfidence"in s&&Ko(this.u,2,s.minFaceDetectionConfidence??.5),"minFaceSuppressionThreshold"in s&&Ko(this.u,3,s.minFaceSuppressionThreshold??.3),"minFacePresenceConfidence"in s&&Ko(this.O,2,s.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in s&&(this.outputFaceBlendshapes=!!s.outputFaceBlendshapes),"minPoseDetectionConfidence"in s&&Ko(this.A,2,s.minPoseDetectionConfidence??.5),"minPoseSuppressionThreshold"in s&&Ko(this.A,3,s.minPoseSuppressionThreshold??.3),"minPosePresenceConfidence"in s&&Ko(this.M,2,s.minPosePresenceConfidence??.5),"outputPoseSegmentationMasks"in s&&(this.outputPoseSegmentationMasks=!!s.outputPoseSegmentationMasks),"minHandLandmarksConfidence"in s&&Ko(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,Vjt(this),TS(this,s,r),Hjt(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.D=typeof n=="function"?n:r,Vjt(this),b3(this,s,a,t),Hjt(this)}m(){var s=new Aj;Tf(s,"input_frames_image"),qu(s,"pose_landmarks"),qu(s,"pose_world_landmarks"),qu(s,"face_landmarks"),qu(s,"left_hand_landmarks"),qu(s,"left_hand_world_landmarks"),qu(s,"right_hand_landmarks"),qu(s,"right_hand_world_landmarks");const t=new Cj,n=new fjt;bj(n,1,"type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"),function(a,i){if(i!=null)if(Array.isArray(i))Vh(a,2,XLe(i,0,jte));else{if(!(typeof i=="string"||i instanceof V4||tst(i)))throw Error("invalid value in Any.value field: "+i+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");YT(a,2,nst(i,!1),V7())}}(n,this.j.g());const r=new U_;bj(r,2,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),xst(r,8,fjt,n),Bp(r,"IMAGE:input_frames_image"),iu(r,"POSE_LANDMARKS:pose_landmarks"),iu(r,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),iu(r,"FACE_LANDMARKS:face_landmarks"),iu(r,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),iu(r,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),iu(r,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),iu(r,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),r.o(t),TN(s,r),hIe(this,s),this.g.attachProtoListener("pose_landmarks",(a,i)=>{Xle(a,this.h.poseLandmarks),yo(this,i)}),this.g.attachEmptyPacketListener("pose_landmarks",a=>{yo(this,a)}),this.g.attachProtoListener("pose_world_landmarks",(a,i)=>{var l=this.h.poseWorldLandmarks;a=Yq(a),l.push(oJ(a)),yo(this,i)}),this.g.attachEmptyPacketListener("pose_world_landmarks",a=>{yo(this,a)}),this.outputPoseSegmentationMasks&&(iu(r,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),DH(this,"pose_segmentation_mask"),this.g.Z("pose_segmentation_mask",(a,i)=>{this.h.poseSegmentationMasks=[FH(this,a,!0,!this.D)],yo(this,i)}),this.g.attachEmptyPacketListener("pose_segmentation_mask",a=>{this.h.poseSegmentationMasks=[],yo(this,a)})),this.g.attachProtoListener("face_landmarks",(a,i)=>{Xle(a,this.h.faceLandmarks),yo(this,i)}),this.g.attachEmptyPacketListener("face_landmarks",a=>{yo(this,a)}),this.outputFaceBlendshapes&&(qu(s,"extra_blendshapes"),iu(r,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(a,i)=>{var l=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(a=cIe(a),l.push(Bst(a.g()??[]))),yo(this,i)}),this.g.attachEmptyPacketListener("extra_blendshapes",a=>{yo(this,a)})),this.g.attachProtoListener("left_hand_landmarks",(a,i)=>{Xle(a,this.h.leftHandLandmarks),yo(this,i)}),this.g.attachEmptyPacketListener("left_hand_landmarks",a=>{yo(this,a)}),this.g.attachProtoListener("left_hand_world_landmarks",(a,i)=>{var l=this.h.leftHandWorldLandmarks;a=Yq(a),l.push(oJ(a)),yo(this,i)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",a=>{yo(this,a)}),this.g.attachProtoListener("right_hand_landmarks",(a,i)=>{Xle(a,this.h.rightHandLandmarks),yo(this,i)}),this.g.attachEmptyPacketListener("right_hand_landmarks",a=>{yo(this,a)}),this.g.attachProtoListener("right_hand_world_landmarks",(a,i)=>{var l=this.h.rightHandWorldLandmarks;a=Yq(a),l.push(oJ(a)),yo(this,i)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",a=>{yo(this,a)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Sp.prototype.detectForVideo=Sp.prototype.G,Sp.prototype.detect=Sp.prototype.F,Sp.prototype.setOptions=Sp.prototype.o,Sp.createFromModelPath=function(s,t){return bu(Sp,s,{baseOptions:{modelAssetPath:t}})},Sp.createFromModelBuffer=function(s,t){return bu(Sp,s,{baseOptions:{modelAssetBuffer:t}})},Sp.createFromOptions=function(s,t){return bu(Sp,s,t)},Sp.HAND_CONNECTIONS=Yst,Sp.POSE_CONNECTIONS=kYt,Sp.FACE_LANDMARKS_LIPS=$st,Sp.FACE_LANDMARKS_LEFT_EYE=Vst,Sp.FACE_LANDMARKS_LEFT_EYEBROW=Hst,Sp.FACE_LANDMARKS_LEFT_IRIS=_Yt,Sp.FACE_LANDMARKS_RIGHT_EYE=Gst,Sp.FACE_LANDMARKS_RIGHT_EYEBROW=Wst,Sp.FACE_LANDMARKS_RIGHT_IRIS=wYt,Sp.FACE_LANDMARKS_FACE_OVAL=Kst,Sp.FACE_LANDMARKS_CONTOURS=jYt,Sp.FACE_LANDMARKS_TESSELATION=NYt;var o2=class extends _j{constructor(s,t){super(new ES(s,t),"input_image","norm_rect",!0),this.j={classifications:[]},bl(s=this.h=new tYt,0,1,t=new hg)}get baseOptions(){return Cu(this.h,hg,1)}set baseOptions(s){bl(this.h,0,1,s)}o(s){return bl(this.h,0,2,cGe(s,Cu(this.h,Lst,2))),this.l(s)}sa(s,t){return this.j={classifications:[]},TS(this,s,t),this.j}ta(s,t,n){return this.j={classifications:[]},b3(this,s,n,t),this.j}m(){var s=new Aj;Tf(s,"input_image"),Tf(s,"norm_rect"),qu(s,"classifications");const t=new Cj;y3(t,sOn,this.h);const n=new U_;bj(n,2,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),Bp(n,"IMAGE:input_image"),Bp(n,"NORM_RECT:norm_rect"),iu(n,"CLASSIFICATIONS:classifications"),n.o(t),TN(s,n),this.g.attachProtoListener("classifications",(r,a)=>{this.j=lOn(VDn(r)),yo(this,a)}),this.g.attachEmptyPacketListener("classifications",r=>{yo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};o2.prototype.classifyForVideo=o2.prototype.ta,o2.prototype.classify=o2.prototype.sa,o2.prototype.setOptions=o2.prototype.o,o2.createFromModelPath=function(s,t){return bu(o2,s,{baseOptions:{modelAssetPath:t}})},o2.createFromModelBuffer=function(s,t){return bu(o2,s,{baseOptions:{modelAssetBuffer:t}})},o2.createFromOptions=function(s,t){return bu(o2,s,t)};var ow=class extends _j{constructor(s,t){super(new ES(s,t),"image_in","norm_rect",!0),this.h=new sYt,this.embeddings={embeddings:[]},bl(s=this.h,0,1,t=new hg)}get baseOptions(){return Cu(this.h,hg,1)}set baseOptions(s){bl(this.h,0,1,s)}o(s){var t=this.h,n=Cu(this.h,Njt,2);return n=n?n.clone():new Njt,s.l2Normalize!==void 0?Vh(n,1,wte(s.l2Normalize)):"l2Normalize"in s&&Vh(n,1),s.quantize!==void 0?Vh(n,2,wte(s.quantize)):"quantize"in s&&Vh(n,2),bl(t,0,2,n),this.l(s)}za(s,t){return TS(this,s,t),this.embeddings}Aa(s,t,n){return b3(this,s,n,t),this.embeddings}m(){var s=new Aj;Tf(s,"image_in"),Tf(s,"norm_rect"),qu(s,"embeddings_out");const t=new Cj;y3(t,nOn,this.h);const n=new U_;bj(n,2,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),Bp(n,"IMAGE:image_in"),Bp(n,"NORM_RECT:norm_rect"),iu(n,"EMBEDDINGS:embeddings_out"),n.o(t),TN(s,n),this.g.attachProtoListener("embeddings_out",(r,a)=>{r=WDn(r),this.embeddings=function(i){return{embeddings:cE(i,GDn,1).map(l=>{var d,u;const o={headIndex:q2(l,3)??0??-1,headName:fv(bf(l,4))??""??""};var c=l.v;return JWt(c,0|c[Do],jjt,e9e(l,1))!==void 0?(l=rO(l=Cu(l,jjt,e9e(l,1),void 0),1,v4,nO()),o.floatEmbedding=l.slice()):(c=new Uint8Array(0),o.quantizedEmbedding=((u=(d=Cu(l,HDn,e9e(l,2),void 0))==null?void 0:d.na())==null?void 0:u.h())??c),o}),timestampMs:cYt(bf(i,2,void 0,void 0,OEe)??KWt)}}(r),yo(this,a)}),this.g.attachEmptyPacketListener("embeddings_out",r=>{yo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};ow.cosineSimilarity=function(s,t){if(s.floatEmbedding&&t.floatEmbedding)s=Tjt(s.floatEmbedding,t.floatEmbedding);else{if(!s.quantizedEmbedding||!t.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");s=Tjt(Ejt(s.quantizedEmbedding),Ejt(t.quantizedEmbedding))}return s},ow.prototype.embedForVideo=ow.prototype.Aa,ow.prototype.embed=ow.prototype.za,ow.prototype.setOptions=ow.prototype.o,ow.createFromModelPath=function(s,t){return bu(ow,s,{baseOptions:{modelAssetPath:t}})},ow.createFromModelBuffer=function(s,t){return bu(ow,s,{baseOptions:{modelAssetBuffer:t}})},ow.createFromOptions=function(s,t){return bu(ow,s,t)};var mGe=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 fOn(s){var n,r;const t=function(a){return cE(a,U_,1)}(s.ca()).filter(a=>(fv(bf(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=Cu(t[0],Cj,7))==null?void 0:n.j())==null?void 0:r.g())??new Map).forEach((a,i)=>{s.u[Number(i)]=fv(bf(a,1))??""})}function Gjt(s){s.categoryMask=void 0,s.confidenceMasks=void 0,s.qualityScores=void 0}function Wjt(s){try{const t=new mGe(s.confidenceMasks,s.categoryMask,s.qualityScores);if(!s.j)return t;s.j(t)}finally{mIe(s)}}mGe.prototype.close=mGe.prototype.close;var U1=class extends _j{constructor(s,t){super(new ES(s,t),"image_in","norm_rect",!1),this.u=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new zst,this.A=new nYt,bl(this.h,0,3,this.A),bl(s=this.h,0,1,t=new hg)}get baseOptions(){return Cu(this.h,hg,1)}set baseOptions(s){bl(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?Vh(this.h,2,$re(s.displayNamesLocale)):"displayNamesLocale"in s&&Vh(this.h,2),"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}L(){fOn(this)}segment(s,t,n){const r=typeof t!="function"?t:{};return this.j=typeof t=="function"?t:n,Gjt(this),TS(this,s,r),Wjt(this)}La(s,t,n,r){const a=typeof n!="function"?n:{};return this.j=typeof n=="function"?n:r,Gjt(this),b3(this,s,a,t),Wjt(this)}Da(){return this.u}m(){var s=new Aj;Tf(s,"image_in"),Tf(s,"norm_rect");const t=new Cj;y3(t,aYt,this.h);const n=new U_;bj(n,2,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),Bp(n,"IMAGE:image_in"),Bp(n,"NORM_RECT:norm_rect"),n.o(t),TN(s,n),hIe(this,s),this.outputConfidenceMasks&&(qu(s,"confidence_masks"),iu(n,"CONFIDENCE_MASKS:confidence_masks"),DH(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>FH(this,i,!0,!this.j)),yo(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],yo(this,r)})),this.outputCategoryMask&&(qu(s,"category_mask"),iu(n,"CATEGORY_MASK:category_mask"),DH(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=FH(this,r,!1,!this.j),yo(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,yo(this,r)})),qu(s,"quality_scores"),iu(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,yo(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,yo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};U1.prototype.getLabels=U1.prototype.Da,U1.prototype.segmentForVideo=U1.prototype.La,U1.prototype.segment=U1.prototype.segment,U1.prototype.setOptions=U1.prototype.o,U1.createFromModelPath=function(s,t){return bu(U1,s,{baseOptions:{modelAssetPath:t}})},U1.createFromModelBuffer=function(s,t){return bu(U1,s,{baseOptions:{modelAssetBuffer:t}})},U1.createFromOptions=function(s,t){return bu(U1,s,t)};var pGe=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()}};pGe.prototype.close=pGe.prototype.close;var c5=class extends _j{constructor(s,t){super(new ES(s,t),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new zst,this.u=new nYt,bl(this.h,0,3,this.u),bl(s=this.h,0,1,t=new hg)}get baseOptions(){return Cu(this.h,hg,1)}set baseOptions(s){bl(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 iYt,t.keypoint&&t.scribble)throw Error("Cannot provide both keypoint and scribble.");if(t.keypoint){var i=new r9e;YT(i,3,wte(!0),!1),YT(i,1,RZ(t.keypoint.x),0),YT(i,2,RZ(t.keypoint.y),0),aJ(r,1,lGe,i)}else{if(!t.scribble)throw Error("Must provide either a keypoint or a scribble.");{const o=new aOn;for(i of t.scribble)YT(t=new r9e,3,wte(!0),!1),YT(t,1,RZ(i.x),0),YT(t,2,RZ(i.y),0),xst(o,1,r9e,t);aJ(r,2,lGe,o)}}this.g.addProtoToStream(r.g(),"mediapipe.tasks.vision.interactive_segmenter.proto.RegionOfInterest","roi_in",n),TS(this,s,a);e:{try{const o=new pGe(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var l=o;break e}this.j(o)}finally{mIe(this)}l=void 0}return l}m(){var s=new Aj;Tf(s,"image_in"),Tf(s,"roi_in"),Tf(s,"norm_rect_in");const t=new Cj;y3(t,aYt,this.h);const n=new U_;bj(n,2,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraphV2"),Bp(n,"IMAGE:image_in"),Bp(n,"ROI:roi_in"),Bp(n,"NORM_RECT:norm_rect_in"),n.o(t),TN(s,n),hIe(this,s),this.outputConfidenceMasks&&(qu(s,"confidence_masks"),iu(n,"CONFIDENCE_MASKS:confidence_masks"),DH(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>FH(this,i,!0,!this.j)),yo(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],yo(this,r)})),this.outputCategoryMask&&(qu(s,"category_mask"),iu(n,"CATEGORY_MASK:category_mask"),DH(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=FH(this,r,!1,!this.j),yo(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,yo(this,r)})),qu(s,"quality_scores"),iu(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,yo(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,yo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};c5.prototype.segment=c5.prototype.segment,c5.prototype.setOptions=c5.prototype.o,c5.createFromModelPath=function(s,t){return bu(c5,s,{baseOptions:{modelAssetPath:t}})},c5.createFromModelBuffer=function(s,t){return bu(c5,s,{baseOptions:{modelAssetBuffer:t}})},c5.createFromOptions=function(s,t){return bu(c5,s,t)};var l2=class extends _j{constructor(s,t){super(new ES(s,t),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},bl(s=this.h=new oYt,0,1,t=new hg)}get baseOptions(){return Cu(this.h,hg,1)}set baseOptions(s){bl(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?Vh(this.h,2,$re(s.displayNamesLocale)):"displayNamesLocale"in s&&Vh(this.h,2),s.maxResults!==void 0?dE(this.h,3,s.maxResults):"maxResults"in s&&Vh(this.h,3),s.scoreThreshold!==void 0?Ko(this.h,4,s.scoreThreshold):"scoreThreshold"in s&&Vh(this.h,4),s.categoryAllowlist!==void 0?zEe(this.h,5,s.categoryAllowlist):"categoryAllowlist"in s&&Vh(this.h,5),s.categoryDenylist!==void 0?zEe(this.h,6,s.categoryDenylist):"categoryDenylist"in s&&Vh(this.h,6),this.l(s)}F(s,t){return this.j={detections:[]},TS(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},b3(this,s,n,t),this.j}m(){var s=new Aj;Tf(s,"input_frame_gpu"),Tf(s,"norm_rect"),qu(s,"detections");const t=new Cj;y3(t,iOn,this.h);const n=new U_;bj(n,2,"mediapipe.tasks.vision.ObjectDetectorGraph"),Bp(n,"IMAGE:input_frame_gpu"),Bp(n,"NORM_RECT:norm_rect"),iu(n,"DETECTIONS:detections"),n.o(t),TN(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=FKt(i),this.j.detections.push(dYt(r));yo(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{yo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};l2.prototype.detectForVideo=l2.prototype.G,l2.prototype.detect=l2.prototype.F,l2.prototype.setOptions=l2.prototype.o,l2.createFromModelPath=async function(s,t){return bu(l2,s,{baseOptions:{modelAssetPath:t}})},l2.createFromModelBuffer=function(s,t){return bu(l2,s,{baseOptions:{modelAssetBuffer:t}})},l2.createFromOptions=function(s,t){return bu(l2,s,t)};var fGe=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 Kjt(s){s.landmarks=[],s.worldLandmarks=[],s.segmentationMasks=void 0}function Yjt(s){try{const t=new fGe(s.landmarks,s.worldLandmarks,s.segmentationMasks);if(!s.u)return t;s.u(t)}finally{mIe(s)}}fGe.prototype.close=fGe.prototype.close;var lw=class extends _j{constructor(s,t){super(new ES(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,bl(s=this.h=new lYt,0,1,t=new hg),this.A=new JKt,bl(this.h,0,3,this.A),this.j=new QKt,bl(this.h,0,2,this.j),dE(this.j,4,1),Ko(this.j,2,.5),Ko(this.A,2,.5),Ko(this.h,4,.5)}get baseOptions(){return Cu(this.h,hg,1)}set baseOptions(s){bl(this.h,0,1,s)}o(s){return"numPoses"in s&&dE(this.j,4,s.numPoses??1),"minPoseDetectionConfidence"in s&&Ko(this.j,2,s.minPoseDetectionConfidence??.5),"minTrackingConfidence"in s&&Ko(this.h,4,s.minTrackingConfidence??.5),"minPosePresenceConfidence"in s&&Ko(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,Kjt(this),TS(this,s,r),Yjt(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.u=typeof n=="function"?n:r,Kjt(this),b3(this,s,a,t),Yjt(this)}m(){var s=new Aj;Tf(s,"image_in"),Tf(s,"norm_rect"),qu(s,"normalized_landmarks"),qu(s,"world_landmarks"),qu(s,"segmentation_masks");const t=new Cj;y3(t,oOn,this.h);const n=new U_;bj(n,2,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),Bp(n,"IMAGE:image_in"),Bp(n,"NORM_RECT:norm_rect"),iu(n,"NORM_LANDMARKS:normalized_landmarks"),iu(n,"WORLD_LANDMARKS:world_landmarks"),n.o(t),TN(s,n),hIe(this,s),this.g.attachProtoVectorListener("normalized_landmarks",(r,a)=>{this.landmarks=[];for(const i of r)r=Gre(i),this.landmarks.push(uIe(r));yo(this,a)}),this.g.attachEmptyPacketListener("normalized_landmarks",r=>{this.landmarks=[],yo(this,r)}),this.g.attachProtoVectorListener("world_landmarks",(r,a)=>{this.worldLandmarks=[];for(const i of r)r=Yq(i),this.worldLandmarks.push(oJ(r));yo(this,a)}),this.g.attachEmptyPacketListener("world_landmarks",r=>{this.worldLandmarks=[],yo(this,r)}),this.outputSegmentationMasks&&(iu(n,"SEGMENTATION_MASK:segmentation_masks"),DH(this,"segmentation_masks"),this.g.aa("segmentation_masks",(r,a)=>{this.segmentationMasks=r.map(i=>FH(this,i,!0,!this.u)),yo(this,a)}),this.g.attachEmptyPacketListener("segmentation_masks",r=>{this.segmentationMasks=[],yo(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};lw.prototype.detectForVideo=lw.prototype.G,lw.prototype.detect=lw.prototype.F,lw.prototype.setOptions=lw.prototype.o,lw.createFromModelPath=function(s,t){return bu(lw,s,{baseOptions:{modelAssetPath:t}})},lw.createFromModelBuffer=function(s,t){return bu(lw,s,{baseOptions:{modelAssetBuffer:t}})},lw.createFromOptions=function(s,t){return bu(lw,s,t)},lw.POSE_CONNECTIONS=kYt;let aO=null,DZ=null;async function gOn(){return aO||DZ||(DZ=(async()=>{const s=await qB.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm");return aO=await U1.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}),aO})(),DZ)}function xOn(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 yOn(){aO&&(aO.close(),aO=null,DZ=null)}const vOn=1280,bOn=720;function _On(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 p=t.type!=="none"&&s!==null;return j.useEffect(()=>{if(t.type==="image"&&t.imageUrl){const f=new Image;f.crossOrigin="anonymous",f.src=t.imageUrl,f.onload=()=>{a.current=f},f.onerror=()=>{a.current=null}}else t.type!=="image"&&(a.current=null)},[t.type,t.imageUrl]),j.useEffect(()=>{if(!p||!s){r.current&&(r.current.srcObject=null,r.current=null);return}const f=document.createElement("video");return f.srcObject=s,f.muted=!0,f.playsInline=!0,f.autoplay=!0,f.play().catch(()=>{}),r.current=f,()=>{f.srcObject=null,r.current=null}},[p,s]),j.useEffect(()=>{if(!p){c(null),m(null);return}let f=!1,x=null,y=null;const v=async()=>{u(!0),m(null);try{const N=await gOn();if(f)return;u(!1);const S=r.current;if(!S||(await new Promise(Wt=>{if(S.videoWidth>0)return Wt();S.onloadedmetadata=()=>Wt(),setTimeout(Wt,2e3)}),f))return;const A=S.videoWidth||640,T=S.videoHeight||480,L=Math.max(A,T),M=Math.min(A,T),I=Math.min(1,vOn/L,bOn/M),R=Math.max(2,Math.round(A*I/2)*2),z=Math.max(2,Math.round(T*I/2)*2),H=!jWt().canRunVirtualBg,K=(H?192:256)/Math.max(R,z),Z=Math.max(2,Math.round(R*K)),Q=Math.max(2,Math.round(z*K)),le=H?90:55,ue=H?24:30,se=n.current;if(!se)return;se.width=R,se.height=z;const ne=se.getContext("2d",{alpha:!1}),ie=document.createElement("canvas");ie.width=R,ie.height=z;const ce=ie.getContext("2d"),je=document.createElement("canvas");je.width=Math.max(2,Math.round(R/2)),je.height=Math.max(2,Math.round(z/2));const be=je.getContext("2d",{alpha:!1}),he=document.createElement("canvas");he.width=Z,he.height=Q;const ge=he.getContext("2d",{alpha:!1}),ke=document.createElement("canvas");ke.width=Z,ke.height=Q;const Te=ke.getContext("2d"),Me=Te.createImageData(Z,Q),Oe=Me.data;for(let Wt=0;WtSe.addTrack(Wt)),f||c(Se);const Ae=new Float32Array(Z*Q),Fe=new Float32Array(Z*Q),Ne=new Float32Array(Z*Q);let $e=!1,Ve=!1;const qe=2,Ze=.4;let Ue=0;const Ye=(Wt,us)=>{ge.drawImage(Wt,0,0,Z,Q);const bt=N.segmentForVideo(he,us).confidenceMasks;if(!(!bt||bt.length===0)){Fe.fill(0);for(let As=1;As1?1:Ms}}for(const As of bt)As.close();if(xOn(Fe,Ae,Z,Q,qe),$e)for(let As=0;As=1?255:Ws*255|0}Te.putImageData(Me,0,0),Ve=!0}},Ge=Wt=>{const us=l.current;if(us.type==="blur"){const zt=Math.max(2,Math.round((us.blurRadius??15)/2));be.filter=`blur(${zt}px)`,be.drawImage(Wt,0,0,je.width,je.height),be.filter="none",ne.drawImage(je,0,0,R,z)}else if(us.type==="image"&&a.current){const zt=a.current,bt=zt.width/zt.height,As=R/z;let vt=0,Ws=0,on=zt.width,Ms=zt.height;bt>As?(on=zt.height*As,vt=(zt.width-on)/2):(Ms=zt.width/As,Ws=(zt.height-Ms)/2),ne.drawImage(zt,vt,Ws,on,Ms,0,0,R,z)}else ne.fillStyle="#000",ne.fillRect(0,0,R,z)},He=()=>{if(f||!r.current)return;const Wt=r.current;if(Wt.readyState<2){Ut(Wt);return}try{const us=performance.now();us-Ue>=le&&(Ue=us,Ye(Wt,us)),Ve?(Ge(Wt),ce.globalCompositeOperation="source-over",ce.clearRect(0,0,R,z),ce.drawImage(Wt,0,0,R,z),ce.globalCompositeOperation="destination-in",ce.drawImage(ke,0,0,R,z),ce.globalCompositeOperation="source-over",l.current.mirror?(ne.save(),ne.translate(R,0),ne.scale(-1,1),ne.drawImage(ie,0,0),ne.restore()):ne.drawImage(ie,0,0)):ne.drawImage(Wt,0,0,R,z)}catch{try{ne.drawImage(Wt,0,0,R,z)}catch{}}Ut(Wt)},tt=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}}",ft=new Blob([pt],{type:"application/javascript"});y=URL.createObjectURL(ft),x=new Worker(y),x.onmessage=()=>{f||!document.hidden||He()};const qt=()=>{x&&(document.hidden?x.postMessage({type:"start",fps:ue}):(x.postMessage({type:"stop"}),Ut(r.current)))};document.addEventListener("visibilitychange",qt);const Ut=Wt=>{f||document.hidden||(tt?Wt.requestVideoFrameCallback(()=>He()):i.current=requestAnimationFrame(He))};Ut(S),b=()=>{document.removeEventListener("visibilitychange",qt)}}catch(N){console.error("[useVirtualBackground] init error:",N),f||(u(!1),m(N.message||"Failed to initialize virtual background"))}};let b=null;return v(),()=>{f=!0,i.current&&cancelAnimationFrame(i.current),b==null||b(),x&&(x.postMessage({type:"stop"}),x.terminate(),x=null),y&&URL.revokeObjectURL(y),c(null)}},[p,s]),j.useEffect(()=>()=>{yOn()},[]),{canvasRef:n,compositedStream:o,isLoading:d,isActive:p,error:h}}function kE({maxDurationSeconds:s=600,onRecordingComplete:t,onError:n,onRecordingStateChange:r,className:a,teleprompterContent:i}){const l=j.useRef(null),o=j.useRef(null),c=j.useRef(null),[d,u]=j.useState(null),h=j.useRef([]),m=j.useRef(null),p=j.useRef(null),f=j.useRef(null),x=j.useRef(null),y=JG(),[v,b]=j.useState("camera"),N=j.useRef(null),S=j.useRef(null),A=j.useRef(null),T=j.useRef(null),L=j.useRef(null),M=j.useRef(null),[I,R]=j.useState(!0),[z,$]=j.useState(!0),[H,V]=j.useState(null),[K,Z]=j.useState(!1),[Q,le]=j.useState(!1),[ue,se]=j.useState(null),[ne,ie]=j.useState(null),[ce,je]=j.useState(0),[be,he]=j.useState("user"),[ge,ke]=j.useState(0),[Te,Me]=j.useState(!1),[Oe,Se]=j.useState(!0),[Qe,Ae]=j.useState(null),[Fe,Ne]=j.useState(!1),[$e,Ve]=j.useState(null),qe=j.useRef(null),[Ze,Ue]=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(Ze))}catch{}},[Ze]);const[Ye,Ge]=j.useState([]),[He,tt]=j.useState([]),[pt,ft]=j.useState(()=>{try{return localStorage.getItem("video-mic-id")||""}catch{return""}}),[qt,Ut]=j.useState(()=>{try{return localStorage.getItem("video-cam-id")||""}catch{return""}});j.useEffect(()=>{try{localStorage.setItem("video-mic-id",pt)}catch{}},[pt]),j.useEffect(()=>{try{localStorage.setItem("video-cam-id",qt)}catch{}},[qt]),j.useEffect(()=>{var Un,sn,un;if(!((Un=navigator.mediaDevices)!=null&&Un.enumerateDevices))return;const kn=async()=>{try{const Ar=await navigator.mediaDevices.enumerateDevices();Ge(Ar.filter(fs=>fs.kind==="audioinput")),tt(Ar.filter(fs=>fs.kind==="videoinput"))}catch(Ar){console.warn("[VideoRecorder] enumerateDevices failed",Ar)}};return kn(),(un=(sn=navigator.mediaDevices).addEventListener)==null||un.call(sn,"devicechange",kn),()=>{var Ar,fs;return(fs=(Ar=navigator.mediaDevices).removeEventListener)==null?void 0:fs.call(Ar,"devicechange",kn)}},[H]);const{canvasRef:Wt,compositedStream:us,isLoading:zt,isActive:bt,error:As}=_On(d,Ze),vt=j.useRef(n);vt.current=n;const Ws=j.useCallback(kn=>{R(kn)},[]),on=j.useRef(I),Ms=j.useCallback(()=>{A.current&&(cancelAnimationFrame(A.current),A.current=null),T.current&&(T.current.terminate(),T.current=null),N.current&&(N.current.getTracks().forEach(kn=>kn.stop()),N.current=null),L.current&&(L.current.getTracks().forEach(kn=>kn.stop()),L.current=null),M.current&&(M.current.srcObject=null,M.current=null)},[]),dn=j.useCallback(async()=>{var kn;try{const Un=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1920},height:{ideal:1080}},audio:!0});N.current=Un;let sn=null;try{sn=await navigator.mediaDevices.getUserMedia({video:qt?{deviceId:{exact:qt},width:{ideal:320},height:{ideal:240}}:{width:{ideal:320},height:{ideal:240}},audio:!1})}catch{console.warn("[VideoRecorder] No webcam for PiP overlay")}let un=null;try{un=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,...pt?{deviceId:{exact:pt}}:{}}}),console.log("[VideoRecorder] mic acquired for screen recording",un.getAudioTracks().map(qr=>qr.label))}catch(qr){console.warn("[VideoRecorder] No mic audio for screen recording",qr);try{un=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{}}const Ar=Un.getVideoTracks()[0],fs=Ar.getSettings(),ot=fs.width||1920,mt=fs.height||1080,Nt=document.createElement("canvas");Nt.width=ot,Nt.height=mt,S.current=Nt;const Pt=Nt.getContext("2d");let ts=null;sn&&(ts=document.createElement("video"),ts.srcObject=sn,ts.muted=!0,ts.playsInline=!0,ts.autoplay=!0,await ts.play(),M.current=ts);const ls=document.createElement("video");ls.srcObject=Un,ls.muted=!0,ls.playsInline=!0,ls.autoplay=!0,await ls.play();const Is=()=>{if(Pt.drawImage(ls,0,0,ot,mt),ts&&ts.readyState>=2){const qr=Math.round(ot*.2),Zr=Math.round(qr*(ts.videoHeight/ts.videoWidth||.75)),Jr=ot-qr-20,ha=mt-Zr-20,Fa=12;Pt.save(),Pt.beginPath(),Pt.moveTo(Jr+Fa,ha),Pt.lineTo(Jr+qr-Fa,ha),Pt.quadraticCurveTo(Jr+qr,ha,Jr+qr,ha+Fa),Pt.lineTo(Jr+qr,ha+Zr-Fa),Pt.quadraticCurveTo(Jr+qr,ha+Zr,Jr+qr-Fa,ha+Zr),Pt.lineTo(Jr+Fa,ha+Zr),Pt.quadraticCurveTo(Jr,ha+Zr,Jr,ha+Zr-Fa),Pt.lineTo(Jr,ha+Fa),Pt.quadraticCurveTo(Jr,ha,Jr+Fa,ha),Pt.closePath(),Pt.clip(),Pt.translate(Jr+qr,ha),Pt.scale(-1,1),Pt.drawImage(ts,0,0,qr,Zr),Pt.restore(),Pt.strokeStyle="rgba(255,255,255,0.6)",Pt.lineWidth=2,Pt.beginPath(),Pt.moveTo(Jr+Fa,ha),Pt.lineTo(Jr+qr-Fa,ha),Pt.quadraticCurveTo(Jr+qr,ha,Jr+qr,ha+Fa),Pt.lineTo(Jr+qr,ha+Zr-Fa),Pt.quadraticCurveTo(Jr+qr,ha+Zr,Jr+qr-Fa,ha+Zr),Pt.lineTo(Jr+Fa,ha+Zr),Pt.quadraticCurveTo(Jr,ha+Zr,Jr,ha+Zr-Fa),Pt.lineTo(Jr,ha+Fa),Pt.quadraticCurveTo(Jr,ha,Jr+Fa,ha),Pt.closePath(),Pt.stroke()}},ps="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}}",Ht=new Blob([ps],{type:"application/javascript"}),Xs=new Worker(URL.createObjectURL(Ht));T.current=Xs,Xs.onmessage=()=>Is(),Xs.postMessage({type:"start",fps:30}),Is();const Rs=Nt.captureStream(30),zn=[],Qr=Un.getAudioTracks();Qr.length&&zn.push(...Qr),un&&zn.push(...un.getAudioTracks());const ma=new MediaStream([...Rs.getVideoTracks(),...zn]);return L.current=ma,Ar.onended=()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),Ms()},ma}catch(Un){return console.error("[VideoRecorder] Screen capture error:",Un),Un.name!=="NotAllowedError"&&((kn=vt.current)==null||kn.call(vt,"Failed to start screen capture: "+(Un.message||"Unknown error"))),null}},[Ms]),rn=j.useCallback(async()=>{var Un,sn;$(!0),Ae(null);const kn=y&&I;console.log("[VideoRecorder] initCamera start",{isMobile:y,usePortraitMode:I,shouldBePortrait:kn,facingMode:be});try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Error("Camera not available in this browser or context. Try opening in a new tab.");c.current&&(console.log("[VideoRecorder] stopping existing stream"),c.current.getTracks().forEach(Pt=>Pt.stop()));const un=y&&kn?{width:{ideal:720},height:{ideal:1280}}:{width:{ideal:1280},height:{ideal:720}},Ar=qt?{...un,deviceId:{exact:qt}}:{...un,facingMode:{ideal:be}},fs={echoCancellation:!0,noiseSuppression:!0,...pt?{deviceId:{exact:pt}}:{}};console.log("[VideoRecorder] requesting getUserMedia",Ar);const ot=await navigator.mediaDevices.getUserMedia({video:Ar,audio:fs});if(console.log("[VideoRecorder] getUserMedia success"),ot.getVideoTracks().length===0)throw new Error("Camera stream started but no video track was provided.");c.current=ot,u(ot),V(!0);const Nt=ot.getVideoTracks()[0].getSettings();if(console.log("[VideoRecorder] Camera initialized with dimensions:",Nt.width,"x",Nt.height),l.current){const Pt=l.current;Pt.srcObject=ot,Pt.muted=!0,Pt.playsInline=!0,Pt.autoplay=!0,Pt.setAttribute("muted",""),Pt.setAttribute("playsinline",""),Pt.setAttribute("autoplay","");try{(Un=Pt.load)==null||Un.call(Pt)}catch(ls){console.warn("[VideoRecorder] videoEl.load failed",ls)}const ts=async()=>{try{return await Pt.play(),console.log("[VideoRecorder] preview play ok"),Ne(!1),setTimeout(()=>{console.debug("[VideoRecorder] preview metrics",{readyState:Pt.readyState,videoWidth:Pt.videoWidth,videoHeight:Pt.videoHeight})},300),!0}catch(ls){return console.warn("[VideoRecorder] preview play blocked",ls),Ne(!0),!1}};await new Promise(ls=>{let Is=!1;const ps=()=>{Is||(Is=!0,ls())},Ht=()=>{ts().finally(ps)};Pt.onloadedmetadata=Ht,Pt.onloadeddata=Ht,setTimeout(ps,1500)})}try{p.current=new AudioContext;const Pt=p.current.createMediaStreamSource(ot);f.current=p.current.createAnalyser(),f.current.fftSize=256,Pt.connect(f.current);const ts=()=>{if(f.current){const ls=new Uint8Array(f.current.frequencyBinCount);f.current.getByteFrequencyData(ls);const Is=ls.reduce((ps,Ht)=>ps+Ht)/ls.length;ke(Math.min(100,Is/128*100))}x.current=requestAnimationFrame(ts)};ts()}catch(Pt){console.warn("Audio context not available:",Pt)}}catch(un){console.error("Camera initialization error:",un),V(!1);let Ar="Failed to access camera or microphone.";un.name==="NotAllowedError"?Ar="Camera permission denied. Please allow camera access in your browser settings.":un.name==="NotFoundError"?Ar="No camera found. Please connect a camera and try again.":un.name==="NotReadableError"?Ar="Camera is in use by another application. Please close other apps using the camera.":un.message&&(Ar=un.message),Ae(Ar),(sn=vt.current)==null||sn.call(vt,Ar)}finally{$(!1)}},[be,y,I,pt,qt]);j.useEffect(()=>{on.current!==I&&H&&!K&&!ne&&(on.current=I,rn())},[I,H,K,ne,rn]),j.useEffect(()=>(rn(),()=>{c.current&&c.current.getTracks().forEach(kn=>kn.stop()),m.current&&clearInterval(m.current),x.current&&cancelAnimationFrame(x.current),p.current&&p.current.close(),qe.current&&clearInterval(qe.current),ne&&URL.revokeObjectURL(ne),Ms()}),[rn,ne]),j.useEffect(()=>{if(z||H!==!0||ne)return;const kn=c.current,Un=l.current;!kn||!Un||bt||(Un.srcObject!==kn&&(Un.srcObject=kn,Un.muted=!0,Un.playsInline=!0,Un.autoplay=!0,Un.setAttribute("muted",""),Un.setAttribute("playsinline",""),Un.setAttribute("autoplay","")),Un.play().then(()=>Ne(!1)).catch(sn=>{Ne(!0),console.warn("Live preview play blocked on mount:",sn)}))},[H,z,ne,bt]),j.useEffect(()=>{r==null||r(K)},[K,r]);const br=j.useCallback(async()=>{if(ne)return;const kn=l.current;if(kn)try{await kn.play(),Ne(!1)}catch(Un){Ne(!0),console.warn("Live preview still blocked (needs user gesture):",Un)}},[ne]),Gn=j.useCallback(()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),m.current&&(clearInterval(m.current),m.current=null),Ms(),Z(!1),le(!1)},[Ms]),On=j.useCallback(async()=>{let kn=null;if(v==="screen"){if(kn=await dn(),!kn)return}else kn=bt&&us?us:c.current;if(!kn)return;br(),h.current=[],je(0);const sn=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"].find(Ar=>MediaRecorder.isTypeSupported(Ar)),un=new MediaRecorder(kn,sn?{mimeType:sn,videoBitsPerSecond:v==="screen"?4e6:25e5,audioBitsPerSecond:128e3}:{videoBitsPerSecond:v==="screen"?4e6:25e5,audioBitsPerSecond:128e3});un.ondataavailable=Ar=>{Ar.data.size>0&&h.current.push(Ar.data)},un.onstop=()=>{var mt;const Ar=un.mimeType||sn||((mt=h.current[0])==null?void 0:mt.type)||"video/webm",fs=new Blob(h.current,{type:Ar});se(fs);const ot=URL.createObjectURL(fs);ie(ot)},o.current=un,un.start(1e3),Z(!0),m.current=setInterval(()=>{je(Ar=>Ar>=s-1?(Gn(),s):Ar+1)},1e3)},[br,s,Gn,bt,us,v,dn]),Rr=j.useCallback(()=>{qe.current&&(clearInterval(qe.current),qe.current=null),Ve(3);let kn=3;qe.current=setInterval(()=>{kn-=1,kn<=0?(qe.current&&clearInterval(qe.current),qe.current=null,Ve(null),On()):Ve(kn)},1e3)},[On]),cr=j.useCallback(()=>{o.current&&o.current.state==="recording"&&(o.current.pause(),le(!0),m.current&&clearInterval(m.current))},[]),Hs=j.useCallback(()=>{o.current&&o.current.state==="paused"&&(o.current.resume(),le(!1),m.current=setInterval(()=>{je(kn=>kn>=s-1?(Gn(),s):kn+1)},1e3))},[s,Gn]),_r=j.useCallback(()=>{ne&&URL.revokeObjectURL(ne),se(null),ie(null),je(0),Me(!1),Se(!0),l.current&&c.current&&!bt&&(l.current.srcObject=c.current,l.current.muted=!0,br())},[br,ne,bt]),nn=j.useCallback(()=>{he(kn=>kn==="user"?"environment":"user")},[]),Zn=j.useCallback(()=>{ue&&t(ue,ce)},[ue,ce,t]),es=j.useCallback(()=>{l.current&&ne&&(Te?l.current.pause():(Se(!1),l.current.muted=!1,l.current.play()),Me(!Te))},[ne,Te]);j.useEffect(()=>{if(!ne)return;const kn=l.current;if(!kn)return;Se(!1),kn.pause(),kn.removeAttribute("src"),kn.srcObject=null,kn.load(),kn.src=ne,kn.currentTime=0,kn.playsInline=!0,kn.muted=!1,kn.onended=()=>Me(!1);const Un=()=>{var Ar;const sn=kn.error,un=sn?`Recorded video failed to play (code ${sn.code}). Likely unsupported format/codec in this browser.`:"Recorded video failed to play.";console.warn("[VideoRecorder] recorded playback error",sn),(Ar=vt.current)==null||Ar.call(vt,un)};return kn.addEventListener("error",Un),kn.load(),()=>{kn.removeEventListener("error",Un)}},[ne]);const ar=kn=>{const Un=Math.floor(kn/60),sn=kn%60;return`${Un}:${sn.toString().padStart(2,"0")}`},Hn=v==="screen"?"aspect-video":y&&I?"aspect-[9/16]":"aspect-video";return z?e.jsx("div",{className:Mt("flex items-center justify-center bg-black rounded-lg",Hn,a),children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(Et,{className:"h-12 w-12 animate-spin mx-auto mb-4"}),e.jsx("p",{children:"Initializing camera..."})]})}):H===!1?e.jsx("div",{className:Mt("flex items-center justify-center bg-black rounded-lg",Hn,a),children:e.jsxs("div",{className:"text-center text-white p-8 max-w-md",children:[e.jsx(Vo,{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:Qe||"Please allow camera and microphone access to record videos."}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(U,{onClick:()=>rn(),variant:"secondary",className:"w-full",children:[e.jsx(no,{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:Mt("flex flex-col gap-2",a),children:[!K&&!ne&&e.jsxs("div",{className:"flex items-center justify-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsxs(U,{variant:v==="camera"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>b("camera"),children:[e.jsx(_x,{className:"h-4 w-4"}),"Camera"]}),e.jsxs(U,{variant:v==="screen"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>b("screen"),children:[e.jsx(IF,{className:"h-4 w-4"}),"Screen"]})]}),v==="camera"&&!K&&!ne&&e.jsx(PRn,{value:Ze,onChange:Ue,isLoading:zt,disabled:K}),!K&&!ne&&(Ye.length>0||He.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3 px-3 py-2 bg-muted/40 rounded-lg",children:[Ye.length>0&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(LF,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(Ns,{value:pt||"default",onValueChange:kn=>ft(kn==="default"?"":kn),children:[e.jsx(ws,{className:"h-8 text-xs",children:e.jsx(ks,{placeholder:"Default microphone"})}),e.jsxs(js,{children:[e.jsx(et,{value:"default",children:"Default microphone"}),Ye.map(kn=>e.jsx(et,{value:kn.deviceId,children:kn.label||`Microphone ${kn.deviceId.slice(0,6)}`},kn.deviceId))]})]})]}),He.length>1&&v==="camera"&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(_x,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(Ns,{value:qt||"default",onValueChange:kn=>Ut(kn==="default"?"":kn),children:[e.jsx(ws,{className:"h-8 text-xs",children:e.jsx(ks,{placeholder:"Default camera"})}),e.jsxs(js,{children:[e.jsx(et,{value:"default",children:"Default camera"}),He.map(kn=>e.jsx(et,{value:kn.deviceId,children:kn.label||`Camera ${kn.deviceId.slice(0,6)}`},kn.deviceId))]})]})]})]}),v==="camera"&&y&&!K&&!ne&&e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2 bg-muted/50 rounded-lg",children:[e.jsx(X2,{className:Mt("h-4 w-4",I?"text-muted-foreground":"text-primary")}),e.jsx(te,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Landscape"}),e.jsx(wn,{id:"orientation-toggle",checked:I,onCheckedChange:Ws}),e.jsx(te,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Portrait"}),e.jsx(i1,{className:Mt("h-4 w-4",I?"text-primary":"text-muted-foreground")})]}),v==="screen"&&!K&&!ne&&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(IF,{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:Mt("relative bg-black rounded-lg overflow-hidden"),onPointerDown:()=>{br()},children:[e.jsx("video",{ref:l,src:ne??void 0,className:Mt("w-full bg-black",I&&!ne?"object-contain":"object-cover",Hn,!ne&&be==="user"!==(Ze.mirror??!1)&&"scale-x-[-1]",bt&&!ne&&"hidden"),playsInline:!0,controls:!!ne,muted:ne?Oe:!0,autoPlay:!ne},ne??"live"),bt&&!ne&&e.jsx("canvas",{ref:Wt,className:Mt("w-full bg-black",I?"object-contain":"object-cover",Hn,be==="user"!==(Ze.mirror??!1)&&"scale-x-[-1]")}),bt&&zt&&!ne&&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(Et,{className:"h-8 w-8 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm",children:"Loading virtual background…"})]})}),!ne&&Fe&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40",children:e.jsx(U,{type:"button",variant:"secondary",onClick:()=>void br(),className:"bg-white/20 hover:bg-white/30 text-white",children:"Tap to enable preview"})}),i&&!ne&&e.jsx("div",{className:"absolute inset-0 pointer-events-none",children:i}),$e!==null&&!ne&&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:$e},$e),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),K&&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:Mt("w-3 h-3 rounded-full",Q?"bg-yellow-500":"bg-red-500 animate-pulse")}),e.jsxs("span",{className:"text-white text-sm font-medium",children:[ar(ce)," / ",ar(s)]})]}),K&&e.jsx("div",{className:"absolute top-0 left-0 right-0",children:e.jsx(ro,{value:ce/s*100,className:"h-1 rounded-none"})}),!ne&&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(LF,{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:`${ge}%`}})})]}),e.jsx("div",{className:"absolute bottom-4 left-0 right-0 flex justify-center gap-3 px-4",children:ne?e.jsxs(e.Fragment,{children:[e.jsxs(U,{variant:"secondary",size:"lg",className:"bg-white/20 hover:bg-white/30 text-white",onClick:_r,children:[e.jsx(no,{className:"h-5 w-5 mr-2"}),"Re-record"]}),e.jsx(U,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:es,children:Te?e.jsx(uv,{className:"h-5 w-5"}):e.jsx(lu,{className:"h-5 w-5"})}),e.jsxs(U,{size:"lg",className:"bg-green-500 hover:bg-green-600 text-white",onClick:Zn,children:[e.jsx(Xr,{className:"h-5 w-5 mr-2"}),"Use This Video"]})]}):e.jsxs(e.Fragment,{children:[v==="camera"?e.jsx(U,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:nn,disabled:K||$e!==null,children:e.jsx(Kg,{className:"h-5 w-5"})}):e.jsx("div",{className:"h-12 w-12"}),!K&&$e===null?e.jsx(U,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:v==="screen"?On:Rr,children:v==="screen"?e.jsx(IF,{className:"h-6 w-6"}):e.jsx(Wr,{className:"h-6 w-6"})}):e.jsxs(e.Fragment,{children:[e.jsx(U,{size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:Q?Hs:cr,children:Q?e.jsx(lu,{className:"h-5 w-5"}):e.jsx(uv,{className:"h-5 w-5"})}),e.jsx(U,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:Gn,children:e.jsx(db,{className:"h-6 w-6 fill-current"})})]}),e.jsx("div",{className:"h-12 w-12"})]})})]})]})}function wOn({open:s,onOpenChange:t,onUploaded:n}){const{user:r}=vs(),{toast:a}=Ai(),[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:p,error:f}=await q.storage.from("cma-videos").createSignedUrl(h,60*60*24*365*5);if(f||!(p!=null&&p.signedUrl))throw f||new Error("Could not sign video URL");n(p.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(Ds,{className:"max-w-2xl",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Record a personal message"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"A 30-second hello goes a long way. Welcome your client, explain the price, and invite their reply."})]}),i?e.jsxs("div",{className:"py-12 flex flex-col items-center gap-3",children:[e.jsx(Et,{className:"w-8 h-8 animate-spin text-primary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading your video…"})]}):e.jsx(kE,{maxDurationSeconds:180,onRecordingComplete:o})]})})}function jOn({value:s,onChange:t}){const{user:n}=vs(),[r,a]=j.useState(!1);return e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(Wr,{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(er,{className:"w-3.5 h-3.5"})})]}),e.jsxs("p",{className:"text-xs text-emerald-700 flex items-center gap-1",children:[e.jsx(lu,{className:"w-3 h-3"})," Video attached"]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(T9,{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(U,{variant:"outline",onClick:()=>a(!0),className:"gap-2",children:[e.jsx(Wr,{className:"w-4 h-4"}),"Record New"]})]}),e.jsx(wOn,{open:r,onOpenChange:a,onUploaded:i=>t({url:i,label:"Personal message"})})]})]})}function Rk(s){const t=Number(String(s).replace(/[^0-9.]/g,""));return Number.isFinite(t)&&t>0?t:null}function NOn({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:Rk(i.bedrooms),bathrooms:Rk(i.bathrooms),sqft:Rk(i.sqft),yearBuilt:Rk(i.yearBuilt),propertyType:i.propertyType||null,propertySubType:i.propertySubType||null}),t(!1)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Fill in the subject property basics"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"When the MLS feed does not return the home details, add the basics here and LevelUp will keep the CMA moving."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Beds"}),e.jsx(xe,{inputMode:"decimal",value:i.bedrooms,onChange:c=>l(d=>({...d,bedrooms:c.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Baths"}),e.jsx(xe,{inputMode:"decimal",value:i.bathrooms,onChange:c=>l(d=>({...d,bathrooms:c.target.value})),placeholder:"2"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Sq Ft"}),e.jsx(xe,{inputMode:"numeric",value:i.sqft,onChange:c=>l(d=>({...d,sqft:c.target.value})),placeholder:"1850"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Year Built"}),e.jsx(xe,{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(te,{className:"text-xs",children:"Property Type"}),e.jsx(xe,{value:i.propertyType,onChange:c=>l(d=>({...d,propertyType:c.target.value})),placeholder:"Residential"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Subtype"}),e.jsx(xe,{value:i.propertySubType,onChange:c=>l(d=>({...d,propertySubType:c.target.value})),placeholder:"Single Family"})]})]}),e.jsxs(U,{className:"w-full",onClick:o,disabled:a,children:[a?e.jsx(Et,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Ho,{className:"w-4 h-4 mr-2"}),"Save subject details"]})]})]})})}function kOn({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=Rk(a.price),c=Rk(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:Rk(a.bedrooms),bathrooms:Rk(a.bathrooms),sqft:c,yearBuilt:Rk(a.yearBuilt),photos:[]}),t(!1))};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-2xl",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Add a comparable manually"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Use this when the MLS feed misses a property or you already know the best comp. Add at least the address, price, and square footage."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(te,{className:"text-xs",children:"Address"}),e.jsx(xe,{value:a.address,onChange:o=>i(c=>({...c,address:o.target.value})),placeholder:"123 Comparable St"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"City"}),e.jsx(xe,{value:a.city,onChange:o=>i(c=>({...c,city:o.target.value}))})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"State"}),e.jsx(xe,{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(te,{className:"text-xs",children:"Status"}),e.jsx(xe,{value:a.status,onChange:o=>i(c=>({...c,status:o.target.value})),placeholder:"Closed"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Price"}),e.jsx(xe,{inputMode:"numeric",value:a.price,onChange:o=>i(c=>({...c,price:o.target.value})),placeholder:"525000"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Sq Ft"}),e.jsx(xe,{inputMode:"numeric",value:a.sqft,onChange:o=>i(c=>({...c,sqft:o.target.value})),placeholder:"1800"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Beds"}),e.jsx(xe,{inputMode:"decimal",value:a.bedrooms,onChange:o=>i(c=>({...c,bedrooms:o.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Baths"}),e.jsx(xe,{inputMode:"decimal",value:a.bathrooms,onChange:o=>i(c=>({...c,bathrooms:o.target.value})),placeholder:"2"})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Year Built"}),e.jsx(xe,{className:"max-w-[180px]",inputMode:"numeric",value:a.yearBuilt,onChange:o=>i(c=>({...c,yearBuilt:o.target.value})),placeholder:"2005"})]}),e.jsxs(U,{className:"w-full",onClick:l,disabled:!a.address.trim()||!Rk(a.price)||!Rk(a.sqft),children:[e.jsx(an,{className:"w-4 h-4 mr-2"}),"Add comp to CMA"]})]})]})})}function SOn(){var he,ge,ke,Te,Me,Oe,Se;const{id:s}=Di(),t=Wn(),{toast:n}=Ai(),{data:r,isLoading:a}=z8n(s),{data:i}=B8n(s),l=U8n(),o=V8n(),c=H8n(),{leadSite:d,isLoading:u}=$p(),[h,m]=j.useState([]),[p,f]=j.useState({sqftPct:.2,monthsBack:6,maxMiles:5,statuses:["Active","Pending","Closed"]}),[x,y]=j.useState(null),[v,b]=j.useState(!1),[N,S]=j.useState({low:"",likely:"",high:"",note:""}),[A,T]=j.useState(!1),[L,M]=j.useState(!1),[I,R]=j.useState(!1),[z,$]=j.useState(null),H=async Qe=>{var qe,Ze;if(!r||!(Qe!=null&&Qe.address)||!(Qe!=null&&Qe.city)||!(Qe!=null&&Qe.state))return Qe;let Ae={...Qe};const Fe=async Ue=>{const{data:Ye,error:Ge}=await q.functions.invoke("cma-subject-lookup",{body:{address:Ue.address,city:Ue.city,state:Ue.state,zip:Ue.zip,latitude:Ue.latitude,longitude:Ue.longitude,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id}});if(Ge)throw Ge;return(Ye==null?void 0:Ye.matches)||[]},Ne=Ue=>{const Ge=Ue.find(ft=>Number.isFinite(Number(ft.latitude))&&Number.isFinite(Number(ft.longitude)))||Ue[0];if(!Ge)return;const He=typeof Ge.match_type=="string"&&Ge.match_type.startsWith("nearby-"),tt=He&&Number.isFinite(Number(Ae.latitude))&&Number.isFinite(Number(Ae.longitude)),pt=ft=>Ge[ft]!==void 0&&Ge[ft]!==null&&Ge[ft]!==""&&Ge[ft]!==0?Ge[ft]:Ae[ft];Ae={...Ae,bedrooms:pt("bedrooms"),bathrooms:pt("bathrooms"),sqft:pt("sqft"),yearBuilt:pt("yearBuilt"),lotSize:pt("lotSize"),propertyType:pt("propertyType"),propertySubType:pt("propertySubType"),source_provider:Ge.source_provider??Ae.source_provider,match_type:Ge.match_type??Ae.match_type,matched_mls_address:He?Ge.address:Ae.matched_mls_address,latitude:tt?Ae.latitude:Ge.latitude??Ae.latitude,longitude:tt?Ae.longitude:Ge.longitude??Ae.longitude,mlsNumber:He?Ae.mlsNumber:Ge.mlsNumber??Ae.mlsNumber,photos:!He&&Array.isArray(Ge.photos)&&Ge.photos.length?Ge.photos:Ae.photos}};Ne(await Fe(Ae));const $e=()=>Number.isFinite(Number(Ae.latitude))&&Number.isFinite(Number(Ae.longitude));if(!$e()){const{data:Ue}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle(),Ye=Ue==null?void 0:Ue.value;if(Ye){const Ge=encodeURIComponent(`${Ae.address}, ${Ae.city}, ${Ae.state} ${Ae.zip||""}`.trim()),tt=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${Ge}.json?access_token=${Ye}&limit=1&country=us`)).json(),pt=(Ze=(qe=tt==null?void 0:tt.features)==null?void 0:qe[0])==null?void 0:Ze.center;Array.isArray(pt)&&pt.length===2&&(Ae.longitude=pt[0],Ae.latitude=pt[1])}}if((!Ae.bedrooms||!Ae.bathrooms||!Ae.sqft||!Ae.yearBuilt)&&$e())try{Ne(await Fe(Ae))}catch(Ue){console.warn("second-pass subject lookup failed",Ue)}return JSON.stringify(Ae)!==JSON.stringify(Qe)&&await l.mutateAsync({id:r.id,patch:{subject:Ae}}),Ae};j.useEffect(()=>{var Fe,Ne;r!=null&&r.settings&&f({sqftPct:r.settings.sqftPct??.2,monthsBack:r.settings.monthsBack??6,maxMiles:r.settings.maxMiles??5,statuses:r.settings.statuses??["Active","Pending","Closed"]});const Qe=(Fe=r==null?void 0:r.settings)==null?void 0:Fe.priceOverride;Qe!=null&&Qe.enabled&&(b(!0),S({low:Qe.low!=null?String(Qe.low):"",likely:Qe.likely!=null?String(Qe.likely):"",high:Qe.high!=null?String(Qe.high):"",note:Qe.note??""}));const Ae=(Ne=r==null?void 0:r.settings)==null?void 0:Ne.personalVideo;Ae!=null&&Ae.url&&$({url:Ae.url,thumb:Ae.thumb,label:Ae.label})},[r==null?void 0:r.id]);const V=j.useRef(!1);j.useEffect(()=>{V.current||i!=null&&i.length&&(m(i.map(Qe=>({...Qe.snapshot,selected:Qe.selected,manual:Qe.manual,score:Qe.score}))),V.current=!0)},[i]);const K=j.useRef(null);j.useEffect(()=>{if(!r||u)return;const Qe=r.subject||{},Ae=Number.isFinite(Number(Qe.latitude))&&Number.isFinite(Number(Qe.longitude)),Fe=!!(Number(Qe.bedrooms)||Number(Qe.bathrooms)||Number(Qe.sqft)||Number(Qe.yearBuilt));if(Ae&&Fe)return;const Ne=`${r.id}:${(d==null?void 0:d.id)??r.lead_site_id??"no-site"}`;K.current!==Ne&&(!Qe.address||!Qe.city||!Qe.state||(K.current=Ne,(async()=>{try{await H(Qe)}catch($e){console.warn("subject enrich failed",$e)}})()))},[r==null?void 0:r.id,r==null?void 0:r.lead_site_id,d==null?void 0:d.id,u]);const Z=j.useMemo(()=>r?qwt(r.subject,h):null,[r,h]),Q=async()=>{if(r)try{const Qe=await H(r.subject),Ae=await o.mutateAsync({subject:Qe,filters:p,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id});m(Ae.comps.map(Fe=>({...Fe,selected:!0})).slice(0,12)),n({title:`Found ${Ae.comps.length} comps`,description:`Top ${Math.min(12,Ae.comps.length)} auto-selected.`})}catch(Qe){n({title:"Search failed",description:Qe.message,variant:"destructive"})}},le=Qe=>{m(Ae=>Ae.map((Fe,Ne)=>Ne===Qe?{...Fe,selected:!Fe.selected}:Fe))},ue=Qe=>{m(Ae=>Ae.filter((Fe,Ne)=>Ne!==Qe))},se=async Qe=>{if(!r)return;const Ae=Object.fromEntries(Object.entries(Qe).filter(([,Ne])=>Ne!=null&&Ne!=="")),Fe={...r.subject,...Ae,manually_enriched:!0};await l.mutateAsync({id:r.id,patch:{subject:Fe}}),n({title:"Subject details saved",description:Fe.sqft?"You can now find comps or add your own.":"Add square footage to unlock suggested pricing."})},ne=Qe=>{m(Ae=>[{...Qe,selected:!0,manual:!0},...Ae]),n({title:"Manual comp added"})},ie=async(Qe=!1)=>{if(!r)return;const Ae=qwt(r.subject,h),Fe=Ze=>{const Ue=Number(String(Ze).replace(/[^0-9.]/g,""));return Number.isFinite(Ue)&&Ue>0?Math.round(Ue):null},Ne=v?Fe(N.likely):null,$e=v?Fe(N.low):null,Ve=v?Fe(N.high):null,qe=v&&Ne;await l.mutateAsync({id:r.id,patch:{settings:{...p,priceOverride:{enabled:v,low:$e,likely:Ne,high:Ve,note:N.note||null},personalVideo:z},price_low:qe?$e??Ne:Ae.low??null,price_likely:qe?Ne:Ae.likely??null,price_high:qe?Ve??Ne:Ae.high??null,status:Qe?"shared":r.status}}),await c.mutateAsync({cmaId:r.id,comps:h}),n({title:Qe?"CMA published":"CMA saved"})},ce=r?`https://cma.relevelup.com/${r.share_token}`:"";if(a||!r)return e.jsx(qs,{children:e.jsx("div",{className:"p-6",children:e.jsx(Et,{className:"w-6 h-6 animate-spin"})})});const je=h.filter(Qe=>Qe.selected).length,be=!((he=r.subject)!=null&&he.bedrooms)||!((ge=r.subject)!=null&&ge.bathrooms)||!((ke=r.subject)!=null&&ke.sqft)||!((Te=r.subject)!=null&&Te.yearBuilt);return e.jsx(qs,{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(U,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/cma"),children:[e.jsx(Aa,{className:"w-4 h-4 mr-1"})," All CMAs"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{variant:"outline",onClick:()=>ie(!1),disabled:l.isPending,children:[e.jsx(Ho,{className:"w-4 h-4 mr-1"}),"Save"]}),e.jsxs(U,{onClick:()=>ie(!0),disabled:l.isPending,children:[e.jsx(jd,{className:"w-4 h-4 mr-1"}),"Publish & Share"]}),r.status==="shared"&&e.jsxs(e.Fragment,{children:[e.jsxs(U,{variant:"secondary",onClick:()=>{navigator.clipboard.writeText(ce),n({title:"Link copied"})},children:[e.jsx(Sr,{className:"w-4 h-4 mr-1"}),"Copy Link"]}),e.jsxs(U,{onClick:()=>T(!0),children:[e.jsx(ln,{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(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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:"})," ",((Me=r.subject.sqft)==null?void 0:Me.toLocaleString())??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Year:"})," ",r.subject.yearBuilt??"—"]})]}),be&&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(U,{size:"sm",variant:"outline",className:"bg-white",onClick:()=>M(!0),children:[e.jsx(ri,{className:"w-3.5 h-3.5 mr-1"}),"Fill in property details"]})]}),!be&&e.jsxs(U,{size:"sm",variant:"ghost",className:"px-0",onClick:()=>M(!0),children:[e.jsx(ri,{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(te,{className:"text-xs",children:"Subject SqFt (needed for price band)"}),e.jsx(xe,{type:"number",defaultValue:"",onBlur:async Qe=>{const Ae=Number(Qe.target.value);Ae>0&&await l.mutateAsync({id:r.id,patch:{subject:{...r.subject,sqft:Ae}}})}})]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(Qw,{className:"w-4 h-4"}),"Suggested Price"]})}),e.jsxs(Ie,{className:"space-y-3",children:[Z!=null&&Z.likely?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-3xl font-bold",children:["$",(v&&Number(N.likely)>0?Number(N.likely):Z.likely).toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Comps suggest: $",(Oe=Z.low)==null?void 0:Oe.toLocaleString()," – $",(Se=Z.high)==null?void 0:Se.toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",Z.ppsf,"/sqft median · ",je," 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(te,{htmlFor:"override-toggle",className:"text-sm font-medium",children:"Override with my price"}),e.jsx(wn,{id:"override-toggle",checked:v,onCheckedChange:b})]}),v&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"My suggested price"}),e.jsx(xe,{type:"number",placeholder:"e.g. 750000",value:N.likely,onChange:Qe=>S(Ae=>({...Ae,likely:Qe.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Range low"}),e.jsx(xe,{type:"number",placeholder:"optional",value:N.low,onChange:Qe=>S(Ae=>({...Ae,low:Qe.target.value}))})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Range high"}),e.jsx(xe,{type:"number",placeholder:"optional",value:N.high,onChange:Qe=>S(Ae=>({...Ae,high:Qe.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Why this price (optional)"}),e.jsx(Fs,{rows:2,maxLength:500,placeholder:"Notes shown to your client",value:N.note,onChange:Qe=>S(Ae=>({...Ae,note:Qe.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(jOn,{value:z,onChange:$}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Filters"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs(te,{className:"text-xs",children:["SqFt tolerance: ±",Math.round(p.sqftPct*100),"%"]}),e.jsx(rg,{value:[p.sqftPct*100],min:5,max:50,step:5,onValueChange:([Qe])=>f(Ae=>({...Ae,sqftPct:Qe/100}))})]}),e.jsxs("div",{children:[e.jsxs(te,{className:"text-xs",children:["Search radius: ",p.maxMiles," mi"]}),e.jsx(rg,{value:[p.maxMiles],min:1,max:25,step:1,onValueChange:([Qe])=>f(Ae=>({...Ae,maxMiles:Qe}))})]}),e.jsxs("div",{children:[e.jsxs(te,{className:"text-xs",children:["Sold within: ",p.monthsBack," months"]}),e.jsx(rg,{value:[p.monthsBack],min:1,max:24,step:1,onValueChange:([Qe])=>f(Ae=>({...Ae,monthsBack:Qe}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs",children:"Status"}),["Active","Pending","Closed"].map(Qe=>e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx(xi,{checked:p.statuses.includes(Qe),onCheckedChange:Ae=>f(Fe=>({...Fe,statuses:Ae?[...Fe.statuses,Qe]:Fe.statuses.filter(Ne=>Ne!==Qe)}))})," ",Qe]},Qe))]}),e.jsxs(U,{className:"w-full",onClick:Q,disabled:o.isPending,children:[o.isPending?e.jsx(Et,{className:"w-4 h-4 animate-spin mr-2"}):e.jsx(cn,{className:"w-4 h-4 mr-2"}),"Find Comps"]}),e.jsxs(U,{variant:"outline",className:"w-full",onClick:()=>R(!0),children:[e.jsx(an,{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(TRn,{subject:r.subject,comps:h,radiusMiles:p.maxMiles,onMarkerClick:Qe=>y(Qe)}),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:[je," selected"]})]}),h.length?e.jsx("div",{className:"space-y-2",children:h.map((Qe,Ae)=>{var Fe;return e.jsx(we,{className:Qe.selected?"":"opacity-50",children:e.jsxs(Ie,{className:"p-3 flex gap-3 items-center",children:[e.jsx(xi,{checked:Qe.selected,onCheckedChange:()=>le(Ae)}),e.jsxs("button",{type:"button",onClick:()=>y(Ae),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(NCe,{photos:Qe.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:Qe.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Qe.city,", ",Qe.state," · ",Qe.bedrooms??"?","bd/",Qe.bathrooms??"?","ba · ",((Fe=Qe.sqft)==null?void 0:Fe.toLocaleString())??"?"," sqft",Qe.yearBuilt?` · ${Qe.yearBuilt}`:""]}),e.jsxs("div",{className:"text-xs mt-0.5",children:[e.jsx(Be,{variant:"outline",className:"mr-1",children:Qe.status}),Qe.score!=null&&e.jsxs("span",{className:"text-muted-foreground",children:["Score ",Qe.score]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"font-semibold",children:["$",(Qe.soldPrice||Qe.price||0).toLocaleString()]}),Qe.sqft&&(Qe.soldPrice||Qe.price)?e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",Math.round((Qe.soldPrice||Qe.price)/Qe.sqft),"/sqft"]}):null]})]}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>y(Ae),title:"View details",children:e.jsx(xa,{className:"w-4 h-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>ue(Ae),title:"Remove",children:e.jsx(In,{className:"w-4 h-4"})})]})},Ae)})}):e.jsx(we,{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:[be&&e.jsx(U,{variant:"outline",size:"sm",onClick:()=>M(!0),children:"Fill subject details"}),e.jsx(U,{variant:"outline",size:"sm",onClick:()=>R(!0),children:"Add manual comp"})]})]})})})]})]}),e.jsx(ROt,{comp:x!=null?h[x]:null,open:x!=null,onClose:()=>y(null)}),e.jsx(NOn,{open:L,onOpenChange:M,subject:r.subject,onSave:se,isSaving:l.isPending}),e.jsx(kOn,{open:I,onOpenChange:R,subject:r.subject,onAdd:ne}),e.jsx(_Wt,{open:A,onOpenChange:T,cma:r})]})})}const vP="listing-presentations";function SYt(){const{user:s}=vs(),t=Qt(),n=ct({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=yt({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=yt({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=yt({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 COn(){return ct({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 CYt(){const{user:s}=vs(),t=Qt(),n=ct({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=yt({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=yt({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=yt({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(vP).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=yt({mutationFn:async c=>{const d=[c.property_photo_path,c.pdf_path,c.thumbnail_path].filter(Boolean);d.length&&await q.storage.from(vP).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 AOn(s){return ct({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 EOn(s,t=3600){if(!s)return null;const{data:n,error:r}=await q.storage.from(vP).createSignedUrl(s,t);return r?null:(n==null?void 0:n.signedUrl)??null}const TOn="#2a4c64",MOn="#B8965A";function AYt(){const{user:s}=vs();return ct({queryKey:["agent-brand",s==null?void 0:s.id],enabled:!!s,staleTime:5*60*1e3,queryFn:async()=>{const t=s.id,[n,r,a]=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()]),i=n.data||{},l=r.data||[],o=l.find(u=>u.is_active)||l[0]||{},c=a.data||{};let d=i.brokerage_name||c.brokerage_display_name||o.brokerage_legal_name||null;if(!d&&i.brokerage_id){const{data:u}=await q.from("brokerages").select("name").eq("id",i.brokerage_id).maybeSingle();d=(u==null?void 0:u.name)||null}return{name:i.name||s.email||"Your Name",headshotUrl:i.avatar_url||null,brokerageName:d,brokerageLogoUrl:c.brokerage_logo_url||c.team_logo_url||o.team_logo_url||null,licenseNumber:o.agent_license_number||null,licenseState:o.license_state||null,phone:i.phone||null,email:c.display_email||i.email||s.email||null,website:i.website_url||null,brandColor:o.brand_color||TOn,accentColor:o.accent_color||MOn,tagline:c.positioning_statement||i.title||c.title||null}}})}const gGe={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."}},POn={cover:"Cover",welcome:"Marketing commitment",agent:"About your agent",overview:"Marketing plan overview",closing:"Closing commitment"};function EYt(s,t){var i;const n=((i=s==null?void 0:s.copy)==null?void 0:i[t])||{},r=gGe[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 TYt={enabled:!1,name:"",title:null,headshotUrl:null,phone:null,email:null,brokerageName:null,licenseNumber:null,bio:null};function MYt(s){return{...TYt,...s||{}}}const i9e=[{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."}],PYt=()=>typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`cp_${Math.random().toString(36).slice(2)}`;function Zst(s,t=0){const n={id:PYt(),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 LYt(s){return Array.isArray(s)?s.filter(t=>t&&typeof t=="object").map((t,n)=>({...Zst(t.layout||"story",n),...t,id:t.id||PYt(),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 xGe={hidden:["overview"]},yGe={x:.5,y:.5},ed=(s,t,n=!0)=>({key:s,label:t,enabled:n}),VEe=[{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:[ed("hdr","Full HDR interior and exterior photo set"),ed("drone","Aerial drone photography of the home and lot"),ed("twilight","Twilight exterior session for the hero image"),ed("staging","Virtual staging for vacant or transitional rooms",!1),ed("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:[ed("walkthrough","Cinematic full-property walkthrough video"),ed("reels","Vertical short-form cuts for Reels, Shorts, and TikTok"),ed("oncamera","On-camera agent introduction to the home"),ed("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:[ed("data","Complete, accurate MLS data so your home shows in every filter"),ed("copy","Copywriting that leads with the features buyers pay for"),ed("pricing","Pricing built on live comparable and absorption data"),ed("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:[ed("zillow","Zillow — the highest-traffic buyer search portal"),ed("realtor","Realtor.com — direct MLS-sourced listing feed"),ed("homes","Homes.com — agent-attributed listing exposure"),ed("others","Redfin, Trulia, Movoto, and hundreds of partner sites"),ed("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:[ed("gallery","Full-screen gallery, video, and floor plan in one place"),ed("mobile","Mobile-first design with a one-tap inquiry form"),ed("link","Shareable link used across ads, email, and QR signage"),ed("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:[ed("organic","Just-listed launch across feed, stories, and reels"),ed("ads","Geo-targeted paid campaigns aimed at active buyers"),ed("retarget","Retargeting so interested viewers keep seeing your home"),ed("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:[ed("database","Direct email to my buyer and past-client database"),ed("agents","Broadcast to area agents with matching buyers"),ed("referral","Referral partner network notified at launch"),ed("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:[ed("public","Strategically timed public open houses"),ed("broker","Broker open house for agents with active buyers"),ed("signin","Digital sign-in that captures every visitor"),ed("neighbors","Neighbor invitations and just-listed mailers"),ed("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:[ed("weekly","Weekly seller report on the schedule you prefer"),ed("feedback","Showing feedback delivered as it comes in"),ed("analytics","Online traffic and engagement analytics"),ed("access","Direct access to me by call, text, or email")]}],LOn=Object.fromEntries(VEe.map(s=>[s.key,(s.options||[]).map(t=>t.label)]));function vGe(s){return s!=null&&s.length?VEe.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}}):VEe.map(t=>{var n;return{...t,options:(n=t.options)==null?void 0:n.map(r=>({...r}))}})}const IOn={welcome:"Marketing commitment",agent:"About your agent",overview:"Marketing plan overview",closing:"Closing commitment"};function kh(s){"@babel/helpers - typeof";return kh=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},kh(s)}var vS=Uint8Array,Hw=Uint16Array,Xst=Int32Array,Qst=new vS([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]),Jst=new vS([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]),Zjt=new vS([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),IYt=function(s,t){for(var n=new Hw(31),r=0;r<31;++r)n[r]=t+=1<>1|(ap&21845)<<1;dT=(dT&52428)>>2|(dT&13107)<<2,dT=(dT&61680)>>4|(dT&3855)<<4,_Ge[ap]=((dT&65280)>>8|(dT&255)<<8)>>1}var lJ=function(s,t,n){for(var r=s.length,a=0,i=new Hw(t);a>c]=d}else for(o=new Hw(r),a=0;a>15-s[a]);return o},W7=new vS(288);for(var ap=0;ap<144;++ap)W7[ap]=8;for(var ap=144;ap<256;++ap)W7[ap]=9;for(var ap=256;ap<280;++ap)W7[ap]=7;for(var ap=280;ap<288;++ap)W7[ap]=8;var HEe=new vS(32);for(var ap=0;ap<32;++ap)HEe[ap]=5;var OOn=lJ(W7,9,0),FOn=lJ(HEe,5,0),DYt=function(s){return(s+7)/8|0},zOn=function(s,t,n){return(n==null||n>s.length)&&(n=s.length),new vS(s.subarray(t,n))},rC=function(s,t,n){n<<=t&7;var r=t/8|0;s[r]|=n,s[r+1]|=n>>8},SY=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},o9e=function(s,t){for(var n=[],r=0;rm&&(m=i[r].s);var p=new Hw(m+1),f=wGe(n[u-1],p,0);if(f>t){var r=0,x=0,y=f-t,v=1<t)x+=v-(1<>=y;x>0;){var N=i[r].s;p[N]=0&&x;--r){var S=i[r].s;p[S]==t&&(--p[S],++x)}f=t}return{t:new vS(p),l:f}},wGe=function(s,t,n){return s.s==-1?Math.max(wGe(s.l,t,n+1),wGe(s.r,t,n+1)):t[s.s]=n},Qjt=function(s){for(var t=s.length;t&&!s[--t];);for(var n=new Hw(++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}},CY=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&&!R[Zjt[$-1]];--$);var H=d+5<<3,V=CY(a,W7)+CY(i,HEe)+l,K=CY(a,m)+CY(i,x)+l+14+3*$+CY(L,R)+2*L[16]+3*L[17]+7*L[18];if(c>=0&&H<=V&&H<=K)return OYt(t,u,s.subarray(c,c+d));var Z,Q,le,ue;if(rC(t,u,1+(K15&&(rC(t,u,ce[M]>>5&127),u+=ce[M]>>12)}}else Z=OOn,Q=W7,le=FOn,ue=HEe;for(var M=0;M255){var je=be>>18&31;SY(t,u,Z[je+257]),u+=Q[je+257],je>7&&(rC(t,u,be>>23&31),u+=Qst[je]);var he=be&31;SY(t,u,le[he]),u+=ue[he],he>3&&(SY(t,u,be>>5&8191),u+=Jst[he])}else SY(t,u,Z[be]),u+=Q[be]}return SY(t,u,Z[256]),u+Q[256]},BOn=new Xst([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),FYt=new vS(0),UOn=function(s,t,n,r,a,i){var l=i.z||s.length,o=new vS(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=BOn[t-1],m=h>>13,p=h&8191,f=(1<7e3||R>24576)&&(Z>423||!d)){u=Jjt(s,c,0,S,A,T,M,R,$,I-$,u),R=L=M=0,$=I;for(var Q=0;Q<286;++Q)A[Q]=0;for(var Q=0;Q<30;++Q)T[Q]=0}var le=2,ue=0,se=p,ne=V-K&32767;if(Z>2&&H==N(I-ne))for(var ie=Math.min(m,Z)-1,ce=Math.min(32767,I),je=Math.min(258,Z);ne<=ce&&--se&&V!=K;){if(s[I+le]==s[I+le-ne]){for(var be=0;bele){if(le=be,ue=ne,be>ie)break;for(var he=Math.min(ne,be-2),ge=0,Q=0;Qge&&(ge=Me,K=ke)}}}V=K,K=x[V],ne+=V-K&32767}if(ue){S[R++]=268435456|bGe[le]<<18|Xjt[ue];var Oe=bGe[le]&31,Se=Xjt[ue]&31;M+=Qst[Oe]+Jst[Se],++A[257+Oe],++T[Se],z=I+le,++L}else S[R++]=s[I],++A[s[I]]}}for(I=Math.max(I,z);I=l&&(c[u/8|0]=d,Qe=l),u=OYt(c,u+1,s.subarray(I,Qe))}i.i=l}return zOn(o,0,r+DYt(u)+a)},zYt=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}}},qOn=function(s,t,n,r,a){if(!a&&(a={l:1},t.dictionary)){var i=t.dictionary.subarray(-32768),l=new vS(i.length+s.length);l.set(i),l.set(s,i.length),s=l,a.w=i.length}return UOn(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)},BYt=function(s,t,n){for(;n;++t)s[t]=n,n>>>=8},$On=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=zYt();a.p(t.dictionary),BYt(s,2,a.d())}};function jGe(s,t){t||(t={});var n=zYt();n.p(s);var r=qOn(s,t,t.dictionary?6:2,4);return $On(r,t),BYt(r,r.length-4,n.d()),r}var VOn=typeof TextDecoder<"u"&&new TextDecoder,HOn=0;try{VOn.decode(FYt,{stream:!0}),HOn=1}catch{}function GOn(s){if(Array.isArray(s))return s}function WOn(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 e2t(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])})(),l9e={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 ent{constructor(t=QOn,n={}){Lr(this,"buffer");Lr(this,"byteLength");Lr(this,"byteOffset");Lr(this,"length");Lr(this,"offset");Lr(this,"lastWrittenByte");Lr(this,"littleEndian");Lr(this,"_data");Lr(this,"_mark");Lr(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 ent)&&(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=l9e[n].BYTES_PER_ELEMENT*t,a=this.byteOffset+this.offset,i=this.buffer.slice(a,a+r);if(this.littleEndian===JOn&&n!=="uint8"&&n!=="int8"){const o=new Uint8Array(this.buffer.slice(a,a+r));o.reverse();const c=new l9e[n](o.buffer);return this.offset+=r,c.reverse(),c}const l=new l9e[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)}}/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */const eFn=4,n2t=0,r2t=1,tFn=2;function mW(s){let t=s.length;for(;--t>=0;)s[t]=0}const sFn=0,UYt=1,nFn=2,rFn=3,aFn=258,tnt=29,Wre=256,Nte=Wre+1+tnt,Zq=30,snt=19,qYt=2*Nte+1,iO=15,c9e=16,iFn=7,nnt=256,$Yt=16,VYt=17,HYt=18,NGe=new Uint8Array([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]),s4e=new Uint8Array([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]),oFn=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),GYt=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),lFn=512,IC=new Array((Nte+2)*2);mW(IC);const cJ=new Array(Zq*2);mW(cJ);const kte=new Array(lFn);mW(kte);const Ste=new Array(aFn-rFn+1);mW(Ste);const rnt=new Array(tnt);mW(rnt);const GEe=new Array(Zq);mW(GEe);function d9e(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}let WYt,KYt,YYt;function u9e(s,t){this.dyn_tree=s,this.max_code=0,this.stat_desc=t}const ZYt=s=>s<256?kte[s]:kte[256+(s>>>7)],Cte=(s,t)=>{s.pending_buf[s.pending++]=t&255,s.pending_buf[s.pending++]=t>>>8&255},b_=(s,t,n)=>{s.bi_valid>c9e-n?(s.bi_buf|=t<>c9e-s.bi_valid,s.bi_valid+=n-c9e):(s.bi_buf|=t<{b_(s,n[t*2],n[t*2+1])},XYt=(s,t)=>{let n=0;do n|=s&1,s>>>=1,n<<=1;while(--t>0);return n>>>1},cFn=s=>{s.bi_valid===16?(Cte(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)},dFn=(s,t)=>{const 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;let d,u,h,m,p,f,x=0;for(m=0;m<=iO;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]++,p=0,u>=o&&(p=l[u-o]),f=n[u*2],s.opt_len+=f*(m+p),i&&(s.static_len+=f*(a[u*2+1]+p)));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--)}},QYt=(s,t,n)=>{const r=new Array(iO+1);let a=0,i,l;for(i=1;i<=iO;i++)a=a+n[i-1]<<1,r[i]=a;for(l=0;l<=t;l++){let o=s[l*2+1];o!==0&&(s[l*2]=XYt(r[o]++,o))}},uFn=()=>{let s,t,n,r,a;const i=new Array(iO+1);for(n=0,r=0;r>=7;r{let t;for(t=0;t{s.bi_valid>8?Cte(s,s.bi_buf):s.bi_valid>0&&(s.pending_buf[s.pending++]=s.bi_buf),s.bi_buf=0,s.bi_valid=0},a2t=(s,t,n,r)=>{const a=t*2,i=n*2;return s[a]{const r=s.heap[n];let a=n<<1;for(;a<=s.heap_len&&(a{let r,a,i=0,l,o;if(s.sym_next!==0)do r=s.pending_buf[s.sym_buf+i++]&255,r+=(s.pending_buf[s.sym_buf+i++]&255)<<8,a=s.pending_buf[s.sym_buf+i++],r===0?d4(s,a,t):(l=Ste[a],d4(s,l+Wre+1,t),o=NGe[l],o!==0&&(a-=rnt[l],b_(s,a,o)),r--,l=ZYt(r),d4(s,l,n),o=s4e[l],o!==0&&(r-=GEe[l],b_(s,r,o)));while(i{const n=t.dyn_tree,r=t.stat_desc.static_tree,a=t.stat_desc.has_stree,i=t.stat_desc.elems;let l,o,c=-1,d;for(s.heap_len=0,s.heap_max=qYt,l=0;l>1;l>=1;l--)h9e(s,n,l);d=i;do l=s.heap[1],s.heap[1]=s.heap[s.heap_len--],h9e(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++,h9e(s,n,1);while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1],dFn(s,t),QYt(n,c,s.bl_count)},o2t=(s,t,n)=>{let 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{let r,a=-1,i,l=t[0*2+1],o=0,c=7,d=4;for(l===0&&(c=138,d=3),r=0;r<=n;r++)if(i=l,l=t[(r+1)*2+1],!(++o{let t;for(o2t(s,s.dyn_ltree,s.l_desc.max_code),o2t(s,s.dyn_dtree,s.d_desc.max_code),kGe(s,s.bl_desc),t=snt-1;t>=3&&s.bl_tree[GYt[t]*2+1]===0;t--);return s.opt_len+=3*(t+1)+5+5+4,t},mFn=(s,t,n,r)=>{let a;for(b_(s,t-257,5),b_(s,n-1,5),b_(s,r-4,4),a=0;a{let t=4093624447,n;for(n=0;n<=31;n++,t>>>=1)if(t&1&&s.dyn_ltree[n*2]!==0)return n2t;if(s.dyn_ltree[9*2]!==0||s.dyn_ltree[10*2]!==0||s.dyn_ltree[13*2]!==0)return r2t;for(n=32;n{c2t||(uFn(),c2t=!0),s.l_desc=new u9e(s.dyn_ltree,WYt),s.d_desc=new u9e(s.dyn_dtree,KYt),s.bl_desc=new u9e(s.bl_tree,YYt),s.bi_buf=0,s.bi_valid=0,JYt(s)},tZt=(s,t,n,r)=>{b_(s,(sFn<<1)+(r?1:0),3),eZt(s),Cte(s,n),Cte(s,~n),n&&s.pending_buf.set(s.window.subarray(t,t+n),s.pending),s.pending+=n},gFn=s=>{b_(s,UYt<<1,3),d4(s,nnt,IC),cFn(s)},xFn=(s,t,n,r)=>{let a,i,l=0;s.level>0?(s.strm.data_type===tFn&&(s.strm.data_type=pFn(s)),kGe(s,s.l_desc),kGe(s,s.d_desc),l=hFn(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?tZt(s,t,n,r):s.strategy===eFn||i===a?(b_(s,(UYt<<1)+(r?1:0),3),i2t(s,IC,cJ)):(b_(s,(nFn<<1)+(r?1:0),3),mFn(s,s.l_desc.max_code+1,s.d_desc.max_code+1,l+1),i2t(s,s.dyn_ltree,s.dyn_dtree)),JYt(s),r&&eZt(s)},yFn=(s,t,n)=>(s.pending_buf[s.sym_buf+s.sym_next++]=t,s.pending_buf[s.sym_buf+s.sym_next++]=t>>8,s.pending_buf[s.sym_buf+s.sym_next++]=n,t===0?s.dyn_ltree[n*2]++:(s.matches++,t--,s.dyn_ltree[(Ste[n]+Wre+1)*2]++,s.dyn_dtree[ZYt(t)*2]++),s.sym_next===s.sym_end);var vFn=fFn,bFn=tZt,_Fn=xFn,wFn=yFn,jFn=gFn,NFn={_tr_init:vFn,_tr_stored_block:bFn,_tr_flush_block:_Fn,_tr_tally:wFn,_tr_align:jFn};const kFn=(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 Ate=kFn;const SFn=()=>{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},CFn=new Uint32Array(SFn()),AFn=(s,t,n,r)=>{const a=CFn,i=r+n;s^=-1;for(let l=r;l>>8^a[(s^t[l])&255];return s^-1};var K0=AFn,zH={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"},Kre={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:EFn,_tr_stored_block:SGe,_tr_flush_block:TFn,_tr_tally:YM,_tr_align:MFn}=NFn,{Z_NO_FLUSH:ZM,Z_PARTIAL_FLUSH:PFn,Z_FULL_FLUSH:LFn,Z_FINISH:D2,Z_BLOCK:d2t,Z_OK:Wy,Z_STREAM_END:u2t,Z_STREAM_ERROR:H4,Z_DATA_ERROR:IFn,Z_BUF_ERROR:m9e,Z_DEFAULT_COMPRESSION:RFn,Z_FILTERED:DFn,Z_HUFFMAN_ONLY:Qle,Z_RLE:OFn,Z_FIXED:FFn,Z_DEFAULT_STRATEGY:zFn,Z_UNKNOWN:BFn,Z_DEFLATED:pIe}=Kre,UFn=9,qFn=15,$Fn=8,VFn=29,HFn=256,CGe=HFn+1+VFn,GFn=30,WFn=19,KFn=2*CGe+1,YFn=15,Gd=3,iM=258,G4=iM+Gd+1,ZFn=32,BH=42,ant=57,AGe=69,EGe=73,TGe=91,MGe=103,oO=113,OZ=666,ib=1,pW=2,K7=3,fW=4,XFn=3,lO=(s,t)=>(s.msg=zH[t],t),h2t=s=>s*2-(s>4?9:0),c6=s=>{let t=s.length;for(;--t>=0;)s[t]=0},QFn=s=>{let t,n,r,a=s.w_size;t=s.hash_size,r=t;do n=s.head[--r],s.head[r]=n>=a?n-a:0;while(--t);t=a,r=t;do n=s.prev[--r],s.prev[r]=n>=a?n-a:0;while(--t)};let JFn=(s,t,n)=>(t<{const t=s.state;let n=t.pending;n>s.avail_out&&(n=s.avail_out),n!==0&&(s.output.set(t.pending_buf.subarray(t.pending_out,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))},Gw=(s,t)=>{TFn(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,t),s.block_start=s.strstart,yw(s.strm)},zu=(s,t)=>{s.pending_buf[s.pending++]=t},AY=(s,t)=>{s.pending_buf[s.pending++]=t>>>8&255,s.pending_buf[s.pending++]=t&255},PGe=(s,t,n,r)=>{let a=s.avail_in;return a>r&&(a=r),a===0?0:(s.avail_in-=a,t.set(s.input.subarray(s.next_in,s.next_in+a),n),s.state.wrap===1?s.adler=Ate(s.adler,t,a,n):s.state.wrap===2&&(s.adler=K0(s.adler,t,a,n)),s.next_in+=a,s.total_in+=a,a)},sZt=(s,t)=>{let n=s.max_chain_length,r=s.strstart,a,i,l=s.prev_length,o=s.nice_match;const c=s.strstart>s.w_size-G4?s.strstart-(s.w_size-G4):0,d=s.window,u=s.w_mask,h=s.prev,m=s.strstart+iM;let p=d[r+l-1],f=d[r+l];s.prev_length>=s.good_match&&(n>>=2),o>s.lookahead&&(o=s.lookahead);do if(a=t,!(d[a+l]!==f||d[a+l-1]!==p||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;p=d[r+l-1],f=d[r+l]}}while((t=h[t&u])>c&&--n!==0);return l<=s.lookahead?l:s.lookahead},UH=s=>{const t=s.w_size;let n,r,a;do{if(r=s.window_size-s.lookahead-s.strstart,s.strstart>=t+(t-G4)&&(s.window.set(s.window.subarray(t,t+t-r),0),s.match_start-=t,s.strstart-=t,s.block_start-=t,s.insert>s.strstart&&(s.insert=s.strstart),QFn(s),r+=t),s.strm.avail_in===0)break;if(n=PGe(s.strm,s.window,s.strstart+s.lookahead,r),s.lookahead+=n,s.lookahead+s.insert>=Gd)for(a=s.strstart-s.insert,s.ins_h=s.window[a],s.ins_h=XM(s,s.ins_h,s.window[a+1]);s.insert&&(s.ins_h=XM(s,s.ins_h,s.window[a+Gd-1]),s.prev[a&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=a,a++,s.insert--,!(s.lookahead+s.insert{let n=s.pending_buf_size-5>s.w_size?s.w_size:s.pending_buf_size-5,r,a,i,l=0,o=s.strm.avail_in;do{if(r=65535,i=s.bi_valid+42>>3,s.strm.avail_outa+s.strm.avail_in&&(r=a+s.strm.avail_in),r>i&&(r=i),r>8,s.pending_buf[s.pending-2]=~r,s.pending_buf[s.pending-1]=~r>>8,yw(s.strm),a&&(a>r&&(a=r),s.strm.output.set(s.window.subarray(s.block_start,s.block_start+a),s.strm.next_out),s.strm.next_out+=a,s.strm.avail_out-=a,s.strm.total_out+=a,s.block_start+=a,r-=a),r&&(PGe(s.strm,s.strm.output,s.strm.next_out,r),s.strm.next_out+=r,s.strm.avail_out-=r,s.strm.total_out+=r)}while(l===0);return o-=s.strm.avail_in,o&&(o>=s.w_size?(s.matches=2,s.window.set(s.strm.input.subarray(s.strm.next_in-s.w_size,s.strm.next_in),0),s.strstart=s.w_size,s.insert=s.strstart):(s.window_size-s.strstart<=o&&(s.strstart-=s.w_size,s.window.set(s.window.subarray(s.w_size,s.w_size+s.strstart),0),s.matches<2&&s.matches++,s.insert>s.strstart&&(s.insert=s.strstart)),s.window.set(s.strm.input.subarray(s.strm.next_in-o,s.strm.next_in),s.strstart),s.strstart+=o,s.insert+=o>s.w_size-s.insert?s.w_size-s.insert:o),s.block_start=s.strstart),s.high_wateri&&s.block_start>=s.w_size&&(s.block_start-=s.w_size,s.strstart-=s.w_size,s.window.set(s.window.subarray(s.w_size,s.w_size+s.strstart),0),s.matches<2&&s.matches++,i+=s.w_size,s.insert>s.strstart&&(s.insert=s.strstart)),i>s.strm.avail_in&&(i=s.strm.avail_in),i&&(PGe(s.strm,s.window,s.strstart,i),s.strstart+=i,s.insert+=i>s.w_size-s.insert?s.w_size-s.insert:i),s.high_water>3,i=s.pending_buf_size-i>65535?65535:s.pending_buf_size-i,n=i>s.w_size?s.w_size:i,a=s.strstart-s.block_start,(a>=n||(a||t===D2)&&t!==ZM&&s.strm.avail_in===0&&a<=i)&&(r=a>i?i:a,l=t===D2&&s.strm.avail_in===0&&r===a?1:0,SGe(s,s.block_start,r,l),s.block_start+=r,yw(s.strm)),l?K7:ib)},p9e=(s,t)=>{let n,r;for(;;){if(s.lookahead=Gd&&(s.ins_h=XM(s,s.ins_h,s.window[s.strstart+Gd-1]),n=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart),n!==0&&s.strstart-n<=s.w_size-G4&&(s.match_length=sZt(s,n)),s.match_length>=Gd)if(r=YM(s,s.strstart-s.match_start,s.match_length-Gd),s.lookahead-=s.match_length,s.match_length<=s.max_lazy_match&&s.lookahead>=Gd){s.match_length--;do s.strstart++,s.ins_h=XM(s,s.ins_h,s.window[s.strstart+Gd-1]),n=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart;while(--s.match_length!==0);s.strstart++}else s.strstart+=s.match_length,s.match_length=0,s.ins_h=s.window[s.strstart],s.ins_h=XM(s,s.ins_h,s.window[s.strstart+1]);else r=YM(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++;if(r&&(Gw(s,!1),s.strm.avail_out===0))return ib}return s.insert=s.strstart{let n,r,a;for(;;){if(s.lookahead=Gd&&(s.ins_h=XM(s,s.ins_h,s.window[s.strstart+Gd-1]),n=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart),s.prev_length=s.match_length,s.prev_match=s.match_start,s.match_length=Gd-1,n!==0&&s.prev_length4096)&&(s.match_length=Gd-1)),s.prev_length>=Gd&&s.match_length<=s.prev_length){a=s.strstart+s.lookahead-Gd,r=YM(s,s.strstart-1-s.prev_match,s.prev_length-Gd),s.lookahead-=s.prev_length-1,s.prev_length-=2;do++s.strstart<=a&&(s.ins_h=XM(s,s.ins_h,s.window[s.strstart+Gd-1]),n=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart);while(--s.prev_length!==0);if(s.match_available=0,s.match_length=Gd-1,s.strstart++,r&&(Gw(s,!1),s.strm.avail_out===0))return ib}else if(s.match_available){if(r=YM(s,0,s.window[s.strstart-1]),r&&Gw(s,!1),s.strstart++,s.lookahead--,s.strm.avail_out===0)return ib}else s.match_available=1,s.strstart++,s.lookahead--}return s.match_available&&(r=YM(s,0,s.window[s.strstart-1]),s.match_available=0),s.insert=s.strstart{let n,r,a,i;const l=s.window;for(;;){if(s.lookahead<=iM){if(UH(s),s.lookahead<=iM&&t===ZM)return ib;if(s.lookahead===0)break}if(s.match_length=0,s.lookahead>=Gd&&s.strstart>0&&(a=s.strstart-1,r=l[a],r===l[++a]&&r===l[++a]&&r===l[++a])){i=s.strstart+iM;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>=Gd?(n=YM(s,1,s.match_length-Gd),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0):(n=YM(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++),n&&(Gw(s,!1),s.strm.avail_out===0))return ib}return s.insert=0,t===D2?(Gw(s,!0),s.strm.avail_out===0?K7:fW):s.sym_next&&(Gw(s,!1),s.strm.avail_out===0)?ib:pW},t7n=(s,t)=>{let n;for(;;){if(s.lookahead===0&&(UH(s),s.lookahead===0)){if(t===ZM)return ib;break}if(s.match_length=0,n=YM(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,n&&(Gw(s,!1),s.strm.avail_out===0))return ib}return s.insert=0,t===D2?(Gw(s,!0),s.strm.avail_out===0?K7:fW):s.sym_next&&(Gw(s,!1),s.strm.avail_out===0)?ib:pW};function d5(s,t,n,r,a){this.good_length=s,this.max_lazy=t,this.nice_length=n,this.max_chain=r,this.func=a}const FZ=[new d5(0,0,0,0,nZt),new d5(4,4,8,4,p9e),new d5(4,5,16,8,p9e),new d5(4,6,32,32,p9e),new d5(4,4,16,16,dB),new d5(8,16,32,32,dB),new d5(8,16,128,128,dB),new d5(8,32,128,256,dB),new d5(32,128,258,1024,dB),new d5(32,258,258,4096,dB)],s7n=s=>{s.window_size=2*s.w_size,c6(s.head),s.max_lazy_match=FZ[s.level].max_lazy,s.good_match=FZ[s.level].good_length,s.nice_match=FZ[s.level].nice_length,s.max_chain_length=FZ[s.level].max_chain,s.strstart=0,s.block_start=0,s.lookahead=0,s.insert=0,s.match_length=s.prev_length=Gd-1,s.match_available=0,s.ins_h=0};function n7n(){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=pIe,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 Uint16Array(KFn*2),this.dyn_dtree=new Uint16Array((2*GFn+1)*2),this.bl_tree=new Uint16Array((2*WFn+1)*2),c6(this.dyn_ltree),c6(this.dyn_dtree),c6(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(YFn+1),this.heap=new Uint16Array(2*CGe+1),c6(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*CGe+1),c6(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const Yre=s=>{if(!s)return 1;const t=s.state;return!t||t.strm!==s||t.status!==BH&&t.status!==ant&&t.status!==AGe&&t.status!==EGe&&t.status!==TGe&&t.status!==MGe&&t.status!==oO&&t.status!==OZ?1:0},rZt=s=>{if(Yre(s))return lO(s,H4);s.total_in=s.total_out=0,s.data_type=BFn;const t=s.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap===2?ant:t.wrap?BH:oO,s.adler=t.wrap===2?0:1,t.last_flush=-2,EFn(t),Wy},aZt=s=>{const t=rZt(s);return t===Wy&&s7n(s.state),t},r7n=(s,t)=>Yre(s)||s.state.wrap!==2?H4:(s.state.gzhead=t,Wy),iZt=(s,t,n,r,a,i)=>{if(!s)return H4;let l=1;if(t===RFn&&(t=6),r<0?(l=0,r=-r):r>15&&(l=2,r-=16),a<1||a>UFn||n!==pIe||r<8||r>15||t<0||t>9||i<0||i>FFn||r===8&&l!==1)return lO(s,H4);r===8&&(r=9);const o=new n7n;return s.state=o,o.strm=s,o.status=BH,o.wrap=l,o.gzhead=null,o.w_bits=r,o.w_size=1<iZt(s,t,pIe,qFn,$Fn,zFn),i7n=(s,t)=>{if(Yre(s)||t>d2t||t<0)return s?lO(s,H4):H4;const n=s.state;if(!s.output||s.avail_in!==0&&!s.input||n.status===OZ&&t!==D2)return lO(s,s.avail_out===0?m9e:H4);const r=n.last_flush;if(n.last_flush=t,n.pending!==0){if(yw(s),s.avail_out===0)return n.last_flush=-1,Wy}else if(s.avail_in===0&&h2t(t)<=h2t(r)&&t!==D2)return lO(s,m9e);if(n.status===OZ&&s.avail_in!==0)return lO(s,m9e);if(n.status===BH&&n.wrap===0&&(n.status=oO),n.status===BH){let a=pIe+(n.w_bits-8<<4)<<8,i=-1;if(n.strategy>=Qle||n.level<2?i=0:n.level<6?i=1:n.level===6?i=2:i=3,a|=i<<6,n.strstart!==0&&(a|=ZFn),a+=31-a%31,AY(n,a),n.strstart!==0&&(AY(n,s.adler>>>16),AY(n,s.adler&65535)),s.adler=1,n.status=oO,yw(s),n.pending!==0)return n.last_flush=-1,Wy}if(n.status===ant){if(s.adler=0,zu(n,31),zu(n,139),zu(n,8),n.gzhead)zu(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),zu(n,n.gzhead.time&255),zu(n,n.gzhead.time>>8&255),zu(n,n.gzhead.time>>16&255),zu(n,n.gzhead.time>>24&255),zu(n,n.level===9?2:n.strategy>=Qle||n.level<2?4:0),zu(n,n.gzhead.os&255),n.gzhead.extra&&n.gzhead.extra.length&&(zu(n,n.gzhead.extra.length&255),zu(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(s.adler=K0(s.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=AGe;else if(zu(n,0),zu(n,0),zu(n,0),zu(n,0),zu(n,0),zu(n,n.level===9?2:n.strategy>=Qle||n.level<2?4:0),zu(n,XFn),n.status=oO,yw(s),n.pending!==0)return n.last_flush=-1,Wy}if(n.status===AGe){if(n.gzhead.extra){let a=n.pending,i=(n.gzhead.extra.length&65535)-n.gzindex;for(;n.pending+i>n.pending_buf_size;){let o=n.pending_buf_size-n.pending;if(n.pending_buf.set(n.gzhead.extra.subarray(n.gzindex,n.gzindex+o),n.pending),n.pending=n.pending_buf_size,n.gzhead.hcrc&&n.pending>a&&(s.adler=K0(s.adler,n.pending_buf,n.pending-a,a)),n.gzindex+=o,yw(s),n.pending!==0)return n.last_flush=-1,Wy;a=0,i-=o}let l=new Uint8Array(n.gzhead.extra);n.pending_buf.set(l.subarray(n.gzindex,n.gzindex+i),n.pending),n.pending+=i,n.gzhead.hcrc&&n.pending>a&&(s.adler=K0(s.adler,n.pending_buf,n.pending-a,a)),n.gzindex=0}n.status=EGe}if(n.status===EGe){if(n.gzhead.name){let a=n.pending,i;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>a&&(s.adler=K0(s.adler,n.pending_buf,n.pending-a,a)),yw(s),n.pending!==0)return n.last_flush=-1,Wy;a=0}n.gzindexa&&(s.adler=K0(s.adler,n.pending_buf,n.pending-a,a)),n.gzindex=0}n.status=TGe}if(n.status===TGe){if(n.gzhead.comment){let a=n.pending,i;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>a&&(s.adler=K0(s.adler,n.pending_buf,n.pending-a,a)),yw(s),n.pending!==0)return n.last_flush=-1,Wy;a=0}n.gzindexa&&(s.adler=K0(s.adler,n.pending_buf,n.pending-a,a))}n.status=MGe}if(n.status===MGe){if(n.gzhead.hcrc){if(n.pending+2>n.pending_buf_size&&(yw(s),n.pending!==0))return n.last_flush=-1,Wy;zu(n,s.adler&255),zu(n,s.adler>>8&255),s.adler=0}if(n.status=oO,yw(s),n.pending!==0)return n.last_flush=-1,Wy}if(s.avail_in!==0||n.lookahead!==0||t!==ZM&&n.status!==OZ){let a=n.level===0?nZt(n,t):n.strategy===Qle?t7n(n,t):n.strategy===OFn?e7n(n,t):FZ[n.level].func(n,t);if((a===K7||a===fW)&&(n.status=OZ),a===ib||a===K7)return s.avail_out===0&&(n.last_flush=-1),Wy;if(a===pW&&(t===PFn?MFn(n):t!==d2t&&(SGe(n,0,0,!1),t===LFn&&(c6(n.head),n.lookahead===0&&(n.strstart=0,n.block_start=0,n.insert=0))),yw(s),s.avail_out===0))return n.last_flush=-1,Wy}return t!==D2?Wy:n.wrap<=0?u2t:(n.wrap===2?(zu(n,s.adler&255),zu(n,s.adler>>8&255),zu(n,s.adler>>16&255),zu(n,s.adler>>24&255),zu(n,s.total_in&255),zu(n,s.total_in>>8&255),zu(n,s.total_in>>16&255),zu(n,s.total_in>>24&255)):(AY(n,s.adler>>>16),AY(n,s.adler&65535)),yw(s),n.wrap>0&&(n.wrap=-n.wrap),n.pending!==0?Wy:u2t)},o7n=s=>{if(Yre(s))return H4;const t=s.state.status;return s.state=null,t===oO?lO(s,IFn):Wy},l7n=(s,t)=>{let n=t.length;if(Yre(s))return H4;const r=s.state,a=r.wrap;if(a===2||a===1&&r.status!==BH||r.lookahead)return H4;if(a===1&&(s.adler=Ate(s.adler,t,n,0)),r.wrap=0,n>=r.w_size){a===0&&(c6(r.head),r.strstart=0,r.block_start=0,r.insert=0);let c=new Uint8Array(r.w_size);c.set(t.subarray(n-r.w_size,n),0),t=c,n=r.w_size}const i=s.avail_in,l=s.next_in,o=s.input;for(s.avail_in=n,s.next_in=0,s.input=t,UH(r);r.lookahead>=Gd;){let c=r.strstart,d=r.lookahead-(Gd-1);do r.ins_h=XM(r,r.ins_h,r.window[c+Gd-1]),r.prev[c&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=c,c++;while(--d);r.strstart=c,r.lookahead=Gd-1,UH(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=Gd-1,r.match_available=0,s.next_in=l,s.input=o,s.avail_in=i,r.wrap=a,Wy};var c7n=a7n,d7n=iZt,u7n=aZt,h7n=rZt,m7n=r7n,p7n=i7n,f7n=o7n,g7n=l7n,x7n="pako deflate (from Nodeca project)",dJ={deflateInit:c7n,deflateInit2:d7n,deflateReset:u7n,deflateResetKeep:h7n,deflateSetHeader:m7n,deflate:p7n,deflateEnd:f7n,deflateSetDictionary:g7n,deflateInfo:x7n};const y7n=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var v7n=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)y7n(n,r)&&(s[r]=n[r])}}return s},b7n=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;Ete[254]=Ete[254]=1;var _7n=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 w7n=(s,t)=>{if(t<65534&&s.subarray&&oZt)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 w7n(i,a)},N7n=(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+Ete[s[n]]>t?n:t},Tte={string2buf:_7n,buf2string:j7n,utf8border:N7n};function k7n(){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 lZt=k7n;const cZt=Object.prototype.toString,{Z_NO_FLUSH:S7n,Z_SYNC_FLUSH:C7n,Z_FULL_FLUSH:A7n,Z_FINISH:E7n,Z_OK:WEe,Z_STREAM_END:T7n,Z_DEFAULT_COMPRESSION:M7n,Z_DEFAULT_STRATEGY:P7n,Z_DEFLATED:L7n}=Kre;function int(s){this.options=fIe.assign({level:M7n,method:L7n,chunkSize:16384,windowBits:15,memLevel:8,strategy:P7n},s||{});let 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 lZt,this.strm.avail_out=0;let n=dJ.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(n!==WEe)throw new Error(zH[n]);if(t.header&&dJ.deflateSetHeader(this.strm,t.header),t.dictionary){let r;if(typeof t.dictionary=="string"?r=Tte.string2buf(t.dictionary):cZt.call(t.dictionary)==="[object ArrayBuffer]"?r=new Uint8Array(t.dictionary):r=t.dictionary,n=dJ.deflateSetDictionary(this.strm,r),n!==WEe)throw new Error(zH[n]);this._dict_set=!0}}int.prototype.push=function(s,t){const n=this.strm,r=this.options.chunkSize;let a,i;if(this.ended)return!1;for(t===~~t?i=t:i=t===!0?E7n:S7n,typeof s=="string"?n.input=Tte.string2buf(s):cZt.call(s)==="[object ArrayBuffer]"?n.input=new Uint8Array(s):n.input=s,n.next_in=0,n.avail_in=n.input.length;;){if(n.avail_out===0&&(n.output=new Uint8Array(r),n.next_out=0,n.avail_out=r),(i===C7n||i===A7n)&&n.avail_out<=6){this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;continue}if(a=dJ.deflate(n,i),a===T7n)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),a=dJ.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===WEe;if(n.avail_out===0){this.onData(n.output);continue}if(i>0&&n.next_out>0){this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;continue}if(n.avail_in===0)break}return!0};int.prototype.onData=function(s){this.chunks.push(s)};int.prototype.onEnd=function(s){s===WEe&&(this.result=fIe.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};const Jle=16209,I7n=16191;var R7n=function(t,n){let r,a,i,l,o,c,d,u,h,m,p,f,x,y,v,b,N,S,A,T,L,M,I,R;const z=t.state;r=t.next_in,I=t.input,a=r+(t.avail_in-5),i=t.next_out,R=t.output,l=i-(n-t.avail_out),o=i+(t.avail_out-257),c=z.dmax,d=z.wsize,u=z.whave,h=z.wnext,m=z.window,p=z.hold,f=z.bits,x=z.lencode,y=z.distcode,v=(1<>>24,p>>>=S,f-=S,S=N>>>16&255,S===0)R[i++]=N&65535;else if(S&16){A=N&65535,S&=15,S&&(f>>=S,f-=S),f<15&&(p+=I[r++]<>>24,p>>>=S,f-=S,S=N>>>16&255,S&16){if(T=N&65535,S&=15,fc){t.msg="invalid distance too far back",z.mode=Jle;break e}if(p>>>=S,f-=S,S=i-l,T>S){if(S=T-S,S>u&&z.sane){t.msg="invalid distance too far back",z.mode=Jle;break e}if(L=0,M=m,h===0){if(L+=d-S,S2;)R[i++]=M[L++],R[i++]=M[L++],R[i++]=M[L++],A-=3;A&&(R[i++]=M[L++],A>1&&(R[i++]=M[L++]))}else{L=i-T;do R[i++]=R[L++],R[i++]=R[L++],R[i++]=R[L++],A-=3;while(A>2);A&&(R[i++]=R[L++],A>1&&(R[i++]=R[L++]))}}else if(S&64){t.msg="invalid distance code",z.mode=Jle;break e}else{N=y[(N&65535)+(p&(1<>3,r-=A,f-=A<<3,p&=(1<{const c=o.bits;let d=0,u=0,h=0,m=0,p=0,f=0,x=0,y=0,v=0,b=0,N,S,A,T,L,M=null,I;const R=new Uint16Array(uB+1),z=new Uint16Array(uB+1);let $=null,H,V,K;for(d=0;d<=uB;d++)R[d]=0;for(u=0;u=1&&R[m]===0;m--);if(p>m&&(p=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===f2t||m!==1))return-1;for(z[1]=0,d=1;dm2t||s===g2t&&v>p2t)return 1;for(;;){H=d-x,l[u]+1=I?(V=$[l[u]-I],K=M[l[u]-I]):(V=96,K=0),N=1<>x)+S]=H<<24|V<<16|K|0;while(S!==0);for(N=1<>=1;if(N!==0?(b&=N-1,b+=N):b=0,u++,--R[d]===0){if(d===m)break;d=t[n+l[u]]}if(d>p&&(b&T)!==A){for(x===0&&(x=p),L+=h,f=d-x,y=1<m2t||s===g2t&&v>p2t)return 1;A=b&T,a[A]=p<<24|f<<16|L-i|0}}return b!==0&&(a[L+b]=d-x<<24|64<<16|0),o.bits=p,0};var uJ=B7n;const U7n=0,dZt=1,uZt=2,{Z_FINISH:x2t,Z_BLOCK:q7n,Z_TREES:ece,Z_OK:Y7,Z_STREAM_END:$7n,Z_NEED_DICT:V7n,Z_STREAM_ERROR:gN,Z_DATA_ERROR:hZt,Z_MEM_ERROR:mZt,Z_BUF_ERROR:H7n,Z_DEFLATED:y2t}=Kre,gIe=16180,v2t=16181,b2t=16182,_2t=16183,w2t=16184,j2t=16185,N2t=16186,k2t=16187,S2t=16188,C2t=16189,KEe=16190,aC=16191,g9e=16192,A2t=16193,x9e=16194,E2t=16195,T2t=16196,M2t=16197,P2t=16198,tce=16199,sce=16200,L2t=16201,I2t=16202,R2t=16203,D2t=16204,O2t=16205,y9e=16206,F2t=16207,z2t=16208,Cp=16209,pZt=16210,fZt=16211,G7n=852,W7n=592,K7n=15,Y7n=K7n,B2t=s=>(s>>>24&255)+(s>>>8&65280)+((s&65280)<<8)+((s&255)<<24);function Z7n(){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.modefZt?1:0},gZt=s=>{if(I9(s))return gN;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=gIe,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(G7n),t.distcode=t.distdyn=new Int32Array(W7n),t.sane=1,t.back=-1,Y7},xZt=s=>{if(I9(s))return gN;const t=s.state;return t.wsize=0,t.whave=0,t.wnext=0,gZt(s)},yZt=(s,t)=>{let n;if(I9(s))return gN;const r=s.state;return t<0?(n=0,t=-t):(n=(t>>4)+5,t<48&&(t&=15)),t&&(t<8||t>15)?gN:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,xZt(s))},vZt=(s,t)=>{if(!s)return gN;const n=new Z7n;s.state=n,n.strm=s,n.window=null,n.mode=gIe;const r=yZt(s,t);return r!==Y7&&(s.state=null),r},X7n=s=>vZt(s,Y7n);let U2t=!0,v9e,b9e;const Q7n=s=>{if(U2t){v9e=new Int32Array(512),b9e=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(uJ(dZt,s.lens,0,288,v9e,0,s.work,{bits:9}),t=0;t<32;)s.lens[t++]=5;uJ(uZt,s.lens,0,32,b9e,0,s.work,{bits:5}),U2t=!1}s.lencode=v9e,s.lenbits=9,s.distcode=b9e,s.distbits=5},bZt=(s,t,n,r)=>{let a;const i=s.state;return i.window===null&&(i.wsize=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,p,f,x,y=0,v,b,N,S,A,T,L,M;const I=new Uint8Array(4);let R,z;const $=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 gN;n=s.state,n.mode===aC&&(n.mode=g9e),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,M=Y7;e:for(;;)switch(n.mode){case gIe:if(n.wrap===0){n.mode=g9e;break}for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=K0(n.check,I,2,0),d=0,u=0,n.mode=v2t;break}if(n.head&&(n.head.done=!1),!(n.wrap&1)||(((d&255)<<8)+(d>>8))%31){s.msg="incorrect header check",n.mode=Cp;break}if((d&15)!==y2t){s.msg="unknown compression method",n.mode=Cp;break}if(d>>>=4,u-=4,L=(d&15)+8,n.wbits===0&&(n.wbits=L),L>15||L>n.wbits){s.msg="invalid window size",n.mode=Cp;break}n.dmax=1<>8&1),n.flags&512&&n.wrap&4&&(I[0]=d&255,I[1]=d>>>8&255,n.check=K0(n.check,I,2,0)),d=0,u=0,n.mode=b2t;case b2t:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>8&255,I[2]=d>>>16&255,I[3]=d>>>24&255,n.check=K0(n.check,I,4,0)),d=0,u=0,n.mode=_2t;case _2t:for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>8),n.flags&512&&n.wrap&4&&(I[0]=d&255,I[1]=d>>>8&255,n.check=K0(n.check,I,2,0)),d=0,u=0,n.mode=w2t;case w2t:if(n.flags&1024){for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=K0(n.check,I,2,0)),d=0,u=0}else n.head&&(n.head.extra=null);n.mode=j2t;case j2t:if(n.flags&1024&&(p=n.length,p>o&&(p=o),p&&(n.head&&(L=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+p),L)),n.flags&512&&n.wrap&4&&(n.check=K0(n.check,r,p,i)),o-=p,i+=p,n.length-=p),n.length))break e;n.length=0,n.mode=N2t;case N2t:if(n.flags&2048){if(o===0)break e;p=0;do L=r[i+p++],n.head&&L&&n.length<65536&&(n.head.name+=String.fromCharCode(L));while(L&&p>9&1,n.head.done=!0),s.adler=n.check=0,n.mode=aC;break;case C2t:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>=u&7,u-=u&7,n.mode=y9e;break}for(;u<3;){if(o===0)break e;o--,d+=r[i++]<>>=1,u-=1,d&3){case 0:n.mode=A2t;break;case 1:if(Q7n(n),n.mode=tce,t===ece){d>>>=2,u-=2;break e}break;case 2:n.mode=T2t;break;case 3:s.msg="invalid block type",n.mode=Cp}d>>>=2,u-=2;break;case A2t: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=Cp;break}if(n.length=d&65535,d=0,u=0,n.mode=x9e,t===ece)break e;case x9e:n.mode=E2t;case E2t:if(p=n.length,p){if(p>o&&(p=o),p>c&&(p=c),p===0)break e;a.set(r.subarray(i,i+p),l),o-=p,i+=p,c-=p,l+=p,n.length-=p;break}n.mode=aC;break;case T2t: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=Cp;break}n.have=0,n.mode=M2t;case M2t:for(;n.have>>=3,u-=3}for(;n.have<19;)n.lens[$[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,R={bits:n.lenbits},M=uJ(U7n,n.lens,0,19,n.lencode,0,n.work,R),n.lenbits=R.bits,M){s.msg="invalid code lengths set",n.mode=Cp;break}n.have=0,n.mode=P2t;case P2t:for(;n.have>>24,b=y>>>16&255,N=y&65535,!(v<=u);){if(o===0)break e;o--,d+=r[i++]<>>=v,u-=v,n.lens[n.have++]=N;else{if(N===16){for(z=v+2;u>>=v,u-=v,n.have===0){s.msg="invalid bit length repeat",n.mode=Cp;break}L=n.lens[n.have-1],p=3+(d&3),d>>>=2,u-=2}else if(N===17){for(z=v+3;u>>=v,u-=v,L=0,p=3+(d&7),d>>>=3,u-=3}else{for(z=v+7;u>>=v,u-=v,L=0,p=11+(d&127),d>>>=7,u-=7}if(n.have+p>n.nlen+n.ndist){s.msg="invalid bit length repeat",n.mode=Cp;break}for(;p--;)n.lens[n.have++]=L}}if(n.mode===Cp)break;if(n.lens[256]===0){s.msg="invalid code -- missing end-of-block",n.mode=Cp;break}if(n.lenbits=9,R={bits:n.lenbits},M=uJ(dZt,n.lens,0,n.nlen,n.lencode,0,n.work,R),n.lenbits=R.bits,M){s.msg="invalid literal/lengths set",n.mode=Cp;break}if(n.distbits=6,n.distcode=n.distdyn,R={bits:n.distbits},M=uJ(uZt,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,R),n.distbits=R.bits,M){s.msg="invalid distances set",n.mode=Cp;break}if(n.mode=tce,t===ece)break e;case tce:n.mode=sce;case sce: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,R7n(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===aC&&(n.back=-1);break}for(n.back=0;y=n.lencode[d&(1<>>24,b=y>>>16&255,N=y&65535,!(v<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],v=y>>>24,b=y>>>16&255,N=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=N,b===0){n.mode=O2t;break}if(b&32){n.back=-1,n.mode=aC;break}if(b&64){s.msg="invalid literal/length code",n.mode=Cp;break}n.extra=b&15,n.mode=L2t;case L2t:if(n.extra){for(z=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=I2t;case I2t:for(;y=n.distcode[d&(1<>>24,b=y>>>16&255,N=y&65535,!(v<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],v=y>>>24,b=y>>>16&255,N=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=Cp;break}n.offset=N,n.extra=b&15,n.mode=R2t;case R2t:if(n.extra){for(z=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=Cp;break}n.mode=D2t;case D2t:if(c===0)break e;if(p=m-c,n.offset>p){if(p=n.offset-p,p>n.whave&&n.sane){s.msg="invalid distance too far back",n.mode=Cp;break}p>n.wnext?(p-=n.wnext,f=n.wsize-p):f=n.wnext-p,p>n.length&&(p=n.length),x=n.window}else x=a,f=l-n.offset,p=n.length;p>c&&(p=c),c-=p,n.length-=p;do a[l++]=x[f++];while(--p);n.length===0&&(n.mode=sce);break;case O2t:if(c===0)break e;a[l++]=n.length,c--,n.mode=sce;break;case y9e:if(n.wrap){for(;u<32;){if(o===0)break e;o--,d|=r[i++]<{if(I9(s))return gN;let t=s.state;return t.window&&(t.window=null),s.state=null,Y7},t9n=(s,t)=>{if(I9(s))return gN;const n=s.state;return n.wrap&2?(n.head=t,t.done=!1,Y7):gN},s9n=(s,t)=>{const n=t.length;let r,a,i;return I9(s)||(r=s.state,r.wrap!==0&&r.mode!==KEe)?gN:r.mode===KEe&&(a=1,a=Ate(a,t,n,0),a!==r.check)?hZt:(i=bZt(s,t,n,n),i?(r.mode=pZt,mZt):(r.havedict=1,Y7))};var n9n=xZt,r9n=yZt,a9n=gZt,i9n=X7n,o9n=vZt,l9n=J7n,c9n=e9n,d9n=t9n,u9n=s9n,h9n="pako inflate (from Nodeca project)",RC={inflateReset:n9n,inflateReset2:r9n,inflateResetKeep:a9n,inflateInit:i9n,inflateInit2:o9n,inflate:l9n,inflateEnd:c9n,inflateGetHeader:d9n,inflateSetDictionary:u9n,inflateInfo:h9n};function m9n(){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 p9n=m9n;const _Zt=Object.prototype.toString,{Z_NO_FLUSH:f9n,Z_FINISH:g9n,Z_OK:Mte,Z_STREAM_END:_9e,Z_NEED_DICT:w9e,Z_STREAM_ERROR:x9n,Z_DATA_ERROR:q2t,Z_MEM_ERROR:y9n}=Kre;function Zre(s){this.options=fIe.assign({chunkSize:1024*64,windowBits:15,to:""},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 lZt,this.strm.avail_out=0;let n=RC.inflateInit2(this.strm,t.windowBits);if(n!==Mte)throw new Error(zH[n]);if(this.header=new p9n,RC.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=Tte.string2buf(t.dictionary):_Zt.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=RC.inflateSetDictionary(this.strm,t.dictionary),n!==Mte)))throw new Error(zH[n])}Zre.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?g9n:f9n,_Zt.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=RC.inflate(n,l),i===w9e&&a&&(i=RC.inflateSetDictionary(n,a),i===Mte?i=RC.inflate(n,l):i===q2t&&(i=w9e));n.avail_in>0&&i===_9e&&n.state.wrap>0&&s[n.next_in]!==0;)RC.inflateReset(n),i=RC.inflate(n,l);switch(i){case x9n:case q2t:case w9e:case y9n:return this.onEnd(i),this.ended=!0,!1}if(o=n.avail_out,n.next_out&&(n.avail_out===0||i===_9e))if(this.options.to==="string"){let c=Tte.utf8border(n.output,n.next_out),d=n.next_out-c,u=Tte.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));if(!(i===Mte&&o===0)){if(i===_9e)return i=RC.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,!0;if(n.avail_in===0)break}}return!0};Zre.prototype.onData=function(s){this.chunks.push(s)};Zre.prototype.onEnd=function(s){s===Mte&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=fIe.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};function ont(s,t){const n=new Zre(t);if(n.push(s),n.err)throw n.msg||zH[n.err];return n.result}function v9n(s,t){return t=t||{},t.raw=!0,ont(s,t)}var b9n=Zre,_9n=ont,w9n=v9n,j9n=ont,N9n=Kre,k9n={Inflate:b9n,inflate:_9n,inflateRaw:w9n,ungzip:j9n,constants:N9n};const{Inflate:S9n,inflate:C9n,inflateRaw:pxr,ungzip:fxr}=k9n;var $2t=S9n,A9n=C9n;const wZt=[];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;wZt[s]=t}const V2t=4294967295;function E9n(s,t,n){let r=s;for(let a=0;a>>8;return r}function T9n(s,t){return(E9n(V2t,s,t)^V2t)>>>0}function H2t(s,t,n){const r=s.readUint32(),a=T9n(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 jZt(s,t,n){for(let r=0;r>1)&255}else{for(;i>1)&255;for(;i>1)&255}}function CZt(s,t,n,r,a){let i=0;if(n.length===0){for(;i=n||T>=r))for(let L=0;L>8&255}const F9n=new Uint16Array([255]),z9n=new Uint8Array(F9n.buffer),B9n=z9n[0]===255,U9n=new Uint8Array(0);function G2t(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=U9n,u=0,h,m;for(let p=0;p>8&255}const n4e=Uint8Array.of(137,80,78,71,13,10,26,10);function W2t(s){if(!$9n(s.readBytes(n4e.length)))throw new Error("wrong PNG signature")}function $9n(s){if(s.length79)throw new Error("keyword length must be between 1 and 79")}const W9n=/^[\u0000-\u00FF]*$/;function K9n(s){if(!W9n.test(s))throw new Error("invalid latin1 text")}function Y9n(s,t,n){const r=EZt(t);s[r]=Z9n(t,n-r.length-1)}function EZt(s){for(s.mark();s.readByte()!==H9n;);const t=s.offset;s.reset();const n=AZt.decode(s.readBytes(t-s.offset-1));return s.skip(1),G9n(n),n}function Z9n(s,t){return AZt.decode(s.readBytes(t))}const cw={UNKNOWN:-1,GREYSCALE:0,TRUECOLOUR:2,INDEXED_COLOUR:3,GREYSCALE_ALPHA:4,TRUECOLOUR_ALPHA:6},j9e={UNKNOWN:-1,DEFLATE:0},K2t={UNKNOWN:-1,ADAPTIVE:0},N9e={UNKNOWN:-1,NO_INTERLACE:0,ADAM7:1},nce={NONE:0,BACKGROUND:1,PREVIOUS:2},k9e={SOURCE:0,OVER:1};class X9n extends ent{constructor(n,r={}){super(n);Lr(this,"_checkCrc");Lr(this,"_inflator");Lr(this,"_png");Lr(this,"_apng");Lr(this,"_end");Lr(this,"_hasPalette");Lr(this,"_palette");Lr(this,"_hasTransparency");Lr(this,"_transparency");Lr(this,"_compressionMethod");Lr(this,"_filterMethod");Lr(this,"_interlaceMethod");Lr(this,"_colorType");Lr(this,"_isAnimated");Lr(this,"_numberOfFrames");Lr(this,"_numberOfPlays");Lr(this,"_frames");Lr(this,"_writingDataChunks");const{checkCrc:a=!1}=r;this._checkCrc=a,this._inflator=new $2t,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=j9e.UNKNOWN,this._filterMethod=K2t.UNKNOWN,this._interlaceMethod=N9e.UNKNOWN,this._colorType=cw.UNKNOWN,this._isAnimated=!1,this._numberOfFrames=1,this._numberOfPlays=0,this._frames=[],this._writingDataChunks=!1,this.setBigEndian()}decode(){for(W2t(this);!this._end;){const n=this.readUint32(),r=this.readChars(4);this.decodeChunk(n,r)}return this.decodeImage(),this._png}decodeApng(){for(W2t(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 V9n:Y9n(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?H2t(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?H2t(this,n+4,r):this.skip(4)}decodeIHDR(){const n=this._png;n.width=this.readUint32(),n.height=this.readUint32(),n.depth=Q9n(this.readUint8());const r=this.readUint8();this._colorType=r;let a;switch(r){case cw.GREYSCALE:a=1;break;case cw.TRUECOLOUR:a=3;break;case cw.INDEXED_COLOUR:a=1;break;case cw.GREYSCALE_ALPHA:a=2;break;case cw.TRUECOLOUR_ALPHA:a=4;break;case cw.UNKNOWN:default:throw new Error(`Unknown color type: ${r}`)}if(this._png.channels=a,this._compressionMethod=this.readUint8(),this._compressionMethod!==j9e.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 k9e.SOURCE:for(let l=0;l=200&&t.status<=299}function rce(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 wD=Yl.saveAs||((typeof window>"u"?"undefined":kh(window))!=="object"||window!==Yl?function(){}:typeof HTMLAnchorElement<"u"&&"download"in HTMLAnchorElement.prototype?function(s,t,n){var r=Yl.URL||Yl.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?Z2t(a.href)?C9e(s,t,n):rce(a,a.target="_blank"):rce(a)):(a.href=r.createObjectURL(s),setTimeout(function(){r.revokeObjectURL(a.href)},4e4),setTimeout(function(){rce(a)},0))}:"msSaveOrOpenBlob"in navigator?function(s,t,n){if(t=t||s.name||"download",typeof s=="string")if(Z2t(s))C9e(s,t,n);else{var r=document.createElement("a");r.href=s,r.target="_blank",setTimeout(function(){rce(r)})}else navigator.msSaveOrOpenBlob(function(a,i){return i===void 0?i={autoBom:!1}:kh(i)!=="object"&&(lm.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 C9e(s,t,n);var a=s.type==="application/octet-stream",i=/constructor/i.test(Yl.HTMLElement)||Yl.safari,l=/CriOS\/[\d]+/.test(navigator.userAgent);if((l||a&&i)&&(typeof FileReader>"u"?"undefined":kh(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=Yl.URL||Yl.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 TZt(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 r4e=Yl.atob.bind(Yl),X2t=Yl.btoa.bind(Yl);/** * @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 A9e(s,t){var n=s[0],r=s[1],a=s[2],i=s[3];n=Fv(n,r,a,i,t[0],7,-680876936),i=Fv(i,n,r,a,t[1],12,-389564586),a=Fv(a,i,n,r,t[2],17,606105819),r=Fv(r,a,i,n,t[3],22,-1044525330),n=Fv(n,r,a,i,t[4],7,-176418897),i=Fv(i,n,r,a,t[5],12,1200080426),a=Fv(a,i,n,r,t[6],17,-1473231341),r=Fv(r,a,i,n,t[7],22,-45705983),n=Fv(n,r,a,i,t[8],7,1770035416),i=Fv(i,n,r,a,t[9],12,-1958414417),a=Fv(a,i,n,r,t[10],17,-42063),r=Fv(r,a,i,n,t[11],22,-1990404162),n=Fv(n,r,a,i,t[12],7,1804603682),i=Fv(i,n,r,a,t[13],12,-40341101),a=Fv(a,i,n,r,t[14],17,-1502002290),n=zv(n,r=Fv(r,a,i,n,t[15],22,1236535329),a,i,t[1],5,-165796510),i=zv(i,n,r,a,t[6],9,-1069501632),a=zv(a,i,n,r,t[11],14,643717713),r=zv(r,a,i,n,t[0],20,-373897302),n=zv(n,r,a,i,t[5],5,-701558691),i=zv(i,n,r,a,t[10],9,38016083),a=zv(a,i,n,r,t[15],14,-660478335),r=zv(r,a,i,n,t[4],20,-405537848),n=zv(n,r,a,i,t[9],5,568446438),i=zv(i,n,r,a,t[14],9,-1019803690),a=zv(a,i,n,r,t[3],14,-187363961),r=zv(r,a,i,n,t[8],20,1163531501),n=zv(n,r,a,i,t[13],5,-1444681467),i=zv(i,n,r,a,t[2],9,-51403784),a=zv(a,i,n,r,t[7],14,1735328473),n=Bv(n,r=zv(r,a,i,n,t[12],20,-1926607734),a,i,t[5],4,-378558),i=Bv(i,n,r,a,t[8],11,-2022574463),a=Bv(a,i,n,r,t[11],16,1839030562),r=Bv(r,a,i,n,t[14],23,-35309556),n=Bv(n,r,a,i,t[1],4,-1530992060),i=Bv(i,n,r,a,t[4],11,1272893353),a=Bv(a,i,n,r,t[7],16,-155497632),r=Bv(r,a,i,n,t[10],23,-1094730640),n=Bv(n,r,a,i,t[13],4,681279174),i=Bv(i,n,r,a,t[0],11,-358537222),a=Bv(a,i,n,r,t[3],16,-722521979),r=Bv(r,a,i,n,t[6],23,76029189),n=Bv(n,r,a,i,t[9],4,-640364487),i=Bv(i,n,r,a,t[12],11,-421815835),a=Bv(a,i,n,r,t[15],16,530742520),n=Uv(n,r=Bv(r,a,i,n,t[2],23,-995338651),a,i,t[0],6,-198630844),i=Uv(i,n,r,a,t[7],10,1126891415),a=Uv(a,i,n,r,t[14],15,-1416354905),r=Uv(r,a,i,n,t[5],21,-57434055),n=Uv(n,r,a,i,t[12],6,1700485571),i=Uv(i,n,r,a,t[3],10,-1894986606),a=Uv(a,i,n,r,t[10],15,-1051523),r=Uv(r,a,i,n,t[1],21,-2054922799),n=Uv(n,r,a,i,t[8],6,1873313359),i=Uv(i,n,r,a,t[15],10,-30611744),a=Uv(a,i,n,r,t[6],15,-1560198380),r=Uv(r,a,i,n,t[13],21,1309151649),n=Uv(n,r,a,i,t[4],6,-145523070),i=Uv(i,n,r,a,t[11],10,-1120210379),a=Uv(a,i,n,r,t[2],15,718787259),r=Uv(r,a,i,n,t[9],21,-343485551),s[0]=oM(n,s[0]),s[1]=oM(r,s[1]),s[2]=oM(a,s[2]),s[3]=oM(i,s[3])}function xIe(s,t,n,r,a,i){return t=oM(oM(t,s),oM(r,i)),oM(t<>>32-a,n)}function Fv(s,t,n,r,a,i,l){return xIe(t&n|~t&r,s,t,a,i,l)}function zv(s,t,n,r,a,i,l){return xIe(t&r|n&~r,s,t,a,i,l)}function Bv(s,t,n,r,a,i,l){return xIe(t^n^r,s,t,a,i,l)}function Uv(s,t,n,r,a,i,l){return xIe(n^(t|~r),s,t,a,i,l)}function MZt(s){var t,n=s.length,r=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=s.length;t+=64)A9e(r,ezn(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(A9e(r,a),t=0;t<16;t++)a[t]=0;return a[14]=8*n,A9e(r,a),r}function ezn(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 Q2t="0123456789abcdef".split("");function tzn(s){for(var t="",n=0;n<4;n++)t+=Q2t[s>>8*n+4&15]+Q2t[s>>8*n&15];return t}function szn(s){return String.fromCharCode(255&s,(65280&s)>>8,(16711680&s)>>16,(4278190080&s)>>24)}function LGe(s){return MZt(s).map(szn).join("")}var nzn=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 IGe(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,p=0,f="";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=LGe(i+this.O+this.lsbFirstWord(this.P)+this.hexToBytes(r)).substr(0,5),this.U=IGe(this.encryptionKey,this.padding)}function VB(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 eNt(s){if(kh(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){Yl.console&&lm.error("jsPDF PubSub Error",o.message,o)}l[1]&&a.push(i)}a.length&&a.forEach(this.unsubscribe)}},this.getTopics=function(){return t}}function YEe(s){if(!(this instanceof YEe))return new YEe(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 PZt(s,t){this.gState=s,this.matrix=t,this.id="",this.objectNumber=-1}function ID(s,t,n,r,a){if(!(this instanceof ID))return new ID(s,t,n,r,a);this.type=s==="axial"?2:3,this.coords=t,this.colors=n,PZt.call(this,r,a)}function PU(s,t,n,r,a){if(!(this instanceof PU))return new PU(s,t,n,r,a);this.boundingBox=s,this.xStep=t,this.yStep=n,this.stream="",this.cloneIndex=0,PZt.call(this,r,a)}function No(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;kh(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={},p={internal:{},__private__:{}};p.__private__.PubSub=eNt;var f="1.3",x=p.__private__.getPdfVersion=function(){return f};p.__private__.setPdfVersion=function(at){f=at};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]};p.__private__.getPageFormats=function(){return y};var v=p.__private__.getPageFormat=function(at){return y[at]};a=a||"a4";var b="compat",N="advanced",S=b;function A(){this.saveGraphicsState(),Fe(new Zn(Wt,0,0,-Wt,0,qm()*Wt).toString()+" cm"),this.setFontSize(this.getFontSize()/Wt),d="n",S=N}function T(){this.restoreGraphicsState(),d="S",S=b}var L=p.__private__.combineFontStyleAndFontWeight=function(at,Yt){if(at=="bold"&&Yt=="normal"||at=="bold"&&Yt==400||at=="normal"&&Yt=="italic"||at=="bold"&&Yt=="italic")throw new Error("Invalid Combination of fontweight and fontstyle");return Yt&&(at=Yt==400||Yt==="normal"?at==="italic"?"italic":"normal":Yt!=700&&Yt!=="bold"||at!=="normal"?(Yt==700?"bold":Yt)+""+at:"bold"),at};p.advancedAPI=function(at){var Yt=S===b;return Yt&&A.call(this),typeof at!="function"||(at(this),Yt&&T.call(this)),this},p.compatAPI=function(at){var Yt=S===N;return Yt&&T.call(this),typeof at!="function"||(at(this),Yt&&A.call(this)),this},p.isAdvancedAPI=function(){return S===N};var M,I=function(at){if(S!==N)throw new Error(at+" is only available in 'advanced' API mode. You need to call advancedAPI() first.")},R=p.roundToPrecision=p.__private__.roundToPrecision=function(at,Yt){var Bs=t||Yt;if(isNaN(at)||isNaN(Bs))throw new Error("Invalid argument passed to jsPDF.roundToPrecision");return at.toFixed(Bs).replace(/0+$/,"")};M=p.hpf=p.__private__.hpf=typeof c=="number"?function(at){if(isNaN(at))throw new Error("Invalid argument passed to jsPDF.hpf");return R(at,c)}:c==="smart"?function(at){if(isNaN(at))throw new Error("Invalid argument passed to jsPDF.hpf");return R(at,at>-1&&at<1?16:5)}:function(at){if(isNaN(at))throw new Error("Invalid argument passed to jsPDF.hpf");return R(at,16)};var z=p.f2=p.__private__.f2=function(at){if(isNaN(at))throw new Error("Invalid argument passed to jsPDF.f2");return R(at,2)},$=p.__private__.f3=function(at){if(isNaN(at))throw new Error("Invalid argument passed to jsPDF.f3");return R(at,3)},H=p.scale=p.__private__.scale=function(at){if(isNaN(at))throw new Error("Invalid argument passed to jsPDF.scale");return S===b?at*Wt:S===N?at:void 0},V=function(at){return H(function(Yt){return S===b?qm()-Yt:S===N?Yt:void 0}(at))};p.__private__.setPrecision=p.setPrecision=function(at){typeof parseInt(at,10)=="number"&&(t=parseInt(at,10))};var K,Z="00000000000000000000000000000000",Q=p.__private__.getFileId=function(){return Z},le=p.__private__.setFileId=function(at){return Z=at!==void 0&&/^[a-fA-F0-9]{32}$/.test(at)?at.toUpperCase():Z.split("").map(function(){return"ABCDEF0123456789".charAt(Math.floor(16*Math.random()))}).join(""),u!==null&&(ds=new $B(u.userPermissions,u.userPassword,u.ownerPassword,Z)),Z};p.setFileId=function(at){return le(at),this},p.getFileId=function(){return Q()};var ue=p.__private__.convertDateToPDFDate=function(at){var Yt=at.getTimezoneOffset(),Bs=Yt<0?"+":"-",Zs=Math.floor(Math.abs(Yt/60)),Sn=Math.abs(Yt%60),Dr=[Bs,je(Zs),"'",je(Sn),"'"].join("");return["D:",at.getFullYear(),je(at.getMonth()+1),je(at.getDate()),je(at.getHours()),je(at.getMinutes()),je(at.getSeconds()),Dr].join("")},se=p.__private__.convertPDFDateToDate=function(at){var Yt=parseInt(at.substr(2,4),10),Bs=parseInt(at.substr(6,2),10)-1,Zs=parseInt(at.substr(8,2),10),Sn=parseInt(at.substr(10,2),10),Dr=parseInt(at.substr(12,2),10),kt=parseInt(at.substr(14,2),10);return new Date(Yt,Bs,Zs,Sn,Dr,kt,0)},ne=p.__private__.setCreationDate=function(at){var Yt;if(at===void 0&&(at=new Date),at instanceof Date)Yt=ue(at);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(at))throw new Error("Invalid argument passed to jsPDF.setCreationDate");Yt=at}return K=Yt},ie=p.__private__.getCreationDate=function(at){var Yt=K;return at==="jsDate"&&(Yt=se(K)),Yt};p.setCreationDate=function(at){return ne(at),this},p.getCreationDate=function(at){return ie(at)};var ce,je=p.__private__.padd2=function(at){return("0"+parseInt(at)).slice(-2)},be=p.__private__.padd2Hex=function(at){return("00"+(at=at.toString())).substr(at.length)},he=0,ge=[],ke=[],Te=0,Me=[],Oe=[],Se=!1,Qe=ke;p.__private__.setCustomOutputDestination=function(at){Se=!0,Qe=at};var Ae=function(at){Se||(Qe=at)};p.__private__.resetCustomOutputDestination=function(){Se=!1,Qe=ke};var Fe=p.__private__.out=function(at){return at=at.toString(),Te+=at.length+1,Qe.push(at),Qe},Ne=p.__private__.write=function(at){return Fe(arguments.length===1?at.toString():Array.prototype.join.call(arguments," "))},$e=p.__private__.getArrayBuffer=function(at){for(var Yt=at.length,Bs=new ArrayBuffer(Yt),Zs=new Uint8Array(Bs);Yt--;)Zs[Yt]=at.charCodeAt(Yt);return Bs},Ve=[["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]];p.__private__.getStandardFonts=function(){return Ve};var qe=s.fontSize||16;p.__private__.setFontSize=p.setFontSize=function(at){return qe=S===N?at/Wt:at,this};var Ze,Ue=p.__private__.getFontSize=p.getFontSize=function(){return S===b?qe:qe*Wt},Ye=s.R2L||!1;p.__private__.setR2L=p.setR2L=function(at){return Ye=at,this},p.__private__.getR2L=p.getR2L=function(){return Ye};var Ge,He=p.__private__.setZoomMode=function(at){if(/^(?:\d+\.\d*|\d*\.\d+|\d+)%$/.test(at))Ze=at;else if(isNaN(at)){if([void 0,null,"fullwidth","fullheight","fullpage","original"].indexOf(at)===-1)throw new Error('zoom must be Integer (e.g. 2), a percentage Value (e.g. 300%) or fullwidth, fullheight, fullpage, original. "'+at+'" is not recognized.');Ze=at}else Ze=parseInt(at,10)};p.__private__.getZoomMode=function(){return Ze};var tt,pt=p.__private__.setPageMode=function(at){if([void 0,null,"UseNone","UseOutlines","UseThumbs","FullScreen"].indexOf(at)==-1)throw new Error('Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "'+at+'" is not recognized.');Ge=at};p.__private__.getPageMode=function(){return Ge};var ft=p.__private__.setLayoutMode=function(at){if([void 0,null,"continuous","single","twoleft","tworight","two"].indexOf(at)==-1)throw new Error('Layout mode must be one of continuous, single, twoleft, tworight. "'+at+'" is not recognized.');tt=at};p.__private__.getLayoutMode=function(){return tt},p.__private__.setDisplayMode=p.setDisplayMode=function(at,Yt,Bs){return He(at),ft(Yt),pt(Bs),this};var qt={title:"",subject:"",author:"",keywords:"",creator:""};p.__private__.getDocumentProperty=function(at){if(Object.keys(qt).indexOf(at)===-1)throw new Error("Invalid argument passed to jsPDF.getDocumentProperty");return qt[at]},p.__private__.getDocumentProperties=function(){return qt},p.__private__.setDocumentProperties=p.setProperties=p.setDocumentProperties=function(at){for(var Yt in qt)qt.hasOwnProperty(Yt)&&at[Yt]&&(qt[Yt]=at[Yt]);return this},p.__private__.setDocumentProperty=function(at,Yt){if(Object.keys(qt).indexOf(at)===-1)throw new Error("Invalid arguments passed to jsPDF.setDocumentProperty");return qt[at]=Yt};var Ut,Wt,us,zt,bt,As={},vt={},Ws=[],on={},Ms={},dn={},rn={},br=null,Gn=0,On=[],Rr=new eNt(p),cr=s.hotfixes||[],Hs={},_r={},nn=[],Zn=function at(Yt,Bs,Zs,Sn,Dr,kt){if(!(this instanceof at))return new at(Yt,Bs,Zs,Sn,Dr,kt);isNaN(Yt)&&(Yt=1),isNaN(Bs)&&(Bs=0),isNaN(Zs)&&(Zs=0),isNaN(Sn)&&(Sn=1),isNaN(Dr)&&(Dr=0),isNaN(kt)&&(kt=0),this._matrix=[Yt,Bs,Zs,Sn,Dr,kt]};Object.defineProperty(Zn.prototype,"sx",{get:function(){return this._matrix[0]},set:function(at){this._matrix[0]=at}}),Object.defineProperty(Zn.prototype,"shy",{get:function(){return this._matrix[1]},set:function(at){this._matrix[1]=at}}),Object.defineProperty(Zn.prototype,"shx",{get:function(){return this._matrix[2]},set:function(at){this._matrix[2]=at}}),Object.defineProperty(Zn.prototype,"sy",{get:function(){return this._matrix[3]},set:function(at){this._matrix[3]=at}}),Object.defineProperty(Zn.prototype,"tx",{get:function(){return this._matrix[4]},set:function(at){this._matrix[4]=at}}),Object.defineProperty(Zn.prototype,"ty",{get:function(){return this._matrix[5]},set:function(at){this._matrix[5]=at}}),Object.defineProperty(Zn.prototype,"a",{get:function(){return this._matrix[0]},set:function(at){this._matrix[0]=at}}),Object.defineProperty(Zn.prototype,"b",{get:function(){return this._matrix[1]},set:function(at){this._matrix[1]=at}}),Object.defineProperty(Zn.prototype,"c",{get:function(){return this._matrix[2]},set:function(at){this._matrix[2]=at}}),Object.defineProperty(Zn.prototype,"d",{get:function(){return this._matrix[3]},set:function(at){this._matrix[3]=at}}),Object.defineProperty(Zn.prototype,"e",{get:function(){return this._matrix[4]},set:function(at){this._matrix[4]=at}}),Object.defineProperty(Zn.prototype,"f",{get:function(){return this._matrix[5]},set:function(at){this._matrix[5]=at}}),Object.defineProperty(Zn.prototype,"rotation",{get:function(){return Math.atan2(this.shx,this.sx)}}),Object.defineProperty(Zn.prototype,"scaleX",{get:function(){return this.decompose().scale.sx}}),Object.defineProperty(Zn.prototype,"scaleY",{get:function(){return this.decompose().scale.sy}}),Object.defineProperty(Zn.prototype,"isIdentity",{get:function(){return this.sx===1&&this.shy===0&&this.shx===0&&this.sy===1&&this.tx===0&&this.ty===0}}),Zn.prototype.join=function(at){return[this.sx,this.shy,this.shx,this.sy,this.tx,this.ty].map(M).join(at)},Zn.prototype.multiply=function(at){var Yt=at.sx*this.sx+at.shy*this.shx,Bs=at.sx*this.shy+at.shy*this.sy,Zs=at.shx*this.sx+at.sy*this.shx,Sn=at.shx*this.shy+at.sy*this.sy,Dr=at.tx*this.sx+at.ty*this.shx+this.tx,kt=at.tx*this.shy+at.ty*this.sy+this.ty;return new Zn(Yt,Bs,Zs,Sn,Dr,kt)},Zn.prototype.decompose=function(){var at=this.sx,Yt=this.shy,Bs=this.shx,Zs=this.sy,Sn=this.tx,Dr=this.ty,kt=Math.sqrt(at*at+Yt*Yt),Es=(at/=kt)*Bs+(Yt/=kt)*Zs;Bs-=at*Es,Zs-=Yt*Es;var bn=Math.sqrt(Bs*Bs+Zs*Zs);return Es/=bn,at*(Zs/=bn)>16&255,Zs=bn>>8&255,Sn=255&bn}if(Zs===void 0||Dr===void 0&&Bs===Zs&&Zs===Sn)Yt=typeof Bs=="string"?Bs+" "+kt[0]:at.precision===2?z(Bs/255)+" "+kt[0]:$(Bs/255)+" "+kt[0];else if(Dr===void 0||kh(Dr)==="object"){if(Dr&&!isNaN(Dr.a)&&Dr.a===0)return["1.","1.","1.",kt[1]].join(" ");Yt=typeof Bs=="string"?[Bs,Zs,Sn,kt[1]].join(" "):at.precision===2?[z(Bs/255),z(Zs/255),z(Sn/255),kt[1]].join(" "):[$(Bs/255),$(Zs/255),$(Sn/255),kt[1]].join(" ")}else Yt=typeof Bs=="string"?[Bs,Zs,Sn,Dr,kt[2]].join(" "):at.precision===2?[z(Bs),z(Zs),z(Sn),z(Dr),kt[2]].join(" "):[$(Bs),$(Zs),$(Sn),$(Dr),kt[2]].join(" ");return Yt},Pt=p.__private__.getFilters=function(){return l},ts=p.__private__.putStream=function(at){var Yt=(at=at||{}).data||"",Bs=at.filters||Pt(),Zs=at.alreadyAppliedFilters||[],Sn=at.addLength1||!1,Dr=Yt.length,kt=at.objectId,Es=function(mi){return mi};if(u!==null&&kt===void 0)throw new Error("ObjectId must be passed to putStream for file encryption");u!==null&&(Es=ds.encryptor(kt,0));var bn={};Bs===!0&&(Bs=["FlateEncode"]);var Br=at.additionalKeyValues||[],Or=(bn=No.API.processDataByFilters!==void 0?No.API.processDataByFilters(Yt,Bs):{data:Yt,reverseChain:[]}).reverseChain+(Array.isArray(Zs)?Zs.join(" "):Zs.toString());if(bn.data.length!==0&&(Br.push({key:"Length",value:bn.data.length}),Sn===!0&&Br.push({key:"Length1",value:Dr})),Or.length!=0)if(Or.split("/").length-1==1)Br.push({key:"Filter",value:Or});else{Br.push({key:"Filter",value:"["+Or+"]"});for(var Ma=0;Ma>"),bn.data.length!==0&&(Fe("stream"),Fe(Es(bn.data)),Fe("endstream"))},ls=p.__private__.putPage=function(at){var Yt=at.number,Bs=at.data,Zs=at.objId,Sn=at.contentsObjId;un(Zs,!0),Fe("<>"),Fe("endobj");var Dr=Bs.join(` `);return S===N&&(Dr+=` Q`),un(Sn,!0),ts({data:Dr,filters:Pt(),objectId:Sn}),Fe("endobj"),Zs},Is=p.__private__.putPages=function(){var at,Yt,Bs=[];for(at=1;at<=Gn;at++)On[at].objId=sn(),On[at].contentsObjId=sn();for(at=1;at<=Gn;at++)Bs.push(ls({number:at,data:Oe[at],objId:On[at].objId,contentsObjId:On[at].contentsObjId,mediaBox:On[at].mediaBox,cropBox:On[at].cropBox,bleedBox:On[at].bleedBox,trimBox:On[at].trimBox,artBox:On[at].artBox,userUnit:On[at].userUnit,rootDictionaryObjId:fs,resourceDictionaryObjId:ot}));un(fs,!0),Fe("<>"),Fe("endobj"),Rr.publish("postPutPages")},ps=function(at){Rr.publish("putFont",{font:at,out:Fe,newObject:Un,putStream:ts}),at.isAlreadyPutted!==!0&&(at.objectNumber=Un(),Fe("<<"),Fe("/Type /Font"),Fe("/BaseFont /"+VB(at.postScriptName)),Fe("/Subtype /Type1"),typeof at.encoding=="string"&&Fe("/Encoding /"+at.encoding),Fe("/FirstChar 32"),Fe("/LastChar 255"),Fe(">>"),Fe("endobj"))},Ht=function(at){at.objectNumber=Un();var Yt=[];Yt.push({key:"Type",value:"/XObject"}),Yt.push({key:"Subtype",value:"/Form"}),Yt.push({key:"BBox",value:"["+[M(at.x),M(at.y),M(at.x+at.width),M(at.y+at.height)].join(" ")+"]"}),Yt.push({key:"Matrix",value:"["+at.matrix.toString()+"]"});var Bs=at.pages[1].join(` `);ts({data:Bs,additionalKeyValues:Yt,objectId:at.objectNumber}),Fe("endobj")},Xs=function(at,Yt){Yt||(Yt=21);var Bs=Un(),Zs=function(kt,Es){var bn,Br=[],Or=1/(Es-1);for(bn=0;bn<1;bn+=Or)Br.push(bn);if(Br.push(1),kt[0].offset!=0){var Ma={offset:0,color:kt[0].color};kt.unshift(Ma)}if(kt[kt.length-1].offset!=1){var Ra={offset:1,color:kt[kt.length-1].color};kt.push(Ra)}for(var nr="",Va=0,mi=0;mikt[Va+1].offset;)Va++;var ol=kt[Va].offset,vc=(bn-ol)/(kt[Va+1].offset-ol),ao=kt[Va].color,$m=kt[Va+1].color;nr+=be(Math.round((1-vc)*ao[0]+vc*$m[0]).toString(16))+be(Math.round((1-vc)*ao[1]+vc*$m[1]).toString(16))+be(Math.round((1-vc)*ao[2]+vc*$m[2]).toString(16))}return nr.trim()}(at.colors,Yt),Sn=[];Sn.push({key:"FunctionType",value:"0"}),Sn.push({key:"Domain",value:"[0.0 1.0]"}),Sn.push({key:"Size",value:"["+Yt+"]"}),Sn.push({key:"BitsPerSample",value:"8"}),Sn.push({key:"Range",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),Sn.push({key:"Decode",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),ts({data:Zs,additionalKeyValues:Sn,alreadyAppliedFilters:["/ASCIIHexDecode"],objectId:Bs}),Fe("endobj"),at.objectNumber=Un(),Fe("<< /ShadingType "+at.type),Fe("/ColorSpace /DeviceRGB");var Dr="/Coords ["+M(parseFloat(at.coords[0]))+" "+M(parseFloat(at.coords[1]))+" ";at.type===2?Dr+=M(parseFloat(at.coords[2]))+" "+M(parseFloat(at.coords[3])):Dr+=M(parseFloat(at.coords[2]))+" "+M(parseFloat(at.coords[3]))+" "+M(parseFloat(at.coords[4]))+" "+M(parseFloat(at.coords[5])),Fe(Dr+="]"),at.matrix&&Fe("/Matrix ["+at.matrix.toString()+"]"),Fe("/Function "+Bs+" 0 R"),Fe("/Extend [true true]"),Fe(">>"),Fe("endobj")},Rs=function(at,Yt){var Bs=sn(),Zs=Un();Yt.push({resourcesOid:Bs,objectOid:Zs}),at.objectNumber=Zs;var Sn=[];Sn.push({key:"Type",value:"/Pattern"}),Sn.push({key:"PatternType",value:"1"}),Sn.push({key:"PaintType",value:"1"}),Sn.push({key:"TilingType",value:"1"}),Sn.push({key:"BBox",value:"["+at.boundingBox.map(M).join(" ")+"]"}),Sn.push({key:"XStep",value:M(at.xStep)}),Sn.push({key:"YStep",value:M(at.yStep)}),Sn.push({key:"Resources",value:Bs+" 0 R"}),at.matrix&&Sn.push({key:"Matrix",value:"["+at.matrix.toString()+"]"}),ts({data:at.stream,additionalKeyValues:Sn,objectId:at.objectNumber}),Fe("endobj")},zn=function(at){for(var Yt in at.objectNumber=Un(),Fe("<<"),at)switch(Yt){case"opacity":Fe("/ca "+z(at[Yt]));break;case"stroke-opacity":Fe("/CA "+z(at[Yt]))}Fe(">>"),Fe("endobj")},Qr=function(at){un(at.resourcesOid,!0),Fe("<<"),Fe("/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]"),function(){for(var Yt in Fe("/Font <<"),As)As.hasOwnProperty(Yt)&&(h===!1||h===!0&&m.hasOwnProperty(Yt))&&Fe("/"+Yt+" "+As[Yt].objectNumber+" 0 R");Fe(">>")}(),function(){if(Object.keys(on).length>0){for(var Yt in Fe("/Shading <<"),on)on.hasOwnProperty(Yt)&&on[Yt]instanceof ID&&on[Yt].objectNumber>=0&&Fe("/"+Yt+" "+on[Yt].objectNumber+" 0 R");Rr.publish("putShadingPatternDict"),Fe(">>")}}(),function(Yt){if(Object.keys(on).length>0){for(var Bs in Fe("/Pattern <<"),on)on.hasOwnProperty(Bs)&&on[Bs]instanceof p.TilingPattern&&on[Bs].objectNumber>=0&&on[Bs].objectNumber>")}}(at.objectOid),function(){if(Object.keys(dn).length>0){var Yt;for(Yt in Fe("/ExtGState <<"),dn)dn.hasOwnProperty(Yt)&&dn[Yt].objectNumber>=0&&Fe("/"+Yt+" "+dn[Yt].objectNumber+" 0 R");Rr.publish("putGStateDict"),Fe(">>")}}(),function(){for(var Yt in Fe("/XObject <<"),Hs)Hs.hasOwnProperty(Yt)&&Hs[Yt].objectNumber>=0&&Fe("/"+Yt+" "+Hs[Yt].objectNumber+" 0 R");Rr.publish("putXobjectDict"),Fe(">>")}(),Fe(">>"),Fe("endobj")},ma=function(at){vt[at.fontName]=vt[at.fontName]||{},vt[at.fontName][at.fontStyle]=at.id},qr=function(at,Yt,Bs,Zs,Sn){var Dr={id:"F"+(Object.keys(As).length+1).toString(10),postScriptName:at,fontName:Yt,fontStyle:Bs,encoding:Zs,isStandardFont:Sn||!1,metadata:{}};return Rr.publish("addFont",{font:Dr,instance:this}),As[Dr.id]=Dr,ma(Dr),Dr.id},Zr=p.__private__.pdfEscape=p.pdfEscape=function(at,Yt){return function(Bs,Zs){var Sn,Dr,kt,Es,bn,Br,Or,Ma,Ra;if(kt=(Zs=Zs||{}).sourceEncoding||"Unicode",bn=Zs.outputEncoding,(Zs.autoencode||bn)&&As[Ut].metadata&&As[Ut].metadata[kt]&&As[Ut].metadata[kt].encoding&&(Es=As[Ut].metadata[kt].encoding,!bn&&As[Ut].encoding&&(bn=As[Ut].encoding),!bn&&Es.codePages&&(bn=Es.codePages[0]),typeof bn=="string"&&(bn=Es[bn]),bn)){for(Or=!1,Br=[],Sn=0,Dr=Bs.length;Sn>8&&(Or=!0);Bs=Br.join("")}for(Sn=Bs.length;Or===void 0&&Sn!==0;)Bs.charCodeAt(Sn-1)>>8&&(Or=!0),Sn--;if(!Or)return Bs;for(Br=Zs.noBOM?[]:[254,255],Sn=0,Dr=Bs.length;Sn>8)>>8)throw new Error("Character at position "+Sn+" of string '"+Bs+"' exceeds 16bits. Cannot be encoded into UCS-2 BE");Br.push(Ra),Br.push(Ma-(Ra<<8))}return String.fromCharCode.apply(void 0,Br)}(at,Yt).replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},Jr=p.__private__.beginPage=function(at){Oe[++Gn]=[],On[Gn]={objId:0,contentsObjId:0,userUnit:Number(o),artBox:null,bleedBox:null,cropBox:null,trimBox:null,mediaBox:{bottomLeftX:0,bottomLeftY:0,topRightX:Number(at[0]),topRightY:Number(at[1])}},Fo(Gn),Ae(Oe[ce])},ha=function(at,Yt){var Bs,Zs,Sn;switch(n=Yt||n,typeof at=="string"&&(Bs=v(at.toLowerCase()),Array.isArray(Bs)&&(Zs=Bs[0],Sn=Bs[1])),Array.isArray(at)&&(Zs=at[0]*Wt,Sn=at[1]*Wt),isNaN(Zs)&&(Zs=a[0],Sn=a[1]),(Zs>14400||Sn>14400)&&(lm.warn("A page in a PDF can not be wider or taller than 14400 userUnit. jsPDF limits the width/height to 14400"),Zs=Math.min(14400,Zs),Sn=Math.min(14400,Sn)),a=[Zs,Sn],n.substr(0,1)){case"l":Sn>Zs&&(a=[Sn,Zs]);break;case"p":Zs>Sn&&(a=[Sn,Zs])}Jr(a),dp(bo),Fe(_u),Jh!==0&&Fe(Jh+" J"),Bm!==0&&Fe(Bm+" j"),Rr.publish("addPage",{pageNumber:Gn})},Fa=function(at){at>0&&at<=Gn&&(Oe.splice(at,1),On.splice(at,1),Gn--,ce>Gn&&(ce=Gn),this.setPage(ce))},Fo=function(at){at>0&&at<=Gn&&(ce=at)},Xo=p.__private__.getNumberOfPages=p.getNumberOfPages=function(){return Oe.length-1},Vi=function(at,Yt,Bs){var Zs,Sn=void 0;return Bs=Bs||{},at=at!==void 0?at:As[Ut].fontName,Yt=Yt!==void 0?Yt:As[Ut].fontStyle,Zs=at.toLowerCase(),vt[Zs]!==void 0&&vt[Zs][Yt]!==void 0?Sn=vt[Zs][Yt]:vt[at]!==void 0&&vt[at][Yt]!==void 0?Sn=vt[at][Yt]:Bs.disableWarning===!1&&lm.warn("Unable to look up font label for font '"+at+"', '"+Yt+"'. Refer to getFontList() for available fonts."),Sn||Bs.noFallback||(Sn=vt.times[Yt])==null&&(Sn=vt.times.normal),Sn},Ja=p.__private__.putInfo=function(){var at=Un(),Yt=function(Zs){return Zs};for(var Bs in u!==null&&(Yt=ds.encryptor(at,0)),Fe("<<"),Fe("/Producer ("+Zr(Yt("jsPDF "+No.version))+")"),qt)qt.hasOwnProperty(Bs)&&qt[Bs]&&Fe("/"+Bs.substr(0,1).toUpperCase()+Bs.substr(1)+" ("+Zr(Yt(qt[Bs]))+")");Fe("/CreationDate ("+Zr(Yt(K))+")"),Fe(">>"),Fe("endobj")},Co=p.__private__.putCatalog=function(at){var Yt=(at=at||{}).rootDictionaryObjId||fs;switch(Un(),Fe("<<"),Fe("/Type /Catalog"),Fe("/Pages "+Yt+" 0 R"),Ze||(Ze="fullwidth"),Ze){case"fullwidth":Fe("/OpenAction [3 0 R /FitH null]");break;case"fullheight":Fe("/OpenAction [3 0 R /FitV null]");break;case"fullpage":Fe("/OpenAction [3 0 R /Fit]");break;case"original":Fe("/OpenAction [3 0 R /XYZ null null 1]");break;default:var Bs=""+Ze;Bs.substr(Bs.length-1)==="%"&&(Ze=parseInt(Ze)/100),typeof Ze=="number"&&Fe("/OpenAction [3 0 R /XYZ null null "+z(Ze)+"]")}switch(tt||(tt="continuous"),tt){case"continuous":Fe("/PageLayout /OneColumn");break;case"single":Fe("/PageLayout /SinglePage");break;case"two":case"twoleft":Fe("/PageLayout /TwoColumnLeft");break;case"tworight":Fe("/PageLayout /TwoColumnRight")}Ge&&Fe("/PageMode /"+Ge),Rr.publish("putCatalog"),Fe(">>"),Fe("endobj")},Go=p.__private__.putTrailer=function(){Fe("trailer"),Fe("<<"),Fe("/Size "+(he+1)),Fe("/Root "+he+" 0 R"),Fe("/Info "+(he-1)+" 0 R"),u!==null&&Fe("/Encrypt "+ds.oid+" 0 R"),Fe("/ID [ <"+Z+"> <"+Z+"> ]"),Fe(">>")},hi=p.__private__.putHeader=function(){Fe("%PDF-"+f),Fe("%ºß¬à")},Qo=p.__private__.putXRef=function(){var at="0000000000";Fe("xref"),Fe("0 "+(he+1)),Fe("0000000000 65535 f ");for(var Yt=1;Yt<=he;Yt++)typeof ge[Yt]=="function"?Fe((at+ge[Yt]()).slice(-10)+" 00000 n "):ge[Yt]!==void 0?Fe((at+ge[Yt]).slice(-10)+" 00000 n "):Fe("0000000000 00000 n ")},Ao=p.__private__.buildDocument=function(){var at;he=0,Te=0,ke=[],ge=[],Me=[],fs=sn(),ot=sn(),Ae(ke),Rr.publish("buildDocument"),hi(),Is(),function(){Rr.publish("putAdditionalObjects");for(var Bs=0;Bs"),Fe("/O <"+ds.toHexString(ds.O)+">"),Fe("/P "+ds.P),Fe(">>"),Fe("endobj")),Ja(),Co();var Yt=Te;return Qo(),Go(),Fe("startxref"),Fe(""+Yt),Fe("%%EOF"),Ae(Oe[ce]),ke.join(` `)},_a=p.__private__.getBlob=function(at){return new Blob([$e(at)],{type:"application/pdf"})},ir=function(at){for(;at.firstChild;)at.removeChild(at.firstChild)},li=function(at){var Yt,Bs=at.document,Zs=Bs.documentElement,Sn=Bs.head,Dr=Bs.body;return Sn||(Sn=Bs.createElement("head"),Zs.appendChild(Sn)),Dr||(Dr=Bs.createElement("body"),Zs.appendChild(Dr)),ir(Sn),ir(Dr),(Yt=Bs.createElement("style")).appendChild(Bs.createTextNode("html, body { padding: 0; margin: 0; } iframe { width: 100%; height: 100%; border: 0;}")),Sn.appendChild(Yt),{document:Bs,body:Dr}},Eo=p.output=p.__private__.output=(kn=function(at,Yt){switch(typeof(Yt=Yt||{})=="string"?Yt={filename:Yt}:Yt.filename=Yt.filename||"generated.pdf",at){case void 0:return Ao();case"save":p.save(Yt.filename);break;case"arraybuffer":return $e(Ao());case"blob":return _a(Ao());case"bloburi":case"bloburl":if(Yl.URL!==void 0&&typeof Yl.URL.createObjectURL=="function")return Yl.URL&&Yl.URL.createObjectURL(_a(Ao()))||void 0;lm.warn("bloburl is not supported by your system, because URL.createObjectURL is not supported by your browser.");break;case"datauristring":case"dataurlstring":var Bs="",Zs=Ao();try{Bs=X2t(Zs)}catch{Bs=X2t(unescape(encodeURIComponent(Zs)))}return"data:application/pdf;filename="+encodeURIComponent(Yt.filename)+";base64,"+Bs;case"pdfobjectnewwindow":if(Object.prototype.toString.call(Yl)==="[object Window]"){var Sn="https://cdnjs.cloudflare.com/ajax/libs/pdfobject/2.1.1/pdfobject.min.js",Dr=!Yt.pdfObjectUrl;Dr||(Sn=Yt.pdfObjectUrl);var kt=Yl.open();if(kt!==null){var Es=li(kt),bn=Es.document.createElement("script"),Br=this;bn.src=Sn,Dr&&(bn.integrity="sha512-4ze/a9/4jqu+tX9dfOqJYSvyYd5M6qum/3HpCLr+/Jqf0whc37VUbkpNGHR7/8pSnCFw47T1fmIpwBV7UySh3g==",bn.crossOrigin="anonymous"),bn.onload=function(){kt.PDFObject.embed(Br.output("dataurlstring"),Yt)},Es.body.appendChild(bn)}return kt}throw new Error("The option pdfobjectnewwindow just works in a browser-environment.");case"pdfjsnewwindow":if(Object.prototype.toString.call(Yl)==="[object Window]"){var Or=Yt.pdfJsUrl||"examples/PDF.js/web/viewer.html",Ma=Yl.open();if(Ma!==null){var Ra=li(Ma),nr=Ra.document.createElement("iframe"),Va=Or.indexOf("?")===-1?"?":"&";Br=this,nr.id="pdfViewer",nr.width="500px",nr.height="400px",nr.src=Or+Va+"file=&downloadName="+encodeURIComponent(Yt.filename),nr.onload=function(){Ma.document.title=Yt.filename,nr.contentWindow.PDFViewerApplication.open(Br.output("bloburl"))},Ra.body.appendChild(nr)}return Ma}throw new Error("The option pdfjsnewwindow just works in a browser-environment.");case"dataurlnewwindow":if(Object.prototype.toString.call(Yl)!=="[object Window]")throw new Error("The option dataurlnewwindow just works in a browser-environment.");var mi=Yl.open();if(mi!==null){var ol=li(mi),vc=ol.document.createElement("iframe");vc.src=this.output("datauristring",Yt),ol.body.appendChild(vc),mi.document.title=Yt.filename}if(mi||typeof safari>"u")return mi;break;case"datauri":case"dataurl":return Yl.document.location.href=this.output("datauristring",Yt);default:return null}},kn.foo=function(){try{return kn.apply(this,arguments)}catch(Bs){var at=Bs.stack||"";~at.indexOf(" at ")&&(at=at.split(" at ")[1]);var Yt="Error in function "+at.split(` `)[0].split("<")[0]+": "+Bs.message;if(!Yl.console)throw new Error(Yt);Yl.console.error(Yt,Bs),Yl.alert&&alert(Yt)}},kn.foo.bar=kn,kn.foo),gl=function(at){return Array.isArray(cr)===!0&&cr.indexOf(at)>-1};switch(r){case"pt":Wt=1;break;case"mm":Wt=72/25.4;break;case"cm":Wt=72/2.54;break;case"in":Wt=72;break;case"px":Wt=gl("px_scaling")==1?.75:96/72;break;case"pc":case"em":Wt=12;break;case"ex":Wt=6;break;default:if(typeof r!="number")throw new Error("Invalid unit: "+r);Wt=r}var ds=null;ne(),le();var Gr=p.__private__.getPageInfo=p.getPageInfo=function(at){if(isNaN(at)||at%1!=0)throw new Error("Invalid argument passed to jsPDF.getPageInfo");return{objId:On[at].objId,pageNumber:at,pageContext:On[at]}},ji=p.__private__.getPageInfoByObjId=function(at){if(isNaN(at)||at%1!=0)throw new Error("Invalid argument passed to jsPDF.getPageInfoByObjId");for(var Yt in On)if(On[Yt].objId===at)break;return Gr(Yt)},ya=p.__private__.getCurrentPageInfo=p.getCurrentPageInfo=function(){return{objId:On[ce].objId,pageNumber:ce,pageContext:On[ce]}};p.addPage=function(){return ha.apply(this,arguments),this},p.setPage=function(){return Fo.apply(this,arguments),Ae.call(this,Oe[ce]),this},p.insertPage=function(at){return this.addPage(),this.movePage(ce,at),this},p.movePage=function(at,Yt){var Bs,Zs;if(at>Yt){Bs=Oe[at],Zs=On[at];for(var Sn=at;Sn>Yt;Sn--)Oe[Sn]=Oe[Sn-1],On[Sn]=On[Sn-1];Oe[Yt]=Bs,On[Yt]=Zs,this.setPage(Yt)}else if(at0&&(typeof at=="string"?at=Va.splitTextToSize(at,Or):Object.prototype.toString.call(at)==="[object Array]"&&(at=at.reduce(function(xl,ll){return xl.concat(Va.splitTextToSize(ll,Or))},[]))),Dr={text:at,x:Yt,y:Bs,options:Zs,mutex:{pdfEscape:Zr,activeFontKey:Ut,fonts:As,activeFontSize:qe}},Rr.publish("preProcessText",Dr),at=Dr.text,Es=(Zs=Dr.options).angle,nr instanceof Zn==0&&Es&&typeof Es=="number"){Es*=Math.PI/180,Zs.rotationDirection===0&&(Es=-Es),S===N&&(Es=-Es);var Sv=Math.cos(Es),Bd=Math.sin(Es);nr=new Zn(Sv,Bd,-Bd,Sv,0,0)}else Es&&Es instanceof Zn&&(nr=Es);S!==N||nr||(nr=ar),(Br=Zs.charSpace||mp)!==void 0&&(vc+=M(H(Br))+` Tc `,this.setCharSpace(this.getCharSpace()||0)),(Ra=Zs.horizontalScale)!==void 0&&(vc+=M(100*Ra)+` Tz `),Zs.lang;var tu=-1,uh=Zs.renderingMode!==void 0?Zs.renderingMode:Zs.stroke,fp=Va.internal.getCurrentPageInfo().pageContext;switch(uh){case 0:case!1:case"fill":tu=0;break;case 1:case!0:case"stroke":tu=1;break;case 2:case"fillThenStroke":tu=2;break;case 3:case"invisible":tu=3;break;case 4:case"fillAndAddForClipping":tu=4;break;case 5:case"strokeAndAddPathForClipping":tu=5;break;case 6:case"fillThenStrokeAndAddToPathForClipping":tu=6;break;case 7:case"addToPathForClipping":tu=7}var xg=fp.usedRenderingMode!==void 0?fp.usedRenderingMode:-1;tu!==-1?vc+=tu+` Tr `:xg!==-1&&(vc+=`0 Tr `),tu!==-1&&(fp.usedRenderingMode=tu),bn=Zs.align||"left";var Hl,Ia=qe*ao,Hr=Va.internal.pageSize.getWidth(),bc=As[Ut];Br=Zs.charSpace||mp,Or=Zs.maxWidth||0,Ma=Object.assign({autoencode:!0,noBOM:!0},Zs.flags);var Da=[],gp=function(xl){return Va.getStringUnitWidth(xl,{font:bc,charSpace:Br,fontSize:qe,doKerning:!1})*qe/$m};if(Object.prototype.toString.call(at)==="[object Array]"){var Ud;kt=S0(at),bn!=="left"&&(Hl=kt.map(gp));var fa,Px=0;if(bn==="right"){Yt-=Hl[0],at=[],wu=kt.length;for(var C0=0;C00?(Or-Hl[gd])/Zp:0;gd":")"),Xc=parseFloat(kt[Ju][1]),Lx=parseFloat(kt[Ju][2]);break;case 0:ky=(ol?"<":"(")+kt[Ju]+(ol?">":")"),Xc=hp(Yt),Lx=Jd(Bs)}Da!==void 0&&Da[Ju]!==void 0&&(vg=Da[Ju]+` Tw `),Ju===0?at.push(vg+Eb(Xc,Lx,nr)+ky):tm===0?at.push(vg+ky):tm===1&&at.push(vg+Eb(Xc,Lx,nr)+ky)}at=tm===0?at.join(` Tj T* `):at.join(` Tj `),at+=` Tj `;var _c=`BT /`;return _c+=Ut+" "+qe+` Tf `,_c+=M(qe*ao)+` TL `,_c+=zm+` `,_c+=vc,_c+=at,Fe(_c+="ET"),m[Ut]=!0,Va};var Wi=p.__private__.clip=p.clip=function(at){return Fe(at==="evenodd"?"W*":"W"),this};p.clipEvenOdd=function(){return Wi("evenodd")},p.__private__.discardPath=p.discardPath=function(){return Fe("n"),this};var wi=p.__private__.isValidStyle=function(at){var Yt=!1;return[void 0,null,"S","D","F","DF","FD","f","f*","B","B*","n"].indexOf(at)!==-1&&(Yt=!0),Yt};p.__private__.setDefaultPathOperation=p.setDefaultPathOperation=function(at){return wi(at)&&(d=at),this};var di=p.__private__.getStyle=p.getStyle=function(at){var Yt=d;switch(at){case"D":case"S":Yt="S";break;case"F":Yt="f";break;case"FD":case"DF":Yt="B";break;case"f":case"f*":case"B":case"B*":Yt=at}return Yt},Dc=p.close=function(){return Fe("h"),this};p.stroke=function(){return Fe("S"),this},p.fill=function(at){return fd("f",at),this},p.fillEvenOdd=function(at){return fd("f*",at),this},p.fillStroke=function(at){return fd("B",at),this},p.fillStrokeEvenOdd=function(at){return fd("B*",at),this};var fd=function(at,Yt){kh(Yt)==="object"?Jo(Yt,at):Fe(at)},Vp=function(at){at===null||S===N&&at===void 0||(at=di(at),Fe(at))};function vy(at,Yt,Bs,Zs,Sn){var Dr=new PU(Yt||this.boundingBox,Bs||this.xStep,Zs||this.yStep,this.gState,Sn||this.matrix);Dr.stream=this.stream;var kt=at+"$$"+this.cloneIndex+++"$$";return Hn(kt,Dr),Dr}var Jo=function(at,Yt){var Bs=Ms[at.key],Zs=on[Bs];if(Zs instanceof ID)Fe("q"),Fe(il(Yt)),Zs.gState&&p.setGState(Zs.gState),Fe(at.matrix.toString()+" cm"),Fe("/"+Bs+" sh"),Fe("Q");else if(Zs instanceof PU){var Sn=new Zn(1,0,0,-1,0,qm());at.matrix&&(Sn=Sn.multiply(at.matrix||ar),Bs=vy.call(Zs,at.key,at.boundingBox,at.xStep,at.yStep,Sn).id),Fe("q"),Fe("/Pattern cs"),Fe("/"+Bs+" scn"),Zs.gState&&p.setGState(Zs.gState),Fe(Yt),Fe("Q")}},il=function(at){switch(at){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"}},Hp=p.moveTo=function(at,Yt){return Fe(M(H(at))+" "+M(V(Yt))+" m"),this},fg=p.lineTo=function(at,Yt){return Fe(M(H(at))+" "+M(V(Yt))+" l"),this},Lh=p.curveTo=function(at,Yt,Bs,Zs,Sn,Dr){return Fe([M(H(at)),M(V(Yt)),M(H(Bs)),M(V(Zs)),M(H(Sn)),M(V(Dr)),"c"].join(" ")),this};p.__private__.line=p.line=function(at,Yt,Bs,Zs,Sn){if(isNaN(at)||isNaN(Yt)||isNaN(Bs)||isNaN(Zs)||!wi(Sn))throw new Error("Invalid arguments passed to jsPDF.line");return S===b?this.lines([[Bs-at,Zs-Yt]],at,Yt,[1,1],Sn||"S"):this.lines([[Bs-at,Zs-Yt]],at,Yt,[1,1]).stroke()},p.__private__.lines=p.lines=function(at,Yt,Bs,Zs,Sn,Dr){var kt,Es,bn,Br,Or,Ma,Ra,nr,Va,mi,ol,vc;if(typeof at=="number"&&(vc=Bs,Bs=Yt,Yt=at,at=vc),Zs=Zs||[1,1],Dr=Dr||!1,isNaN(Yt)||isNaN(Bs)||!Array.isArray(at)||!Array.isArray(Zs)||!wi(Sn)||typeof Dr!="boolean")throw new Error("Invalid arguments passed to jsPDF.lines");for(Hp(Yt,Bs),kt=Zs[0],Es=Zs[1],Br=at.length,mi=Yt,ol=Bs,bn=0;bn>8&255,s>>16&255,s>>24&255)},$B.prototype.toHexString=function(s){return s.split("").map(function(t){return("0"+(255&t.charCodeAt(0)).toString(16)).slice(-2)}).join("")},$B.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 IGe(n,r)}},YEe.prototype.equals=function(s){var t,n="id,objectNumber,equals";if(!s||kh(s)!==kh(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},No.API={events:[]},No.version="4.2.1";var Zf=No.API,lnt=1,R9=function(s){return s.replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},hB=function(s){return s.replace(/\\\\/g,"\\").replace(/\\\(/g,"(").replace(/\\\)/g,")")},Z7=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)})},gc=function(s){return s.toFixed(2)},uT=function(s){return s.toFixed(5)};Zf.__acroform__={};var q_=function(s,t){s.prototype=Object.create(t.prototype),s.prototype.constructor=s},tNt=function(s){return s*lnt},w5=function(s){var t=new IZt,n=go.internal.getHeight(s)||0,r=go.internal.getWidth(s)||0;return t.BBox=[0,0,Number(gc(r)),Number(gc(n))],t},rzn=Zf.__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=ace("3",s,i).height,m=s.multiline?l-i:(l-h)/2,p=m+=2,f=0,x=0,y=0;if(i<=0){t=`(...) Tj `,t+="% Width of Text: "+ace(t,s,i=12).width+", FieldWidth:"+o+` `;break}for(var v="",b=0,N=0;Nl)continue e;v+=a[N][y],S=!0,x=N,N--}else{v=(v+=a[N][y]+" ").substr(v.length-1)==" "?v.substr(0,v.length-1):v;var A=parseInt(N),T=c(A,v,i),L=N>=a.length-1;if(T&&!L){v+=" ",y=0;continue}if(T||L){if(L)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 M="",I=f;I<=x;I++){var R=a[I];if(s.multiline){if(I===x){M+=R[y]+" ",y=(y+1)%R.length;continue}if(I===f){M+=R[R.length-1]+" ";continue}}M+=R[0]+" "}switch(M=M.substr(M.length-1)==" "?M.substr(0,M.length-1):M,u=ace(M,s,i).width,s.textAlign){case"right":d=o-u-2;break;case"center":d=(o-u)/2;break;default:d=2}t+=gc(d)+" "+gc(p)+` Td `,t+="("+R9(M)+`) Tj `,t+=-gc(d)+` 0 Td `,p=-(i+2),u=0,f=S?x:x+1,b++,v=""}break}return r.text=t,r.fontSize=i,r},ace=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}},czn={fields:[],xForms:[],acroFormDictionaryRoot:null,printedOut:!1,internal:null,isInitialized:!1},dzn=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)},uzn=function(s,t){if(t.scope=s,s.internal!==void 0&&(s.internal.acroformPlugin===void 0||s.internal.acroformPlugin.isInitialized===!1)){if(MS.FieldNum=0,s.internal.acroformPlugin=JSON.parse(JSON.stringify(czn)),s.internal.acroformPlugin.acroFormDictionaryRoot)throw new Error("Exception while creating AcroformDictionary");lnt=s.internal.scaleFactor,s.internal.acroformPlugin.acroFormDictionaryRoot=new RZt,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&&dzn(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=ozn(o.Rect,a)),a.internal.newObjectDeferredBegin(o.objId,!0),o.DA=go.createDefaultAppearanceStream(o),kh(o)==="object"&&typeof o.getKeyValueListForStream=="function"&&(c=o.getKeyValueListForStream()),o.Rect=d,o.hasAppearanceStream&&!o.appearanceStreamContent){var u=lzn(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 p=o.appearanceStreamContent[m];if(h+="/"+m+" ",h+="<<",Object.keys(p).length>=1||Array.isArray(p)){for(var l in p)if(p.hasOwnProperty(l)){var f=p[l];typeof f=="function"&&(f=f.call(a,o)),h+="/"+l+" "+f+" ",a.internal.acroformPlugin.xForms.indexOf(f)>=0||a.internal.acroformPlugin.xForms.push(f)}}else typeof(f=p)=="function"&&(f=f.call(a,o)),h+="/"+l+" "+f,a.internal.acroformPlugin.xForms.indexOf(f)>=0||a.internal.acroformPlugin.xForms.push(f);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,N=x[v];y.internal.newObjectDeferredBegin(N.objId,!0),kh(N)==="object"&&typeof N.putStream=="function"&&N.putStream(),delete x[b]}}(a.internal.acroformPlugin.xForms,a)})(n,s)}),s.internal.acroformPlugin.isInitialized=!0}},LZt=Zf.__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)),"("+R9(n(s))+")"}},set:function(n){s=n}})};q_(RZt,b4);var MS=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!!Ig(t,3)},set:function(v){v?this.F=Rg(t,3):this.F=Dg(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 ZEe)return;i="FieldObject"+s.FieldNum++}var v=function(b){return b};return this.scope&&(v=this.scope.internal.getEncryptor(this.objId)),"("+R9(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/lnt: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 ZEe||this instanceof c7))return E9e(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 J0==0?E9e(m,this.objId,this.scope):m},set:function(v){v=v.toString(),m=this instanceof J0==0?v.substr(0,1)==="("?hB(v.substr(1,v.length-2)):hB(v):v}}),Object.defineProperty(this,"defaultValue",{enumerable:!0,configurable:!0,get:function(){return this instanceof J0==1?hB(m.substr(1,m.length-1)):m},set:function(v){v=v.toString(),m=this instanceof J0==1?"/"+Z7(v):v}});var p=null;Object.defineProperty(this,"_V",{enumerable:!1,configurable:!1,get:function(){if(p)return p},set:function(v){this.V=v}}),Object.defineProperty(this,"V",{enumerable:!1,configurable:!1,get:function(){if(p)return this instanceof J0==0?E9e(p,this.objId,this.scope):p},set:function(v){v=v.toString(),p=this instanceof J0==0?v.substr(0,1)==="("?hB(v.substr(1,v.length-2)):hB(v):v}}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,get:function(){return this instanceof J0==1?hB(p.substr(1,p.length-1)):p},set:function(v){v=v.toString(),p=this instanceof J0==1?"/"+Z7(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 f,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(f)return f},set:function(v){f=v}}),Object.defineProperty(this,"readOnly",{enumerable:!0,configurable:!0,get:function(){return!!Ig(this.Ff,1)},set:function(v){v?this.Ff=Rg(this.Ff,1):this.Ff=Dg(this.Ff,1)}}),Object.defineProperty(this,"required",{enumerable:!0,configurable:!0,get:function(){return!!Ig(this.Ff,2)},set:function(v){v?this.Ff=Rg(this.Ff,2):this.Ff=Dg(this.Ff,2)}}),Object.defineProperty(this,"noExport",{enumerable:!0,configurable:!0,get:function(){return!!Ig(this.Ff,3)},set:function(v){v?this.Ff=Rg(this.Ff,3):this.Ff=Dg(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}}})};q_(MS,b4);var Xq=function(){MS.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 LZt(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!!Ig(this.Ff,18)},set:function(n){n?this.Ff=Rg(this.Ff,18):this.Ff=Dg(this.Ff,18)}}),Object.defineProperty(this,"edit",{enumerable:!0,configurable:!0,get:function(){return!!Ig(this.Ff,19)},set:function(n){this.combo===!0&&(n?this.Ff=Rg(this.Ff,19):this.Ff=Dg(this.Ff,19))}}),Object.defineProperty(this,"sort",{enumerable:!0,configurable:!0,get:function(){return!!Ig(this.Ff,20)},set:function(n){n?(this.Ff=Rg(this.Ff,20),t.sort()):this.Ff=Dg(this.Ff,20)}}),Object.defineProperty(this,"multiSelect",{enumerable:!0,configurable:!0,get:function(){return!!Ig(this.Ff,22)},set:function(n){n?this.Ff=Rg(this.Ff,22):this.Ff=Dg(this.Ff,22)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!Ig(this.Ff,23)},set:function(n){n?this.Ff=Rg(this.Ff,23):this.Ff=Dg(this.Ff,23)}}),Object.defineProperty(this,"commitOnSelChange",{enumerable:!0,configurable:!0,get:function(){return!!Ig(this.Ff,27)},set:function(n){n?this.Ff=Rg(this.Ff,27):this.Ff=Dg(this.Ff,27)}}),this.hasAppearanceStream=!1};q_(Xq,MS);var Qq=function(){Xq.call(this),this.fontName="helvetica",this.combo=!1};q_(Qq,Xq);var Jq=function(){Qq.call(this),this.combo=!0};q_(Jq,Qq);var a4e=function(){Jq.call(this),this.edit=!0};q_(a4e,Jq);var J0=function(){MS.call(this),this.FT="/Btn",Object.defineProperty(this,"noToggleToOff",{enumerable:!0,configurable:!0,get:function(){return!!Ig(this.Ff,15)},set:function(n){n?this.Ff=Rg(this.Ff,15):this.Ff=Dg(this.Ff,15)}}),Object.defineProperty(this,"radio",{enumerable:!0,configurable:!0,get:function(){return!!Ig(this.Ff,16)},set:function(n){n?this.Ff=Rg(this.Ff,16):this.Ff=Dg(this.Ff,16)}}),Object.defineProperty(this,"pushButton",{enumerable:!0,configurable:!0,get:function(){return!!Ig(this.Ff,17)},set:function(n){n?this.Ff=Rg(this.Ff,17):this.Ff=Dg(this.Ff,17)}}),Object.defineProperty(this,"radioIsUnison",{enumerable:!0,configurable:!0,get:function(){return!!Ig(this.Ff,26)},set:function(n){n?this.Ff=Rg(this.Ff,26):this.Ff=Dg(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+" ("+R9(n(t[r]))+")");return a.push(">>"),a.join(` `)}},set:function(n){kh(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="/"+Z7(r)}}),Object.defineProperty(this,"appearanceState",{enumerable:!0,configurable:!0,get:function(){return s.substr(1,s.length-1)},set:function(n){s="/"+Z7(n)}})};q_(J0,MS);var i4e=function(){J0.call(this),this.pushButton=!0};q_(i4e,J0);var e$=function(){J0.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:[]}})};q_(e$,J0);var ZEe=function(){var s,t;MS.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+" ("+R9(a(r[i]))+")");return l.push(">>"),l.join(` `)},set:function(a){kh(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="/"+Z7(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="/"+Z7(i)}}),this.caption="l",this.appearanceState="Off",this._AppearanceType=go.RadioButton.Circle,this.appearanceStreamContent=this._AppearanceType.createAppearanceStream(this.optionName)};q_(ZEe,MS),e$.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()}},e$.prototype.createOption=function(s){var t=new ZEe;return t.Parent=this,t.optionName=s,this.Kids.push(t),hzn.call(this.scope,t),t};var o4e=function(){J0.call(this),this.fontName="zapfdingbats",this.caption="3",this.appearanceState="On",this.value="On",this.textAlign="center",this.appearanceStreamContent=go.CheckBox.createAppearanceStream()};q_(o4e,J0);var c7=function(){MS.call(this),this.FT="/Tx",Object.defineProperty(this,"multiline",{enumerable:!0,configurable:!0,get:function(){return!!Ig(this.Ff,13)},set:function(t){t?this.Ff=Rg(this.Ff,13):this.Ff=Dg(this.Ff,13)}}),Object.defineProperty(this,"fileSelect",{enumerable:!0,configurable:!0,get:function(){return!!Ig(this.Ff,21)},set:function(t){t?this.Ff=Rg(this.Ff,21):this.Ff=Dg(this.Ff,21)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!Ig(this.Ff,23)},set:function(t){t?this.Ff=Rg(this.Ff,23):this.Ff=Dg(this.Ff,23)}}),Object.defineProperty(this,"doNotScroll",{enumerable:!0,configurable:!0,get:function(){return!!Ig(this.Ff,24)},set:function(t){t?this.Ff=Rg(this.Ff,24):this.Ff=Dg(this.Ff,24)}}),Object.defineProperty(this,"comb",{enumerable:!0,configurable:!0,get:function(){return!!Ig(this.Ff,25)},set:function(t){t?this.Ff=Rg(this.Ff,25):this.Ff=Dg(this.Ff,25)}}),Object.defineProperty(this,"richText",{enumerable:!0,configurable:!0,get:function(){return!!Ig(this.Ff,26)},set:function(t){t?this.Ff=Rg(this.Ff,26):this.Ff=Dg(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}})};q_(c7,MS);var l4e=function(){c7.call(this),Object.defineProperty(this,"password",{enumerable:!0,configurable:!0,get:function(){return!!Ig(this.Ff,14)},set:function(s){s?this.Ff=Rg(this.Ff,14):this.Ff=Dg(this.Ff,14)}}),this.password=!0};q_(l4e,c7);var go={CheckBox:{createAppearanceStream:function(){return{N:{On:go.CheckBox.YesNormal},D:{On:go.CheckBox.YesPushDown,Off:go.CheckBox.OffPushDown}}},YesPushDown:function(s){var t=w5(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=RGe(s,s.caption);return n.push("0.749023 g"),n.push("0 0 "+gc(go.internal.getWidth(s))+" "+gc(go.internal.getHeight(s))+" re"),n.push("f"),n.push("BMC"),n.push("q"),n.push("0 0 1 rg"),n.push("/"+r+" "+gc(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=w5(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=go.internal.getHeight(s),l=go.internal.getWidth(s),o=RGe(s,s.caption);return a.push("1 g"),a.push("0 0 "+gc(l)+" "+gc(i)+" re"),a.push("f"),a.push("q"),a.push("0 0 1 rg"),a.push("0 0 "+gc(l-1)+" "+gc(i-1)+" re"),a.push("W"),a.push("n"),a.push("0 g"),a.push("BT"),a.push("/"+n+" "+gc(o.fontSize)+" Tf "+r),a.push(o.text),a.push("ET"),a.push("Q"),t.stream=a.join(` `),t},OffPushDown:function(s){var t=w5(s);t.scope=s.scope;var n=[];return n.push("0.749023 g"),n.push("0 0 "+gc(go.internal.getWidth(s))+" "+gc(go.internal.getHeight(s))+" re"),n.push("f"),t.stream=n.join(` `),t}},RadioButton:{Circle:{createAppearanceStream:function(s){var t={D:{Off:go.RadioButton.Circle.OffPushDown},N:{}};return t.N[s]=go.RadioButton.Circle.YesNormal,t.D[s]=go.RadioButton.Circle.YesPushDown,t},getCA:function(){return"l"},YesNormal:function(s){var t=w5(s);t.scope=s.scope;var n=[],r=go.internal.getWidth(s)<=go.internal.getHeight(s)?go.internal.getWidth(s)/4:go.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=go.internal.Bezier_C,i=Number((r*a).toFixed(5));return n.push("q"),n.push("1 0 0 1 "+uT(go.internal.getWidth(s)/2)+" "+uT(go.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=w5(s);t.scope=s.scope;var n=[],r=go.internal.getWidth(s)<=go.internal.getHeight(s)?go.internal.getWidth(s)/4:go.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=Number((2*r).toFixed(5)),i=Number((a*go.internal.Bezier_C).toFixed(5)),l=Number((r*go.internal.Bezier_C).toFixed(5));return n.push("0.749023 g"),n.push("q"),n.push("1 0 0 1 "+uT(go.internal.getWidth(s)/2)+" "+uT(go.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 "+uT(go.internal.getWidth(s)/2)+" "+uT(go.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=w5(s);t.scope=s.scope;var n=[],r=go.internal.getWidth(s)<=go.internal.getHeight(s)?go.internal.getWidth(s)/4:go.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=Number((2*r).toFixed(5)),i=Number((a*go.internal.Bezier_C).toFixed(5));return n.push("0.749023 g"),n.push("q"),n.push("1 0 0 1 "+uT(go.internal.getWidth(s)/2)+" "+uT(go.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:go.RadioButton.Cross.OffPushDown},N:{}};return t.N[s]=go.RadioButton.Cross.YesNormal,t.D[s]=go.RadioButton.Cross.YesPushDown,t},getCA:function(){return"8"},YesNormal:function(s){var t=w5(s);t.scope=s.scope;var n=[],r=go.internal.calculateCross(s);return n.push("q"),n.push("1 1 "+gc(go.internal.getWidth(s)-2)+" "+gc(go.internal.getHeight(s)-2)+" re"),n.push("W"),n.push("n"),n.push(gc(r.x1.x)+" "+gc(r.x1.y)+" m"),n.push(gc(r.x2.x)+" "+gc(r.x2.y)+" l"),n.push(gc(r.x4.x)+" "+gc(r.x4.y)+" m"),n.push(gc(r.x3.x)+" "+gc(r.x3.y)+" l"),n.push("s"),n.push("Q"),t.stream=n.join(` `),t},YesPushDown:function(s){var t=w5(s);t.scope=s.scope;var n=go.internal.calculateCross(s),r=[];return r.push("0.749023 g"),r.push("0 0 "+gc(go.internal.getWidth(s))+" "+gc(go.internal.getHeight(s))+" re"),r.push("f"),r.push("q"),r.push("1 1 "+gc(go.internal.getWidth(s)-2)+" "+gc(go.internal.getHeight(s)-2)+" re"),r.push("W"),r.push("n"),r.push(gc(n.x1.x)+" "+gc(n.x1.y)+" m"),r.push(gc(n.x2.x)+" "+gc(n.x2.y)+" l"),r.push(gc(n.x4.x)+" "+gc(n.x4.y)+" m"),r.push(gc(n.x3.x)+" "+gc(n.x3.y)+" l"),r.push("s"),r.push("Q"),t.stream=r.join(` `),t},OffPushDown:function(s){var t=w5(s);t.scope=s.scope;var n=[];return n.push("0.749023 g"),n.push("0 0 "+gc(go.internal.getWidth(s))+" "+gc(go.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}};go.internal={Bezier_C:.551915024494,calculateCross:function(s){var t=go.internal.getWidth(s),n=go.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}}}},go.internal.getWidth=function(s){var t=0;return kh(s)==="object"&&(t=tNt(s.Rect[2])),t},go.internal.getHeight=function(s){var t=0;return kh(s)==="object"&&(t=tNt(s.Rect[3])),t};var hzn=Zf.addField=function(s){if(uzn(this,s),!(s instanceof MS))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};Zf.AcroFormChoiceField=Xq,Zf.AcroFormListBox=Qq,Zf.AcroFormComboBox=Jq,Zf.AcroFormEditBox=a4e,Zf.AcroFormButton=J0,Zf.AcroFormPushButton=i4e,Zf.AcroFormRadioButton=e$,Zf.AcroFormCheckBox=o4e,Zf.AcroFormTextField=c7,Zf.AcroFormPasswordField=l4e,Zf.AcroFormAppearance=go,Zf.AcroForm={ChoiceField:Xq,ListBox:Qq,ComboBox:Jq,EditBox:a4e,Button:J0,PushButton:i4e,RadioButton:e$,CheckBox:o4e,TextField:c7,PasswordField:l4e,Appearance:go},No.AcroForm={ChoiceField:Xq,ListBox:Qq,ComboBox:Jq,EditBox:a4e,Button:J0,PushButton:i4e,RadioButton:e$,CheckBox:o4e,TextField:c7,PasswordField:l4e,Appearance:go};function DZt(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(z,$){var H,V,K,Z,Q,le=n;if(($=$||n)==="RGBA"||z.data!==void 0&&z.data instanceof Uint8ClampedArray&&"height"in z&&"width"in z)return"RGBA";if(T(z))for(Q in r)for(K=r[Q],H=0;H>"}),"transparency"in $&&Array.isArray($.transparency)&&$.transparency.length>0){for(var Q="",le=0,ue=$.transparency.length;le>",x.content=i;var N=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="",N=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}])}(No.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 p=arguments[5];Object.defineProperty(this,"lineNumber",{enumerable:!0,get:function(){return p},set:function(x){p=x}});var f=arguments[6];return Object.defineProperty(this,"align",{enumerable:!0,get:function(){return f},set:function(x){f=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,p=0,f=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(N,S){return N.concat(y.splitTextToSize(S,v))},[])):c=Array.isArray(c)?c:[c];for(var b=0;bthis.getPageHeight()?(this.cellAddPage(),c.y=h.top,p&&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 p,f,x,y,v=[],b=[],N=[],S={},A={},T=[],L=[],M=(m=m||{}).autoSize||!1,I=m.printHeaders!==!1,R=m.css&&m.css["font-size"]!==void 0?16*m.css["font-size"]:m.fontSize||12,z=m.margins||Object.assign({width:this.getPageWidth()},t),$=typeof m.padding=="number"?m.padding:3,H=m.headerBackgroundColor||"#c8c8c8",V=m.headerTextColor||"#000";if(a.call(this),this.internal.__cell__.printHeaders=I,this.internal.__cell__.margins=z,this.internal.__cell__.table_font_size=R,this.internal.__cell__.padding=$,this.internal.__cell__.headerBackgroundColor=H,this.internal.__cell__.headerTextColor=V,this.setFontSize(R),h==null)b=v=Object.keys(u[0]),N=v.map(function(){return"left"});else if(Array.isArray(h)&&kh(h[0])==="object")for(v=h.map(function(se){return se.name}),b=h.map(function(se){return se.prompt||se.name||""}),N=h.map(function(se){return se.align||"left"}),p=0;p0&&this.setTableHeaderRow(m),this.setFont(void 0,"normal"),n=!1}}(No.API);var OZt={italic:["italic","oblique","normal"],oblique:["oblique","italic","normal"],normal:["normal","oblique","italic"]},FZt=["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded"],DGe=DZt(FZt),zZt=[100,200,300,400,500,600,700,800,900],mzn=DZt(zZt);function T9e(s){var t=s.family.replace(/"|'/g,"").toLowerCase(),n=function(i){return OZt[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 DGe[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 sNt(s,t,n,r){var a;for(a=n;a>=0&&a=0&&a>>1)&255}return a}function mNt(s,t,n){var r=s.length,a=[];a[0]=4;for(var i=0;i>i&l}function pNt(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,BZt(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,p=0,f=null;for(this.width=n,this.height=r;d&&t=0))throw Error("Invalid block size");if(z===0)break;t+=z}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),p=x>>2&7,t++;break;case 254:for(;;){if(!((z=s[t++])>=0))throw Error("Invalid block size");if(z===0)break;t+=z}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,N=s[t++]|s[t++]<<8,S=s[t++],A=S>>6&1,T=1<<1+(7&S),L=o,M=c,I=!1;S>>7&&(I=!0,L=t,M=T,t+=3*T);var R=t;for(t++;;){var z;if(!((z=s[t++])>=0))throw Error("Invalid block size");if(z===0)break;t+=z}u.push({x:y,y:v,width:b,height:N,has_local_palette:I,palette_offset:L,palette_size:M,data_offset:R,data_length:t-R,transparent_index:m,interlaced:!!A,delay:h,disposal:p});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 f},this.frameInfo=function($){if($<0||$>=u.length)throw new Error("Frame index out of range.");return u[$]},this.decodeAndBlitFrameBGRA=function($,H){var V=this.frameInfo($),K=V.width*V.height;if(K>536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");var Z=new Uint8Array(K);fNt(s,V.data_offset,Z,K);var Q=V.palette_offset,le=V.transparent_index;le===null&&(le=256);var ue=V.width,se=n-ue,ne=ue,ie=4*(V.y*n+V.x),ce=4*((V.y+V.height)*n+V.x),je=ie,be=4*se;V.interlaced===!0&&(be+=4*n*7);for(var he=8,ge=0,ke=Z.length;ge=ce&&(be=4*se+4*n*(he-1),je=ie+(ue+se)*(he<<1),he>>=1)),Te===le)je+=4;else{var Me=s[Q+3*Te],Oe=s[Q+3*Te+1],Se=s[Q+3*Te+2];H[je++]=Se,H[je++]=Oe,H[je++]=Me,H[je++]=255}--ne}},this.decodeAndBlitFrameRGBA=function($,H){var V=this.frameInfo($),K=V.width*V.height;if(K>536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");var Z=new Uint8Array(K);fNt(s,V.data_offset,Z,K);var Q=V.palette_offset,le=V.transparent_index;le===null&&(le=256);var ue=V.width,se=n-ue,ne=ue,ie=4*(V.y*n+V.x),ce=4*((V.y+V.height)*n+V.x),je=ie,be=4*se;V.interlaced===!0&&(be+=4*n*7);for(var he=8,ge=0,ke=Z.length;ge=ce&&(be=4*se+4*n*(he-1),je=ie+(ue+se)*(he<<1),he>>=1)),Te===le)je+=4;else{var Me=s[Q+3*Te],Oe=s[Q+3*Te+1],Se=s[Q+3*Te+2];H[je++]=Me,H[je++]=Oe,H[je++]=Se,H[je++]=255}--ne}}}function fNt(s,t,n,r){for(var a=s[t++],i=1<>=c,u-=c,y!==i){if(y===l)break;for(var v=yi;)N=f[N]>>8,++b;var S=N;if(m+b+(v!==y?1:0)>r)return void lm.log("Warning, gif stream longer than expected.");n[m++]=S;var A=m+=b;for(v!==y&&(n[m++]=S),N=v;b--;)N=f[N],n[--A]=255&N,N>>=8;x!==null&&o<4096&&(f[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&&lm.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 L9e(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),p=new Array(64),f=new Array(64),x=[],y=0,v=7,b=new Array(64),N=new Array(64),S=new Array(64),A=new Array(256),T=new Array(2048),L=[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],M=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],I=[0,1,2,3,4,5,6,7,8,9,10,11],R=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],z=[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],$=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],H=[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],K=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function Z(ie,ce){for(var je=0,be=0,he=new Array,ge=1;ge<=16;ge++){for(var ke=1;ke<=ie[ge];ke++)he[ce[be]]=[],he[ce[be]][0]=je,he[ce[be]][1]=ge,be++,je++;je*=2}return he}function Q(ie){for(var ce=ie[0],je=ie[1]-1;je>=0;)ce&1<>8&255),le(255&ie)}function se(ie,ce,je,be,he){for(var ge,ke=he[0],Te=he[240],Me=function(qe,Ze){var Ue,Ye,Ge,He,tt,pt,ft,qt,Ut,Wt,us=0;for(Ut=0;Ut<8;++Ut){Ue=qe[us],Ye=qe[us+1],Ge=qe[us+2],He=qe[us+3],tt=qe[us+4],pt=qe[us+5],ft=qe[us+6];var zt=Ue+(qt=qe[us+7]),bt=Ue-qt,As=Ye+ft,vt=Ye-ft,Ws=Ge+pt,on=Ge-pt,Ms=He+tt,dn=He-tt,rn=zt+Ms,br=zt-Ms,Gn=As+Ws,On=As-Ws;qe[us]=rn+Gn,qe[us+4]=rn-Gn;var Rr=.707106781*(On+br);qe[us+2]=br+Rr,qe[us+6]=br-Rr;var cr=.382683433*((rn=dn+on)-(On=vt+bt)),Hs=.5411961*rn+cr,_r=1.306562965*On+cr,nn=.707106781*(Gn=on+vt),Zn=bt+nn,es=bt-nn;qe[us+5]=es+Hs,qe[us+3]=es-Hs,qe[us+1]=Zn+_r,qe[us+7]=Zn-_r,us+=8}for(us=0,Ut=0;Ut<8;++Ut){Ue=qe[us],Ye=qe[us+8],Ge=qe[us+16],He=qe[us+24],tt=qe[us+32],pt=qe[us+40],ft=qe[us+48];var ar=Ue+(qt=qe[us+56]),Hn=Ue-qt,kn=Ye+ft,Un=Ye-ft,sn=Ge+pt,un=Ge-pt,Ar=He+tt,fs=He-tt,ot=ar+Ar,mt=ar-Ar,Nt=kn+sn,Pt=kn-sn;qe[us]=ot+Nt,qe[us+32]=ot-Nt;var ts=.707106781*(Pt+mt);qe[us+16]=mt+ts,qe[us+48]=mt-ts;var ls=.382683433*((ot=fs+un)-(Pt=Un+Hn)),Is=.5411961*ot+ls,ps=1.306562965*Pt+ls,Ht=.707106781*(Nt=un+Un),Xs=Hn+Ht,Rs=Hn-Ht;qe[us+40]=Rs+Is,qe[us+24]=Rs-Is,qe[us+8]=Xs+ps,qe[us+56]=Xs-ps,us++}for(Ut=0;Ut<64;++Ut)Wt=qe[Ut]*Ze[Ut],p[Ut]=Wt>0?Wt+.5|0:Wt-.5|0;return p}(ie,ce),Oe=0;Oe<64;++Oe)f[L[Oe]]=Me[Oe];var Se=f[0]-je;je=f[0],Se==0?Q(be[0]):(Q(be[m[ge=32767+Se]]),Q(h[ge]));for(var Qe=63;Qe>0&&f[Qe]==0;)Qe--;if(Qe==0)return Q(ke),je;for(var Ae,Fe=1;Fe<=Qe;){for(var Ne=Fe;f[Fe]==0&&Fe<=Qe;)++Fe;var $e=Fe-Ne;if($e>=16){Ae=$e>>4;for(var Ve=1;Ve<=Ae;++Ve)Q(Te);$e&=15}ge=32767+f[Fe],Q(he[($e<<4)+m[ge]]),Q(h[ge]),Fe++}return Qe!=63&&Q(ke),je}function ne(ie){ie=Math.min(Math.max(ie,1),100),i!=ie&&(function(ce){for(var je=[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],be=0;be<64;be++){var he=l((je[be]*ce+50)/100);he=Math.min(Math.max(he,1),255),o[L[be]]=he}for(var ge=[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],ke=0;ke<64;ke++){var Te=l((ge[ke]*ce+50)/100);Te=Math.min(Math.max(Te,1),255),c[L[ke]]=Te}for(var Me=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379],Oe=0,Se=0;Se<8;Se++)for(var Qe=0;Qe<8;Qe++)d[Oe]=1/(o[L[Oe]]*Me[Se]*Me[Qe]*8),u[Oe]=1/(c[L[Oe]]*Me[Se]*Me[Qe]*8),Oe++}(ie<50?Math.floor(5e3/ie):Math.floor(200-2*ie)),i=ie)}this.encode=function(ie,ce){ce&&ne(ce),x=new Array,y=0,v=7,ue(65496),ue(65504),ue(16),le(74),le(70),le(73),le(70),le(0),le(1),le(1),le(0),ue(1),ue(1),le(0),le(0),function(){ue(65499),ue(132),le(0);for(var Ye=0;Ye<64;Ye++)le(o[Ye]);le(1);for(var Ge=0;Ge<64;Ge++)le(c[Ge])}(),function(Ye,Ge){ue(65472),ue(17),le(8),ue(Ge),ue(Ye),le(3),le(1),le(17),le(0),le(2),le(17),le(1),le(3),le(17),le(1)}(ie.width,ie.height),function(){ue(65476),ue(418),le(0);for(var Ye=0;Ye<16;Ye++)le(M[Ye+1]);for(var Ge=0;Ge<=11;Ge++)le(I[Ge]);le(16);for(var He=0;He<16;He++)le(R[He+1]);for(var tt=0;tt<=161;tt++)le(z[tt]);le(1);for(var pt=0;pt<16;pt++)le($[pt+1]);for(var ft=0;ft<=11;ft++)le(H[ft]);le(17);for(var qt=0;qt<16;qt++)le(V[qt+1]);for(var Ut=0;Ut<=161;Ut++)le(K[Ut])}(),ue(65498),ue(12),le(3),le(1),le(0),le(2),le(17),le(3),le(17),le(0),le(63),le(0);var je=0,be=0,he=0;y=0,v=7,this.encode.displayName="_encode_";for(var ge,ke,Te,Me,Oe,Se,Qe,Ae,Fe,Ne=ie.data,$e=ie.width,Ve=ie.height,qe=4*$e,Ze=0;Ze>3)*qe+(Qe=4*(7&Fe)),Ze+Ae>=Ve&&(Se-=qe*(Ze+1+Ae-Ve)),ge+Qe>=qe&&(Se-=ge+Qe-qe+4),ke=Ne[Se++],Te=Ne[Se++],Me=Ne[Se++],b[Fe]=(T[ke]+T[Te+256|0]+T[Me+512|0]>>16)-128,N[Fe]=(T[ke+768|0]+T[Te+1024|0]+T[Me+1280|0]>>16)-128,S[Fe]=(T[ke+1280|0]+T[Te+1536|0]+T[Me+1792|0]>>16)-128;je=se(b,d,je,t,r),be=se(N,u,be,n,a),he=se(S,u,he,n,a),ge+=32}Ze+=8}if(v>=0){var Ue=[];Ue[1]=v+1,Ue[0]=(1<$;$++)if(I[R+$]!=z.charCodeAt($))return!0;return!1}function r(I,R,z,$,H){for(var V=0;VV+1?[]:new R),!(K.length>>0;Ee&ht;)ht>>>=1;return ht?(Ee&ht-1)+ht:Ee}function z(Ee,ze,ht,_t,Jt){t(!(_t%ht));do Ee[ze+(_t-=ht)]=Jt;while(0<_t)}function $(Ee,ze,ht,_t,Jt){if(t(2328>=Jt),512>=Jt)var cs=i(512);else if((cs=i(Jt))==null)return 0;return function(gs,Cs,Ps,Qs,En,Xn){var Js,Fn,rr=Cs,Tr=1<Js;++Js){if(vr[Js]>1<(yl-=vr[Js]))return 0;for(;0=Js;++Js,En<<=1){if(Mi+=yl<<=1,0>(yl-=vr[Js]))return 0;for(;0wa&&!(0>=(Vr-=vr[wa]));)++wa,Vr<<=1;Tr+=Ui=1<<(Vr=wa-Ps),gs[Cs+(wa=Xi&ga)].g=Vr+Ps,gs[Cs+wa].value=rr-Cs-wa}Qs.g=Js-Ps,Qs.value=Xn[Fn++],z(gs,rr+(Xi>>Ps),En,Ui,Qs),Xi=R(Xi,Js)}}return Mi!=2*qn[15]-1?0:Tr}(Ee,ze,ht,_t,Jt,cs)}function H(){this.value=this.g=0}function V(){this.value=this.g=0}function K(){this.G=l(5,H),this.H=i(5),this.jc=this.Qb=this.qb=this.nd=0,this.pd=l(bc,V)}function Z(Ee,ze,ht,_t){t(Ee!=null),t(ze!=null),t(2147483648>_t),Ee.Ca=254,Ee.I=0,Ee.b=-8,Ee.Ka=0,Ee.oa=ze,Ee.pa=ht,Ee.Jd=ze,Ee.Yc=ht+_t,Ee.Zc=4<=_t?ht+_t-4+1:ht,ke(Ee)}function Q(Ee,ze){for(var ht=0;0_t),Ee.Sb=_t,Ee.Ra=0,Ee.u=0,Ee.h=0,4<_t&&(_t=4),Jt=0;Jt<_t;++Jt)cs+=ze[ht+Jt]<<8*Jt;Ee.Ra=cs,Ee.bb=_t,Ee.oa=ze,Ee.pa=ht}function se(Ee){for(;8<=Ee.u&&Ee.bb>>=8,Ee.Ra+=Ee.oa[Ee.pa+Ee.bb]<>>0,++Ee.bb,Ee.u-=8;be(Ee)&&(Ee.h=1,Ee.u=0)}function ne(Ee,ze){if(t(0<=ze),!Ee.h&&ze<=gp){var ht=je(Ee)&Da[ze];return Ee.u+=ze,se(Ee),ht}return Ee.h=1,Ee.u=0}function ie(){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 je(Ee){return Ee.Ra>>>(Ee.u&Ud-1)>>>0}function be(Ee){return t(Ee.bb<=Ee.Sb),Ee.h||Ee.bb==Ee.Sb&&Ee.u>Ud}function he(Ee,ze){Ee.u=ze,Ee.h=be(Ee)}function ge(Ee){Ee.u>=fa&&(t(Ee.u>=fa),se(Ee))}function ke(Ee){t(Ee!=null&&Ee.oa!=null),Ee.pa>>0,Ee.b+=8):(t(Ee!=null&&Ee.oa!=null),Ee.paEe.b&&ke(Ee);var _t=Ee.b,Jt=ht*ze>>>8,cs=(Ee.I>>>_t>Jt)+0;for(cs?(ht-=Jt,Ee.I-=Jt+1<<_t>>>0):ht=Jt+1,_t=ht,Jt=0;256<=_t;)Jt+=8,_t>>=8;return _t=7^Jt+Px[_t],Ee.b-=_t,Ee.Ca=(ht<<_t)-1,cs}function Oe(Ee,ze,ht){Ee[ze+0]=ht>>24&255,Ee[ze+1]=ht>>16&255,Ee[ze+2]=ht>>8&255,Ee[ze+3]=255&ht}function Se(Ee,ze){return Ee[ze+0]|Ee[ze+1]<<8}function Qe(Ee,ze){return Se(Ee,ze)|Ee[ze+2]<<16}function Ae(Ee,ze){return Se(Ee,ze)|Se(Ee,ze+2)<<16}function Fe(Ee,ze){var ht=1<=Jt||0>=cs?0:(ht[0]=Jt,_t[0]=cs,1)}function qe(Ee,ze){return Ee+(1<>>ze}function Ze(Ee,ze){return((4278255360&Ee)+(4278255360&ze)>>>0&4278255360)+((16711935&Ee)+(16711935&ze)>>>0&16711935)>>>0}function Ue(Ee,ze){I[ze]=function(ht,_t,Jt,cs,gs,Cs,Ps){var Qs;for(Qs=0;Qs>>1)+(Ee&ze)>>>0}function He(Ee){return 0<=Ee&&256>Ee?Ee:0>Ee?0:255>1))}function pt(Ee,ze,ht){return Math.abs(ze-ht)-Math.abs(Ee-ht)}function ft(Ee,ze,ht,_t,Jt,cs,gs){for(_t=cs[gs-1],ht=0;ht>8&255,Ps=16711935&(Ps=(Ps=16711935&gs)+((Cs<<16)+Cs));_t[Jt+cs]=(4278255360&gs)+Ps>>>0}}function Ut(Ee,ze){ze.jd=255&Ee,ze.hd=Ee>>8&255,ze.ud=Ee>>16&255}function Wt(Ee,ze,ht,_t,Jt,cs){var gs;for(gs=0;gs<_t;++gs){var Cs=ze[ht+gs],Ps=Cs>>>8,Qs=Cs,En=255&(En=(En=Cs>>>16)+((Ee.jd<<24>>24)*(Ps<<24>>24)>>>5));Qs=255&(Qs=(Qs+=(Ee.hd<<24>>24)*(Ps<<24>>24)>>>5)+((Ee.ud<<24>>24)*(En<<24>>24)>>>5)),Jt[cs+gs]=(4278255360&Cs)+(En<<16)+Qs}}function us(Ee,ze,ht,_t,Jt){I[ze]=function(cs,gs,Cs,Ps,Qs,En,Xn,Js,Fn){for(Ps=Xn;Ps>cs.b,Fn=cs.Ea,rr=cs.K[0],Tr=cs.w;if(8>Js)for(cs=(1<>=Js}else I["VP8LMapColor"+ht](Ps,Qs,rr,Tr,En,Xn,gs,Cs,Fn)}}function zt(Ee,ze,ht,_t,Jt){for(ht=ze+ht;ze>16&255,_t[Jt++]=cs>>8&255,_t[Jt++]=255&cs}}function bt(Ee,ze,ht,_t,Jt){for(ht=ze+ht;ze>16&255,_t[Jt++]=cs>>8&255,_t[Jt++]=255&cs,_t[Jt++]=cs>>24&255}}function As(Ee,ze,ht,_t,Jt){for(ht=ze+ht;ze>16&240|gs>>12&15,gs=240&gs|gs>>28&15;_t[Jt++]=cs,_t[Jt++]=gs}}function vt(Ee,ze,ht,_t,Jt){for(ht=ze+ht;ze>16&248|gs>>13&7,gs=gs>>5&224|gs>>3&31;_t[Jt++]=cs,_t[Jt++]=gs}}function Ws(Ee,ze,ht,_t,Jt){for(ht=ze+ht;ze>8&255,_t[Jt++]=cs>>16&255}}function on(Ee,ze,ht,_t,Jt,cs){if(cs==0)for(ht=ze+ht;ze>24|cs[1]>>8&65280|cs[2]<<8&16711680|cs[3]<<24)>>>0),Jt+=32;else r(_t,Jt,Ee,ze,ht)}function Ms(Ee,ze){I[ze][0]=I[Ee+"0"],I[ze][1]=I[Ee+"1"],I[ze][2]=I[Ee+"2"],I[ze][3]=I[Ee+"3"],I[ze][4]=I[Ee+"4"],I[ze][5]=I[Ee+"5"],I[ze][6]=I[Ee+"6"],I[ze][7]=I[Ee+"7"],I[ze][8]=I[Ee+"8"],I[ze][9]=I[Ee+"9"],I[ze][10]=I[Ee+"10"],I[ze][11]=I[Ee+"11"],I[ze][12]=I[Ee+"12"],I[ze][13]=I[Ee+"13"],I[ze][14]=I[Ee+"0"],I[ze][15]=I[Ee+"0"]}function dn(Ee){return Ee==w1||Ee==DN||Ee==Pj||Ee==A0}function rn(){this.eb=[],this.size=this.A=this.fb=0}function br(){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 Gn(){this.Rd=this.height=this.width=this.S=0,this.f={},this.f.RGBA=new rn,this.f.kb=new br,this.sd=null}function On(){this.width=[0],this.height=[0],this.Pd=[0],this.Qd=[0],this.format=[0]}function Rr(){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 cr(Ee){return alert("todo:WebPSamplerProcessPlane"),Ee.T}function Hs(Ee,ze){var ht=Ee.T,_t=ze.ba.f.RGBA,Jt=_t.eb,cs=_t.fb+Ee.ka*_t.A,gs=Df[ze.ba.S],Cs=Ee.y,Ps=Ee.O,Qs=Ee.f,En=Ee.N,Xn=Ee.ea,Js=Ee.W,Fn=ze.cc,rr=ze.dc,Tr=ze.Mc,vr=ze.Nc,qn=Ee.ka,Vr=Ee.ka+Ee.T,wa=Ee.U,ga=wa+1>>1;for(qn==0?gs(Cs,Ps,null,null,Qs,En,Xn,Js,Qs,En,Xn,Js,Jt,cs,null,null,wa):(gs(ze.ec,ze.fc,Cs,Ps,Fn,rr,Tr,vr,Qs,En,Xn,Js,Jt,cs-_t.A,Jt,cs,wa),++ht);qn+2ht,Jt=ht==Lb||ht==Rf||ht==Cv||ht==Ey||ht==12||dn(ht);if(ze.memory=null,ze.Ib=null,ze.Jb=null,ze.Nd=null,!Hl(ze.Oa,Ee,Jt?11:12))return 0;if(Jt&&dn(ht)&&$m(),Ee.da)alert("todo:use_scaling");else{if(_t){if(ze.Ib=cr,Ee.Kb){if(ht=Ee.U+1>>1,ze.memory=i(Ee.U+2*ht),ze.memory==null)return 0;ze.ec=ze.memory,ze.fc=0,ze.cc=ze.ec,ze.dc=ze.fc+Ee.U,ze.Mc=ze.cc,ze.Nc=ze.dc+ht,ze.Ib=Hs,$m()}}else alert("todo:EmitYUV");Jt&&(ze.Jb=_r,_t&&vc())}if(_t&&!Fj){for(Ee=0;256>Ee;++Ee)zj[Ee]=89858*(Ee-128)+Dj>>Av,BS[Ee]=-22014*(Ee-128)+Dj,zN[Ee]=-45773*(Ee-128),Z_[Ee]=113618*(Ee-128)+Dj>>Av;for(Ee=Oj;Ee>Av,PE[Ee-Oj]=Ja(ze,255),X_[Ee-Oj]=Ja(ze+8>>4,15);Fj=1}return 1}function Zn(Ee){var ze=Ee.ma,ht=Ee.U,_t=Ee.T;return t(!(1&Ee.ka)),0>=ht||0>=_t?0:(ht=ze.Ib(Ee,ze),ze.Jb!=null&&ze.Jb(Ee,ze,ht),ze.Dc+=ht,1)}function es(Ee){Ee.ma.memory=null}function ar(Ee,ze,ht,_t){return ne(Ee,8)!=47?0:(ze[0]=ne(Ee,14)+1,ht[0]=ne(Ee,14)+1,_t[0]=ne(Ee,1),ne(Ee,3)!=0?0:!Ee.h)}function Hn(Ee,ze){if(4>Ee)return Ee+1;var ht=Ee-2>>1;return(2+(1&Ee)<>4)*Ee+(8-(15&ht)))?ht:1;var ht}function Un(Ee,ze,ht){var _t=je(ht),Jt=Ee[ze+=255&_t].g-8;return 0>>0,t(8>=ht.g),Ee.g}function un(Ee,ze,ht){var _t=Ee.xc;return t((ze=_t==0?0:Ee.vc[Ee.md*(ht>>_t)+(ze>>_t)])>Ui.b)*Mi;Trwa&&(Hi=wa),(0,Qu[ic[cu++]>>8&15])(Js,Fn+ +vl,qn,Vr+vl-wa,Hi-vl,qn,Vr+vl),vl=Hi}Fn+=wa,Vr+=wa,++Tr&Xi||(Ui+=Mi)}Xn!=Qs.nc&&r(Ps,Cs-rr,Ps,Cs+(Xn-En-1)*rr,rr);break;case 1:for(rr=Js,vr=Fn,wa=(Js=Qs.Ea)-(Vr=Js&~(qn=(Fn=1<>Qs.b)*Tr;En=Jt),0cs.o&&(_t=cs.o),ht=_t?ht=0:(Jt[0]+=4*cs.v,cs.ka=ht-cs.j,cs.U=cs.va-cs.v,cs.T=_t-ht,ht=1),ht){if(Cs=Cs[0],11>(ht=Ee.ca).S){var En=ht.f.RGBA,Xn=(_t=ht.S,Jt=cs.U,cs=cs.T,Qs=En.eb,En.A),Js=cs;for(En=En.fb+Ee.Ma*En.A;0_t){var Jt=Ee.l.width,cs=ht.ca,gs=ht.tb+Jt*_t,Cs=Ee.V,Ps=Ee.Ba+Ee.c*_t,Qs=Ee.gc;t(Ee.ab==1),t(Qs[0].hc==3),Yp(Qs[0],_t,ze,Cs,Ps,cs,gs),mt(ht,_t,ze,cs,gs,Jt)}Ee.C=Ee.Ma=ze}function Pt(Ee,ze,ht,_t,Jt,cs,gs){var Cs=Ee.$/_t,Ps=Ee.$%_t,Qs=Ee.m,En=Ee.s,Xn=ht+Ee.$,Js=Xn;Jt=ht+_t*Jt;var Fn=ht+_t*cs,rr=280+En.ua,Tr=Ee.Pb?Cs:16777216,vr=0=Tr){var Xi=Xn-ht;t((Tr=Ee).Pb),Tr.wd=Tr.m,Tr.xd=Xi,0yl.g?(he(ga,ga.u+yl.g),Xi[Mi]=yl.value,ga=0):(he(ga,ga.u+yl.g-256),t(256<=yl.value),ga=yl.value),ga==0&&(wa=!0)}else ga=Un(Vr.G[0],Vr.H[0],Qs);if(Qs.h)break;if(wa||256>ga){if(!wa)if(Vr.nd)ze[Xn]=(Vr.qb|ga<<8)>>>0;else{if(ge(Qs),wa=Un(Vr.G[1],Vr.H[1],Qs),ge(Qs),Xi=Un(Vr.G[2],Vr.H[2],Qs),Mi=Un(Vr.G[3],Vr.H[3],Qs),Qs.h)break;ze[Xn]=(Mi<<24|wa<<16|ga<<8|Xi)>>>0}if(wa=!1,++Xn,++Ps>=_t&&(Ps=0,++Cs,gs!=null&&Cs<=cs&&!(Cs%16)&&gs(Ee,Cs),vr!=null))for(;Js>>vr.Mb]=ga}else if(280>ga){if(ga=Hn(ga-256,Qs),Xi=Un(Vr.G[4],Vr.H[4],Qs),ge(Qs),Xi=kn(_t,Xi=Hn(Xi,Qs)),Qs.h)break;if(Xn-ht=_t;)Ps-=_t,++Cs,gs!=null&&Cs<=cs&&!(Cs%16)&&gs(Ee,Cs);if(t(Xn<=Jt),Ps&qn&&(Vr=un(En,Ps,Cs)),vr!=null)for(;Js>>vr.Mb]=ga}else{if(!(ga>>vr.Mb]=ga;ga=Xn,t(!(wa>>>(Xi=vr).Xa)),ze[ga]=Xi.X[wa],wa=!0}wa||t(Qs.h==be(Qs))}if(Ee.Pb&&Qs.h&&Xncs?cs:Cs),Ee.a=0,Ee.$=Xn-ht}return 1}return Ee.a=3,0}function ts(Ee){t(Ee!=null),Ee.vc=null,Ee.yc=null,Ee.Ya=null;var ze=Ee.Wa;ze!=null&&(ze.X=null),Ee.vb=null,t(Ee!=null)}function ls(){var Ee=new Es;return Ee==null?null:(Ee.a=0,Ee.xb=E3,Ms("Predictor","VP8LPredictors"),Ms("Predictor","VP8LPredictors_C"),Ms("PredictorAdd","VP8LPredictorsAdd"),Ms("PredictorAdd","VP8LPredictorsAdd_C"),Ny=qt,Sd=Wt,Zp=zt,v1=bt,b1=As,Xc=vt,Lx=Ws,I.VP8LMapColor32b=gd,I.VP8LMapColor8b=em,Ee)}function Is(Ee,ze,ht,_t,Jt){var cs=1,gs=[Ee],Cs=[ze],Ps=_t.m,Qs=_t.s,En=null,Xn=0;e:for(;;){if(ht)for(;cs&&ne(Ps,1);){var Js=gs,Fn=Cs,rr=_t,Tr=1,vr=rr.m,qn=rr.gc[rr.ab],Vr=ne(vr,2);if(rr.Oc&1<=rr.ab),Vr){case 0:case 1:qn.b=ne(vr,3)+2,Tr=Is(qe(qn.Ea,qn.b),qe(qn.nc,qn.b),0,rr,qn.K),qn.K=qn.K[0];break;case 3:var wa,ga=ne(vr,8)+1,Xi=16>Ui.b),cu=i(ic);if(cu==null)wa=0;else{var vl=Ui.K[0],Hi=Ui.w;for(cu[0]=Ui.K[0][0],Mi=1;Mi<1*yl;++Mi)cu[Mi]=Ze(vl[Hi+Mi],cu[Mi-1]);for(;Mi<4*ic;++Mi)cu[Mi]=0;Ui.K[0]=null,Ui.K[0]=cu,wa=1}}Tr=wa;break;case 2:break;default:t(0)}cs=Tr}}if(gs=gs[0],Cs=Cs[0],cs&&ne(Ps,1)&&!(cs=1<=(Xn=ne(Ps,4))&&11>=Xn)){_t.a=3;break e}var ci;if(ci=cs)t:{var wl,vo,ul,su=_t,vm=gs,nu=Cs,Lu=Xn,Nu=ht,Ff=su.m,qd=su.s,Vc=[null],Ad=1,th=0,Jc=ME[Lu];s:for(;;){if(Nu&&ne(Ff,1)){var hh=ne(Ff,3)+2,xp=qe(vm,hh),xd=qe(nu,hh),Ih=xp*xd;if(!Is(xp,xd,0,su,Vc))break s;for(Vc=Vc[0],qd.xc=hh,wl=0;wl>8&65535;Vc[wl]=wc,wc>=Ad&&(Ad=wc+1)}}if(Ff.h)break s;for(vo=0;5>vo;++vo){var mh=IS[vo];!vo&&0=du),Bf=zf;var vp=i(th);if(Bf==null||vp==null||yp==null){su.a=1;break s}var rm=yp;for(wl=ul=0;wlvo;++vo){mh=IS[vo],wr[vo]=rm,To[vo]=ul,!vo&&0zb)break n}else Mv=zb;for(sx=0;sxUb)Hj[sx++]=Ub,Ub!=0&&(Py=Ub);else{var P3=Ub==16,US=Ub-16,k1=_o[US],S1=ne(sh,k3[US])+k1;if(sx+S1>zb)break n;for(var L3=P3?Py:0;0=vo){var C1,P0=vp[0];for(C1=1;C1P0&&(P0=vp[C1]);Gc+=P0}}if(Hc.nd=Oc,Hc.Qb=0,Oc&&(Hc.qb=(wr[3][To[3]+0].value<<24|wr[1][To[1]+0].value<<16|wr[2][To[2]+0].value)>>>0,cd==0&&256>wr[0][To[0]+0].value&&(Hc.Qb=1,Hc.qb+=wr[0][To[0]+0].value<<8)),Hc.jc=!Hc.Qb&&6>Gc,Hc.jc){var BN,ph=Hc;for(BN=0;BN>=sn($f,8,uu),Gm>>=sn(ph.G[1][ph.H[1]+Gm],16,uu),Gm>>=sn(ph.G[2][ph.H[2]+Gm],0,uu),sn(ph.G[3][ph.H[3]+Gm],24,uu))}}}qd.vc=Vc,qd.Wb=Ad,qd.Ya=Bf,qd.yc=yp,ci=1;break t}ci=0}if(!(cs=ci)){_t.a=3;break e}if(0_t+1?[]:0),!(Jt.length<_t+1));gs++)ze(ht[gs],_t+1,Jt)}(Ee,0,[3,11]),Ee}()}function ma(){this.jb=i(3),this.Wc=o([4,8],Qr),this.Xc=o([4,17],Qr)}function qr(){this.Pc=this.wb=this.Tb=this.zd=0,this.vd=new i(4),this.od=new i(4)}function Zr(){this.ld=this.La=this.dd=this.tc=0}function Jr(){this.Na=this.la=0}function ha(){this.Sc=[0,0],this.Eb=[0,0],this.Qc=[0,0],this.ia=this.lc=0}function Fa(){this.ad=i(384),this.Za=0,this.Ob=i(16),this.$b=this.Ad=this.ia=this.Gc=this.Hc=this.Dd=0}function Fo(){this.uc=this.M=this.Nb=0,this.wa=Array(new Zr),this.Y=0,this.ya=Array(new Fa),this.aa=0,this.l=new Co}function Xo(){this.y=i(16),this.f=i(8),this.ea=i(8)}function Vi(){this.cb=this.a=0,this.sc="",this.m=new ie,this.Od=new Xs,this.Kc=new Rs,this.ed=new qr,this.Qa=new zn,this.Ic=this.$c=this.Aa=0,this.D=new Fo,this.Xb=this.Va=this.Hb=this.zb=this.yb=this.Ub=this.za=0,this.Jc=l(8,ie),this.ia=0,this.pb=l(4,ha),this.Pa=new ma,this.Bd=this.kc=0,this.Ac=[],this.Bc=0,this.zc=[0,0,0,0],this.Gd=Array(new Xo),this.Hd=0,this.rb=Array(new Jr),this.sb=0,this.wa=Array(new Zr),this.Y=0,this.oc=[],this.pc=0,this.sa=[],this.ta=0,this.qa=[],this.ra=0,this.Ha=[],this.B=this.R=this.Ia=0,this.Ec=[],this.M=this.ja=this.Vb=this.Fc=0,this.ya=Array(new Fa),this.L=this.aa=0,this.gd=o([4,2],Zr),this.ga=null,this.Fa=[],this.Cc=this.qc=this.P=0,this.Gb=[],this.Uc=0,this.mb=[],this.nb=0,this.rc=[],this.Ga=this.Vc=0}function Ja(Ee,ze){return 0>Ee?0:Ee>ze?ze:Ee}function Co(){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 Go(){var Ee=new Vi;return Ee!=null&&(Ee.a=0,Ee.sc="OK",Ee.cb=0,Ee.Xb=0,Ib||(Ib=_a)),Ee}function hi(Ee,ze,ht){return Ee.a==0&&(Ee.a=ze,Ee.sc=ht,Ee.cb=0),0}function Qo(Ee,ze,ht){return 3<=ht&&Ee[ze+0]==157&&Ee[ze+1]==1&&Ee[ze+2]==42}function Ao(Ee,ze){if(Ee==null)return 0;if(Ee.a=0,Ee.sc="OK",ze==null)return hi(Ee,2,"null VP8Io passed to VP8GetHeaders()");var ht=ze.data,_t=ze.w,Jt=ze.ha;if(4>Jt)return hi(Ee,7,"Truncated header.");var cs=ht[_t+0]|ht[_t+1]<<8|ht[_t+2]<<16,gs=Ee.Od;if(gs.Rb=!(1&cs),gs.td=cs>>1&7,gs.yd=cs>>4&1,gs.ub=cs>>5,3Jt)return hi(Ee,7,"cannot parse picture header");if(!Qo(ht,_t,Jt))return hi(Ee,3,"Bad code word");Cs.c=16383&(ht[_t+4]<<8|ht[_t+3]),Cs.Td=ht[_t+4]>>6,Cs.i=16383&(ht[_t+6]<<8|ht[_t+5]),Cs.Ud=ht[_t+6]>>6,_t+=7,Jt-=7,Ee.za=Cs.c+15>>4,Ee.Ub=Cs.i+15>>4,ze.width=Cs.c,ze.height=Cs.i,ze.Da=0,ze.j=0,ze.v=0,ze.va=ze.width,ze.o=ze.height,ze.da=0,ze.ib=ze.width,ze.hb=ze.height,ze.U=ze.width,ze.T=ze.height,a((cs=Ee.Pa).jb,0,255,cs.jb.length),t((cs=Ee.Qa)!=null),cs.Cb=0,cs.Bb=0,cs.Fb=1,a(cs.Zb,0,0,cs.Zb.length),a(cs.Lb,0,0,cs.Lb)}if(gs.ub>Jt)return hi(Ee,7,"bad partition length");Z(cs=Ee.m,ht,_t,gs.ub),_t+=gs.ub,Jt-=gs.ub,gs.Rb&&(Cs.Ld=Te(cs),Cs.Kd=Te(cs)),Cs=Ee.Qa;var Ps,Qs=Ee.Pa;if(t(cs!=null),t(Cs!=null),Cs.Cb=Te(cs),Cs.Cb){if(Cs.Bb=Te(cs),Te(cs)){for(Cs.Fb=Te(cs),Ps=0;4>Ps;++Ps)Cs.Zb[Ps]=Te(cs)?le(cs,7):0;for(Ps=0;4>Ps;++Ps)Cs.Lb[Ps]=Te(cs)?le(cs,6):0}if(Cs.Bb)for(Ps=0;3>Ps;++Ps)Qs.jb[Ps]=Te(cs)?Q(cs,8):255}else Cs.Bb=0;if(cs.Ka)return hi(Ee,3,"cannot parse segment header");if((Cs=Ee.ed).zd=Te(cs),Cs.Tb=Q(cs,6),Cs.wb=Q(cs,3),Cs.Pc=Te(cs),Cs.Pc&&Te(cs)){for(Qs=0;4>Qs;++Qs)Te(cs)&&(Cs.vd[Qs]=le(cs,6));for(Qs=0;4>Qs;++Qs)Te(cs)&&(Cs.od[Qs]=le(cs,6))}if(Ee.L=Cs.Tb==0?0:Cs.zd?1:2,cs.Ka)return hi(Ee,3,"cannot parse filter header");var En=Jt;if(Jt=Ps=_t,_t=Ps+En,Cs=En,Ee.Xb=(1<Cs&&(Xn=Cs),Z(Ee.Jc[+En],ht,Ps,Xn),Ps+=Xn,Cs-=Xn,Jt+=3}Z(Ee.Jc[+Qs],ht,Ps,Cs),ht=Ps<_t?0:5}if(ht!=0)return hi(Ee,ht,"cannot parse partitions");for(ht=Q(Ps=Ee.m,7),Jt=Te(Ps)?le(Ps,4):0,_t=Te(Ps)?le(Ps,4):0,Cs=Te(Ps)?le(Ps,4):0,Qs=Te(Ps)?le(Ps,4):0,Ps=Te(Ps)?le(Ps,4):0,En=Ee.Qa,Xn=0;4>Xn;++Xn){if(En.Cb){var Js=En.Zb[Xn];En.Fb||(Js+=ht)}else{if(0>16,8>Fn.Eb[1]&&(Fn.Eb[1]=8),Fn.Qc[0]=K_[Ja(Js+Qs,117)],Fn.Qc[1]=A3[Ja(Js+Ps,127)],Fn.lc=Js+Ps}if(!gs.Rb)return hi(Ee,4,"Not a key frame.");for(Te(cs),gs=Ee.Pa,ht=0;4>ht;++ht){for(Jt=0;8>Jt;++Jt)for(_t=0;3>_t;++_t)for(Cs=0;11>Cs;++Cs)Qs=Me(cs,Rb[ht][Jt][_t][Cs])?Q(cs,8):Y_[ht][Jt][_t][Cs],gs.Wc[ht][Jt].Yb[_t][Cs]=Qs;for(Jt=0;17>Jt;++Jt)gs.Xc[ht][Jt]=gs.Wc[ht][Db[Jt]]}return Ee.kc=Te(cs),Ee.kc&&(Ee.Bd=Q(cs,8)),Ee.cb=1}function _a(Ee,ze,ht,_t,Jt,cs,gs){var Cs=ze[Jt].Yb[ht];for(ht=0;16>Jt;++Jt){if(!Me(Ee,Cs[ht+0]))return Jt;for(;!Me(Ee,Cs[ht+1]);)if(Cs=ze[++Jt].Yb[0],ht=0,Jt==16)return 16;var Ps=ze[Jt+1].Yb;if(Me(Ee,Cs[ht+2])){var Qs=Ee,En=0;if(Me(Qs,(Js=Cs)[(Xn=ht)+3]))if(Me(Qs,Js[Xn+6])){for(Cs=0,Xn=2*(En=Me(Qs,Js[Xn+8]))+(Js=Me(Qs,Js[Xn+9+En])),En=0,Js=yL[Xn];Js[Cs];++Cs)En+=En+Me(Qs,Js[Cs]);En+=3+(8<(Qs=Ee).b&&ke(Qs);var Xn,Js=Qs.b,Fn=(Xn=Qs.Ca>>1)-(Qs.I>>Js)>>31;--Qs.b,Qs.Ca+=Fn,Qs.Ca|=1,Qs.I-=(Xn+1&Fn)<>3),Ee[ze+ht+32*_t]=-256&Jt?0>Jt?0:255:Jt}function Eo(Ee,ze,ht,_t,Jt,cs){li(Ee,ze,0,ht,_t+Jt),li(Ee,ze,1,ht,_t+cs),li(Ee,ze,2,ht,_t-cs),li(Ee,ze,3,ht,_t-Jt)}function gl(Ee){return(20091*Ee>>16)+Ee}function ds(Ee,ze,ht,_t){var Jt,cs=0,gs=i(16);for(Jt=0;4>Jt;++Jt){var Cs=Ee[ze+0]+Ee[ze+8],Ps=Ee[ze+0]-Ee[ze+8],Qs=(35468*Ee[ze+4]>>16)-gl(Ee[ze+12]),En=gl(Ee[ze+4])+(35468*Ee[ze+12]>>16);gs[cs+0]=Cs+En,gs[cs+1]=Ps+Qs,gs[cs+2]=Ps-Qs,gs[cs+3]=Cs-En,cs+=4,ze++}for(Jt=cs=0;4>Jt;++Jt)Cs=(Ee=gs[cs+0]+4)+gs[cs+8],Ps=Ee-gs[cs+8],Qs=(35468*gs[cs+4]>>16)-gl(gs[cs+12]),li(ht,_t,0,0,Cs+(En=gl(gs[cs+4])+(35468*gs[cs+12]>>16))),li(ht,_t,1,0,Ps+Qs),li(ht,_t,2,0,Ps-Qs),li(ht,_t,3,0,Cs-En),cs++,_t+=32}function Gr(Ee,ze,ht,_t){var Jt=Ee[ze+0]+4,cs=35468*Ee[ze+4]>>16,gs=gl(Ee[ze+4]),Cs=35468*Ee[ze+1]>>16;Eo(ht,_t,0,Jt+gs,Ee=gl(Ee[ze+1]),Cs),Eo(ht,_t,1,Jt+cs,Ee,Cs),Eo(ht,_t,2,Jt-cs,Ee,Cs),Eo(ht,_t,3,Jt-gs,Ee,Cs)}function ji(Ee,ze,ht,_t,Jt){ds(Ee,ze,ht,_t),Jt&&ds(Ee,ze+16,ht,_t+4)}function ya(Ee,ze,ht,_t){tm(Ee,ze+0,ht,_t,1),tm(Ee,ze+32,ht,_t+128,1)}function Wi(Ee,ze,ht,_t){var Jt;for(Ee=Ee[ze+0]+4,Jt=0;4>Jt;++Jt)for(ze=0;4>ze;++ze)li(ht,_t,ze,Jt,Ee)}function wi(Ee,ze,ht,_t){Ee[ze+0]&&Ju(Ee,ze+0,ht,_t),Ee[ze+16]&&Ju(Ee,ze+16,ht,_t+4),Ee[ze+32]&&Ju(Ee,ze+32,ht,_t+128),Ee[ze+48]&&Ju(Ee,ze+48,ht,_t+128+4)}function di(Ee,ze,ht,_t){var Jt,cs=i(16);for(Jt=0;4>Jt;++Jt){var gs=Ee[ze+0+Jt]+Ee[ze+12+Jt],Cs=Ee[ze+4+Jt]+Ee[ze+8+Jt],Ps=Ee[ze+4+Jt]-Ee[ze+8+Jt],Qs=Ee[ze+0+Jt]-Ee[ze+12+Jt];cs[0+Jt]=gs+Cs,cs[8+Jt]=gs-Cs,cs[4+Jt]=Qs+Ps,cs[12+Jt]=Qs-Ps}for(Jt=0;4>Jt;++Jt)gs=(Ee=cs[0+4*Jt]+3)+cs[3+4*Jt],Cs=cs[1+4*Jt]+cs[2+4*Jt],Ps=cs[1+4*Jt]-cs[2+4*Jt],Qs=Ee-cs[3+4*Jt],ht[_t+0]=gs+Cs>>3,ht[_t+16]=Qs+Ps>>3,ht[_t+32]=gs-Cs>>3,ht[_t+48]=Qs-Ps>>3,_t+=64}function Dc(Ee,ze,ht){var _t,Jt=ze-32,cs=nm,gs=255-Ee[Jt-1];for(_t=0;_tht;++ht)r(Ee,ze+32*ht,Ee,ze-32,16)}function il(Ee,ze){var ht;for(ht=16;0_t;++_t)a(ze,ht+32*_t,Ee,16)}function fg(Ee,ze){var ht,_t=16;for(ht=0;16>ht;++ht)_t+=Ee[ze-1+32*ht]+Ee[ze+ht-32];Hp(_t>>5,Ee,ze)}function Lh(Ee,ze){var ht,_t=8;for(ht=0;16>ht;++ht)_t+=Ee[ze-1+32*ht];Hp(_t>>4,Ee,ze)}function by(Ee,ze){var ht,_t=8;for(ht=0;16>ht;++ht)_t+=Ee[ze+ht-32];Hp(_t>>4,Ee,ze)}function qo(Ee,ze){Hp(128,Ee,ze)}function bo(Ee,ze,ht){return Ee+2*ze+ht+2>>2}function Ex(Ee,ze){var ht,_t=ze-32;for(_t=new Uint8Array([bo(Ee[_t-1],Ee[_t+0],Ee[_t+1]),bo(Ee[_t+0],Ee[_t+1],Ee[_t+2]),bo(Ee[_t+1],Ee[_t+2],Ee[_t+3]),bo(Ee[_t+2],Ee[_t+3],Ee[_t+4])]),ht=0;4>ht;++ht)r(Ee,ze+32*ht,_t,0,_t.length)}function dp(Ee,ze){var ht=Ee[ze-1],_t=Ee[ze-1+32],Jt=Ee[ze-1+64],cs=Ee[ze-1+96];Oe(Ee,ze+0,16843009*bo(Ee[ze-1-32],ht,_t)),Oe(Ee,ze+32,16843009*bo(ht,_t,Jt)),Oe(Ee,ze+64,16843009*bo(_t,Jt,cs)),Oe(Ee,ze+96,16843009*bo(Jt,cs,cs))}function up(Ee,ze){var ht,_t=4;for(ht=0;4>ht;++ht)_t+=Ee[ze+ht-32]+Ee[ze-1+32*ht];for(_t>>=3,ht=0;4>ht;++ht)a(Ee,ze+32*ht,_t,4)}function gg(Ee,ze){var ht=Ee[ze-1+0],_t=Ee[ze-1+32],Jt=Ee[ze-1+64],cs=Ee[ze-1-32],gs=Ee[ze+0-32],Cs=Ee[ze+1-32],Ps=Ee[ze+2-32],Qs=Ee[ze+3-32];Ee[ze+0+96]=bo(_t,Jt,Ee[ze-1+96]),Ee[ze+1+96]=Ee[ze+0+64]=bo(ht,_t,Jt),Ee[ze+2+96]=Ee[ze+1+64]=Ee[ze+0+32]=bo(cs,ht,_t),Ee[ze+3+96]=Ee[ze+2+64]=Ee[ze+1+32]=Ee[ze+0+0]=bo(gs,cs,ht),Ee[ze+3+64]=Ee[ze+2+32]=Ee[ze+1+0]=bo(Cs,gs,cs),Ee[ze+3+32]=Ee[ze+2+0]=bo(Ps,Cs,gs),Ee[ze+3+0]=bo(Qs,Ps,Cs)}function Vl(Ee,ze){var ht=Ee[ze+1-32],_t=Ee[ze+2-32],Jt=Ee[ze+3-32],cs=Ee[ze+4-32],gs=Ee[ze+5-32],Cs=Ee[ze+6-32],Ps=Ee[ze+7-32];Ee[ze+0+0]=bo(Ee[ze+0-32],ht,_t),Ee[ze+1+0]=Ee[ze+0+32]=bo(ht,_t,Jt),Ee[ze+2+0]=Ee[ze+1+32]=Ee[ze+0+64]=bo(_t,Jt,cs),Ee[ze+3+0]=Ee[ze+2+32]=Ee[ze+1+64]=Ee[ze+0+96]=bo(Jt,cs,gs),Ee[ze+3+32]=Ee[ze+2+64]=Ee[ze+1+96]=bo(cs,gs,Cs),Ee[ze+3+64]=Ee[ze+2+96]=bo(gs,Cs,Ps),Ee[ze+3+96]=bo(Cs,Ps,Ps)}function hp(Ee,ze){var ht=Ee[ze-1+0],_t=Ee[ze-1+32],Jt=Ee[ze-1+64],cs=Ee[ze-1-32],gs=Ee[ze+0-32],Cs=Ee[ze+1-32],Ps=Ee[ze+2-32],Qs=Ee[ze+3-32];Ee[ze+0+0]=Ee[ze+1+64]=cs+gs+1>>1,Ee[ze+1+0]=Ee[ze+2+64]=gs+Cs+1>>1,Ee[ze+2+0]=Ee[ze+3+64]=Cs+Ps+1>>1,Ee[ze+3+0]=Ps+Qs+1>>1,Ee[ze+0+96]=bo(Jt,_t,ht),Ee[ze+0+64]=bo(_t,ht,cs),Ee[ze+0+32]=Ee[ze+1+96]=bo(ht,cs,gs),Ee[ze+1+32]=Ee[ze+2+96]=bo(cs,gs,Cs),Ee[ze+2+32]=Ee[ze+3+96]=bo(gs,Cs,Ps),Ee[ze+3+32]=bo(Cs,Ps,Qs)}function Jd(Ee,ze){var ht=Ee[ze+0-32],_t=Ee[ze+1-32],Jt=Ee[ze+2-32],cs=Ee[ze+3-32],gs=Ee[ze+4-32],Cs=Ee[ze+5-32],Ps=Ee[ze+6-32],Qs=Ee[ze+7-32];Ee[ze+0+0]=ht+_t+1>>1,Ee[ze+1+0]=Ee[ze+0+64]=_t+Jt+1>>1,Ee[ze+2+0]=Ee[ze+1+64]=Jt+cs+1>>1,Ee[ze+3+0]=Ee[ze+2+64]=cs+gs+1>>1,Ee[ze+0+32]=bo(ht,_t,Jt),Ee[ze+1+32]=Ee[ze+0+96]=bo(_t,Jt,cs),Ee[ze+2+32]=Ee[ze+1+96]=bo(Jt,cs,gs),Ee[ze+3+32]=Ee[ze+2+96]=bo(cs,gs,Cs),Ee[ze+3+64]=bo(gs,Cs,Ps),Ee[ze+3+96]=bo(Cs,Ps,Qs)}function Mu(Ee,ze){var ht=Ee[ze-1+0],_t=Ee[ze-1+32],Jt=Ee[ze-1+64],cs=Ee[ze-1+96];Ee[ze+0+0]=ht+_t+1>>1,Ee[ze+2+0]=Ee[ze+0+32]=_t+Jt+1>>1,Ee[ze+2+32]=Ee[ze+0+64]=Jt+cs+1>>1,Ee[ze+1+0]=bo(ht,_t,Jt),Ee[ze+3+0]=Ee[ze+1+32]=bo(_t,Jt,cs),Ee[ze+3+32]=Ee[ze+1+64]=bo(Jt,cs,cs),Ee[ze+3+64]=Ee[ze+2+64]=Ee[ze+0+96]=Ee[ze+1+96]=Ee[ze+2+96]=Ee[ze+3+96]=cs}function kv(Ee,ze){var ht=Ee[ze-1+0],_t=Ee[ze-1+32],Jt=Ee[ze-1+64],cs=Ee[ze-1+96],gs=Ee[ze-1-32],Cs=Ee[ze+0-32],Ps=Ee[ze+1-32],Qs=Ee[ze+2-32];Ee[ze+0+0]=Ee[ze+2+32]=ht+gs+1>>1,Ee[ze+0+32]=Ee[ze+2+64]=_t+ht+1>>1,Ee[ze+0+64]=Ee[ze+2+96]=Jt+_t+1>>1,Ee[ze+0+96]=cs+Jt+1>>1,Ee[ze+3+0]=bo(Cs,Ps,Qs),Ee[ze+2+0]=bo(gs,Cs,Ps),Ee[ze+1+0]=Ee[ze+3+32]=bo(ht,gs,Cs),Ee[ze+1+32]=Ee[ze+3+64]=bo(_t,ht,gs),Ee[ze+1+64]=Ee[ze+3+96]=bo(Jt,_t,ht),Ee[ze+1+96]=bo(cs,Jt,_t)}function _u(Ee,ze){var ht;for(ht=0;8>ht;++ht)r(Ee,ze+32*ht,Ee,ze-32,8)}function zi(Ee,ze){var ht;for(ht=0;8>ht;++ht)a(Ee,ze,Ee[ze-1],8),ze+=32}function zm(Ee,ze,ht){var _t;for(_t=0;8>_t;++_t)a(ze,ht+32*_t,Ee,8)}function Qh(Ee,ze){var ht,_t=8;for(ht=0;8>ht;++ht)_t+=Ee[ze+ht-32]+Ee[ze-1+32*ht];zm(_t>>4,Ee,ze)}function mp(Ee,ze){var ht,_t=4;for(ht=0;8>ht;++ht)_t+=Ee[ze+ht-32];zm(_t>>3,Ee,ze)}function If(Ee,ze){var ht,_t=4;for(ht=0;8>ht;++ht)_t+=Ee[ze-1+32*ht];zm(_t>>3,Ee,ze)}function Jh(Ee,ze){zm(128,Ee,ze)}function Bm(Ee,ze,ht){var _t=Ee[ze-ht],Jt=Ee[ze+0],cs=3*(Jt-_t)+G_[1020+Ee[ze-2*ht]-Ee[ze+ht]],gs=Xp[112+(cs+4>>3)];Ee[ze-ht]=nm[255+_t+Xp[112+(cs+3>>3)]],Ee[ze+0]=nm[255+Jt-gs]}function j0(Ee,ze,ht,_t){var Jt=Ee[ze+0],cs=Ee[ze+ht];return dr[255+Ee[ze-2*ht]-Ee[ze-ht]]>_t||dr[255+cs-Jt]>_t}function N0(Ee,ze,ht,_t){return 4*dr[255+Ee[ze-ht]-Ee[ze+0]]+dr[255+Ee[ze-2*ht]-Ee[ze+ht]]<=_t}function pp(Ee,ze,ht,_t,Jt){var cs=Ee[ze-3*ht],gs=Ee[ze-2*ht],Cs=Ee[ze-ht],Ps=Ee[ze+0],Qs=Ee[ze+ht],En=Ee[ze+2*ht],Xn=Ee[ze+3*ht];return 4*dr[255+Cs-Ps]+dr[255+gs-Qs]>_t?0:dr[255+Ee[ze-4*ht]-cs]<=Jt&&dr[255+cs-gs]<=Jt&&dr[255+gs-Cs]<=Jt&&dr[255+Xn-En]<=Jt&&dr[255+En-Qs]<=Jt&&dr[255+Qs-Ps]<=Jt}function Um(Ee,ze,ht,_t){var Jt=2*_t+1;for(_t=0;16>_t;++_t)N0(Ee,ze+_t,ht,Jt)&&Bm(Ee,ze+_t,ht)}function Tx(Ee,ze,ht,_t){var Jt=2*_t+1;for(_t=0;16>_t;++_t)N0(Ee,ze+_t*ht,1,Jt)&&Bm(Ee,ze+_t*ht,1)}function Qg(Ee,ze,ht,_t){var Jt;for(Jt=3;0>7,qn=18*Vr+63>>7,Vr=9*Vr+63>>7;Ps[Qs-3*En]=nm[255+Ps[Qs-3*En]+Vr],Ps[Qs-2*En]=nm[255+Xn+qn],Ps[Qs-En]=nm[255+Js+vr],Ps[Qs+0]=nm[255+Fn-vr],Ps[Qs+En]=nm[255+rr-qn],Ps[Qs+2*En]=nm[255+Tr-Vr]}ze+=_t}}function ld(Ee,ze,ht,_t,Jt,cs,gs,Cs){for(cs=2*cs+1;0>3)],Tr=Xp[112+(Tr+3>>3)],vr=rr+1>>1;Ps[Qs-2*En]=nm[255+Ps[Qs-2*En]+vr],Ps[Qs-En]=nm[255+Xn+Tr],Ps[Qs+0]=nm[255+Js-rr],Ps[Qs+En]=nm[255+Fn-vr]}ze+=_t}}function Gp(Ee,ze,ht,_t,Jt,cs){zd(Ee,ze,ht,1,16,_t,Jt,cs)}function eu(Ee,ze,ht,_t,Jt,cs){zd(Ee,ze,1,ht,16,_t,Jt,cs)}function Wp(Ee,ze,ht,_t,Jt,cs){var gs;for(gs=3;0Qs?0:255:Qs)&255,Qs=Ps,Jt[cs+Cs]=En}}function Ra(Ee,ze,ht,_t){var Jt=ze.width,cs=ze.o;if(t(Ee!=null&&ze!=null),0>ht||0>=_t||ht+_t>cs)return null;if(!Ee.Cc){if(Ee.ga==null){var gs;if(Ee.ga=new bn,(gs=Ee.ga==null)||(gs=ze.width*ze.o,t(Ee.Gb.length==0),Ee.Gb=i(gs),Ee.Uc=0,Ee.Gb==null?gs=0:(Ee.mb=Ee.Gb,Ee.nb=Ee.Uc,Ee.rc=null,gs=1),gs=!gs),!gs){gs=Ee.ga;var Cs=Ee.Fa,Ps=Ee.P,Qs=Ee.qc,En=Ee.mb,Xn=Ee.nb,Js=Ps+1,Fn=Qs-1,rr=gs.l;if(t(Cs!=null&&En!=null&&ze!=null),ex[0]=null,ex[1]=Br,ex[2]=Or,ex[3]=Ma,gs.ca=En,gs.tb=Xn,gs.c=ze.width,gs.i=ze.height,t(0=Qs)ze=0;else if(gs.$a=3&Cs[Ps+0],gs.Z=Cs[Ps+0]>>2&3,gs.Lc=Cs[Ps+0]>>4&3,Ps=Cs[Ps+0]>>6&3,0>gs.$a||1=gs.c*gs.i;gs=!ze}if(gs)return null;Ee.ga.Lc!=1?Ee.Ga=0:_t=cs-ht}t(Ee.ga!=null),t(ht+_t<=cs);e:{if(ze=(Cs=Ee.ga).c,cs=Cs.l.o,Cs.$a==0){if(Js=Ee.rc,Fn=Ee.Vc,rr=Ee.Fa,Ps=Ee.P+1+ht*ze,Qs=Ee.mb,En=Ee.nb+ht*ze,t(Ps<=Ee.P+Ee.qc),Cs.Z!=0)for(t(ex[Cs.Z]!=null),gs=0;gs<_t;++gs)ex[Cs.Z](Js,Fn,rr,Ps,Qs,En,ze),Js=Qs,Fn=En,En+=ze,Ps+=ze;else for(gs=0;gs<_t;++gs)r(Qs,En,rr,Ps,ze),Js=Qs,Fn=En,En+=ze,Ps+=ze;Ee.rc=Js,Ee.Vc=Fn}else{if(t(Cs.mc!=null),ze=ht+_t,t((gs=Cs.mc)!=null),t(ze<=gs.i),gs.C>=ze)ze=1;else if(Cs.ic||vc(),Cs.ic){Cs=gs.V,Js=gs.Ba,Fn=gs.c;var Tr=gs.i,vr=(rr=1,Ps=gs.$/Fn,Qs=gs.$%Fn,En=gs.m,Xn=gs.s,gs.$),qn=Fn*Tr,Vr=Fn*ze,wa=Xn.wc,ga=vr(Tr=Un(ga.G[0],ga.H[0],En)))Cs[Js+vr]=Tr,++vr,++Qs>=Fn&&(Qs=0,++Ps<=ze&&!(Ps%16)&&Nt(gs,Ps));else{if(!(280>Tr)){rr=0;break t}Tr=Hn(Tr-256,En);var Xi,Mi=Un(ga.G[4],ga.H[4],En);if(ge(En),!(vr>=(Mi=kn(Fn,Mi=Hn(Mi,En)))&&qn-vr>=Tr)){rr=0;break t}for(Xi=0;Xi=Fn;)Qs-=Fn,++Ps<=ze&&!(Ps%16)&&Nt(gs,Ps);vrze?ze:Ps);break t}!rr||En.h&&vr=cs&&(Ee.Cc=1),_t=1}if(!_t)return null;if(Ee.Cc&&((_t=Ee.ga)!=null&&(_t.mc=null),Ee.ga=null,0>23,Cs[Ps+4*gs+1]=Cs[Ps+4*gs+1]*Xn>>23,Cs[Ps+4*gs+2]=Cs[Ps+4*gs+2]*Xn>>23)}ze+=cs}}function Va(Ee,ze,ht,_t,Jt){for(;0<_t--;){var cs;for(cs=0;cs>4)*Ps>>16;Ee[ze+2*cs+0]=(240&gs|gs>>4)*Ps>>16&240|(15&gs|gs<<4)*Ps>>16>>4&15,Ee[ze+2*cs+1]=240&Qs|Cs}ze+=Jt}}function mi(Ee,ze,ht,_t,Jt,cs,gs,Cs){var Ps,Qs,En=255;for(Qs=0;Qs>8}function vc(){Cy=nr,Mj=Va,Ay=mi,H_=ol}function ao(Ee,ze,ht){I[Ee]=function(_t,Jt,cs,gs,Cs,Ps,Qs,En,Xn,Js,Fn,rr,Tr,vr,qn,Vr,wa){var ga,Xi=wa-1>>1,Mi=Cs[Ps+0]|Qs[En+0]<<16,yl=Xn[Js+0]|Fn[rr+0]<<16;t(_t!=null);var Ui=3*Mi+yl+131074>>2;for(ze(_t[Jt+0],255&Ui,Ui>>16,Tr,vr),cs!=null&&(Ui=3*yl+Mi+131074>>2,ze(cs[gs+0],255&Ui,Ui>>16,qn,Vr)),ga=1;ga<=Xi;++ga){var ic=Cs[Ps+ga]|Qs[En+ga]<<16,cu=Xn[Js+ga]|Fn[rr+ga]<<16,vl=Mi+ic+yl+cu+524296,Hi=vl+2*(ic+yl)>>3;Ui=Hi+Mi>>1,Mi=(vl=vl+2*(Mi+cu)>>3)+ic>>1,ze(_t[Jt+2*ga-1],255&Ui,Ui>>16,Tr,vr+(2*ga-1)*ht),ze(_t[Jt+2*ga-0],255&Mi,Mi>>16,Tr,vr+(2*ga-0)*ht),cs!=null&&(Ui=vl+yl>>1,Mi=Hi+cu>>1,ze(cs[gs+2*ga-1],255&Ui,Ui>>16,qn,Vr+(2*ga-1)*ht),ze(cs[gs+2*ga+0],255&Mi,Mi>>16,qn,Vr+(2*ga+0)*ht)),Mi=ic,yl=cu}1&wa||(Ui=3*Mi+yl+131074>>2,ze(_t[Jt+wa-1],255&Ui,Ui>>16,Tr,vr+(wa-1)*ht),cs!=null&&(Ui=3*yl+Mi+131074>>2,ze(cs[gs+wa-1],255&Ui,Ui>>16,qn,Vr+(wa-1)*ht)))}}function $m(){Df[Pb]=FN,Df[Lb]=Ij,Df[_1]=DS,Df[Rf]=Rj,Df[Cv]=Of,Df[Ey]=Qp,Df[W_]=T3,Df[w1]=Ij,Df[DN]=Rj,Df[Pj]=Of,Df[A0]=Qp}function k0(Ee){return Ee&~zS?0>Ee?0:255:Ee>>FS}function S0(Ee,ze){return k0((19077*Ee>>8)+(26149*ze>>8)-14234)}function Xu(Ee,ze,ht){return k0((19077*Ee>>8)-(6419*ze>>8)-(13320*ht>>8)+8708)}function Ac(Ee,ze){return k0((19077*Ee>>8)+(33050*ze>>8)-17685)}function Ab(Ee,ze,ht,_t,Jt){_t[Jt+0]=S0(Ee,ht),_t[Jt+1]=Xu(Ee,ze,ht),_t[Jt+2]=Ac(Ee,ze)}function Mx(Ee,ze,ht,_t,Jt){_t[Jt+0]=Ac(Ee,ze),_t[Jt+1]=Xu(Ee,ze,ht),_t[Jt+2]=S0(Ee,ht)}function wy(Ee,ze,ht,_t,Jt){var cs=Xu(Ee,ze,ht);ze=cs<<3&224|Ac(Ee,ze)>>3,_t[Jt+0]=248&S0(Ee,ht)|cs>>5,_t[Jt+1]=ze}function wu(Ee,ze,ht,_t,Jt){var cs=240&Ac(Ee,ze)|15;_t[Jt+0]=240&S0(Ee,ht)|Xu(Ee,ze,ht)>>4,_t[Jt+1]=cs}function Kp(Ee,ze,ht,_t,Jt){_t[Jt+0]=255,Ab(Ee,ze,ht,_t,Jt+1)}function jy(Ee,ze,ht,_t,Jt){Mx(Ee,ze,ht,_t,Jt),_t[Jt+3]=255}function Sv(Ee,ze,ht,_t,Jt){Ab(Ee,ze,ht,_t,Jt),_t[Jt+3]=255}function Bd(Ee,ze,ht){I[Ee]=function(_t,Jt,cs,gs,Cs,Ps,Qs,En,Xn){for(var Js=En+(-2&Xn)*ht;En!=Js;)ze(_t[Jt+0],cs[gs+0],Cs[Ps+0],Qs,En),ze(_t[Jt+1],cs[gs+0],Cs[Ps+0],Qs,En+ht),Jt+=2,++gs,++Ps,En+=2*ht;1&Xn&&ze(_t[Jt+0],cs[gs+0],Cs[Ps+0],Qs,En)}}function tu(Ee,ze,ht){return ht==0?Ee==0?ze==0?6:5:ze==0?4:0:ht}function uh(Ee,ze,ht,_t,Jt){switch(Ee>>>30){case 3:tm(ze,ht,_t,Jt,0);break;case 2:vg(ze,ht,_t,Jt);break;case 1:Ju(ze,ht,_t,Jt)}}function fp(Ee,ze){var ht,_t,Jt=ze.M,cs=ze.Nb,gs=Ee.oc,Cs=Ee.pc+40,Ps=Ee.oc,Qs=Ee.pc+584,En=Ee.oc,Xn=Ee.pc+600;for(ht=0;16>ht;++ht)gs[Cs+32*ht-1]=129;for(ht=0;8>ht;++ht)Ps[Qs+32*ht-1]=129,En[Xn+32*ht-1]=129;for(0ht;++ht)r(gs,Cs+32*ht-4,gs,Cs+32*ht+12,4);for(ht=-1;8>ht;++ht)r(Ps,Qs+32*ht-4,Ps,Qs+32*ht+4,4),r(En,Xn+32*ht-4,En,Xn+32*ht+4,4)}var Fn=Ee.Gd,rr=Ee.Hd+_t,Tr=Js.ad,vr=Js.Hc;if(0=Ee.za-1?a(qn,Vr,Fn[rr].y[15],4):r(qn,Vr,Fn[rr+1].y,0,4)),ht=0;4>ht;ht++)qn[Vr+128+ht]=qn[Vr+256+ht]=qn[Vr+384+ht]=qn[Vr+0+ht];for(ht=0;16>ht;++ht,vr<<=2)qn=gs,Vr=Cs+Ev[ht],Pu[Js.Ob[ht]](qn,Vr),uh(vr,Tr,16*+ht,qn,Vr)}else if(qn=tu(_t,Jt,Js.Ob[0]),bg[qn](gs,Cs),vr!=0)for(ht=0;16>ht;++ht,vr<<=2)uh(vr,Tr,16*+ht,gs,Cs+Ev[ht]);for(ht=Js.Gc,qn=tu(_t,Jt,Js.Dd),T0[qn](Ps,Qs),T0[qn](En,Xn),vr=Tr,qn=Ps,Vr=Qs,255&(Js=0|ht)&&(170&Js?Eb(vr,256,qn,Vr):_c(vr,256,qn,Vr)),Js=En,vr=Xn,255&(ht>>=8)&&(170&ht?Eb(Tr,320,Js,vr):_c(Tr,320,Js,vr)),Jtht;++ht)r(Fn,rr+ht*Ee.R,gs,Cs+32*ht,16);for(ht=0;8>ht;++ht)r(Tr,Js+ht*Ee.B,Ps,Qs+32*ht,8),r(vr,qn+ht*Ee.B,En,Xn+32*ht,8)}}function xg(Ee,ze,ht,_t,Jt,cs,gs,Cs,Ps){var Qs=[0],En=[0],Xn=0,Js=Ps!=null?Ps.kd:0,Fn=Ps??new Sn;if(Ee==null||12>ht)return 7;Fn.data=Ee,Fn.w=ze,Fn.ha=ht,ze=[ze],ht=[ht],Fn.gb=[Fn.gb];e:{var rr=ze,Tr=ht,vr=Fn.gb;if(t(Ee!=null),t(Tr!=null),t(vr!=null),vr[0]=0,12<=Tr[0]&&!n(Ee,rr[0],"RIFF")){if(n(Ee,rr[0]+8,"WEBP")){vr=3;break e}var qn=Ae(Ee,rr[0]+4);if(12>qn||4294967286Tr[0]-8){vr=7;break e}vr[0]=qn,rr[0]+=12,Tr[0]-=12}vr=0}if(vr!=0)return vr;for(qn=0vr[0])vr=7;else{if(!n(Vr,Tr[0],"VP8X")){if(Ae(Vr,Tr[0]+4)!=10){vr=3;break e}if(18>vr[0]){vr=7;break e}var Mi=Ae(Vr,Tr[0]+8),yl=1+Qe(Vr,Tr[0]+12);if(2147483648<=yl*(Vr=1+Qe(Vr,Tr[0]+15))){vr=3;break e}Xi!=null&&(Xi[0]=Mi),wa!=null&&(wa[0]=yl),ga!=null&&(ga[0]=Vr),Tr[0]+=18,vr[0]-=18,Ui[0]=1}vr=0}}if(Xn=Xn[0],rr=rr[0],vr!=0)return vr;if(Tr=!!(2&rr),!qn&&Xn)return 3;if(cs!=null&&(cs[0]=!!(16&rr)),gs!=null&&(gs[0]=Tr),Cs!=null&&(Cs[0]=0),gs=Qs[0],rr=En[0],Xn&&Tr&&Ps==null){vr=0;break}if(4>ht){vr=7;break}if(qn&&Xn||!qn&&!Xn&&!n(Ee,ze[0],"ALPH")){ht=[ht],Fn.na=[Fn.na],Fn.P=[Fn.P],Fn.Sa=[Fn.Sa];e:{Mi=Ee,vr=ze,qn=ht;var Ui=Fn.gb;wa=Fn.na,ga=Fn.P,Xi=Fn.Sa,yl=22,t(Mi!=null),t(qn!=null),Vr=vr[0];var ic=qn[0];for(t(wa!=null),t(Xi!=null),wa[0]=null,ga[0]=null,Xi[0]=0;;){if(vr[0]=Vr,qn[0]=ic,8>ic){vr=7;break e}var cu=Ae(Mi,Vr+4);if(4294967286Ui){vr=3;break e}if(!n(Mi,Vr,"VP8 ")||!n(Mi,Vr,"VP8L")){vr=0;break e}if(ic[0]qn[0])vr=7;else{if(Vr||yl){if(Ui=Ae(Ui,Mi+4),12<=wa&&Ui>wa-12){vr=3;break e}if(Js&&Ui>qn[0]-8){vr=7;break e}ga[0]=Ui,vr[0]+=8,qn[0]-=8,Xi[0]=yl}else Xi[0]=5<=qn[0]&&Ui[Mi+0]==47&&!(Ui[Mi+4]>>5),ga[0]=qn[0];vr=0}if(ht=ht[0],Fn.Ja=Fn.Ja[0],Fn.xa=Fn.xa[0],ze=ze[0],vr!=0)break;if(4294967286ht){vr=7;break}Cs=gs,Js=rr,Tr=cs,Ee==null||5>ht?Ee=0:5<=ht&&Ee[ze+0]==47&&!(Ee[ze+4]>>5)?(qn=[0],Ui=[0],wa=[0],ue(ga=new ce,Ee,ze,ht),ar(ga,qn,Ui,wa)?(Cs!=null&&(Cs[0]=qn[0]),Js!=null&&(Js[0]=Ui[0]),Tr!=null&&(Tr[0]=wa[0]),Ee=1):Ee=0):Ee=0}else{if(10>ht){vr=7;break}Cs=rr,Ee==null||10>ht||!Qo(Ee,ze+3,ht-3)?Ee=0:(Js=Ee[ze+0]|Ee[ze+1]<<8|Ee[ze+2]<<16,Tr=16383&(Ee[ze+7]<<8|Ee[ze+6]),Ee=16383&(Ee[ze+9]<<8|Ee[ze+8]),1&Js||3<(Js>>1&7)||!(Js>>4&1)||Js>>5>=Fn.Ja||!Tr||!Ee?Ee=0:(gs&&(gs[0]=Tr),Cs&&(Cs[0]=Ee),Ee=1))}if(!Ee||(gs=gs[0],rr=rr[0],Xn&&(Qs[0]!=gs||En[0]!=rr)))return 3;Ps!=null&&(Ps[0]=Fn,Ps.offset=ze-Ps.w,t(4294967286>ze-Ps.w),t(Ps.offset==Ps.ha-ht));break}return vr==0||vr==7&&Xn&&Ps==null?(cs!=null&&(cs[0]|=Fn.na!=null&&0ht||(cs&=-2,gs&=-2),0>cs||0>gs||0>=Cs||0>=Ps||cs+Cs>_t||gs+Ps>Jt))return 0;if(ze.v=cs,ze.j=gs,ze.va=cs+Cs,ze.o=gs+Ps,ze.U=Cs,ze.T=Ps,ze.da=Ee!=null&&0Ee.S){var ze=Ee.f.RGBA;ze.fb+=(Ee.height-1)*ze.A,ze.A=-ze.A}else ze=Ee.f.kb,Ee=Ee.height,ze.O+=(Ee-1)*ze.fa,ze.fa=-ze.fa,ze.N+=(Ee-1>>1)*ze.Ab,ze.Ab=-ze.Ab,ze.W+=(Ee-1>>1)*ze.Db,ze.Db=-ze.Db,ze.F!=null&&(ze.J+=(Ee-1)*ze.lb,ze.lb=-ze.lb);return 0}function Hr(Ee,ze,ht,_t){if(_t==null||0>=Ee||0>=ze)return 2;if(ht!=null){if(ht.Da){var Jt=ht.cd,cs=ht.bd,gs=-2&ht.v,Cs=-2&ht.j;if(0>gs||0>Cs||0>=Jt||0>=cs||gs+Jt>Ee||Cs+cs>ze)return 2;Ee=Jt,ze=cs}if(ht.da){if(!Ve(Ee,ze,Jt=[ht.ib],cs=[ht.hb]))return 2;Ee=Jt[0],ze=cs[0]}}_t.width=Ee,_t.height=ze;e:{var Ps=_t.width,Qs=_t.height;if(Ee=_t.S,0>=Ps||0>=Qs||!(Ee>=Pb&&13>Ee))Ee=2;else{if(0>=_t.Rd&&_t.sd==null){gs=cs=Jt=ze=0;var En=(Cs=Ps*Q_[Ee])*Qs;if(11>Ee||(cs=(Qs+1)/2*(ze=(Ps+1)/2),Ee==12&&(gs=(Jt=Ps)*Qs)),(Qs=i(En+2*cs+gs))==null){Ee=1;break e}_t.sd=Qs,11>Ee?((Ps=_t.f.RGBA).eb=Qs,Ps.fb=0,Ps.A=Cs,Ps.size=En):((Ps=_t.f.kb).y=Qs,Ps.O=0,Ps.fa=Cs,Ps.Fd=En,Ps.f=Qs,Ps.N=0+En,Ps.Ab=ze,Ps.Cd=cs,Ps.ea=Qs,Ps.W=0+En+cs,Ps.Db=ze,Ps.Ed=cs,Ee==12&&(Ps.F=Qs,Ps.J=0+En+2*cs),Ps.Tc=gs,Ps.lb=Jt)}if(ze=1,Jt=_t.S,cs=_t.width,gs=_t.height,Jt>=Pb&&13>Jt)if(11>Jt)Ee=_t.f.RGBA,ze&=(Cs=Math.abs(Ee.A))*(gs-1)+cs<=Ee.size,ze&=Cs>=cs*Q_[Jt],ze&=Ee.eb!=null;else{Ee=_t.f.kb,Cs=(cs+1)/2,En=(gs+1)/2,Ps=Math.abs(Ee.fa),Qs=Math.abs(Ee.Ab);var Xn=Math.abs(Ee.Db),Js=Math.abs(Ee.lb),Fn=Js*(gs-1)+cs;ze&=Ps*(gs-1)+cs<=Ee.Fd,ze&=Qs*(En-1)+Cs<=Ee.Cd,ze=(ze&=Xn*(En-1)+Cs<=Ee.Ed)&Ps>=cs&Qs>=Cs&Xn>=Cs,ze&=Ee.y!=null,ze&=Ee.f!=null,ze&=Ee.ea!=null,Jt==12&&(ze&=Js>=cs,ze&=Fn<=Ee.Tc,ze&=Ee.F!=null)}else ze=0;Ee=ze?0:2}}return Ee!=0||ht!=null&&ht.fd&&(Ee=Ia(_t)),Ee}var bc=64,Da=[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],gp=24,Ud=32,fa=8,Px=[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];Ue("Predictor0","PredictorAdd0"),I.Predictor0=function(){return 4278190080},I.Predictor1=function(Ee){return Ee},I.Predictor2=function(Ee,ze,ht){return ze[ht+0]},I.Predictor3=function(Ee,ze,ht){return ze[ht+1]},I.Predictor4=function(Ee,ze,ht){return ze[ht-1]},I.Predictor5=function(Ee,ze,ht){return Ge(Ge(Ee,ze[ht+1]),ze[ht+0])},I.Predictor6=function(Ee,ze,ht){return Ge(Ee,ze[ht-1])},I.Predictor7=function(Ee,ze,ht){return Ge(Ee,ze[ht+0])},I.Predictor8=function(Ee,ze,ht){return Ge(ze[ht-1],ze[ht+0])},I.Predictor9=function(Ee,ze,ht){return Ge(ze[ht+0],ze[ht+1])},I.Predictor10=function(Ee,ze,ht){return Ge(Ge(Ee,ze[ht-1]),Ge(ze[ht+0],ze[ht+1]))},I.Predictor11=function(Ee,ze,ht){var _t=ze[ht+0];return 0>=pt(_t>>24&255,Ee>>24&255,(ze=ze[ht-1])>>24&255)+pt(_t>>16&255,Ee>>16&255,ze>>16&255)+pt(_t>>8&255,Ee>>8&255,ze>>8&255)+pt(255&_t,255&Ee,255&ze)?_t:Ee},I.Predictor12=function(Ee,ze,ht){var _t=ze[ht+0];return(He((Ee>>24&255)+(_t>>24&255)-((ze=ze[ht-1])>>24&255))<<24|He((Ee>>16&255)+(_t>>16&255)-(ze>>16&255))<<16|He((Ee>>8&255)+(_t>>8&255)-(ze>>8&255))<<8|He((255&Ee)+(255&_t)-(255&ze)))>>>0},I.Predictor13=function(Ee,ze,ht){var _t=ze[ht-1];return(tt((Ee=Ge(Ee,ze[ht+0]))>>24&255,_t>>24&255)<<24|tt(Ee>>16&255,_t>>16&255)<<16|tt(Ee>>8&255,_t>>8&255)<<8|tt(255&Ee,255&_t))>>>0};var C0=I.PredictorAdd0;I.PredictorAdd1=ft,Ue("Predictor2","PredictorAdd2"),Ue("Predictor3","PredictorAdd3"),Ue("Predictor4","PredictorAdd4"),Ue("Predictor5","PredictorAdd5"),Ue("Predictor6","PredictorAdd6"),Ue("Predictor7","PredictorAdd7"),Ue("Predictor8","PredictorAdd8"),Ue("Predictor9","PredictorAdd9"),Ue("Predictor10","PredictorAdd10"),Ue("Predictor11","PredictorAdd11"),Ue("Predictor12","PredictorAdd12"),Ue("Predictor13","PredictorAdd13");var Jg=I.PredictorAdd2;us("ColorIndexInverseTransform","MapARGB","32b",function(Ee){return Ee>>8&255},function(Ee){return Ee}),us("VP8LColorIndexInverseTransformAlpha","MapAlpha","8b",function(Ee){return Ee},function(Ee){return Ee>>8&255});var Ny,yg=I.ColorIndexInverseTransform,gd=I.MapARGB,Yp=I.VP8LColorIndexInverseTransformAlpha,em=I.MapAlpha,Qu=I.VP8LPredictorsAdd=[];Qu.length=16,(I.VP8LPredictors=[]).length=16,(I.VP8LPredictorsAdd_C=[]).length=16,(I.VP8LPredictors_C=[]).length=16;var Sd,Zp,v1,b1,Xc,Lx,ky,tm,vg,Eb,Ju,_c,xl,ll,ju,Cd,Ix,Sy,sm,$_,Tj,V_,Rx,eh,Cy,Mj,Ay,H_,LN=i(511),IN=i(2041),Tb=i(225),Mb=i(767),RN=0,G_=IN,Xp=Tb,nm=Mb,dr=LN,Pb=0,Lb=1,_1=2,Rf=3,Cv=4,Ey=5,W_=6,w1=7,DN=8,Pj=9,A0=10,k3=[2,3,7],_o=[3,3,11],IS=[280,256,256,256,40],S3=[0,1,1,1,0],xL=[17,18,0,1,2,3,4,5,16,6,7,8,9,10,11,12,13,14,15],C3=[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],ME=[2954,2956,2958,2962,2970,2986,3018,3082,3212,3468,3980,5004],Qc=8,K_=[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],A3=[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],Ib=null,yL=[[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]],E0=[0,1,4,8,5,2,3,6,9,12,13,10,7,11,14,15],Lj=[-0,1,-1,2,-2,3,4,6,-3,5,-4,-5,-6,7,-7,8,-8,-9],Y_=[[[[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]]]],RS=[[[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]]],Rb=[[[[255,255,255,255,255,255,255,255,255,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]]]],Db=[0,1,2,3,6,4,5,6,6,6,6,6,6,6,6,7,0],bg=[],Pu=[],T0=[],ON=1,E3=2,ex=[],Df=[];ao("UpsampleRgbLinePair",Ab,3),ao("UpsampleBgrLinePair",Mx,3),ao("UpsampleRgbaLinePair",Sv,4),ao("UpsampleBgraLinePair",jy,4),ao("UpsampleArgbLinePair",Kp,4),ao("UpsampleRgba4444LinePair",wu,2),ao("UpsampleRgb565LinePair",wy,2);var FN=I.UpsampleRgbLinePair,DS=I.UpsampleBgrLinePair,Ij=I.UpsampleRgbaLinePair,Rj=I.UpsampleBgraLinePair,Of=I.UpsampleArgbLinePair,Qp=I.UpsampleRgba4444LinePair,T3=I.UpsampleRgb565LinePair,Av=16,Dj=1<_t.ca.S||(alert("todo:WebPInitConvertARGBToYUV"),_t.ca.f.kb.F!=null&&vc()),_t.Pb&&0<_t.s.ua&&_t.s.vb.X==null&&!Fe(_t.s.vb,_t.s.Wa.Xa)){_t.a=1;break s}_t.xb=0}if(!Pt(_t,_t.V,_t.Ba,_t.c,_t.i,ht.o,fs))break s;Jt.Dc=_t.Ma,_t=1;break t}t(_t.a!=0),_t=0}_t=!_t}_t&&(ze=Ee.a)}else ze=Ee.a}else{if((Ee=new Go)==null){gs=1;break e}if(Ee.Fa=Jt.na,Ee.P=Jt.P,Ee.qc=Jt.Sa,Ao(Ee,_t)){if((ze=Hr(_t.width,_t.height,gs.Oa,gs.ba))==0){if(Ee.Aa=0,ht=gs.Oa,t((Jt=Ee)!=null),ht!=null){if(0<(Ps=0>(Ps=ht.Md)?0:100Qs;++Qs)12>(Xn=Jt.pb[Qs]).lc&&(Xn.ia=Ps*Vm[0>Xn.lc?0:Xn.lc]>>3),En|=Xn.ia;En&&(alert("todo:VP8InitRandom"),Jt.ia=1)}Jt.Ga=ht.Id,100Jt.Ga&&(Jt.Ga=0)}(function(Js,Fn){if(Js==null)return 0;if(Fn==null)return hi(Js,2,"NULL VP8Io parameter in VP8Decode().");if(!Js.cb&&!Ao(Js,Fn))return 0;if(t(Js.cb),Fn.ac==null||Fn.ac(Fn)){Fn.ob&&(Js.L=0);var rr=Bj[Js.L];if(Js.L==2?(Js.yb=0,Js.zb=0):(Js.yb=Fn.v-rr>>4,Js.zb=Fn.j-rr>>4,0>Js.yb&&(Js.yb=0),0>Js.zb&&(Js.zb=0)),Js.Va=Fn.o+15+rr>>4,Js.Hb=Fn.va+15+rr>>4,Js.Hb>Js.za&&(Js.Hb=Js.za),Js.Va>Js.Ub&&(Js.Va=Js.Ub),0rr;++rr){var vr;if(Js.Qa.Cb){var qn=Js.Qa.Lb[rr];Js.Qa.Fb||(qn+=Tr.Tb)}else qn=Tr.Tb;for(vr=0;1>=vr;++vr){var Vr=Js.gd[rr][vr],wa=qn;if(Tr.Pc&&(wa+=Tr.vd[0],vr&&(wa+=Tr.od[0])),0<(wa=0>wa?0:63>2:ga>>1)>9-Tr.wb&&(ga=9-Tr.wb),1>ga&&(ga=1),Vr.dd=ga,Vr.tc=2*wa+ga,Vr.ld=40<=wa?2:15<=wa?1:0}else Vr.tc=0;Vr.La=vr}}}rr=0}else hi(Js,6,"Frame setup failed"),rr=Js.a;if(rr=rr==0){if(rr){Js.$c=0,0Js.Vb){if(Js.Vb=0,Js.Ec=i(Vr),Js.Fc=0,Js.Ec==null){rr=hi(Js,1,"no memory during frame initialization.");break t}Js.Vb=Vr}Vr=Js.Ec,wa=Js.Fc,Js.Ac=Vr,Js.Bc=wa,wa+=Tr,Js.Gd=l(Xi,Xo),Js.Hd=0,Js.rb=l(Mi+1,Jr),Js.sb=1,Js.wa=yl?l(yl,Zr):null,Js.Y=0,Js.D.Nb=0,Js.D.wa=Js.wa,Js.D.Y=Js.Y,0=rr;++rr)LN[255+rr]=0>rr?-rr:rr;for(rr=-1020;1020>=rr;++rr)IN[1020+rr]=-128>rr?-128:127=rr;++rr)Tb[112+rr]=-16>rr?-16:15=rr;++rr)Mb[255+rr]=0>rr?0:255ul;++ul){var qd,Vc=nu[0+ul];for(qd=0;4>qd;++qd){Vc=RS[su[vm+qd]][Vc];for(var Ad=Lj[Me(vo,Vc[0])];0>3;for(Ad=0;256>Ad;Ad+=16)ul[Nu+Ad]=Ih}hh=1,xp=vm[0]}var wc=15&vo.la,mh=15&Ff.la;for(Ad=0;4>Ad;++Ad){var yp=1&mh;for(Ih=Jc=0;4>Ih;++Ih)wc=wc>>1|(yp=(xd=Ib(su,xp,xd=yp+(1&wc),Lu.Sc,hh,ul,Nu))>hh)<<7,Jc=Jc<<2|(3>=4,mh=mh>>1|yp<<7,qd=(qd<<8|Jc)>>>0}for(xp=wc,hh=mh>>4,th=0;4>th;th+=2){for(Jc=0,wc=vo.la>>4+th,mh=Ff.la>>4+th,Ad=0;2>Ad;++Ad){for(yp=1&mh,Ih=0;2>Ih;++Ih)xd=yp+(1&wc),wc=wc>>1|(yp=0<(xd=Ib(su,vm[2],xd,Lu.Qc,0,ul,Nu)))<<3,Jc=Jc<<2|(3>=2,mh=mh>>1|yp<<5}Vc|=Jc<<4*th,xp|=wc<<4<=Hi.zb&&Hi.M<=Hi.Va,Hi.Aa==0)t:{if(vl.M=Hi.M,vl.uc=vo,fp(Hi,vl),wl=1,vl=(Jc=Hi.D).Nb,vo=(Vc=Bj[Hi.L])*Hi.R,su=Vc/2*Hi.B,Ad=16*vl*Hi.R,Ih=8*vl*Hi.B,vm=Hi.sa,nu=Hi.ta-vo+Ad,Lu=Hi.qa,ul=Hi.ra-su+Ih,Nu=Hi.Ha,Ff=Hi.Ia-su+Ih,mh=(wc=Jc.M)==0,qd=wc>=Hi.Va-1,Hi.Aa==2&&fp(Hi,Jc),Jc.uc)for(yp=(xd=Hi).D.M,t(xd.D.uc),Jc=xd.yb;Jcci.o&&(wc=ci.o),ci.F=null,ci.J=null,Hi.Fa!=null&&0>1),ci.W+=Hi.B*(Vc>>1),ci.F!=null&&(ci.J+=ci.width*Vc)),Jc>1,ci.W+=ci.v>>1,ci.F!=null&&(ci.J+=ci.v),ci.ka=Jc-ci.j,ci.U=ci.va-ci.v,ci.T=wc-Jc,wl=ci.put(ci))}vl+1!=Hi.Ic||qd||(r(Hi.sa,Hi.ta-vo,vm,nu+16*Hi.R,vo),r(Hi.qa,Hi.ra-su,Lu,ul+8*Hi.B,su),r(Hi.Ha,Hi.Ia-su,Nu,Ff+8*Hi.B,su))}if(!wl)return hi(ic,6,"Output aborted.")}return 1}(Js,Fn)),Fn.bc!=null&&Fn.bc(Fn),rr&=1}return rr?(Js.cb=0,rr):0})(Ee,_t)||(ze=Ee.a)}}else ze=Ee.a}ze==0&&gs.Oa!=null&&gs.Oa.fd&&(ze=Ia(gs.ba))}gs=ze}cs=gs!=0?null:11>cs?Cs.f.RGBA.eb:Cs.f.kb.y}else cs=null;return cs};var Q_=[3,4,3,4,4,2,2,4,4,4,2,1,1]};function d(I,R){for(var z="",$=0;$<4;$++)z+=String.fromCharCode(I[R++]);return z}function u(I,R){return I[R+0]|I[R+1]<<8}function h(I,R){return(I[R+0]|I[R+1]<<8|I[R+2]<<16)>>>0}function m(I,R){return(I[R+0]|I[R+1]<<8|I[R+2]<<16|I[R+3]<<24)>>>0}new c;var p=[0],f=[0],x=[],y=new c,v=s,b=function(I,R){var z={},$=0,H=!1,V=0,K=0;if(z.frames=[],!function(ie,ce){for(var je=0;je<4;je++)if(ie[ce+je]!="RIFF".charCodeAt(je))return!0;return!1}(I,R)){for(m(I,R+=4),R+=8;R>1&1}Z!="ANMF"&&(R+=le)}return z}}(v,0);b.response=v,b.rgbaoutput=!0,b.dataurl=!1;var N=b.header?b.header:null,S=b.frames?b.frames:null;if(N){N.loop_counter=N.loop_count,p=[N.canvas_height],f=[N.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 wzn(){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(ie){return ie=ie||{},this.isStrokeTransparent=ie.isStrokeTransparent||!1,this.strokeOpacity=ie.strokeOpacity||1,this.strokeStyle=ie.strokeStyle||"#000000",this.fillStyle=ie.fillStyle||"#000000",this.isFillTransparent=ie.isFillTransparent||!1,this.fillOpacity=ie.fillOpacity||1,this.font=ie.font||"10px sans-serif",this.textBaseline=ie.textBaseline||"alphabetic",this.textAlign=ie.textAlign||"left",this.lineWidth=ie.lineWidth||1,this.lineJoin=ie.lineJoin||"miter",this.lineCap=ie.lineCap||"butt",this.path=ie.path||[],this.transform=ie.transform!==void 0?ie.transform.clone():new c,this.globalCompositeOperation=ie.globalCompositeOperation||"normal",this.globalAlpha=ie.globalAlpha||1,this.clip_path=ie.clip_path||[],this.currentPoint=ie.currentPoint||new l,this.miterLimit=ie.miterLimit||10,this.lastPoint=ie.lastPoint||new l,this.lineDashOffset=ie.lineDashOffset||0,this.lineDash=ie.lineDash||[],this.margin=ie.margin||[0,0,0,0],this.prevPageLastElemOffset=ie.prevPageLastElemOffset||0,this.ignoreClearRect=typeof ie.ignoreClearRect!="boolean"||ie.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(ie){Object.defineProperty(this,"canvas",{get:function(){return{parentNode:!1,style:!1}}});var ce=ie;Object.defineProperty(this,"pdf",{get:function(){return ce}});var je=!1;Object.defineProperty(this,"pageWrapXEnabled",{get:function(){return je},set:function(Fe){je=!!Fe}});var be=!1;Object.defineProperty(this,"pageWrapYEnabled",{get:function(){return be},set:function(Fe){be=!!Fe}});var he=0;Object.defineProperty(this,"posX",{get:function(){return he},set:function(Fe){isNaN(Fe)||(he=Fe)}});var ge=0;Object.defineProperty(this,"posY",{get:function(){return ge},set:function(Fe){isNaN(Fe)||(ge=Fe)}}),Object.defineProperty(this,"margin",{get:function(){return d.margin},set:function(Fe){var Ne;typeof Fe=="number"?Ne=[Fe,Fe,Fe,Fe]:((Ne=new Array(4))[0]=Fe[0],Ne[1]=Fe.length>=2?Fe[1]:Ne[0],Ne[2]=Fe.length>=3?Fe[2]:Ne[0],Ne[3]=Fe.length>=4?Fe[3]:Ne[1]),d.margin=Ne}});var ke=!1;Object.defineProperty(this,"autoPaging",{get:function(){return ke},set:function(Fe){ke=Fe}});var Te=0;Object.defineProperty(this,"lastBreak",{get:function(){return Te},set:function(Fe){Te=Fe}});var Me=[];Object.defineProperty(this,"pageBreaks",{get:function(){return Me},set:function(Fe){Me=Fe}}),Object.defineProperty(this,"ctx",{get:function(){return d},set:function(Fe){Fe instanceof u&&(d=Fe)}}),Object.defineProperty(this,"path",{get:function(){return d.path},set:function(Fe){d.path=Fe}});var Oe=[];Object.defineProperty(this,"ctxStack",{get:function(){return Oe},set:function(Fe){Oe=Fe}}),Object.defineProperty(this,"fillStyle",{get:function(){return this.ctx.fillStyle},set:function(Fe){var Ne;Ne=m(Fe),this.ctx.fillStyle=Ne.style,this.ctx.isFillTransparent=Ne.a===0,this.ctx.fillOpacity=Ne.a,this.pdf.setFillColor(Ne.r,Ne.g,Ne.b,{a:Ne.a}),this.pdf.setTextColor(Ne.r,Ne.g,Ne.b,{a:Ne.a})}}),Object.defineProperty(this,"strokeStyle",{get:function(){return this.ctx.strokeStyle},set:function(Fe){var Ne=m(Fe);this.ctx.strokeStyle=Ne.style,this.ctx.isStrokeTransparent=Ne.a===0,this.ctx.strokeOpacity=Ne.a,Ne.a===0?this.pdf.setDrawColor(255,255,255):(Ne.a,this.pdf.setDrawColor(Ne.r,Ne.g,Ne.b))}}),Object.defineProperty(this,"lineCap",{get:function(){return this.ctx.lineCap},set:function(Fe){["butt","round","square"].indexOf(Fe)!==-1&&(this.ctx.lineCap=Fe,this.pdf.setLineCap(Fe))}}),Object.defineProperty(this,"lineWidth",{get:function(){return this.ctx.lineWidth},set:function(Fe){isNaN(Fe)||(this.ctx.lineWidth=Fe,this.pdf.setLineWidth(Fe))}}),Object.defineProperty(this,"lineJoin",{get:function(){return this.ctx.lineJoin},set:function(Fe){["bevel","round","miter"].indexOf(Fe)!==-1&&(this.ctx.lineJoin=Fe,this.pdf.setLineJoin(Fe))}}),Object.defineProperty(this,"miterLimit",{get:function(){return this.ctx.miterLimit},set:function(Fe){isNaN(Fe)||(this.ctx.miterLimit=Fe,this.pdf.setMiterLimit(Fe))}}),Object.defineProperty(this,"textBaseline",{get:function(){return this.ctx.textBaseline},set:function(Fe){this.ctx.textBaseline=Fe}}),Object.defineProperty(this,"textAlign",{get:function(){return this.ctx.textAlign},set:function(Fe){["right","end","center","left","start"].indexOf(Fe)!==-1&&(this.ctx.textAlign=Fe)}});var Se=null,Qe=null,Ae=null;Object.defineProperty(this,"fontFaces",{get:function(){return Ae},set:function(Fe){Se=null,Qe=null,Ae=Fe}}),Object.defineProperty(this,"font",{get:function(){return this.ctx.font},set:function(Fe){var Ne;if(this.ctx.font=Fe,(Ne=/^\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(Fe))!==null){var $e=Ne[1];Ne[2];var Ve=Ne[3],qe=Ne[4];Ne[5];var Ze=Ne[6],Ue=/^([.\d]+)((?:%|in|[cem]m|ex|p[ctx]))$/i.exec(qe)[2];qe=Math.floor(Ue==="px"?parseFloat(qe)*this.pdf.internal.scaleFactor:Ue==="em"?parseFloat(qe)*this.pdf.getFontSize():parseFloat(qe)*this.pdf.internal.scaleFactor),this.pdf.setFontSize(qe);var Ye=function(us){var zt,bt,As=[],vt=us.trim();if(vt==="")return M9e;if(vt in nNt)return[nNt[vt]];for(;vt!=="";){switch(bt=null,zt=(vt=aNt(vt)).charAt(0)){case'"':case"'":bt=fzn(vt.substring(1),zt);break;default:bt=gzn(vt)}if(bt===null||(As.push(bt[0]),(vt=aNt(bt[1]))!==""&&vt.charAt(0)!==","))return M9e;vt=vt.replace(/^,/,"")}return As}(Ze);if(this.fontFaces){var Ge=function(us,zt){var bt=us.getFontList(),As=JSON.stringify(bt);if(Se===null||Qe!==As){var vt=function(Ws){var on=[];return Object.keys(Ws).forEach(function(Ms){Ws[Ms].forEach(function(dn){var rn=null;switch(dn){case"bold":rn={family:Ms,weight:"bold"};break;case"italic":rn={family:Ms,style:"italic"};break;case"bolditalic":rn={family:Ms,weight:"bold",style:"italic"};break;case"":case"normal":rn={family:Ms}}rn!==null&&(rn.ref={name:Ms,style:dn},on.push(rn))})}),on}(bt);Se=function(Ws){for(var on={},Ms=0;Ms=700||$e==="bold")&&(pt="bold"),$e==="italic"&&(pt+="italic"),pt.length===0&&(pt="normal");for(var ft="",qt={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"},Ut=0;Ut=2*Math.PI&&(be=0,he=2*Math.PI),this.path.push({type:"arc",x:ie,y:ce,radius:je,startAngle:be,endAngle:he,counterclockwise:ge})},h.prototype.arcTo=function(ie,ce,je,be,he){throw new Error("arcTo not implemented.")},h.prototype.rect=function(ie,ce,je,be){if(isNaN(ie)||isNaN(ce)||isNaN(je)||isNaN(be))throw lm.error("jsPDF.context2d.rect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.rect");this.moveTo(ie,ce),this.lineTo(ie+je,ce),this.lineTo(ie+je,ce+be),this.lineTo(ie,ce+be),this.lineTo(ie,ce),this.lineTo(ie+je,ce),this.lineTo(ie,ce)},h.prototype.fillRect=function(ie,ce,je,be){if(isNaN(ie)||isNaN(ce)||isNaN(je)||isNaN(be))throw lm.error("jsPDF.context2d.fillRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.fillRect");if(!p.call(this)){var he={};this.lineCap!=="butt"&&(he.lineCap=this.lineCap,this.lineCap="butt"),this.lineJoin!=="miter"&&(he.lineJoin=this.lineJoin,this.lineJoin="miter"),this.beginPath(),this.rect(ie,ce,je,be),this.fill(),he.hasOwnProperty("lineCap")&&(this.lineCap=he.lineCap),he.hasOwnProperty("lineJoin")&&(this.lineJoin=he.lineJoin)}},h.prototype.strokeRect=function(ie,ce,je,be){if(isNaN(ie)||isNaN(ce)||isNaN(je)||isNaN(be))throw lm.error("jsPDF.context2d.strokeRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.strokeRect");f.call(this)||(this.beginPath(),this.rect(ie,ce,je,be),this.stroke())},h.prototype.clearRect=function(ie,ce,je,be){if(isNaN(ie)||isNaN(ce)||isNaN(je)||isNaN(be))throw lm.error("jsPDF.context2d.clearRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.clearRect");this.ignoreClearRect||(this.fillStyle="#ffffff",this.fillRect(ie,ce,je,be))},h.prototype.save=function(ie){ie=typeof ie!="boolean"||ie;for(var ce=this.pdf.internal.getCurrentPageInfo().pageNumber,je=0;je0||this.margin[1]>0||this.margin[2]>0||this.margin[3]>0};h.prototype.drawImage=function(ie,ce,je,be,he,ge,ke,Te,Me){var Oe=this.pdf.getImageProperties(ie),Se=1,Qe=1,Ae=1,Fe=1;be!==void 0&&Te!==void 0&&(Ae=Te/be,Fe=Me/he,Se=Oe.width/be*Te/be,Qe=Oe.height/he*Me/he),ge===void 0&&(ge=ce,ke=je,ce=0,je=0),be!==void 0&&Te===void 0&&(Te=be,Me=he),be===void 0&&Te===void 0&&(Te=Oe.width,Me=Oe.height);var Ne=this.ctx.transform.decompose(),$e=le(Ne.rotate.shx),Ve=new c,qe=(Ve=(Ve=(Ve=Ve.multiply(Ne.translate)).multiply(Ne.skew)).multiply(Ne.scale)).applyToRectangle(new o(ge-ce*Ae,ke-je*Fe,be*Se,he*Qe));if(this.autoPaging){for(var Ze,Ue=y.call(this,qe),Ye=[],Ge=0;GeHe||ptqe||Ue0)){for(;Me>=0;Me--)if(he[Me-1].close!==!0&&he[Me-1].begin!==!0){he[Me-1].deltas.push(je),he[Me-1].abs.push(Te);break}}break;case"bct":je=[Te.x1-ge[ke-1].x,Te.y1-ge[ke-1].y,Te.x2-ge[ke-1].x,Te.y2-ge[ke-1].y,Te.x-ge[ke-1].x,Te.y-ge[ke-1].y],he[he.length-1].deltas.push(je);break;case"qct":var Oe=ge[ke-1].x+2/3*(Te.x1-ge[ke-1].x),Se=ge[ke-1].y+2/3*(Te.y1-ge[ke-1].y),Qe=Te.x+2/3*(Te.x1-Te.x),Ae=Te.y+2/3*(Te.y1-Te.y),Fe=Te.x,Ne=Te.y;je=[Oe-ge[ke-1].x,Se-ge[ke-1].y,Qe-ge[ke-1].x,Ae-ge[ke-1].y,Fe-ge[ke-1].x,Ne-ge[ke-1].y],he[he.length-1].deltas.push(je);break;case"arc":he.push({deltas:[],abs:[],arc:!0}),Array.isArray(he[he.length-1].abs)&&he[he.length-1].abs.push(Te)}}be=ce?null:ie==="stroke"?"stroke":"fill";for(var $e=!1,Ve=0;Ve=.01&&(be=this.pdf.internal.getFontSize(),this.pdf.setFontSize(be*ie.scale),he=this.lineWidth,this.lineWidth=he*ie.scale);var Wt=this.autoPaging!=="text";if(Wt||Ut.y+Ut.h<=Ge){if(Wt||Ut.y>=Ue&&Ut.x<=tt){var us=Wt?ie.text:this.pdf.splitTextToSize(ie.text,ie.maxWidth||tt-Ut.x)[0],zt=b([JSON.parse(JSON.stringify(Qe))],this.posX+this.margin[3],-ft+Ue+this.ctx.prevPageLastElemOffset)[0],bt=Wt&&(Ze>Ve||Ze=.01&&(this.pdf.setFontSize(be),this.lineWidth=he)}}else ie.scale>=.01&&(be=this.pdf.internal.getFontSize(),this.pdf.setFontSize(be*ie.scale),he=this.lineWidth,this.lineWidth=he*ie.scale),this.pdf.text(ie.text,Me.x+this.posX,Me.y+this.posY,{angle:ie.angle,align:ce,renderingMode:ie.renderingMode,maxWidth:ie.maxWidth}),ie.scale>=.01&&(this.pdf.setFontSize(be),this.lineWidth=he)},H=function(ie,ce,je,be){je=je||0,be=be||0,this.pdf.internal.out(n(ie+je)+" "+r(ce+be)+" l")},V=function(ie,ce,je){return this.pdf.lines(ie,ce,je,null,null)},K=function(ie,ce,je,be,he,ge,ke,Te){this.pdf.internal.out([t(a(je+ie)),t(i(be+ce)),t(a(he+ie)),t(i(ge+ce)),t(a(ke+ie)),t(i(Te+ce)),"c"].join(" "))},Z=function(ie,ce,je,be){for(var he=2*Math.PI,ge=Math.PI/2;ce>je;)ce-=he;var ke=Math.abs(je-ce);ke1e-5;){var Se=Oe+Me*Math.min(ke,ge);Te.push(Q.call(this,ie,Oe,Se)),ke-=Math.abs(Se-Oe),Oe=Se}return Te},Q=function(ie,ce,je){var be=(je-ce)/2,he=ie*Math.cos(be),ge=ie*Math.sin(be),ke=he,Te=-ge,Me=ke*ke+Te*Te,Oe=Me+ke*he+Te*ge,Se=4/3*(Math.sqrt(2*Me*Oe)-Oe)/(ke*ge-Te*he),Qe=ke-Se*Te,Ae=Te+Se*ke,Fe=Qe,Ne=-Ae,$e=be+ce,Ve=Math.cos($e),qe=Math.sin($e);return{x1:ie*Math.cos(ce),y1:ie*Math.sin(ce),x2:Qe*Ve-Ae*qe,y2:Qe*qe+Ae*Ve,x3:Fe*Ve-Ne*qe,y3:Fe*qe+Ne*Ve,x4:ie*Math.cos(je),y4:ie*Math.sin(je)}},le=function(ie){return 180*ie/Math.PI},ue=function(ie,ce,je,be,he,ge){var ke=ie+.5*(je-ie),Te=ce+.5*(be-ce),Me=he+.5*(je-he),Oe=ge+.5*(be-ge),Se=Math.min(ie,he,ke,Me),Qe=Math.max(ie,he,ke,Me),Ae=Math.min(ce,ge,Te,Oe),Fe=Math.max(ce,ge,Te,Oe);return new o(Se,Ae,Qe-Se,Fe-Ae)},se=function(ie,ce,je,be,he,ge,ke,Te){var Me,Oe,Se,Qe,Ae,Fe,Ne,$e,Ve,qe,Ze,Ue,Ye,Ge,He=je-ie,tt=be-ce,pt=he-je,ft=ge-be,qt=ke-he,Ut=Te-ge;for(Oe=0;Oe<41;Oe++)Ve=(Ne=(Se=ie+(Me=Oe/40)*He)+Me*((Ae=je+Me*pt)-Se))+Me*(Ae+Me*(he+Me*qt-Ae)-Ne),qe=($e=(Qe=ce+Me*tt)+Me*((Fe=be+Me*ft)-Qe))+Me*(Fe+Me*(ge+Me*Ut-Fe)-$e),Oe==0?(Ze=Ve,Ue=qe,Ye=Ve,Ge=qe):(Ze=Math.min(Ze,Ve),Ue=Math.min(Ue,qe),Ye=Math.max(Ye,Ve),Ge=Math.max(Ge,qe));return new o(Math.round(Ze),Math.round(Ue),Math.round(Ye-Ze),Math.round(Ge-Ue))},ne=function(){if(this.prevLineDash||this.ctx.lineDash.length||this.ctx.lineDashOffset){var ie,ce,je=(ie=this.ctx.lineDash,ce=this.ctx.lineDashOffset,JSON.stringify({lineDash:ie,lineDashOffset:ce}));this.prevLineDash!==je&&(this.pdf.setLineDash(this.ctx.lineDash,this.ctx.lineDashOffset),this.prevLineDash=je)}}})(No.API),function(s){var t=function(l){var o,c,d,u,h,m,p,f,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)-(f=h%85))/85)-(p=h%85))/85)%85,c.push(m+33,p+33,f+33,x+33,y+33)):c.push(122);return function(v,b){for(var N=b;N>0;N--)v.pop()}(c,o.length),String.fromCharCode.apply(String,c)+"~>"},n=function(l){var o,c,d,u,h,m=String,p="length",f=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[p]%5||5))[p];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(f&c>>24,f&c>>16,f&c>>8,f&c);return function(b,N){for(var S=N;S>0;S--)b.pop()}(d,o[p]),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(Yl.DOMPurify?Promise.resolve(Yl.DOMPurify):ui(()=>import("./purify.es-dhnUglUx.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=kh(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 p=0;px&&(f=y,y=x,x=f);else{if(o!=="l"&&o!=="landscape")throw"Invalid orientation: "+o;o="l",x>y&&(f=y,y=x,x=f)}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(T9e):null;var d=new l(c);return c.worker?d:d.from(o).doCallback()}}(No.API),No.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 p=n.internal.newObject();for(n.internal.write("<< /Names [ "),i=0;i>","endobj"),t=n.internal.newObject(),n.internal.write("<< /Dests "+p+" 0 R"),n.internal.write(">>","endobj")}}]),s.events.push(["putCatalog",function(){var n=this;n.outline.root.children.length>0&&(n.internal.write("/Outlines",this.outline.makeRef(this.outline.root)),this.outline.createNamedDestinations&&n.internal.write("/Names "+t+" 0 R"))}]),s.events.push(["initialized",function(){var n=this;n.outline={createNamedDestinations:!1,root:{children:[]}},n.outline.add=function(r,a,i){var l={title:a,options:i,children:[]};return r==null&&(r=this.root),r.children.push(l),l},n.outline.render=function(){return this.ctx={},this.ctx.val="",this.ctx.pdf=n,this.genIds_r(this.root),this.renderRoot(this.root),this.renderItems(this.root),this.ctx.val},n.outline.genIds_r=function(r){r.id=n.internal.newObjectDeferred();for(var a=0;a0&&(this.line("/First "+this.makeRef(r.children[0])),this.line("/Last "+this.makeRef(r.children[r.children.length-1]))),this.line("/Count "+this.count_r({count:0},r)),this.objEnd()},n.outline.renderItems=function(r){for(var a=this.ctx.pdf.internal.getVerticalCoordinateString,i=0;i0&&this.line("/Prev "+this.makeRef(r.children[i-1])),i0&&(this.line("/First "+this.makeRef(l.children[0])),this.line("/Last "+this.makeRef(l.children[l.children.length-1])));var o=this.count=this.count_r({count:0},l);if(o>0&&this.line("/Count "+o),l.options&&l.options.pageNumber){var c=n.internal.getPageInfo(l.options.pageNumber);this.line("/Dest ["+c.objId+" 0 R /XYZ 0 "+a(0)+" 0]")}this.objEnd()}for(var d=0;d> \r endobj\r `},n.outline.count_r=function(r,a){for(var i=0;i1){V=!0,Z=void 0;var he=I*R;Q=new Uint8Array(he);for(var ge=new DataView(z.buffer),ke=0;ke536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");this.data=new Uint8Array(t);try{this[s]()}catch(n){lm.log("bit decode error:"+n)}},nk.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)}},nk.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)}},nk.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}},nk.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}},nk.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},lNt=function(s,t,n){n||(n={});var r,a,i,l,o,c,d,u=[],h=[u],m=n.textIndent||0,p=0,f=0,x=s.split(" "),y=ice.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,T){return(T&&A.length?` `:"")+A})):b.push(S[0])}),x=b,c=iNt.apply(this,[v,n])}for(i=0,l=x.length;it||N){if(f>t){for(o=oNt.apply(this,[r,a,t-(m+p),t]),u.push(o.shift()),u=[o.pop()];o.length;)h.push([o.shift()]);f=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=f+c,p=y}else u.push(r),m+=p+f,p=y}return d=c?function(S,A){return(A?v:"")+S.join(" ")}:function(S){return S.join(" ")},h.map(d)},mB.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-D2QUWnFZ.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)})},No.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},No.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",wzn),this.internal.events.subscribe("postPutResources",_zn)),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(p,f){return p-f})).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),p="",f=0;f>"),c("endobj");var b=d();c("<<"),c("/Type /Font"),c("/BaseFont /"+VB(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 /"+VB(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="",p=0;p>"),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,p=h.activeFontKey,f=h.fonts,x=p,y="",v=0,b="",N=f[x].encoding;if(f[x].encoding!=="Identity-H")return{text:o,x:c,y:d,options:u,mutex:h};for(b=o,x=p,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,N=0;this.__bidiEngine__={};var S=function(z){var $=z.charCodeAt(),H=$>>8,V=x[H];return V!==void 0?h[256*V+(255&$)]:H===252||H===253?"AL":v.test(H)?"L":H===8?"R":"N"},A=function(z){for(var $,H=0;H=$.length||(K=H[V-1])!=="EN"&&K!=="AN"||(Z=$[V+1])!=="EN"&&Z!=="AN"?ue="N":b&&(Z="AN"),ue=Z===K?Z:"N";break;case"ES":ue=(K=V>0?H[V-1]:"B")==="EN"&&V+1<$.length&&$[V+1]==="EN"?"EN":"N";break;case"ET":if(V>0&&H[V-1]==="EN"){ue="EN";break}if(b){ue="N";break}for(Q=V+1,le=$.length;Q=1425&&se<=2303||se===64286;if(K=$[Q],ne&&(K==="R"||K==="AL")){ue="R";break}}}ue=V<1||(K=$[V-1])==="B"?"N":H[V-1];break;case"B":b=!1,a=!0,ue=N;break;case"S":i=!0,ue="N"}return ue},L=function(z,$,H){var V=z.split("");return H&&M(V,H,{hiLevel:N}),V.reverse(),$&&$.reverse(),V.join("")},M=function(z,$,H){var V,K,Z,Q,le,ue=-1,se=z.length,ne=0,ie=[],ce=N?p:m,je=[];for(b=!1,a=!1,i=!1,K=0;K0)if(V===16){for(K=ue;K-1){for(K=ue;K=0&&be[Te]==="WS";Te--)he[Te]=N}}(je,$,se)},I=function(z,$,H,V,K){if(!(K.hiLevel=z){for(le=ne+1;le=z;)le++;for(ue=ne,Q=le-1;ue=0&&(Z[se]=y[ue+1])}(V,H,K),I(2,V,$,H,K),I(1,V,$,H,K),V.join("")};return this.__bidiEngine__.doBidiReorder=function(z,$,H){if(function(K,Z){if(Z)for(var Q=0;Q>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 PS,bP=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,p,f,x;for(x in p=Object.keys(n).length,c=Math.log(2),h=16*Math.floor(Math.log(p)/c),l=Math.floor(h/c),u=16*p-h,(a=new bP).writeInt(this.scalarType),a.writeShort(p),a.writeShort(h),a.writeShort(l),a.writeShort(u),i=16*p,d=a.pos+i,o=null,f=[],n)for(m=n[x],a.writeString(x),a.writeInt(s(m)),a.writeInt(d),a.writeInt(m.length),f=f.concat(m),x==="head"&&(o=d),d+=m.length;d%4;)f.push(0),d++;return a.write(f),r=2981146554-s(a.data),a.pos=o+8,a.writeUInt32(r),a.data},s=function(n){var r,a,i,l;for(n=qZt.call(n);n.length%4;)n.push(0);for(i=new bP(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,N=i.length;v=y;r=f<=y?++b:--b)u[c]===0?l=r+d[c]:(l=o[u[c]/2+(r-f)-(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,p,f,x,y,v,b,N,S,A,T,L,M,I,R,z,$,H,V,K,Z,Q,le,ue,se,ne,ie,ce,je,be,he,ge,ke,Te,Me,Oe,Se;switch(V=new bP,l=Object.keys(t).sort(function(Qe,Ae){return Qe-Ae}),n){case"macroman":for(x=0,y=function(){var Qe=[];for(f=0;f<256;++f)Qe.push(0);return Qe}(),b={0:0},i={},K=0,ue=l.length;K=32768)for(c.push(0),T.push(2*(p.length+I-f)),a=le=z;z<=u?le<=u:le>=u;a=z<=u?++le:--le)p.push(r[a].new);else c.push(H-z),T.push(0)}for(V.writeUInt16(3),V.writeUInt16(1),V.writeUInt32(12),V.writeUInt16(4),V.writeUInt16(16+8*I+2*p.length),V.writeUInt16(0),V.writeUInt16(R),V.writeUInt16(M),V.writeUInt16(m),V.writeUInt16(L),ge=0,ie=h.length;gea;r=0<=a?++r:--r)n=new xNt(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=xNt.encode(t,n),(a=new bP).writeUInt16(0),a.writeUInt16(1),r.table=a.data.concat(r.subtable),r},s}(),Szn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return _3(s,PS),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}(),Czn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return _3(s,PS),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}(),Azn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return _3(s,PS),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}(),Ezn=function(s,t){this.raw=s,this.length=s.length,this.platformID=t.platformID,this.encodingID=t.encodingID,this.languageID=t.languageID},Tzn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return _3(s,PS),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}(),qZt=[].slice,Lzn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return _3(s,PS),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 bP(n.read(a))).readShort(),d=o.readShort(),h=o.readShort(),c=o.readShort(),u=o.readShort(),this.cache[t]=l===-1?new Rzn(o,d,h,c,u):new Izn(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}(),Ozn=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,p,f,x,y,v;for(a in r=UZt.encode(this.generateCmap(),"unicode"),l=this.glyphsFor(t),p={0:0},v=r.charMap)p[(c=v[a]).old]=c.new;for(f in m=r.maxGlyphID,l)f in p||(p[f]=m++);return u=function(b){var N,S;for(N in S={},b)S[b[N]]=N;return S}(p),h=Object.keys(u).sort(function(b,N){return b-N}),x=function(){var b,N,S;for(S=[],b=0,N=h.length;b>"),i.join(` `)}return""+n},t}();const OGe=[{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}],Fzn="signature";function zzn(s){return OGe.find(t=>t.id===s)||OGe[0]}const Cc=792,Em=612,na=52;function pB(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 wf(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],pb=[124,128,136],jo=[255,255,255];function Bzn(s){return s==null||!Number.isFinite(Number(s))?null:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Number(s))}const I9e="https://relzejiswnotikjgvjhz.supabase.co";function Uzn(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(I9e).origin?s:`${I9e}/functions/v1/image-proxy?url=${encodeURIComponent(t.toString())}`}catch{return s}}async function EY(s,t=2e3){if(!s)return null;try{const n=await fetch(Uzn(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",p=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=p}),dataUrl:p,w:o,h:c,format:m}}catch{return null}}let $Zt={x:.5,y:.5};function qzn(s){$Zt={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 Xre(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,p=a/i;let f=0,x=0,y=t.w,v=t.h;const b=l.focal??$Zt;if(m>p?(y=t.h*p,f=Math.min(Math.max(0,t.w*b.x-y/2),t.w-y)):(v=t.w/p,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 N=[];l.grayscale&&N.push("grayscale(1)"),l.blur&&N.push(`blur(${l.blur*o}px)`),N.length&&(h.filter=N.join(" "));try{h.drawImage(t.el,f,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,T,L]=l.tint.color;h.globalCompositeOperation="multiply",h.fillStyle=`rgba(${A},${T},${L},${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 d7(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,p=t.w,f=t.h;u>1?(p=t.h,h=(t.w-p)/2):(f=t.w,m=(t.h-f)/2);try{d.drawImage(t.el,h,m,p,f,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 cnt(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 d_(s,t){const n=s.GState;n&&s.setGState(new n({opacity:t}))}function $zn(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 gW(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=$zn(s,c,n+13,l,a-13,{font:i.font,size:i.size,color:i.color,leading:o})+(i.gap??7)}),l}function h1(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 D9='',O9='',Vzn={title:"Facebook",slug:"facebook",get svg(){return D9+"Facebook"+O9+this.path+F9},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"},Hzn={title:"Instagram",slug:"instagram",get svg(){return D9+"Instagram"+O9+this.path+F9},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"},Gzn={title:"Pinterest",slug:"pinterest",get svg(){return D9+"Pinterest"+O9+this.path+F9},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"},Wzn={title:"TikTok",slug:"tiktok",get svg(){return D9+"TikTok"+O9+this.path+F9},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"},Kzn={title:"trulia",slug:"trulia",get svg(){return D9+"trulia"+O9+this.path+F9},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"},Yzn={title:"YouTube",slug:"youtube",get svg(){return D9+"YouTube"+O9+this.path+F9},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"},Zzn={title:"Zillow",slug:"zillow",get svg(){return D9+"Zillow"+O9+this.path+F9},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"},Xzn={facebook:Vzn,instagram:Hzn,youtube:Yzn,tiktok:Wzn,pinterest:Gzn,zillow:Zzn,trulia:Kzn},yNt=new Map;function Qzn(s,t,n){return`${s}|${t}|${n}`}function Jzn(s,t,n=128){const r=s.toLowerCase().replace(/[^a-z]/g,""),a=Xzn[r];if(!a)return null;const i=Qzn(r,t,n),l=yNt.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 yNt.set(i,d),d}catch{return null}}const Rd="helvetica";let qH="helvetica";function VZt(s,t,n,r,a,i){const l=`#${n.map(d=>Math.round(d).toString(16).padStart(2,"0")).join("")}`,o=Jzn(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(Rd,"bold"),s.setFontSize(c*1.15),s.setTextColor(...jo),s.text(t.charAt(0).toUpperCase(),r,a+c*.42,{align:"center"})}let Qre=[252,251,248],X7=[244,247,250],L_=[223,228,234],jv=[72,78,88];function Jre(s,t){return EYt(s.data.pages,t)}function dnt(s){var n;const t=s.coAgent;return t!=null&&t.enabled&&((n=t.name)!=null&&n.trim())?t:null}function HZt(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 eBn(s){return[s.agent.brokerageName,s.agent.phone,s.agent.email].filter(Boolean).join(" | ")}function Og(s,t,n,r,a,i,l){const o=l.font||Rd,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 Wu(s,t,n,r,a,i){s.setFont(Rd,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 xW(s,t,n,r,a,i){const{doc:l}=s;l.setFont(Rd,"bold"),l.setFontSize(7.5),l.setTextColor(...a||s.accent),l.text(t.toUpperCase(),n,r,{charSpace:1.8,align:i})}function xy(s,t=Qre){s.doc.addPage("letter","landscape"),s.pageNo+=1,s.doc.setFillColor(...t),s.doc.rect(0,0,Cc,Em,"F")}function Nv(s,t,n,r,a={}){const{doc:i}=s,l=!!a.dark,o=a.width??Cc-na*2-60;xW(s,t,na,62,s.accent),i.setFont(qH,"bold"),i.setFontSize(qH==="times"?25:23);const c=i.splitTextToSize(n,o).slice(0,3);i.setTextColor(...l?jo:s.brand),c.forEach((u,h)=>i.text(u,na,96+h*29));let d=96+(c.length-1)*29;return r&&(d=Wu(i,r,na,d+26,Math.min(o+40,Cc-na*2),{size:10,color:l?wf(jo,s.deep,.28):pb,leading:15,maxLines:2})),d+34}function yy(s,t=!1){const{doc:n,data:r}=s,a=t?wf(jo,s.deep,.7):L_;n.setDrawColor(...a),n.setLineWidth(.6),n.line(na,Em-46,Cc-na,Em-46);const i=Em-30;n.setFont(Rd,"bold"),n.setFontSize(7),n.setTextColor(...t?jo:s.brand),t&&d_(n,.9),n.text((r.agent.name||"").toUpperCase(),na,i,{charSpace:1.4});const l=eBn(r);l&&(n.setFont(Rd,"normal"),n.setFontSize(7),n.setTextColor(...t?jo:pb),Og(n,l,Cc/2,i,Cc/2-na-40,7,{color:t?jo:pb,align:"center"})),n.setFont(Rd,"normal"),n.setFontSize(7),n.setTextColor(...t?jo:pb),n.text(String(s.pageNo).padStart(2,"0"),Cc-na,i,{align:"right"}),t&&d_(n,1)}function GZt(s,t,n,r,a){const{doc:i}=s;i.setFont(Rd,"bold"),i.setFontSize(8);const l=i.splitTextToSize(t,a-28),o=16+l.length*12;return h1(i,n,r,a,o,6,wf(s.accent,jo,.86)),i.setTextColor(...wf(s.brand,w3,.2)),l.forEach((c,d)=>i.text(c,n+14,r+20+d*12)),r+o}function unt(s,t,n,r,a,i={}){const{doc:l}=s;s.hero?Xre(l,s.hero,t,n,r,a,{radius:10,dpi:s.dpi,tint:i.tint?{color:s.deep,amount:i.tint}:void 0}):h1(l,t,n,r,a,10,wf(s.deep,jo,.12))}function tBn(s){const{doc:t,data:n}=s,{line1:r,line2:a}=HZt(n),i=336;s.hero?Xre(t,s.hero,0,0,Cc,Em,{dpi:s.dpi,darken:.12}):(t.setFillColor(...s.deep),t.rect(0,0,Cc,Em,"F")),t.setFillColor(...s.deep),t.rect(0,0,i,Em,"F"),t.setFillColor(...s.accent),t.rect(i-3,0,3,Em,"F");const l=Jre(s,"cover");xW(s,l.kicker,na,66),t.setFont(qH,"bold"),t.setFontSize(qH==="times"?29:26),t.setTextColor(...jo);const o=t.splitTextToSize(r,i-na*2).slice(0,3);o.forEach((y,v)=>t.text(y,na,102+v*30));let c=102+(o.length-1)*30;a&&(t.setFont(Rd,"normal"),t.setFontSize(9),d_(t,.9),Og(t,a.toUpperCase(),na,c+22,i-na*2,9,{color:jo,charSpace:1.4}),d_(t,1),c+=22),c=Wu(t,l.body,na,c+34,i-na*2,{size:10,color:wf(jo,s.deep,.22),leading:16});const d=[Bzn(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(na,c+30,na+40,c+30),Og(t,d.join(" · "),na,c+54,i-na*2,10,{style:"bold",color:jo,charSpace:1}));const u=dnt(n),h=Em-(u?152:128);let m=na;s.headshot&&(d7(t,s.headshot,na+22,h+18,22),u&&s.coHeadshot?(d7(t,s.coHeadshot,na+56,h+18,22),m=na+90):m=na+56),Og(t,u?`${n.agent.name} + ${u.name}`:n.agent.name,m,h+12,i-m-24,14,{style:"bold",color:jo}),t.setFont(Rd,"normal"),t.setFontSize(8),d_(t,.85);const p=[n.agent.brokerageName].filter(Boolean).join("");p&&Og(t,p,m,h+26,i-m-24,8,{color:jo});const f=[n.agent.phone,n.agent.email].filter(Boolean).join(" · ");if(f&&Og(t,f,m,h+38,i-m-24,8,{color:jo}),u){const y=[u.title||"Co-listing agent",u.phone].filter(Boolean).join(" · ");y&&Og(t,y,na,h+56,i-na-24,8,{color:jo})}d_(t,1),s.logo&&(d_(t,.95),cnt(t,s.logo,na,Em-74,132,30,"left"),d_(t,1));const x=n.sellerName?`PREPARED FOR ${n.sellerName.toUpperCase()}`:"PREPARED FOR YOUR HOME";t.setFont(Rd,"bold"),t.setFontSize(7.5),t.setTextColor(...jo),d_(t,.9),t.text(x,Cc-na,Em-34,{align:"right",charSpace:1.6}),d_(t,1)}function sBn(s){xy(s);const{doc:t}=s,n=Jre(s,"welcome"),r=Nv(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(...wf(s.accent,jo,.85)),t.circle(na+13,i-3,13,"F"),t.setFont(Rd,"bold"),t.setFontSize(9),t.setTextColor(...s.brand),t.text(String(c+1).padStart(2,"0"),na+13,i,{align:"center"});const d=na+44,u=Cc-d-na-40;t.setFont(Rd,"bold"),t.setFontSize(11.5),t.setTextColor(...w3),t.text(l,d,i),Wu(t,o,d,i+18,u,{size:9.5,color:jv,leading:14,maxLines:2}),i+=88}),yy(s)}function nBn(s){xy(s,jo);const{doc:t,data:n}=s,r=Jre(s,"agent"),a=Nv(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=dnt(n),l=Cc-na-260,o=a-6,c=262;if(i){const f=(x,y,v,b)=>{h1(t,l,x,260,124,10,X7,"FD",L_),t.setFillColor(...s.accent),t.rect(l,x,260,3,"F");let N=l+18;v&&(d7(t,v,l+48,x+62+2,30),N=l+90);const S=260-(N-l)-18;Og(t,y,N,x+40,S,13,{style:"bold",color:s.brand});let A=x+56;b.filter(Boolean).slice(0,4).forEach(T=>{Og(t,String(T),N,A,S,8,{color:pb}),A+=13})};f(o,n.agent.name,s.headshot,[n.agent.brokerageName,n.agent.phone,n.agent.email]),f(o+124+14,i.name,s.coHeadshot,[i.title||"Co-listing agent",i.brokerageName||n.agent.brokerageName,i.phone,i.email])}else{h1(t,l,o,260,c,10,X7,"FD",L_),t.setFillColor(...s.accent),t.rect(l,o,260,3,"F"),s.headshot&&d7(t,s.headshot,l+130,o+72,42),Og(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(p=>{Og(t,String(p),l+130,m,220,8.5,{color:pb,align:"center"}),m+=14}),s.logo&&cnt(t,s.logo,l+80,o+c-44,100,28,"left")}const d=l-na-44;let u=Wu(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.",na,a+4,d,{size:10,color:jv,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,p])=>!!m&&!!p).forEach(([m,p])=>{t.setFont(Rd,"bold"),t.setFontSize(7),t.setTextColor(...pb),t.text(m.toUpperCase(),na,u,{charSpace:1.4}),Og(t,p,na+86,u,d-86,10.5,{color:w3}),t.setDrawColor(...L_),t.setLineWidth(.5),t.line(na,u+11,na+d,u+11),u+=36}),yy(s)}function rBn(s,t){xy(s);const{doc:n}=s,r=Jre(s,"overview"),a=Nv(s,r.kicker,r.headline,r.subhead||null),i=4,l=14,o=(Cc-na*2-l*(i-1))/i,c=96;t.slice(0,8).forEach((d,u)=>{const h=na+u%i*(o+l),m=a+Math.floor(u/i)*(c+l);h1(n,h,m,o,c,8,jo,"FD",L_),n.setFillColor(...s.accent),n.rect(h,m,3,c,"F"),n.setFont(Rd,"bold"),n.setFontSize(15),n.setTextColor(...wf(s.brand,jo,.55)),n.text(String(u+1).padStart(2,"0"),h+16,m+30),Wu(n,d.title,h+16,m+52,o-30,{size:9.5,style:"bold",color:w3,leading:13,maxLines:3})}),yy(s)}function hL(s,t=5){var n;return(((n=s.options)==null?void 0:n.filter(r=>r.enabled).map(r=>r.label))??LOn[s.key]??[]).slice(0,t)}function vNt(s,t,n){xy(s,n.dark?s.deep:Qre);const{doc:r}=s,a=Nv(s,n.kicker,n.headline,n.sub,{dark:n.dark}),i=404,l=272,o=!!n.flip,c=o?Cc-na-i:na,d=o?na:na+i+40,u=Cc-na*2-i-40;unt(s,c,a,i,l,{tint:n.dark?.1:0}),xW(s,t.title,d,a+12);let h=Wu(r,t.body,d,a+32,u,{size:9.5,color:n.dark?wf(jo,s.deep,.2):jv,leading:15,maxLines:4});const m=hL(t,5);if(m.length&&(h=gW(r,m,d,h+28,u,{font:Rd,size:9.5,color:n.dark?jo:w3,accent:s.accent,gap:7})),n.note&&!n.dark){const p=Math.min(h+14,Em-120);GZt(s,n.note,d,p,u)}else n.note&&(r.setFont(Rd,"bold"),r.setFontSize(9.5),r.setTextColor(...jo),d_(r,.9),Wu(r,n.note,na,Em-78,Cc-na*2,{size:9.5,style:"bold",color:jo,leading:13,maxLines:1}),d_(r,1));yy(s,n.dark)}function aBn(s,t){xy(s);const{doc:n}=s,r=Nv(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=hL(t,4),i=["Price + position","MLS story","Media ready","Go live"],l=Math.max(1,a.length||4),o=16,c=(Cc-na*2-o*(l-1))/l,d=176;(a.length?a:i).forEach((u,h)=>{const m=na+h*(c+o);h1(n,m,r,c,d,8,jo,"FD",L_),n.setFont(Rd,"bold"),n.setFontSize(16),n.setTextColor(...s.accent),n.text(String(h+1),m+16,r+34),n.setFont(Rd,"bold"),n.setFontSize(7.5),n.setTextColor(...pb),n.text((i[h]||`STEP ${h+1}`).toUpperCase(),m+16,r+56,{charSpace:1.2}),Wu(n,u,m+16,r+76,c-32,{size:9,color:jv,leading:13,maxLines:5})}),Wu(n,t.body,na,r+d+34,Cc-na*2-120,{size:10,style:"bold",color:s.brand,leading:15,maxLines:2}),yy(s)}function iBn(s,t){xy(s);const{doc:n}=s,r=Nv(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=(Cc-na*2-l*(i-1))/i,c=68;a.forEach(([u,h],m)=>{const p=na+m%i*(o+l),f=r+Math.floor(m/i)*(c+l);h1(n,p,f,o,c,8,jo,"FD",L_),VZt(n,u,h,p+28,f+c/2,20),Og(n,u,p+48,f+c/2+4,o-64,13,{style:"bold",color:h})});const d=r+2*(c+l)+22;Wu(n,t.body,na,d,Cc-na*2-140,{size:9.5,color:jv,leading:14,maxLines:3}),n.setFont(Rd,"normal"),n.setFontSize(7.5),n.setTextColor(...pb),n.text("Distribution varies by MLS, market, and portal policies.",na,Em-62),yy(s)}function oBn(s,t){xy(s,X7);const{doc:n,data:r}=s,{line1:a}=HZt(r),i=Nv(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;h1(n,na,i,l,o,10,jo,"FD",L_),h1(n,na,i,l,22,10,s.deep),n.setFillColor(...s.deep),n.rect(na,i+12,l,10,"F"),n.setFont(Rd,"bold"),n.setFontSize(7),n.setTextColor(...jo);const c=(r.agent.website||`${a}`).replace(/^https?:\/\//,"").toUpperCase();Og(n,c,na+14,i+15,l-28,7,{style:"bold",color:jo,charSpace:1}),unt(s,na+14,i+36,186,142);const d=na+214,u=l-228;Og(n,a,d,i+54,u,12,{style:"bold",color:s.brand}),Wu(n,"Welcome home.",d,i+72,u,{size:9,color:s.accent,leading:12,maxLines:1}),Wu(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:jv,leading:12,maxLines:5}),GZt(s,"Shareable. Trackable. Memorable.",na+14,i+o-46,l-28);const h=na+l+40,m=Cc-h-na;xW(s,t.title,h,i+12);let p=Wu(n,t.body,h,i+32,m,{size:9.5,color:jv,leading:15,maxLines:5});const f=hL(t,5);f.length&&gW(n,f,h,p+26,m,{font:Rd,size:9,color:w3,accent:s.accent,gap:7}),yy(s)}function lBn(s,t){xy(s,s.deep);const{doc:n}=s,r=Nv(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=na+h*(i+l);h1(n,m,r,i,i,12,jo),VZt(n,d,u,m+i/2,r+i/2-4,30),n.setFont(Rd,"bold"),n.setFontSize(6.5),n.setTextColor(...pb),n.text(d.toUpperCase(),m+i/2,r+i-8,{align:"center",charSpace:.6})});const o=na+5*(i+l)+14,c=Cc-o-na;xW(s,"The campaign can include",o,r+12),gW(n,hL(t,5),o,r+32,c,{font:Rd,size:9,color:jo,accent:s.accent,gap:7}),Wu(n,t.body,na,r+i+44,420,{size:9.5,color:wf(jo,s.deep,.2),leading:15,maxLines:4}),Wu(n,"Every post sends attention back to the property.",na,Em-84,460,{size:11,style:"bold",color:jo,leading:14,maxLines:1}),yy(s,!0)}function cBn(s,t){xy(s);const{doc:n}=s,r=Nv(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=hL(t,4),i=["Email announcement","Agent-to-agent outreach","Database follow-up","Local community visibility"];let l=r+6;a.forEach((o,c)=>{h1(n,na,l-14,34,34,8,wf(s.accent,jo,.85)),n.setFont(Rd,"bold"),n.setFontSize(11),n.setTextColor(...s.brand),n.text(String(c+1),na+17,l+7,{align:"center"});const d=na+52,u=Cc-d-na-20;n.setFont(Rd,"bold"),n.setFontSize(8),n.setTextColor(...s.brand),n.text((i[c]||t.title).toUpperCase(),d,l-2,{charSpace:1.2}),Wu(n,o,d,l+14,u,{size:9.5,color:jv,leading:14,maxLines:2}),l+=76}),Wu(n,t.body,na,Math.min(l+8,Em-92),Cc-na*2-120,{size:9.5,color:pb,leading:14,maxLines:2}),yy(s)}function dBn(s,t){xy(s);const{doc:n}=s,r=Nv(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=hL(t,4),i=["Open house","Signage","Neighborhood","Follow-up"],l=2,o=20,c=(Cc-na*2-o)/l,d=112;a.forEach((u,h)=>{const m=na+h%l*(c+o),p=r+Math.floor(h/l)*(d+o);h1(n,m,p,c,d,8,X7,"FD",L_),n.setFont(Rd,"bold"),n.setFontSize(7.5),n.setTextColor(...s.brand),n.text((i[h]||t.title).toUpperCase(),m+16,p+24,{charSpace:1.2}),Wu(n,u,m+16,p+46,c-32,{size:9.5,color:jv,leading:14,maxLines:3})}),yy(s)}function uBn(s,t){xy(s,X7);const{doc:n}=s,r=Nv(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=hL(t,4),i=["Weekly update","Market check","Smart adjustments","Direct access"];let l=r+10;a.forEach((o,c)=>{n.setFont(Rd,"bold"),n.setFontSize(11),n.setTextColor(...s.accent),n.text(String(c+1).padStart(2,"0"),na,l),n.setFont(Rd,"bold"),n.setFontSize(9),n.setTextColor(...s.brand),n.text((i[c]||"").toUpperCase(),na+48,l,{charSpace:1.2}),Wu(n,o,na+250,l-1,Cc-na-250-na,{size:9.5,color:jv,leading:13,maxLines:2}),n.setDrawColor(...L_),n.setLineWidth(.5),n.line(na,l+22,Cc-na,l+22),l+=62}),Wu(n,"Marketing creates opportunity. Communication helps us act on it.",na,Math.min(l+18,Em-84),520,{size:11,style:"bold",color:s.brand,leading:14,maxLines:1}),yy(s)}function hBn(s){xy(s,s.deep);const{doc:t,data:n}=s;s.hero&&Xre(t,s.hero,0,0,Cc,Em,{tint:{color:s.deep,amount:.92},darken:.25,dpi:s.dpi});const r=Jre(s,"closing"),a=Nv(s,r.kicker,r.headline,r.subhead||null,{dark:!0,width:520}),i=420;let l=Wu(t,r.body,na,a,i,{size:10.5,color:wf(jo,s.deep,.18),leading:17});l+=30,gW(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"],na,l,i,{font:Rd,size:9.5,color:jo,accent:s.accent,gap:8});const o=dnt(n),c=250,d=Cc-na-c,u=a-20,h=o?300:258;h1(t,d,u,c,h,10,jo),t.setFillColor(...s.accent),t.rect(d,u,c,3,"F"),s.headshot&&(o&&s.coHeadshot?(d7(t,s.headshot,d+c/2-34,u+70,32),d7(t,s.coHeadshot,d+c/2+34,u+70,32)):d7(t,s.headshot,d+c/2,u+70,38)),Og(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(p=>{Og(t,String(p),d+c/2,m,c-30,8.5,{color:pb,align:"center"}),m+=14}),o?(m+=6,t.setDrawColor(...L_),t.setLineWidth(.5),t.line(d+24,m-8,d+c-24,m-8),Og(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(p=>{Og(t,String(p),d+c/2,m,c-30,8.5,{color:pb,align:"center"}),m+=13})):s.logo&&cnt(t,s.logo,d+c/2-50,u+h-44,100,28,"left"),t.setFont(Rd,"bold"),t.setFontSize(9),t.setTextColor(...jo),d_(t,.9),t.text("LET'S MAKE YOUR HOME THE ONE BUYERS REMEMBER.",na,Em-72,{charSpace:1.4}),d_(t,1),yy(s,!0)}function hnt(s,t){return s.customImages[t.id]||null}function WZt(s,t,n,r,a,i){const l=hnt(s,t);l?Xre(s.doc,l,n,r,a,i,{radius:10,dpi:s.dpi}):unt(s,n,r,a,i)}function mBn(s,t){xy(s,t.dark?s.deep:Qre);const{doc:n}=s,r=Nv(s,t.kicker||"About",t.headline,t.subhead||null,{dark:t.dark}),a=300,i=t.imageSide!=="left",l=i?Cc-na-a:na,o=i?na:na+a+40,c=Cc-na*2-a-40;WZt(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=Wu(n,h,o,u,c,{size:10,color:t.dark?wf(jo,s.deep,.2):jv,leading:16,maxLines:7}),u+=26}),t.bullets.length&&gW(n,t.bullets.slice(0,5),o,Math.min(u,Em-150),c,{font:Rd,size:9.5,color:t.dark?jo:w3,accent:s.accent,gap:7}),yy(s,t.dark)}function pBn(s,t){xy(s,t.dark?s.deep:X7);const{doc:n}=s,r=Nv(s,t.kicker||"What others are saying",t.headline,t.subhead||null,{dark:t.dark}),a=t.testimonials.filter(m=>{var p;return(p=m.quote)==null?void 0:p.trim()}).slice(0,6),i=a.length<=2?a.length||1:a.length>4?3:2,l=18,o=(Cc-na*2-l*(i-1))/i,c=Math.ceil(a.length/i)||1,d=Em-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,p)=>{const f=na+p%i*(o+l),x=r+Math.floor(p/i)*(u+l);h1(n,f,x,o,u,10,t.dark?wf(s.deep,jo,.08):jo,"FD",L_),n.setFillColor(...s.accent),n.rect(f,x,3,u,"F"),n.setFont(qH,"bold"),n.setFontSize(30),n.setTextColor(...wf(s.accent,t.dark?s.deep:jo,.4)),n.text("“",f+18,x+40),Wu(n,m.quote,f+18,x+56,o-40,{size:9.5,color:t.dark?wf(jo,s.deep,.2):jv,leading:14,maxLines:h}),n.setDrawColor(...s.accent),n.setLineWidth(1.2),n.line(f+18,x+u-32,f+42,x+u-32),n.setFont(Rd,"bold"),n.setFontSize(8),n.setTextColor(...s.brand);const y=[m.name,m.detail].filter(Boolean).join(" · ");y&&Og(n,y.toUpperCase(),f+18,x+u-16,o-36,8,{style:"bold",color:t.dark?jo:s.brand,charSpace:1.1})}),t.body&&Wu(n,t.body,na,Math.min(r+c*(u+l)+14,Em-88),Cc-na*2-120,{size:9.5,color:t.dark?wf(jo,s.deep,.2):pb,leading:14,maxLines:2}),yy(s,t.dark)}function fBn(s,t){xy(s,t.dark?s.deep:Qre);const{doc:n}=s,r=Nv(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=(Cc-na*2-18*(a.length-1))/a.length,o=150;a.forEach((c,d)=>{const u=na+d*(l+18);h1(n,u,r,l,o,10,t.dark?wf(s.deep,jo,.1):jo,"FD",L_),n.setFillColor(...s.accent),n.rect(u,r,l,3,"F"),Og(n,c.value||"—",u+l/2,r+76,l-28,34,{style:"bold",color:t.dark?jo:s.brand,align:"center"}),Wu(n,c.label||"",u+20,r+100,l-40,{size:9,color:t.dark?wf(jo,s.deep,.3):pb,leading:12,maxLines:2,align:"center"})}),t.body&&Wu(n,t.body,na,r+o+40,Cc-na*2-140,{size:10,color:t.dark?wf(jo,s.deep,.2):jv,leading:15,maxLines:3})}else t.body&&Wu(n,t.body,na,r,Cc-na*2-140,{size:10.5,color:t.dark?jo:jv,leading:16});yy(s,t.dark)}function gBn(s,t){xy(s,t.dark?s.deep:jo);const{doc:n}=s,r=Nv(s,t.kicker||"Our promise",t.headline,t.subhead||null,{dark:t.dark}),i=!!hnt(s,t)||!!s.hero,l=i?Cc-na*2-280:Cc-na*2-140;let o=r;t.body&&(o=Wu(n,t.body,na,o,l,{size:10,color:t.dark?wf(jo,s.deep,.2):jv,leading:15,maxLines:3})+28),t.bullets.filter(d=>d==null?void 0:d.trim()).slice(0,7).forEach(d=>{h1(n,na,o-9,14,14,4,s.accent),n.setFont(Rd,"bold"),n.setFontSize(8),n.setTextColor(...jo),n.text("✓",na+7,o+1,{align:"center"}),o=Wu(n,d,na+26,o,l-26,{size:10,color:t.dark?jo:w3,leading:14,maxLines:2})+22}),i&&WZt(s,t,Cc-na-240,r,240,250),yy(s,t.dark)}function xBn(s,t){xy(s,s.deep);const{doc:n}=s,r=hnt(s,t)||s.hero;r&&Xre(n,r,0,0,Cc,Em,{tint:{color:s.deep,amount:.82},darken:.28,dpi:s.dpi}),xW(s,t.kicker||"Our approach",na,Em/2-84),n.setFont(Rd,"bold"),n.setFontSize(30),n.setTextColor(...jo);const a=n.splitTextToSize(t.headline||"",Cc-na*2-140).slice(0,4);a.forEach((i,l)=>n.text(i,na,Em/2-44+l*38)),t.body&&Wu(n,t.body,na,Em/2+a.length*38-24,480,{size:10.5,color:wf(jo,s.deep,.2),leading:16,maxLines:4}),yy(s,!0)}function bNt(s,t){switch(t.layout){case"testimonials":return pBn(s,t);case"stats":return fBn(s,t);case"checklist":return gBn(s,t);case"statement":return xBn(s,t);case"story":default:return mBn(s,t)}}async function yBn(s,t,n){var L,M,I,R;const r=n==="print"?4:2,a=n==="print"?2600:1600,i=zzn((L=t.pages)==null?void 0:L.theme);Qre=pB(i.paper),X7=pB(i.paperCool),L_=pB(i.softLine),jv=pB(i.bodyInk),qH=i.headFont;const l=pB((i.useAgentColors?t.agent.brandColor:i.brand)||i.brand||"#0E1B2C"),o=pB((i.useAgentColors?t.agent.accentColor:i.accent)||i.accent||"#B8965A"),c=wf(l,[0,0,0],i.id==="luxury"?.35:.2),d=(M=t.coAgent)!=null&&M.enabled&&((I=t.coAgent.name)!=null&&I.trim())?t.coAgent:null,u=(t.customPages||[]).filter(z=>z.enabled).sort((z,$)=>z.order-$.order),[h,m,p,f,...x]=await Promise.all([EY(t.property.photoUrl,a),EY(t.agent.headshotUrl,700),EY(t.agent.brokerageLogoUrl,800),EY((d==null?void 0:d.headshotUrl)||null,700),...u.map(z=>EY(z.imageUrl||null,a))]),y={};u.forEach((z,$)=>{y[z.id]=x[$]??null}),qzn(t.focal);const v={doc:s,data:t,brand:l,accent:o,deep:c,hero:h,headshot:m,coHeadshot:f,logo:p,customImages:y,dpi:r,pageNo:1},b=new Set(((R=t.pages)==null?void 0:R.hidden)||[]),N=[...t.services].filter(z=>z.enabled).sort((z,$)=>z.order-$.order),S=z=>N.find($=>$.key===z);tBn(v),b.has("welcome")||sBn(v),b.has("agent")||nBn(v),u.filter(z=>z.placement!=="end").forEach(z=>bNt(v,z)),b.has("overview")||rBn(v,N);const A=new Set,T=(z,$)=>{const H=S(z);H&&(A.add(z),$(H))};T("photography",z=>vNt(v,z,{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."})),T("video",z=>vNt(v,z,{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})),T("mls",z=>aBn(v,z)),T("syndication",z=>iBn(v,z)),T("website",z=>oBn(v,z)),T("social",z=>lBn(v,z)),T("email",z=>cBn(v,z)),T("openhouse",z=>dBn(v,z)),T("communication",z=>uBn(v,z)),N.filter(z=>!A.has(z.key)).forEach(z=>{xy(v);const $=Nv(v,"Marketing",z.title,null),H=hL(z,6),V=Wu(s,z.body,na,$,Cc-na*2-160,{size:10.5,color:jv,leading:16});H.length&&gW(s,H,na,V+30,Cc-na*2-160,{font:Rd,size:9.5,color:w3,accent:v.accent,gap:8}),yy(v)}),u.filter(z=>z.placement==="end").forEach(z=>bNt(v,z)),b.has("closing")||hBn(v)}const _Nt=[{id:"signature",name:"Signature",description:"Editorial full-bleed cover with a brand-tinted photo motif throughout.",render:yBn}];function vBn(s){return _Nt.find(t=>t.id===s)||_Nt[0]}async function KZt(s,t,n="screen"){const r=new No({unit:"pt",format:"letter",orientation:"landscape",compress:!0});return await vBn(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 bBn(s){return`${(s.property.addressLine1||s.title||"listing-presentation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"listing-presentation"}-presentation.pdf`}const _Bn={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 XEe(s){if(!s)return null;const{data:t}=await q.storage.from(vP).createSignedUrl(s,3600);return(t==null?void 0:t.signedUrl)??null}function QEe(s,t,n){const r=s.agent_snapshot||{},a={..._Bn,...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:MYt(s.co_agent),customPages:LYt(s.custom_pages),services:vGe(s.services),pages:s.page_settings&&Object.keys(s.page_settings).length?s.page_settings:xGe,focal:s.photo_focal||yGe}}async function YZt(s,t){if(s.property.photoUrl||!t)return s;const n=await XEe(t);return{...s,property:{...s.property,photoUrl:n}}}async function ZZt(s,t,n){const r=await YZt(s,n);return(await KZt(r,t,"screen")).output("blob")}async function XZt(s,t,n="print",r){const a=await YZt(s,r),l=(await KZt(a,t,n)).output("blob"),o=URL.createObjectURL(l),c=document.createElement("a");return c.href=o,c.download=bBn(a),document.body.appendChild(c),c.click(),c.remove(),setTimeout(()=>URL.revokeObjectURL(o),4e3),l}async function QZt(s,t,n){const r=`${s}/${t}/presentation.pdf`,{error:a}=await q.storage.from(vP).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 JZt(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 wBn(s,t,n){const r=await JZt(n),a=`${s}/${t}/photo.jpg`,{error:i}=await q.storage.from(vP).upload(a,r,{upsert:!0,contentType:"image/jpeg"});if(i)throw i;return a}async function jBn(s,t,n="presentation",r=1800){const a=await JZt(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 NBn({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 EOn(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(ra,{className:"h-8 w-8 text-primary/50"})})}const wNt=60*60*24*30;function eXt({open:s,onOpenChange:t,row:n,brand:r,photoUrl:a}){const{user:i}=vs(),[l,o]=j.useState([]),[c,d]=j.useState(""),[u,h]=j.useState([]),[m,p]=j.useState(!1),[f,x]=j.useState(""),[y,v]=j.useState(""),[b,N]=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 R=c.trim();if(!i||R.length<2||/\S+@\S+\.\S+/.test(R)){h([]);return}return S.current=setTimeout(async()=>{p(!0);const z=`%${R}%`,$=q,{data:H}=await $.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",i.id).not("email","is",null).or(`first_name.ilike.${z},last_name.ilike.${z},email.ilike.${z}`).order("first_name",{ascending:!0}).limit(6);p(!1),h(H||[])},200),()=>{S.current&&clearTimeout(S.current)}},[c,i==null?void 0:i.id]);const T=R=>{R.email&&(o(z=>z.some($=>$.email.toLowerCase()===R.email.toLowerCase())?z:[...z,R]),d(""),h([]))},L=()=>{const R=c.trim();if(!/\S+@\S+\.\S+/.test(R)){re.error("Enter a valid email address");return}T({email:R})},M=j.useMemo(()=>!!n&&l.length>0&&f.trim().length>0&&!b,[n,l,f,b]),I=async()=>{if(!(!n||!i)){if(!n.property_photo_path){re.error("Add the primary exterior photo before emailing the presentation");return}N(!0);try{const R=await ZZt(QEe(n,r,a??null),n.template_id,n.property_photo_path),z=await QZt(i.id,n.id,R)||n.pdf_path;if(!z)throw new Error("Could not save the presentation PDF");const{data:$,error:H}=await q.storage.from(vP).createSignedUrl(z,wNt);if(H||!($!=null&&$.signedUrl))throw new Error("Could not create a share link");const V=await XEe(n.property_photo_path).then(le=>le).catch(()=>null),{data:K}=await q.storage.from(vP).createSignedUrl(n.property_photo_path,wNt),{data:Z,error:Q}=await q.functions.invoke("listing-presentation-email",{body:{presentation_id:n.id,subject:f,message:y,pdf_url:$.signedUrl,photo_url:(K==null?void 0:K.signedUrl)||V,recipients:l}});if(Q)throw Q;if(!(Z!=null&&Z.success))throw new Error((Z==null?void 0:Z.error)||"Could not send the email");re.success(Z.failed?`Sent to ${Z.sent} · ${Z.failed} failed`:`Presentation emailed to ${Z.sent} ${Z.sent===1?"contact":"contacts"}`),t(!1)}catch(R){re.error((R==null?void 0:R.message)||"Could not send the presentation")}finally{N(!1)}}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(ln,{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(te,{children:"To"}),l.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:l.map(R=>e.jsxs(Be,{variant:"secondary",className:"gap-1 py-1",children:[[R.first_name,R.last_name].filter(Boolean).join(" ")||R.email,e.jsx("button",{type:"button",onClick:()=>o(z=>z.filter($=>$.email!==R.email)),"aria-label":`Remove ${R.email}`,children:e.jsx(er,{className:"h-3 w-3"})})]},R.email))}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:c,onChange:R=>d(R.target.value),onKeyDown:R=>{R.key==="Enter"&&(R.preventDefault(),L())},placeholder:"Search contacts or type an email"}),e.jsx(U,{type:"button",variant:"outline",size:"icon",onClick:L,children:e.jsx(an,{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(Et,{className:"h-3 w-3 animate-spin"})," Searching…"]}),u.map(R=>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:()=>T({email:R.email,first_name:R.first_name,last_name:R.last_name,contact_id:R.id}),children:[e.jsx(So,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:[R.first_name,R.last_name].filter(Boolean).join(" ")||R.email}),e.jsx("span",{className:"ml-auto truncate text-xs text-muted-foreground",children:R.email})]},R.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"pres-subject",children:"Subject"}),e.jsx(xe,{id:"pres-subject",value:f,onChange:R=>x(R.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"pres-message",children:"Message"}),e.jsx(Fs,{id:"pres-message",rows:7,value:y,onChange:R=>v(R.target.value)})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),disabled:b,children:"Cancel"}),e.jsxs(U,{onClick:I,disabled:!M,className:"gap-2",children:[b?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx($r,{className:"h-4 w-4"}),b?"Sending…":`Send${l.length?` (${l.length})`:""}`]})]})]})})}const kBn=()=>{const s=Wn(),{presentations:t,isLoading:n,create:r,duplicate:a,remove:i,update:l}=CYt(),{data:o}=COn(),{data:c}=AYt(),{savedTemplates:d,remove:u}=SYt(),[h,m]=j.useState(null),[p,f]=j.useState(""),[x,y]=j.useState(null),[v,b]=j.useState(null),[N,S]=j.useState(null),A=j.useMemo(()=>{var I,R;return(R=(I=o==null?void 0:o[0])==null?void 0:I.default_services)!=null&&R.length?o[0].default_services:VEe},[o]),T=async()=>{var R;if(!c)return;const I=await r.mutateAsync({title:"Untitled Presentation",template_id:((R=o==null?void 0:o[0])==null?void 0:R.slug)||"signature",agent_snapshot:c,services:A});s(`/apps/listing-presentation-studio/${I.id}`)},L=async I=>{var z;const R=await r.mutateAsync({title:`${I.name} — new listing`,template_id:I.template_id||"signature",agent_snapshot:I.agent_snapshot,co_agent:I.co_agent,custom_pages:I.custom_pages,services:(z=I.services)!=null&&z.length?I.services:A,page_settings:I.page_settings});s(`/apps/listing-presentation-studio/${R.id}`)},M=async I=>{try{b(I.id),await XZt(QEe(I,c),I.template_id,"print",I.property_photo_path)}catch(R){re.error((R==null?void 0:R.message)||"Could not build the PDF")}finally{b(null)}};return e.jsxs(qs,{children:[e.jsxs("div",{className:"space-y-8",children:[e.jsx("div",{className:"relative overflow-hidden rounded-2xl border bg-gradient-to-br from-primary/10 via-background to-accent/10 p-8",children:e.jsxs("div",{className:"flex flex-col gap-6 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(cn,{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(U,{size:"lg",onClick:T,disabled:r.isPending||!c,className:"gap-2",children:[r.isPending?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(an,{className:"h-4 w-4"}),"New presentation"]}),d.length>0&&e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsxs(U,{size:"lg",variant:"outline",className:"gap-2",children:[e.jsx(u0,{className:"h-4 w-4"})," From template",e.jsx(rl,{className:"h-4 w-4"})]})}),e.jsx(Eu,{align:"end",className:"w-64",children:d.map(I=>e.jsxs(La,{onClick:()=>L(I),children:[e.jsx(u0,{className:"mr-2 h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:I.name})]},I.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(I=>e.jsx(we,{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:()=>L(I),disabled:r.isPending,children:[e.jsxs("p",{className:"flex items-center gap-2 truncate font-medium",children:[e.jsx(u0,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),I.name]}),e.jsx("p",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:I.description||"Branding, theme, page wording, and marketing plan saved."})]}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>u.mutate(I.id),children:e.jsx(In,{className:"h-4 w-4"})})]})},I.id))})]}),n?e.jsx("div",{className:"grid gap-5 sm:grid-cols-2 lg:grid-cols-3",children:[0,1,2].map(I=>e.jsx(xn,{className:"h-56 rounded-xl"},I))}):t.length===0?e.jsx(we,{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(Ur,{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(U,{onClick:T,disabled:r.isPending||!c,className:"gap-2",children:[e.jsx(an,{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(I=>{const R=I.property_address_line1||"No address yet",z=[I.city,I.state].filter(Boolean).join(", ");return e.jsxs(we,{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/${I.id}`),children:e.jsx(NBn,{path:I.property_photo_path,alt:`${R} 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:I.title}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[R,z?` · ${z}`:""]})]}),e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",children:e.jsx(ey,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",children:[e.jsxs(La,{onClick:()=>s(`/apps/listing-presentation-studio/${I.id}`),children:[e.jsx(ri,{className:"mr-2 h-4 w-4"})," Open"]}),e.jsxs(La,{onClick:()=>{m(I),f(I.title)},children:[e.jsx(Ur,{className:"mr-2 h-4 w-4"})," Rename"]}),e.jsxs(La,{onClick:()=>a.mutate(I),children:[e.jsx(Pa,{className:"mr-2 h-4 w-4"})," Duplicate"]}),e.jsxs(La,{onClick:()=>M(I),children:[e.jsx(pi,{className:"mr-2 h-4 w-4"})," Download PDF"]}),e.jsxs(La,{onClick:()=>S(I),children:[e.jsx(ln,{className:"mr-2 h-4 w-4"})," Email to a contact"]}),e.jsx(l1,{}),e.jsxs(La,{className:"text-destructive",onClick:()=>y(I),children:[e.jsx(In,{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 ",Gs(new Date(I.updated_at),"MMM d, yyyy")]}),I.last_generated_at?e.jsx(Be,{variant:"secondary",className:"text-[10px]",children:"PDF ready"}):e.jsx(Be,{variant:"outline",className:"text-[10px]",children:"Draft"})]}),e.jsxs(U,{variant:"outline",size:"sm",className:"w-full gap-2",disabled:v===I.id,onClick:()=>M(I),children:[v===I.id?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(pi,{className:"h-4 w-4"}),"Download PDF"]})]})]},I.id)})})]}),e.jsx(zs,{open:!!h,onOpenChange:I=>!I&&m(null),children:e.jsxs(Ds,{className:"sm:max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Rename presentation"})}),e.jsx(xe,{value:p,onChange:I=>f(I.target.value),autoFocus:!0}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>m(null),children:"Cancel"}),e.jsx(U,{onClick:async()=>{h&&(await l.mutateAsync({id:h.id,title:p.trim()||"Untitled Presentation"}),m(null),re.success("Renamed"))},children:"Save"})]})]})}),e.jsx(Fl,{open:!!x,onOpenChange:I=>!I&&y(null),children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Delete this presentation?"}),e.jsx(Ll,{children:"This permanently removes the presentation, its property photo, and the generated PDF."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{x&&i.mutate(x),y(null)},children:"Delete"})]})]})}),e.jsx(eXt,{open:!!N,onOpenChange:I=>!I&&S(null),row:N,brand:c})]})};var hJ={};hJ.d=(s,t)=>{for(var n in t)hJ.o(t,n)&&!hJ.o(s,n)&&Object.defineProperty(s,n,{enumerable:!0,get:t[n]})};hJ.o=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var yc=globalThis.pdfjsLib={};hJ.d(yc,{AbortException:()=>B9,AnnotationEditorLayer:()=>KWe,AnnotationEditorParamsType:()=>dc,AnnotationEditorType:()=>Uc,AnnotationEditorUIManager:()=>J7,AnnotationLayer:()=>jqn,AnnotationMode:()=>d6,ColorPicker:()=>sTe,DOMSVGFactory:()=>Nnt,DrawLayer:()=>QWe,FeatureTest:()=>fb,GlobalWorkerOptions:()=>uA,ImageKind:()=>c4e,InvalidPDFException:()=>sXt,MissingPDFException:()=>z9,OPS:()=>pk,OutputScale:()=>qGe,PDFDataRangeTransport:()=>QXt,PDFDateString:()=>xnt,PDFWorker:()=>s$,PasswordResponses:()=>EBn,PermissionFlag:()=>ABn,PixelsPerInch:()=>_P,RenderingCancelledException:()=>fnt,TextLayer:()=>Pte,UnexpectedResponseException:()=>_Ie,Util:()=>Lo,VerbosityLevel:()=>yIe,XfaLayer:()=>eQt,build:()=>nqn,createValidAbsoluteUrl:()=>LBn,fetchData:()=>jIe,getDocument:()=>KUn,getFilenameFromUrl:()=>qBn,getPdfFilenameFromUrl:()=>$Bn,getXfaPageViewport:()=>VBn,isDataScheme:()=>NIe,isPdfFile:()=>gnt,noContextMenu:()=>xN,normalizeUnicode:()=>zBn,setLayerDimensions:()=>Q7,shadow:()=>Yd,version:()=>sqn});const s1=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),tXt=[1,0,0,1,0,0],FGe=[.001,0,0,.001,0,0],SBn=1e7,R9e=1.35,Ew={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},d6={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},CBn="pdfjs_internal_editor_",Uc={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},dc={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},ABn={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},qv={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},c4e={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Ux={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,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},TY={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},yIe={ERRORS:0,WARNINGS:1,INFOS:5},pk={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},EBn={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let vIe=yIe.WARNINGS;function TBn(s){Number.isInteger(s)&&(vIe=s)}function MBn(){return vIe}function bIe(s){vIe>=yIe.INFOS&&console.log(`Info: ${s}`)}function nd(s){vIe>=yIe.WARNINGS&&console.log(`Warning: ${s}`)}function ip(s){throw new Error(s)}function r0(s,t){s||ip(t)}function PBn(s){switch(s==null?void 0:s.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function LBn(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=FBn(s)}catch{}}const r=t?new URL(s,t):new URL(s);if(PBn(r))return r}catch{}return null}function Yd(s,t,n,r=!1){return Object.defineProperty(s,t,{value:n,enumerable:!r,configurable:!0,writable:!1}),n}const mL=function(){function t(n,r){this.message=n,this.name=r}return t.prototype=new Error,t.constructor=t,t}();class zGe extends mL{constructor(t,n){super(t,"PasswordException"),this.code=n}}class BGe extends mL{constructor(t,n){super(t,"UnknownErrorException"),this.details=n}}class sXt extends mL{constructor(t){super(t,"InvalidPDFException")}}class z9 extends mL{constructor(t){super(t,"MissingPDFException")}}class _Ie extends mL{constructor(t,n){super(t,"UnexpectedResponseException"),this.status=n}}class IBn extends mL{constructor(t){super(t,"FormatError")}}class B9 extends mL{constructor(t){super(t,"AbortException")}}function nXt(s){(typeof s!="object"||(s==null?void 0:s.length)===void 0)&&ip("Invalid argument for bytesToString");const t=s.length,n=8192;if(t>24&255,s>>16&255,s>>8&255,s&255)}function mnt(s){const t=Object.create(null);for(const[n,r]of s)t[n]=r;return t}function DBn(){const s=new Uint8Array(4);return s[0]=1,new Uint32Array(s.buffer,0,1)[0]===1}function OBn(){try{return new Function(""),!0}catch{return!1}}class fb{static get isLittleEndian(){return Yd(this,"isLittleEndian",DBn())}static get isEvalSupported(){return Yd(this,"isEvalSupported",OBn())}static get isOffscreenCanvasSupported(){return Yd(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get platform(){return typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.platform)=="string"?Yd(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")}):Yd(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){var t,n;return Yd(this,"isCSSRoundSupported",(n=(t=globalThis.CSS)==null?void 0:t.supports)==null?void 0:n.call(t,"width: round(1.5px, 1px)"))}}const D9e=Array.from(Array(256).keys(),s=>s.toString(16).padStart(2,"0"));var KA,d4e,UGe;class Lo{static makeHexColor(t,n,r){return`#${D9e[t]}${D9e[n]}${D9e[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)],Xt(this,KA,UGe).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),Xt(this,KA,UGe).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}}KA=new WeakSet,d4e=function(t,n,r,a,i,l,o,c,d,u){if(d<=0||d>=1)return;const h=1-d,m=d*d,p=m*d,f=h*(h*(h*t+3*d*n)+3*m*r)+p*a,x=h*(h*(h*i+3*d*l)+3*m*o)+p*c;u[0]=Math.min(u[0],f),u[1]=Math.min(u[1],x),u[2]=Math.max(u[2],f),u[3]=Math.max(u[3],x)},UGe=function(t,n,r,a,i,l,o,c,d,u,h,m){if(Math.abs(d)<1e-12){Math.abs(u)>=1e-12&&Xt(this,KA,d4e).call(this,t,n,r,a,i,l,o,c,-h/u,m);return}const p=u**2-4*h*d;if(p<0)return;const f=Math.sqrt(p),x=2*d;Xt(this,KA,d4e).call(this,t,n,r,a,i,l,o,c,(-u+f)/x,m),Xt(this,KA,d4e).call(this,t,n,r,a,i,l,o,c,(-u-f)/x,m)},is(Lo,KA);function FBn(s){return decodeURIComponent(escape(s))}let O9e=null,jNt=null;function zBn(s){return O9e||(O9e=/([\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,jNt=new Map([["ſt","ſt"]])),s.replaceAll(O9e,(t,n,r)=>n?n.normalize("NFKC"):jNt.get(r))}function BBn(){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 nXt(s)}const pnt="pdfjs_internal_id_",iC={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 UBn(s){return Uint8Array.prototype.toBase64?s.toBase64():btoa(nXt(s))}const xC="http://www.w3.org/2000/svg",DD=class DD{};Lr(DD,"CSS",96),Lr(DD,"PDF",72),Lr(DD,"PDF_TO_CSS_UNITS",DD.CSS/DD.PDF);let _P=DD;async function jIe(s,t="text"){if(zZ(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 eae{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 p,f,x,y;d===0?(p=Math.abs(c-t[1])*n+a,f=Math.abs(o-t[0])*n+i,x=(t[3]-t[1])*n,y=(t[2]-t[0])*n):(p=Math.abs(o-t[0])*n+a,f=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,p-d*n*o-h*n*c,f-u*n*o-m*n*c],this.width=x,this.height=y}get rawDims(){const{viewBox:t}=this;return Yd(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 eae({viewBox:this.viewBox.slice(),scale:t,rotation:n,offsetX:r,offsetY:a,dontFlip:i})}convertToViewportPoint(t,n){return Lo.applyTransform([t,n],this.transform)}convertToViewportRectangle(t){const n=Lo.applyTransform([t[0],t[1]],this.transform),r=Lo.applyTransform([t[2],t[3]],this.transform);return[n[0],n[1],r[0],r[1]]}convertToPdfPoint(t,n){return Lo.applyInverseTransform([t,n],this.transform)}}class fnt extends mL{constructor(t,n=0){super(t,"RenderingCancelledException"),this.extraDelay=n}}function NIe(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))}}rse=new WeakMap,is(xnt,rse);function VBn(s,{scale:t=1,rotation:n=0}){const{width:r,height:a}=s.attributes.style,i=[0,0,parseInt(r),parseInt(a)];return new eae({viewBox:i,scale:t,rotation:n})}function ynt(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):(nd(`Not a valid color format: "${s}"`),[0,0,0])}function HBn(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,ynt(r))}t.remove()}function df(s){const{a:t,b:n,c:r,d:a,e:i,f:l}=s.getTransform();return[t,n,r,a,i,l]}function oC(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 Q7(s,t,n=!1,r=!0){if(t instanceof eae){const{pageWidth:a,pageHeight:i}=t.rawDims,{style:l}=s,o=fb.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 qGe{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 w6,wO,xk,jO,ase,ise,zTe,rXt,yb,aXt,iXt,u4e,oXt,VGe;const CC=class CC{constructor(t){is(this,yb);is(this,w6,null);is(this,wO,null);is(this,xk);is(this,jO,null);is(this,ase,null);$t(this,xk,t),fe(CC,ise)||$t(CC,ise,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=$t(this,w6,document.createElement("div"));t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const n=fe(this,xk)._uiManager._signal;t.addEventListener("contextmenu",xN,{signal:n}),t.addEventListener("pointerdown",Xt(CC,zTe,rXt),{signal:n});const r=$t(this,jO,document.createElement("div"));r.className="buttons",t.append(r);const a=fe(this,xk).toolbarPosition;if(a){const{style:i}=t,l=fe(this,xk)._uiManager.direction==="ltr"?1-a[0]:a[0];i.insetInlineEnd=`${100*l}%`,i.top=`calc(${100*a[1]}% + var(--editor-toolbar-vert-offset))`}return Xt(this,yb,oXt).call(this),t}get div(){return fe(this,w6)}hide(){var t;fe(this,w6).classList.add("hidden"),(t=fe(this,wO))==null||t.hideDropdown()}show(){var t;fe(this,w6).classList.remove("hidden"),(t=fe(this,ase))==null||t.shown()}async addAltText(t){const n=await t.render();Xt(this,yb,u4e).call(this,n),fe(this,jO).prepend(n,fe(this,yb,VGe)),$t(this,ase,t)}addColorPicker(t){$t(this,wO,t);const n=t.renderButton();Xt(this,yb,u4e).call(this,n),fe(this,jO).prepend(n,fe(this,yb,VGe))}remove(){var t;fe(this,w6).remove(),(t=fe(this,wO))==null||t.destroy(),$t(this,wO,null)}};w6=new WeakMap,wO=new WeakMap,xk=new WeakMap,jO=new WeakMap,ase=new WeakMap,ise=new WeakMap,zTe=new WeakSet,rXt=function(t){t.stopPropagation()},yb=new WeakSet,aXt=function(t){fe(this,xk)._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()},iXt=function(t){fe(this,xk)._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()},u4e=function(t){const n=fe(this,xk)._uiManager._signal;t.addEventListener("focusin",Xt(this,yb,aXt).bind(this),{capture:!0,signal:n}),t.addEventListener("focusout",Xt(this,yb,iXt).bind(this),{capture:!0,signal:n}),t.addEventListener("contextmenu",xN,{signal:n})},oXt=function(){const{editorType:t,_uiManager:n}=fe(this,xk),r=document.createElement("button");r.className="delete",r.tabIndex=0,r.setAttribute("data-l10n-id",fe(CC,ise)[t]),Xt(this,yb,u4e).call(this,r),r.addEventListener("click",a=>{n.delete()},{signal:n._signal}),fe(this,jO).append(r)},VGe=function(){const t=document.createElement("div");return t.className="divider",t},is(CC,zTe),is(CC,ise,null);let $Ge=CC;var ose,NO,kO,EP,lXt,cXt,dXt;class GBn{constructor(t){is(this,EP);is(this,ose,null);is(this,NO,null);is(this,kO);$t(this,kO,t)}show(t,n,r){const[a,i]=Xt(this,EP,cXt).call(this,n,r),{style:l}=fe(this,NO)||$t(this,NO,Xt(this,EP,lXt).call(this));t.append(fe(this,NO)),l.insetInlineEnd=`${100*a}%`,l.top=`calc(${100*i}% + var(--editor-toolbar-vert-offset))`}hide(){fe(this,NO).remove()}}ose=new WeakMap,NO=new WeakMap,kO=new WeakMap,EP=new WeakSet,lXt=function(){const t=$t(this,NO,document.createElement("div"));t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",xN,{signal:fe(this,kO)._signal});const n=$t(this,ose,document.createElement("div"));return n.className="buttons",t.append(n),Xt(this,EP,dXt).call(this),t},cXt=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{fe(this,kO).highlightSelection("floating_button")},{signal:r}),fe(this,ose).append(t)};function JEe(s,t,n){for(const r of n)t.addEventListener(r,s[r].bind(s))}function WBn(s){return Math.round(Math.min(255,Math.max(1,255*s))).toString(16).padStart(2,"0")}var BTe;class KBn{constructor(){is(this,BTe,0)}get id(){return`${CBn}${O0(this,BTe)._++}`}}BTe=new WeakMap;var k$,lse,Hv,S$,h4e;const Sat=class Sat{constructor(){is(this,S$);is(this,k$,BBn());is(this,lse,0);is(this,Hv,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 Yd(this,"_isSVGFittingCanvas",i)}async getFromFile(t){const{lastModified:n,name:r,size:a,type:i}=t;return Xt(this,S$,h4e).call(this,`${n}_${r}_${a}_${i}`,t)}async getFromUrl(t){return Xt(this,S$,h4e).call(this,t,t)}async getFromBlob(t,n){const r=await n;return Xt(this,S$,h4e).call(this,t,r)}async getFromId(t){fe(this,Hv)||$t(this,Hv,new Map);const n=fe(this,Hv).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){fe(this,Hv)||$t(this,Hv,new Map);let r=fe(this,Hv).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_${fe(this,k$)}_${O0(this,lse)._++}`,refCounter:1,isSvg:!1},fe(this,Hv).set(t,r),fe(this,Hv).set(r.id,r),r}getSvgUrl(t){const n=fe(this,Hv).get(t);return n!=null&&n.isSvg?n.svgUrl:null}deleteId(t){var a;fe(this,Hv)||$t(this,Hv,new Map);const n=fe(this,Hv).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_${fe(this,k$)}_`)}};k$=new WeakMap,lse=new WeakMap,Hv=new WeakMap,S$=new WeakSet,h4e=async function(t,n){fe(this,Hv)||$t(this,Hv,new Map);let r=fe(this,Hv).get(t);if(r===null)return null;if(r!=null&&r.bitmap)return r.refCounter+=1,r;try{r||(r={bitmap:null,id:`image_${fe(this,k$)}_${O0(this,lse)._++}`,refCounter:0,isSvg:!1});let a;if(typeof n=="string"?(r.url=n,a=await jIe(n,"blob")):n instanceof File?a=r.file=n:n instanceof Blob&&(a=n),a.type==="image/svg+xml"){const i=Sat._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 fe(this,Hv).set(t,r),r&&fe(this,Hv).set(r.id,r),r};let HGe=Sat;var q0,j6,cse,$0;class YBn{constructor(t=128){is(this,q0,[]);is(this,j6,!1);is(this,cse);is(this,$0,-1);$t(this,cse,t)}add({cmd:t,undo:n,post:r,mustExec:a,type:i=NaN,overwriteIfSameType:l=!1,keepUndo:o=!1}){if(a&&t(),fe(this,j6))return;const c={cmd:t,undo:n,post:r,type:i};if(fe(this,$0)===-1){fe(this,q0).length>0&&(fe(this,q0).length=0),$t(this,$0,0),fe(this,q0).push(c);return}if(l&&fe(this,q0)[fe(this,$0)].type===i){o&&(c.undo=fe(this,q0)[fe(this,$0)].undo),fe(this,q0)[fe(this,$0)]=c;return}const d=fe(this,$0)+1;d===fe(this,cse)?fe(this,q0).splice(0,1):($t(this,$0,d),di===n[l]))return qTe._colorsMapping.get(r);return n}getHexCode(t){const n=this._colors.get(t);return n?Lo.makeHexColor(...n):t}};Lr(qTe,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let GGe=qTe;var C$,bw,Vx,Uy,A$,zC,E$,yk,N6,T$,SO,D5,vk,CO,dse,use,M$,hse,O5,k6,P$,S6,F5,$Te,C6,mse,A6,AO,pse,fse,V0,xh,BC,EO,gse,xse,E6,z5,UC,yse,x2,Ri,m4e,WGe,hXt,mXt,p4e,pXt,fXt,gXt,KGe,xXt,YGe,ZGe,yXt,q1,PT,vXt,bXt,XGe,_Xt,BZ,QGe;const zU=class zU{constructor(t,n,r,a,i,l,o,c,d,u,h){is(this,Ri);is(this,C$,new AbortController);is(this,bw,null);is(this,Vx,new Map);is(this,Uy,new Map);is(this,A$,null);is(this,zC,null);is(this,E$,null);is(this,yk,new YBn);is(this,N6,null);is(this,T$,0);is(this,SO,new Set);is(this,D5,null);is(this,vk,null);is(this,CO,new Set);is(this,dse,!1);is(this,use,!1);is(this,M$,!1);is(this,hse,null);is(this,O5,null);is(this,k6,null);is(this,P$,null);is(this,S6,!1);is(this,F5,null);is(this,$Te,new KBn);is(this,C6,!1);is(this,mse,!1);is(this,A6,null);is(this,AO,null);is(this,pse,null);is(this,fse,null);is(this,V0,Uc.NONE);is(this,xh,new Set);is(this,BC,null);is(this,EO,null);is(this,gse,null);is(this,xse,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});is(this,E6,[0,0]);is(this,z5,null);is(this,UC,null);is(this,yse,null);is(this,x2,null);const m=this._signal=fe(this,C$).signal;$t(this,UC,t),$t(this,yse,n),$t(this,A$,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",p=>this.updateParams(p.type,p.value),{signal:m}),Xt(this,Ri,pXt).call(this),Xt(this,Ri,yXt).call(this),Xt(this,Ri,KGe).call(this),$t(this,zC,i.annotationStorage),$t(this,hse,i.filterFactory),$t(this,EO,l),$t(this,P$,o||null),$t(this,dse,c),$t(this,use,d),$t(this,M$,u),$t(this,fse,h||null),this.viewParameters={realScale:_P.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}static get _keyboardManager(){const t=zU.prototype,n=l=>fe(l,UC).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 Yd(this,"_keyboardManager",new tae([[["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)&&fe(l,UC).contains(o)&&!l.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(l,{target:o})=>!(o instanceof HTMLButtonElement)&&fe(l,UC).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=fe(this,x2))==null||t.resolve(),$t(this,x2,null),(n=fe(this,C$))==null||n.abort(),$t(this,C$,null),this._signal=null;for(const i of fe(this,Uy).values())i.destroy();fe(this,Uy).clear(),fe(this,Vx).clear(),fe(this,CO).clear(),$t(this,bw,null),fe(this,xh).clear(),fe(this,yk).destroy(),(r=fe(this,A$))==null||r.destroy(),(a=fe(this,F5))==null||a.hide(),$t(this,F5,null),fe(this,O5)&&(clearTimeout(fe(this,O5)),$t(this,O5,null)),fe(this,z5)&&(clearTimeout(fe(this,z5)),$t(this,z5,null))}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return fe(this,fse)}get useNewAltTextFlow(){return fe(this,use)}get useNewAltTextWhenAddingImage(){return fe(this,M$)}get hcmFilter(){return Yd(this,"hcmFilter",fe(this,EO)?fe(this,hse).addHCMFilter(fe(this,EO).foreground,fe(this,EO).background):"none")}get direction(){return Yd(this,"direction",getComputedStyle(fe(this,UC)).direction)}get highlightColors(){return Yd(this,"highlightColors",fe(this,P$)?new Map(fe(this,P$).split(",").map(t=>t.split("=").map(n=>n.trim()))):null)}get highlightColorNames(){return Yd(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setMainHighlightColorPicker(t){$t(this,pse,t)}editAltText(t,n=!1){var r;(r=fe(this,A$))==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":$t(this,M$,n);break}}onPageChanging({pageNumber:t}){$t(this,T$,t-1)}focusMainContainer(){fe(this,UC).focus()}findParent(t,n){for(const r of fe(this,Uy).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){fe(this,yse).classList.toggle("noUserSelect",t)}addShouldRescale(t){fe(this,CO).add(t)}removeShouldRescale(t){fe(this,CO).delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*_P.PDF_TO_CSS_UNITS;for(const n of fe(this,CO))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=Xt(this,Ri,m4e).call(this,n).closest(".textLayer"),u=this.getSelectionBoxes(d);if(!u)return;n.empty();const h=Xt(this,Ri,WGe).call(this,d),m=fe(this,V0)===Uc.NONE,p=()=>{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(Uc.HIGHLIGHT,p);return}p()}addToAnnotationStorage(t){!t.isEmpty()&&fe(this,zC)&&!fe(this,zC).has(t.id)&&fe(this,zC).setValue(t.id,t)}blur(){if(this.isShiftKeyDown=!1,fe(this,S6)&&($t(this,S6,!1),Xt(this,Ri,p4e).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const n of fe(this,xh))if(n.div.contains(t)){$t(this,AO,[n,t]),n._focusEventsAllowed=!1;break}}focus(){if(!fe(this,AO))return;const[t,n]=fe(this,AO);$t(this,AO,null),n.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),n.focus()}addEditListeners(){Xt(this,Ri,KGe).call(this),Xt(this,Ri,YGe).call(this)}removeEditListeners(){Xt(this,Ri,xXt).call(this),Xt(this,Ri,ZGe).call(this)}dragOver(t){for(const{type:n}of t.dataTransfer.items)for(const r of fe(this,vk))if(r.isHandlingMimeForPasting(n)){t.dataTransfer.dropEffect="copy",t.preventDefault();return}}drop(t){for(const n of t.dataTransfer.items)for(const r of fe(this,vk))if(r.isHandlingMimeForPasting(n.type)){r.paste(n,this.currentLayer),t.preventDefault();return}}copy(t){var r;if(t.preventDefault(),(r=fe(this,bw))==null||r.commitOrRemove(),!this.hasSelection)return;const n=[];for(const a of fe(this,xh)){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 fe(this,vk))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){nd(`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)Xt(this,Ri,XGe).call(this,c);Xt(this,Ri,QGe).call(this,i)},o=()=>{for(const c of i)c.remove()};this.addCommands({cmd:l,undo:o,mustExec:!0})}catch(i){nd(`paste: "${i.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),fe(this,V0)!==Uc.NONE&&!this.isEditorHandlingKeyboard&&zU._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,fe(this,S6)&&($t(this,S6,!1),Xt(this,Ri,p4e).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?(Xt(this,Ri,fXt).call(this),Xt(this,Ri,YGe).call(this),Xt(this,Ri,q1).call(this,{isEditing:fe(this,V0)!==Uc.NONE,isEmpty:Xt(this,Ri,BZ).call(this),hasSomethingToUndo:fe(this,yk).hasSomethingToUndo(),hasSomethingToRedo:fe(this,yk).hasSomethingToRedo(),hasSelectedEditor:!1})):(Xt(this,Ri,gXt).call(this),Xt(this,Ri,ZGe).call(this),Xt(this,Ri,q1).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!fe(this,vk)){$t(this,vk,t);for(const n of fe(this,vk))Xt(this,Ri,PT).call(this,n.defaultPropertiesToUpdate)}}getId(){return fe(this,$Te).id}get currentLayer(){return fe(this,Uy).get(fe(this,T$))}getLayer(t){return fe(this,Uy).get(t)}get currentPageIndex(){return fe(this,T$)}addLayer(t){fe(this,Uy).set(t.pageIndex,t),fe(this,C6)?t.enable():t.disable()}removeLayer(t){fe(this,Uy).delete(t.pageIndex)}async updateMode(t,n=null,r=!1){if(fe(this,V0)!==t&&!(fe(this,x2)&&(await fe(this,x2).promise,!fe(this,x2)))){if($t(this,x2,Promise.withResolvers()),$t(this,V0,t),t===Uc.NONE){this.setEditingState(!1),Xt(this,Ri,bXt).call(this),fe(this,x2).resolve();return}this.setEditingState(!0),await Xt(this,Ri,vXt).call(this),this.unselectAll();for(const a of fe(this,Uy).values())a.updateMode(t);if(!n){r&&this.addNewEditorFromKeyboard(),fe(this,x2).resolve();return}for(const a of fe(this,Vx).values())a.annotationElementId===n?(this.setSelected(a),a.enterInEditMode()):a.unselect();fe(this,x2).resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==fe(this,V0)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,n){var r;if(fe(this,vk)){switch(t){case dc.CREATE:this.currentLayer.addNewEditor();return;case dc.HIGHLIGHT_DEFAULT_COLOR:(r=fe(this,pse))==null||r.updateColor(n);break;case dc.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(fe(this,gse)||$t(this,gse,new Map)).set(t,n),this.showAllEditors("highlight",n);break}for(const a of fe(this,xh))a.updateParams(t,n);for(const a of fe(this,vk))a.updateDefaultParams(t,n)}}showAllEditors(t,n,r=!1){var i;for(const l of fe(this,Vx).values())l.editorType===t&&l.show(n);(((i=fe(this,gse))==null?void 0:i.get(dc.HIGHLIGHT_SHOW_ALL))??!0)!==n&&Xt(this,Ri,PT).call(this,[[dc.HIGHLIGHT_SHOW_ALL,n]])}enableWaiting(t=!1){if(fe(this,mse)!==t){$t(this,mse,t);for(const n of fe(this,Uy).values())t?n.disableClick():n.enableClick(),n.div.classList.toggle("waiting",t)}}getEditors(t){const n=[];for(const r of fe(this,Vx).values())r.pageIndex===t&&n.push(r);return n}getEditor(t){return fe(this,Vx).get(t)}addEditor(t){fe(this,Vx).set(t.id,t)}removeEditor(t){var n;t.div.contains(document.activeElement)&&(fe(this,O5)&&clearTimeout(fe(this,O5)),$t(this,O5,setTimeout(()=>{this.focusMainContainer(),$t(this,O5,null)},0))),fe(this,Vx).delete(t.id),this.unselect(t),(!t.annotationElementId||!fe(this,SO).has(t.annotationElementId))&&((n=fe(this,zC))==null||n.remove(t.id))}addDeletedAnnotationElement(t){fe(this,SO).add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return fe(this,SO).has(t)}removeDeletedAnnotationElement(t){fe(this,SO).delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}setActiveEditor(t){fe(this,bw)!==t&&($t(this,bw,t),t&&Xt(this,Ri,PT).call(this,t.propertiesToUpdate))}updateUI(t){fe(this,Ri,_Xt)===t&&Xt(this,Ri,PT).call(this,t.propertiesToUpdate)}toggleSelected(t){if(fe(this,xh).has(t)){fe(this,xh).delete(t),t.unselect(),Xt(this,Ri,q1).call(this,{hasSelectedEditor:this.hasSelection});return}fe(this,xh).add(t),t.select(),Xt(this,Ri,PT).call(this,t.propertiesToUpdate),Xt(this,Ri,q1).call(this,{hasSelectedEditor:!0})}setSelected(t){for(const n of fe(this,xh))n!==t&&n.unselect();fe(this,xh).clear(),fe(this,xh).add(t),t.select(),Xt(this,Ri,PT).call(this,t.propertiesToUpdate),Xt(this,Ri,q1).call(this,{hasSelectedEditor:!0})}isSelected(t){return fe(this,xh).has(t)}get firstSelectedEditor(){return fe(this,xh).values().next().value}unselect(t){t.unselect(),fe(this,xh).delete(t),Xt(this,Ri,q1).call(this,{hasSelectedEditor:this.hasSelection})}get hasSelection(){return fe(this,xh).size!==0}get isEnterHandled(){return fe(this,xh).size===1&&this.firstSelectedEditor.isEnterHandled}undo(){fe(this,yk).undo(),Xt(this,Ri,q1).call(this,{hasSomethingToUndo:fe(this,yk).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:Xt(this,Ri,BZ).call(this)})}redo(){fe(this,yk).redo(),Xt(this,Ri,q1).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:fe(this,yk).hasSomethingToRedo(),isEmpty:Xt(this,Ri,BZ).call(this)})}addCommands(t){fe(this,yk).add(t),Xt(this,Ri,q1).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:Xt(this,Ri,BZ).call(this)})}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const t=[...fe(this,xh)],n=()=>{for(const a of t)a.remove()},r=()=>{for(const a of t)Xt(this,Ri,XGe).call(this,a)};this.addCommands({cmd:n,undo:r,mustExec:!0})}commitOrRemove(){var t;(t=fe(this,bw))==null||t.commitOrRemove()}hasSomethingToControl(){return fe(this,bw)||this.hasSelection}selectAll(){for(const t of fe(this,xh))t.commit();Xt(this,Ri,QGe).call(this,fe(this,Vx).values())}unselectAll(){if(!(fe(this,bw)&&(fe(this,bw).commitOrRemove(),fe(this,V0)!==Uc.NONE))&&this.hasSelection){for(const t of fe(this,xh))t.unselect();fe(this,xh).clear(),Xt(this,Ri,q1).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(t,n,r=!1){if(r||this.commitOrRemove(),!this.hasSelection)return;fe(this,E6)[0]+=t,fe(this,E6)[1]+=n;const[a,i]=fe(this,E6),l=[...fe(this,xh)],o=1e3;fe(this,z5)&&clearTimeout(fe(this,z5)),$t(this,z5,setTimeout(()=>{$t(this,z5,null),fe(this,E6)[0]=fe(this,E6)[1]=0,this.addCommands({cmd:()=>{for(const c of l)fe(this,Vx).has(c.id)&&c.translateInPage(a,i)},undo:()=>{for(const c of l)fe(this,Vx).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),$t(this,D5,new Map);for(const t of fe(this,xh))fe(this,D5).set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!fe(this,D5))return!1;this.disableUserSelect(!1);const t=fe(this,D5);$t(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(fe(this,Vx).has(a.id)){const c=fe(this,Uy).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(fe(this,D5))for(const r of fe(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())||fe(this,xh).size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return fe(this,bw)===t}getActive(){return fe(this,bw)}getMode(){return fe(this,V0)}get imageManager(){return Yd(this,"imageManager",new HGe)}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"&&Xt(this,Ri,p4e).call(this,"main_toolbar"))};window.addEventListener("pointerup",h,{signal:u}),window.addEventListener("blur",h,{signal:u})}},p4e=function(t=""){fe(this,V0)===Uc.HIGHLIGHT?this.highlightSelection(t):fe(this,dse)&&Xt(this,Ri,hXt).call(this)},pXt=function(){document.addEventListener("selectionchange",Xt(this,Ri,mXt).bind(this),{signal:this._signal})},fXt=function(){if(fe(this,k6))return;$t(this,k6,new AbortController);const t=this.combinedSignal(fe(this,k6));window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})},gXt=function(){var t;(t=fe(this,k6))==null||t.abort(),$t(this,k6,null)},KGe=function(){if(fe(this,A6))return;$t(this,A6,new AbortController);const t=this.combinedSignal(fe(this,A6));window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})},xXt=function(){var t;(t=fe(this,A6))==null||t.abort(),$t(this,A6,null)},YGe=function(){if(fe(this,N6))return;$t(this,N6,new AbortController);const t=this.combinedSignal(fe(this,N6));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})},ZGe=function(){var t;(t=fe(this,N6))==null||t.abort(),$t(this,N6,null)},yXt=function(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})},q1=function(t){Object.entries(t).some(([r,a])=>fe(this,xse)[r]!==a)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(fe(this,xse),t)}),fe(this,V0)===Uc.HIGHLIGHT&&t.hasSelectedEditor===!1&&Xt(this,Ri,PT).call(this,[[dc.HIGHLIGHT_FREE,!0]]))},PT=function(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})},vXt=async function(){if(!fe(this,C6)){$t(this,C6,!0);const t=[];for(const n of fe(this,Uy).values())t.push(n.enable());await Promise.all(t);for(const n of fe(this,Vx).values())n.enable()}},bXt=function(){if(this.unselectAll(),fe(this,C6)){$t(this,C6,!1);for(const t of fe(this,Uy).values())t.disable();for(const t of fe(this,Vx).values())t.disable()}},XGe=function(t){const n=fe(this,Uy).get(t.pageIndex);n?n.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))},_Xt=function(){let t=null;for(t of fe(this,xh));return t},BZ=function(){if(fe(this,Vx).size===0)return!0;if(fe(this,Vx).size===1)for(const t of fe(this,Vx).values())return t.isEmpty();return!1},QGe=function(t){for(const n of fe(this,xh))n.unselect();fe(this,xh).clear();for(const n of t)n.isEmpty()||(fe(this,xh).add(n),n.select());Xt(this,Ri,q1).call(this,{hasSelectedEditor:this.hasSelection})},Lr(zU,"TRANSLATE_SMALL",1),Lr(zU,"TRANSLATE_BIG",10);let J7=zU;var H0,B5,bk,L$,U5,_w,I$,q5,r_,qC,TO,$5,T6,Wk,UZ,f4e;const V1=class V1{constructor(t){is(this,Wk);is(this,H0,null);is(this,B5,!1);is(this,bk,null);is(this,L$,null);is(this,U5,null);is(this,_w,null);is(this,I$,!1);is(this,q5,null);is(this,r_,null);is(this,qC,null);is(this,TO,null);is(this,$5,!1);$t(this,r_,t),$t(this,$5,t._uiManager.useNewAltTextFlow),fe(V1,T6)||$t(V1,T6,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){V1._l10n??(V1._l10n=t)}async render(){const t=$t(this,bk,document.createElement("button"));t.className="altText",t.tabIndex="0";const n=$t(this,L$,document.createElement("span"));t.append(n),fe(this,$5)?(t.classList.add("new"),t.setAttribute("data-l10n-id",fe(V1,T6).missing),n.setAttribute("data-l10n-id",fe(V1,T6)["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=fe(this,r_)._uiManager._signal;t.addEventListener("contextmenu",xN,{signal:r}),t.addEventListener("pointerdown",i=>i.stopPropagation(),{signal:r});const a=i=>{i.preventDefault(),fe(this,r_)._uiManager.editAltText(fe(this,r_)),fe(this,$5)&&fe(this,r_)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:fe(this,Wk,UZ)}})};return t.addEventListener("click",a,{capture:!0,signal:r}),t.addEventListener("keydown",i=>{i.target===t&&i.key==="Enter"&&($t(this,I$,!0),a(i))},{signal:r}),await Xt(this,Wk,f4e).call(this),t}finish(){fe(this,bk)&&(fe(this,bk).focus({focusVisible:fe(this,I$)}),$t(this,I$,!1))}isEmpty(){return fe(this,$5)?fe(this,H0)===null:!fe(this,H0)&&!fe(this,B5)}hasData(){return fe(this,$5)?fe(this,H0)!==null||!!fe(this,qC):this.isEmpty()}get guessedText(){return fe(this,qC)}async setGuessedText(t){fe(this,H0)===null&&($t(this,qC,t),$t(this,TO,await V1._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t})),Xt(this,Wk,f4e).call(this))}toggleAltTextBadge(t=!1){var n;if(!fe(this,$5)||fe(this,H0)){(n=fe(this,q5))==null||n.remove(),$t(this,q5,null);return}if(!fe(this,q5)){const r=$t(this,q5,document.createElement("div"));r.className="noAltTextBadge",fe(this,r_).div.append(r)}fe(this,q5).classList.toggle("hidden",!t)}serialize(t){let n=fe(this,H0);return!t&&fe(this,qC)===n&&(n=fe(this,TO)),{altText:n,decorative:fe(this,B5),guessedText:fe(this,qC),textWithDisclaimer:fe(this,TO)}}get data(){return{altText:fe(this,H0),decorative:fe(this,B5)}}set data({altText:t,decorative:n,guessedText:r,textWithDisclaimer:a,cancel:i=!1}){r&&($t(this,qC,r),$t(this,TO,a)),!(fe(this,H0)===t&&fe(this,B5)===n)&&(i||($t(this,H0,t),$t(this,B5,n)),Xt(this,Wk,f4e).call(this))}toggle(t=!1){fe(this,bk)&&(!t&&fe(this,_w)&&(clearTimeout(fe(this,_w)),$t(this,_w,null)),fe(this,bk).disabled=!t)}shown(){fe(this,r_)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:fe(this,Wk,UZ)}})}destroy(){var t,n;(t=fe(this,bk))==null||t.remove(),$t(this,bk,null),$t(this,L$,null),$t(this,U5,null),(n=fe(this,q5))==null||n.remove(),$t(this,q5,null)}};H0=new WeakMap,B5=new WeakMap,bk=new WeakMap,L$=new WeakMap,U5=new WeakMap,_w=new WeakMap,I$=new WeakMap,q5=new WeakMap,r_=new WeakMap,qC=new WeakMap,TO=new WeakMap,$5=new WeakMap,T6=new WeakMap,Wk=new WeakSet,UZ=function(){return fe(this,H0)&&"added"||fe(this,H0)===null&&this.guessedText&&"review"||"missing"},f4e=async function(){var a,i,l;const t=fe(this,bk);if(!t)return;if(fe(this,$5)){if(t.classList.toggle("done",!!fe(this,H0)),t.setAttribute("data-l10n-id",fe(V1,T6)[fe(this,Wk,UZ)]),(a=fe(this,L$))==null||a.setAttribute("data-l10n-id",fe(V1,T6)[`${fe(this,Wk,UZ)}-label`]),!fe(this,H0)){(i=fe(this,U5))==null||i.remove();return}}else{if(!fe(this,H0)&&!fe(this,B5)){t.classList.remove("done"),(l=fe(this,U5))==null||l.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let n=fe(this,U5);if(!n){$t(this,U5,n=document.createElement("span")),n.className="tooltip",n.setAttribute("role","tooltip"),n.id=`alt-text-tooltip-${fe(this,r_).id}`;const o=100,c=fe(this,r_)._uiManager._signal;c.addEventListener("abort",()=>{clearTimeout(fe(this,_w)),$t(this,_w,null)},{once:!0}),t.addEventListener("mouseenter",()=>{$t(this,_w,setTimeout(()=>{$t(this,_w,null),fe(this,U5).classList.add("show"),fe(this,r_)._reportTelemetry({action:"alt_text_tooltip"})},o))},{signal:c}),t.addEventListener("mouseleave",()=>{var d;fe(this,_w)&&(clearTimeout(fe(this,_w)),$t(this,_w,null)),(d=fe(this,U5))==null||d.classList.remove("show")},{signal:c})}fe(this,B5)?n.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(n.removeAttribute("data-l10n-id"),n.textContent=fe(this,H0)),n.parentNode||t.append(n);const r=fe(this,r_).getImageForAltText();r==null||r.setAttribute("aria-describedby",n.id)},is(V1,T6,null),Lr(V1,"_l10n",null);let eTe=V1;var MO,_k,lf,R$,PO,qy,LO,M6,vse,IO,P6,bse,RO,$C,V5,D$,O$,y2,_se,VTe,Zc,JGe,wse,eWe,tWe,wXt,jXt,sWe,nWe,rWe,NXt,aWe,kXt,SXt,CXt,iWe,qZ;const oh=class oh{constructor(t){is(this,Zc);is(this,MO,null);is(this,_k,null);is(this,lf,null);is(this,R$,!1);is(this,PO,!1);is(this,qy,null);is(this,LO,null);is(this,M6,null);is(this,vse,"");is(this,IO,!1);is(this,P6,null);is(this,bse,!1);is(this,RO,!1);is(this,$C,!1);is(this,V5,null);is(this,D$,0);is(this,O$,0);is(this,y2,null);Lr(this,"_editToolbar",null);Lr(this,"_initialOptions",Object.create(null));Lr(this,"_initialData",null);Lr(this,"_isVisible",!0);Lr(this,"_uiManager",null);Lr(this,"_focusEventsAllowed",!0);is(this,_se,!1);is(this,VTe,oh._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=oh.prototype._resizeWithKeyboard,n=J7.TRANSLATE_SMALL,r=J7.TRANSLATE_BIG;return Yd(this,"_resizerKeyboardManager",new tae([[["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"],oh.prototype._stopResizingWithKeyboard]]))}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return Yd(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const n=new ZBn({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(oh._l10n??(oh._l10n=t),oh._l10nResizer||(oh._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"})),oh._borderLineWidth!==-1)return;const r=getComputedStyle(document.documentElement);oh._borderLineWidth=parseFloat(r.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,n){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,n){ip("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return fe(this,_se)}set _isDraggable(t){var n;$t(this,_se,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=fe(this,VTe)}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):Xt(this,Zc,qZ).call(this),this.parent=t}focusin(t){this._focusEventsAllowed&&(fe(this,IO)?$t(this,IO,!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){Xt(this,Zc,JGe).call(this,this.parentDimensions,t,n)}translateInPage(t,n){fe(this,P6)||$t(this,P6,[this.x,this.y]),Xt(this,Zc,JGe).call(this,this.pageDimensions,t,n),this.div.scrollIntoView({block:"nearest"})}drag(t,n){fe(this,P6)||$t(this,P6,[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!!fe(this,P6)&&(fe(this,P6)[0]!==this.x||fe(this,P6)[1]!==this.y)}getBaseTranslation(){const[t,n]=this.parentDimensions,{_borderLineWidth:r}=oh,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 Xt(r=oh,wse,eWe).call(r,t,n,this.parentRotation)}pageTranslationToScreen(t,n){var r;return Xt(r=oh,wse,eWe).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)}%`,fe(this,PO)||(this.div.style.height=`${(100*n/a).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:n,width:r}=t,a=r.endsWith("%"),i=!fe(this,PO)&&n.endsWith("%");if(a&&i)return;const[l,o]=this.parentDimensions;a||(t.width=`${(100*parseFloat(r)/l).toFixed(2)}%`),!fe(this,PO)&&!i&&(t.height=`${(100*parseFloat(n)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}altTextFinish(){var t;(t=fe(this,lf))==null||t.finish()}async addEditToolbar(){return this._editToolbar||fe(this,RO)?this._editToolbar:(this._editToolbar=new $Ge(this),this.div.append(this._editToolbar.render()),fe(this,lf)&&await this._editToolbar.addAltText(fe(this,lf)),this._editToolbar)}removeEditToolbar(){var t;this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,(t=fe(this,lf))==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(){fe(this,lf)||(eTe.initialize(oh._l10n),$t(this,lf,new eTe(this)),fe(this,MO)&&(fe(this,lf).data=fe(this,MO),$t(this,MO,null)),await this.addEditToolbar())}get altTextData(){var t;return(t=fe(this,lf))==null?void 0:t.data}set altTextData(t){fe(this,lf)&&(fe(this,lf).data=t)}get guessedAltText(){var t;return(t=fe(this,lf))==null?void 0:t.guessedText}async setGuessedAltText(t){var n;await((n=fe(this,lf))==null?void 0:n.setGuessedText(t))}serializeAltText(t){var n;return(n=fe(this,lf))==null?void 0:n.serialize(t)}hasAltText(){return!!fe(this,lf)&&!fe(this,lf).isEmpty()}hasAltTextData(){var t;return((t=fe(this,lf))==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=fe(this,R$)?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),Xt(this,Zc,aWe).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),JEe(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:n}=fb.platform;if(t.button!==0||t.ctrlKey&&n){t.preventDefault();return}if($t(this,IO,!0),this._isDraggable){Xt(this,Zc,NXt).call(this,t);return}Xt(this,Zc,rWe).call(this,t)}get isSelected(){return this._uiManager.isSelected(this)}moveInDOM(){fe(this,V5)&&clearTimeout(fe(this,V5)),$t(this,V5,setTimeout(()=>{var t;$t(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,p=this.width*i,f=this.height*l;switch(r){case 0:return[h+d+o,l-m-u-f+c,h+d+p+o,l-m-u+c];case 90:return[h+u+o,l-m+d+c,h+u+f+o,l-m+d+p+c];case 180:return[h-d-p+o,l-m+u+c,h-d+o,l-m+u+f+c];case 270:return[h-u-f+o,l-m-d-p+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(){$t(this,RO,!0)}disableEditMode(){$t(this,RO,!1)}isInEditMode(){return fe(this,RO)}shouldGetKeyboardEvents(){return fe(this,$C)}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){Xt(this,Zc,aWe).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){ip("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,$t(a,MO,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=fe(this,M6))==null||t.abort(),$t(this,M6,null),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),fe(this,V5)&&(clearTimeout(fe(this,V5)),$t(this,V5,null)),Xt(this,Zc,qZ).call(this),this.removeEditToolbar(),fe(this,y2)){for(const n of fe(this,y2).values())clearTimeout(n);$t(this,y2,null)}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(Xt(this,Zc,wXt).call(this),fe(this,qy).classList.remove("hidden"),JEe(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),$t(this,LO,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const n=fe(this,qy).children;if(!fe(this,_k)){$t(this,_k,Array.from(n));const l=Xt(this,Zc,kXt).bind(this),o=Xt(this,Zc,SXt).bind(this),c=this._uiManager._signal;for(const d of fe(this,_k)){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",Xt(this,Zc,CXt).bind(this,u),{signal:c}),d.setAttribute("data-l10n-id",oh._l10nResizer[u])}}const r=fe(this,_k)[0];let a=0;for(const l of n){if(l===r)break;a++}const i=(360-this.rotation+this.parentRotation)%360/90*(fe(this,_k).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=fe(this,lf))==null||r.toggleAltTextBadge(!1)}unselect(){var t,n,r,a,i;(t=fe(this,qy))==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=fe(this,lf))==null||i.toggleAltTextBadge(!0)}updateParams(t,n){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return fe(this,bse)}set isEditing(t){$t(this,bse,t),this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,n){$t(this,PO,!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){fe(this,y2)||$t(this,y2,new Map);const{action:r}=t;let a=fe(this,y2).get(r);a&&clearTimeout(a),a=setTimeout(()=>{this._reportTelemetry(t),fe(this,y2).delete(r),fe(this,y2).size===0&&$t(this,y2,null)},oh._telemetryTimeout),fe(this,y2).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),$t(this,R$,!1)}disable(){this.div&&(this.div.tabIndex=-1),$t(this,R$,!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()}};MO=new WeakMap,_k=new WeakMap,lf=new WeakMap,R$=new WeakMap,PO=new WeakMap,qy=new WeakMap,LO=new WeakMap,M6=new WeakMap,vse=new WeakMap,IO=new WeakMap,P6=new WeakMap,bse=new WeakMap,RO=new WeakMap,$C=new WeakMap,V5=new WeakMap,D$=new WeakMap,O$=new WeakMap,y2=new WeakMap,_se=new WeakMap,VTe=new WeakMap,Zc=new WeakSet,JGe=function([t,n],r,a){[r,a]=this.screenToPageTranslation(r,a),this.x+=r/t,this.y+=a/n,this.fixAndSetPosition()},wse=new WeakSet,eWe=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]}},tWe=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]}},wXt=function(){if(fe(this,qy))return;$t(this,qy,document.createElement("div")),fe(this,qy).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");fe(this,qy).append(a),a.classList.add("resizer",r),a.setAttribute("data-resizer-name",r),a.addEventListener("pointerdown",Xt(this,Zc,jXt).bind(this,r),{signal:n}),a.addEventListener("contextmenu",xN,{signal:n}),a.tabIndex=-1}this.div.prepend(fe(this,qy))},jXt=function(t,n){var f;n.preventDefault();const{isMac:r}=fb.platform;if(n.button!==0||n.ctrlKey&&r)return;(f=fe(this,lf))==null||f.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",Xt(this,Zc,nWe).bind(this,t),{passive:!0,capture:!0,signal:l}),window.addEventListener("contextmenu",xN,{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 p=()=>{var x;i.abort(),this.parent.togglePointerEvents(!0),(x=fe(this,lf))==null||x.toggle(!0),this._isDraggable=a,this.parent.div.style.cursor=h,this.div.style.cursor=m,Xt(this,Zc,sWe).call(this,o,c,d,u)};window.addEventListener("pointerup",p,{signal:l}),window.addEventListener("blur",p,{signal:l})},sWe=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})},nWe=function(t,n){const[r,a]=this.parentDimensions,i=this.x,l=this.y,o=this.width,c=this.height,d=oh.MIN_SIZE/r,u=oh.MIN_SIZE/a,h=Q=>Math.round(Q*1e4)/1e4,m=Xt(this,Zc,tWe).call(this,this.rotation),p=(Q,le)=>[m[0]*Q+m[2]*le,m[1]*Q+m[3]*le],f=Xt(this,Zc,tWe).call(this,360-this.rotation),x=(Q,le)=>[f[0]*Q+f[2]*le,f[1]*Q+f[3]*le];let y,v,b=!1,N=!1;switch(t){case"topLeft":b=!0,y=(Q,le)=>[0,0],v=(Q,le)=>[Q,le];break;case"topMiddle":y=(Q,le)=>[Q/2,0],v=(Q,le)=>[Q/2,le];break;case"topRight":b=!0,y=(Q,le)=>[Q,0],v=(Q,le)=>[0,le];break;case"middleRight":N=!0,y=(Q,le)=>[Q,le/2],v=(Q,le)=>[0,le/2];break;case"bottomRight":b=!0,y=(Q,le)=>[Q,le],v=(Q,le)=>[0,0];break;case"bottomMiddle":y=(Q,le)=>[Q/2,le],v=(Q,le)=>[Q/2,0];break;case"bottomLeft":b=!0,y=(Q,le)=>[0,le],v=(Q,le)=>[Q,0];break;case"middleLeft":N=!0,y=(Q,le)=>[0,le/2],v=(Q,le)=>[Q,le/2];break}const S=y(o,c),A=v(o,c);let T=p(...A);const L=h(i+T[0]),M=h(l+T[1]);let I=1,R=1,[z,$]=this.screenToPageTranslation(n.movementX,n.movementY);if([z,$]=x(z/r,$/a),b){const Q=Math.hypot(o,c);I=R=Math.max(Math.min(Math.hypot(A[0]-S[0]-z,A[1]-S[1]-$)/Q,1/o,1/c),d/o,u/c)}else N?I=Math.max(d,Math.min(1,Math.abs(A[0]-S[0]-z)))/o:R=Math.max(u,Math.min(1,Math.abs(A[1]-S[1]-$)))/c;const H=h(o*I),V=h(c*R);T=p(...v(H,V));const K=L-T[0],Z=M-T[1];this.width=H,this.height=V,this.x=K,this.y=Z,this.setDims(r*H,a*V),this.fixAndSetPosition()},rWe=function(t){const{isMac:n}=fb.platform;t.ctrlKey&&!n||t.shiftKey||t.metaKey&&n?this.parent.toggleSelected(this):this.parent.setSelected(this)},NXt=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"),$t(this,D$,t.clientX),$t(this,O$,t.clientY);const l=o=>{const{clientX:c,clientY:d}=o,[u,h]=this.screenToPageTranslation(c-fe(this,D$),d-fe(this,O$));$t(this,D$,c),$t(this,O$,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"),$t(this,IO,!1),this._uiManager.endDragSession()||Xt(this,Zc,rWe).call(this,t)};window.addEventListener("pointerup",i,{signal:a}),window.addEventListener("blur",i,{signal:a})},aWe=function(){if(fe(this,M6)||!this.div)return;$t(this,M6,new AbortController);const t=this._uiManager.combinedSignal(fe(this,M6));this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})},kXt=function(t){oh._resizerKeyboardManager.exec(this,t)},SXt=function(t){var n;fe(this,$C)&&((n=t.relatedTarget)==null?void 0:n.parentNode)!==fe(this,qy)&&Xt(this,Zc,qZ).call(this)},CXt=function(t){$t(this,vse,fe(this,$C)?t:"")},iWe=function(t){if(fe(this,_k))for(const n of fe(this,_k))n.tabIndex=t},qZ=function(){if($t(this,$C,!1),Xt(this,Zc,iWe).call(this,-1),fe(this,LO)){const{savedX:t,savedY:n,savedWidth:r,savedHeight:a}=fe(this,LO);Xt(this,Zc,sWe).call(this,t,n,r,a),$t(this,LO,null)}},is(oh,wse),Lr(oh,"_l10n",null),Lr(oh,"_l10nResizer",null),Lr(oh,"_borderLineWidth",-1),Lr(oh,"_colorManager",new GGe),Lr(oh,"_zIndex",1),Lr(oh,"_telemetryTimeout",1e3);let wh=oh;class ZBn extends wh{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const SNt=3285377520,c2=4294901760,u5=65535;class AXt{constructor(t){this.h1=t?t&4294967295:SNt,this.h2=t?t&4294967295:SNt}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,p=h&u5,f=m&u5;for(let x=0;x>>17,o=o*m&c2|o*f&u5,d^=o,d=d<<13|d>>>19,d=d*5+3864292196):(c=l[x],c=c*h&c2|c*p&u5,c=c<<15|c>>>17,c=c*m&c2|c*f&u5,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&c2|o*p&u5,o=o<<15|o>>>17,o=o*m&c2|o*f&u5,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&c2|t*36045&u5,n=n*4283543511&c2|((n<<16|t>>>16)*2950163797&c2)>>>16,t^=n>>>1,t=t*444984403&c2|t*60499&u5,n=n*3301882366&c2|((n<<16|t>>>16)*3120437893&c2)>>>16,t^=n>>>1,(t>>>0).toString(16).padStart(8,"0")+(n>>>0).toString(16).padStart(8,"0")}}const oWe=Object.freeze({map:null,hash:"",transfer:void 0});var DO,OO,G0,HTe,EXt;class vnt{constructor(){is(this,HTe);is(this,DO,!1);is(this,OO,null);is(this,G0,new Map);this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,n){const r=fe(this,G0).get(t);return r===void 0?n:Object.assign(n,r)}getRawValue(t){return fe(this,G0).get(t)}remove(t){if(fe(this,G0).delete(t),fe(this,G0).size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const n of fe(this,G0).values())if(n instanceof wh)return;this.onAnnotationEditor(null)}}setValue(t,n){const r=fe(this,G0).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,fe(this,G0).set(t,n);a&&Xt(this,HTe,EXt).call(this),n instanceof wh&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(n.constructor._type)}has(t){return fe(this,G0).has(t)}getAll(){return fe(this,G0).size>0?mnt(fe(this,G0)):null}setAll(t){for(const[n,r]of Object.entries(t))this.setValue(n,r)}get size(){return fe(this,G0).size}resetModified(){fe(this,DO)&&($t(this,DO,!1),typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new TXt(this)}get serializable(){if(fe(this,G0).size===0)return oWe;const t=new Map,n=new AXt,r=[],a=Object.create(null);let i=!1;for(const[l,o]of fe(this,G0)){const c=o instanceof wh?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}:oWe}get editorStats(){let t=null;const n=new Map;for(const r of fe(this,G0).values()){if(!(r instanceof wh))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(){$t(this,OO,null)}get modifiedIds(){if(fe(this,OO))return fe(this,OO);const t=[];for(const n of fe(this,G0).values())!(n instanceof wh)||!n.annotationElementId||!n.serialize()||t.push(n.annotationElementId);return $t(this,OO,{ids:new Set(t),hash:t.join(",")})}}DO=new WeakMap,OO=new WeakMap,G0=new WeakMap,HTe=new WeakSet,EXt=function(){fe(this,DO)||($t(this,DO,!0),typeof this.onSetModified=="function"&&this.onSetModified())};var jse;class TXt extends vnt{constructor(n){super();is(this,jse);const{map:r,hash:a,transfer:i}=n.serializable,l=structuredClone(r,i?{transfer:i}:null);$t(this,jse,{map:l,hash:a,transfer:i})}get print(){ip("Should not call PrintAnnotationStorage.print")}get serializable(){return fe(this,jse)}get modifiedIds(){return Yd(this,"modifiedIds",{ids:new Set,hash:""})}}jse=new WeakMap;var F$;class XBn{constructor({ownerDocument:t=globalThis.document,styleElement:n=null}){is(this,F$,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(),fe(this,F$).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:n}){if(!(!t||fe(this,F$).has(t.loadedName))){if(r0(!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(),fe(this,F$).add(r),n==null||n(t)}catch{nd(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(l)}return}ip("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 nd(`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 Yd(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(s1||typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.userAgent)=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),Yd(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function n(){for(r0(!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 Yd(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,T,L){const M=S.substring(0,A),I=S.substring(A+T);return M+L+I}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){nd("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 f=16,x=1482184792;let y=r(m,f);for(i=0,l=h.length-3;i{N.remove(),n.complete()})}}F$=new WeakMap;class QBn{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,${UBn(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){nd(`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;ip.bezierCurveTo(o,c,d,u,h,m)),i+=6}break;case iC.MOVE_TO:{const[o,c]=r.slice(i,i+2);a.push(d=>d.moveTo(o,c)),i+=2}break;case iC.LINE_TO:{const[o,c]=r.slice(i,i+2);a.push(d=>d.lineTo(o,c)),i+=2}break;case iC.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 iC.RESTORE:a.push(o=>o.restore());break;case iC.SAVE:a.push(o=>o.save());break;case iC.SCALE:r0(a.length===2,"Scale command is only valid at the third position.");break;case iC.TRANSFORM:{const[o,c,d,u,h,m]=r.slice(i,i+6);a.push(p=>p.transform(o,c,d,u,h,m)),i+=6}break;case iC.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){ip("Abstract method `_fetch` called.")}}class LXt extends PXt{async _fetch(t){const n=await jIe(t,this.isCompressed?"arraybuffer":"text");return n instanceof ArrayBuffer?new Uint8Array(n):wIe(n)}}class IXt{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 FO,zO,H5,VC,Gv,GTe,BO,so,$v,HB,GB,g4e,WB,RXt,lWe,KB,$Z,VZ,cWe,HZ;class eUn extends IXt{constructor({docId:n,ownerDocument:r=globalThis.document}){super();is(this,so);is(this,FO);is(this,zO);is(this,H5);is(this,VC);is(this,Gv);is(this,GTe);is(this,BO,0);$t(this,VC,n),$t(this,Gv,r)}addFilter(n){if(!n)return"none";let r=fe(this,so,$v).get(n);if(r)return r;const[a,i,l]=Xt(this,so,g4e).call(this,n),o=n.length===1?a:`${a}${i}${l}`;if(r=fe(this,so,$v).get(o),r)return fe(this,so,$v).set(n,r),r;const c=`g_${fe(this,VC)}_transfer_map_${O0(this,BO)._++}`,d=Xt(this,so,WB).call(this,c);fe(this,so,$v).set(n,d),fe(this,so,$v).set(o,d);const u=Xt(this,so,KB).call(this,c);return Xt(this,so,VZ).call(this,a,i,l,u),d}addHCMFilter(n,r){var f;const a=`${n}-${r}`,i="base";let l=fe(this,so,HB).get(i);if((l==null?void 0:l.key)===a||(l?((f=l.filter)==null||f.remove(),l.key=a,l.url="none",l.filter=null):(l={key:a,url:"none",filter:null},fe(this,so,HB).set(i,l)),!n||!r))return l.url;const o=Xt(this,so,HZ).call(this,n);n=Lo.makeHexColor(...o);const c=Xt(this,so,HZ).call(this,r);if(r=Lo.makeHexColor(...c),fe(this,so,GB).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_${fe(this,VC)}_hcm_filter`,m=l.filter=Xt(this,so,KB).call(this,h);Xt(this,so,VZ).call(this,u,u,u,m),Xt(this,so,lWe).call(this,m);const p=(x,y)=>{const v=o[x]/255,b=c[x]/255,N=new Array(y+1);for(let S=0;S<=y;S++)N[S]=v+S/y*(b-v);return N.join(",")};return Xt(this,so,VZ).call(this,p(0,5),p(1,5),p(2,5),m),l.url=Xt(this,so,WB).call(this,h),l.url}addAlphaFilter(n){let r=fe(this,so,$v).get(n);if(r)return r;const[a]=Xt(this,so,g4e).call(this,[n]),i=`alpha_${a}`;if(r=fe(this,so,$v).get(i),r)return fe(this,so,$v).set(n,r),r;const l=`g_${fe(this,VC)}_alpha_map_${O0(this,BO)._++}`,o=Xt(this,so,WB).call(this,l);fe(this,so,$v).set(n,o),fe(this,so,$v).set(i,o);const c=Xt(this,so,KB).call(this,l);return Xt(this,so,cWe).call(this,a,c),o}addLuminosityFilter(n){let r=fe(this,so,$v).get(n||"luminosity");if(r)return r;let a,i;if(n?([a]=Xt(this,so,g4e).call(this,[n]),i=`luminosity_${a}`):i="luminosity",r=fe(this,so,$v).get(i),r)return fe(this,so,$v).set(n,r),r;const l=`g_${fe(this,VC)}_luminosity_map_${O0(this,BO)._++}`,o=Xt(this,so,WB).call(this,l);fe(this,so,$v).set(n,o),fe(this,so,$v).set(i,o);const c=Xt(this,so,KB).call(this,l);return Xt(this,so,RXt).call(this,c),n&&Xt(this,so,cWe).call(this,a,c),o}addHighlightHCMFilter(n,r,a,i,l){var b;const o=`${r}-${a}-${i}-${l}`;let c=fe(this,so,HB).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},fe(this,so,HB).set(n,c)),!r||!a))return c.url;const[d,u]=[r,a].map(Xt(this,so,HZ).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]),[p,f]=[i,l].map(Xt(this,so,HZ).bind(this));m{const T=new Array(256),L=(m-h)/A,M=N/255,I=(S-N)/(255*A);let R=0;for(let z=0;z<=A;z++){const $=Math.round(h+z*L),H=M+z*I;for(let V=R;V<=$;V++)T[V]=H;R=$+1}for(let z=R;z<256;z++)T[z]=T[R-1];return T.join(",")},y=`g_${fe(this,VC)}_hcm_${n}_filter`,v=c.filter=Xt(this,so,KB).call(this,y);return Xt(this,so,lWe).call(this,v),Xt(this,so,VZ).call(this,x(p[0],f[0],5),x(p[1],f[1],5),x(p[2],f[2],5),v),c.url=Xt(this,so,WB).call(this,y),c.url}destroy(n=!1){n&&fe(this,so,HB).size!==0||(fe(this,H5)&&(fe(this,H5).parentNode.parentNode.remove(),$t(this,H5,null)),fe(this,zO)&&(fe(this,zO).clear(),$t(this,zO,null)),$t(this,BO,0))}}FO=new WeakMap,zO=new WeakMap,H5=new WeakMap,VC=new WeakMap,Gv=new WeakMap,GTe=new WeakMap,BO=new WeakMap,so=new WeakSet,$v=function(){return fe(this,zO)||$t(this,zO,new Map)},HB=function(){return fe(this,GTe)||$t(this,GTe,new Map)},GB=function(){if(!fe(this,H5)){const n=fe(this,Gv).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=fe(this,Gv).createElementNS(xC,"svg");a.setAttribute("width",0),a.setAttribute("height",0),$t(this,H5,fe(this,Gv).createElementNS(xC,"defs")),n.append(a),a.append(fe(this,H5)),fe(this,Gv).body.append(n)}return fe(this,H5)},g4e=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(",")]},WB=function(n){if(fe(this,FO)===void 0){$t(this,FO,"");const r=fe(this,Gv).URL;r!==fe(this,Gv).baseURI&&(NIe(r)?nd('#createUrl: ignore "data:"-URL for performance reasons.'):$t(this,FO,r.split("#",1)[0]))}return`url(${fe(this,FO)}#${n})`},RXt=function(n){const r=fe(this,Gv).createElementNS(xC,"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)},lWe=function(n){const r=fe(this,Gv).createElementNS(xC,"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)},KB=function(n){const r=fe(this,Gv).createElementNS(xC,"filter");return r.setAttribute("color-interpolation-filters","sRGB"),r.setAttribute("id",n),fe(this,so,GB).append(r),r},$Z=function(n,r,a){const i=fe(this,Gv).createElementNS(xC,r);i.setAttribute("type","discrete"),i.setAttribute("tableValues",a),n.append(i)},VZ=function(n,r,a,i){const l=fe(this,Gv).createElementNS(xC,"feComponentTransfer");i.append(l),Xt(this,so,$Z).call(this,l,"feFuncR",n),Xt(this,so,$Z).call(this,l,"feFuncG",r),Xt(this,so,$Z).call(this,l,"feFuncB",a)},cWe=function(n,r){const a=fe(this,Gv).createElementNS(xC,"feComponentTransfer");r.append(a),Xt(this,so,$Z).call(this,a,"feFuncA",n)},HZ=function(n){return fe(this,so,GB).style.color=n,ynt(getComputedStyle(fe(this,so,GB)).getPropertyValue("color"))};class DXt{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){ip("Abstract method `_fetch` called.")}}class OXt extends DXt{async _fetch(t){const n=await jIe(t,"arraybuffer");return new Uint8Array(n)}}if(s1){var dWe=Promise.withResolvers(),mJ=null;(async()=>{const t=await ui(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),n=await ui(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),r=await ui(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),a=await ui(()=>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=>{mJ=t,dWe.resolve()},t=>{nd(`loadPackages: ${t}`),mJ=new Map,dWe.resolve()})}class wP{static get promise(){return dWe.promise}static get(t){return mJ==null?void 0:mJ.get(t)}}async function FXt(s){const n=await wP.get("fs").promises.readFile(s);return new Uint8Array(n)}class tUn extends IXt{}class sUn extends MXt{_createCanvas(t,n){return wP.get("canvas").createCanvas(t,n)}}class nUn extends PXt{async _fetch(t){return FXt(t)}}class rUn extends DXt{async _fetch(t){return FXt(t)}}const X1={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function uWe(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 bnt{getPattern(){ip("Abstract method `getPattern` called.")}}class aUn extends bnt{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===X1.STROKE||a===X1.FILL){const l=n.current.getClippedPathBoundingBox(a,df(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=Lo.transform(r,[1,0,0,1,l[0],l[1]]),u.transform(...n.baseTransform),this.matrix&&u.transform(...this.matrix),uWe(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 uWe(t,this._bbox),i=this._createGradient(t);return i}}function F9e(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 p=(c[n]+t.offsetX)*t.scaleX,f=(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(f>=b)return;const N=d[i],S=d[i+1],A=d[i+2],T=d[l],L=d[l+1],M=d[l+2],I=d[o],R=d[o+1],z=d[o+2],$=Math.round(f),H=Math.round(b);let V,K,Z,Q,le,ue,se,ne;for(let ie=$;ie<=H;ie++){if(ieb?ge=1:y===b?ge=0:ge=(y-ie)/(y-b),V=x-(x-v)*ge,K=T-(T-I)*ge,Z=L-(L-R)*ge,Q=M-(M-z)*ge}let ce;ieb?ce=1:ce=(f-ie)/(f-b),le=p-(p-v)*ce,ue=N-(N-I)*ce,se=S-(S-R)*ce,ne=A-(A-z)*ce;const je=Math.round(Math.min(V,le)),be=Math.round(Math.max(V,le));let he=h*ie+je*4;for(let ge=je;ge<=be;ge++)ce=(V-ge)/(V-le),ce<0?ce=0:ce>1&&(ce=1),u[he++]=K-(K-ue)*ce|0,u[he++]=Z-(Z-se)*ce|0,u[he++]=Q-(Q-ne)*ce|0,u[he++]=255}}function iUn(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=R?S=c:T=!0,I>=z?A=d:L=!0;const $=this.getSizeAndScale(S,this.ctx.canvas.width,b),H=this.getSizeAndScale(A,this.ctx.canvas.height,N),V=t.cachedCanvases.getCanvas("pattern",$.size,H.size),K=V.context,Z=o.createCanvasGraphics(K);if(Z.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(Z,a,l),K.translate(-$.scale*u,-H.scale*h),Z.transform($.scale,0,0,H.scale,0,0),K.save(),this.clipBbox(Z,u,h,m,p),Z.baseTransform=df(Z.ctx),Z.executeOperatorList(r),Z.endDrawing(),K.restore(),T||L){const Q=V.canvas;T&&(S=c),L&&(A=d);const le=this.getSizeAndScale(S,this.ctx.canvas.width,b),ue=this.getSizeAndScale(A,this.ctx.canvas.height,N),se=le.size,ne=ue.size,ie=t.cachedCanvases.getCanvas("pattern-workaround",se,ne),ce=ie.context,je=T?Math.floor(f/c):0,be=L?Math.floor(x/d):0;for(let he=0;he<=je;he++)for(let ge=0;ge<=be;ge++)ce.drawImage(Q,se*he,ne*ge,se,ne,0,0,se,ne);return{canvas:ie.canvas,scaleX:le.scale,scaleY:ue.scale,offsetX:u,offsetY:h}}return{canvas:V.canvas,scaleX:$.scale,scaleY:H.scale,offsetX:u,offsetY:h}}getSizeAndScale(t,n,r){const a=Math.max(WTe.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(df(t.ctx),[n,r,a,i]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,n,r){const a=t.ctx,i=t.current;switch(n){case CNt.COLORED:const l=this.ctx;a.fillStyle=l.fillStyle,a.strokeStyle=l.strokeStyle,i.fillColor=l.fillStyle,i.strokeColor=l.strokeStyle;break;case CNt.UNCOLORED:const o=Lo.makeHexColor(r[0],r[1],r[2]);a.fillStyle=o,a.strokeStyle=o,i.fillColor=o,i.strokeColor=o;break;default:throw new IBn(`Unsupported paint type: ${n}`)}}getPattern(t,n,r,a){let i=r;a!==X1.SHADING&&(i=Lo.transform(i,n.baseTransform),this.matrix&&(i=Lo.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}};Lr(WTe,"MAX_PATTERN_SIZE",3e3);let hWe=WTe;function dUn({src:s,srcPos:t=0,dest:n,width:r,height:a,nonBlackColor:i=4294967295,inverseDecode:l=!1}){const o=fb.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 p=0;for(let f=0;f{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 mUn{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 oce(s,t,n,r,a,i,l,o,c,d){const[u,h,m,p,f,x]=df(s);if(h===0&&m===0){const b=l*u+f,N=Math.round(b),S=o*p+x,A=Math.round(S),T=(l+c)*u+f,L=Math.abs(Math.round(T)-N)||1,M=(o+d)*p+x,I=Math.abs(Math.round(M)-A)||1;return s.setTransform(Math.sign(u),0,0,Math.sign(p),N,A),s.drawImage(t,n,r,a,i,0,0,L,I),s.setTransform(u,h,m,p,f,x),[L,I]}if(u===0&&p===0){const b=o*m+f,N=Math.round(b),S=l*h+x,A=Math.round(S),T=(o+d)*m+f,L=Math.abs(Math.round(T)-N)||1,M=(l+c)*h+x,I=Math.abs(Math.round(M)-A)||1;return s.setTransform(0,Math.sign(h),Math.sign(m),0,N,A),s.drawImage(t,n,r,a,i,0,0,I,L),s.setTransform(u,h,m,p,f,x),[I,L]}s.drawImage(t,n,r,a,i,l,o,c,d);const y=Math.hypot(u,h),v=Math.hypot(m,p);return[y*c,v*d]}function pUn(s){const{width:t,height:n}=s;if(t>MNt||n>MNt)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 p=0;for(m=0,h[m]!==0&&(l[0]=1,++p),c=1;c>2)+(h[m+1]?4:0)+(h[m-u+1]?8:0),a[v]&&(l[d+c]=a[v],++p),m++;if(h[m-u]!==h[m]&&(l[d+c]=h[m]?2:4,++p),p>r)return null}for(m=u*(n-1),d=o*i,h[m]!==0&&(l[d]=8,++p),c=1;cr)return null;const f=new Int32Array([0,i,-1,0,-i,0,0,0,1]),x=new Path2D;for(o=0;p&&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]||--p}while(N!==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 PNt{constructor(t,n){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=tXt,this.textMatrixScale=1,this.fontMatrix=FGe,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=qv.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]=Lo.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=Lo.applyTransform(n,t),a=Lo.applyTransform(n.slice(2),t),i=Lo.applyTransform([n[0],n[3]],t),l=Lo.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){Lo.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=Lo.bezierBoundingBox(n,r,a,i,l,o,c,d,u);u||this.updateRectMinMax(t,h)}getPathBoundingBox(t=X1.FILL,n=null){const r=[this.minX,this.minY,this.maxX,this.maxY];if(t===X1.STROKE){n||ip("Stroke bounding box must include transform.");const a=Lo.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=Lo.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=X1.FILL,n=null){return Lo.intersect(this.clipBox,this.getPathBoundingBox(t,n))}}function LNt(s,t){if(typeof ImageData<"u"&&t instanceof ImageData){s.putImageData(t,0,0);return}const n=t.height,r=t.width,a=n%c_,i=(n-a)/c_,l=a===0?i:i+1,o=s.createImageData(r,c_);let c=0,d;const u=t.data,h=o.data;let m,p,f,x;if(t.kind===c4e.GRAYSCALE_1BPP){const y=u.byteLength,v=new Uint32Array(h.buffer,0,h.byteLength>>2),b=v.length,N=r+7>>3,S=4294967295,A=fb.isLittleEndian?4278190080:255;for(m=0;mN?r:T*8-7,I=M&-8;let R=0,z=0;for(;L>=1}for(;d=i&&(f=a,x=r*f),d=0,p=x;p--;)h[d++]=u[c++],h[d++]=u[c++],h[d++]=u[c++],h[d++]=255;s.putImageData(o,0,m*c_)}else throw new Error(`bad image kind: ${t.kind}`)}function INt(s,t){if(t.bitmap){s.drawImage(t.bitmap,0,0);return}const n=t.height,r=t.width,a=n%c_,i=(n-a)/c_,l=a===0?i:i+1,o=s.createImageData(r,c_);let c=0;const d=t.data,u=o.data;for(let h=0;hTNt&&typeof r=="function",u=d?Date.now()+uUn:0;let h=0;const m=this.commonObjs,p=this.objs;let f;for(;;){if(a!==void 0&&o===a.nextBreakPoint)return a.breakIt(o,r),o;if(f=l[o],f!==pk.dependency)this[f].apply(this,i[o]);else for(const x of i[o]){const y=x.startsWith("g_")?m:p;if(!y.has(x))return y.get(x,r),o}if(o++,o===c)return o;if(d&&++h>TNt){if(Date.now()>u)return r(),o;h=0}}}endDrawing(){Xt(this,TP,mWe).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(),Xt(this,TP,pWe).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,p=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&&(p=c>=16384?Math.floor(c/2)-1||1:Math.ceil(c)/2,l/=c/p),u=this.cachedCanvases.getCanvas(d,m,p),h=u.context,h.clearRect(0,0,m,p),h.drawImage(t,0,0,o,c,0,0,m,p),t=u.canvas,o=m,c=p,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=df(n);let c,d,u,h;if((t.bitmap||t.data)&&t.count>1){const M=t.bitmap||t.data.buffer;d=JSON.stringify(l?o:[o.slice(0,4),i]),c=this._cachedBitmapsMap.get(M),c||(c=new Map,this._cachedBitmapsMap.set(M,c));const I=c.get(d);if(I&&!l){const R=Math.round(Math.min(o[0],o[2])+o[4]),z=Math.round(Math.min(o[1],o[3])+o[5]);return{canvas:I,offsetX:R,offsetY:z}}u=I}u||(h=this.cachedCanvases.getCanvas("maskCanvas",r,a),INt(h.context,t));let m=Lo.transform(o,[1/r,0,0,-1/a,0,0]);m=Lo.transform(m,[1,0,0,1,0,-a]);const[p,f,x,y]=Lo.getAxialAlignedBoundingBox([0,0,r,a],m),v=Math.round(x-p)||1,b=Math.round(y-f)||1,N=this.cachedCanvases.getCanvas("fillCanvas",v,b),S=N.context,A=p,T=f;S.translate(-A,-T),S.transform(...m),u||(u=this._scaleImage(h.canvas,oC(S)),u=u.img,c&&l&&c.set(d,u)),S.imageSmoothingEnabled=RNt(df(S),t.interpolate),oce(S,u,0,0,u.width,u.height,0,0,r,a),S.globalCompositeOperation="source-in";const L=Lo.transform(oC(S),[1,0,0,1,-A,-T]);return S.fillStyle=l?i.getPattern(n,this,L,X1.FILL):i,S.fillRect(0,0,r,a),c&&!l&&(this.cachedCanvases.delete("fillCanvas"),c.set(d,N.canvas)),{canvas:N.canvas,offsetX:Math.round(A),offsetY:Math.round(T)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=fUn[t]}setLineJoin(t){this.ctx.lineJoin=gUn[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(...df(this.suspendedCtx)),MY(this.suspendedCtx,i),hUn(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(),MY(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,p=c-u,f=d-h;if(l){const y=Lo.makeHexColor(...l);if(p<0||f<0||p+r>m.width||f+a>m.height){const v=this.cachedCanvases.getCanvas("maskExtension",r,a),b=v.context;b.drawImage(m,-p,-f),b.globalCompositeOperation="destination-atop",b.fillStyle=y,b.fillRect(0,0,r,a),b.globalCompositeOperation="source-over",m=v.canvas,p=f=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const v=new Path2D;v.rect(p,f,r,a),t.clip(v),t.globalCompositeOperation="destination-atop",t.fillStyle=y,t.fillRect(p,f,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,p,f,r,a,c,d,r,a),n.restore()}save(){this.inSMaskMode?(MY(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(),MY(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=df(a),h=u[0]===0&&u[3]===0||u[1]===0&&u[2]===0,m=h?r.slice(0):null;for(let p=0,f=0,x=t.length;pENt&&(d=ENt),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&qv.FILL_STROKE_MASK,h=!!(c&qv.ADD_TO_PATH_FLAG),m=l.patternFill&&!o.missingFile;let p;(o.disableFontFace||h||m)&&(p=o.getPathGenerator(this.commonObjs,t)),o.disableFontFace||m?(i.save(),i.translate(n,r),i.beginPath(),p(i,d),a&&i.setTransform(...a),(u===qv.FILL||u===qv.FILL_STROKE)&&i.fill(),(u===qv.STROKE||u===qv.FILL_STROKE)&&i.stroke(),i.restore()):((u===qv.FILL||u===qv.FILL_STROKE)&&i.fillText(t,n,r),(u===qv.STROKE||u===qv.FILL_STROKE)&&i.strokeText(t,n,r)),h&&(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:df(i),x:n,y:r,fontSize:d,addToPath:p})}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 Yd(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,p=m?1:-1,f=r.defaultVMetrics,x=a*n.fontMatrix[0],y=n.textRenderingMode===qv.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 T=n.fillColor.getPattern(i,this,oC(i),X1.FILL);v=df(i),i.restore(),i.fillStyle=T}let b=n.lineWidth;const N=n.textMatrixScale;if(N===0||b===0){const T=n.textRenderingMode&qv.FILL_STROKE_MASK;(T===qv.STROKE||T===qv.FILL_STROKE)&&(b=this.getSinglePixelWidth())}else b/=N;if(l!==1&&(i.scale(l,l),b/=l),i.lineWidth=b,r.isInvalidPDFjsFont){const T=[];let L=0;for(const M of t)T.push(M.unicode),L+=M.width;i.fillText(T.join(""),0,0),n.x+=L*x*u,i.restore(),this.compose();return}let S=0,A;for(A=0;A0){const K=i.measureText(I).width*1e3/a*l;if(Hnew Cat(l,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};n=new hWe(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=Lo.makeHexColor(t,n,r)}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent"}setFillRGBColor(t,n,r){this.ctx.fillStyle=this.current.fillColor=Lo.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=cUn(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,oC(n),X1.SHADING);const a=oC(n);if(a){const{width:i,height:l}=n.canvas,[o,c,d,u]=Lo.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(){ip("Should not call beginInlineImage")}beginImageData(){ip("Should not call beginImageData")}paintFormXObjectBegin(t,n){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=df(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(df(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||bIe("TODO: Support non-isolated groups."),t.knockout&&nd("Knockout groups not supported.");const r=df(n);if(t.matrix&&n.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let a=Lo.getAxialAlignedBoundingBox(t.bbox,df(n));const i=[0,0,n.canvas.width,n.canvas.height];a=Lo.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()),MY(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=df(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...a);const i=Lo.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(Xt(this,TP,mWe).call(this),lce(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]=Lo.singularValueDecompose2dScale(df(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:p,context:f}=this.annotationCanvas;this.annotationCanvasMap.set(t,p),this.annotationCanvas.savedCtx=this.ctx,this.ctx=f,this.ctx.save(),this.ctx.setTransform(c,0,0,-d,0,o*d),lce(this.ctx)}else lce(this.ctx),this.endPath(),this.ctx.rect(n[0],n[1],l,o),this.ctx.clip(),this.ctx.beginPath()}this.current=new PNt(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...r),this.transform(...a)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),Xt(this,TP,pWe).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=pUn(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=df(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}};TP=new WeakSet,mWe=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)},pWe=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 t$=Cat;for(const s in pk)t$.prototype[s]!==void 0&&(t$.prototype[pk[s]]=t$.prototype[s]);var kse,Sse;class uA{static get workerPort(){return fe(this,kse)}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");$t(this,kse,t)}static get workerSrc(){return fe(this,Sse)}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");$t(this,Sse,t)}}kse=new WeakMap,Sse=new WeakMap,is(uA,kse,null),is(uA,Sse,"");const cce={UNKNOWN:0,DATA:1,ERROR:2},ax={UNKNOWN:0,CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function dw(s){switch(s instanceof Error||typeof s=="object"&&s!==null||ip('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),s.name){case"AbortException":return new B9(s.message);case"MissingPDFException":return new z9(s.message);case"PasswordException":return new zGe(s.message,s.code);case"UnexpectedResponseException":return new _Ie(s.message,s.status);case"UnknownErrorException":return new BGe(s.message,s.details);default:return new BGe(s.message,s.toString())}}var z$,cN,zXt,BXt,UXt,x4e;class GZ{constructor(t,n,r){is(this,cN);is(this,z$,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",Xt(this,cN,zXt).bind(this),{signal:fe(this,z$).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:ax.PULL,streamId:i,desiredSize:d.desiredSize}),u.promise},cancel:d=>{r0(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:ax.CANCEL,streamId:i,reason:dw(d)}),u.promise}},r)}destroy(){var t;(t=fe(this,z$))==null||t.abort(),$t(this,z$,null)}}z$=new WeakMap,cN=new WeakSet,zXt=function({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){Xt(this,cN,UXt).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===cce.DATA)a.resolve(t.data);else if(t.callback===cce.ERROR)a.reject(dw(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:cce.DATA,callbackId:t.callbackId,data:l})},function(l){i.postMessage({sourceName:r,targetName:a,callback:cce.ERROR,callbackId:t.callbackId,reason:dw(l)})});return}if(t.streamId){Xt(this,cN,BXt).call(this,t);return}n(t.data)},BXt=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:ax.ENQUEUE,streamId:n,chunk:d},h)},close(){this.isCancelled||(this.isCancelled=!0,i.postMessage({sourceName:r,targetName:a,stream:ax.CLOSE,streamId:n}),delete l.streamSinks[n])},error(d){r0(d instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,i.postMessage({sourceName:r,targetName:a,stream:ax.ERROR,streamId:n,reason:dw(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:ax.START_COMPLETE,streamId:n,success:!0})},function(d){i.postMessage({sourceName:r,targetName:a,stream:ax.START_COMPLETE,streamId:n,reason:dw(d)})})},UXt=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 ax.START_COMPLETE:t.success?l.startCall.resolve():l.startCall.reject(dw(t.reason));break;case ax.PULL_COMPLETE:t.success?l.pullCall.resolve():l.pullCall.reject(dw(t.reason));break;case ax.PULL:if(!o){i.postMessage({sourceName:r,targetName:a,stream:ax.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:ax.PULL_COMPLETE,streamId:n,success:!0})},function(c){i.postMessage({sourceName:r,targetName:a,stream:ax.PULL_COMPLETE,streamId:n,reason:dw(c)})});break;case ax.ENQUEUE:if(r0(l,"enqueue should have stream controller"),l.isClosed)break;l.controller.enqueue(t.chunk);break;case ax.CLOSE:if(r0(l,"close should have stream controller"),l.isClosed)break;l.isClosed=!0,l.controller.close(),Xt(this,cN,x4e).call(this,l,n);break;case ax.ERROR:r0(l,"error should have stream controller"),l.controller.error(dw(t.reason)),Xt(this,cN,x4e).call(this,l,n);break;case ax.CANCEL_COMPLETE:t.success?l.cancelCall.resolve():l.cancelCall.reject(dw(t.reason)),Xt(this,cN,x4e).call(this,l,n);break;case ax.CANCEL:if(!o)break;new Promise(function(c){var d;c((d=o.onCancel)==null?void 0:d.call(o,dw(t.reason)))}).then(function(){i.postMessage({sourceName:r,targetName:a,stream:ax.CANCEL_COMPLETE,streamId:n,success:!0})},function(c){i.postMessage({sourceName:r,targetName:a,stream:ax.CANCEL_COMPLETE,streamId:n,reason:dw(c)})}),o.sinkCapability.reject(dw(t.reason)),o.isCancelled=!0,delete this.streamSinks[n];break;default:throw new Error("Unexpected stream case")}},x4e=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 UO,Cse;class yUn{constructor({parsedData:t,rawData:n}){is(this,UO);is(this,Cse);$t(this,UO,t),$t(this,Cse,n)}getRaw(){return fe(this,Cse)}get(t){return fe(this,UO).get(t)??null}getAll(){return mnt(fe(this,UO))}has(t){return fe(this,UO).has(t)}}UO=new WeakMap,Cse=new WeakMap;const YB=Symbol("INTERNAL");var Ase,Ese,Tse,B$;class vUn{constructor(t,{name:n,intent:r,usage:a,rbGroups:i}){is(this,Ase,!1);is(this,Ese,!1);is(this,Tse,!1);is(this,B$,!0);$t(this,Ase,!!(t&Ew.DISPLAY)),$t(this,Ese,!!(t&Ew.PRINT)),this.name=n,this.intent=r,this.usage=a,this.rbGroups=i}get visible(){if(fe(this,Tse))return fe(this,B$);if(!fe(this,B$))return!1;const{print:t,view:n}=this.usage;return fe(this,Ase)?(n==null?void 0:n.viewState)!=="OFF":fe(this,Ese)?(t==null?void 0:t.printState)!=="OFF":!0}_setVisible(t,n,r=!1){t!==YB&&ip("Internal method `_setVisible` called."),$t(this,Tse,r),$t(this,B$,n)}}Ase=new WeakMap,Ese=new WeakMap,Tse=new WeakMap,B$=new WeakMap;var L6,yh,U$,q$,Mse,fWe;class bUn{constructor(t,n=Ew.DISPLAY){is(this,Mse);is(this,L6,null);is(this,yh,new Map);is(this,U$,null);is(this,q$,null);if(this.renderingIntent=n,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,$t(this,q$,t.order);for(const r of t.groups)fe(this,yh).set(r.id,new vUn(n,r));if(t.baseState==="OFF")for(const r of fe(this,yh).values())r._setVisible(YB,!1);for(const r of t.on)fe(this,yh).get(r)._setVisible(YB,!0);for(const r of t.off)fe(this,yh).get(r)._setVisible(YB,!1);$t(this,U$,this.getHash())}}isVisible(t){if(fe(this,yh).size===0)return!0;if(!t)return bIe("Optional content group not defined."),!0;if(t.type==="OCG")return fe(this,yh).has(t.id)?fe(this,yh).get(t.id).visible:(nd(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return Xt(this,Mse,fWe).call(this,t.expression);if(!t.policy||t.policy==="AnyOn"){for(const n of t.ids){if(!fe(this,yh).has(n))return nd(`Optional content group not found: ${n}`),!0;if(fe(this,yh).get(n).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const n of t.ids){if(!fe(this,yh).has(n))return nd(`Optional content group not found: ${n}`),!0;if(!fe(this,yh).get(n).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const n of t.ids){if(!fe(this,yh).has(n))return nd(`Optional content group not found: ${n}`),!0;if(!fe(this,yh).get(n).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const n of t.ids){if(!fe(this,yh).has(n))return nd(`Optional content group not found: ${n}`),!0;if(fe(this,yh).get(n).visible)return!1}return!0}return nd(`Unknown optional content policy ${t.policy}.`),!0}return nd(`Unknown group type ${t.type}.`),!0}setVisibility(t,n=!0,r=!0){var i;const a=fe(this,yh).get(t);if(!a){nd(`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=fe(this,yh).get(o))==null||i._setVisible(YB,!1,!0));a._setVisible(YB,!!n,!0),$t(this,L6,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=fe(this,yh).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}}$t(this,L6,null)}get hasInitialVisibility(){return fe(this,U$)===null||this.getHash()===fe(this,U$)}getOrder(){return fe(this,yh).size?fe(this,q$)?fe(this,q$).slice():[...fe(this,yh).keys()]:null}getGroups(){return fe(this,yh).size>0?mnt(fe(this,yh)):null}getGroup(t){return fe(this,yh).get(t)||null}getHash(){if(fe(this,L6)!==null)return fe(this,L6);const t=new AXt;for(const[n,r]of fe(this,yh))t.update(`${n}:${r.visible}`);return $t(this,L6,t.hexdigest())}}L6=new WeakMap,yh=new WeakMap,U$=new WeakMap,q$=new WeakMap,Mse=new WeakSet,fWe=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)});r0(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(){r0(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new wUn(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,n){if(n<=this._progressiveDataLength)return null;const r=new jUn(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 wUn{constructor(t,n,r=!1,a=null){this._stream=t,this._done=r||!1,this._filename=gnt(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 jUn{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 NUn(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}),p=wIe(h);h=m.decode(p),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 p=r("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(m=p.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 f=[];for(let x=0;x{if(!qXt(i.status))throw kIe(i.status,a);this._reader=i.body.getReader(),this._headersCapability.resolve();const l=i.headers,{allowRangeRequests:o,suggestedLength:c}=wnt({responseHeaders:l,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=c||this._contentLength,this._filename=jnt(l),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new B9("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:VXt(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}class SUn{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,$Xt(i,this._withCredentials,this._abortController)).then(o=>{if(!qXt(o.status))throw kIe(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:VXt(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}const z9e=200,B9e=206;function CUn(s){const t=s.response;return typeof t!="string"?t:wIe(t).buffer}class AUn{constructor({url:t,httpHeaders:n,withCredentials:r}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=_nt(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=B9e):a.expectedStatus=z9e,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||z9e;if(!(i===z9e&&r.expectedStatus===B9e)&&i!==r.expectedStatus){(d=r.onError)==null||d.call(r,a.status);return}const o=CUn(a);if(i===B9e){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 EUn{constructor(t){this._source=t,this._manager=new AUn(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 r0(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new TUn(this._manager,this._source),this._fullRequestReader}getRangeReader(t,n){const r=new MUn(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 TUn{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}=wnt({responseHeaders:r,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});a&&(this._isRangeSupported=!0),this._contentLength=i||this._contentLength,this._filename=jnt(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=kIe(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 MUn{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=kIe(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 PUn=/^[a-z][a-z0-9\-+.]+:/i;function LUn(s){if(PUn.test(s))return new URL(s);const t=wP.get("url");return new URL(t.pathToFileURL(s))}function HXt(s,t,n){return s.protocol==="http:"?wP.get("http").request(s,{headers:t},n):wP.get("https").request(s,{headers:t},n)}class IUn{constructor(t){this.source=t,this.url=LUn(t.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.headers=_nt(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 r0(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new OUn(this):new RUn(this),this._fullRequestReader}getRangeReader(t,n){if(n<=this._progressiveDataLength)return null;const r=this.isFsUrl?new FUn(this,t,n):new DUn(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 GXt{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 B9("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class WXt{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 RUn extends GXt{constructor(t){super(t);const n=Object.fromEntries(t.headers),r=a=>{if(a.statusCode===404){const c=new z9(`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}=wnt({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=l,this._contentLength=o||this._contentLength,this._filename=jnt(i)};this._request=HXt(this._url,n,r),this._request.on("error",a=>{this._storedError=a,this._headersCapability.reject(a)}),this._request.end()}}class DUn extends WXt{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 z9(`Missing PDF "${this._url}".`);this._storedError=o;return}this._setReadableStream(l)};this._request=HXt(this._url,a,i),this._request.on("error",l=>{this._storedError=l}),this._request.end()}}class OUn extends GXt{constructor(t){super(t);const n=wP.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 z9(`Missing PDF "${this._url}".`)),this._storedError=r,this._headersCapability.reject(r)})}}class FUn extends WXt{constructor(t,n,r){super(t);const a=wP.get("fs");this._setReadableStream(a.createReadStream(this._url,{start:n,end:r-1}))}}const zUn=1e5,Zb=30,BUn=.8;var nCt,I6,a_,Pse,Lse,qO,HC,Ise,Rse,$O,$$,V$,R6,H$,Dse,G$,VO,Ose,Fse,HO,GO,zse,D6,W$,hE,KXt,YXt,gWe,hj,y4e,xWe,ZXt,XXt;const $x=class $x{constructor({textContentSource:t,container:n,viewport:r}){is(this,hE);is(this,I6,Promise.withResolvers());is(this,a_,null);is(this,Pse,!1);is(this,Lse,!!((nCt=globalThis.FontInspector)!=null&&nCt.enabled));is(this,qO,null);is(this,HC,null);is(this,Ise,0);is(this,Rse,0);is(this,$O,null);is(this,$$,null);is(this,V$,0);is(this,R6,0);is(this,H$,Object.create(null));is(this,Dse,[]);is(this,G$,null);is(this,VO,[]);is(this,Ose,new WeakMap);is(this,Fse,null);var c;if(t instanceof ReadableStream)$t(this,G$,t);else if(typeof t=="object")$t(this,G$,new ReadableStream({start(d){d.enqueue(t),d.close()}}));else throw new Error('No "textContentSource" parameter specified.');$t(this,a_,$t(this,$$,n)),$t(this,R6,r.scale*(globalThis.devicePixelRatio||1)),$t(this,V$,r.rotation),$t(this,HC,{div:null,properties:null,ctx:null});const{pageWidth:a,pageHeight:i,pageX:l,pageY:o}=r.rawDims;$t(this,Fse,[1,0,0,-1,-l,o+i]),$t(this,Rse,a),$t(this,Ise,i),Xt(c=$x,hj,ZXt).call(c),Q7(n,r),fe(this,I6).promise.finally(()=>{fe($x,W$).delete(this),$t(this,HC,null),$t(this,H$,null)}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:n}=fb.platform;return Yd(this,"fontFamilyMap",new Map([["sans-serif",`${t&&n?"Calibri, ":""}sans-serif`],["monospace",`${t&&n?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{fe(this,$O).read().then(({value:n,done:r})=>{if(r){fe(this,I6).resolve();return}fe(this,qO)??$t(this,qO,n.lang),Object.assign(fe(this,H$),n.styles),Xt(this,hE,KXt).call(this,n.items),t()},fe(this,I6).reject)};return $t(this,$O,fe(this,G$).getReader()),fe($x,W$).add(this),t(),fe(this,I6).promise}update({viewport:t,onBefore:n=null}){var i;const r=t.scale*(globalThis.devicePixelRatio||1),a=t.rotation;if(a!==fe(this,V$)&&(n==null||n(),$t(this,V$,a),Q7(fe(this,$$),{rotation:a})),r!==fe(this,R6)){n==null||n(),$t(this,R6,r);const l={div:null,properties:null,ctx:Xt(i=$x,hj,y4e).call(i,fe(this,qO))};for(const o of fe(this,VO))l.properties=fe(this,Ose).get(o),l.div=o,Xt(this,hE,gWe).call(this,l)}}cancel(){var n;const t=new B9("TextLayer task cancelled.");(n=fe(this,$O))==null||n.cancel(t).catch(()=>{}),$t(this,$O,null),fe(this,I6).reject(t)}get textDivs(){return fe(this,VO)}get textContentItemsStr(){return fe(this,Dse)}static cleanup(){if(!(fe(this,W$).size>0)){fe(this,HO).clear();for(const{canvas:t}of fe(this,GO).values())t.remove();fe(this,GO).clear()}}};I6=new WeakMap,a_=new WeakMap,Pse=new WeakMap,Lse=new WeakMap,qO=new WeakMap,HC=new WeakMap,Ise=new WeakMap,Rse=new WeakMap,$O=new WeakMap,$$=new WeakMap,V$=new WeakMap,R6=new WeakMap,H$=new WeakMap,Dse=new WeakMap,G$=new WeakMap,VO=new WeakMap,Ose=new WeakMap,Fse=new WeakMap,HO=new WeakMap,GO=new WeakMap,zse=new WeakMap,D6=new WeakMap,W$=new WeakMap,hE=new WeakSet,KXt=function(t){var a,i;if(fe(this,Pse))return;(i=fe(this,HC)).ctx??(i.ctx=Xt(a=$x,hj,y4e).call(a,fe(this,qO)));const n=fe(this,VO),r=fe(this,Dse);for(const l of t){if(n.length>zUn){nd("Ignoring additional textDivs for performance reasons."),$t(this,Pse,!0);return}if(l.str===void 0){if(l.type==="beginMarkedContentProps"||l.type==="beginMarkedContent"){const o=fe(this,a_);$t(this,a_,document.createElement("span")),fe(this,a_).classList.add("markedContent"),l.id!==null&&fe(this,a_).setAttribute("id",`${l.id}`),o.append(fe(this,a_))}else l.type==="endMarkedContent"&&$t(this,a_,fe(this,a_).parentNode);continue}r.push(l.str),Xt(this,hE,YXt).call(this,l)}},YXt=function(t){var x;const n=document.createElement("span"),r={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};fe(this,VO).push(n);const a=Lo.transform(fe(this,Fse),t.transform);let i=Math.atan2(a[1],a[0]);const l=fe(this,H$)[t.fontName];l.vertical&&(i+=Math.PI/2);let o=fe(this,Lse)&&l.fontSubstitution||l.fontFamily;o=$x.fontFamilyMap.get(o)||o;const c=Math.hypot(a[2],a[3]),d=c*Xt(x=$x,hj,XXt).call(x,o,fe(this,qO));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)*",p=n.style;fe(this,a_)===fe(this,$$)?(p.left=`${(100*u/fe(this,Rse)).toFixed(2)}%`,p.top=`${(100*h/fe(this,Ise)).toFixed(2)}%`):(p.left=`${m}${u.toFixed(2)}px)`,p.top=`${m}${h.toFixed(2)}px)`),p.fontSize=`${m}${(fe($x,D6)*c).toFixed(2)}px)`,p.fontFamily=o,r.fontSize=c,n.setAttribute("role","presentation"),n.textContent=t.str,n.dir=t.dir,fe(this,Lse)&&(n.dataset.fontName=l.fontSubstitutionLoadedName||t.fontName),i!==0&&(r.angle=i*(180/Math.PI));let f=!1;if(t.str.length>1)f=!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&&(f=!0)}if(f&&(r.canvasWidth=l.vertical?t.height:t.width),fe(this,Ose).set(n,r),fe(this,HC).div=n,fe(this,HC).properties=r,Xt(this,hE,gWe).call(this,fe(this,HC)),r.hasText&&fe(this,a_).append(n),r.hasEOL){const y=document.createElement("br");y.setAttribute("role","presentation"),fe(this,a_).append(y)}},gWe=function(t){var o;const{div:n,properties:r,ctx:a}=t,{style:i}=n;let l="";if(fe($x,D6)>1&&(l=`scale(${1/fe($x,D6)})`),r.canvasWidth!==0&&r.hasText){const{fontFamily:c}=i,{canvasWidth:d,fontSize:u}=r;Xt(o=$x,hj,xWe).call(o,a,u*fe(this,R6),c);const{width:h}=a.measureText(n.textContent);h>0&&(l=`scaleX(${d*fe(this,R6)/h}) ${l}`)}r.angle!==0&&(l=`rotate(${r.angle}deg) ${l}`),l.length>0&&(i.transform=l)},hj=new WeakSet,y4e=function(t=null){let n=fe(this,GO).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}),fe(this,GO).set(t,n),fe(this,zse).set(n,{size:0,family:""})}return n},xWe=function(t,n,r){const a=fe(this,zse).get(t);n===a.size&&r===a.family||(t.font=`${n}px ${r}`,a.size=n,a.family=r)},ZXt=function(){if(fe(this,D6)!==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),$t(this,D6,t.getBoundingClientRect().height),t.remove()},XXt=function(t,n){const r=fe(this,HO).get(t);if(r)return r;const a=Xt(this,hj,y4e).call(this,n);a.canvas.width=a.canvas.height=Zb,Xt(this,hj,xWe).call(this,a,Zb,t);const i=a.measureText("");let l=i.fontBoundingBoxAscent,o=Math.abs(i.fontBoundingBoxDescent);if(l){const u=l/(l+o);return fe(this,HO).set(t,u),a.canvas.width=a.canvas.height=0,u}a.strokeStyle="red",a.clearRect(0,0,Zb,Zb),a.strokeText("g",0,0);let c=a.getImageData(0,0,Zb,Zb).data;o=0;for(let u=c.length-1-3;u>=0;u-=4)if(c[u]>0){o=Math.ceil(u/4/Zb);break}a.clearRect(0,0,Zb,Zb),a.strokeText("A",0,Zb),c=a.getImageData(0,0,Zb,Zb).data,l=0;for(let u=0,h=c.length;u0){l=Zb-Math.floor(u/4/Zb);break}a.canvas.width=a.canvas.height=0;const d=l?l/(l+o):BUn;return fe(this,HO).set(t,d),d},is($x,hj),is($x,HO,new Map),is($x,GO,new Map),is($x,zse,new WeakMap),is($x,D6,null),is($x,W$,new Set);let Pte=$x;class Lte{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(Lte.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 UUn=65536,qUn=100,$Un=5e3,VUn=s1?sUn:JBn,HUn=s1?nUn:LXt,GUn=s1?tUn:eUn,WUn=s1?rUn:OXt;function KUn(s={}){typeof s=="string"||s instanceof URL?s={url:s}:(s instanceof ArrayBuffer||ArrayBuffer.isView(s))&&(s={data:s});const t=new yWe,{docId:n}=t,r=s.url?YUn(s.url):null,a=s.data?ZUn(s.data):null,i=s.httpHeaders||null,l=s.withCredentials===!0,o=s.password??null,c=s.range instanceof QXt?s.range:null,d=Number.isInteger(s.rangeChunkSize)&&s.rangeChunkSize>0?s.rangeChunkSize:UUn;let u=s.worker instanceof s$?s.worker:null;const h=s.verbosity,m=typeof s.docBaseUrl=="string"&&!NIe(s.docBaseUrl)?s.docBaseUrl:null,p=typeof s.cMapUrl=="string"?s.cMapUrl:null,f=s.cMapPacked!==!1,x=s.CMapReaderFactory||HUn,y=typeof s.standardFontDataUrl=="string"?s.standardFontDataUrl:null,v=s.StandardFontDataFactory||WUn,b=s.stopAtErrors!==!0,N=Number.isInteger(s.maxImageSize)&&s.maxImageSize>-1?s.maxImageSize:-1,S=s.isEvalSupported!==!1,A=typeof s.isOffscreenCanvasSupported=="boolean"?s.isOffscreenCanvasSupported:!s1,T=typeof s.isChrome=="boolean"?s.isChrome:!fb.platform.isFirefox&&typeof window<"u"&&!!(window!=null&&window.chrome),L=Number.isInteger(s.canvasMaxAreaInBytes)?s.canvasMaxAreaInBytes:-1,M=typeof s.disableFontFace=="boolean"?s.disableFontFace:s1,I=s.fontExtraProperties===!0,R=s.enableXfa===!0,z=s.ownerDocument||globalThis.document,$=s.disableRange===!0,H=s.disableStream===!0,V=s.disableAutoFetch===!0,K=s.pdfBug===!0,Z=s.CanvasFactory||VUn,Q=s.FilterFactory||GUn,le=s.enableHWA===!0,ue=c?c.length:s.length??NaN,se=typeof s.useSystemFonts=="boolean"?s.useSystemFonts:!s1&&!M,ne=typeof s.useWorkerFetch=="boolean"?s.useWorkerFetch:x===LXt&&v===OXt&&p&&y&&zZ(p,document.baseURI)&&zZ(y,document.baseURI);s.canvasFactory&&kNt("`canvasFactory`-instance option, please use `CanvasFactory` instead."),s.filterFactory&&kNt("`filterFactory`-instance option, please use `FilterFactory` instead.");const ie=null;TBn(h);const ce={canvasFactory:new Z({ownerDocument:z,enableHWA:le}),filterFactory:new Q({docId:n,ownerDocument:z}),cMapReaderFactory:ne?null:new x({baseUrl:p,isCompressed:f}),standardFontDataFactory:ne?null:new v({baseUrl:y})};if(!u){const he={verbosity:h,port:uA.workerPort};u=he.port?s$.fromPort(he):new s$(he),t._worker=u}const je={docId:n,apiVersion:"4.8.69",data:a,password:o,disableAutoFetch:V,rangeChunkSize:d,length:ue,docBaseUrl:m,enableXfa:R,evaluatorOptions:{maxImageSize:N,disableFontFace:M,ignoreErrors:b,isEvalSupported:S,isOffscreenCanvasSupported:A,isChrome:T,canvasMaxAreaInBytes:L,fontExtraProperties:I,useSystemFonts:se,cMapUrl:ne?p:null,standardFontDataUrl:ne?y:null}},be={disableFontFace:M,fontExtraProperties:I,ownerDocument:z,pdfBug:K,styleElement:ie,loadingParams:{disableAutoFetch:V,enableXfa:R}};return u.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const he=u.messageHandler.sendWithPromise("GetDocRequest",je,a?[a.buffer]:null);let ge;if(c)ge=new _Un(c,{disableRange:$,disableStream:H});else if(!a){if(!r)throw new Error("getDocument - no `url` parameter provided.");let ke;s1?ke=typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype&&zZ(r)?ONt:IUn:ke=zZ(r)?ONt:EUn,ge=new ke({url:r,length:ue,httpHeaders:i,withCredentials:l,rangeChunkSize:d,disableRange:$,disableStream:H})}return he.then(ke=>{if(t.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const Te=new GZ(n,ke,u.port),Me=new eqn(Te,t,ge,be,ce);t._transport=Me,Te.send("Ready",null)})}).catch(t._capability.reject),t}function YUn(s){if(s instanceof URL)return s.href;try{return new URL(s,window.location).href}catch{if(s1&&typeof s=="string")return s}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function ZUn(s){if(s1&&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 wIe(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 FNt(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 KTe;const YTe=class YTe{constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${O0(YTe,KTe)._++}`,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)}};KTe=new WeakMap,is(YTe,KTe,0);let yWe=YTe;class QXt{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){ip("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class XUn{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 Yd(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 O6,GC,O2,ZB,v4e;class QUn{constructor(t,n,r,a=!1){is(this,O2);is(this,O6,null);is(this,GC,!1);this._pageIndex=t,this._pageInfo=n,this._transport=r,this._stats=a?new NNt:null,this._pdfBug=a,this.commonObjs=r.commonObjs,this.objs=new JXt,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 eae({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 Yd(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=d6.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:p,cacheKey:f}=m;$t(this,GC,!1),Xt(this,O2,v4e).call(this),o||(o=this._transport.getOptionalContentConfig(p));let x=this._intentStates.get(f);x||(x=Object.create(null),this._intentStates.set(f,x)),x.streamReaderCancelTimeout&&(clearTimeout(x.streamReaderCancelTimeout),x.streamReaderCancelTimeout=null);const y=!!(p&Ew.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=T=>{var L;x.renderTasks.delete(b),(this._maybeCleanupAfterRender||y)&&$t(this,GC,!0),Xt(this,O2,ZB).call(this,!y),T?(b.capability.reject(T),this._abortOperatorList({intentState:x,reason:T instanceof Error?T:new Error(T)})):b.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),(L=globalThis.Stats)!=null&&L.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},b=new bWe({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 N=b.task;return Promise.all([x.displayReadyCapability.promise,o]).then(([T,L])=>{var M;if(this.destroyed){v();return}if((M=this._stats)==null||M.time("Rendering"),!(L.renderingIntent&p))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");b.initializeGraphics({transparency:T,optionalContentConfig:L}),b.operatorListChanged()}).catch(v),N}getOperatorList({intent:t="display",annotationMode:n=d6.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=>Lte.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(),$t(this,GC,!1),Xt(this,O2,v4e).call(this),Promise.all(t)}cleanup(t=!1){$t(this,GC,!0);const n=Xt(this,O2,ZB).call(this,!1);return t&&n&&this._stats&&(this._stats=new NNt),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();Xt(this,O2,ZB).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 fnt){let a=qUn;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 B9(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}}O6=new WeakMap,GC=new WeakMap,O2=new WeakSet,ZB=function(t=!1){if(Xt(this,O2,v4e).call(this),!fe(this,GC)||this.destroyed)return!1;if(t)return $t(this,O6,setTimeout(()=>{$t(this,O6,null),Xt(this,O2,ZB).call(this,!1)},$Un)),!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(),$t(this,GC,!1),!0},v4e=function(){fe(this,O6)&&(clearTimeout(fe(this,O6)),$t(this,O6,null))};var WC,ZTe;class JUn{constructor(){is(this,WC,new Map);is(this,ZTe,Promise.resolve())}postMessage(t,n){const r={data:structuredClone(t,n?{transfer:n}:null)};fe(this,ZTe).then(()=>{for(const[a]of fe(this,WC))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){nd("LoopbackPort - cannot use an `aborted` signal.");return}const l=()=>this.removeEventListener(t,n);a=()=>i.removeEventListener("abort",l),i.addEventListener("abort",l)}fe(this,WC).set(n,a)}removeEventListener(t,n){const r=fe(this,WC).get(n);r==null||r(),fe(this,WC).delete(n)}terminate(){for(const[,t]of fe(this,WC))t==null||t();fe(this,WC).clear()}}WC=new WeakMap,ZTe=new WeakMap;var XTe,WO,KO,K$,b4e,Y$,_4e;const Tp=class Tp{constructor({name:t=null,port:n=null,verbosity:r=MBn()}={}){is(this,K$);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=fe(Tp,KO))!=null&&a.has(n))throw new Error("Cannot use more than one PDFWorker per port.");(fe(Tp,KO)||$t(Tp,KO,new WeakMap)).set(n,this),this._initializeFromPort(n);return}this._initialize()}get promise(){return s1?Promise.all([wP.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 GZ("main","worker",t),this._messageHandler.on("ready",function(){}),Xt(this,K$,b4e).call(this)}_initialize(){if(fe(Tp,WO)||fe(Tp,Y$,_4e)){this._setupFakeWorker();return}let{workerSrc:t}=Tp;try{Tp._isSameOrigin(window.location.href,t)||(t=Tp._createCDNWrapper(new URL(t,window.location).href));const n=new Worker(t,{type:"module"}),r=new GZ("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,Xt(this,K$,b4e).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{bIe("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){fe(Tp,WO)||(nd("Setting up fake worker."),$t(Tp,WO,!0)),Tp._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const n=new JUn;this._port=n;const r=`fake${O0(Tp,XTe)._++}`,a=new GZ(r+"_worker",r,n);t.setup(a,n),this._messageHandler=new GZ(r,r+"_worker",n),Xt(this,K$,b4e).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=fe(Tp,KO))==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=fe(this,KO))==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 Tp(t)}static get workerSrc(){if(uA.workerSrc)return uA.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return Yd(this,"_setupFakeWorkerGlobal",(async()=>fe(this,Y$,_4e)?fe(this,Y$,_4e):(await import(this.workerSrc)).WorkerMessageHandler)())}};XTe=new WeakMap,WO=new WeakMap,KO=new WeakMap,K$=new WeakSet,b4e=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},Y$=new WeakSet,_4e=function(){var t;try{return((t=globalThis.pdfjsWorker)==null?void 0:t.WorkerMessageHandler)||null}catch{return null}},is(Tp,Y$),is(Tp,XTe,0),is(Tp,WO,!1),is(Tp,KO),s1&&($t(Tp,WO,!0),uA.workerSrc||(uA.workerSrc="./pdf.worker.mjs")),Tp._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},Tp._createCDNWrapper=t=>{const n=`await import("${t}");`;return URL.createObjectURL(new Blob([n],{type:"text/javascript"}))};let s$=Tp;var KC,G5,Z$,X$,W5,YO,WZ;class eqn{constructor(t,n,r,a,i){is(this,YO);is(this,KC,new Map);is(this,G5,new Map);is(this,Z$,new Map);is(this,X$,new Map);is(this,W5,null);this.messageHandler=t,this.loadingTask=n,this.commonObjs=new JXt,this.fontLoader=new XBn({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 Yd(this,"annotationStorage",new vnt)}getRenderingIntent(t,n=d6.ENABLE,r=null,a=!1,i=!1){let l=Ew.DISPLAY,o=oWe;switch(t){case"any":l=Ew.ANY;break;case"display":break;case"print":l=Ew.PRINT;break;default:nd(`getRenderingIntent - invalid intent: ${t}`)}const c=l&Ew.PRINT&&r instanceof TXt?r:this.annotationStorage;switch(n){case d6.DISABLE:l+=Ew.ANNOTATIONS_DISABLE;break;case d6.ENABLE:break;case d6.ENABLE_FORMS:l+=Ew.ANNOTATIONS_FORMS;break;case d6.ENABLE_STORAGE:l+=Ew.ANNOTATIONS_STORAGE,o=c.serializable;break;default:nd(`getRenderingIntent - invalid annotationMode: ${n}`)}a&&(l+=Ew.IS_EDITING),i&&(l+=Ew.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=fe(this,W5))==null||r.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const a of fe(this,G5).values())t.push(a._destroy());fe(this,G5).clear(),fe(this,Z$).clear(),fe(this,X$).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(),fe(this,KC).clear(),this.filterFactory.destroy(),Pte.cleanup(),(a=this._networkStream)==null||a.cancelAllRequests(new B9("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)=>{r0(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}r0(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)=>{r0(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}r0(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 XUn(r,this))}),t.on("DocException",function(r){let a;switch(r.name){case"PasswordException":a=new zGe(r.message,r.code);break;case"InvalidPDFException":a=new sXt(r.message);break;case"MissingPDFException":a=new z9(r.message);break;case"UnexpectedResponseException":a=new _Ie(r.message,r.status);break;case"UnknownErrorException":a=new BGe(r.message,r.details);break;default:ip("DocException - expected a valid Error.")}n._capability.reject(a)}),t.on("PasswordRequest",r=>{if($t(this,W5,Promise.withResolvers()),n.onPassword){const a=i=>{i instanceof Error?fe(this,W5).reject(i):fe(this,W5).resolve({password:i})};try{n.onPassword(a,r.code)}catch(i){fe(this,W5).reject(i)}}else fe(this,W5).reject(new zGe(r.message,r.code));return fe(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;fe(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 p=i.error;nd(`Error during font loading: ${p}`),this.commonObjs.resolve(r,p);break}const u=d&&((l=globalThis.FontInspector)!=null&&l.enabled)?(p,f)=>globalThis.FontInspector.fontAdded(p,f):null,h=new QBn(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;r0(m,"The imageRef must be defined.");for(const p of fe(this,G5).values())for(const[,f]of p.objs)if((f==null?void 0:f.ref)===m)return f.dataLen?(this.commonObjs.resolve(r,structuredClone(f)),f.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=fe(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)>SBn&&(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&&nd("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=fe(this,Z$).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&&fe(this,X$).set(i.refStr,t);const l=new QUn(n,i,this,this._params.pdfBug);return fe(this,G5).set(n,l),l});return fe(this,Z$).set(n,a),a}getPageIndex(t){return FNt(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 Xt(this,YO,WZ).call(this,"GetFieldObjects")}hasJSActions(){return Xt(this,YO,WZ).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 Xt(this,YO,WZ).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 Xt(this,YO,WZ).call(this,"GetOptionalContentConfig").then(n=>new bUn(n,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",n=fe(this,KC).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 yUn(a[1]):null,contentDispositionFilename:((i=this._fullReader)==null?void 0:i.filename)??null,contentLength:((l=this._fullReader)==null?void 0:l.contentLength)??null}});return fe(this,KC).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 fe(this,G5).values())if(!n.cleanup())throw new Error(`startCleanup: Page ${n.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),fe(this,KC).clear(),this.filterFactory.destroy(!0),Pte.cleanup()}}cachedPageNumber(t){if(!FNt(t))return null;const n=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return fe(this,X$).get(n)??null}}KC=new WeakMap,G5=new WeakMap,Z$=new WeakMap,X$=new WeakMap,W5=new WeakMap,YO=new WeakSet,WZ=function(t,n=null){const r=fe(this,KC).get(t);if(r)return r;const a=this.messageHandler.sendWithPromise(t,n);return fe(this,KC).set(t,a),a};const dce=Symbol("INITIAL_DATA");var wk,Bse,vWe;class JXt{constructor(){is(this,Bse);is(this,wk,Object.create(null))}get(t,n=null){if(n){const a=Xt(this,Bse,vWe).call(this,t);return a.promise.then(()=>n(a.data)),null}const r=fe(this,wk)[t];if(!r||r.data===dce)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return r.data}has(t){const n=fe(this,wk)[t];return!!n&&n.data!==dce}resolve(t,n=null){const r=Xt(this,Bse,vWe).call(this,t);r.data=n,r.resolve()}clear(){var t;for(const n in fe(this,wk)){const{data:r}=fe(this,wk)[n];(t=r==null?void 0:r.bitmap)==null||t.close()}$t(this,wk,Object.create(null))}*[Symbol.iterator](){for(const t in fe(this,wk)){const{data:n}=fe(this,wk)[t];n!==dce&&(yield[t,n])}}}wk=new WeakMap,Bse=new WeakSet,vWe=function(t){var n;return(n=fe(this,wk))[t]||(n[t]={...Promise.withResolvers(),data:dce})};var F6;class tqn{constructor(t){is(this,F6,null);$t(this,F6,t),this.onContinue=null}get promise(){return fe(this,F6).capability.promise}cancel(t=0){fe(this,F6).cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=fe(this,F6).operatorList;if(!t)return!1;const{annotationCanvasMap:n}=fe(this,F6);return t.form||t.canvas&&(n==null?void 0:n.size)>0}}F6=new WeakMap;var z6,ZO;const OD=class OD{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}){is(this,z6,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 tqn(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(fe(OD,ZO).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.");fe(OD,ZO).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 t$(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(),fe(this,z6)&&(window.cancelAnimationFrame(fe(this,z6)),$t(this,z6,null)),fe(OD,ZO).delete(this._canvas),this.callback(t||new fnt(`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?$t(this,z6,window.requestAnimationFrame(()=>{$t(this,z6,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(),fe(OD,ZO).delete(this._canvas),this.callback())))}};z6=new WeakMap,ZO=new WeakMap,is(OD,ZO,new WeakSet);let bWe=OD;const sqn="4.8.69",nqn="3634dab10";function zNt(s){return Math.floor(Math.max(0,Math.min(1,s))*255).toString(16).padStart(2,"0")}function PY(s){return Math.max(0,Math.min(255,255*s))}class BNt{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=PY(t),[t,t,t]}static G_HTML([t]){const n=zNt(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(PY)}static RGB_HTML(t){return`#${t.map(zNt).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[PY(1-Math.min(1,t+a)),PY(1-Math.min(1,r+a)),PY(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 rqn{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){ip("Abstract method `_createSVG` called.")}}class Nnt extends rqn{_createSVG(t){return document.createElementNS(xC,t)}}class eQt{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 p=`matrix(${t.viewport.transform.join(",")})`;c.style.transform=p}o&&c.setAttribute("class","xfaLayer xfaFont");const d=[];if(a.children.length===0){if(a.value){const p=document.createTextNode(a.value);l.append(p),o&&Lte.shouldBuildText(a.name)&&d.push(p)}return{textDivs:d}}const u=[[a,-1,l]];for(;u.length>0;){const[p,f,x]=u.at(-1);if(f+1===p.children.length){u.pop();continue}const y=p.children[++u.at(-1)[1]];if(y===null)continue;const{name:v}=y;if(v==="#text"){const N=document.createTextNode(y.value);d.push(N),x.append(N);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 N=document.createTextNode(y.value);o&&Lte.shouldBuildText(v)&&d.push(N),b.append(N)}}for(const p of c.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))p.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 sae=1e3,aqn=9,e9=new WeakSet;function BA(s){return{width:s[2]-s[0],height:s[3]-s[1]}}class iqn{static create(t){switch(t.data.annotationType){case Ux.LINK:return new tQt(t);case Ux.TEXT:return new oqn(t);case Ux.WIDGET:switch(t.data.fieldType){case"Tx":return new lqn(t);case"Btn":return t.data.radioButton?new rQt(t):t.data.checkBox?new dqn(t):new uqn(t);case"Ch":return new hqn(t);case"Sig":return new cqn(t)}return new U9(t);case Ux.POPUP:return new wWe(t);case Ux.FREETEXT:return new cQt(t);case Ux.LINE:return new pqn(t);case Ux.SQUARE:return new fqn(t);case Ux.CIRCLE:return new gqn(t);case Ux.POLYLINE:return new dQt(t);case Ux.CARET:return new yqn(t);case Ux.INK:return new knt(t);case Ux.POLYGON:return new xqn(t);case Ux.HIGHLIGHT:return new uQt(t);case Ux.UNDERLINE:return new vqn(t);case Ux.SQUIGGLY:return new bqn(t);case Ux.STRIKEOUT:return new _qn(t);case Ux.STAMP:return new hQt(t);case Ux.FILEATTACHMENT:return new wqn(t);default:return new Zg(t)}}}var XO,Q$,J$,Use,_We;const Aat=class Aat{constructor(t,{isRenderable:n=!1,ignoreBorder:r=!1,createQuadrilaterals:a=!1}={}){is(this,Use);is(this,XO,null);is(this,Q$,!1);is(this,J$,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 Aat._hasPopupData(this.data)}updateEdited(t){var r;if(!this.container)return;fe(this,XO)||$t(this,XO,{rect:this.data.rect.slice(0)});const{rect:n}=t;n&&Xt(this,Use,_We).call(this,n),(r=fe(this,J$))==null||r.popup.updateEdited(t)}resetEdited(){var t;fe(this,XO)&&(Xt(this,Use,_We).call(this,fe(this,XO).rect),(t=fe(this,J$))==null||t.popup.resetEdited(),$t(this,XO,null))}_createContainer(t){const{data:n,parent:{page:r,viewport:a}}=this,i=document.createElement("section");i.setAttribute("data-annotation-id",n.id),this instanceof U9||(i.tabIndex=sae);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 wWe){const{rotation:x}=n;return!n.hasOwnCanvas&&x!==0&&this.setRotation(x,i),i}const{width:o,height:c}=BA(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 rQt){const b=`calc(${o}px * var(--scale-factor)) / calc(${c}px * var(--scale-factor))`;l.borderRadius=b}switch(n.borderStyle.style){case TY.SOLID:l.borderStyle="solid";break;case TY.DASHED:l.borderStyle="dashed";break;case TY.BEVELED:nd("Unimplemented border style: beveled");break;case TY.INSET:nd("Unimplemented border style: inset");break;case TY.UNDERLINE:l.borderBottomStyle="solid";break}const v=n.borderColor||null;v?($t(this,Q$,!0),l.borderColor=Lo.makeHexColor(v[0]|0,v[1]|0,v[2]|0)):l.borderWidth=0}const d=Lo.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:p}=a.rawDims;l.left=`${100*(d[0]-m)/u}%`,l.top=`${100*(d[1]-p)/h}%`;const{rotation:f}=n;return n.hasOwnCanvas||f===0?(l.width=`${100*o/u}%`,l.height=`${100*c/h}%`):this.setRotation(f,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}=BA(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]=BNt[`${l}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[r]:BNt[`${l}_rgb`](o)})};return Yd(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(fe(this,Q$)){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 p=u.createElement("clipPath"),f=`clippath_${this.data.id}`;p.setAttribute("id",f),p.setAttribute("clipPathUnits","objectBoundingBox"),m.append(p);for(let x=2,y=t.length;x`)}fe(this,Q$)&&(o.push("')"),l.backgroundImage=o.join("")),this.container.append(h),this.container.style.clipPath=`url(#${f})`}_createPopup(){const{data:t}=this,n=$t(this,J$,new wWe({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(){ip("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&&!e9.has(d)){nd(`_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&&e9.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})})}};XO=new WeakMap,Q$=new WeakMap,J$=new WeakMap,Use=new WeakSet,_We=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}=BA(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 Zg=Aat;var Ow,jD,sQt,nQt;class tQt extends Zg{constructor(n,r=null){super(n,{isRenderable:!0,ignoreBorder:!!(r!=null&&r.ignoreBorder),createQuadrilaterals:!0});is(this,Ow);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?(Xt(this,Ow,sQt).call(this,a,n.attachment,n.attachmentDest),i=!0):n.setOCGState?(Xt(this,Ow,nQt).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==="")&&Xt(this,Ow,jD).call(this)}_bindNamedAction(n,r){n.href=this.linkService.getAnchorUrl(""),n.onclick=()=>(this.linkService.executeNamedAction(r),!1),Xt(this,Ow,jD).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),Xt(this,Ow,jD).call(this)}_bindResetFormAction(n,r){const a=n.onclick;if(a||(n.href=this.linkService.getAnchorUrl("")),Xt(this,Ow,jD).call(this),!this._fieldObjects){nd('_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 p of i){const f=this._fieldObjects[p]||[];for(const{id:x}of f)m.add(x)}for(const p of Object.values(this._fieldObjects))for(const f of p)m.has(f.id)===o&&c.push(f)}else for(const m of Object.values(this._fieldObjects))c.push(...m);const d=this.annotationStorage,u=[];for(const m of c){const{id:p}=m;switch(u.push(p),m.type){case"text":{const x=m.defaultValue||"";d.setValue(p,{value:x});break}case"checkbox":case"radiobutton":{const x=m.defaultValue===m.exportValues;d.setValue(p,{value:x});break}case"combobox":case"listbox":{const x=m.defaultValue||"";d.setValue(p,{value:x});break}default:continue}const f=document.querySelector(`[data-element-id="${p}"]`);if(f){if(!e9.has(f)){nd(`_bindResetFormAction - element not allowed: ${p}`);continue}}else continue;f.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}}}Ow=new WeakSet,jD=function(){this.container.setAttribute("data-internal-link","")},sQt=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},Xt(this,Ow,jD).call(this)},nQt=function(n,r){n.href=this.linkService.getAnchorUrl(""),n.onclick=()=>(this.linkService.executeSetOCGState(r),!1),Xt(this,Ow,jD).call(this)};class oqn extends Zg{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(t),this.container}}class U9 extends Zg{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 fb.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":Lo.makeHexColor(n[0],n[1],n[2])}_setTextStyle(t){const n=["left","center","right"],{fontColor:r}=this.data.defaultAppearanceData,a=this.data.defaultAppearanceData.fontSize||aqn,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/(R9e*a))||1,h=d/u;l=Math.min(a,c(h/R9e))}else{const d=Math.abs(this.data.rect[3]-this.data.rect[1]-o);l=Math.min(a,c(d/R9e))}i.fontSize=`calc(${l}px * var(--scale-factor))`,i.color=Lo.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 lqn extends U9{constructor(t){const n=t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue;super(t,{isRenderable:n})}setPropertyOnSiblings(t,n,r,a){const i=this.annotationStorage;for(const l of this._getElementsByName(t.name,t.id))l.domElement&&(l.domElement[n]=r),i.setValue(l.id,{[a]:r})}render(){var a,i;const t=this.annotationStorage,n=this.data.id;this.container.classList.add("textWidgetAnnotation");let r=null;if(this.renderForms){const l=t.getValue(n,{value:this.data.fieldValue});let o=l.value||"";const c=t.getValue(n,{charLimit:this.data.maxLen}).charLimit;c&&o.length>c&&(o=o.slice(0,c));let d=l.formattedValue||((a=this.data.textContent)==null?void 0:a.join(` `))||null;d&&this.data.comb&&(d=d.replaceAll(/\s+/g,""));const u={userValue:o,formattedValue:d,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(r=document.createElement("textarea"),r.textContent=d??o,this.data.doNotScroll&&(r.style.overflowY="hidden")):(r=document.createElement("input"),r.type="text",r.setAttribute("value",d??o),this.data.doNotScroll&&(r.style.overflowX="hidden")),this.data.hasOwnCanvas&&(r.hidden=!0),e9.add(r),r.setAttribute("data-element-id",n),r.disabled=this.data.readOnly,r.name=this.data.fieldName,r.tabIndex=sae,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 p=this.data.defaultFieldValue??"";r.value=u.userValue=p,u.formattedValue=null});let h=m=>{const{formattedValue:p}=u;p!=null&&(m.target.value=p),m.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){r.addEventListener("focus",p=>{var x;if(u.focused)return;const{target:f}=p;u.userValue&&(f.value=u.userValue),u.lastCommittedValue=f.value,u.commitKey=1,(x=this.data.actions)!=null&&x.Focus||(u.focused=!0)}),r.addEventListener("updatefromsandbox",p=>{this.showElementAndHideCanvas(p.target);const f={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 N;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}),(N=this.linkService.eventBus)==null||N.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:b,willCommit:!0,commitKey:1,selStart:v.selectionStart,selEnd:v.selectionEnd}}))}};this._dispatchEventFromSandbox(f,p)}),r.addEventListener("keydown",p=>{var y;u.commitKey=1;let f=-1;if(p.key==="Escape"?f=0:p.key==="Enter"&&!this.data.multiLine?f=2:p.key==="Tab"&&(u.commitKey=3),f===-1)return;const{value:x}=p.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:f,selStart:p.target.selectionStart,selEnd:p.target.selectionEnd}}))});const m=h;h=null,r.addEventListener("blur",p=>{var x,y;if(!u.focused||!p.relatedTarget)return;(x=this.data.actions)!=null&&x.Blur||(u.focused=!1);const{value:f}=p.target;u.userValue=f,u.lastCommittedValue!==f&&((y=this.linkService.eventBus)==null||y.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:f,willCommit:!0,commitKey:u.commitKey,selStart:p.target.selectionStart,selEnd:p.target.selectionEnd}})),m(p)}),(i=this.data.actions)!=null&&i.Keystroke&&r.addEventListener("beforeinput",p=>{var A;u.lastCommittedValue=null;const{data:f,target:x}=p,{value:y,selectionStart:v,selectionEnd:b}=x;let N=v,S=b;switch(p.inputType){case"deleteWordBackward":{const T=y.substring(0,v).match(/\w*[^\w]*$/);T&&(N-=T[0].length);break}case"deleteWordForward":{const T=y.substring(v).match(/^[^\w]*\w*/);T&&(S+=T[0].length);break}case"deleteContentBackward":v===b&&(N-=1);break;case"deleteContentForward":v===b&&(S+=1);break}p.preventDefault(),(A=this.linkService.eventBus)==null||A.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:y,change:f||"",willCommit:!1,selStart:N,selEnd:S}})}),this._setEventListeners(r,u,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],p=>p.target.value)}if(h&&r.addEventListener("blur",h),this.data.comb){const p=(this.data.rect[2]-this.data.rect[0])/c;r.classList.add("comb"),r.style.letterSpacing=`calc(${p}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 cqn extends U9{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class dqn extends U9{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,n=this.data,r=n.id;let a=t.getValue(r,{value:n.exportValue===n.fieldValue}).value;typeof a=="string"&&(a=a!=="Off",t.setValue(r,{value:a})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const i=document.createElement("input");return e9.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=sae,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 rQt extends U9{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,n=this.data,r=n.id;let a=t.getValue(r,{value:n.fieldValue===n.buttonValue}).value;if(typeof a=="string"&&(a=a!==n.buttonValue,t.setValue(r,{value:a})),a)for(const l of this._getElementsByName(n.fieldName,r))t.setValue(l.id,{value:!1});const i=document.createElement("input");if(e9.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=sae,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 uqn extends tQt{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 hqn extends U9{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,n=this.data.id,r=t.getValue(n,{value:this.data.fieldValue}),a=document.createElement("select");e9.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=sae;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:p}=a;return p?Array.prototype.filter.call(m,f=>f.selected).map(f=>f[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 p=m.detail.value,f=new Set(Array.isArray(p)?p:[p]);for(const x of a.options)x.selected=f.has(x.value);t.setValue(n,{value:o(!0)}),c=o(!1)},multipleSelection(m){a.multiple=!0},remove(m){const p=a.options,f=m.detail.remove;p[f].selected=!1,a.remove(f),p.length>0&&Array.prototype.findIndex.call(p,y=>y.selected)===-1&&(p[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:p,displayValue:f,exportValue:x}=m.detail.insert,y=a.children[p],v=document.createElement("option");v.textContent=f,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:p}=m.detail;for(;a.length!==0;)a.remove(0);for(const f of p){const{displayValue:x,exportValue:y}=f,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 p=new Set(m.detail.indices);for(const f of m.target.options)f.selected=p.has(f.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 p;const h=o(!0),m=o(!1);t.setValue(n,{value:h}),u.preventDefault(),(p=this.linkService.eventBus)==null||p.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 wWe extends Zg{constructor(t){const{data:n,elements:r}=t;super(t,{isRenderable:Zg._hasPopupData(n)}),this.elements=r,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new mqn({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=>`${pnt}${r}`).join(",")),this.container}}var eV,QTe,JTe,tV,QO,Yf,YC,sV,qse,$se,nV,ZC,jk,XC,Vse,QC,Hse,JO,eF,Zh,w4e,jWe,aQt,iQt,oQt,lQt,j4e,N4e,NWe;class mqn{constructor({container:t,color:n,elements:r,titleObj:a,modificationDate:i,contentsObj:l,richText:o,parent:c,rect:d,parentRect:u,open:h}){is(this,Zh);is(this,eV,Xt(this,Zh,oQt).bind(this));is(this,QTe,Xt(this,Zh,NWe).bind(this));is(this,JTe,Xt(this,Zh,N4e).bind(this));is(this,tV,Xt(this,Zh,j4e).bind(this));is(this,QO,null);is(this,Yf,null);is(this,YC,null);is(this,sV,null);is(this,qse,null);is(this,$se,null);is(this,nV,null);is(this,ZC,!1);is(this,jk,null);is(this,XC,null);is(this,Vse,null);is(this,QC,null);is(this,Hse,null);is(this,JO,null);is(this,eF,!1);var m;$t(this,Yf,t),$t(this,Hse,a),$t(this,YC,l),$t(this,QC,o),$t(this,$se,c),$t(this,QO,n),$t(this,Vse,d),$t(this,nV,u),$t(this,qse,r),$t(this,sV,xnt.toDateObject(i)),this.trigger=r.flatMap(p=>p.getElementsToTriggerPopup());for(const p of this.trigger)p.addEventListener("click",fe(this,tV)),p.addEventListener("mouseenter",fe(this,JTe)),p.addEventListener("mouseleave",fe(this,QTe)),p.classList.add("popupTriggerArea");for(const p of r)(m=p.container)==null||m.addEventListener("keydown",fe(this,eV));fe(this,Yf).hidden=!0,h&&Xt(this,Zh,j4e).call(this)}render(){if(fe(this,jk))return;const t=$t(this,jk,document.createElement("div"));if(t.className="popup",fe(this,QO)){const i=t.style.outlineColor=Lo.makeHexColor(...fe(this,QO));CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?t.style.backgroundColor=`color-mix(in srgb, ${i} 30%, white)`:t.style.backgroundColor=Lo.makeHexColor(...fe(this,QO).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}=fe(this,Hse),t.append(n),fe(this,sV)){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:fe(this,sV).valueOf()})),n.append(i)}const a=fe(this,Zh,w4e);if(a)eQt.render({xfaHtml:a,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const i=this._formatContents(fe(this,YC));t.append(i)}fe(this,Yf).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)&&Xt(this,Qse,kWe).call(this)}),!r.popupRef&&this.hasPopupData?this._createPopup():a.classList.add("popupTriggerArea"),n.append(a),n}getElementsToTriggerPopup(){return fe(this,Xse)}addHighlightArea(){this.container.classList.add("highlightArea")}}Xse=new WeakMap,Qse=new WeakSet,kWe=function(){var n;(n=this.downloadManager)==null||n.openOrDownloadData(this.content,this.filename)};var Jse,tF,sF,ene,o9,mQt,SWe;class jqn{constructor({div:t,accessibilityManager:n,annotationCanvasMap:r,annotationEditorUIManager:a,page:i,viewport:l,structTreeLayer:o}){is(this,o9);is(this,Jse,null);is(this,tF,null);is(this,sF,new Map);is(this,ene,null);this.div=t,$t(this,Jse,n),$t(this,tF,r),$t(this,ene,o||null),this.page=i,this.viewport=l,this.zIndex=0,this._annotationEditorUIManager=a}hasEditableAnnotations(){return fe(this,sF).size>0}async render(t){var l;const{annotations:n}=t,r=this.div;Q7(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 Nnt,annotationStorage:t.annotationStorage||new vnt,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===Ux.POPUP;if(c){const h=a.get(o.id);if(!h)continue;i.elements=h}else{const{width:h,height:m}=BA(o.rect);if(h<=0||m<=0)continue}i.data=o;const d=iqn.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 Xt(this,o9,mQt).call(this,u,o.id),d._isEditable&&(fe(this,sF).set(d.data.id,d),(l=this._annotationEditorUIManager)==null||l.renderAnnotationElement(d))}Xt(this,o9,SWe).call(this)}update({viewport:t}){const n=this.div;this.viewport=t,Q7(n,{rotation:t.rotation}),Xt(this,o9,SWe).call(this),n.hidden=!1}getEditableAnnotations(){return Array.from(fe(this,sF).values())}getEditableAnnotation(t){return fe(this,sF).get(t)}}Jse=new WeakMap,tF=new WeakMap,sF=new WeakMap,ene=new WeakMap,o9=new WeakSet,mQt=async function(t,n){var l,o;const r=t.firstChild||t,a=r.id=`${pnt}${n}`,i=await((l=fe(this,ene))==null?void 0:l.getAriaAttributes(a));if(i)for(const[c,d]of i)r.setAttribute(c,d);this.div.append(t),(o=fe(this,Jse))==null||o.moveElementInDOM(this.div,t,r,!1)},SWe=function(){if(!fe(this,tF))return;const t=this.div;for(const[n,r]of fe(this,tF)){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)}fe(this,tF).clear()};const uce=/\r\n?|\n/g;var Nk,ww,tne,nF,jw,kx,pQt,fQt,gQt,k4e,YA,S4e,C4e,xQt,AWe,yQt;const km=class km extends wh{constructor(n){super({...n,name:"freeTextEditor"});is(this,kx);is(this,Nk);is(this,ww,"");is(this,tne,`${this.id}-editor`);is(this,nF,null);is(this,jw);$t(this,Nk,n.color||km._defaultColor||wh._defaultLineColor),$t(this,jw,n.fontSize||km._defaultFontSize)}static get _keyboardManager(){const n=km.prototype,r=l=>l.isEmpty(),a=J7.TRANSLATE_SMALL,i=J7.TRANSLATE_BIG;return Yd(this,"_keyboardManager",new tae([[["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){wh.initialize(n,r);const a=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(a.getPropertyValue("--freetext-padding"))}static updateDefaultParams(n,r){switch(n){case dc.FREETEXT_SIZE:km._defaultFontSize=r;break;case dc.FREETEXT_COLOR:km._defaultColor=r;break}}updateParams(n,r){switch(n){case dc.FREETEXT_SIZE:Xt(this,kx,pQt).call(this,r);break;case dc.FREETEXT_COLOR:Xt(this,kx,fQt).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[dc.FREETEXT_SIZE,km._defaultFontSize],[dc.FREETEXT_COLOR,km._defaultColor||wh._defaultLineColor]]}get propertiesToUpdate(){return[[dc.FREETEXT_SIZE,fe(this,jw)],[dc.FREETEXT_COLOR,fe(this,Nk)]]}_translateEmpty(n,r){this._uiManager.translateSelectedEditors(n,r,!0)}getInitialTranslation(){const n=this.parentScale;return[-km._internalPadding*n,-(km._internalPadding+fe(this,jw))*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(Uc.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),$t(this,nF,new AbortController);const n=this._uiManager.combinedSignal(fe(this,nF));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",fe(this,tne)),this._isDraggable=!0,(n=fe(this,nF))==null||n.abort(),$t(this,nF,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=fe(this,ww),r=$t(this,ww,Xt(this,kx,gQt).call(this).trimEnd());if(n===r)return;const a=i=>{if($t(this,ww,i),!i){this.remove();return}Xt(this,kx,C4e).call(this),this._uiManager.rebuild(this),Xt(this,kx,k4e).call(this)};this.addCommands({cmd:()=>{a(r)},undo:()=>{a(n)},mustExec:!1}),Xt(this,kx,k4e).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){km._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",fe(this,tne)),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(${fe(this,jw)}px * var(--scale-factor))`,a.color=fe(this,Nk),this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),JEe(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,p]=this.pageTranslation;let f,x;switch(this.rotation){case 0:f=n+(o[0]-m)/u,x=r+this.height-(o[1]-p)/h;break;case 90:f=n+(o[0]-m)/u,x=r-(o[1]-p)/h,[c,d]=[d,-c];break;case 180:f=n-this.width+(o[0]-m)/u,x=r-(o[1]-p)/h,[c,d]=[-c,-d];break;case 270:f=n+(o[0]-m-this.height*h)/u,x=r+(o[1]-p-this.width*u)/h,[c,d]=[-d,c];break}this.setAt(f*i,x*l,c,d)}else this.setAt(n*i,r*l,this.width*i,this.height*l);Xt(this,kx,C4e).call(this),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}editorDivPaste(n){var f,x,y;const r=n.clipboardData||window.clipboardData,{types:a}=r;if(a.length===1&&a[0]==="text/plain")return;n.preventDefault();const i=Xt(f=km,YA,AWe).call(f,r.getData("text")||"").replaceAll(uce,` `);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(uce,"")),v!==this.editorDiv){let b=u;for(const N of this.editorDiv.childNodes){if(N===v){b=h;continue}b.push(Xt(x=km,YA,S4e).call(x,N))}}u.push(c.nodeValue.slice(0,d).replaceAll(uce,""))}else if(c===this.editorDiv){let v=u,b=0;for(const N of this.editorDiv.childNodes)b++===d&&(v=h),v.push(Xt(y=km,YA,S4e).call(y,N))}$t(this,ww,`${u.join(` `)}${i}${h.join(` `)}`),Xt(this,kx,C4e).call(this);const m=new Range;let p=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(p<=b){m.setStart(v,p),m.setEnd(v,p);break}p-=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 cQt){const{data:{defaultAppearanceData:{fontSize:c,fontColor:d},rect:u,rotation:h,id:m,popupRef:p},textContent:f,textPosition:x,parent:{page:{pageNumber:y}}}=n;if(!f||f.length===0)return null;i=n={annotationType:Uc.FREETEXT,color:Array.from(d),fontSize:c,value:f.join(` `),position:x,pageIndex:y-1,rect:u.slice(0),rotation:h,id:m,deleted:!1,popupRef:p}}const l=await super.deserialize(n,r,a);return $t(l,jw,n.fontSize),$t(l,Nk,Lo.makeHexColor(...n.color)),$t(l,ww,Xt(o=km,YA,AWe).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=km._internalPadding*this.parentScale,a=this.getRect(r,r),i=wh._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:fe(this,Nk)),l={annotationType:Uc.FREETEXT,color:i,fontSize:fe(this,jw),value:Xt(this,kx,xQt).call(this),pageIndex:this.pageIndex,rect:a,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return n?l:this.annotationElementId&&!Xt(this,kx,yQt).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(${fe(this,jw)}px * var(--scale-factor))`,a.color=fe(this,Nk),r.replaceChildren();for(const l of fe(this,ww).split(` `)){const o=document.createElement("div");o.append(l?document.createTextNode(l):document.createElement("br")),r.append(o)}const i=km._internalPadding*this.parentScale;return n.updateEdited({rect:this.getRect(i,i),popupContent:fe(this,ww)}),r}resetAnnotationElement(n){super.resetAnnotationElement(n),n.resetEdited()}};Nk=new WeakMap,ww=new WeakMap,tne=new WeakMap,nF=new WeakMap,jw=new WeakMap,kx=new WeakSet,pQt=function(n){const r=i=>{this.editorDiv.style.fontSize=`calc(${i}px * var(--scale-factor))`,this.translate(0,-(i-fe(this,jw))*this.parentScale),$t(this,jw,i),Xt(this,kx,k4e).call(this)},a=fe(this,jw);this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:dc.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})},fQt=function(n){const r=i=>{$t(this,Nk,this.editorDiv.style.color=i)},a=fe(this,Nk);this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:dc.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})},gQt=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(Xt(a=km,YA,S4e).call(a,i)),r=i);return n.join(` `)},k4e=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()},YA=new WeakSet,S4e=function(n){return(n.nodeType===Node.TEXT_NODE?n.nodeValue:n.innerText).replaceAll(uce,"")},C4e=function(){if(this.editorDiv.replaceChildren(),!!fe(this,ww))for(const n of fe(this,ww).split(` `)){const r=document.createElement("div");r.append(n?document.createTextNode(n):document.createElement("br")),this.editorDiv.append(r)}},xQt=function(){return fe(this,ww).replaceAll(" "," ")},AWe=function(n){return n.replaceAll(" "," ")},yQt=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},is(km,YA),Lr(km,"_freeTextDefaultContent",""),Lr(km,"_internalPadding",0),Lr(km,"_defaultColor",null),Lr(km,"_defaultFontSize",10),Lr(km,"_type","freetext"),Lr(km,"_editorType",Uc.FREETEXT);let CWe=km;class vQt{toSVGPath(){ip("Abstract method `toSVGPath` must be implemented.")}get box(){ip("Abstract getter `box` must be implemented.")}serialize(t,n){ip("Abstract method `serialize` must be implemented.")}get classNamesForDrawing(){ip("Abstract getter `classNamesForDrawing` must be implemented.")}get classNamesForOutlining(){ip("Abstract getter `classNamesForOutlining` must be implemented.")}get mustRemoveSelfIntersections(){return!1}}var Nw,kk,rV,aV,K5,ud,rF,aF,sne,nne,iV,oV,B6,rne,e6e,t6e,c0,KZ,bQt,_Qt,wQt,jQt,NQt,kQt;const AC=class AC{constructor({x:t,y:n},r,a,i,l,o=0){is(this,c0);is(this,Nw);is(this,kk,[]);is(this,rV);is(this,aV);is(this,K5,[]);is(this,ud,new Float64Array(18));is(this,rF);is(this,aF);is(this,sne);is(this,nne);is(this,iV);is(this,oV);is(this,B6,[]);$t(this,Nw,r),$t(this,oV,i*a),$t(this,aV,l),fe(this,ud).set([NaN,NaN,NaN,NaN,t,n],6),$t(this,rV,o),$t(this,nne,fe(AC,rne)*a),$t(this,sne,fe(AC,t6e)*a),$t(this,iV,a),fe(this,B6).push(t,n)}isEmpty(){return isNaN(fe(this,ud)[8])}add({x:t,y:n}){var I;$t(this,rF,t),$t(this,aF,n);const[r,a,i,l]=fe(this,Nw);let[o,c,d,u]=fe(this,ud).subarray(8,12);const h=t-d,m=n-u,p=Math.hypot(h,m);if(p=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 Xt(this,c0,_Qt).call(this,r),r.join(" ")}newFreeDrawOutline(t,n,r,a,i,l){return new SQt(t,n,r,a,i,l)}getOutlines(){var h;const t=fe(this,K5),n=fe(this,kk),r=fe(this,ud),[a,i,l,o]=fe(this,Nw),c=new Float64Array((((h=fe(this,B6))==null?void 0:h.length)??0)+2);for(let m=0,p=c.length-2;m=6;m-=6)for(let p=0;p<6;p+=2){if(isNaN(n[m+p])){d[u]=d[u+1]=NaN,u+=2;continue}d[u]=n[m+p],d[u+1]=n[m+p+1],u+=2}return Xt(this,c0,NQt).call(this,d,u),this.newFreeDrawOutline(d,c,fe(this,Nw),fe(this,iV),fe(this,rV),fe(this,aV))}};Nw=new WeakMap,kk=new WeakMap,rV=new WeakMap,aV=new WeakMap,K5=new WeakMap,ud=new WeakMap,rF=new WeakMap,aF=new WeakMap,sne=new WeakMap,nne=new WeakMap,iV=new WeakMap,oV=new WeakMap,B6=new WeakMap,rne=new WeakMap,e6e=new WeakMap,t6e=new WeakMap,c0=new WeakSet,KZ=function(){const t=fe(this,ud).subarray(4,6),n=fe(this,ud).subarray(16,18),[r,a,i,l]=fe(this,Nw);return[(fe(this,rF)+(t[0]-n[0])/2-r)/i,(fe(this,aF)+(t[1]-n[1])/2-a)/l,(fe(this,rF)+(n[0]-t[0])/2-r)/i,(fe(this,aF)+(n[1]-t[1])/2-a)/l]},bQt=function(){const[t,n,r,a]=fe(this,Nw),[i,l,o,c]=Xt(this,c0,KZ).call(this);return`M${(fe(this,ud)[2]-t)/r} ${(fe(this,ud)[3]-n)/a} L${(fe(this,ud)[4]-t)/r} ${(fe(this,ud)[5]-n)/a} L${i} ${l} L${o} ${c} L${(fe(this,ud)[16]-t)/r} ${(fe(this,ud)[17]-n)/a} L${(fe(this,ud)[14]-t)/r} ${(fe(this,ud)[15]-n)/a} Z`},_Qt=function(t){const n=fe(this,kk);t.push(`L${n[4]} ${n[5]} Z`)},wQt=function(t){const[n,r,a,i]=fe(this,Nw),l=fe(this,ud).subarray(4,6),o=fe(this,ud).subarray(16,18),[c,d,u,h]=Xt(this,c0,KZ).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}`)},jQt=function(t){const n=fe(this,ud),[r,a,i,l]=fe(this,Nw),[o,c,d,u]=Xt(this,c0,KZ).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,fe(this,Nw),fe(this,iV),fe(this,rV),fe(this,aV))},NQt=function(t,n){const r=fe(this,kk);return t.set([NaN,NaN,NaN,NaN,r[4],r[5]],n),n+=6},kQt=function(t,n){const r=fe(this,ud).subarray(4,6),a=fe(this,ud).subarray(16,18),[i,l,o,c]=fe(this,Nw),[d,u,h,m]=Xt(this,c0,KZ).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},is(AC,rne,8),is(AC,e6e,2),is(AC,t6e,fe(AC,rne)+fe(AC,e6e));let tTe=AC;var lV,iF,JC,ane,kw,ine,Cg,j_,YZ,ZZ,CQt;class SQt extends vQt{constructor(n,r,a,i,l,o){super();is(this,j_);is(this,lV);is(this,iF,null);is(this,JC);is(this,ane);is(this,kw);is(this,ine);is(this,Cg);$t(this,Cg,n),$t(this,kw,r),$t(this,lV,a),$t(this,ine,i),$t(this,JC,l),$t(this,ane,o),Xt(this,j_,CQt).call(this,o);const{x:c,y:d,width:u,height:h}=fe(this,iF);for(let m=0,p=n.length;mn[0]-r[0]||n[1]-r[1]||n[2]-r[2]);const t=[];for(const n of fe(this,U6))n[3]?(t.push(...Xt(this,vb,EWe).call(this,n)),Xt(this,vb,EQt).call(this,n)):(Xt(this,vb,TQt).call(this,n),t.push(...Xt(this,vb,EWe).call(this,n)));return Xt(this,vb,AQt).call(this,t)}}one=new WeakMap,U6=new WeakMap,Sk=new WeakMap,vb=new WeakSet,AQt=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,p=c;for(i=[o,d],a.push(i);;){let f;if(r.has(u))f=u;else if(r.has(h))f=h;else break;r.delete(f),[o,c,d,u,h]=f,m!==o&&(i.push(m,p,o,p===c?c:d),m=o),p=p===c?d:c}i.push(m,p)}return new Nqn(a,fe(this,one))},A4e=function(t){const n=fe(this,Sk);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]=fe(this,Sk)[a];if(i!==t)break;if(i===t&&l===n){fe(this,Sk).splice(a,1);return}}},EWe=function(t){const[n,r,a]=t,i=[[n,r,a]],l=Xt(this,vb,A4e).call(this,a);for(let o=0;o=c){if(p>d)i[u][1]=d;else{if(h===1)return[];i.splice(u,1),u--,h--}continue}i[u][2]=c,p>d&&i.push([n,d,p])}}}return i};var lne,cV;class Nqn extends vQt{constructor(n,r){super();is(this,lne);is(this,cV);$t(this,cV,n),$t(this,lne,r)}toSVGPath(){const n=[];for(const r of fe(this,cV)){let[a,i]=r;n.push(`M${a} ${i}`);for(let l=2;l-1?($t(this,i_,!0),Xt(this,Ic,E4e).call(this,n),Xt(this,Ic,kD).call(this)):fe(this,eA)&&($t(this,mV,n.anchorNode),$t(this,mne,n.anchorOffset),$t(this,pne,n.focusNode),$t(this,fne,n.focusOffset),Xt(this,Ic,IWe).call(this),Xt(this,Ic,kD).call(this),this.rotate(this.rotation))}static get _keyboardManager(){const n=Bu.prototype;return Yd(this,"_keyboardManager",new tae([[["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:fe(this,i_)?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:fe(this,b2),methodOfCreation:fe(this,gne)}}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;wh.initialize(n,r),Bu._defaultColor||(Bu._defaultColor=((a=r.highlightColors)==null?void 0:a.values().next().value)||"#fff066")}static updateDefaultParams(n,r){switch(n){case dc.HIGHLIGHT_DEFAULT_COLOR:Bu._defaultColor=r;break;case dc.HIGHLIGHT_THICKNESS:Bu._defaultThickness=r;break}}translateInPage(n,r){}get toolbarPosition(){return fe(this,fV)}updateParams(n,r){switch(n){case dc.HIGHLIGHT_COLOR:Xt(this,Ic,PQt).call(this,r);break;case dc.HIGHLIGHT_THICKNESS:Xt(this,Ic,LQt).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[dc.HIGHLIGHT_DEFAULT_COLOR,Bu._defaultColor],[dc.HIGHLIGHT_THICKNESS,Bu._defaultThickness]]}get propertiesToUpdate(){return[[dc.HIGHLIGHT_COLOR,this.color||Bu._defaultColor],[dc.HIGHLIGHT_THICKNESS,fe(this,b2)||Bu._defaultThickness],[dc.HIGHLIGHT_FREE,fe(this,i_)]]}async addEditToolbar(){const n=await super.addEditToolbar();return n?(this._uiManager.highlightColors&&($t(this,pV,new sTe({editor:this})),n.addColorPicker(fe(this,pV))),n):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(Xt(this,Ic,XZ).call(this))}getBaseTranslation(){return[0,0]}getRect(n,r){return super.getRect(n,r,Xt(this,Ic,XZ).call(this))}onceAdded(){this.annotationElementId||this.parent.addUndoableEditor(this),this.div.focus()}remove(){Xt(this,Ic,RWe).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(Xt(this,Ic,kD).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(n){var a;let r=!1;this.parent&&!n?Xt(this,Ic,RWe).call(this):n&&(Xt(this,Ic,kD).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;fe(this,i_)?(n=(n-this.rotation+360)%360,a=Xt(i=Bu,F2,XB).call(i,fe(this,Ek).box,n)):a=Xt(l=Bu,F2,XB).call(l,this,n),r.rotate(fe(this,Wv),n),r.rotate(fe(this,Gx),n),r.updateBox(fe(this,Wv),a),r.updateBox(fe(this,Gx),Xt(o=Bu,F2,XB).call(o,fe(this,v2).box,n))}render(){if(this.div)return this.div;const n=super.render();fe(this,gV)&&(n.setAttribute("aria-label",fe(this,gV)),n.setAttribute("role","mark")),fe(this,i_)?n.classList.add("free"):this.div.addEventListener("keydown",Xt(this,Ic,RQt).bind(this),{signal:this._uiManager._signal});const r=$t(this,cF,document.createElement("div"));n.append(r),r.setAttribute("aria-hidden","true"),r.className="internal",r.style.clipPath=fe(this,lF);const[a,i]=this.parentDimensions;return this.setDims(this.width*a,this.height*i),JEe(this,fe(this,cF),["pointerover","pointerleave"]),this.enableEditing(),n}pointerover(){this.isSelected||this.parent.drawLayer.addClass(fe(this,Gx),"hovered")}pointerleave(){this.isSelected||this.parent.drawLayer.removeClass(fe(this,Gx),"hovered")}_moveCaret(n){switch(this.parent.unselect(this),n){case 0:case 2:Xt(this,Ic,T4e).call(this,!0);break;case 1:case 3:Xt(this,Ic,T4e).call(this,!1);break}}select(){var n,r;super.select(),fe(this,Gx)&&((n=this.parent)==null||n.drawLayer.removeClass(fe(this,Gx),"hovered"),(r=this.parent)==null||r.drawLayer.addClass(fe(this,Gx),"selected"))}unselect(){var n;super.unselect(),fe(this,Gx)&&((n=this.parent)==null||n.drawLayer.removeClass(fe(this,Gx),"selected"),fe(this,i_)||Xt(this,Ic,T4e).call(this,!1))}get _mustFixPosition(){return!fe(this,i_)}show(n=this._isVisible){super.show(n),this.parent&&(this.parent.drawLayer.show(fe(this,Wv),n),this.parent.drawLayer.show(fe(this,Gx),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),p=x=>{x.preventDefault(),x.stopPropagation()},f=x=>{h.abort(),Xt(this,F2,zQt).call(this,n,x)};window.addEventListener("blur",f,{signal:m}),window.addEventListener("pointerup",f,{signal:m}),window.addEventListener("pointerdown",p,{capture:!0,passive:!1,signal:m}),window.addEventListener("contextmenu",xN,{signal:m}),a.addEventListener("pointermove",Xt(this,F2,FQt).bind(this,n),{signal:m}),this._freeHighlight=new TWe({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 uQt){const{data:{quadPoints:N,rect:S,rotation:A,id:T,color:L,opacity:M,popupRef:I},parent:{page:{pageNumber:R}}}=n;i=n={annotationType:Uc.HIGHLIGHT,color:Array.from(L),opacity:M,quadPoints:N,boxes:null,pageIndex:R-1,rect:S.slice(0),rotation:A,id:T,deleted:!1,popupRef:I}}else if(n instanceof knt){const{data:{inkLists:N,rect:S,rotation:A,id:T,color:L,borderStyle:{rawWidth:M},popupRef:I},parent:{page:{pageNumber:R}}}=n;i=n={annotationType:Uc.HIGHLIGHT,color:Array.from(L),thickness:M,inkLists:N,boxes:null,pageIndex:R-1,rect:S.slice(0),rotation:A,id:T,deleted:!1,popupRef:I}}const{color:l,quadPoints:o,inkLists:c,opacity:d}=n,u=await super.deserialize(n,r,a);u.color=Lo.makeHexColor(...l),$t(u,tA,d||1),c&&$t(u,b2,n.thickness),u.annotationElementId=n.id||null,u._initialData=i;const[h,m]=u.pageDimensions,[p,f]=u.pageTranslation;if(o){const N=$t(u,eA,[]);for(let S=0;S=0)$t(this,Wv,r),$t(this,lF,a),this.parent.drawLayer.finalizeLine(r,n),$t(this,Gx,this.parent.drawLayer.drawOutline(fe(this,v2)));else if(this.parent){const p=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(fe(this,Wv),n),this.parent.drawLayer.updateBox(fe(this,Wv),Xt(h=Bu,F2,XB).call(h,fe(this,Ek).box,(p-this.rotation+360)%360)),this.parent.drawLayer.updateLine(fe(this,Gx),fe(this,v2)),this.parent.drawLayer.updateBox(fe(this,Gx),Xt(m=Bu,F2,XB).call(m,fe(this,v2).box,p))}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[p,f]=this.parentDimensions;this.x=o,this.y=1-l,this.width=c*f/p,this.height=d*p/f;break}case 180:this.x=1-l,this.y=1-o,this.width=c,this.height=d;break;case 270:{const[p,f]=this.parentDimensions;this.x=1-o,this.y=l,this.width=c*f/p,this.height=d*p/f;break}}const{lastPoint:u}=fe(this,v2).box;$t(this,fV,[(u[0]-l)/c,(u[1]-o)/d])},PQt=function(n){const r=(l,o)=>{var c,d,u;this.color=l,(c=this.parent)==null||c.drawLayer.changeColor(fe(this,Wv),l),(d=fe(this,pV))==null||d.updateColor(l),$t(this,tA,o),(u=this.parent)==null||u.drawLayer.changeOpacity(fe(this,Wv),o)},a=this.color,i=fe(this,tA);this.addCommands({cmd:r.bind(this,n,Bu._defaultOpacity),undo:r.bind(this,a,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:dc.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(n)},!0)},LQt=function(n){const r=fe(this,b2),a=i=>{$t(this,b2,i),Xt(this,Ic,IQt).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:dc.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:n},!0)},IQt=function(n){if(!fe(this,i_))return;Xt(this,Ic,E4e).call(this,{highlightOutlines:fe(this,Ek).getNewOutline(n/2)}),this.fixAndSetPosition();const[r,a]=this.parentDimensions;this.setDims(this.width*r,this.height*a)},RWe=function(){fe(this,Wv)===null||!this.parent||(this.parent.drawLayer.remove(fe(this,Wv)),$t(this,Wv,null),this.parent.drawLayer.remove(fe(this,Gx)),$t(this,Gx,null))},kD=function(n=this.parent){fe(this,Wv)===null&&({id:O0(this,Wv)._,clipPathId:O0(this,lF)._}=n.drawLayer.draw(fe(this,Ek),this.color,fe(this,tA)),$t(this,Gx,n.drawLayer.drawOutline(fe(this,v2))),fe(this,cF)&&(fe(this,cF).style.clipPath=fe(this,lF)))},F2=new WeakSet,XB=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}},RQt=function(n){Bu._keyboardManager.exec(this,n)},T4e=function(n){if(!fe(this,mV))return;const r=window.getSelection();n?r.setPosition(fe(this,mV),fe(this,mne)):r.setPosition(fe(this,pne),fe(this,fne))},XZ=function(){return fe(this,i_)?this.rotation:0},DQt=function(){if(fe(this,i_))return null;const[n,r]=this.pageDimensions,[a,i]=this.pageTranslation,l=fe(this,eA),o=new Float32Array(l.length*8);let c=0;for(const{x:d,y:u,width:h,height:m}of l){const p=d*n+a,f=(1-u-m)*r+i;o[c]=o[c+4]=p,o[c+1]=o[c+3]=f,o[c+2]=o[c+6]=p+h*n,o[c+5]=o[c+7]=f+m*r,c+=8}return o},OQt=function(n){return fe(this,Ek).serialize(n,Xt(this,Ic,XZ).call(this))},FQt=function(n,r){this._freeHighlight.add(r)&&n.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)},zQt=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=""},BQt=function(n){const{color:r}=this._initialData;return n.color.some((a,i)=>a!==r[i])},is(Bu,F2),Lr(Bu,"_defaultColor",null),Lr(Bu,"_defaultOpacity",1),Lr(Bu,"_defaultThickness",12),Lr(Bu,"_type","highlight"),Lr(Bu,"_editorType",Uc.HIGHLIGHT),Lr(Bu,"_freeHighlightId",-1),Lr(Bu,"_freeHighlight",null),Lr(Bu,"_freeHighlightClipId","");let nTe=Bu;var dF,uF,Y5,sA,_2,hF,mF,pF,nA,xV,fF,gF,$6,ki,UQt,qQt,$Qt,VQt,OWe,HQt,FWe,GQt,WQt,KQt,YQt,ZQt,SD,zWe,BWe,UWe,M4e,P4e,QB,qWe,L4e,mE,XQt,$We,QQt,JQt,VWe,I4e,QZ;const of=class of extends wh{constructor(n){super({...n,name:"inkEditor"});is(this,ki);is(this,dF,0);is(this,uF,0);is(this,Y5,null);is(this,sA,new Path2D);is(this,_2,!1);is(this,hF,null);is(this,mF,!1);is(this,pF,!1);is(this,nA,null);is(this,xV,null);is(this,fF,0);is(this,gF,0);is(this,$6,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){wh.initialize(n,r)}static updateDefaultParams(n,r){switch(n){case dc.INK_THICKNESS:of._defaultThickness=r;break;case dc.INK_COLOR:of._defaultColor=r;break;case dc.INK_OPACITY:of._defaultOpacity=r/100;break}}updateParams(n,r){switch(n){case dc.INK_THICKNESS:Xt(this,ki,UQt).call(this,r);break;case dc.INK_COLOR:Xt(this,ki,qQt).call(this,r);break;case dc.INK_OPACITY:Xt(this,ki,$Qt).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[dc.INK_THICKNESS,of._defaultThickness],[dc.INK_COLOR,of._defaultColor||wh._defaultLineColor],[dc.INK_OPACITY,Math.round(of._defaultOpacity*100)]]}get propertiesToUpdate(){return[[dc.INK_THICKNESS,this.thickness||of._defaultThickness],[dc.INK_COLOR,this.color||of._defaultColor||wh._defaultLineColor],[dc.INK_OPACITY,Math.round(100*(this.opacity??of._defaultOpacity))]]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(Xt(this,ki,M4e).call(this),Xt(this,ki,P4e).call(this)),this.isAttachedToDOM||(this.parent.add(this),Xt(this,ki,QB).call(this)),Xt(this,ki,QZ).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,fe(this,Y5)&&(clearTimeout(fe(this,Y5)),$t(this,Y5,null)),(n=fe(this,nA))==null||n.disconnect(),$t(this,nA,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(){fe(this,_2)||this.canvas===null||(super.enableEditMode(),this._isDraggable=!1,Xt(this,ki,zWe).call(this))}disableEditMode(){!this.isInEditMode()||this.canvas===null||(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),Xt(this,ki,BWe).call(this))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return this.paths.length===0||this.paths.length===1&&this.paths[0].length===0}commit(){fe(this,_2)||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),$t(this,_2,!0),this.div.classList.add("disabled"),Xt(this,ki,QZ).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()||fe(this,_2)||(this.setInForeground(),n.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),Xt(this,ki,HQt).call(this,n.offsetX,n.offsetY))}canvasPointermove(n){n.preventDefault(),Xt(this,ki,FWe).call(this,n.offsetX,n.offsetY)}canvasPointerup(n){n.preventDefault(),Xt(this,ki,UWe).call(this,n)}canvasPointerleave(n){Xt(this,ki,UWe).call(this,n)}get isResizable(){return!this.isEmpty()&&fe(this,_2)}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]=Xt(this,ki,VQt).call(this);if(this.setAt(a,i,0,0),this.setDims(l,o),Xt(this,ki,M4e).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),$t(this,pF,!0),Xt(this,ki,QB).call(this),this.setDims(this.width*c,this.height*d),Xt(this,ki,SD).call(this),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return Xt(this,ki,P4e).call(this),this.div}setDimensions(n,r){const a=Math.round(n),i=Math.round(r);if(fe(this,fF)===a&&fe(this,gF)===i)return;$t(this,fF,a),$t(this,gF,i),this.canvas.style.visibility="hidden";const[l,o]=this.parentDimensions;this.width=n/l,this.height=r/o,this.fixAndSetPosition(),fe(this,_2)&&Xt(this,ki,qWe).call(this,n,r),Xt(this,ki,QB).call(this),Xt(this,ki,SD).call(this),this.canvas.style.visibility="visible",this.fixDims()}static async deserialize(n,r,a){var y,v,b;if(n instanceof knt)return null;const i=await super.deserialize(n,r,a);i.thickness=n.thickness,i.color=Lo.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;$t(i,_2,!0),$t(i,fF,Math.round(c)),$t(i,gF,Math.round(d));const{paths:m,rect:p,rotation:f}=n;for(let{bezier:N}of m){N=Xt(y=of,mE,QQt).call(y,N,p,f);const S=[];i.paths.push(S);let A=u*(N[0]-h),T=u*(N[1]-h);for(let M=2,I=N.length;M{this.thickness=i,Xt(this,ki,QZ).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:dc.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})},qQt=function(n){const r=i=>{this.color=i,Xt(this,ki,SD).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:dc.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})},$Qt=function(n){const r=i=>{this.opacity=i,Xt(this,ki,SD).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:dc.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})},VQt=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]}},OWe=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}${WBn(a)}`},HQt=function(n,r){this.canvas.addEventListener("contextmenu",xN,{signal:this._uiManager._signal}),Xt(this,ki,BWe).call(this),$t(this,hF,new AbortController);const a=this._uiManager.combinedSignal(fe(this,hF));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,fe(this,pF)||($t(this,pF,!0),Xt(this,ki,QB).call(this),this.thickness||(this.thickness=of._defaultThickness),this.color||(this.color=of._defaultColor||wh._defaultLineColor),this.opacity??(this.opacity=of._defaultOpacity)),this.currentPath.push([n,r]),$t(this,mF,!1),Xt(this,ki,OWe).call(this),$t(this,$6,()=>{Xt(this,ki,KQt).call(this),fe(this,$6)&&window.requestAnimationFrame(fe(this,$6))}),window.requestAnimationFrame(fe(this,$6))},FWe=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=fe(this,sA);if(l.push([n,r]),$t(this,mF,!0),l.length<=2){o.moveTo(...l[0]),o.lineTo(n,r);return}l.length===3&&($t(this,sA,o=new Path2D),o.moveTo(...l[0])),Xt(this,ki,YQt).call(this,o,...l.at(-3),...l.at(-2),n,r)},GQt=function(){if(this.currentPath.length===0)return;const n=this.currentPath.at(-1);fe(this,sA).lineTo(...n)},WQt=function(n,r){$t(this,$6,null),n=Math.min(Math.max(n,0),this.canvas.width),r=Math.min(Math.max(r,0),this.canvas.height),Xt(this,ki,FWe).call(this,n,r),Xt(this,ki,GQt).call(this);let a;if(this.currentPath.length!==1)a=Xt(this,ki,ZQt).call(this);else{const d=[n,r];a=[[d,d.slice(),d.slice(),d]]}const i=fe(this,sA),l=this.currentPath;this.currentPath=[],$t(this,sA,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||(Xt(this,ki,M4e).call(this),Xt(this,ki,P4e).call(this)),Xt(this,ki,QZ).call(this))};this.addCommands({cmd:o,undo:c,mustExec:!0})},KQt=function(){if(!fe(this,mF))return;$t(this,mF,!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(fe(this,sA)),l.restore()},YQt=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)},ZQt=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{$t(this,Y5,null),this.canvas.removeEventListener("contextmenu",xN)},10)),Xt(this,ki,WQt).call(this,n.offsetX,n.offsetY),this.addToAnnotationStorage(),this.setInBackground()},M4e=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")},P4e=function(){$t(this,nA,new ResizeObserver(n=>{const r=n[0].contentRect;r.width&&r.height&&this.setDimensions(r.width,r.height)})),fe(this,nA).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var n;(n=fe(this,nA))==null||n.disconnect(),$t(this,nA,null)},{once:!0})},QB=function(){if(!fe(this,pF))return;const[n,r]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*n),this.canvas.height=Math.ceil(this.height*r),Xt(this,ki,L4e).call(this)},qWe=function(n,r){const a=Xt(this,ki,I4e).call(this),i=(n-a)/fe(this,uF),l=(r-a)/fe(this,dF);this.scaleFactor=Math.min(i,l)},L4e=function(){const n=Xt(this,ki,I4e).call(this)/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+n,this.translationY*this.scaleFactor+n)},mE=new WeakSet,XQt=function(n){const r=new Path2D;for(let a=0,i=n.length;a`image/${r}`))}static get supportedTypesStr(){return Yd(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(n){return this.supportedTypes.includes(n)}static paste(n,r){r.pasteEditor(Uc.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;fe(this,$y)&&($t(this,cf,null),this._uiManager.imageManager.deleteId(fe(this,$y)),(n=fe(this,Z5))==null||n.remove(),$t(this,Z5,null),(r=fe(this,aA))==null||r.disconnect(),$t(this,aA,null),fe(this,X5)&&(clearTimeout(fe(this,X5)),$t(this,X5,null))),super.remove()}rebuild(){if(!this.parent){fe(this,$y)&&Xt(this,Id,R4e).call(this);return}super.rebuild(),this.div!==null&&(fe(this,$y)&&fe(this,Z5)===null&&Xt(this,Id,R4e).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(fe(this,V6)||fe(this,cf)||fe(this,rA)||fe(this,H6)||fe(this,$y))}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(),fe(this,cf)?Xt(this,Id,GWe).call(this):Xt(this,Id,R4e).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 p;n||(n=224);const{width:i,height:l}=fe(this,cf),o=new qGe;let c=fe(this,cf),d=i,u=l,h=null;if(r){if(i>r||l>r){const M=Math.min(r/i,r/l);d=Math.floor(i*M),u=Math.floor(l*M)}h=document.createElement("canvas");const f=h.width=Math.ceil(d*o.sx),x=h.height=Math.ceil(u*o.sy);fe(this,Sw)||(c=Xt(this,Id,D4e).call(this,f,x));const y=h.getContext("2d");y.filter=this._uiManager.hcmFilter;let v="white",b="#cfcfd8";this._uiManager.hcmFilter!=="none"?b="black":(p=window.matchMedia)!=null&&p.call(window,"(prefers-color-scheme: dark)").matches&&(v="#8f8f9d",b="#42414d");const N=15,S=N*o.sx,A=N*o.sy,T=new OffscreenCanvas(S*2,A*2),L=T.getContext("2d");L.fillStyle=v,L.fillRect(0,0,S*2,A*2),L.fillStyle=b,L.fillRect(0,0,S,A),L.fillRect(S,A,S,A),y.fillStyle=y.createPattern(T,"repeat"),y.fillRect(0,0,f,x),y.drawImage(c,0,0,c.width,c.height,0,0,f,x)}let m=null;if(a){let f,x;if(o.symmetric&&c.widthn||l>n){const b=Math.min(n/i,n/l);f=Math.floor(i*b),x=Math.floor(l*b),fe(this,Sw)||(c=Xt(this,Id,D4e).call(this,f,x))}const v=new OffscreenCanvas(f,x).getContext("2d",{willReadFrequently:!0});v.drawImage(c,0,0,c.width,c.height,0,0,f,x),m={width:f,height:x,data:v.getImageData(0,0,f,x).data}}return{canvas:h,width:d,height:u,imageData:m}}getImageForAltText(){return fe(this,Z5)}static async deserialize(n,r,a){var x;let i=null;if(n instanceof hQt){const{data:{rect:y,rotation:v,id:b,structParent:N,popupRef:S},container:A,parent:{page:{pageNumber:T}}}=n,L=A.querySelector("canvas"),M=a.imageManager.getFromCanvas(A.id,L);L.remove();const I=((x=await r._structTree.getAriaAttributes(`${pnt}${b}`))==null?void 0:x.get("aria-label"))||"";i=n={annotationType:Uc.STAMP,bitmapId:M.id,bitmap:M.bitmap,pageIndex:T-1,rect:y.slice(0),rotation:v,id:b,deleted:!1,accessibilityData:{decorative:!1,altText:I},isSvg:!1,structParent:N,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)?($t(l,$y,u),c&&$t(l,cf,c)):$t(l,rA,d),$t(l,Sw,h);const[p,f]=l.pageDimensions;return l.width=(o[2]-o[0])/p,l.height=(o[3]-o[1])/f,l.annotationElementId=n.id||null,m&&(l.altTextData=m),l._initialData=i,$t(l,vV,!!i),l}serialize(n=!1,r=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const a={annotationType:Uc.STAMP,bitmapId:fe(this,$y),pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:fe(this,Sw),structTreeParentId:this._structTreeParentId};if(n)return a.bitmapUrl=Xt(this,Id,O4e).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=Xt(this,Id,sJt).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=fe(this,Sw)?(a.rect[2]-a.rect[0])*(a.rect[3]-a.rect[1]):null;if(!r.stamps.has(fe(this,$y)))r.stamps.set(fe(this,$y),{area:o,serialized:a}),a.bitmap=Xt(this,Id,O4e).call(this,!1);else if(fe(this,Sw)){const c=r.stamps.get(fe(this,$y));o>c.area&&(c.area=o,c.serialized.bitmap.close(),c.serialized.bitmap=Xt(this,Id,O4e).call(this,!1))}return a}renderAnnotationElement(n){return n.updateEdited({rect:this.getRect(0,0)}),null}};cf=new WeakMap,$y=new WeakMap,V6=new WeakMap,rA=new WeakMap,H6=new WeakMap,yV=new WeakMap,Z5=new WeakMap,aA=new WeakMap,X5=new WeakMap,Sw=new WeakMap,vV=new WeakMap,Id=new WeakSet,JZ=function(n,r=!1){if(!n){this.remove();return}$t(this,cf,n.bitmap),r||($t(this,$y,n.id),$t(this,Sw,n.isSvg)),n.file&&$t(this,yV,n.file.name),Xt(this,Id,GWe).call(this)},eX=function(){if($t(this,V6,null),this._uiManager.enableWaiting(!1),!!fe(this,Z5)){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&fe(this,cf)){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&fe(this,cf)){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}},R4e=function(){if(fe(this,$y)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(fe(this,$y)).then(a=>Xt(this,Id,JZ).call(this,a,!0)).finally(()=>Xt(this,Id,eX).call(this));return}if(fe(this,rA)){const a=fe(this,rA);$t(this,rA,null),this._uiManager.enableWaiting(!0),$t(this,V6,this._uiManager.imageManager.getFromUrl(a).then(i=>Xt(this,Id,JZ).call(this,i)).finally(()=>Xt(this,Id,eX).call(this)));return}if(fe(this,H6)){const a=fe(this,H6);$t(this,H6,null),this._uiManager.enableWaiting(!0),$t(this,V6,this._uiManager.imageManager.getFromFile(a).then(i=>Xt(this,Id,JZ).call(this,i)).finally(()=>Xt(this,Id,eX).call(this)));return}const n=document.createElement("input");n.type="file",n.accept=TJ.supportedTypesStr;const r=this._uiManager._signal;$t(this,V6,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}}),Xt(this,Id,JZ).call(this,i)}a()},{signal:r}),n.addEventListener("cancel",()=>{this.remove(),a()},{signal:r})}).finally(()=>Xt(this,Id,eX).call(this))),n.click()},GWe=function(){const{div:n}=this;let{width:r,height:a}=fe(this,cf);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=$t(this,Z5,document.createElement("canvas"));u.setAttribute("role","img"),this.addContainer(u),(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(n.hidden=!1),Xt(this,Id,WWe).call(this,r,a),Xt(this,Id,tJt).call(this),fe(this,vV)||(this.parent.addUndoableEditor(this),$t(this,vV,!0)),this._reportTelemetry({action:"inserted_image"}),fe(this,yV)&&u.setAttribute("aria-label",fe(this,yV))},eJt=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,fe(this,X5)!==null&&clearTimeout(fe(this,X5)),$t(this,X5,setTimeout(()=>{$t(this,X5,null),Xt(this,Id,WWe).call(this,n,r)},200))},D4e=function(n,r){const{width:a,height:i}=fe(this,cf);let l=a,o=i,c=fe(this,cf);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},WWe=function(n,r){const a=new qGe,i=Math.ceil(n*a.sx),l=Math.ceil(r*a.sy),o=fe(this,Z5);if(!o||o.width===i&&o.height===l)return;o.width=i,o.height=l;const c=fe(this,Sw)?fe(this,cf):Xt(this,Id,D4e).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)},O4e=function(n){if(n){if(fe(this,Sw)){const i=this._uiManager.imageManager.getSvgUrl(fe(this,$y));if(i)return i}const r=document.createElement("canvas");return{width:r.width,height:r.height}=fe(this,cf),r.getContext("2d").drawImage(fe(this,cf),0,0),r.toDataURL()}if(fe(this,Sw)){const[r,a]=this.pageDimensions,i=Math.round(this.width*r*_P.PDF_TO_CSS_UNITS),l=Math.round(this.height*a*_P.PDF_TO_CSS_UNITS),o=new OffscreenCanvas(i,l);return o.getContext("2d").drawImage(fe(this,cf),0,0,fe(this,cf).width,fe(this,cf).height,0,0,i,l),o.transferToImageBitmap()}return structuredClone(fe(this,cf))},tJt=function(){this._uiManager._signal&&($t(this,aA,new ResizeObserver(n=>{const r=n[0].contentRect;r.width&&r.height&&Xt(this,Id,eJt).call(this,r.width,r.height)})),fe(this,aA).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var n;(n=fe(this,aA))==null||n.disconnect(),$t(this,aA,null)},{once:!0}))},sJt=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}},Lr(TJ,"_type","stamp"),Lr(TJ,"_editorType",Uc.STAMP);let HWe=TJ;var xF,bV,Q5,G6,iA,Cw,W6,_V,wV,Kv,oA,tl,K6,xv,nJt,YWe,ZWe,XWe,F4e;const hk=class hk{constructor({uiManager:t,pageIndex:n,div:r,structTreeLayer:a,accessibilityManager:i,annotationLayer:l,drawLayer:o,textLayer:c,viewport:d,l10n:u}){is(this,xv);is(this,xF);is(this,bV,!1);is(this,Q5,null);is(this,G6,null);is(this,iA,null);is(this,Cw,new Map);is(this,W6,!1);is(this,_V,!1);is(this,wV,!1);is(this,Kv,null);is(this,oA,null);is(this,tl);const h=[...fe(hk,K6).values()];if(!hk._initialized){hk._initialized=!0;for(const m of h)m.initialize(u,t)}t.registerEditorTypes(h),$t(this,tl,t),this.pageIndex=n,this.div=r,$t(this,xF,i),$t(this,Q5,l),this.viewport=d,$t(this,Kv,c),this.drawLayer=o,this._structTree=a,fe(this,tl).addLayer(this)}get isEmpty(){return fe(this,Cw).size===0}get isInvisible(){return this.isEmpty&&fe(this,tl).getMode()===Uc.NONE}updateToolbar(t){fe(this,tl).updateToolbar(t)}updateMode(t=fe(this,tl).getMode()){switch(Xt(this,xv,F4e).call(this),t){case Uc.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case Uc.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case Uc.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 fe(hk,K6).values())n.toggle(`${r._type}Editing`,t===r._editorType);this.div.hidden=!1}hasTextLayer(t){var n;return t===((n=fe(this,Kv))==null?void 0:n.div)}addInkEditorIfNeeded(t){if(fe(this,tl).getMode()!==Uc.INK)return;if(!t){for(const r of fe(this,Cw).values())if(r.isEmpty()){r.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}setEditingState(t){fe(this,tl).setEditingState(t)}addCommands(t){fe(this,tl).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=fe(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 fe(this,Cw).values())r.enableEditing(),r.show(!0),r.annotationElementId&&(fe(this,tl).removeChangedExistingAnnotation(r),t.add(r.annotationElementId));if(!fe(this,Q5))return;const n=fe(this,Q5).getEditableAnnotations();for(const r of n){if(r.hide(),fe(this,tl).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;$t(this,wV,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,n=new Map;for(const i of fe(this,Cw).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(fe(this,Q5)){const i=fe(this,Q5).getEditableAnnotations();for(const l of i){const{id:o}=l.data;if(fe(this,tl).isDeletedAnnotationElement(o))continue;let c=n.get(o);if(c){c.resetAnnotationElement(l),c.show(!1),l.show();continue}c=t.get(o),c&&(fe(this,tl).addChangedExistingAnnotation(c),c.renderAnnotationElement(l)&&c.show(!1)),l.show()}}Xt(this,xv,F4e).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:r}=this.div;for(const i of fe(hk,K6).values())r.remove(`${i._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),$t(this,wV,!1)}getEditableAnnotation(t){var n;return((n=fe(this,Q5))==null?void 0:n.getEditableAnnotation(t))||null}setActiveEditor(t){fe(this,tl).getActive()!==t&&fe(this,tl).setActiveEditor(t)}enableTextSelection(){var t;if(this.div.tabIndex=-1,(t=fe(this,Kv))!=null&&t.div&&!fe(this,oA)){$t(this,oA,new AbortController);const n=fe(this,tl).combinedSignal(fe(this,oA));fe(this,Kv).div.addEventListener("pointerdown",Xt(this,xv,nJt).bind(this),{signal:n}),fe(this,Kv).div.classList.add("highlighting")}}disableTextSelection(){var t;this.div.tabIndex=0,(t=fe(this,Kv))!=null&&t.div&&fe(this,oA)&&(fe(this,oA).abort(),$t(this,oA,null),fe(this,Kv).div.classList.remove("highlighting"))}enableClick(){if(fe(this,G6))return;$t(this,G6,new AbortController);const t=fe(this,tl).combinedSignal(fe(this,G6));this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t}),this.div.addEventListener("pointerup",this.pointerup.bind(this),{signal:t})}disableClick(){var t;(t=fe(this,G6))==null||t.abort(),$t(this,G6,null)}attach(t){fe(this,Cw).set(t.id,t);const{annotationElementId:n}=t;n&&fe(this,tl).isDeletedAnnotationElement(n)&&fe(this,tl).removeDeletedAnnotationElement(t)}detach(t){var n;fe(this,Cw).delete(t.id),(n=fe(this,xF))==null||n.removePointerInTextLayer(t.contentDiv),!fe(this,wV)&&t.annotationElementId&&fe(this,tl).addDeletedAnnotationElement(t)}remove(t){this.detach(t),fe(this,tl).removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1,fe(this,_V)||this.addInkEditorIfNeeded(!1)}changeParent(t){var n;t.parent!==this&&(t.parent&&t.annotationElementId&&(fe(this,tl).addDeletedAnnotationElement(t.annotationElementId),wh.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),fe(this,tl).addEditor(t),this.attach(t),!t.isAttachedToDOM){const n=t.render();this.div.append(n),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(),fe(this,tl).addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){var r;if(!t.isAttachedToDOM)return;const{activeElement:n}=document;t.div.contains(n)&&!fe(this,iA)&&(t._focusEventsAllowed=!1,$t(this,iA,setTimeout(()=>{$t(this,iA,null),t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:fe(this,tl)._signal}),n.focus())},0))),t._structTreeParentId=(r=fe(this,xF))==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 fe(this,tl).getId()}combinedSignal(t){return fe(this,tl).combinedSignal(t)}canCreateNewEmptyEditor(){var t;return(t=fe(this,xv,YWe))==null?void 0:t.canCreateNewEmptyEditor()}pasteEditor(t,n){fe(this,tl).updateToolbar(t),fe(this,tl).updateMode(t);const{offsetX:r,offsetY:a}=Xt(this,xv,XWe).call(this),i=this.getNextId(),l=Xt(this,xv,ZWe).call(this,{parent:this,id:i,x:r,y:a,uiManager:fe(this,tl),isCentered:!0,...n});l&&this.add(l)}async deserialize(t){var n;return await((n=fe(hk,K6).get(t.annotationType??t.annotationEditorType))==null?void 0:n.deserialize(t,this,fe(this,tl)))||null}createAndAddNewEditor(t,n,r={}){const a=this.getNextId(),i=Xt(this,xv,ZWe).call(this,{parent:this,id:a,x:t.offsetX,y:t.offsetY,uiManager:fe(this,tl),isCentered:n,...r});return i&&this.add(i),i}addNewEditor(){this.createAndAddNewEditor(Xt(this,xv,XWe).call(this),!0)}setSelected(t){fe(this,tl).setSelected(t)}toggleSelected(t){fe(this,tl).toggleSelected(t)}unselect(t){fe(this,tl).unselect(t)}pointerup(t){const{isMac:n}=fb.platform;if(!(t.button!==0||t.ctrlKey&&n)&&t.target===this.div&&fe(this,W6)){if($t(this,W6,!1),!fe(this,bV)){$t(this,bV,!0);return}if(fe(this,tl).getMode()===Uc.STAMP){fe(this,tl).unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(fe(this,tl).getMode()===Uc.HIGHLIGHT&&this.enableTextSelection(),fe(this,W6)){$t(this,W6,!1);return}const{isMac:n}=fb.platform;if(t.button!==0||t.ctrlKey&&n||t.target!==this.div)return;$t(this,W6,!0);const r=fe(this,tl).getActive();$t(this,bV,!r||r.isEmpty())}findNewParent(t,n,r){const a=fe(this,tl).findParent(n,r);return a===null||a===this?!1:(a.changeParent(t),!0)}destroy(){var t,n;((t=fe(this,tl).getActive())==null?void 0:t.parent)===this&&(fe(this,tl).commitOrRemove(),fe(this,tl).setActiveEditor(null)),fe(this,iA)&&(clearTimeout(fe(this,iA)),$t(this,iA,null));for(const r of fe(this,Cw).values())(n=fe(this,xF))==null||n.removePointerInTextLayer(r.contentDiv),r.setParent(null),r.isAttachedToDOM=!1,r.div.remove();this.div=null,fe(this,Cw).clear(),fe(this,tl).removeLayer(this)}render({viewport:t}){this.viewport=t,Q7(this.div,t);for(const n of fe(this,tl).getEditors(this.pageIndex))this.add(n),n.rebuild();this.updateMode()}update({viewport:t}){fe(this,tl).commitOrRemove(),Xt(this,xv,F4e).call(this);const n=this.viewport.rotation,r=t.rotation;if(this.viewport=t,Q7(this.div,{rotation:r}),n!==r)for(const a of fe(this,Cw).values())a.rotate(r);this.addInkEditorIfNeeded(!1)}get pageDimensions(){const{pageWidth:t,pageHeight:n}=this.viewport.rawDims;return[t,n]}get scale(){return fe(this,tl).viewParameters.realScale}};xF=new WeakMap,bV=new WeakMap,Q5=new WeakMap,G6=new WeakMap,iA=new WeakMap,Cw=new WeakMap,W6=new WeakMap,_V=new WeakMap,wV=new WeakMap,Kv=new WeakMap,oA=new WeakMap,tl=new WeakMap,K6=new WeakMap,xv=new WeakSet,nJt=function(t){fe(this,tl).unselectAll();const{target:n}=t;if(n===fe(this,Kv).div||(n.getAttribute("role")==="img"||n.classList.contains("endOfContent"))&&fe(this,Kv).div.contains(n)){const{isMac:r}=fb.platform;if(t.button!==0||t.ctrlKey&&r)return;fe(this,tl).showAllEditors("highlight",!0,!0),fe(this,Kv).div.classList.add("free"),this.toggleDrawing(),nTe.startHighlighting(this,fe(this,tl).direction==="ltr",{target:fe(this,Kv).div,x:t.x,y:t.y}),fe(this,Kv).div.addEventListener("pointerup",()=>{fe(this,Kv).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:fe(this,tl)._signal}),t.preventDefault()}},YWe=function(){return fe(hk,K6).get(fe(this,tl).getMode())},ZWe=function(t){const n=fe(this,xv,YWe);return n?new n.prototype.constructor(t):null},XWe=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}},F4e=function(){$t(this,_V,!0);for(const t of fe(this,Cw).values())t.isEmpty()&&t.remove();$t(this,_V,!1)},Lr(hk,"_initialized",!1),is(hk,K6,new Map([CWe,DWe,HWe,nTe].map(t=>[t._editorType,t])));let KWe=hk;var J5,xne,ox,lA,yne,JWe,l9,eKe,rJt;const By=class By{constructor({pageIndex:t}){is(this,l9);is(this,J5,null);is(this,xne,0);is(this,ox,new Map);is(this,lA,new Map);this.pageIndex=t}setParent(t){if(!fe(this,J5)){$t(this,J5,t);return}if(fe(this,J5)!==t){if(fe(this,ox).size>0)for(const n of fe(this,ox).values())n.remove(),t.append(n);$t(this,J5,t)}}static get _svgFactory(){return Yd(this,"_svgFactory",new Nnt)}draw(t,n,r,a=!1){const i=O0(this,xne)._++,l=Xt(this,l9,eKe).call(this,t.box);l.classList.add(...t.classNamesForDrawing);const o=By._svgFactory.createElement("defs");l.append(o);const c=By._svgFactory.createElement("path");o.append(c);const d=`path_p${this.pageIndex}_${i}`;c.setAttribute("id",d),c.setAttribute("d",t.toSVGPath()),a&&fe(this,lA).set(i,c);const u=Xt(this,l9,rJt).call(this,o,d),h=By._svgFactory.createElement("use");return l.append(h),l.setAttribute("fill",n),l.setAttribute("fill-opacity",r),h.setAttribute("href",`#${d}`),fe(this,ox).set(i,l),{id:i,clipPathId:`url(#${u})`}}drawOutline(t){const n=O0(this,xne)._++,r=Xt(this,l9,eKe).call(this,t.box);r.classList.add(...t.classNamesForOutlining);const a=By._svgFactory.createElement("defs");r.append(a);const i=By._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=By._svgFactory.createElement("mask");a.append(u),o=`mask_p${this.pageIndex}_${n}`,u.setAttribute("id",o),u.setAttribute("maskUnits","objectBoundingBox");const h=By._svgFactory.createElement("rect");u.append(h),h.setAttribute("width","1"),h.setAttribute("height","1"),h.setAttribute("fill","white");const m=By._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=By._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"),fe(this,ox).set(n,r),n}finalizeLine(t,n){const r=fe(this,lA).get(t);fe(this,lA).delete(t),this.updateBox(t,n.box),r.setAttribute("d",n.toSVGPath())}updateLine(t,n){fe(this,ox).get(t).firstChild.firstChild.setAttribute("d",n.toSVGPath())}updatePath(t,n){fe(this,lA).get(t).setAttribute("d",n.toSVGPath())}updateBox(t,n){var r;Xt(r=By,yne,JWe).call(r,fe(this,ox).get(t),n)}show(t,n){fe(this,ox).get(t).classList.toggle("hidden",!n)}rotate(t,n){fe(this,ox).get(t).setAttribute("data-main-rotation",n)}changeColor(t,n){fe(this,ox).get(t).setAttribute("fill",n)}changeOpacity(t,n){fe(this,ox).get(t).setAttribute("fill-opacity",n)}addClass(t,n){fe(this,ox).get(t).classList.add(n)}removeClass(t,n){fe(this,ox).get(t).classList.remove(n)}getSVGRoot(t){return fe(this,ox).get(t)}remove(t){fe(this,lA).delete(t),fe(this,J5)!==null&&(fe(this,ox).get(t).remove(),fe(this,ox).delete(t))}destroy(){$t(this,J5,null);for(const t of fe(this,ox).values())t.remove();fe(this,ox).clear(),fe(this,lA).clear()}};J5=new WeakMap,xne=new WeakMap,ox=new WeakMap,lA=new WeakMap,yne=new WeakSet,JWe=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}%`},l9=new WeakSet,eKe=function(t){var r;const n=By._svgFactory.create(1,1,!0);return fe(this,J5).append(n),n.setAttribute("aria-hidden",!0),Xt(r=By,yne,JWe).call(r,n,t),n},rJt=function(t,n){const r=By._svgFactory.createElement("clipPath");t.append(r);const a=`clip_${n}`;r.setAttribute("id",a),r.setAttribute("clipPathUnits","objectBoundingBox");const i=By._svgFactory.createElement("use");return r.append(i),i.setAttribute("href",`#${n}`),i.classList.add("clip"),a},is(By,yne);let QWe=By;yc.AbortException;yc.AnnotationEditorLayer;yc.AnnotationEditorParamsType;yc.AnnotationEditorType;yc.AnnotationEditorUIManager;yc.AnnotationLayer;yc.AnnotationMode;yc.ColorPicker;yc.DOMSVGFactory;yc.DrawLayer;yc.FeatureTest;var Snt=yc.GlobalWorkerOptions;yc.ImageKind;yc.InvalidPDFException;yc.MissingPDFException;yc.OPS;yc.OutputScale;yc.PDFDataRangeTransport;yc.PDFDateString;yc.PDFWorker;yc.PasswordResponses;yc.PermissionFlag;yc.PixelsPerInch;yc.RenderingCancelledException;yc.TextLayer;yc.UnexpectedResponseException;yc.Util;yc.VerbosityLevel;yc.XfaLayer;yc.build;yc.createValidAbsoluteUrl;yc.fetchData;var rTe=yc.getDocument;yc.getFilenameFromUrl;yc.getPdfFilenameFromUrl;yc.getXfaPageViewport;yc.isDataScheme;yc.isPdfFile;yc.noContextMenu;yc.normalizeUnicode;yc.setLayerDimensions;yc.shadow;yc.version;const Cnt="/assets/pdf.worker.min-GB3t0DcA.mjs";Snt.workerSrc=Cnt;const Sqn=({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 rTe({data:u}).promise;if(o)return;c.innerHTML="";for(let m=1;m<=h.numPages;m+=1){const p=await h.getPage(m);if(o)return;const f=p.getViewport({scale:t}),x=document.createElement("canvas");x.width=Math.floor(f.width),x.height=Math.floor(f.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 p.render({canvasContext:y,viewport:f}).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(Et,{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 q9({label:s,value:t,onChange:n,prefix:r="presentation",hint:a,urlPlaceholder:i="…or paste an image URL",round:l=!1,className:o}){const{user:c}=vs(),d=j.useRef(null),[u,h]=j.useState(!1),m=async p=>{if(!(!p||!c)){if(!p.type.startsWith("image/")){re.error("Please choose an image file");return}if(p.size>20*1024*1024){re.error("That photo is larger than 20 MB");return}h(!0);try{const f=await jBn(c.id,p,r);n(f),re.success("Photo uploaded")}catch(f){re.error((f==null?void 0:f.message)||"Upload failed")}finally{h(!1),d.current&&(d.current.value="")}}};return e.jsxs("div",{className:Mt("space-y-2",o),children:[e.jsx(te,{className:"text-xs",children:s}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Mt("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(pc,{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:p=>{var f;return m((f=p.target.files)==null?void 0:f[0])}}),e.jsxs(U,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:u,onClick:()=>{var p;return(p=d.current)==null?void 0:p.click()},children:[u?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(ly,{className:"h-4 w-4"}),t?"Replace photo":"Upload photo"]}),t&&e.jsxs(U,{type:"button",variant:"ghost",size:"sm",className:"gap-1 text-muted-foreground",onClick:()=>n(null),children:[e.jsx(er,{className:"h-4 w-4"})," Remove"]})]})]}),e.jsx(xe,{value:t||"",onChange:p=>n(p.target.value||null),placeholder:i}),a&&e.jsx("p",{className:"text-xs text-muted-foreground",children:a})]})}function Cqn({value:s,onChange:t}){return e.jsxs(we,{children:[e.jsxs(Tt,{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(Bn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(It,{className:"text-base",children:"Co-listing agent"})]}),e.jsx(wn,{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(te,{children:"Name"}),e.jsx(xe,{value:s.name,onChange:n=>t({name:n.target.value}),placeholder:"Jordan Ellis"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Title"}),e.jsx(xe,{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(te,{children:"Phone"}),e.jsx(xe,{value:s.phone||"",onChange:n=>t({phone:n.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Email"}),e.jsx(xe,{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(te,{children:"Brokerage"}),e.jsx(xe,{value:s.brokerageName||"",onChange:n=>t({brokerageName:n.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"License #"}),e.jsx(xe,{value:s.licenseNumber||"",onChange:n=>t({licenseNumber:n.target.value})})]})]}),e.jsx(q9,{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(te,{children:"Shared bio (optional)"}),e.jsx(Fs,{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 Aqn({value:s,onChange:t}){return e.jsxs(we,{children:[e.jsxs(Tt,{className:"pb-3",children:[e.jsx(It,{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:OGe.map(n=>{const r=n.id===s;return e.jsxs("button",{type:"button",onClick:()=>t(n.id),className:Mt("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(Xr,{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 Eqn={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}]},Tqn=["cover","welcome","agent","overview","closing"];function Mqn({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(we,{children:[e.jsxs(Tt,{className:"pb-3",children:[e.jsx(It,{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(y9,{type:"multiple",className:"w-full",children:Tqn.filter(i=>i==="cover"||!n.has(i)).map(i=>{const l=EYt(s,i);return e.jsxs(WP,{value:i,children:[e.jsx(KP,{className:"text-sm",children:POn[i]}),e.jsxs(YP,{className:"space-y-3 pt-1",children:[Eqn[i].map(o=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:o.label}),o.long?e.jsx(Fs,{rows:2,value:l[o.key]||"",placeholder:gGe[i][o.key],onChange:c=>r(i,o.key,c.target.value)}):e.jsx(xe,{value:l[o.key]||"",placeholder:gGe[i][o.key],onChange:c=>r(i,o.key,c.target.value)})]},o.key)),e.jsxs(U,{variant:"ghost",size:"sm",className:"gap-2",onClick:()=>a(i),children:[e.jsx(Kg,{className:"h-3.5 w-3.5"})," Reset to default wording"]})]})]},i)})})})]})}function Pqn({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,Zst(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,p)=>({...m,order:p})))};return e.jsxs(we,{children:[e.jsxs(Tt,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ej,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(It,{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:i9e.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(an,{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(hc,{}),e.jsx(y9,{type:"multiple",className:"w-full",children:n.map((o,c)=>{var d,u,h;return e.jsxs(WP,{value:o.id,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wn,{checked:o.enabled,onCheckedChange:m=>r(o.id,{enabled:m})}),e.jsx(KP,{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=i9e.find(m=>m.layout===o.layout))==null?void 0:u.name),e.jsx(Be,{variant:"secondary",className:"text-[10px]",children:(h=i9e.find(m=>m.layout===o.layout))==null?void 0:h.name})]})}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:c===0,onClick:()=>l(o.id,-1),children:e.jsx(cp,{className:"h-3.5 w-3.5"})}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:c===n.length-1,onClick:()=>l(o.id,1),children:e.jsx(ag,{className:"h-3.5 w-3.5"})}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>i(o.id),children:e.jsx(In,{className:"h-3.5 w-3.5"})})]}),e.jsxs(YP,{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(te,{className:"text-xs",children:"Placement"}),e.jsxs(Ns,{value:o.placement,onValueChange:m=>r(o.id,{placement:m}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"after-agent",children:'After "About your agent"'}),e.jsx(et,{value:"end",children:"Before the closing page"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Style"}),e.jsxs("div",{className:"flex h-10 items-center gap-2 rounded-md border px-3",children:[e.jsx(wn,{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(te,{className:"text-xs",children:"Eyebrow"}),e.jsx(xe,{value:o.kicker,onChange:m=>r(o.id,{kicker:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Headline"}),e.jsx(xe,{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(te,{className:"text-xs",children:"Subhead"}),e.jsx(xe,{value:o.subhead,onChange:m=>r(o.id,{subhead:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Body copy"}),e.jsx(Fs,{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(q9,{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(te,{className:"text-xs",children:"Photo side"}),e.jsxs(Ns,{value:o.imageSide,onValueChange:m=>r(o.id,{imageSide:m}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"right",children:"Right"}),e.jsx(et,{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(te,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"List items"}),o.bullets.map((m,p)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{value:m,onChange:f=>{const x=[...o.bullets];x[p]=f.target.value,r(o.id,{bullets:x})}}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>r(o.id,{bullets:o.bullets.filter((f,x)=>x!==p)}),children:e.jsx(In,{className:"h-3.5 w-3.5"})})]},p)),e.jsxs(U,{variant:"outline",size:"sm",className:"gap-2",disabled:o.bullets.length>=7,onClick:()=>r(o.id,{bullets:[...o.bullets,""]}),children:[e.jsx(an,{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(te,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Testimonials (up to 4)"}),o.testimonials.map((m,p)=>e.jsxs("div",{className:"space-y-2 rounded-md border bg-background p-3",children:[e.jsx(Fs,{rows:3,value:m.quote,placeholder:"Client quote",onChange:f=>{const x=[...o.testimonials];x[p]={...m,quote:f.target.value},r(o.id,{testimonials:x})}}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(xe,{value:m.name,placeholder:"Name",onChange:f=>{const x=[...o.testimonials];x[p]={...m,name:f.target.value},r(o.id,{testimonials:x})}}),e.jsx(xe,{value:m.detail,placeholder:"Neighborhood or year",onChange:f=>{const x=[...o.testimonials];x[p]={...m,detail:f.target.value},r(o.id,{testimonials:x})}})]}),e.jsxs(U,{variant:"ghost",size:"sm",className:"gap-2 text-destructive",onClick:()=>r(o.id,{testimonials:o.testimonials.filter((f,x)=>x!==p)}),children:[e.jsx(In,{className:"h-3.5 w-3.5"})," Remove"]})]},p)),e.jsxs(U,{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(an,{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(te,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Stats (up to 4)"}),o.stats.map((m,p)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{className:"w-28",value:m.value,placeholder:"27",onChange:f=>{const x=[...o.stats];x[p]={...m,value:f.target.value},r(o.id,{stats:x})}}),e.jsx(xe,{value:m.label,placeholder:"Homes sold",onChange:f=>{const x=[...o.stats];x[p]={...m,label:f.target.value},r(o.id,{stats:x})}}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>r(o.id,{stats:o.stats.filter((f,x)=>x!==p)}),children:e.jsx(In,{className:"h-3.5 w-3.5"})})]},p)),e.jsxs(U,{variant:"outline",size:"sm",className:"gap-2",disabled:o.stats.length>=4,onClick:()=>r(o.id,{stats:[...o.stats,{value:"",label:""}]}),children:[e.jsx(an,{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 Lqn({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(Ds,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{children:"Template name"}),e.jsx(xe,{value:i,onChange:d=>l(d.target.value),autoFocus:!0})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Notes (optional)"}),e.jsx(Fs,{rows:2,value:o,onChange:d=>c(d.target.value),placeholder:"Luxury version with co-listing agent and testimonials"})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{disabled:!i.trim()||r,onClick:async()=>{await a(i.trim(),o.trim()),t(!1)},className:"gap-2",children:[r&&e.jsx(Et,{className:"h-4 w-4 animate-spin"})," Save template"]})]})]})})}const qNt=["welcome","agent","overview","closing"],Iqn=()=>{const{id:s}=Di(),t=Wn(),{user:n}=vs(),{data:r}=AYt(),{data:a,isLoading:i,refetch:l}=AOn(s),{update:o}=CYt(),{save:c}=SYt(),[d,u]=j.useState(null),[h,m]=j.useState(null),[p,f]=j.useState(vGe(null)),[x,y]=j.useState(TYt),[v,b]=j.useState([]),[N,S]=j.useState(xGe),[A,T]=j.useState(yGe),[L,M]=j.useState(null),[I,R]=j.useState(null),[z,$]=j.useState(!1),[H,V]=j.useState(!1),[K,Z]=j.useState(null),[Q,le]=j.useState(!1),[ue,se]=j.useState(!1),[ne,ie]=j.useState(!1),[ce,je]=j.useState(!1),[be,he]=j.useState(!0),[ge,ke]=j.useState(!1),Te=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 Ue=a.agent_snapshot;m({...r,...Ue||{}}),f(vGe(a.services)),y(MYt(a.co_agent)),b(LYt(a.custom_pages)),S(a.page_settings&&Object.keys(a.page_settings).length?a.page_settings:xGe),T(a.photo_focal||yGe),M(a.property_photo_path)},[a,r,d]),j.useEffect(()=>{let Ue=!1;return L?XEe(L).then(Ye=>{Ue||R(Ye)}):R(null),()=>{Ue=!0}},[L]);const Me=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:p,page_settings:N,photo_focal:A,property_photo_path:L},[a,d,h,x,v,p,N,A,L]),Oe=Ue=>u(Ye=>Ye&&{...Ye,...Ue}),Se=Ue=>m(Ye=>Ye&&{...Ye,...Ue}),Qe=Ue=>(N.hidden||[]).includes(Ue),Ae=(Ue,Ye)=>S(Ge=>{const He=new Set(Ge.hidden||[]);return Ye?He.delete(Ue):He.add(Ue),{...Ge,hidden:Array.from(He)}}),Fe=p.filter(Ue=>Ue.enabled),Ne=1+qNt.filter(Ue=>!Qe(Ue)&&Ue!=="overview").length+(Qe("overview")?0:1)+Fe.filter(Ue=>Ue.key!=="communication").length+v.filter(Ue=>Ue.enabled).length,$e=async(Ue=!1)=>{if(Me){je(!0);try{await o.mutateAsync({id:Me.id,title:Me.title||"Untitled Presentation",property_address_line1:Me.property_address_line1,city:Me.city,state:Me.state,postal_code:Me.postal_code,list_price:Me.list_price,beds:Me.beds,baths:Me.baths,sqft:Me.sqft,agent_snapshot:Me.agent_snapshot,co_agent:Me.co_agent,custom_pages:Me.custom_pages,services:Me.services,page_settings:Me.page_settings,photo_focal:Me.photo_focal,property_photo_path:Me.property_photo_path}),Ue||re.success("Presentation saved")}finally{je(!1)}}},Ve=async Ue=>{if(!(!n||!s)){if(!Ue.type.startsWith("image/")){re.error("Please choose a JPG or PNG photo");return}if(Ue.size>25*1024*1024){re.error("That photo is larger than 25 MB");return}$(!0);try{const Ye=await wBn(n.id,s,Ue);M(Ye);const Ge=await XEe(Ye);R(Ge?`${Ge}${Ge.includes("?")?"&":"?"}v=${Date.now()}`:null),await o.mutateAsync({id:s,property_photo_path:Ye}),re.success("Photo uploaded")}catch(Ye){re.error((Ye==null?void 0:Ye.message)||"Upload failed")}finally{$(!1)}}},qe=async()=>{if(Me){le(!0);try{const Ue=await ZZt(QEe(Me,r,I),Me.template_id,L);Z(Ue)}catch(Ue){re.error((Ue==null?void 0:Ue.message)||"Could not build the preview")}finally{le(!1)}}};j.useEffect(()=>{if(!be||!Me)return;const Ue=setTimeout(()=>{qe()},900);return()=>clearTimeout(Ue)},[be,Me]);const Ze=async()=>{if(!(!Me||!n)){if(!Me.property_photo_path){re.error("Add the primary exterior photo before generating the PDF");return}se(!0);try{await $e(!0);const Ue=await XZt(QEe(Me,r,I),Me.template_id,"print",L);await QZt(n.id,Me.id,Ue),await l(),re.success("Presentation downloaded")}catch(Ue){re.error((Ue==null?void 0:Ue.message)||"Could not build the PDF")}finally{se(!1)}}};return i||!d||!a?e.jsx(qs,{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(qs,{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(U,{variant:"ghost",size:"icon",onClick:()=>t("/apps/listing-presentation-studio"),children:e.jsx(Aa,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx(xe,{value:d.title,onChange:Ue=>Oe({title:Ue.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:[Fe.length," services selected · ",Ne," pages"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(U,{variant:"outline",onClick:()=>$e(),disabled:ce,className:"gap-2",children:[ce?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4"})," Save"]}),e.jsxs(U,{variant:"outline",onClick:()=>ke(!0),className:"gap-2",children:[e.jsx(NM,{className:"h-4 w-4"})," Save as template"]}),e.jsxs(U,{variant:"outline",onClick:qe,disabled:Q,className:"gap-2",children:[Q?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(xa,{className:"h-4 w-4"})," Preview"]}),e.jsxs(U,{variant:"outline",onClick:async()=>{await $e(!0),ie(!0)},className:"gap-2",children:[e.jsx(ln,{className:"h-4 w-4"})," Email"]}),e.jsxs(U,{onClick:Ze,disabled:ue,className:"gap-2",children:[ue?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(pi,{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(oa,{defaultValue:"property",className:"space-y-4",children:[e.jsxs(la,{className:"grid w-full grid-cols-4",children:[e.jsx(Kt,{value:"property",children:"Property"}),e.jsx(Kt,{value:"branding",children:"Branding"}),e.jsx(Kt,{value:"plan",children:"Plan"}),e.jsx(Kt,{value:"pages",children:"Pages"})]}),e.jsxs(Zt,{value:"property",className:"space-y-4",children:[e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsx(It,{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(te,{children:"Street address"}),e.jsx(xe,{value:d.addressLine1,onChange:Ue=>Oe({addressLine1:Ue.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(te,{children:"City"}),e.jsx(xe,{value:d.city,onChange:Ue=>Oe({city:Ue.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"State"}),e.jsx(xe,{value:d.state,onChange:Ue=>Oe({state:Ue.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"ZIP"}),e.jsx(xe,{value:d.postalCode,onChange:Ue=>Oe({postalCode:Ue.target.value})})]}),e.jsx(hc,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"List price (optional)"}),e.jsx(xe,{inputMode:"numeric",value:d.listPrice,onChange:Ue=>Oe({listPrice:Ue.target.value.replace(/[^0-9.]/g,"")}),placeholder:"649000"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Square feet"}),e.jsx(xe,{inputMode:"numeric",value:d.sqft,onChange:Ue=>Oe({sqft:Ue.target.value.replace(/[^0-9]/g,"")})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Beds"}),e.jsx(xe,{inputMode:"numeric",value:d.beds,onChange:Ue=>Oe({beds:Ue.target.value.replace(/[^0-9.]/g,"")})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Baths"}),e.jsx(xe,{inputMode:"numeric",value:d.baths,onChange:Ue=>Oe({baths:Ue.target.value.replace(/[^0-9.]/g,"")})})]})]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs(It,{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 Ue;return(Ue=Te.current)==null?void 0:Ue.click()},onKeyDown:Ue=>{var Ye;return Ue.key==="Enter"&&((Ye=Te.current)==null?void 0:Ye.click())},onDragOver:Ue=>{Ue.preventDefault(),V(!0)},onDragLeave:()=>V(!1),onDrop:Ue=>{var Ge;Ue.preventDefault(),V(!1);const Ye=(Ge=Ue.dataTransfer.files)==null?void 0:Ge[0];Ye&&Ve(Ye)},className:Mt("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",H&&"border-primary bg-primary/10"),children:I?e.jsx("img",{src:I,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:[z?e.jsx(Et,{className:"h-6 w-6 animate-spin"}):e.jsx(ly,{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:Te,type:"file",accept:"image/*",className:"hidden",onChange:Ue=>{var Ge;const Ye=(Ge=Ue.target.files)==null?void 0:Ge[0];Ye&&Ve(Ye),Ue.target.value=""}}),I&&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(eQ,{className:"h-3.5 w-3.5"})," Reposition crop"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Horizontal"}),e.jsx(rg,{value:[A.x*100],min:0,max:100,step:1,onValueChange:([Ue])=>T(Ye=>({...Ye,x:Ue/100}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Vertical"}),e.jsx(rg,{value:[A.y*100],min:0,max:100,step:1,onValueChange:([Ue])=>T(Ye=>({...Ye,y:Ue/100}))})]})]}),e.jsxs(U,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:()=>{var Ue;return(Ue=Te.current)==null?void 0:Ue.click()},disabled:z,children:[e.jsx(no,{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(Zt,{value:"branding",className:"space-y-4",children:[e.jsx(Aqn,{value:N.theme||Fzn,onChange:Ue=>S(Ye=>({...Ye,theme:Ue}))}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(It,{className:"text-base",children:"Your details"}),e.jsx(Be,{variant:"secondary",className:"text-[10px]",children:"Loaded from your LevelUp profile"})]})}),e.jsx(Ie,{className:"space-y-3",children:h&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Edits here apply to this presentation only — your LevelUp profile stays unchanged."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Name"}),e.jsx(xe,{value:h.name,onChange:Ue=>Se({name:Ue.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Tagline"}),e.jsx(xe,{value:h.tagline||"",onChange:Ue=>Se({tagline:Ue.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(te,{children:"Phone"}),e.jsx(xe,{value:h.phone||"",onChange:Ue=>Se({phone:Ue.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Email"}),e.jsx(xe,{value:h.email||"",onChange:Ue=>Se({email:Ue.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Website"}),e.jsx(xe,{value:h.website||"",onChange:Ue=>Se({website:Ue.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Brokerage"}),e.jsx(xe,{value:h.brokerageName||"",onChange:Ue=>Se({brokerageName:Ue.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"License #"}),e.jsx(xe,{value:h.licenseNumber||"",onChange:Ue=>Se({licenseNumber:Ue.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"License state"}),e.jsx(xe,{value:h.licenseState||"",onChange:Ue=>Se({licenseState:Ue.target.value})})]})]}),e.jsx(hc,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Primary color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.brandColor,onChange:Ue=>Se({brandColor:Ue.target.value}),className:"h-9 w-12 cursor-pointer rounded border bg-transparent"}),e.jsx(xe,{value:h.brandColor,onChange:Ue=>Se({brandColor:Ue.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Accent color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.accentColor,onChange:Ue=>Se({accentColor:Ue.target.value}),className:"h-9 w-12 cursor-pointer rounded border bg-transparent"}),e.jsx(xe,{value:h.accentColor,onChange:Ue=>Se({accentColor:Ue.target.value})})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Headshot URL"}),e.jsx(xe,{value:h.headshotUrl||"",onChange:Ue=>Se({headshotUrl:Ue.target.value}),placeholder:"Pulled from your profile photo"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Brokerage logo URL"}),e.jsx(xe,{value:h.brokerageLogoUrl||"",onChange:Ue=>Se({brokerageLogoUrl:Ue.target.value})})]}),r&&e.jsxs(U,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:()=>m({...r}),children:[e.jsx(no,{className:"h-4 w-4"})," Reset to my LevelUp profile"]})]})})]}),e.jsx(Cqn,{value:x,onChange:Ue=>y(Ye=>({...Ye,...Ue}))})]}),e.jsx(Zt,{value:"plan",className:"space-y-4",children:e.jsxs(we,{children:[e.jsxs(Tt,{className:"pb-3",children:[e.jsx(It,{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(y9,{type:"multiple",className:"w-full",children:p.slice().sort((Ue,Ye)=>Ue.order-Ye.order).map(Ue=>{var Ye;return e.jsxs(WP,{value:Ue.key,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(wn,{checked:Ue.enabled,onCheckedChange:Ge=>f(He=>He.map(tt=>tt.key===Ue.key?{...tt,enabled:Ge}:tt))}),e.jsx(KP,{className:"flex-1 text-left text-sm",children:Ue.title})]}),e.jsxs(YP,{className:"space-y-3 pt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Headline"}),e.jsx(xe,{value:Ue.title,onChange:Ge=>f(He=>He.map(tt=>tt.key===Ue.key?{...tt,title:Ge.target.value}:tt))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Description"}),e.jsx(Fs,{rows:4,value:Ue.body,onChange:Ge=>f(He=>He.map(tt=>tt.key===Ue.key?{...tt,body:Ge.target.value}:tt))})]}),!!((Ye=Ue.options)!=null&&Ye.length)&&e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/30 p-3",children:[e.jsx(te,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Included in this page"}),Ue.options.map(Ge=>e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx(xi,{className:"mt-0.5",checked:Ge.enabled,onCheckedChange:He=>f(tt=>tt.map(pt=>{var ft;return pt.key===Ue.key?{...pt,options:(ft=pt.options)==null?void 0:ft.map(qt=>qt.key===Ge.key?{...qt,enabled:!!He}:qt)}:pt}))}),e.jsx("span",{className:"leading-snug",children:Ge.label})]},Ge.key))]})]})]},Ue.key)})})})]})}),e.jsxs(Zt,{value:"pages",className:"space-y-4",children:[e.jsxs(we,{children:[e.jsxs(Tt,{className:"pb-3",children:[e.jsx(It,{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:[qNt.map(Ue=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx("span",{className:"text-sm",children:IOn[Ue]}),e.jsx(wn,{checked:!Qe(Ue),onCheckedChange:Ye=>Ae(Ue,Ye)})]},Ue)),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"}),!Qe("welcome")&&e.jsx("li",{children:"Marketing commitment"}),!Qe("agent")&&e.jsx("li",{children:"About your agent"}),v.filter(Ue=>Ue.enabled&&Ue.placement!=="end").sort((Ue,Ye)=>Ue.order-Ye.order).map(Ue=>e.jsx("li",{children:Ue.headline||"Custom page"},Ue.id)),!Qe("overview")&&e.jsx("li",{children:"Marketing plan overview"}),Fe.filter(Ue=>Ue.key!=="communication").map(Ue=>e.jsx("li",{children:Ue.title},Ue.key)),v.filter(Ue=>Ue.enabled&&Ue.placement==="end").sort((Ue,Ye)=>Ue.order-Ye.order).map(Ue=>e.jsx("li",{children:Ue.headline||"Custom page"},Ue.id)),!Qe("closing")&&e.jsx("li",{children:"Communication & closing commitment"})]})]})]})]}),e.jsx(Mqn,{pages:N,onChange:S}),e.jsxs(we,{children:[e.jsxs(Tt,{className:"pb-3",children:[e.jsx(It,{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(U,{variant:"outline",size:"sm",className:"w-full",onClick:()=>b(Ue=>[...Ue,{...Zst("testimonials",Ue.length),placement:"end"}]),children:`Add a "What they're saying" page`})})]}),e.jsx(Pqn,{pages:v,onChange:b})]})]}),e.jsxs(we,{className:"min-h-[70vh] overflow-hidden",children:[e.jsxs(Tt,{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(It,{className:"text-base",children:"Live preview"}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(wn,{checked:be,onCheckedChange:he}),"Auto-update"]})]}),e.jsxs(U,{variant:"ghost",size:"sm",onClick:qe,disabled:Q,className:"gap-2",children:[Q?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(no,{className:"h-4 w-4"}),"Refresh"]})]}),e.jsx(Ie,{className:"h-[calc(70vh-60px)] p-0",children:K?e.jsx(Sqn,{blob:K}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 bg-muted/30 text-center",children:[e.jsx(xa,{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(U,{onClick:qe,disabled:Q,className:"gap-2",children:[Q?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(xa,{className:"h-4 w-4"}),"Generate preview"]})]})})]})]})]}),e.jsx(Lqn,{open:ge,onOpenChange:ke,defaultName:d.title,saving:c.isPending,onSave:async(Ue,Ye)=>{await c.mutateAsync({name:Ue,description:Ye||null,template_id:a.template_id,agent_snapshot:h||{},co_agent:x,custom_pages:v,services:p,page_settings:N})}}),e.jsx(eXt,{open:ne,onOpenChange:ie,row:Me,brand:r,photoUrl:I})]})};function Rqn(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 aJt="popby_geocode_cache_v1";function Dqn(){try{return JSON.parse(localStorage.getItem(aJt)||"{}")}catch{return{}}}function Oqn(s){try{localStorage.setItem(aJt,JSON.stringify(s))}catch{}}function Fqn({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,p]=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 f=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||f.length===0)return;let b=!1;const N=Dqn(),S=new Map;f.forEach(T=>{const L=[T.address,T.city,T.state,T.zip].filter(Boolean).join("|").toLowerCase();N[L]&&S.set(T.id,N[L])}),h(new Map(S));const A=f.filter(T=>!([T.address,T.city,T.state,T.zip].filter(Boolean).join("|").toLowerCase()in N));if(A.length!==0)return p(!0),(async()=>{const T=[...A],L=async()=>{var M,I;for(;T.length&&!b;){const R=T.shift(),z=[R.address,R.city,R.state,R.zip].filter(Boolean),$=z.join("|").toLowerCase(),H=z.join(", ");try{const K=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(H)}.json?limit=1&access_token=${c}`)).json();if((I=(M=K==null?void 0:K.features)==null?void 0:M[0])!=null&&I.center){const[Z,Q]=K.features[0].center;N[$]={lat:Q,lng:Z},S.set(R.id,{lat:Q,lng:Z})}else N[$]=null}catch{}}};await Promise.all([L(),L(),L(),L()]),b||(Oqn(N),h(new Map(S)),p(!1))})(),()=>{b=!0}},[c,n,f]);const y=j.useMemo(()=>{if(!n)return[];const b=[];return f.forEach(N=>{const S=u.get(N.id);if(!S)return;const A=Rqn(n.lat,n.lng,S.lat,S.lng);A<=l&&b.push({...N,distanceMiles:A,lat:S.lat,lng:S.lng})}),b.sort((N,S)=>N.distanceMiles-S.distanceMiles)},[n,f,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(we,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2 text-lg",children:[e.jsx(nq,{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(Ns,{value:String(l),onValueChange:b=>o(Number(b)),children:[e.jsx(ws,{className:"w-[110px] h-9",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"2",children:"2 miles"}),e.jsx(et,{value:"5",children:"5 miles"}),e.jsx(et,{value:"10",children:"10 miles"}),e.jsx(et,{value:"25",children:"25 miles"})]})]}),e.jsxs(U,{size:"sm",variant:a==="ok"?"outline":"default",onClick:x,disabled:a==="loading",children:[a==="loading"?e.jsx(no,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(nq,{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(ni,{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(Vo,{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&&f.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&&f.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&&f.length>0&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:["No due contacts within ",l," miles. Try widening the radius."]}),y.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Be,{variant:"secondary",className:"font-medium",children:[y.length," nearby"]}),m&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(no,{className:"h-3 w-3 animate-spin"})," still locating…"]})]}),e.jsx("div",{className:"space-y-2",children:y.map(b=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg bg-card border hover:border-primary/40 transition-colors",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"font-medium truncate",children:[b.first_name," ",b.last_name]}),e.jsx(Be,{variant:"outline",className:"text-xs",children:b.distanceMiles<1?`${(b.distanceMiles*5280).toFixed(0)} ft`:`${b.distanceMiles.toFixed(1)} mi`}),b.daysOverdue>0&&e.jsxs(Be,{variant:"destructive",className:"text-xs",children:[b.daysOverdue,"d overdue"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:[b.address,b.city,b.state].filter(Boolean).join(", ")})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[b.phone&&e.jsx(U,{size:"icon",variant:"ghost",asChild:!0,className:"h-9 w-9",title:"Call",children:e.jsx("a",{href:`tel:${b.phone}`,children:e.jsx(ba,{className:"h-4 w-4"})})}),e.jsx(U,{size:"icon",variant:"ghost",onClick:()=>v(b),className:"h-9 w-9",title:"Directions",children:e.jsx(tQ,{className:"h-4 w-4"})}),e.jsxs(U,{size:"sm",onClick:()=>t(b),children:[e.jsx(Ro,{className:"h-4 w-4 mr-1"}),"Log"]})]})]},b.id))})]})]})]})}const zqn="0dde5abb-0005-4c8c-a471-30d0cbc9e280",Bqn=[{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 Uqn(){const s=Wn(),t=ZGt(),{data:n}=HLn(),{data:r}=F_(),{data:a}=Ztt(),{data:i}=qLe(90),{data:l}=Cb(),o=ZLn(),c=KLn(),d=WLn(),u=YLn(),{data:h=[],isLoading:m}=ct({queryKey:["popby-templates"],queryFn:async()=>{const{data:K,error:Z}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("category_id",zqn).order("publish_date",{ascending:!1});if(Z)throw Z;const{data:Q}=await q.from("template_likes").select("template_id"),{data:le}=await q.from("template_comments").select("template_id"),ue=new Map;Q==null||Q.forEach(ne=>{ue.set(ne.template_id,(ue.get(ne.template_id)||0)+1)});const se=new Map;return le==null||le.forEach(ne=>{se.set(ne.template_id,(se.get(ne.template_id)||0)+1)}),(K||[]).map(ne=>({...ne,likesCount:ue.get(ne.id)||0,commentsCount:se.get(ne.id)||0}))}}),p=K=>{const Z=l==null?void 0:l.find(Q=>Q.id===K);return Z?`${Z.first_name} ${Z.last_name||""}`.trim():"Unknown"},f=K=>{if(!K)return null;const Z=n==null?void 0:n.find(Q=>Q.id===K);return(Z==null?void 0:Z.name)||null},[x,y]=j.useState(null),[v,b]=j.useState(!1),[N,S]=j.useState(!1),[A,T]=j.useState(!1),[L,M]=j.useState({popby_item_id:"",notes:""}),[I,R]=j.useState({name:"",description:""}),z=async()=>{x&&(await c.mutateAsync({contact_id:x.id,popby_item_id:L.popby_item_id||void 0,notes:L.notes||void 0}),b(!1),y(null),M({popby_item_id:"",notes:""}))},$=async()=>{I.name.trim()&&(await d.mutateAsync({name:I.name.trim(),description:I.description.trim()||void 0}),T(!1),R({name:"",description:""}))},H=async(K,Z)=>{await u.mutateAsync({relationship_type_id:K,frequency_days:parseInt(Z)})},V=K=>{var Q;const Z=a==null?void 0:a.find(le=>le.relationship_type_id===K);return((Q=Z==null?void 0:Z.frequency_days)==null?void 0:Q.toString())||"90"};return e.jsx(qs,{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(we,{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(we,{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(we,{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(U,{onClick:()=>s("/mission-control/popbys/map"),children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"View Map"]}),e.jsxs(U,{variant:"outline",onClick:()=>S(!0),children:[e.jsx(qc,{className:"h-4 w-4 mr-2"}),"Frequency Settings"]}),e.jsxs(U,{variant:"outline",onClick:()=>T(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsxs(oa,{defaultValue:"due",children:[e.jsxs(la,{children:[e.jsx(Kt,{value:"due",children:"Due for Popby"}),e.jsx(Kt,{value:"activity",children:"Recent Activity"}),e.jsx(Kt,{value:"library",children:"Popby Library"}),e.jsx(Kt,{value:"templates",children:"Popby Templates"})]}),e.jsxs(Zt,{value:"due",className:"space-y-4 mt-4",children:[e.jsx(Fqn,{contacts:t||[],onLogPopby:K=>{y(K),b(!0)}}),!t||t.length===0?e.jsx(we,{children:e.jsxs(Ie,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Ro,{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(K=>e.jsx(we,{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:[K.first_name," ",K.last_name]}),K.daysOverdue>0&&e.jsxs(Be,{variant:"destructive",className:"text-xs",children:[K.daysOverdue,"+ days overdue"]}),K.daysSinceLastPopby===null&&e.jsx(Be,{variant:"outline",className:"text-xs",children:"Never visited"})]}),e.jsxs("div",{className:"flex items-center gap-4 mt-1 text-sm text-muted-foreground",children:[K.address&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ni,{className:"h-3 w-3"}),K.city||K.address]}),K.tags&&K.tags.length>0&&e.jsx("span",{children:K.tags.map(Z=>{var Q;return(Q=Z.relationship_type)==null?void 0:Q.name}).join(", ")})]}),K.lastPopby&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Last popby: ",Gs(new Date(K.lastPopby),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[K.phone&&e.jsx(U,{size:"sm",variant:"ghost",asChild:!0,children:e.jsx("a",{href:`tel:${K.phone}`,children:e.jsx(ba,{className:"h-4 w-4"})})}),e.jsxs(U,{size:"sm",onClick:()=>{y(K),b(!0)},children:[e.jsx(Yo,{className:"h-4 w-4 mr-1"}),"Log Popby"]})]})]})})},K.id))})]}),e.jsx(Zt,{value:"activity",className:"space-y-4 mt-4",children:!i||i.length===0?e.jsx(we,{children:e.jsxs(Ie,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Yr,{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(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-lg",children:"Recent Popby Log"})}),e.jsx(Ie,{className:"space-y-3",children:i.map(K=>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(Ro,{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:p(K.contact_id)}),f(K.popby_item_id)&&e.jsx(Be,{variant:"secondary",className:"text-xs",children:f(K.popby_item_id)})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Gs(new Date(K.completed_at),"MMM d, yyyy h:mm a")}),K.notes&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:K.notes})]})]},K.id))})]})}),e.jsx(Zt,{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(K=>e.jsx(we,{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(Ro,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-medium",children:K.name}),K.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:K.description}),!K.owner_user_id&&e.jsx(Be,{variant:"secondary",className:"mt-2 text-xs",children:"Shared"})]})]})})},K.id)),e.jsx(we,{className:"border-dashed cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>T(!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(an,{className:"h-8 w-8 mx-auto mb-2"}),e.jsx("p",{children:"Add New Popby Idea"})]})})})]})}),e.jsxs(Zt,{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((K,Z)=>e.jsx(we,{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"})]})]})},Z))}),!m&&h.length===0&&e.jsx(we,{children:e.jsxs(Ie,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(dh,{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(K=>e.jsxs(we,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer",onClick:()=>s(`/templates/${K.id}`),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:K.preview_image_url?e.jsx("img",{src:K.preview_image_url,alt:K.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:K.name}),K.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:KJ(K.description)}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:e.jsx(Be,{variant:"secondary",className:"text-xs",children:"PopBys"})}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground mb-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(wx,{className:"h-3.5 w-3.5"}),K.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(vu,{className:"h-3.5 w-3.5"}),K.commentsCount]})]}),e.jsxs(U,{size:"sm",className:"w-full gap-2",onClick:Z=>{Z.stopPropagation(),s(`/templates/${K.id}`)},children:[e.jsx(Sr,{className:"h-4 w-4"}),"View Template"]})]})]},K.id))})]})]}),e.jsx(zs,{open:v,onOpenChange:b,children:e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsxs($s,{children:["Log Popby for ",x==null?void 0:x.first_name," ",x==null?void 0:x.last_name]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Popby Item (optional)"}),e.jsxs(Ns,{value:L.popby_item_id,onValueChange:K=>M(Z=>({...Z,popby_item_id:K})),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select a popby item..."})}),e.jsx(js,{children:n==null?void 0:n.map(K=>e.jsx(et,{value:K.id,children:K.name},K.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Notes (optional)"}),e.jsx(Fs,{placeholder:"Any notes about this popby...",value:L.notes,onChange:K=>M(Z=>({...Z,notes:K.target.value}))})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx(U,{onClick:z,disabled:c.isPending,children:"Log Popby"})]})]})}),e.jsx(zs,{open:N,onOpenChange:S,children:e.jsxs(Ds,{className:"max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Popby Frequency Settings"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set default popby frequency for each relationship type. You can override these per-contact."}),r==null?void 0:r.map(K=>e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx(te,{className:"font-medium",children:K.name}),e.jsxs(Ns,{value:V(K.id),onValueChange:Z=>H(K.id,Z),children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{})}),e.jsx(js,{children:Bqn.map(Z=>e.jsx(et,{value:Z.value,children:Z.label},Z.value))})]})]},K.id))]}),e.jsx(Mr,{children:e.jsx(U,{onClick:()=>S(!1),children:"Done"})})]})}),e.jsx(zs,{open:A,onOpenChange:T,children:e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Add Popby Idea"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Name *"}),e.jsx(xe,{placeholder:"e.g., Homemade cookies",value:I.name,onChange:K=>R(Z=>({...Z,name:K.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Description"}),e.jsx(Fs,{placeholder:"Optional description...",value:I.description,onChange:K=>R(Z=>({...Z,description:K.target.value}))})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>T(!1),children:"Cancel"}),e.jsx(U,{onClick:$,disabled:!I.name.trim()||d.isPending,children:"Add Item"})]})]})})]})})}const qqn=kN({property_address:sl().min(1,"Property address is required"),city:sl().optional(),state:sl().optional(),zip:sl().optional(),transaction_type:pXe(["buyer","seller"]),close_date:sl().min(1,"Close date is required"),sale_price:NQ().min(0,"Sale price must be positive"),commission_amount:NQ().optional(),lead_source_id:sl().optional(),client_type_id:sl().optional(),contact_id:sl().optional(),notes:sl().optional(),is_win:Rks()});function iJt({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=iPe(),m=Ezs(),{data:p}=g9(),{data:f}=F_(),{data:x}=Cb(),y=ePe(),v=WQe(),{data:b}=oPe(),N=(b==null?void 0:b.show_commission)??!0,S=eMe({resolver:tMe(qqn),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 I=>{const R={property_address:I.property_address,transaction_type:I.transaction_type,close_date:I.close_date,sale_price:I.sale_price,is_win:I.is_win,commission_amount:I.commission_amount||null,lead_source_id:I.lead_source_id||null,client_type_id:I.client_type_id||null,contact_id:I.contact_id||null,city:I.city||null,state:I.state||null,zip:I.zip||null,notes:I.notes||null};n?await m.mutateAsync({id:n.id,...R}):await h.mutateAsync(R),t(!1)},T=async()=>{if(!i.trim())return;const[I,...R]=i.trim().split(" "),z=R.join(" ")||null,$=await y.mutateAsync({first_name:I,last_name:z,tagIds:[]});$&&(S.setValue("contact_id",$.id),l(""),c(!1),a(!1))},L=async()=>{if(!d.trim())return;const I=await v.mutateAsync(d.trim());I&&(S.setValue("lead_source_id",I.id),u(""))},M=x==null?void 0:x.find(I=>I.id===S.watch("contact_id"));return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-lg max-h-[90vh]",children:[e.jsx(Vs,{children:e.jsx($s,{children:n?"Edit Transaction":"Add Transaction"})}),e.jsx(Gi,{className:"max-h-[70vh] pr-4",children:e.jsx(aMe,{...S,children:e.jsxs("form",{onSubmit:S.handleSubmit(A),className:"space-y-4",children:[e.jsx(hf,{control:S.control,name:"property_address",render:({field:I})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"Property Address *"}),e.jsx(Ip,{children:e.jsx(xe,{placeholder:"123 Main St",...I})}),e.jsx(J1,{})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(hf,{control:S.control,name:"city",render:({field:I})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"City"}),e.jsx(Ip,{children:e.jsx(xe,{placeholder:"City",...I})})]})}),e.jsx(hf,{control:S.control,name:"state",render:({field:I})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"State"}),e.jsx(Ip,{children:e.jsx(xe,{placeholder:"TX",...I})})]})}),e.jsx(hf,{control:S.control,name:"zip",render:({field:I})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"Zip"}),e.jsx(Ip,{children:e.jsx(xe,{placeholder:"75001",...I})})]})})]}),e.jsx(hf,{control:S.control,name:"transaction_type",render:({field:I})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"Transaction Type *"}),e.jsxs(Ns,{onValueChange:I.onChange,value:I.value,children:[e.jsx(Ip,{children:e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select type"})})}),e.jsxs(js,{children:[e.jsx(et,{value:"buyer",children:"Buyer"}),e.jsx(et,{value:"seller",children:"Seller"})]})]}),e.jsx(J1,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(hf,{control:S.control,name:"close_date",render:({field:I})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"Close Date *"}),e.jsx(Ip,{children:e.jsx(xe,{type:"date",...I})}),e.jsx(J1,{})]})}),e.jsx(hf,{control:S.control,name:"sale_price",render:({field:I})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"Sale Price *"}),e.jsx(Ip,{children:e.jsx(xe,{type:"number",placeholder:"0",...I,onChange:R=>I.onChange(Number(R.target.value))})}),e.jsx(J1,{})]})})]}),N&&e.jsx(hf,{control:S.control,name:"commission_amount",render:({field:I})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"Commission"}),e.jsx(Ip,{children:e.jsx(xe,{type:"number",placeholder:"0",...I,value:I.value??"",onChange:R=>I.onChange(R.target.value?Number(R.target.value):void 0)})})]})}),e.jsx(hf,{control:S.control,name:"lead_source_id",render:({field:I})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"Lead Source"}),e.jsxs(Ns,{onValueChange:I.onChange,value:I.value||"",children:[e.jsx(Ip,{children:e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select source"})})}),e.jsx(js,{children:p==null?void 0:p.map(R=>e.jsx(et,{value:R.id,children:R.name},R.id))})]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{placeholder:"Add custom source...",value:d,onChange:I=>u(I.target.value),className:"flex-1"}),e.jsx(U,{type:"button",variant:"outline",size:"icon",onClick:L,disabled:!d.trim(),children:e.jsx(an,{className:"h-4 w-4"})})]}),e.jsx(hf,{control:S.control,name:"client_type_id",render:({field:I})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"Client Type"}),e.jsxs(Ns,{onValueChange:I.onChange,value:I.value||"",children:[e.jsx(Ip,{children:e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select client type"})})}),e.jsx(js,{children:f==null?void 0:f.map(R=>e.jsx(et,{value:R.id,children:R.name},R.id))})]})]})}),e.jsx(hf,{control:S.control,name:"contact_id",render:({field:I})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"Client Contact"}),e.jsxs(md,{open:r,onOpenChange:a,children:[e.jsx(pd,{asChild:!0,children:e.jsx(Ip,{children:e.jsxs(U,{variant:"outline",role:"combobox",className:Mt("w-full justify-between",!I.value&&"text-muted-foreground"),children:[M?`${M.first_name} ${M.last_name||""}`.trim():"Select contact",e.jsx(Jw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),e.jsxs(id,{className:"w-full p-0",align:"start",children:[e.jsxs(pj,{children:[e.jsx(fj,{placeholder:"Search contacts..."}),e.jsxs(gj,{children:[e.jsx(xj,{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(U,{variant:"outline",size:"sm",className:"w-full",onClick:()=>c(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),e.jsx(I_,{children:x==null?void 0:x.map(R=>e.jsxs(e1,{value:`${R.first_name} ${R.last_name||""}`,onSelect:()=>{I.onChange(R.id),a(!1)},children:[e.jsx(Xr,{className:Mt("mr-2 h-4 w-4",R.id===I.value?"opacity-100":"opacity-0")}),R.first_name," ",R.last_name||""]},R.id))})]})]}),o&&e.jsxs("div",{className:"p-2 border-t space-y-2",children:[e.jsx(xe,{placeholder:"Enter contact name...",value:i,onChange:R=>l(R.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{size:"sm",onClick:T,disabled:!i.trim()||y.isPending,children:"Add Contact"}),e.jsx(U,{size:"sm",variant:"outline",onClick:()=>{c(!1),l("")},children:"Cancel"})]})]})]})]})]})}),e.jsx(hf,{control:S.control,name:"notes",render:({field:I})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"Notes"}),e.jsx(Ip,{children:e.jsx(Fs,{placeholder:"Any notes about this transaction...",...I})})]})}),e.jsx(hf,{control:S.control,name:"is_win",render:({field:I})=>e.jsxs(Pp,{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Lp,{children:"Mark as Win 🏆"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),e.jsx(Ip,{children:e.jsx(wn,{checked:I.value,onCheckedChange:I.onChange})})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{type:"submit",disabled:h.isPending||m.isPending,children:[n?"Update":"Add"," Transaction"]})]})]})})})]})})}function Ant({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"),[p,f]=j.useState("all"),[x,y]=j.useState("all"),[v,b]=j.useState(!1),N=Tzs(),S=iPe(),{data:A}=g9();F_();const T=JG(),L=R=>{const{id:z,created_at:$,updated_at:H,lead_source:V,client_type:K,contact:Z,...Q}=R;S.mutate(Q)},M=()=>{o&&(N.mutate(o),c(null))},I=s.filter(R=>{var Z,Q,le,ue;const z=d===""||R.property_address.toLowerCase().includes(d.toLowerCase())||((Q=(Z=R.contact)==null?void 0:Z.first_name)==null?void 0:Q.toLowerCase().includes(d.toLowerCase()))||((ue=(le=R.contact)==null?void 0:le.last_name)==null?void 0:ue.toLowerCase().includes(d.toLowerCase())),$=h==="all"||R.transaction_type===h,H=p==="all"||R.lead_source_id===p,V=x==="all"||R.client_type_id===x,K=!v||R.is_win;return z&&$&&H&&V&&K});return n?e.jsx(we,{children:e.jsx(Ie,{className:"p-6 space-y-4",children:[1,2,3].map(R=>e.jsx(xn,{className:"h-16 w-full"},R))})}):e.jsxs(e.Fragment,{children:[e.jsxs(we,{children:[e.jsx(Tt,{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(It,{children:["Transactions (",I.length,")"]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search...",value:d,onChange:R=>u(R.target.value),className:"pl-8 w-[150px]"})]}),e.jsxs(Ns,{value:h,onValueChange:m,children:[e.jsx(ws,{className:"w-[100px]",children:e.jsx(ks,{placeholder:"Type"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Types"}),e.jsx(et,{value:"buyer",children:"Buyer"}),e.jsx(et,{value:"seller",children:"Seller"})]})]}),e.jsxs(Ns,{value:p,onValueChange:f,children:[e.jsx(ws,{className:"w-[130px]",children:e.jsx(ks,{placeholder:"Lead Source"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Sources"}),A==null?void 0:A.map(R=>e.jsx(et,{value:R.id,children:R.name},R.id))]})]}),e.jsxs(U,{variant:v?"default":"outline",size:"sm",onClick:()=>b(!v),children:[e.jsx(Eh,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),e.jsx(Ie,{children:I.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No transactions found"}):T?e.jsx("div",{className:"space-y-3",children:I.map(R=>e.jsxs(we,{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:R.property_address}),R.is_win&&e.jsx(Eh,{className:"h-4 w-4 text-yellow-500 flex-shrink-0"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[R.city,R.state?`, ${R.state}`:""]})]}),e.jsx(Be,{variant:R.transaction_type==="buyer"?"default":"secondary",children:R.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: "}),out(R.close_date)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Price: "}),Uh(R.sale_price)]}),t&&R.commission_amount&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Commission: "}),Uh(R.commission_amount)]}),R.lead_source&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Source: "}),R.lead_source.name]}),R.contact&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Client: "}),R.contact.first_name," ",R.contact.last_name]}),r&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent: "}),r[R.owner_user_id]||"Unknown"]})]}),!a&&e.jsxs("div",{className:"flex justify-end gap-2 mt-3 pt-3 border-t",children:[e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>l(R),children:e.jsx(sp,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>L(R),children:e.jsx(Pa,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>c(R.id),children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]})]},R.id))}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[r&&e.jsx(Lt,{children:"Agent"}),e.jsx(Lt,{children:"Property"}),e.jsx(Lt,{children:"Type"}),e.jsx(Lt,{children:"Close Date"}),e.jsx(Lt,{children:"Sale Price"}),t&&e.jsx(Lt,{children:"Commission"}),e.jsx(Lt,{children:"Lead Source"}),e.jsx(Lt,{children:"Client"}),!a&&e.jsx(Lt,{className:"w-[50px]"})]})}),e.jsx(Xa,{children:I.map(R=>{var z;return e.jsxs(gn,{children:[r&&e.jsx(gt,{className:"font-medium text-sm",children:r[R.owner_user_id]||"Unknown"}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[R.is_win&&e.jsx(Eh,{className:"h-4 w-4 text-yellow-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:R.property_address}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[R.city,R.state?`, ${R.state}`:""]})]})]})}),e.jsx(gt,{children:e.jsx(Be,{variant:R.transaction_type==="buyer"?"default":"secondary",children:R.transaction_type})}),e.jsx(gt,{children:out(R.close_date)}),e.jsx(gt,{children:Uh(R.sale_price)}),t&&e.jsx(gt,{children:R.commission_amount?Uh(R.commission_amount):"-"}),e.jsx(gt,{children:((z=R.lead_source)==null?void 0:z.name)||"-"}),e.jsx(gt,{children:R.contact?`${R.contact.first_name} ${R.contact.last_name||""}`.trim():"-"}),!a&&e.jsx(gt,{children:e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",children:e.jsx(ey,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",children:[e.jsxs(La,{onClick:()=>l(R),children:[e.jsx(sp,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(La,{onClick:()=>L(R),children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),e.jsxs(La,{onClick:()=>c(R.id),className:"text-destructive",children:[e.jsx(In,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},R.id)})})]})})})]}),e.jsx(iJt,{open:!!i,onOpenChange:R=>!R&&l(null),transaction:i||void 0}),e.jsx(Fl,{open:!!o,onOpenChange:R=>!R&&c(null),children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Delete Transaction?"}),e.jsx(Ll,{children:"This action cannot be undone. This will permanently delete this transaction."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:M,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function oJt({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,p)=>{if(!p||p===0)return null;const f=Math.min(m/p*100,100),x=Math.max(p-m,0),y=l>0?x/l:0,v=i/12*100,b=f>=v?"ahead":f>=v*.8?"on-track":"behind";return{percent:f,remaining:x,pace:y,status:b}},c=o(t.totalTransactions,s.transactions_goal),d=o(t.totalVolume,s.volume_goal),u=r?o(t.totalCommission,s.gci_goal):null,h=m=>{switch(m){case"ahead":return e.jsxs(Be,{className:"bg-green-500 text-white",children:[e.jsx(rc,{className:"h-3 w-3 mr-1"}),"Ahead"]});case"on-track":return e.jsxs(Be,{variant:"secondary",children:[e.jsx(Z2,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return e.jsxs(Be,{variant:"destructive",children:[e.jsx(nS,{className:"h-3 w-3 mr-1"}),"Behind"]});default:return null}};return!s.transactions_goal&&!s.volume_goal&&!s.gci_goal?null:e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gu,{className:"h-5 w-5 text-primary"}),e.jsxs(It,{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(ro,{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(ro,{value:d.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[Uh(t.totalVolume,!0)," of ",Uh(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 ",Uh(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(ro,{value:u.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[Uh(t.totalCommission,!0)," of ",Uh(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 ",Uh(u.pace,!0),"/month"]})]})]})})]})}const $qn={light:"",dark:".dark"},lJt=j.createContext(null);function cJt(){const s=j.useContext(lJt);if(!s)throw new Error("useChart must be used within a ");return s}const dJt=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(lJt.Provider,{value:{config:r},children:e.jsxs("div",{"data-chart":o,ref:i,className:Mt("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(Vqn,{id:o,config:r}),e.jsx(oj,{children:n})]})})});dJt.displayName="Chart";const Vqn=({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($qn).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},uJt=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},p)=>{const{config:f}=cJt(),x=j.useMemo(()=>{var A;if(a||!(t!=null&&t.length))return null;const[v]=t,b=`${m||v.dataKey||v.name||"value"}`,N=tKe(f,v,b),S=!m&&typeof l=="string"?((A=f[l])==null?void 0:A.label)||l:N==null?void 0:N.label;return o?e.jsx("div",{className:Mt("font-medium",c),children:o(S,t)}):S?e.jsx("div",{className:Mt("font-medium",c),children:S}):null},[l,o,t,a,c,f,m]);if(!s||!(t!=null&&t.length))return null;const y=t.length===1&&r!=="dot";return e.jsxs("div",{ref:p,className:Mt("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 N=`${h||v.name||v.dataKey||"value"}`,S=tKe(f,v,N),A=u||v.payload.fill||v.color;return e.jsx("div",{className:Mt("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:Mt("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:Mt("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)})})]})});uJt.displayName="ChartTooltip";const Hqn=j.forwardRef(({className:s,hideIcon:t=!1,payload:n,verticalAlign:r="bottom",nameKey:a},i)=>{const{config:l}=cJt();return n!=null&&n.length?e.jsx("div",{ref:i,className:Mt("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=tKe(l,o,c);return e.jsxs("div",{className:Mt("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});Hqn.displayName="ChartLegend";function tKe(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 hce=["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 Ent({stats:s,year:t}){const n=s.transactionsByMonth.some(a=>a.count>0),r=s.leadSourceBreakdown.length>0;return!n&&!r?e.jsx(we,{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(we,{className:"overflow-hidden",children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Transactions by Month"})}),e.jsx(Ie,{className:"overflow-hidden",children:e.jsx(dJt,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:e.jsx(oj,{width:"100%",height:"100%",children:e.jsxs(RLe,{data:s.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx($7,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(wb,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),e.jsx(jb,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),e.jsx(Tg,{content:e.jsx(uJt,{})}),e.jsx(pN,{dataKey:"count",fill:"hsl(var(--primary))",radius:[4,4,0,0],name:"Transactions"})]})})})})]}),r&&e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Ie,{children:[e.jsx("div",{className:"h-[250px]",children:e.jsx(oj,{width:"100%",height:"100%",children:e.jsxs(rGt,{children:[e.jsx(p3,{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(VG,{fill:hce[i%hce.length]},`cell-${i}`))}),e.jsx(Tg,{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:hce[i%hce.length]}}),e.jsx("span",{className:"text-muted-foreground",children:a.name})]},a.name))})]})]})]})}function Gqn(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=NXe(t,r,new Date);if(gqe(a))return Gs(a,"yyyy-MM-dd")}catch{}try{const r=new Date(t);if(gqe(r))return Gs(r,"yyyy-MM-dd")}catch{}return null}const Wqn=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function Kqn({open:s,onOpenChange:t}){const[n,r]=j.useState([]),[a,i]=j.useState(!1),[l,o]=j.useState(0),{data:c}=g9(),{data:d}=F_(),u=iPe(),h=()=>{const v=Wqn.join(","),b=["123 Main St","Dallas","TX","75001","buyer","2024-06-15","450000","13500","Referral","Past Client","yes","Great transaction!"].join(","),N=`${v} ${b}`,S=new Blob([N],{type:"text/csv"}),A=URL.createObjectURL(S),T=document.createElement("a");T.href=A,T.download="transaction-import-template.csv",T.click(),URL.revokeObjectURL(A)},m=v=>{const b=v.split(` `).filter(S=>S.trim());if(b.length<2)return[];const N=b[0].split(",").map(S=>S.trim().toLowerCase().replace(/['"]/g,""));return b.slice(1).map((S,A)=>{var Q,le,ue,se;const T=[];let L="",M=!1;for(const ne of S)ne==='"'?M=!M:ne===","&&!M?(T.push(L.trim()),L=""):L+=ne;T.push(L.trim());const I=ne=>{var ce;const ie=N.indexOf(ne);return ie>=0?(ce=T[ie])==null?void 0:ce.replace(/^["']|["']$/g,"").trim():""},R=(Q=I("transaction_type"))==null?void 0:Q.toLowerCase(),z=(le=I("sale_price"))==null?void 0:le.replace(/[$,]/g,""),$=(ue=I("commission_amount"))==null?void 0:ue.replace(/[$,]/g,""),H=(se=I("is_win"))==null?void 0:se.toLowerCase(),V=I("close_date"),K=Gqn(V);let Z;return I("property_address")?["buyer","seller"].includes(R)?K?(!z||isNaN(Number(z)))&&(Z="Invalid sale price"):Z=`Invalid date format: "${V}" - use MM/DD/YYYY or YYYY-MM-DD`:Z='Transaction type must be "buyer" or "seller"':Z="Missing property address",{property_address:I("property_address"),city:I("city"),state:I("state"),zip:I("zip"),transaction_type:R==="seller"?"seller":"buyer",close_date:K||"",sale_price:Number(z)||0,commission_amount:$?Number($):null,lead_source_name:I("lead_source"),client_type_name:I("client_type"),is_win:["yes","true","1"].includes(H),notes:I("notes"),error:Z}})},p=v=>{var S;const b=(S=v.target.files)==null?void 0:S[0];if(!b)return;const N=new FileReader;N.onload=A=>{var M;const T=(M=A.target)==null?void 0:M.result,L=m(T);r(L)},N.readAsText(b)},f=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,N=0;for(let S=0;SM.name.toLowerCase()===A.lead_source_name.toLowerCase()),L=d==null?void 0:d.find(M=>M.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:(T==null?void 0:T.id)||null,client_type_id:(L==null?void 0:L.id)||null,contact_id:null,notes:A.notes||null,is_win:A.is_win}),b++}catch(T){N++,console.error("Failed to import transaction:",T)}o(Math.round((S+1)/v.length*100))}i(!1),b>0&&re.success(`Imported ${b} transaction${b>1?"s":""}`),N>0&&re.error(`Failed to import ${N} transaction${N>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(Ds,{className:"max-w-2xl max-h-[90vh]",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(U,{variant:"outline",onClick:h,children:[e.jsx(pi,{className:"h-4 w-4 mr-2"}),"Template"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"csv-file",children:"Upload CSV File"}),e.jsx(xe,{id:"csv-file",type:"file",accept:".csv",onChange:p})]}),n.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Be,{variant:"outline",children:[n.length," rows found"]}),x>0&&e.jsxs(Be,{className:"bg-green-500 text-white",children:[e.jsx(Xr,{className:"h-3 w-3 mr-1"}),x," valid"]}),y>0&&e.jsxs(Be,{variant:"destructive",children:[e.jsx(Vo,{className:"h-3 w-3 mr-1"}),y," errors"]})]}),e.jsx(Gi,{className:"h-[200px] border rounded-lg",children:e.jsxs("div",{className:"p-2 space-y-2",children:[n.slice(0,10).map((v,b)=>e.jsxs("div",{className:`p-2 rounded text-sm ${v.error?"bg-destructive/10":"bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium",children:v.property_address||"(no address)"}),e.jsx(Be,{variant:v.transaction_type==="buyer"?"default":"secondary",children:v.transaction_type})]}),e.jsxs("div",{className:"text-muted-foreground",children:[v.close_date," • $",v.sale_price.toLocaleString()]}),v.error&&e.jsx(Lee,{variant:"destructive",className:"mt-1 py-1",children:e.jsx(Iee,{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(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{onClick:f,disabled:x===0||a,children:[e.jsx(qa,{className:"h-4 w-4 mr-2"}),"Import ",x," Transaction",x!==1?"s":""]})]})]})]})})}const Yqn=kN({transactions_goal:NQ().min(0).optional(),volume_goal:NQ().min(0).optional(),gci_goal:NQ().min(0).optional()});function Zqn({open:s,onOpenChange:t,year:n,existingGoals:r}){const a=Mzs(),{data:i}=oPe(),l=(i==null?void 0:i.show_commission)??!0,o=eMe({resolver:tMe(Yqn),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(Ds,{className:"max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{children:[n," Goals"]}),e.jsx(Pr,{children:"Set your annual targets to track your progress throughout the year."})]}),e.jsx(aMe,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(c),className:"space-y-4",children:[e.jsx(hf,{control:o.control,name:"transactions_goal",render:({field:d})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"Transactions Goal"}),e.jsx(Ip,{children:e.jsx(xe,{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(w5e,{children:"Total number of deals you want to close"}),e.jsx(J1,{})]})}),e.jsx(hf,{control:o.control,name:"volume_goal",render:({field:d})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"Volume Goal ($)"}),e.jsx(Ip,{children:e.jsx(xe,{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(w5e,{children:"Total sales volume you want to achieve"}),e.jsx(J1,{})]})}),l&&e.jsx(hf,{control:o.control,name:"gci_goal",render:({field:d})=>e.jsxs(Pp,{children:[e.jsx(Lp,{children:"GCI Goal ($)"}),e.jsx(Ip,{children:e.jsx(xe,{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(w5e,{children:"Gross commission income target"}),e.jsx(J1,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(U,{type:"submit",disabled:a.isPending,children:"Save Goals"})]})]})})]})})}function Tnt({transactions:s,isLoading:t}){const n=j.useRef(null),r=j.useRef(null),a=j.useRef([]),i=j.useRef(null),{isAdmin:l}=vs(),[o,c]=j.useState(""),[d,u]=j.useState(!0),[h,m]=j.useState(0),[p,f]=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||p)return;(async()=>{var N;f(!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 L=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(A)}.json?access_token=${o}&limit=1`)).json();if((N=L.features)!=null&&N[0]){const[M,I]=L.features[0].center;await q.from("scorecard_transactions").update({latitude:I,longitude:M}).eq("id",S.id),S.latitude=I,S.longitude=M,b++}}catch(T){console.error("Geocode error:",T)}}m(b),f(!1)})()},[o,s]),j.useEffect(()=>{if(!n.current||!o||r.current)return;bd.accessToken=o;const v=s.filter(S=>S.latitude!=null&&S.longitude!=null);let b=[-98.5795,39.8283],N=4;if(v.length>0){const S=v.reduce((T,L)=>T+L.longitude,0)/v.length,A=v.reduce((T,L)=>T+L.latitude,0)/v.length;b=[S,A],N=v.length===1?12:10}return r.current=new bd.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:N,center:b}),r.current.addControl(new bd.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(N=>N.remove()),a.current=[],(b=i.current)==null||b.remove();const v=s.filter(N=>N.latitude!=null&&N.longitude!=null);if(v.forEach(N=>{var I;const S=N.transaction_type==="buyer",A=S?"#3B82F6":"#10B981",T=document.createElement("div");T.className="cursor-pointer",T.innerHTML=`
${S?'':''}
`;const L=new bd.Popup({offset:25,closeButton:!0}).setHTML(`
${N.property_address}
${N.city?`
${N.city}${N.state?", "+N.state:""} ${N.zip||""}
`:""}
${S?"Buyer":"Seller"} $${Number(N.sale_price).toLocaleString()}
Closed: ${Su(N.close_date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})} ${(I=N.lead_source)!=null&&I.name?" · "+N.lead_source.name:""}
${N.contact?`
Client: ${N.contact.first_name} ${N.contact.last_name||""}
`:""}
`),M=new bd.Marker(T).setLngLat([N.longitude,N.latitude]).setPopup(L).addTo(r.current);a.current.push(M)}),v.length>1){const N=new bd.LngLatBounds;v.forEach(S=>N.extend([S.longitude,S.latitude])),r.current.fitBounds(N,{padding:60,maxZoom:13})}else v.length===1&&r.current.flyTo({center:[v[0].longitude,v[0].latitude],zoom:12})},[s,o,p]),d||t?e.jsx(we,{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(we,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(ni,{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",p&&" · Geocoding..."]})]}),e.jsx("div",{ref:n,className:"w-full h-[55vh] rounded-lg shadow-lg border"})]}):e.jsx(we,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(Vo,{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 hJt=()=>{const{data:s}=Sj();return ct({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"})},Xqn=s=>{const{data:t}=Sj(),{data:n}=hJt();return ct({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 Qqn(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 Jqn(s,t){return s?s.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2):t[0].toUpperCase()}function e$n({year:s}){var m;const{data:t,isLoading:n}=hJt(),{data:r,isLoading:a}=Xqn(s),i=Wn(),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 p=t.map(R=>Qqn(R,r));p.sort((R,z)=>z.totalVolume-R.totalVolume);const f={};t.forEach(R=>{f[R.id]=R.name||R.email});const x=r.length,y=r.reduce((R,z)=>R+Number(z.sale_price),0),v=r.reduce((R,z)=>R+(Number(z.commission_amount)||0),0),b=r.filter(R=>R.transaction_type==="buyer").length,N=r.filter(R=>R.transaction_type==="seller").length,S={};r.forEach(R=>{var $;const z=(($=R.lead_source)==null?void 0:$.name)||"Unknown";S[z]=(S[z]||0)+1});const A=Object.entries(S).sort((R,z)=>z[1]-R[1])[0],T={};r.forEach(R=>{const z=Su(R.close_date).toLocaleString("default",{month:"short"});T[z]=(T[z]||0)+1});const M=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(R=>({month:R,count:T[R]||0})),I=Object.entries(S).map(([R,z])=>({name:R,count:z})).sort((R,z)=>z.count-R.count);return{aggregate:{totalTxns:x,buyerCount:b,sellerCount:N,totalVolume:y,avgPrice:x>0?y/x:0,totalGCI:v,topSource:A?{name:A[0],count:A[1]}:null,memberCount:t.length},memberStats:p,topPerformer:p[0]||null,agentNameMap:f,teamChartStats:{transactionsByMonth:M,leadSourceBreakdown:I}}},[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(p=>e.jsx(xn,{className:"h-24"},p))}),e.jsx(xn,{className:"h-64"})]}):!o||c.length===0?e.jsx(we,{className:"py-12",children:e.jsxs(Ie,{className:"text-center space-y-2",children:[e.jsx(Bn,{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(we,{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(Bn,{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(we,{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(ra,{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(we,{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(yu,{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:Uh(o.totalVolume,!0)})]})}),e.jsx(we,{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(rc,{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:Uh(o.avgPrice,!0)})]})}),e.jsx(we,{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(yu,{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:Uh(o.totalGCI,!0)})]})}),e.jsx(we,{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(Eh,{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(we,{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(Al,{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:Uh(d.totalVolume,!0)})]})]})}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-lg",children:"Member Performance"})}),e.jsx(Ie,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Agent"}),e.jsx(Lt,{className:"text-center",children:"Transactions"}),e.jsx(Lt,{className:"text-center",children:"B / S"}),e.jsx(Lt,{className:"text-right",children:"Volume"}),e.jsx(Lt,{className:"text-right",children:"Avg Price"}),e.jsx(Lt,{className:"text-right",children:"GCI"}),e.jsx(Lt,{className:"text-right"})]})}),e.jsx(Xa,{children:c.map((p,f)=>e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[f===0&&p.totalTransactions>0&&e.jsx(Al,{className:"absolute -top-2 -right-2 h-3.5 w-3.5 text-amber-500"}),e.jsxs(Ea,{className:"h-8 w-8",children:[e.jsx(Ci,{src:p.member.avatar_url||void 0}),e.jsx(Ta,{className:"text-xs",children:Jqn(p.member.name,p.member.email)})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:p.member.name||p.member.email}),p.member.name&&e.jsx("p",{className:"text-xs text-muted-foreground",children:p.member.email})]})]})}),e.jsx(gt,{className:"text-center font-semibold",children:p.totalTransactions}),e.jsxs(gt,{className:"text-center text-sm",children:[p.buyerCount," / ",p.sellerCount]}),e.jsx(gt,{className:"text-right font-medium",children:Uh(p.totalVolume,!0)}),e.jsx(gt,{className:"text-right text-sm",children:Uh(p.averagePrice,!0)}),e.jsx(gt,{className:"text-right font-medium",children:Uh(p.totalGCI,!0)}),e.jsx(gt,{className:"text-right",children:e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>i(`/mission-control/scorecard/${p.member.id}`),children:e.jsx(xa,{className:"h-4 w-4"})})})]},p.member.id))})]})})})]}),e.jsxs(oa,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(la,{children:[e.jsxs(Kt,{value:"transactions",children:[e.jsx(m0,{className:"h-4 w-4 mr-1"}),"All Transactions"]}),e.jsxs(Kt,{value:"charts",children:[e.jsx(Cl,{className:"h-4 w-4 mr-1"}),"Charts"]}),e.jsxs(Kt,{value:"map",children:[e.jsx(ni,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(Zt,{value:"transactions",children:e.jsx(Ant,{transactions:r||[],showCommission:!0,isLoading:a,agentNameMap:u,readOnly:!0})}),e.jsx(Zt,{value:"charts",children:h&&e.jsx(Ent,{stats:h,year:s})}),e.jsx(Zt,{value:"map",children:e.jsx(Tnt,{transactions:r||[],isLoading:a})})]})]})}const z4e=new Date().getFullYear(),$Nt=Array.from({length:10},(s,t)=>z4e-t),mce="all";function t$n(){var $;const[s,t]=j.useState(z4e),n=s===null?mce:String(s),r=H=>t(H===mce?null:Number(H)),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,p]=j.useState("my"),{data:f}=Sj(),x=(f==null?void 0:f.role)==="team_leader",{data:y,isLoading:v}=KQe(s??void 0),{yearStats:b,lifetimeStats:N,isLoading:S,showCommission:A}=j7t(s??void 0),{data:T,isLoading:L}=w7t(s??z4e),{data:M}=oPe(),I=Pzs(),R=()=>{if(!y||y.length===0)return;const H=["Property Address","City","State","Zip","Transaction Type","Close Date","Sale Price",...A?["Commission"]:[],"Lead Source","Client Type","Contact Name","Is Win","Notes"],V=y.map(ue=>{var se,ne;return[ue.property_address,ue.city||"",ue.state||"",ue.zip||"",ue.transaction_type,ue.close_date,ue.sale_price,...A?[ue.commission_amount||""]:[],((se=ue.lead_source)==null?void 0:se.name)||"",((ne=ue.client_type)==null?void 0:ne.name)||"",ue.contact?`${ue.contact.first_name} ${ue.contact.last_name||""}`.trim():"",ue.is_win?"Yes":"No",ue.notes||""]}),K=[H,...V].map(ue=>ue.map(se=>`"${String(se).replace(/"/g,'""')}"`).join(",")).join(` `),Z=new Blob([K],{type:"text/csv"}),Q=URL.createObjectURL(Z),le=document.createElement("a");le.href=Q,le.download=s===null?"transactions-all.csv":`transactions-${s}.csv`,le.click(),URL.revokeObjectURL(Q)},z=!y||y.length===0;return e.jsxs(qs,{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(U,{variant:m==="my"?"default":"ghost",size:"sm",onClick:()=>p("my"),className:"h-8",children:"My Scorecard"}),e.jsxs(U,{variant:m==="team"?"default":"ghost",size:"sm",onClick:()=>p("team"),className:"h-8",children:[e.jsx(Bn,{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(Ns,{value:n,onValueChange:r,children:[e.jsx(ws,{className:"w-[140px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:mce,children:"All Years"}),$Nt.map(H=>e.jsx(et,{value:String(H),children:H},H))]})]})]}),e.jsx(e$n,{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(Ns,{value:n,onValueChange:r,children:[e.jsx(ws,{className:"w-[140px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:mce,children:"All Years"}),$Nt.map(H=>e.jsx(et,{value:String(H),children:H},H))]})]}),e.jsx(U,{variant:"outline",size:"icon",onClick:()=>h(!u),children:e.jsx(qc,{className:"h-4 w-4"})})]})]}),u&&e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsx(It,{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(te,{children:"Show Commission"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Display commission fields and include in stats"})]}),e.jsx(wn,{checked:(M==null?void 0:M.show_commission)??!0,onCheckedChange:H=>I.mutate({show_commission:H})})]})})]}),z&&!v?e.jsx(we,{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(Cl,{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(U,{onClick:()=>i(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Add Your First Transaction"]}),e.jsxs(U,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(qa,{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(U,{variant:"link",className:"h-auto p-0",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(pi,{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(U,{onClick:()=>i(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),e.jsxs(U,{variant:"outline",onClick:()=>d(!0),children:[e.jsx(Gu,{className:"h-4 w-4 mr-2"}),"Set Goals"]}),e.jsxs(U,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(qa,{className:"h-4 w-4 mr-2"}),"Import"]}),e.jsxs(U,{variant:"outline",onClick:R,disabled:z,children:[e.jsx(pi,{className:"h-4 w-4 mr-2"}),"Export"]}),e.jsx(U,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(pi,{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(we,{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(ra,{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:[N.totalTransactions," lifetime"]})]})}),e.jsx(we,{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(Bn,{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(we,{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(yu,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:Uh(b.totalVolume,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Uh(N.totalVolume,!0)," lifetime"]})]})}),e.jsx(we,{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(rc,{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:Uh(b.averagePrice,!0)})]})}),e.jsx(we,{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(Eh,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),e.jsx("p",{className:"text-lg font-bold truncate",children:(($=b.topLeadSource)==null?void 0:$.name)||"-"}),b.topLeadSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.topLeadSource.count," deals"]})]})}),A&&e.jsx(we,{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(yu,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"GCI"})]}),e.jsx("p",{className:"text-2xl font-bold",children:Uh(b.totalCommission,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Uh(N.totalCommission,!0)," lifetime"]})]})}),A&&b.totalNetToAgent>0&&b.totalNetToAgent!==b.totalCommission&&e.jsx(we,{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(yu,{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:Uh(b.totalNetToAgent,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Uh(N.totalNetToAgent,!0)," lifetime"]})]})})]}),s!==null&&T&&e.jsx(oJt,{goals:T,stats:b,year:s,showCommission:A}),e.jsxs(oa,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(la,{children:[e.jsx(Kt,{value:"transactions",children:"Transactions"}),e.jsx(Kt,{value:"charts",children:"Charts"}),e.jsxs(Kt,{value:"map",children:[e.jsx(ni,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(Zt,{value:"transactions",children:e.jsx(Ant,{transactions:y||[],showCommission:A,isLoading:v})}),e.jsx(Zt,{value:"charts",children:e.jsx(Ent,{stats:b,year:s??void 0})}),e.jsx(Zt,{value:"map",children:e.jsx(Tnt,{transactions:y||[],isLoading:v})})]})]})]})]}),e.jsx(iJt,{open:a,onOpenChange:i}),e.jsx(Kqn,{open:l,onOpenChange:o}),e.jsx(Zqn,{open:c,onOpenChange:d,year:s??z4e,existingGoals:T})]})}const s$n={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"},n$n={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},r$n={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function a$n({listing:s,onClick:t,onEdit:n,onDelete:r,onCreateMusicVideo:a,showActions:i}){var S,A;const{user:l}=vs(),{data:o}=pFt(s.id),c=mFt(),[d,u]=j.useState(!1),h=T=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(T),m=((S=s.photos)==null?void 0:S.find(T=>T.is_primary))||((A=s.photos)==null?void 0:A[0]),p=(l==null?void 0:l.id)===s.agent_id,f=s.listing_class==="commercial",x=s.commercial??null,y=s.lifecycle_stage==="pitch",v=f?[fA(x==null?void 0:x.building_sf)?`${fA(x==null?void 0:x.building_sf)} building`:null,fA(x==null?void 0:x.available_sf)?`${fA(x==null?void 0:x.available_sf)} available`:null,mCe(x==null?void 0:x.cap_rate)?`${mCe(x==null?void 0:x.cap_rate)} cap`:null,(x==null?void 0:x.price_per_sf)!=null?`${M2(x.price_per_sf,2)}/SF`:null,(x==null?void 0:x.units)!=null?`${x.units} units`:null].filter(Boolean).slice(0,3):[],b=async T=>{T.stopPropagation();try{const L=await c.mutateAsync(s.id);re.success(L.saved?"Listing saved!":"Listing removed from saved")}catch{re.error("Failed to save listing")}},N=T=>{if(T.stopPropagation(),l)u(!0);else{const L=`${s.listing_class==="commercial"?"https://commercial.relevelup.com":"https://listings.relevelup.com"}/${s.slug||s.id}`;navigator.clipboard.writeText(L),re.success("Link copied to clipboard!")}};return e.jsxs(we,{className:"overflow-hidden hover:shadow-lg transition-shadow cursor-pointer group",onClick:t,children:[e.jsxs("div",{className:"relative aspect-[4/3] bg-muted",children:[m?e.jsx("img",{src:m.photo_url,alt:s.property_address||s.city,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(db,{className:"h-12 w-12"})}),e.jsxs("div",{className:"absolute top-2 left-2 flex flex-wrap gap-1",children:[e.jsx(Be,{className:`${s$n[s.status]} text-white border-0`,children:f&&y?"Pitch":n$n[s.status]}),f&&e.jsx(Be,{className:"border-0 bg-[#0b0f14]/90 text-white",children:x!=null&&x.deal_type?uP[x.deal_type]:"Commercial"})]}),s.is_featured&&e.jsx("div",{className:"absolute top-2 right-2 p-1.5 bg-amber-500 rounded-full",children:e.jsx(Ua,{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(U,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:b,children:e.jsx(ko,{className:`h-4 w-4 ${o?"fill-pink-500 text-pink-500":""}`})}),e.jsx(U,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:N,title:p?"Copy link":"Share & earn leads",children:p?e.jsx(jd,{className:"h-4 w-4"}):e.jsx(cn,{className:"h-4 w-4 text-amber-500"})})]})]}),e.jsx(JMe,{open:d,onOpenChange:u,listingId:s.id,listingSlug:s.slug||null,listingTitle:s.property_address||`${s.city}, ${s.state}`,isCommercial:s.listing_class==="commercial"}),e.jsxs(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:f?BV(x,s.price):h(s.price)}),s.open_to_referrals&&e.jsxs(Be,{variant:"outline",className:"text-xs",children:[e.jsx(Bn,{className:"h-3 w-3 mr-1"}),"Referrals"]})]}),e.jsxs("div",{children:[f?e.jsx("p",{className:"font-medium truncate",children:UM(s,x)}):s.property_address&&e.jsx("p",{className:"font-medium truncate",children:s.property_address}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(ni,{className:"h-3 w-3"}),f?Xne(s,x):`${s.city}, ${s.state}${s.neighborhood?` • ${s.neighborhood}`:""}`]})]}),e.jsx("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:f?v.map(T=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(db,{className:"h-4 w-4"}),T]},T)):e.jsxs(e.Fragment,{children:[s.bedrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xw,{className:"h-4 w-4"}),s.bedrooms," bd"]}),s.bathrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(d0,{className:"h-4 w-4"}),s.bathrooms," ba"]}),s.square_footage&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(db,{className:"h-4 w-4"}),s.square_footage.toLocaleString()," sqft"]})]})}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsx(Be,{variant:"secondary",className:"text-xs",children:f?x!=null&&x.commercial_type?qP[x.commercial_type]:"Commercial":r$n[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(xa,{className:"h-3 w-3"}),s.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(jd,{className:"h-3 w-3"}),s.share_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ko,{className:"h-3 w-3"}),s.save_count]})]}),i&&(n||r||a)&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[a&&e.jsxs(U,{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:T=>{T.stopPropagation(),a()},children:[e.jsx(oq,{className:"h-4 w-4"}),"Music Video"]}),n&&e.jsxs(U,{variant:"outline",size:"sm",className:"flex-1",onClick:T=>{T.stopPropagation(),n()},children:[e.jsx(sp,{className:"h-4 w-4 mr-2"}),"Edit"]}),r&&e.jsx(U,{variant:"destructive",size:"sm",onClick:T=>{T.stopPropagation(),r()},children:e.jsx(In,{className:"h-4 w-4"})})]})]})]})}const Mnt="lu_listing_selection_v1",aTe=24,iTe=new Set;function mJt(){try{return JSON.parse(sessionStorage.getItem(Mnt)||"{}")}catch{return{}}}function U9e(s){try{sessionStorage.setItem(Mnt,JSON.stringify(s))}catch{}iTe.forEach(t=>t())}let yC=mJt();function i$n(){yC=mJt(),iTe.forEach(s=>s())}typeof window<"u"&&window.addEventListener("storage",s=>{s.key===Mnt&&i$n()});const ZT={getSnapshot:()=>yC,subscribe(s){return iTe.add(s),()=>iTe.delete(s)},toggle(s){const t={...yC};if(t[s.mlsNumber])delete t[s.mlsNumber];else{if(Object.keys(t).length>=aTe)return!1;t[s.mlsNumber]=s}return yC=t,U9e(t),!0},remove(s){const t={...yC};delete t[s],yC=t,U9e(t)},clear(){yC={},U9e({})},has(s){return!!yC[s]},all(){return Object.values(yC)}};function pJt(){const s=j.useSyncExternalStore(ZT.subscribe,ZT.getSnapshot,ZT.getSnapshot);return{selected:Object.values(s),selectedIds:new Set(Object.keys(s)),count:Object.keys(s).length,has:t=>!!s[t],toggle:ZT.toggle,remove:ZT.remove,clear:ZT.clear}}const o$n=new Set(["office_exclusive","coming_soon","pre_market"]);function l$n(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=o$n.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 LY(s){const{has:t}=pJt(),n=`lx-${s.listing.id}`,r=t(n);return e.jsxs("div",{className:"relative",children:[e.jsx(a$n,{...s}),e.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),ZT.toggle(l$n(s.listing))||re.error(`You can select up to ${aTe} 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(Xr,{className:"h-4 w-4"}):e.jsx(ln,{className:"h-4 w-4"})})]})}function c$n({open:s,onOpenChange:t,listings:n}){const{user:r}=vs(),{leadSite:a}=$p(),[i,l]=j.useState("grid"),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,f]=j.useState(new Set),[x,y]=j.useState(!1),[v,b]=j.useState(!1),{data:N}=dre(),[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:K})=>b(!!(K!=null&&K.gmail_email)))},[s,r==null?void 0:r.id]),j.useEffect(()=>{if(s){if(!o){const K=Array.from(new Set(n.map(Q=>Q.city).filter(Boolean))),Z=K.length===1?` in ${K[0]}`:"";c(n.length===1?`New listing for you${Z}`:`${n.length} hand-picked listings${Z}`)}d||u(`Hi {{first_name}}, Thought of you — I just picked a few properties I think you'll love. Take a look and let me know if anything catches your eye. Happy to set up a private showing whenever works.`)}},[s]);const{data:T=[],isLoading:L}=ct({queryKey:["send-listings-contacts",r==null?void 0:r.id],queryFn:async()=>{const{data:K}=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 K||[]},enabled:!!(r!=null&&r.id)&&s}),{data:M}=ct({queryKey:["send-listings-suggestions",n.map(K=>K.mlsNumber).join(",")],queryFn:async()=>{const{data:K,error:Z}=await q.functions.invoke("listing-email-suggestions",{body:{listings:n.map(Q=>({mlsNumber:Q.mlsNumber,city:Q.city,state:Q.state,price:Q.price,bedrooms:Q.bedrooms,bathrooms:Q.bathrooms}))}});if(Z)throw Z;return K},enabled:s&&n.length>0}),I=(M==null?void 0:M.suggestions)||[],R=j.useMemo(()=>{const K=h.trim().toLowerCase();return K?T.filter(Z=>`${Z.first_name??""} ${Z.last_name??""} ${Z.email} ${Z.city??""}`.toLowerCase().includes(K)):T},[T,h]),z=K=>{f(Z=>{const Q=new Set(Z);return Q.has(K)?Q.delete(K):Q.add(K),Q})},$=()=>{f(K=>{const Z=new Set(K);return I.forEach(Q=>Z.add(Q.contact_id)),Z})},H=n.length>0&&n.every(K=>K.mlsNumber.startsWith("lx-")),V=async()=>{if(!H&&!(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(p.size===0)return re.error("Pick at least one recipient");if(!v&&N&&!N.hasVerifiedSes){A(!0);return}const K=T.filter(Z=>p.has(Z.id)).map(Z=>({contact_id:Z.id,email:Z.email,first_name:Z.first_name,last_name:Z.last_name}));y(!0);try{const{data:Z,error:Q}=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(le=>({mlsNumber:le.mlsNumber,address:le.address,city:le.city,state:le.state,zip:le.zip,price:le.price,bedrooms:le.bedrooms,bathrooms:le.bathrooms,sqft:le.sqft,status:le.status,photos:(le.photos||[]).slice(0,1),description:le.description||"",external_url:le.externalUrl||null,is_private:le.is_private===!0})),recipients:K}});if(Q)throw Q;if(!(Z!=null&&Z.success))throw new Error((Z==null?void 0:Z.error)||"Send failed");re.success(`Sent ${Z.sent}/${K.length} via ${v?"Gmail":"Amazon SES"}${Z.failed?` · ${Z.failed} failed`:""}`),ZT.clear(),f(new Set),t(!1)}catch(Z){re.error((Z==null?void 0:Z.message)||"Failed to send")}finally{y(!1)}};return e.jsxs(zs,{open:s,onOpenChange:t,children:[e.jsxs(Ds,{className:"max-w-5xl max-h-[92vh] overflow-hidden p-0 flex flex-col",children:[e.jsxs(Vs,{className:"px-6 pt-6 pb-2",children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5 text-primary"}),"Email ",n.length," ",n.length===1?"Listing":"Listings"]}),e.jsx(Pr,{children:H?"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(te,{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(K=>{var Z;return e.jsxs("div",{className:"shrink-0 w-32 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("div",{className:"h-20 w-full bg-muted",children:((Z=K.photos)==null?void 0:Z[0])&&e.jsx("img",{src:K.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:["$",(K.price/1e3).toFixed(0),"k"]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground truncate",children:[K.city,", ",K.state]})]})]},K.mlsNumber)})})]}),e.jsxs("div",{children:[e.jsx(te,{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(Hg,{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(pc,{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(te,{htmlFor:"subject",children:"Subject"}),e.jsx(xe,{id:"subject",value:o,onChange:K=>c(K.target.value),placeholder:"Subject line",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"intro",children:"Personal message"}),e.jsx(Fs,{id:"intro",value:d,onChange:K=>u(K.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:[I.length>0&&e.jsxs(we,{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(cn,{className:"h-4 w-4 text-amber-600"}),e.jsxs("div",{className:"text-sm font-medium",children:[I.length," smart ",I.length===1?"match":"matches"]})]}),e.jsx(U,{size:"sm",variant:"outline",onClick:$,children:"Add all"})]}),e.jsx(Gi,{className:"max-h-32 mt-2",children:e.jsx("div",{className:"space-y-1",children:I.slice(0,12).map(K=>{const Z=p.has(K.contact_id);return e.jsxs("label",{className:"flex items-start gap-2 text-xs py-1 cursor-pointer",children:[e.jsx(xi,{checked:Z,onCheckedChange:()=>z(K.contact_id),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate",children:[K.first_name," ",K.last_name??""," ",e.jsxs("span",{className:"text-muted-foreground font-normal",children:["· ",K.email]})]}),e.jsx("div",{className:"text-muted-foreground truncate",children:K.reason})]})]},K.contact_id)})})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(te,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:["All contacts (",R.length,")"]}),p.size>0&&e.jsxs(Be,{variant:"secondary",children:[p.size," selected"]})]}),e.jsx(xe,{placeholder:"Search contacts…",value:h,onChange:K=>m(K.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(Gi,{className:"h-full",children:L?e.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading…"}):R.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:R.map(K=>{const Z=p.has(K.id);return e.jsxs("label",{className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-muted/40",children:[e.jsx(xi,{checked:Z,onCheckedChange:()=>z(K.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[K.first_name," ",K.last_name??""]}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[K.email,K.city&&e.jsxs(e.Fragment,{children:[" · ",K.city]})]})]})]},K.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:p.size})," recipients"]}),p.size>0&&e.jsxs(U,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>f(new Set),children:[e.jsx(er,{className:"h-3 w-3 mr-1"}),"Clear"]})]})]})]}),e.jsxs(Mr,{className:"px-6 py-4 border-t bg-muted/30",children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),disabled:x,children:"Cancel"}),e.jsx(U,{onClick:V,disabled:x||p.size===0,children:x?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),"Send to ",p.size," ",p.size===1?"contact":"contacts"]})})]})]}),e.jsx(nPe,{open:S,onOpenChange:A,hasPending:!!(N!=null&&N.hasPendingSes),pendingEmails:N==null?void 0:N.pendingEmails})]})}function d$n(){const{selected:s,count:t,remove:n,clear:r}=pJt(),[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>=aTe?"Max reached":`Pick up to ${aTe}`})]})]}),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(er,{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(U,{variant:"ghost",size:"sm",onClick:r,className:"gap-1.5",children:[e.jsx(In,{className:"h-4 w-4"})," Clear"]}),e.jsxs(U,{size:"sm",className:"gap-1.5",onClick:()=>i(!0),children:[e.jsx($r,{className:"h-4 w-4"}),"Email these ",t===1?"listing":"listings"]})]})]})}),e.jsx(c$n,{open:a,onOpenChange:i,listings:s})]})}const u$n=[{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"}],h$n=[{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 m$n({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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsx(It,{className:"text-lg",children:"Filters"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(U,{variant:"ghost",size:"sm",onClick:l,children:"Clear All"}),e.jsx(U,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(er,{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(te,{children:"Status"}),e.jsxs(Ns,{value:s.status||"all",onValueChange:o=>t({...s,status:o==="all"?void 0:o}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"All statuses"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Statuses"}),u$n.map(o=>e.jsx(et,{value:o.value,children:o.label},o.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Property Type"}),e.jsxs(Ns,{value:s.propertyType||"all",onValueChange:o=>t({...s,propertyType:o==="all"?void 0:o}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"All types"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Types"}),h$n.map(o=>e.jsx(et,{value:o.value,children:o.label},o.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Min Price"}),e.jsx(xe,{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(te,{children:"Max Price"}),e.jsx(xe,{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(te,{children:"Deal Type"}),e.jsxs(Ns,{value:a.dealType||"all",onValueChange:o=>i({dealType:o==="all"?void 0:o}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Any"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"Any deal type"}),Object.entries(uP).map(([o,c])=>e.jsx(et,{value:o,children:c},o))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Asset Type"}),e.jsxs(Ns,{value:a.commercialType||"all",onValueChange:o=>i({commercialType:o==="all"?void 0:o}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Any"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"Any asset type"}),Object.entries(qP).map(([o,c])=>e.jsx(et,{value:o,children:c},o))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Min Building SF"}),e.jsx(xe,{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(te,{children:"Min Cap Rate (%)"}),e.jsx(xe,{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(te,{children:"Open to Referrals Only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show only listings accepting buyer referrals"})]}),e.jsx(wn,{checked:s.openToReferrals||!1,onCheckedChange:o=>t({...s,openToReferrals:o||void 0})})]})]})]})}function p$n({leaderboard:s}){const t=r=>{switch(r){case 0:return e.jsx(Al,{className:"h-5 w-5 text-amber-500"});case 1:return e.jsx(CA,{className:"h-5 w-5 text-gray-400"});case 2:return e.jsx(Eh,{className:"h-5 w-5 text-amber-700"});default:return e.jsx("span",{className:"text-sm font-medium text-muted-foreground w-5 text-center",children:r+1})}},n=(r,a)=>!r||r.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No data yet. Start sharing to climb the leaderboard!"}):e.jsx("div",{className:"space-y-2",children:r.map((i,l)=>e.jsxs("div",{className:`flex items-center gap-4 p-3 rounded-lg ${l===0?"bg-gradient-to-r from-amber-500/10 to-amber-500/5 border border-amber-500/20":"bg-muted/50"}`,children:[e.jsx("div",{className:"flex items-center justify-center w-8",children:t(l)}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("p",{className:"font-medium truncate",children:i.name})}),e.jsxs(Be,{variant:l===0?"default":"secondary",children:[i.count," ",a]})]},i.agentId))});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Al,{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(jd,{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(ra,{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(CA,{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(Al,{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(we,{children:[e.jsx(Tt,{children:e.jsx(It,{children:"Community Leaderboard"})}),e.jsx(Ie,{children:e.jsxs(oa,{defaultValue:"sharers",children:[e.jsxs(la,{className:"w-full",children:[e.jsxs(Kt,{value:"sharers",className:"flex-1",children:[e.jsx(jd,{className:"h-4 w-4 mr-2"}),"Top Sharers"]}),e.jsxs(Kt,{value:"listers",className:"flex-1",children:[e.jsx(ra,{className:"h-4 w-4 mr-2"}),"Top Contributors"]})]}),e.jsx(Zt,{value:"sharers",className:"mt-4",children:n(s==null?void 0:s.topSharers,"shares")}),e.jsx(Zt,{value:"listers",className:"mt-4",children:n(s==null?void 0:s.topListers,"listings")})]})})]})]})}const VNt={coming_soon:"#F59E0B",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#8B5CF6",under_contract:"#3B82F6",sold:"#A855F7"},HNt={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 f$n(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function g$n({listings:s,isLoading:t}){const n=Wn(),r=j.useRef(null),a=j.useRef(null),i=j.useRef([]),{isAdmin:l}=vs(),[o,c]=j.useState(""),[d,u]=j.useState(!0),[h,m]=j.useState(!1),p=s.filter(x=>x.latitude!=null&&x.longitude!=null),f=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||f.length===0||h)return;(async()=>{var y;m(!0);for(const v of f){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,T]=S.features[0].center;await q.from("listings").update({latitude:T,longitude:A}).eq("id",v.id),v.latitude=T,v.longitude=A}}catch(N){console.error("Geocode error:",N)}}m(!1)})()},[o,s]),j.useEffect(()=>{if(!r.current||!o||a.current)return;bd.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,N=x.reduce((S,A)=>S+A.latitude,0)/x.length;y=[b,N],v=x.length===1?12:10}return a.current=new bd.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:v,center:y}),a.current.addControl(new bd.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 T,L,M;const v=VNt[y.status]||"#10B981",b=((T=y.photos)==null?void 0:T.find(I=>I.is_primary))||((L=y.photos)==null?void 0:L[0]),N=document.createElement("div");N.className="cursor-pointer",N.innerHTML=`
`;const S=new bd.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${b!=null&&b.photo_url?``:""}
${f$n(y.price)}
${y.property_address||""}
${y.city}, ${y.state}
${HNt[y.status]||y.status} ${y.bedrooms?`${y.bedrooms} bed`:""} ${y.bathrooms?`${y.bathrooms} bath`:""}
${(M=y.agent)!=null&&M.name?`
Listed by ${y.agent.name}
`:""}
Click to view details →
`),A=new bd.Marker(N).setLngLat([y.longitude,y.latitude]).setPopup(S).addTo(a.current);i.current.push(A)}),x.length>1){const y=new bd.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(we,{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(we,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(ni,{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(VNt).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:HNt[x]})]},x)),e.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[p.length," of ",s.length," mapped",h&&" · Geocoding..."]})]}),e.jsx("div",{ref:r,className:"w-full h-[60vh] rounded-lg shadow-lg border"})]}):e.jsx(we,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(Vo,{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 sKe="homereel_mv_prefill",nKe="homereel_mv_badge_default";function fJt(s){try{sessionStorage.setItem(sKe,JSON.stringify(s)),s.badge&&s.badge.type!=="none"&&sessionStorage.setItem(nKe,JSON.stringify(s.badge))}catch{}}function gxr(){try{const s=sessionStorage.getItem(sKe);return s?(sessionStorage.removeItem(sKe),JSON.parse(s)):null}catch{return null}}function xxr(){try{const s=sessionStorage.getItem(nKe);return s?(sessionStorage.removeItem(nKe),JSON.parse(s)):null}catch{return null}}function gJt(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 x$n(){var K,Z,Q,le,ue,se,ne,ie;const s=Wn(),{brokerageId:t}=vs(),{data:n,isLoading:r}=rFt(),[a,i]=j.useState("feed"),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState("all"),[m,p]=j.useState({sortBy:"newest"}),{data:f,isLoading:x}=aFt({...m,listingClass:u==="all"?void 0:u,city:c||m.city}),{data:y,isLoading:v}=yOs(),{data:b,isLoading:N}=TQe(),{data:S,isLoading:A}=wOs(),{data:T,isLoading:L}=kOs(),{data:M}=NOs(),I=lFt(),R=m.commercial,z=(f??[]).filter(ce=>{if(!R||ce.listing_class!=="commercial")return!R||Object.values(R).every(be=>be===void 0)||ce.listing_class!=="commercial";const je=ce.commercial??{};return!(R.dealType&&je.deal_type!==R.dealType||R.commercialType&&je.commercial_type!==R.commercialType||R.minBuildingSf&&Number(je.building_sf??0)ce.lifecycle_stage==="pitch"),H=ce=>s(ce.listing_class==="commercial"?`/mission-control/listings/${ce.id}/commercial`:`/mission-control/listings/${ce.id}`),V=async ce=>{if(await Yi("Are you sure you want to delete this listing? This action cannot be undone."))try{await I.mutateAsync(ce),re.success("Listing deleted successfully")}catch{re.error("Failed to delete listing")}};return r?e.jsx(qs,{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(qs,{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(U,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(an,{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(we,{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(ra,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(f==null?void 0:f.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active Listings"})]})]})}),e.jsx(we,{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(ko,{className:"h-5 w-5 text-pink-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(y==null?void 0:y.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saved"})]})]})}),e.jsx(we,{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(wF,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(b==null?void 0:b.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"My Listings"})]})]})}),e.jsx(we,{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(Bn,{className:"h-5 w-5 text-sky-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(((K=S==null?void 0:S.sent)==null?void 0:K.length)||0)+(((Z=S==null?void 0:S.received)==null?void 0:Z.length)||0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referrals"})]})]})})]}),e.jsxs(oa,{value:a,onValueChange:i,children:[e.jsxs(la,{className:"w-full justify-start overflow-x-auto",children:[e.jsx(Kt,{value:"feed",children:"Community Feed"}),t&&e.jsx(Kt,{value:"brokerage",children:"Brokerage"}),e.jsx(Kt,{value:"my-listings",children:"My Listings"}),$.length>0&&e.jsxs(Kt,{value:"pitches",children:["Pitches (",$.length,")"]}),e.jsx(Kt,{value:"saved",children:"Saved"}),e.jsx(Kt,{value:"referrals",children:"Referrals"}),e.jsx(Kt,{value:"map",children:"Map"}),e.jsx(Kt,{value:"leaderboard",children:"Leaderboard"})]}),e.jsxs(Zt,{value:"feed",className:"space-y-4",children:[e.jsx("div",{className:"inline-flex rounded-lg border bg-muted/40 p-1",children:["all","residential","commercial"].map(ce=>e.jsx("button",{type:"button",onClick:()=>h(ce),className:`rounded-md px-4 py-1.5 text-sm font-medium capitalize transition ${u===ce?"bg-background shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:ce==="all"?"All listings":ce},ce))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by city or neighborhood...",value:c,onChange:ce=>d(ce.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:m.sortBy,onValueChange:ce=>p({...m,sortBy:ce}),children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{placeholder:"Sort by"})}),e.jsxs(js,{children:[e.jsx(et,{value:"newest",children:"Newest First"}),e.jsx(et,{value:"updated",children:"Recently Updated"}),e.jsx(et,{value:"price_asc",children:"Price: Low to High"}),e.jsx(et,{value:"price_desc",children:"Price: High to Low"})]})]}),e.jsxs(U,{variant:"outline",onClick:()=>o(!l),children:[e.jsx(K2,{className:"h-4 w-4 mr-2"}),"Filters"]})]}),l&&e.jsx(m$n,{filters:m,onFiltersChange:p,onClose:()=>o(!1),showCommercial:u!=="residential"}),x?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(6)].map((ce,je)=>e.jsxs(we,{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"})]})]},je))}):(f==null?void 0:f.length)===0?e.jsx(we,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(ra,{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(U,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(an,{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:z.map(ce=>e.jsx(LY,{listing:ce,onClick:()=>H(ce)},ce.id))})]}),e.jsx(Zt,{value:"my-listings",className:"space-y-4",children:N?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((ce,je)=>e.jsxs(we,{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"})]})]},je))}):(b==null?void 0:b.length)===0?e.jsx(we,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(wF,{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(U,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Add Your First Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:b==null?void 0:b.map(ce=>e.jsx(LY,{listing:ce,showActions:!0,onClick:()=>H(ce),onEdit:()=>s(ce.listing_class==="commercial"?`/mission-control/listings/${ce.id}/commercial`:`/mission-control/listings/${ce.id}/edit`),onDelete:()=>V(ce.id),onCreateMusicVideo:()=>{const je=(ce.photos??[]).slice().sort((be,he)=>(he.is_primary?1:0)-(be.is_primary?1:0)||(be.sort_order??0)-(he.sort_order??0)).map(be=>be.photo_url).filter(Boolean);if(je.length===0){re.error("Add photos to this listing first.");return}fJt({photos:je,details:{address:ce.property_address||`${ce.city??""} ${ce.state??""}`.trim(),beds:ce.bedrooms?String(ce.bedrooms):"",baths:ce.bathrooms?String(ce.bathrooms):"",sqft:ce.square_footage?String(ce.square_footage):"",price:ce.price?String(ce.price):"",highlights:ce.description||""},sourceLabel:"My Listings",badge:gJt(ce.status,ce.price)}),s("/admin/beta/homereel?tab=music-video")}},ce.id))})}),e.jsxs(Zt,{value:"pitches",className:"space-y-4",children:[e.jsx(we,{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:$.map(ce=>e.jsx(LY,{listing:ce,showActions:!0,onClick:()=>s(`/mission-control/listings/${ce.id}/commercial`),onEdit:()=>s(`/mission-control/listings/${ce.id}/commercial`),onDelete:()=>V(ce.id)},ce.id))})]}),e.jsx(Zt,{value:"saved",className:"space-y-4",children:v?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((ce,je)=>e.jsxs(we,{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"})]})]},je))}):(y==null?void 0:y.length)===0?e.jsx(we,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(ko,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No saved listings"}),e.jsx("p",{className:"text-muted-foreground",children:"Save listings to quickly access them later"})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:y==null?void 0:y.map(ce=>e.jsx(LY,{listing:ce.listing,onClick:()=>H(ce.listing)},ce.id))})}),e.jsx(Zt,{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(jd,{className:"h-4 w-4"}),"Referrals Sent (",((Q=S==null?void 0:S.sent)==null?void 0:Q.length)||0,")"]}),((le=S==null?void 0:S.sent)==null?void 0:le.length)===0?e.jsx(we,{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:(ue=S==null?void 0:S.sent)==null?void 0:ue.map(ce=>{var je,be;return e.jsx(we,{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:ce.buyer_name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((je=ce.listing)==null?void 0:je.property_address)||((be=ce.listing)==null?void 0:be.city)})]}),e.jsx(Be,{variant:ce.status==="closed"?"default":"secondary",children:ce.status.replace("_"," ")})]})})},ce.id)})})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4"}),"Referrals Received (",((se=S==null?void 0:S.received)==null?void 0:se.length)||0,")"]}),((ne=S==null?void 0:S.received)==null?void 0:ne.length)===0?e.jsx(we,{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:(ie=S==null?void 0:S.received)==null?void 0:ie.map(ce=>{var je;return e.jsx(we,{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:ce.buyer_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["From: ",(je=ce.sender)==null?void 0:je.name]})]}),e.jsx(Be,{variant:ce.status==="closed"?"default":"secondary",children:ce.status.replace("_"," ")})]}),e.jsx(U,{size:"sm",variant:"outline",className:"w-full mt-2",onClick:()=>s(`/mission-control/listings/${ce.listing_id}`),children:"View Listing"})]})},ce.id)})})]})]})}),t&&e.jsx(Zt,{value:"brokerage",className:"space-y-4",children:L?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((ce,je)=>e.jsxs(we,{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"})]})]},je))}):(T==null?void 0:T.length)===0?e.jsx(we,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(wF,{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(U,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(an,{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:T==null?void 0:T.map(ce=>e.jsx(LY,{listing:ce,onClick:()=>H(ce)},ce.id))})}),e.jsx(Zt,{value:"map",children:e.jsx(g$n,{listings:f||[],isLoading:x})}),e.jsx(Zt,{value:"leaderboard",children:e.jsx(p$n,{leaderboard:M})})]})]}),e.jsx(d$n,{})]}):e.jsx(qs,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx(we,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(ra,{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 y$n=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function v$n({listingId:s,ownerOnly:t=!1}){const{data:n=[]}=UMe(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 MQe(i);window.open(l,"_blank")}catch{re.error("Failed to open document")}};return e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"text-lg flex items-center gap-2",children:[e.jsx(Ur,{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(Ur,{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:y$n(i.file_size)})]}),e.jsx(pi,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary"})]},i.id))})})]})}function g_(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 nae(){const s=Sa();return ct({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 xJt(){const s=Sa(),t=Qt();return yt({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 rae(){const s=Sa();return ct({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 yJt(){const s=Sa(),t=Qt();return yt({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 vJt(){const s=Qt();return yt({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 b$n(){const s=Qt();return yt({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 _$n(){const s=Qt();return yt({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 w$n(s){return ct({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 j$n(){const s=Qt();return yt({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 N$n(s){return ct({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 k$n(){const s=Qt();return yt({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 S$n(){const s=Qt();return yt({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 C$n(){const s=Sa();return ct({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+(g_(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+(g_(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+(g_(c)||0),0),projectedAnnualNet:l.reduce((o,c)=>o+(g_(c)||0),0)+r.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(g_(c)||0)*d},0)}},enabled:!!s})}function A$n(s){const t=Sa();return ct({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 E$n(){const s=Qt();return yt({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 T$n(){const s=Qt();return yt({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 M$n({listing:s}){const t=Wn(),[n,r]=j.useState(""),[a,i]=j.useState(!1),{data:l,isLoading:o}=A$n(s.id),{data:c,isLoading:d}=nae(),{data:u,isLoading:h}=rae(),m=xJt(),p=E$n(),f=T$n(),x=yJt(),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(T=>T.name==="Active");case"under_contract":return c.find(T=>T.name==="Under Contract");case"sold":return c.find(T=>T.is_won_stage);default:return c.find(T=>T.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)}},N=async()=>{if(!n){re.error("Please select a deal");return}try{await p.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 f.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(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx(P4,{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(Et,{className:"h-5 w-5 animate-spin text-muted-foreground"})})})]}):l?e.jsxs(we,{className:"border-primary/20 bg-primary/5",children:[e.jsx(Tt,{className:"pb-2",children:e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx(ad,{className:"h-4 w-4 text-primary"}),"Linked to Pipeline"]})}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:l.deal_name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:l.deal_pipeline_stages&&e.jsx(Be,{variant:"secondary",className:"text-xs",style:{backgroundColor:`${l.deal_pipeline_stages.color}20`,color:l.deal_pipeline_stages.color},children:l.deal_pipeline_stages.name})})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Status changes sync automatically between the listing and pipeline."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{variant:"outline",size:"sm",className:"flex-1",onClick:()=>t("/mission-control/pipeline"),children:["View Pipeline",e.jsx(Oa,{className:"h-3 w-3 ml-1"})]}),e.jsx(U,{variant:"ghost",size:"sm",onClick:S,disabled:f.isPending,children:f.isPending?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(qF,{className:"h-4 w-4"})})]})]})]}):e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx(P4,{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(U,{onClick:b,disabled:a||x.isPending,className:"w-full",size:"sm",children:[a||x.isPending?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(an,{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(Ns,{value:n,onValueChange:r,children:[e.jsx(ws,{className:"flex-1 text-sm",children:e.jsx(ks,{placeholder:"Link to existing deal..."})}),e.jsx(js,{children:y.map(A=>e.jsx(et,{value:A.id,children:A.deal_name},A.id))})]}),e.jsx(U,{variant:"secondary",size:"icon",onClick:N,disabled:!n||p.isPending,children:p.isPending?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(ad,{className:"h-4 w-4"})})]})]})]})]})}const P$n={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"},L$n={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},GNt={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function I$n(){var ue,se,ne,ie,ce,je,be,he,ge;const{listingId:s}=Di(),t=Wn(),{user:n}=vs(),{data:r,isLoading:a}=rre(s||""),{data:i}=pFt(s||""),{data:l}=bOs(s||""),o=mFt(),c=vOs(),d=_Os(),u=lFt(),h=jOs(),[m,p]=j.useState(!1),[f,x]=j.useState(!1),[y,v]=j.useState(!1),[b,N]=j.useState(!1),[S,A]=j.useState(!1),[T,L]=j.useState(!1),[M,I]=j.useState(null),[R,z]=j.useState({buyerName:"",buyerType:"",notes:""}),$=(n==null?void 0:n.id)===(r==null?void 0:r.agent_id),H=ke=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(ke),V=async ke=>{const Te=`https://listings.relevelup.com/${(r==null?void 0:r.slug)||(r==null?void 0:r.id)}`,Me=`Check out this listing: ${(r==null?void 0:r.property_address)||(r==null?void 0:r.city)}`;d.mutate({listingId:r.id,shareType:ke});try{switch(ke){case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(Te)}`,"_blank");break;case"copy":await navigator.clipboard.writeText(Te),re.success("Link copied to clipboard!");break;case"text":window.open(`sms:?body=${encodeURIComponent(`${Me} ${Te}`)}`);break;case"email":window.open(`mailto:?subject=${encodeURIComponent(Me)}&body=${encodeURIComponent(`Check out this listing: ${Te}`)}`);break}}catch(Oe){console.error("Share error:",Oe),re.error("Failed to share")}},K=async()=>{try{await u.mutateAsync(r.id),re.success("Listing deleted"),t("/mission-control/listings")}catch{re.error("Failed to delete listing")}},Z=async()=>{if(!R.buyerName.trim()){re.error("Please enter buyer name");return}try{await h.mutateAsync({listingId:r.id,listingAgentId:r.agent_id,buyerName:R.buyerName,buyerType:R.buyerType||void 0,notes:R.notes||void 0}),re.success("Referral sent successfully!"),x(!1),z({buyerName:"",buyerType:"",notes:""})}catch{re.error("Failed to send referral")}},Q=ke=>{var Fe,Ne;const Te=(r==null?void 0:r.property_address)||`${r==null?void 0:r.city}, ${r==null?void 0:r.state}`,Me=H((r==null?void 0:r.price)||0),Oe=r!=null&&r.bedrooms?`${r.bedrooms}BD`:"",Se=r!=null&&r.bathrooms?`${r.bathrooms}BA`:"",Qe=r!=null&&r.square_footage?`${r.square_footage.toLocaleString()}SF`:"",Ae=[Oe,Se,Qe].filter(Boolean).join(" | ");switch(ke){case"just_listed":return`🏡 JUST LISTED! ${Te} ${Me} ${Ae} ${(r==null?void 0:r.description)||"Schedule your showing today!"} #JustListed #RealEstate #HomeForSale #${(Fe=r==null?void 0:r.city)==null?void 0:Fe.replace(/\s/g,"")}`;case"price_improvement":return`📣 PRICE IMPROVEMENT! ${Te} Now ${Me}! ${Ae} Don't miss this opportunity! #PriceReduced #RealEstate #HomeForSale`;case"teaser":return`Looking for a ${GNt[(r==null?void 0:r.property_type)||"single_family"].toLowerCase()} in ${r==null?void 0:r.city}? 👀 I've got just the one for you! ${Ae} DM me for details! 📩 #ComingSoon #RealEstate #${(Ne=r==null?void 0:r.city)==null?void 0:Ne.replace(/\s/g,"")}`;default:return""}};if(r&&r.listing_class==="commercial")return e.jsx(td,{to:`/mission-control/listings/${r.id}/commercial`,replace:!0});if(a)return e.jsx(qs,{title:"Listing",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(xn,{className:"h-10 w-32"}),e.jsx(xn,{className:"h-[400px] w-full"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsx(xn,{className:"h-48"}),e.jsx(xn,{className:"h-48"}),e.jsx(xn,{className:"h-48"})]})]})});if(!r)return e.jsx(qs,{title:"Listing Not Found",description:"",children:e.jsx(we,{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(U,{onClick:()=>t("/mission-control/listings"),children:"Back to Listings"})]})})});const le=((ue=r.photos)==null?void 0:ue.find(ke=>ke.is_primary))||((se=r.photos)==null?void 0:se[0]);return e.jsxs(qs,{title:"",description:"",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs(U,{variant:"ghost",onClick:()=>t("/mission-control/listings"),children:[e.jsx(Aa,{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:()=>le&&I(le.photo_url),children:le?e.jsx("img",{src:le.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:(ne=r.photos)==null?void 0:ne.slice(1,5).map((ke,Te)=>e.jsx("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>I(ke.photo_url),children:e.jsx("img",{src:ke.photo_url,alt:`Photo ${Te+2}`,className:"w-full h-full object-cover"})},ke.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(we,{children:e.jsxs(Ie,{className:"p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4 mb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Be,{className:`${P$n[r.status]} text-white border-0`,children:L$n[r.status]}),r.is_featured&&e.jsxs(Be,{variant:"outline",className:"border-amber-500 text-amber-500",children:[e.jsx(Ua,{className:"h-3 w-3 mr-1 fill-amber-500"}),"Featured"]}),r.open_to_referrals&&e.jsxs(Be,{variant:"outline",children:[e.jsx(Bn,{className:"h-3 w-3 mr-1"}),"Open to Referrals"]})]}),e.jsx("h1",{className:"text-3xl font-bold text-primary mb-2",children:H(r.price)}),r.property_address&&e.jsx("p",{className:"text-xl font-medium",children:r.property_address}),e.jsxs("p",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(ni,{className:"h-4 w-4"}),r.city,", ",r.state,r.neighborhood&&` • ${r.neighborhood}`]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(U,{variant:"outline",size:"icon",onClick:()=>o.mutate(r.id),children:e.jsx(ko,{className:`h-4 w-4 ${i?"fill-pink-500 text-pink-500":""}`})}),e.jsx(U,{variant:"outline",size:"icon",onClick:()=>c.mutate(r.id),children:l?e.jsx(Zk,{className:"h-4 w-4"}):e.jsx(bx,{className:"h-4 w-4"})}),!$&&e.jsxs(U,{variant:"outline",className:"border-amber-500 text-amber-600 hover:bg-amber-50",onClick:()=>v(!0),children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Share & Earn Leads"]}),e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsxs(U,{variant:"outline",children:[e.jsx(jd,{className:"h-4 w-4 mr-2"}),"Share"]})}),e.jsxs(Eu,{children:[e.jsxs(La,{onClick:()=>V("copy"),children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Copy Link"]}),e.jsxs(La,{onClick:()=>V("facebook"),children:[e.jsx(zp,{className:"h-4 w-4 mr-2"}),"Facebook"]}),e.jsxs(La,{onClick:()=>V("text"),children:[e.jsx(Ki,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(La,{onClick:()=>V("email"),children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Email"]})]})]}),$&&e.jsxs(e.Fragment,{children:[e.jsxs(U,{variant:"outline",onClick:()=>{const ke=(r.photos??[]).slice().sort((Te,Me)=>(Me.is_primary?1:0)-(Te.is_primary?1:0)||(Te.sort_order??0)-(Me.sort_order??0)).map(Te=>Te.photo_url).filter(Boolean);if(ke.length===0){re.error("Add photos to this listing first.");return}fJt({photos:ke,details:{address:r.property_address||`${r.city??""} ${r.state??""}`.trim(),beds:r.bedrooms?String(r.bedrooms):"",baths:r.bathrooms?String(r.bathrooms):"",sqft:r.square_footage?String(r.square_footage):"",price:r.price?String(r.price):"",highlights:r.description||""},sourceLabel:"Listing Exchange",badge:gJt(r.status,r.price)}),t("/admin/beta/homereel?tab=music-video")},className:"gap-2 border-violet-500/60 text-violet-600 hover:bg-violet-50",children:[e.jsx(oq,{className:"h-4 w-4"}),"Create Music Video"]}),e.jsxs(U,{variant:"outline",onClick:()=>A(!0),className:"gap-2 border-amber-500/60 text-amber-600 hover:bg-amber-50",children:[e.jsx(cn,{className:"h-4 w-4"}),"Just Listed Graphic"]}),e.jsxs(U,{variant:"outline",onClick:()=>L(!0),className:"gap-2",children:[e.jsx(Sf,{className:"h-4 w-4"}),"QR Code"]}),e.jsxs(U,{variant:"outline",onClick:()=>N(!0),className:"gap-2",children:[e.jsx(ln,{className:"h-4 w-4"}),"Email My Sphere"]}),e.jsxs(U,{onClick:()=>t(`/mission-control/listings/${r.id}/customize`),className:"gap-2 bg-gradient-to-r from-primary to-primary/80 hover:opacity-95 text-primary-foreground shadow-md",children:[e.jsx(cn,{className:"h-4 w-4"}),"Customize Public Page"]}),e.jsxs(U,{variant:"outline",onClick:()=>t(`/mission-control/listings/${r.id}/edit`),children:[e.jsx(sp,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsx(U,{variant:"destructive",size:"icon",onClick:()=>p(!0),children:e.jsx(In,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4 py-4 border-y",children:[r.bedrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(Xw,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:r.bedrooms}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Beds"})]}),r.bathrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(d0,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:r.bathrooms}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Baths"})]}),r.square_footage&&e.jsxs("div",{className:"text-center",children:[e.jsx(db,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:r.square_footage.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sq Ft"})]}),r.year_built&&e.jsxs("div",{className:"text-center",children:[e.jsx(pa,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:r.year_built}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Built"})]})]}),e.jsxs("div",{className:"pt-4 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(Be,{variant:"secondary",children:[e.jsx(_i,{className:"h-3 w-3 mr-1"}),GNt[r.property_type]]}),r.lot_size&&e.jsxs(Be,{variant:"secondary",children:["Lot: ",r.lot_size]}),r.has_hoa&&e.jsx(Be,{variant:"secondary",children:"HOA"})]}),r.description&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Description"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})]}),r.agent_notes&&r.agent_notes_public&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Agent Notes"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.agent_notes})]}),r.co_agent_name&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Co-Listing Agent"}),e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border p-3",children:[r.co_agent_photo_url?e.jsx("img",{src:r.co_agent_photo_url,alt:r.co_agent_name,className:"h-12 w-12 rounded-full object-cover"}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-muted flex items-center justify-center text-sm font-medium",children:r.co_agent_name.charAt(0)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:r.co_agent_name}),r.co_agent_brokerage&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:r.co_agent_brokerage}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:[r.co_agent_email,r.co_agent_phone].filter(Boolean).join(" · ")})]})]})]}),r.mls_link&&e.jsx(U,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:r.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Sr,{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(xa,{className:"h-4 w-4"}),r.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(jd,{className:"h-4 w-4"}),r.share_count," shares"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ko,{className:"h-4 w-4"}),r.save_count," saves"]})]})]})}),r.allow_sharing&&e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-lg",children:"Share Content"})}),e.jsx(Ie,{className:"space-y-4",children:["just_listed","price_improvement","teaser"].map(ke=>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:[ke.replace("_"," ")," Caption"]}),e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(Q(ke)),re.success("Caption copied!")},children:e.jsx(Pa,{className:"h-3 w-3"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:Q(ke)})]},ke))})]}),e.jsx(v$n,{listingId:r.id,ownerOnly:$})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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:((ce=(ie=r.agent)==null?void 0:ie.name)==null?void 0:ce.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((je=r.agent)==null?void 0:je.name)||"Unknown"}),((he=(be=r.agent)==null?void 0:be.brokerage)==null?void 0:he.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:r.agent.brokerage.name})]})]}),!$&&e.jsx("div",{className:"space-y-2",children:((ge=r.agent)==null?void 0:ge.email)&&e.jsx(U,{variant:"outline",className:"w-full",asChild:!0,children:e.jsxs("a",{href:`mailto:${r.agent.email}`,children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Email Agent"]})})})]})]}),$&&e.jsx(M$n,{listing:r}),!$&&r.open_to_referrals&&e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"text-lg flex items-center gap-2",children:[e.jsx(Bn,{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(U,{className:"w-full",onClick:()=>x(!0),children:"Send Referral"})]})]})]})]})]}),e.jsx(zs,{open:!!M,onOpenChange:()=>I(null),children:e.jsx(Ds,{className:"max-w-4xl",children:e.jsx("img",{src:M||"",alt:"Full size",className:"w-full h-auto"})})}),e.jsx(zs,{open:m,onOpenChange:p,children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Delete Listing"}),e.jsx(Pr,{children:"Are you sure you want to delete this listing? This action cannot be undone."})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>p(!1),children:"Cancel"}),e.jsx(U,{variant:"destructive",onClick:K,disabled:u.isPending,children:u.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(zs,{open:f,onOpenChange:x,children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{children:"Buyer Name *"}),e.jsx(xe,{value:R.buyerName,onChange:ke=>z({...R,buyerName:ke.target.value}),placeholder:"Enter buyer's name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Buyer Type"}),e.jsxs(Ns,{value:R.buyerType,onValueChange:ke=>z({...R,buyerType:ke}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select type"})}),e.jsxs(js,{children:[e.jsx(et,{value:"first_time",children:"First-Time Buyer"}),e.jsx(et,{value:"investor",children:"Investor"}),e.jsx(et,{value:"relocating",children:"Relocating"}),e.jsx(et,{value:"upgrade",children:"Upgrading"}),e.jsx(et,{value:"downsize",children:"Downsizing"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Notes"}),e.jsx(Fs,{value:R.notes,onChange:ke=>z({...R,notes:ke.target.value}),placeholder:"Any additional information..."})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsx(U,{onClick:Z,disabled:h.isPending,children:h.isPending?"Sending...":"Send Referral"})]})]})}),e.jsx(QFt,{open:T,onOpenChange:L,url:`https://listings.relevelup.com/${r.slug||r.id}`,title:r.property_address||`${r.city}, ${r.state}`,fileBase:r.slug||r.property_address||r.city}),e.jsx(JMe,{open:y,onOpenChange:v,listingId:(r==null?void 0:r.id)||"",listingSlug:(r==null?void 0:r.slug)||null,listingTitle:(r==null?void 0:r.property_address)||`${r==null?void 0:r.city}, ${r==null?void 0:r.state}`}),r&&e.jsx(l7t,{open:b,onOpenChange:N,listing:r}),e.jsx(UQe,{listingId:(r==null?void 0:r.id)||null,open:S,onOpenChange:A})]})}function R$n({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=N=>{m.current&&!m.current.contains(N.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]);const p=async b=>{if(b.trim().length<3){a([]),c(!1);return}l(!0);try{const{data:N,error:S}=await q.functions.invoke("mls-listing-search",{body:{query:b}});if(S)throw S;a((N==null?void 0:N.listings)||[]),c(!0)}catch(N){console.error("MLS search error:",N),a([])}finally{l(!1)}},f=b=>{n(b),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>p(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 N=(b||"").toLowerCase();return N.includes("single")||N.includes("detached")?"Single Family":N.includes("condo")?"Condo":N.includes("town")?"Townhouse":N.includes("land")||N.includes("lot")?"Land":N.includes("multi")?"Multi-Family":N.includes("commercial")?"Commercial":b||"Other"};return e.jsxs(we,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Tt,{className:"pb-3",children:[e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(pi,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:t,onChange:b=>f(b.target.value),onFocus:()=>r.length>0&&c(!0),placeholder:"Start typing a property address...",className:"pl-9 pr-9"}),i&&e.jsx(Et,{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(er,{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(ni,{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(Xw,{className:"h-3 w-3"})," ",b.bedrooms]}),b.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(d0,{className:"h-3 w-3"})," ",b.bathrooms]}),b.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(I4,{className:"h-3 w-3"})," ",b.sqft.toLocaleString()]})]})]}),e.jsxs("div",{className:"flex-shrink-0 flex flex-col items-end gap-1",children:[e.jsx(Be,{variant:"outline",className:"text-[10px]",children:v(b.propertyType)}),b.photos.length>0&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[b.photos.length," photos"]})]})]},b.mlsNumber))})]})})]})}function D$n({selectedVideoId:s,onVideoSelect:t,listingId:n}){const r=Wn(),{user:a}=vs(),[i,l]=j.useState(!1),[o,c]=j.useState([]),[d,u]=j.useState(!1),[h,m]=j.useState(null),[p,f]=j.useState({});j.useEffect(()=>{s&&a?x():m(null)},[s,a]);const x=async()=>{if(!s)return;const{data:I,error:R}=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();!R&&I&&(m(I),y(I))},y=async I=>{try{const{data:R,error:z}=await q.functions.invoke("bunny-upload",{body:{action:"asset-urls",videoId:I.bunny_video_id,isAgentVideo:!0}});!z&&(R!=null&&R.thumbnailUrl)&&f($=>({...$,[I.id]:{thumbnailUrl:R.thumbnailUrl}}))}catch(R){console.warn("Failed to get signed URL",R)}},v=async()=>{if(a){u(!0);try{const{data:I,error:R}=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(R)throw R;c(I||[]),I!=null&&I.length&&b(I)}catch(I){console.error("Error fetching videos:",I),re.error("Failed to load videos")}finally{u(!1)}}},b=async I=>{var R;try{const z=I.map(Z=>Z.bunny_video_id),{data:$,error:H}=await q.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:z,isAgentVideo:!0}});if(H)throw H;const V=($==null?void 0:$.assets)||{},K={};for(const Z of I)(R=V[Z.bunny_video_id])!=null&&R.thumbnailUrl&&(K[Z.id]={thumbnailUrl:V[Z.bunny_video_id].thumbnailUrl});f(Z=>({...Z,...K}))}catch(z){console.warn("Failed to bulk-fetch signed URLs",z)}},N=()=>{l(!0),v()},S=I=>{t(I.id),m(I),l(!1),re.success("Video selected")},A=()=>{t(null),m(null)},T=()=>{const I=n?`/mission-control/listings/${n}/edit`:"/mission-control/listings/new";r(`/mission-control/video?returnUrl=${encodeURIComponent(I)}`)},L=I=>{if(!I)return"0:00";const R=Math.floor(I/60),z=I%60;return`${R}:${z.toString().padStart(2,"0")}`},M=I=>{var R;return((R=p[I.id])==null?void 0:R.thumbnailUrl)||I.thumbnail_url};return e.jsxs("div",{className:"space-y-3",children:[h?e.jsx(we,{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:[M(h)?e.jsx("img",{src:M(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(Wr,{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(lu,{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:L(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(U,{type:"button",variant:"outline",size:"sm",onClick:N,children:"Change"}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",onClick:A,className:"text-destructive hover:text-destructive",children:e.jsx(er,{className:"h-4 w-4"})})]})]})})}):e.jsx(we,{className:"border-dashed",children:e.jsx(Ie,{className:"p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Wr,{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(U,{type:"button",variant:"outline",onClick:N,className:"gap-2",children:[e.jsx(tj,{className:"h-4 w-4"}),"Select from Library"]}),e.jsxs(U,{type:"button",variant:"outline",onClick:T,className:"gap-2",children:[e.jsx(_x,{className:"h-4 w-4"}),"Record New Video"]})]})]})})}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Ds,{className:"max-w-2xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(tj,{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(Et,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):o.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Wr,{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(U,{onClick:T,className:"gap-2",children:[e.jsx(_x,{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(I=>e.jsxs("button",{type:"button",onClick:()=>S(I),className:`group relative rounded-lg overflow-hidden border-2 transition-all text-left ${s===I.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:[M(I)?e.jsx("img",{src:M(I),alt:I.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(Wr,{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(lu,{className:"h-8 w-8 text-white opacity-0 group-hover:opacity-100 transition-opacity"})}),I.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:L(I.duration_seconds)})]}),e.jsx("div",{className:"p-2 bg-card",children:e.jsx("p",{className:"text-xs font-medium truncate",children:I.title||"Untitled Video"})})]},I.id))})}),e.jsxs("div",{className:"flex justify-between items-center pt-4 border-t",children:[e.jsxs(U,{type:"button",variant:"ghost",onClick:T,className:"gap-2",children:[e.jsx(_x,{className:"h-4 w-4"}),"Record New Video"]}),e.jsx(U,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"})]})]})})]})}const O$n=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function F$n({listingId:s}){const t=j.useRef(null),{data:n=[],isLoading:r}=UMe(s),a=fFt(),i=gFt(),l=TOs(),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 MQe(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(U,{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(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(qa,{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(we,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(Ur,{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:O$n(d.file_size)})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[d.visible_on_exchange?e.jsx(xa,{className:"h-3 w-3"}):e.jsx(Vg,{className:"h-3 w-3"}),e.jsx("span",{className:"hidden sm:inline",children:d.visible_on_exchange?"Visible":"Hidden"}),e.jsx(wn,{checked:d.visible_on_exchange,onCheckedChange:u=>l.mutate({id:d.id,visible:u,listingId:s}),className:"ml-1"})]}),e.jsx(U,{type:"button",variant:"ghost",size:"icon",onClick:()=>c(d.storage_path),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx(U,{type:"button",variant:"ghost",size:"icon",onClick:async()=>{await Yi(`Delete ${d.file_name}?`)&&i.mutate({id:d.id,storage_path:d.storage_path,listingId:s})},children:e.jsx(er,{className:"h-4 w-4 text-destructive"})})]},d.id))})]})}const z$n=[{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"}],B$n=[{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 U$n({id:s,url:t,index:n,onRemove:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=QMe({id:s}),u={transform:pP.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(kf,{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(er,{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(Ua,{className:"h-2.5 w-2.5 fill-current"})," Primary"]})]})}function q$n({photoUrls:s,pendingPhotos:t,onRemove:n,onReorder:r,uploading:a,onUpload:i}){const l=$Me(HV(SG,{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),p=o.indexOf(h.id),f=[...s],x=[...t],[y]=f.splice(m,1),[v]=x.splice(m,1);f.splice(p,0,y),x.splice(p,0,v),r(f,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(YMe,{sensors:l,collisionDetection:VMe,onDragEnd:c,children:e.jsx(XMe,{items:o,strategy:lre,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[s.map((d,u)=>e.jsx(U$n,{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(Et,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(qa,{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 WNt(){const{listingId:s}=Di(),[t]=fc(),n=t.get("brokerage"),r=Wn(),{user:a}=vs(),{hasLeadSite:i}=$p(),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:p}=rre(l?s:""),f=iFt(),x=xOs(),y=oFt(),v=cFt(),b=dFt(),N=uFt(),S=hFt(),{data:A=[]}=ct({queryKey:["brokerage-agents",n],queryFn:async()=>{if(!n)return[];const{data:he,error:ge}=await q.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name");if(ge)throw ge;return he||[]},enabled:o}),[T,L]=j.useState(""),[M,I]=j.useState(!1),[R,z]=j.useState([]),[$,H]=j.useState([]),[V,K]=j.useState(!1),Z=async he=>{if(he.size>5*1024*1024){re.error("Image must be under 5MB");return}K(!0);try{const ge=he.name.split(".").pop()||"jpg",ke=`${(a==null?void 0:a.id)||"anon"}/co-agents/${Date.now()}.${ge}`,{error:Te}=await q.storage.from("listing-photos").upload(ke,he,{upsert:!0});if(Te)throw Te;const{data:Me}=q.storage.from("listing-photos").getPublicUrl(ke);le(Oe=>({...Oe,co_agent_photo_url:Me.publicUrl})),re.success("Headshot uploaded")}catch(ge){re.error((ge==null?void 0:ge.message)||"Failed to upload headshot")}finally{K(!1)}},[Q,le]=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 he,ge,ke,Te,Me;m&&l&&le({property_address:m.property_address||"",city:m.city||"",state:m.state||"",neighborhood:m.neighborhood||"",price:((he=m.price)==null?void 0:he.toString())||"",property_type:m.property_type,status:m.status,bedrooms:((ge=m.bedrooms)==null?void 0:ge.toString())||"",bathrooms:((ke=m.bathrooms)==null?void 0:ke.toString())||"",square_footage:((Te=m.square_footage)==null?void 0:Te.toString())||"",lot_size:m.lot_size||"",year_built:((Me=m.year_built)==null?void 0:Me.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})},[m,l]);const ue=he=>{var Me,Oe;const ge={"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"},ke=(he.propertyType||"").toLowerCase(),Te=((Me=Object.entries(ge).find(([Se])=>ke.includes(Se)))==null?void 0:Me[1])||"other";le(Se=>({...Se,property_address:he.address||Se.property_address,city:he.city||Se.city,state:he.state||Se.state,price:he.price?String(he.price):Se.price,property_type:Te,bedrooms:he.bedrooms?String(he.bedrooms):Se.bedrooms,bathrooms:he.bathrooms?String(he.bathrooms):Se.bathrooms,square_footage:he.sqft?String(he.sqft):Se.square_footage,lot_size:he.lotSize?String(he.lotSize):Se.lot_size,year_built:he.yearBuilt?String(he.yearBuilt):Se.year_built,description:he.description||Se.description})),((Oe=he.photos)==null?void 0:Oe.length)>0&&(d(he.photos),$.forEach(Se=>URL.revokeObjectURL(Se)),z([]),H([]))},se=he=>{if(!he)return;const ge=Array.from(he);z(Te=>[...Te,...ge]);const ke=ge.map(Te=>URL.createObjectURL(Te));H(Te=>[...Te,...ke])},ne=he=>{URL.revokeObjectURL($[he]),z(ge=>ge.filter((ke,Te)=>Te!==he)),H(ge=>ge.filter((ke,Te)=>Te!==he))},ie=async he=>{var ge;if(!(!he||!m)){I(!0);try{for(const ke of Array.from(he)){const Te=ke.name.split(".").pop(),Me=`${a==null?void 0:a.id}/${m.id}/${Date.now()}.${Te}`,{error:Oe}=await q.storage.from("listing-photos").upload(Me,ke);if(Oe)throw Oe;const{data:{publicUrl:Se}}=q.storage.from("listing-photos").getPublicUrl(Me);await v.mutateAsync({listingId:m.id,photoUrl:Se,isPrimary:!((ge=m.photos)!=null&&ge.length)})}re.success("Photos uploaded!")}catch(ke){console.error("Upload error:",ke),re.error("Failed to upload photos")}finally{I(!1)}}},ce=async he=>{for(let ge=0;ge{if(m)try{await b.mutateAsync({photoId:he,listingId:m.id}),re.success("Photo removed")}catch{re.error("Failed to remove photo")}},be=async he=>{if(he.preventDefault(),!Q.city.trim()||!Q.state.trim()||!Q.price){re.error("Please fill in required fields (City, State, Price)");return}if(o&&!T){re.error("Please select an agent to assign this listing to");return}try{const ge={property_address:Q.property_address||null,city:Q.city,state:Q.state,neighborhood:Q.neighborhood||null,price:Number(Q.price),property_type:Q.property_type,status:Q.status,bedrooms:Q.bedrooms?Number(Q.bedrooms):null,bathrooms:Q.bathrooms?Number(Q.bathrooms):null,square_footage:Q.square_footage?Number(Q.square_footage):null,lot_size:Q.lot_size||null,year_built:Q.year_built?Number(Q.year_built):null,has_hoa:Q.has_hoa,description:Q.description||null,agent_notes:Q.agent_notes||null,agent_notes_public:Q.agent_notes_public,mls_link:Q.mls_link||null,video_link:Q.video_link||null,video_id:Q.video_id||null,co_agent_name:Q.co_agent_name||null,co_agent_email:Q.co_agent_email||null,co_agent_phone:Q.co_agent_phone||null,co_agent_brokerage:Q.co_agent_brokerage||null,co_agent_photo_url:Q.co_agent_photo_url||null,allow_sharing:Q.allow_sharing,open_to_referrals:Q.open_to_referrals,open_to_social_promotion:Q.open_to_social_promotion,share_with_brokerage:Q.share_with_brokerage,is_public:Q.site_only?!1:Q.is_public,site_only:Q.site_only,show_on_lead_site:Q.site_only?!0:Q.show_on_lead_site};if(l)await y.mutateAsync({id:s,...ge}),re.success("Listing updated!"),r(`/mission-control/listings/${s}`);else{I(!0);let ke;if(o&&T?ke=await x.mutateAsync({agentId:T,...ge}):ke=await f.mutateAsync(ge),R.length>0)try{await ce(ke.id),$.forEach(Me=>URL.revokeObjectURL(Me)),z([]),H([])}catch(Me){console.error("Photo upload error:",Me),re.error("Listing created but some photos failed to upload")}if(c.length>0)try{for(let Me=0;Mer(o?"/my-brokerage":"/mission-control/listings"),children:[e.jsx(Aa,{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(we,{children:[e.jsx(Tt,{children:e.jsx(It,{children:"Assign to Agent *"})}),e.jsxs(Ie,{children:[e.jsxs(Ns,{value:T,onValueChange:L,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select an agent..."})}),e.jsx(js,{children:A.map(he=>e.jsx(et,{value:he.id,children:he.name||he.email},he.id))})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"This listing will appear on the selected agent's Listing Exchange."})]})]}),!l&&i&&!o&&e.jsx(R$n,{onImport:ue}),c.length>0&&e.jsxs(we,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Tt,{className:"pb-3",children:[e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(pi,{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((he,ge)=>e.jsx("div",{className:"aspect-square rounded overflow-hidden bg-muted",children:e.jsx("img",{src:he,alt:"",className:"w-full h-full object-cover"})},ge)),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(U,{type:"button",variant:"ghost",size:"sm",className:"mt-2 text-destructive",onClick:()=>d([]),children:[e.jsx(er,{className:"h-3 w-3 mr-1"})," Clear MLS photos"]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(te,{children:"Property Address"}),e.jsx(xe,{value:Q.property_address,onChange:he=>le({...Q,property_address:he.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"City *"}),e.jsx(xe,{value:Q.city,onChange:he=>le({...Q,city:he.target.value}),placeholder:"City",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"State *"}),e.jsx(xe,{value:Q.state,onChange:he=>le({...Q,state:he.target.value}),placeholder:"State",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Neighborhood"}),e.jsx(xe,{value:Q.neighborhood,onChange:he=>le({...Q,neighborhood:he.target.value}),placeholder:"Neighborhood"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Price *"}),e.jsx(xe,{type:"number",value:Q.price,onChange:he=>le({...Q,price:he.target.value}),placeholder:"500000",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Property Type"}),e.jsxs(Ns,{value:Q.property_type,onValueChange:he=>le({...Q,property_type:he}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:B$n.map(he=>e.jsx(et,{value:he.value,children:he.label},he.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Status"}),e.jsxs(Ns,{value:Q.status,onValueChange:he=>le({...Q,status:he}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:z$n.map(he=>e.jsx(et,{value:he.value,children:he.label},he.value))})]})]})]})})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(te,{children:"Bedrooms"}),e.jsx(xe,{type:"number",value:Q.bedrooms,onChange:he=>le({...Q,bedrooms:he.target.value}),placeholder:"3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Bathrooms"}),e.jsx(xe,{type:"number",step:"0.5",value:Q.bathrooms,onChange:he=>le({...Q,bathrooms:he.target.value}),placeholder:"2"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Sq Ft"}),e.jsx(xe,{type:"number",value:Q.square_footage,onChange:he=>le({...Q,square_footage:he.target.value}),placeholder:"2000"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Lot Size"}),e.jsx(xe,{value:Q.lot_size,onChange:he=>le({...Q,lot_size:he.target.value}),placeholder:"0.25 acres"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Year Built"}),e.jsx(xe,{type:"number",value:Q.year_built,onChange:he=>le({...Q,year_built:he.target.value}),placeholder:"2005"})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(wn,{checked:Q.has_hoa,onCheckedChange:he=>le({...Q,has_hoa:he})}),e.jsx(te,{children:"Has HOA"})]})]})})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{children:"Description & Links"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Description"}),e.jsx(Fs,{value:Q.description,onChange:he=>le({...Q,description:he.target.value}),placeholder:"Tell the story of this property...",rows:4})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Agent Notes"}),e.jsx(Fs,{value:Q.agent_notes,onChange:he=>le({...Q,agent_notes:he.target.value}),placeholder:"Notes for other agents...",rows:2}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wn,{checked:Q.agent_notes_public,onCheckedChange:he=>le({...Q,agent_notes_public:he})}),e.jsx(te,{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(te,{children:"MLS Link"}),e.jsx(xe,{value:Q.mls_link,onChange:he=>le({...Q,mls_link:he.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Video Link"}),e.jsx(xe,{value:Q.video_link,onChange:he=>le({...Q,video_link:he.target.value}),placeholder:"YouTube or Vimeo URL"})]})]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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."}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Name"}),e.jsx(xe,{value:Q.co_agent_name,onChange:he=>le({...Q,co_agent_name:he.target.value}),placeholder:"Jordan Ellis"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Brokerage"}),e.jsx(xe,{value:Q.co_agent_brokerage,onChange:he=>le({...Q,co_agent_brokerage:he.target.value}),placeholder:"Brokerage name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Email"}),e.jsx(xe,{type:"email",value:Q.co_agent_email,onChange:he=>le({...Q,co_agent_email:he.target.value}),placeholder:"agent@email.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Phone"}),e.jsx(xe,{value:Q.co_agent_phone,onChange:he=>le({...Q,co_agent_phone:he.target.value}),placeholder:"(555) 123-4567"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-4",children:[Q.co_agent_photo_url?e.jsx("img",{src:Q.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(qa,{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:he=>{var ke;const ge=(ke=he.target.files)==null?void 0:ke[0];he.target.value="",ge&&Z(ge)}}),e.jsx(U,{type:"button",variant:"outline",disabled:V,onClick:()=>{var he;return(he=document.getElementById("co-agent-headshot"))==null?void 0:he.click()},children:V?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"})," Uploading…"]}):e.jsxs(e.Fragment,{children:[e.jsx(qa,{className:"h-4 w-4 mr-2"})," ",Q.co_agent_photo_url?"Replace photo":"Upload photo"]})}),Q.co_agent_photo_url&&e.jsxs(U,{type:"button",variant:"ghost",onClick:()=>le(he=>({...he,co_agent_photo_url:""})),children:[e.jsx(er,{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(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Wr,{className:"h-5 w-5"}),"Property Video"]})}),e.jsx(Ie,{children:e.jsx(D$n,{selectedVideoId:Q.video_id,onVideoSelect:he=>le({...Q,video_id:he}),listingId:l?s:void 0})})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{children:"Photos"})}),e.jsx(Ie,{children:l&&(m!=null&&m.photos)?e.jsx(BFt,{photos:m.photos,uploading:M,onUpload:he=>ie(he),onRemove:he=>je(he),onReorder:he=>{N.mutate({photos:he.map(ge=>({id:ge.id,sort_order:ge.sort_order,is_primary:ge.is_primary}))})},onSetPrimary:he=>{m&&S.mutate({photoId:he,listingId:m.id})}}):e.jsx(q$n,{photoUrls:$,onRemove:ne,onReorder:(he,ge)=>{H(he),z(ge)},pendingPhotos:R,uploading:M,onUpload:se})})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(pi,{className:"h-5 w-5"}),"Documents & Disclosures"]})}),e.jsx(Ie,{children:l&&s?e.jsx(F$n,{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(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(te,{children:"Allow Sharing"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other agents can share this listing"})]}),e.jsx(wn,{checked:Q.allow_sharing,onCheckedChange:he=>le({...Q,allow_sharing:he})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Open to Referrals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Accept buyer referrals"})]}),e.jsx(wn,{checked:Q.open_to_referrals,onCheckedChange:he=>le({...Q,open_to_referrals:he})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Social Promotion"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Can be promoted on social media"})]}),e.jsx(wn,{checked:Q.open_to_social_promotion,onCheckedChange:he=>le({...Q,open_to_social_promotion:he})})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Share with Brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents in your brokerage"})]}),e.jsx(wn,{checked:Q.share_with_brokerage,onCheckedChange:he=>le({...Q,share_with_brokerage:he})})]}),i&&e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(te,{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(wn,{checked:Q.site_only,onCheckedChange:he=>le({...Q,site_only:he,is_public:he?!1:Q.is_public,show_on_lead_site:he?!0:Q.show_on_lead_site,share_with_brokerage:he?!1:Q.share_with_brokerage})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Make Public"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Publish on listings.relevelup.com to get leads"})]}),e.jsx(wn,{checked:Q.is_public,disabled:Q.site_only,onCheckedChange:he=>le({...Q,is_public:he})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Show on My Website"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Q.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(wn,{checked:Q.show_on_lead_site,onCheckedChange:he=>le({...Q,show_on_lead_site:he})})]})]})]}),e.jsx(U,{type:"submit",className:"w-full",size:"lg",disabled:f.isPending||y.isPending,children:f.isPending||y.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):l?"Update Listing":"Create Listing"})]})]})]}),e.jsx(UQe,{listingId:u.listingId,open:u.open,onOpenChange:he=>{if(!he){const{nextPath:ge}=u;h({open:!1,listingId:null,nextPath:ge}),r(ge)}}})]})}const rKe=[{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"}],bJt=[{type:"extra_video",label:"Extra Video / Reel",icon:Wr,desc:"Add a YouTube, Vimeo, or MP4 embed",accent:"from-rose-500/20 to-rose-500/5"},{type:"tour_3d",label:"3D Tour",icon:CX,desc:"Matterport, iGuide, or Kuula embed",accent:"from-indigo-500/20 to-indigo-500/5"},{type:"floor_plans",label:"Floor Plans",icon:pc,desc:"Upload floor plan images",accent:"from-sky-500/20 to-sky-500/5"},{type:"testimonial",label:"Testimonial",icon:tS,desc:"A quote from a past client",accent:"from-amber-500/20 to-amber-500/5"},{type:"countdown",label:"Offer Countdown",icon:Yr,desc:'"Offers due Friday 5pm"',accent:"from-emerald-500/20 to-emerald-500/5"},{type:"custom_cta",label:"Custom CTA Button",icon:Rc,desc:"Link to a brochure or booking page",accent:"from-violet-500/20 to-violet-500/5"}],$$n=["#0f172a","#406E71","#c9a84c","#b91c1c","#0d7a5f","#4f46e5","#e85d3a","#111827"],q9e={sections:Object.fromEntries(rKe.map(s=>[s.key,!0])),hero_style:"photo",accent_color:null,custom_note:"",addons:[]},V$n=()=>Math.random().toString(36).slice(2,10);function H$n(){const{listingId:s}=Di(),t=Wn(),{user:n}=vs(),r=Qt(),[a,i]=j.useState("desktop"),[l,o]=j.useState(q9e),[c,d]=j.useState(!1),[u,h]=j.useState(0),{data:m,isLoading:p}=ct({queryKey:["listing-customize",s],queryFn:async()=>{const{data:R,error:z}=await q.from("listings").select("id, agent_id, slug, property_address, city, state, price, page_config, page_theme").eq("id",s).single();if(z)throw z;return R},enabled:!!s});j.useEffect(()=>{var R,z;m!=null&&m.page_config&&o({...q9e,...m.page_config||{},sections:{...q9e.sections,...((R=m.page_config)==null?void 0:R.sections)||{}},addons:((z=m.page_config)==null?void 0:z.addons)||[]})},[m==null?void 0:m.id]);const f=!!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=yt({mutationFn:async()=>{const{error:R}=await q.from("listings").update({page_config:l}).eq("id",s);if(R)throw R},onSuccess:()=>{re.success("Saved. Your public page is live."),d(!1),r.invalidateQueries({queryKey:["listing-customize",s]}),r.invalidateQueries({queryKey:["public-listing"]}),h(R=>R+1)},onError:R=>re.error(`Save failed: ${R.message||"Try again"}`)}),b=R=>{o(z=>({...z,...R})),d(!0)},N=(R,z)=>b({sections:{...l.sections||{},[R]:z}}),S=R=>b({addons:[...l.addons||[],{id:V$n(),type:R,data:{}}]}),A=(R,z)=>b({addons:(l.addons||[]).map($=>$.id===R?{...$,data:{...$.data,...z}}:$)}),T=R=>b({addons:(l.addons||[]).filter(z=>z.id!==R)}),L=(R,z)=>{const $=[...l.addons||[]],H=$.findIndex(K=>K.id===R);if(H<0)return;const V=H+z;V<0||V>=$.length||([$[H],$[V]]=[$[V],$[H]],b({addons:$}))};if(p)return e.jsx(qs,{title:"",description:"",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading…"})});if(!m)return e.jsx(qs,{title:"",description:"",children:e.jsx("div",{className:"p-8",children:"Listing not found."})});if(!f)return e.jsx(qs,{title:"",description:"",children:e.jsxs("div",{className:"p-8",children:[e.jsx("p",{children:"You can only customize your own listing pages."}),e.jsx(U,{className:"mt-3",onClick:()=>t(`/mission-control/listings/${m.id}`),children:"Back"})]})});const M=(l.addons||[]).length,I=Object.values(l.sections||{}).filter(Boolean).length;return e.jsxs(qs,{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(U,{variant:"ghost",size:"sm",onClick:()=>t(`/mission-control/listings/${m.id}`),children:[e.jsx(Aa,{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(X2,{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(i1,{className:"h-3.5 w-3.5"})," Mobile"]})]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>h(R=>R+1),children:[e.jsx(no,{className:"h-3.5 w-3.5 mr-1.5"})," Refresh"]}),e.jsx(U,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Sr,{className:"h-3.5 w-3.5 mr-1.5"})," Open live"]})}),e.jsx(U,{size:"sm",onClick:()=>v.mutate(),disabled:!c||v.isPending,children:v.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(Ho,{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(Gi,{className:"lg:h-[calc(100vh-140px)] pr-2",children:e.jsxs("div",{className:"space-y-6 pb-16",children:[e.jsx(IY,{icon:e.jsx(cn,{className:"h-4 w-4"}),title:"Hero",desc:"What visitors see first",children:e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Hero style"}),e.jsx("div",{className:"mt-2 grid grid-cols-3 gap-2",children:["photo","video","slideshow"].map(R=>e.jsx("button",{onClick:()=>b({hero_style:R}),className:`text-xs rounded-lg border py-3 capitalize transition ${l.hero_style===R?"border-primary bg-primary/5 text-primary font-medium":"border-border hover:bg-muted"}`,children:R},R))})]})}),e.jsx(IY,{icon:e.jsx($c,{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"}),$$n.map(R=>e.jsx("button",{onClick:()=>b({accent_color:R}),className:`h-9 w-9 rounded-full border-2 transition ${l.accent_color===R?"ring-2 ring-offset-2 ring-primary border-white":"border-white/20"}`,style:{background:R},"aria-label":R},R))]})}),e.jsx(IY,{icon:e.jsx(Lg,{className:"h-4 w-4"}),title:"Personal note",desc:"Shows in a beautiful callout on the public page",children:e.jsx(Fs,{value:l.custom_note||"",onChange:R=>b({custom_note:R.target.value}),placeholder:"Why we love this home… (optional)",rows:3})}),e.jsx(IY,{icon:e.jsx(LC,{className:"h-4 w-4"}),title:"Page sections",desc:"Toggle any default section on or off",rightLabel:`${I} of ${rKe.length} on`,children:e.jsx("div",{className:"divide-y rounded-xl border",children:rKe.map(R=>{var $;const z=(($=l.sections)==null?void 0:$[R.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:R.label}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:R.hint})]}),e.jsx(wn,{checked:z,onCheckedChange:H=>N(R.key,H)})]},R.key)})})}),e.jsxs(IY,{icon:e.jsx(an,{className:"h-4 w-4"}),title:"Add-on modules",desc:"Drop in extras to make this page unique",rightLabel:M?`${M} added`:void 0,children:[e.jsx("div",{className:"grid grid-cols-2 gap-2",children:bJt.map(R=>e.jsxs("button",{onClick:()=>S(R.type),className:`group text-left rounded-xl border p-3 hover:shadow-md transition bg-gradient-to-br ${R.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(R.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-sm font-medium",children:R.label})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug",children:R.desc})]},R.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((R,z)=>e.jsx(G$n,{addon:R,onChange:$=>A(R.id,$),onRemove:()=>T(R.id),onMoveUp:z>0?()=>L(R.id,-1):void 0,onMoveDown:zL(R.id,1):void 0},R.id))]})]}),e.jsx("div",{className:"lg:hidden",children:e.jsx(U,{className:"w-full",onClick:()=>v.mutate(),disabled:!c||v.isPending,children:v.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(Ho,{className:"h-4 w-4 mr-1.5"})," Save & Publish"]})})})]})}),e.jsx("div",{className:"lg:h-[calc(100vh-140px)]",children:e.jsxs(we,{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(xa,{className:"h-3.5 w-3.5"}),"Live preview",c&&e.jsx(Be,{variant:"outline",className:"text-[10px] border-amber-400 text-amber-700 bg-amber-50 ml-1",children:"Save to update"}),!c&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-emerald-600 ml-1",children:[e.jsx(Xr,{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(X2,{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(i1,{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 IY({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 G$n({addon:s,onChange:t,onRemove:n,onMoveUp:r,onMoveDown:a}){const i=bJt.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(kf,{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(U,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:a,"aria-label":"Move down",children:e.jsx(kf,{className:"h-3.5 w-3.5 rotate-180"})}),e.jsx(U,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:n,"aria-label":"Remove",children:e.jsx(In,{className:"h-3.5 w-3.5"})})]})]}),s.type==="extra_video"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs",children:"Video URL"}),e.jsx(xe,{placeholder:"https://youtu.be/…",value:s.data.url||"",onChange:o=>t({url:o.target.value})}),e.jsx(te,{className:"text-xs",children:"Title (optional)"}),e.jsx(xe,{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(te,{className:"text-xs",children:"3D tour embed URL"}),e.jsx(xe,{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(te,{className:"text-xs",children:"Floor plan image URLs (one per line)"}),e.jsx(Fs,{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(te,{className:"text-xs",children:"Quote"}),e.jsx(Fs,{rows:3,placeholder:`"Best home-buying experience we've ever had."`,value:s.data.quote||"",onChange:o=>t({quote:o.target.value})}),e.jsx(te,{className:"text-xs",children:"Attribution"}),e.jsx(xe,{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(te,{className:"text-xs",children:"Headline"}),e.jsx(xe,{placeholder:"Offers due",value:s.data.headline||"",onChange:o=>t({headline:o.target.value})}),e.jsx(te,{className:"text-xs",children:"Deadline (date & time)"}),e.jsx(xe,{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(te,{className:"text-xs",children:"Button label"}),e.jsx(xe,{placeholder:"Download brochure",value:s.data.label||"",onChange:o=>t({label:o.target.value})}),e.jsx(te,{className:"text-xs",children:"Link URL"}),e.jsx(xe,{placeholder:"https://…",value:s.data.url||"",onChange:o=>t({url:o.target.value})})]})]})}const _Jt="teleprompter_settings",$9e={scrollSpeed:30,fontSize:24,lineHeight:1.6,opacity:.85,position:"top",isMirrored:!1};function W$n(){try{const s=localStorage.getItem(_Jt);return s?{...$9e,...JSON.parse(s)}:$9e}catch{return $9e}}function K$n(s){try{localStorage.setItem(_Jt,JSON.stringify(s))}catch{}}function Pnt({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(W$n),{scrollSpeed:p,fontSize:f,lineHeight:x,opacity:y,position:v,isMirrored:b}=h,N=j.useCallback(($,H)=>{m(V=>{const K={...V,[$]:H};return K$n(K),K})},[]),[S,A]=j.useState(!1),[T,L]=j.useState(null),M=j.useCallback($=>{if(!o.current)return;d.current===0&&(d.current=$);const H=$-d.current;d.current=$,u.current+=p*H/1e3;const V=Math.floor(u.current);V>0&&(o.current.scrollTop+=V,u.current-=V);const{scrollTop:K,scrollHeight:Z,clientHeight:Q}=o.current;if(K+Q>=Z){A(!1);return}c.current=requestAnimationFrame(M)},[p]);j.useEffect(()=>(S?(d.current=0,u.current=0,c.current=requestAnimationFrame(M)):c.current&&cancelAnimationFrame(c.current),()=>{c.current&&cancelAnimationFrame(c.current)}),[S,M]),j.useEffect(()=>{if(r&&t)if(o.current&&(o.current.scrollTop=0),a){L(3);let $=3;const H=setInterval(()=>{$-=1,$<=0?(clearInterval(H),L(null),i==null||i(),A(!0)):L($)},1e3);return()=>clearInterval(H)}else setTimeout(()=>A(!0),100);else r||(A(!1),L(null))},[r,t,a,i]);const I=j.useCallback(()=>{o.current&&(o.current.scrollTop=0),A(!1)},[]),R=j.useCallback(()=>{A($=>!$)},[]);if(!t)return e.jsx("div",{className:Mt("absolute top-4 right-4 pointer-events-auto z-10",l),children:e.jsxs(U,{variant:"secondary",size:"sm",onClick:n,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(xa,{className:"h-4 w-4 mr-2"}),"Show Script"]})});const z={top:"top-0 pt-16",center:"top-1/2 -translate-y-1/2",bottom:"bottom-0 pb-24"};return e.jsxs("div",{className:Mt("absolute inset-0 pointer-events-none",l),children:[T!==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:T},T),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),e.jsx("div",{className:Mt("absolute left-0 right-0 h-[60%] overflow-hidden pointer-events-auto",z[v],T!==null&&"opacity-30"),style:{opacity:T!==null?.3:y},children:e.jsxs("div",{ref:o,className:Mt("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:`${f}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(md,{children:[e.jsx(pd,{asChild:!0,children:e.jsx(U,{variant:"secondary",size:"icon",className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(qc,{className:"h-4 w-4"})})}),e.jsx(id,{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(te,{className:"text-xs",children:"Scroll Speed"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p})]}),e.jsx(rg,{value:[p],onValueChange:([$])=>N("scrollSpeed",$),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(te,{className:"text-xs",children:"Font Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[f,"px"]})]}),e.jsx(rg,{value:[f],onValueChange:([$])=>N("fontSize",$),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(te,{className:"text-xs",children:"Line Spacing"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x.toFixed(1)})]}),e.jsx(rg,{value:[x*10],onValueChange:([$])=>N("lineHeight",$/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(te,{className:"text-xs",children:"Opacity"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Math.round(y*100),"%"]})]}),e.jsx(rg,{value:[y*100],onValueChange:([$])=>N("opacity",$/100),min:30,max:100,step:5})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs",children:"Position"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(U,{variant:v==="top"?"default":"outline",size:"sm",onClick:()=>N("position","top"),children:e.jsx(dv,{className:"h-4 w-4"})}),e.jsx(U,{variant:v==="center"?"default":"outline",size:"sm",onClick:()=>N("position","center"),children:e.jsx(Z2,{className:"h-4 w-4"})}),e.jsx(U,{variant:v==="bottom"?"default":"outline",size:"sm",onClick:()=>N("position","bottom"),children:e.jsx(rl,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{className:"text-xs",children:"Mirror Mode"}),e.jsx(wn,{checked:b,onCheckedChange:$=>N("isMirrored",$)})]})]})})]}),e.jsx(U,{variant:"secondary",size:"icon",onClick:R,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:S?e.jsx(uv,{className:"h-4 w-4"}):e.jsx(lu,{className:"h-4 w-4"})}),e.jsx(U,{variant:"secondary",size:"icon",onClick:I,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(Kg,{className:"h-4 w-4"})}),e.jsxs(U,{variant:"secondary",size:"sm",onClick:n,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(Vg,{className:"h-4 w-4 mr-2"}),"Hide"]})]})]})}function Y$n({onSelectScript:s,onCreateNew:t,selectedScriptId:n,className:r}){const{toast:a}=Ai(),[i,l]=j.useState(""),[o,c]=j.useState(null),[d,u]=j.useState("levelup"),{data:h,isLoading:m}=NIn(),{data:p,isLoading:f}=kIn(),{data:x,isLoading:y}=SIn(),v=CIn(),b=j.useMemo(()=>p?p.filter(L=>{const M=!i||L.title.toLowerCase().includes(i.toLowerCase())||L.script_text.toLowerCase().includes(i.toLowerCase())||L.tags.some(R=>R.toLowerCase().includes(i.toLowerCase())),I=!o||L.category_id===o;return M&&I}):[],[p,i,o]),N=j.useMemo(()=>x?x.filter(L=>!i||L.title.toLowerCase().includes(i.toLowerCase())||L.script_text.toLowerCase().includes(i.toLowerCase())):[],[x,i]),S=L=>{s({title:L.title,text:L.script_text})},A=async L=>{try{await v.mutateAsync(L),a({title:"Script saved to My Scripts"})}catch{a({title:"Failed to save script",variant:"destructive"})}},T=m||f||y;return e.jsxs("div",{className:Mt("flex flex-col h-full",r),children:[e.jsx("div",{className:"p-4 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search scripts...",value:i,onChange:L=>l(L.target.value),className:"pl-9"})]})}),e.jsxs(oa,{value:d,onValueChange:L=>u(L),className:"flex-1 flex flex-col",children:[e.jsxs(la,{className:"mx-4 mt-4 grid grid-cols-2",children:[e.jsxs(Kt,{value:"levelup",children:[e.jsx(Ur,{className:"h-4 w-4 mr-2"}),"LevelUp Scripts"]}),e.jsxs(Kt,{value:"my-scripts",children:[e.jsx(u0,{className:"h-4 w-4 mr-2"}),"My Scripts"]})]}),e.jsxs(Zt,{value:"levelup",className:"flex-1 flex flex-col mt-0 p-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 mb-4",children:[e.jsx(Be,{variant:o?"outline":"default",className:"cursor-pointer",onClick:()=>c(null),children:"All"}),h==null?void 0:h.map(L=>e.jsx(Be,{variant:o===L.id?"default":"outline",className:"cursor-pointer",onClick:()=>c(L.id),children:L.name},L.id))]}),e.jsx(Gi,{className:"flex-1 max-h-[50vh]",children:T?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Et,{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(Ur,{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(L=>e.jsxs(we,{className:Mt("cursor-pointer hover:bg-accent/50 transition-colors",n===L.id&&"ring-2 ring-primary"),onClick:()=>S(L),children:[e.jsx(Tt,{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(It,{className:"text-sm font-medium truncate",children:L.title}),L.category&&e.jsx(Be,{variant:"secondary",className:"mt-1 text-xs",children:L.category.name})]}),e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:M=>{M.stopPropagation(),A(L)},children:e.jsx(u0,{className:"h-4 w-4"})}),e.jsx(gi,{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:L.script_text})})]},L.id))})})]}),e.jsxs(Zt,{value:"my-scripts",className:"flex-1 flex flex-col mt-0 p-4",children:[t&&e.jsxs(U,{variant:"outline",className:"mb-4",onClick:t,children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Create New Script"]}),e.jsx(Gi,{className:"flex-1 max-h-[50vh]",children:y?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Et,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):N.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(u0,{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:N.map(L=>e.jsxs(we,{className:Mt("cursor-pointer hover:bg-accent/50 transition-colors",n===L.id&&"ring-2 ring-primary"),onClick:()=>S(L),children:[e.jsx(Tt,{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(It,{className:"text-sm font-medium truncate",children:L.title}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:L.is_custom?e.jsx(Be,{variant:"outline",className:"text-xs",children:"Custom"}):e.jsx(Be,{variant:"secondary",className:"text-xs",children:"Saved"})})]}),e.jsx(gi,{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:L.script_text})})]},L.id))})})]})]})]})}function Z$n({selectedTemplate:s,onSelect:t,contactName:n,saving:r=!1}){const[a,i]=j.useState(()=>{const o=Dq(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(te,{className:"text-sm font-medium",children:"Share Page Template"}),r&&e.jsx(Et,{className:"h-3 w-3 animate-spin text-muted-foreground"})]}),e.jsx("div",{className:"space-y-3",children:uOs.map(o=>{const c=hOs(o.id),d=a.has(o.id),u=c.some(h=>h.id===s);return e.jsxs(ub,{open:d,onOpenChange:()=>l(o.id),children:[e.jsxs(hb,{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(rl,{className:Mt("h-4 w-4 text-muted-foreground transition-transform",d&&"rotate-180")})]}),e.jsx(mb,{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:Mt("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(Xr,{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: "',Dq(s).headerText(n),'"']})]})}function wJt({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"),[p,f]=j.useState([]),[x,y]=j.useState(n.contact_id&&r?{id:n.contact_id,name:r,email:null}:null),[v,b]=j.useState(!1),[N,S]=j.useState(!1),A=n.share_token?`https://video.relevelup.com/${n.share_token}`:"";j.useEffect(()=>{s&&p.length===0&&T()},[s]);const T=async()=>{S(!0);try{const{data:K,error:Z}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(Z)throw Z;const Q=(K||[]).map(le=>({id:le.id,name:[le.first_name,le.last_name].filter(Boolean).join(" ")||"Unnamed",email:le.email||null}));f(Q)}catch(K){console.error("Failed to fetch contacts:",K)}finally{S(!1)}},L=async K=>{y(K),b(!1),c(!0);try{const{error:Z}=await q.from("agent_videos").update({contact_id:(K==null?void 0:K.id)||null,recipient_name:(K==null?void 0:K.name)||null}).eq("id",n.id);if(Z)throw Z;re.success(K?`Assigned to ${K.name}`:"Contact removed"),a==null||a()}catch(Z){console.error("Failed to update contact:",Z),re.error("Failed to update contact")}finally{c(!1)}},M=async K=>{l(K),c(!0);try{const{error:Z}=await q.from("agent_videos").update({page_template:K}).eq("id",n.id);if(Z)throw Z;m(K),re.success("Template saved!"),a==null||a()}catch(Z){console.error("Failed to save template:",Z),re.error("Failed to save template"),l(h)}finally{c(!1)}},I=(x==null?void 0:x.name)||null,R=()=>{const K=n.title||"Video Message",Z=n.share_token?`https://video.relevelup.com/thumb/${n.share_token}`:n.thumbnail_url||"";return``},z=async()=>{if(!n.thumbnail_url){re.error("Video thumbnail not available yet");return}const K=R(),Z=`Watch: ${n.title||"Video Message"} ${A}`;try{const Q=new Blob([K],{type:"text/html"}),le=new Blob([Z],{type:"text/plain"}),ue=new ClipboardItem({"text/html":Q,"text/plain":le});await navigator.clipboard.write([ue]),re.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(Z+` `+K),re.success("Copied! Paste into your email.")}},$=async()=>{await navigator.clipboard.writeText(A),u(!0),re.success("Share link copied!"),setTimeout(()=>u(!1),2e3)},H=()=>{const Z=Dq(i).headerText(I),Q=i==="default"?`Check out this video: ${A}`:`${Z} Check out this special video: ${A}`;window.open(`sms:?body=${encodeURIComponent(Q)}`,"_self")},V=()=>{const K=Dq(i),Z=K.headerText(I),Q=i==="default"?n.title||"Video Message":Z,le=`${K.subText} Watch the video: ${A}`,ue=x!=null&&x.email?encodeURIComponent(x.email):"";window.open(`mailto:${ue}?subject=${encodeURIComponent(Q)}&body=${encodeURIComponent(le)}`,"_self")};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Rc,{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(te,{className:"text-sm font-medium",children:"Personalize for Contact (Optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(md,{open:v,onOpenChange:b,children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{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(So,{className:"h-4 w-4 text-muted-foreground"}),x.name]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(Jw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(id,{className:"w-[300px] p-0",align:"start",children:e.jsxs(pj,{children:[e.jsx(fj,{placeholder:"Search contacts..."}),e.jsxs(gj,{children:[e.jsx(xj,{children:N?"Loading...":"No contacts found."}),e.jsx(I_,{children:p.map(K=>e.jsxs(e1,{value:K.name,onSelect:()=>L(K),children:[e.jsx(Xr,{className:Mt("mr-2 h-4 w-4",(x==null?void 0:x.id)===K.id?"opacity-100":"opacity-0")}),K.name]},K.id))})]})]})})]}),x&&e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>L(null),disabled:o,className:"shrink-0",children:e.jsx(er,{className:"h-4 w-4"})})]}),x&&i!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Page will show: "',Dq(i).headerText(x.name),'"']})]}),e.jsx(Z$n,{selectedTemplate:i,onSelect:M,contactName:I,saving:o}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Share Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:A,readOnly:!0,className:"font-mono text-sm"}),e.jsx(U,{onClick:$,variant:d?"default":"outline",className:"shrink-0 gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Xr,{className:"h-4 w-4"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Pa,{className:"h-4 w-4"}),"Copy"]})})]})]}),n.thumbnail_url&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Share for Email"}),e.jsxs(U,{variant:"outline",className:"w-full gap-2",onClick:z,children:[e.jsx(pc,{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(te,{children:"Quick Share"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{variant:"outline",className:"flex-1 gap-2",onClick:H,children:[e.jsx(Ki,{className:"h-4 w-4"}),"Text"]}),e.jsxs(U,{variant:"outline",className:"flex-1 gap-2",onClick:V,children:[e.jsx(ln,{className:"h-4 w-4"}),"Email"]})]})]})]}),e.jsx(Mr,{children:e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Done"})})]})})}function X$n(){var Ve;const s=Wn(),[t]=fc(),{toast:n}=Ai(),r=t.get("contact_id"),a=t.get("task_id"),{canRecord:i,remainingMb:l,usagePercent:o,isNearLimit:c,storage:d}=nWt(),{data:u}=Cb(),h=f3(),m=PIn(),[p,f]=j.useState("record"),[x,y]=j.useState(""),[v,b]=j.useState(!1),[N,S]=j.useState(!1),[A,T]=j.useState(!1),[L,M]=j.useState(null),[I,R]=j.useState(0),[z,$]=j.useState(0),[H,V]=j.useState(null),[K,Z]=j.useState(null),[Q,le]=j.useState(r||""),[ue,se]=j.useState(""),[ne,ie]=j.useState(""),[ce,je]=j.useState(null),[be,he]=j.useState(null),[ge,ke]=j.useState(null),[Te,Me]=j.useState(!1),Oe=j.useCallback(async(qe,Ze)=>{M(qe),f("uploading");try{const{videoId:Ue,uploadUrl:Ye}=await cL(ue||"Quick Video Touch");V(Ue);const{apiKey:Ge}=await dL(Ue),He=new XMLHttpRequest;He.upload.onprogress=qt=>{qt.lengthComputable&&R(qt.loaded/qt.total*100)},await new Promise((qt,Ut)=>{He.onload=()=>{He.status>=200&&He.status<300?qt():Ut(new Error(`Upload failed: ${He.status}`))},He.onerror=()=>Ut(new Error("Upload failed")),He.open("PUT",Ye),He.setRequestHeader("AccessKey",Ge),He.send(qe)}),f("processing");let tt=0;const pt=Date.now(),ft=90*1e3;for(;tt<4;){if(await new Promise(Ut=>setTimeout(Ut,3e3)),Date.now()-pt>ft){const Ut=qe.size/1048576,Wt=`https://iframe.mediadelivery.net/play/${Ue}/${Ue}`;await h.mutateAsync({bunny_video_id:Ue,playback_url:Wt,file_size_mb:Ut,title:ue||"Quick Video Touch",notes:ne||void 0,contact_id:Q&&Q!=="none"?Q: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 qt=await fN(Ue);if(tt=qt.status,$(qt.encodeProgress||0),tt===4)Z({playbackUrl:qt.directPlayUrl,thumbnailUrl:qt.thumbnailUrl,previewUrl:qt.previewUrl||null,duration:qt.length||Ze,fileSizeMb:(qt.storageSize||qe.size)/(1024*1024)});else if(tt===5||tt===6)throw new Error("Video processing failed")}f("details")}catch(Ue){console.error("Upload error:",Ue),n({title:"Upload failed",description:"Please try recording again.",variant:"destructive"}),f("record")}},[ue,n]),Se=async()=>{if(!(!H||!K))try{const qe=Q&&Q!=="none"?Q:null,Ze=await h.mutateAsync({bunny_video_id:H,contact_id:qe,playback_url:K.playbackUrl,thumbnail_url:K.thumbnailUrl,preview_url:K.previewUrl,duration_seconds:K.duration,file_size_mb:K.fileSizeMb,title:ue||"Quick Video Touch",notes:ne,task_id:a||null,status:"ready"});je(Ze.id),he(Ze.share_token||null),qe&&await m.mutateAsync({contactId:qe,videoId:Ze.id,notes:ne}),n({title:"Video saved successfully!"}),f("share")}catch(qe){console.error("Save video error:",qe),n({title:"Failed to save video",description:(qe==null?void 0:qe.message)||"Please try again.",variant:"destructive"})}},Qe=(qe,Ze)=>{navigator.clipboard.writeText(Ze),ke(qe),setTimeout(()=>ke(null),2e3),n({title:"Copied to clipboard!"})},Ae=()=>be?`https://video.relevelup.com/${be}`:(K==null?void 0:K.playbackUrl)||"",Fe=()=>{const qe=u==null?void 0:u.find(He=>He.id===Q),Ze=qe?`${qe.first_name}`:"",Ue=(qe==null?void 0:qe.phone)||"",Ye=(qe==null?void 0:qe.email)||"",Ge=Ae();return{text:`Hey${Ze?` ${Ze}`:""}! I recorded a quick video for you: ${Ge}`,link:Ge,contactPhone:Ue,contactEmail:Ye}},Ne=()=>{const{text:qe,contactPhone:Ze}=Fe(),Ue=Ze?`sms:${Ze}?body=${encodeURIComponent(qe)}`:`sms:?body=${encodeURIComponent(qe)}`;window.open(Ue,"_self")},$e=()=>{const{link:qe,contactEmail:Ze}=Fe(),Ue="Check out this video",Ye=`I recorded a quick video for you: ${qe}`,Ge=Ze?`mailto:${Ze}?subject=${encodeURIComponent(Ue)}&body=${encodeURIComponent(Ye)}`:`mailto:?subject=${encodeURIComponent(Ue)}&body=${encodeURIComponent(Ye)}`;window.open(Ge,"_self")};return i?e.jsx(qs,{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(U,{variant:"ghost",size:"icon",onClick:()=>s(-1),children:e.jsx(Aa,{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(U,{variant:"outline",size:"sm",onClick:()=>s("/mission-control/video-library"),className:"gap-1.5",children:[e.jsx(Ur,{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"]})]})]})]}),p==="record"&&e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2",children:[e.jsx(kE,{maxDurationSeconds:600,onRecordingComplete:Oe,onRecordingStateChange:T,className:"w-full",teleprompterContent:v&&x&&e.jsx(Pnt,{text:x,isVisible:v,onToggleVisibility:()=>b(!1),isRecording:A,startCountdown:!1})}),!v&&x&&e.jsxs(U,{variant:"outline",className:"mt-4",onClick:()=>b(!0),children:[e.jsx(Ur,{className:"h-4 w-4 mr-2"}),"Show Teleprompter"]})]}),e.jsxs(we,{className:"lg:col-span-1",children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{className:"text-lg",children:"Teleprompter Script"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx(Fs,{placeholder:"Type or paste your script here...",value:x,onChange:qe=>y(qe.target.value),rows:6}),e.jsxs(my,{open:N,onOpenChange:S,children:[e.jsx($ne,{asChild:!0,children:e.jsxs(U,{variant:"outline",className:"w-full",children:[e.jsx(Ur,{className:"h-4 w-4 mr-2"}),"Browse Scripts"]})}),e.jsxs(g0,{side:"right",className:"w-[400px] sm:w-[540px] p-0",children:[e.jsx(vv,{className:"p-4 border-b",children:e.jsx(bv,{children:"Select a Script"})}),e.jsx(Y$n,{onSelectScript:qe=>{y(qe.text),S(!1),b(!0)},className:"h-[calc(100vh-80px)]"})]})]}),x&&e.jsx(U,{className:"w-full",onClick:()=>b(!0),children:"Use Script"})]})]})]}),p==="uploading"&&e.jsx(we,{className:"max-w-md mx-auto",children:e.jsxs(Ie,{className:"pt-6 text-center",children:[e.jsx(qa,{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(ro,{value:I,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[I.toFixed(0),"%"]})]})}),p==="processing"&&e.jsx(we,{className:"max-w-md mx-auto",children:e.jsxs(Ie,{className:"pt-6 text-center space-y-4",children:[e.jsx(Et,{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(ro,{value:z,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[z.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.`})]})}),p==="details"&&e.jsxs(we,{className:"max-w-lg mx-auto",children:[e.jsx(Tt,{children:e.jsx(It,{children:"Video Details"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Title"}),e.jsx(xe,{value:ue,onChange:qe=>se(qe.target.value),placeholder:"Quick Video Touch"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Attach to Contact (Optional)"}),e.jsxs(Ns,{value:Q,onValueChange:le,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"No contact - use anywhere"})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Rc,{className:"h-4 w-4"}),"No contact - use anywhere"]})}),u==null?void 0:u.map(qe=>e.jsx(et,{value:qe.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(So,{className:"h-4 w-4"}),qe.first_name," ",qe.last_name]})},qe.id))]})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Notes"}),e.jsx(Fs,{value:ne,onChange:qe=>ie(qe.target.value),placeholder:"Add notes about this video...",rows:3})]}),e.jsxs(U,{className:"w-full",onClick:Se,disabled:h.isPending,children:[h.isPending&&e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Video"]})]})]}),p==="share"&&e.jsxs(we,{className:"max-w-lg mx-auto",children:[e.jsx(Tt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Xr,{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(U,{variant:"outline",className:"justify-start",onClick:Ne,children:[e.jsx(Ki,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),e.jsxs(U,{variant:"outline",className:"justify-start",onClick:$e,children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(U,{variant:"outline",className:"justify-start",onClick:()=>Qe("link",Fe().link),children:[e.jsx(Rc,{className:"h-4 w-4 mr-2"}),"Copy Video Link",ge==="link"&&e.jsx(Xr,{className:"h-4 w-4 ml-auto text-green-500"})]}),e.jsxs(U,{variant:"outline",className:"justify-start",onClick:()=>Me(!0),children:[e.jsx($c,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx(U,{variant:"outline",onClick:()=>s("/mission-control/video-library"),children:"View Library"}),e.jsx(U,{onClick:()=>{f("record"),M(null),V(null),Z(null)},children:"Record Another"})]})]})]}),ce&&be&&e.jsx(wJt,{open:Te,onOpenChange:Me,video:{id:ce,share_token:be,title:ue||null,contact_id:Q||null,thumbnail_url:(K==null?void 0:K.thumbnailUrl)||null},contactName:((Ve=u==null?void 0:u.find(qe=>qe.id===Q))==null?void 0:Ve.first_name)||null})]})}):e.jsx(qs,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center py-12",children:[e.jsx(tc,{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(U,{onClick:()=>s("/mission-control/video-library"),children:"Open Video Library"})]})})}function Q$n({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,p]=j.useState(!1),[f,x]=j.useState(""),[y,v]=j.useState(""),[b,N]=j.useState(""),[S,A]=j.useState(!1),T=QGt(),L=n.share_token?`https://video.relevelup.com/share/video/${n.share_token}`:"",M=n.share_token?`https://video.relevelup.com/thumb/${n.share_token}`:a||n.thumbnail_url||"",I=n.title||"Video Message";j.useEffect(()=>{s&&l.length===0&&R()},[s]),j.useEffect(()=>{if(s&&(v(`I recorded a video for you — ${I}`),N("Hey! I recorded a quick video just for you. Click below to watch it:"),d(null),x(""),n.contact_id)){const Z=l.find(Q=>Q.id===n.contact_id);Z&&(d(Z),x(Z.email||""))}},[s,n.contact_id,l]);const R=async()=>{p(!0);try{const{data:Z,error:Q}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(Q)throw Q;o(Z||[])}catch{console.error("Failed to fetch contacts")}finally{p(!1)}},z=Z=>{d(Z),h(!1),x(Z.email||""),N(`Hey ${Z.first_name}! I recorded a quick video just for you. Click below to watch it:`),v(`I recorded a video for you — ${I}`)},$=()=>{d(null),x(""),N("Hey! I recorded a quick video just for you. Click below to watch it:")},H=Z=>{const Q=`${Z.first_name||""} ${Z.last_name||""}`.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim();return Q?Q.length>60?`${Q.slice(0,60)}…`:Q:Z.email||"Unnamed contact"},V=Z=>{const Q=b.split(/\n\n+/).map(se=>`

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

`).join(""),le=Z?eWt(Z):L,ue=Z?``:"";return`
${Q}

▶ Watch Video

${ue}
`},K=async()=>{var Z;if(!f){re.error("Please enter a recipient email");return}if(!L){re.error("Video does not have a share link");return}A(!0);try{let Q;try{const ie=c?H(c):f.split("@")[0];Q=(await T.mutateAsync({video_id:n.id,recipient_email:f,recipient_name:ie,contact_id:(c==null?void 0:c.id)||null,sent_via:"gmail"})).share_token}catch(ie){console.warn("Failed to create tracking record, sending without tracking:",ie)}const le=V(Q),{data:ue,error:se}=await q.functions.invoke("gmail-send",{body:{to:f,subject:y,body:le,contactId:(c==null?void 0:c.id)||null}});let ne=null;if(se&&((Z=se.context)!=null&&Z.json))try{ne=await se.context.json()}catch{}if((ne==null?void 0:ne.error)==="insufficient_scope"||(ue==null?void 0:ue.error)==="insufficient_scope"){re.error((ne==null?void 0:ne.message)||"Gmail is missing send permission. Please disconnect and reconnect Gmail, allowing 'Send email on your behalf'.",{duration:1e4});return}if(se)throw new Error((ne==null?void 0:ne.message)||se.message);if(!(ue!=null&&ue.success))throw new Error((ue==null?void 0:ue.error)||"Failed to send");re.success("Video email sent!"),t(!1),i==null||i()}catch(Q){console.error("Gmail send error:",Q),re.error("Failed to send: "+(Q instanceof Error?Q.message:"Unknown error"))}finally{A(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"sm:max-w-[560px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(ln,{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(te,{children:"Send to Contact"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(md,{open:u,onOpenChange:h,children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{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(So,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:H(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(Jw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(id,{className:"w-[350px] p-0",align:"start",children:e.jsxs(pj,{children:[e.jsx(fj,{placeholder:"Search contacts..."}),e.jsxs(gj,{children:[e.jsx(xj,{children:m?"Loading...":"No contacts found."}),e.jsx(I_,{children:l.filter(Z=>Z.email).map(Z=>e.jsxs(e1,{value:`${H(Z)} ${Z.email||""}`,onSelect:()=>z(Z),children:[e.jsx(Xr,{className:Mt("mr-2 h-4 w-4",(c==null?void 0:c.id)===Z.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:H(Z)}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Z.email})]})]},Z.id))})]})]})})]}),c&&e.jsx(U,{variant:"ghost",size:"icon",onClick:$,className:"shrink-0",children:e.jsx(er,{className:"h-4 w-4"})})]})]}),!c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"video-to",children:"Or type email address"}),e.jsx(xe,{id:"video-to",value:f,onChange:Z=>x(Z.target.value),placeholder:"recipient@example.com",type:"email"})]}),e.jsx(hc,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"video-subject",children:"Subject"}),e.jsx(xe,{id:"video-subject",value:y,onChange:Z=>v(Z.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"video-message",children:"Personal Message"}),e.jsx(Fs,{id:"video-message",value:b,onChange:Z=>N(Z.target.value),rows:4,className:"resize-y"})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsx(te,{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:[M?e.jsx("img",{src:M,alt:I,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(lu,{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(lu,{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(U,{variant:"outline",onClick:()=>t(!1),disabled:S,children:"Cancel"}),e.jsxs(U,{onClick:K,disabled:S||!f||!y,className:"gap-2",children:[S?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx($r,{className:"h-4 w-4"}),S?"Sending...":"Send Video Email"]})]})]})]})})}const J$n=()=>{const{user:s}=vs();return ct({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 eVn({recipient:s}){return s.watched_at?e.jsxs(Be,{className:"bg-emerald-100 text-emerald-800 text-[10px]",children:[e.jsx(lu,{className:"h-2.5 w-2.5 mr-0.5"}),"Watched"]}):s.clicked_at?e.jsxs(Be,{className:"bg-blue-100 text-blue-800 text-[10px]",children:[e.jsx(n0,{className:"h-2.5 w-2.5 mr-0.5"}),"Clicked"]}):s.opened_at?e.jsxs(Be,{className:"bg-amber-100 text-amber-800 text-[10px]",children:[e.jsx(xa,{className:"h-2.5 w-2.5 mr-0.5"}),"Opened"]}):e.jsxs(Be,{variant:"outline",className:"text-[10px]",children:[e.jsx($r,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]})}function tVn({open:s,onOpenChange:t,videoId:n,videoTitle:r}){const{data:a=[],isLoading:i}=oIn(n);return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-2xl max-h-[80vh]",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Cl,{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(Gi,{className:"h-[400px]",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Recipient"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{children:"Sent"}),e.jsx(Lt,{children:"Last Activity"})]})}),e.jsx(Xa,{children:a.map(l=>e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:l.recipient_name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l.recipient_email})]})}),e.jsx(gt,{children:e.jsx(eVn,{recipient:l})}),e.jsx(gt,{className:"text-xs text-muted-foreground",children:Gs(new Date(l.sent_at),"MMM d, h:mm a")}),e.jsx(gt,{className:"text-xs text-muted-foreground",children:l.last_activity_at?Nd(new Date(l.last_activity_at),{addSuffix:!0}):"—"})]},l.id))})]})})]})]})})}function sVn(){const{data:s,isLoading:t}=lIn(),{data:n=[],isLoading:r}=cIn(),[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(we,{children:[e.jsx(Tt,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Total Sent"}),e.jsx($r,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Open Rate"}),e.jsx(xa,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(n0,{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(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-sm font-medium",children:"Send History by Video"}),e.jsx(Jn,{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(Wr,{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($r,{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(xa,{className:"h-3 w-3"})," ",d]}),e.jsxs("span",{className:"text-xs text-blue-600 flex items-center gap-1",children:[e.jsx(n0,{className:"h-3 w-3"})," ",u]})]})]}),e.jsx(rc,{className:"h-4 w-4 text-muted-foreground"})]},c.videoId)})})})]}),e.jsx(tVn,{open:!!a,onOpenChange:c=>!c&&i(null),videoId:(a==null?void 0:a.id)||null,videoTitle:(a==null?void 0:a.title)||""})]})}function nVn({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(Wr,{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 rVn({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:p,getShareUrl:f,copyToClipboard:x,formatDuration:y}){const[v,b]=j.useState(!1);return e.jsxs(we,{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(nVn,{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(lu,{className:"h-6 w-6 text-primary ml-1"})})}),e.jsx("div",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-1.5 py-0.5 rounded",children:y(s.duration_seconds)}),s.status!=="ready"&&e.jsx(Be,{variant:s.status==="processing"?"secondary":"destructive",className:"absolute top-2 left-2",children:s.status})]}),e.jsx(Ie,{className:"p-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"font-medium truncate",children:s.title||"Untitled Video"}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-1",children:[e.jsx(So,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:p(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(Yr,{className:"h-3 w-3"}),e.jsx("span",{children:Gs(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(xa,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]}),m&&s.share_token&&e.jsxs(U,{variant:"outline",size:"sm",className:"mt-2 gap-1.5 text-xs h-7",onClick:N=>{N.stopPropagation(),h==null||h()},children:[e.jsx(ln,{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(So,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:p(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(Yr,{className:"h-3 w-3"}),e.jsx("span",{children:Gs(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(xa,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]})]}),e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:N=>N.stopPropagation(),children:e.jsx(ey,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",className:"bg-popover",children:[e.jsxs(La,{onClick:N=>{N.stopPropagation(),r()},children:[e.jsx(xa,{className:"h-4 w-4 mr-2"}),"Watch"]}),e.jsx(l1,{}),e.jsxs(La,{onClick:N=>{N.stopPropagation(),u()},children:[e.jsx($c,{className:"h-4 w-4 mr-2"}),"Share with Template"]}),e.jsxs(La,{onClick:N=>{N.stopPropagation(),x(f(s),"Share link")},children:[e.jsx(Rc,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(La,{onClick:N=>{N.stopPropagation(),o()},children:[e.jsx(jA,{className:"h-4 w-4 mr-2"}),"Get Embed Code"]}),e.jsxs(La,{onClick:N=>{N.stopPropagation(),c()},children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(La,{onClick:N=>{N.stopPropagation(),d()},children:[e.jsx(Sr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),m&&s.share_token&&e.jsxs(La,{onClick:N=>{N.stopPropagation(),h==null||h()},children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]}),e.jsxs(La,{onClick:N=>{N.stopPropagation(),i()},children:[e.jsx(ri,{className:"h-4 w-4 mr-2"}),"Rename"]}),e.jsx(l1,{}),s.contact_id&&e.jsxs(La,{onClick:N=>{N.stopPropagation(),l()},children:[e.jsx(So,{className:"h-4 w-4 mr-2"}),"View Contact"]}),e.jsxs(La,{onClick:N=>{N.stopPropagation(),a()},className:"text-destructive",children:[e.jsx(In,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})})]})}function aVn(){var Wt,us;const s=Wn(),{data:t,isLoading:n,refetch:r}=AIn(),{data:a}=VLe(),{data:i}=Cb(),l=MIn(),o=TIn(),{isGmailConnected:c,gmailEmail:d}=Ax(),{data:u}=Sj(),{data:h=[],isLoading:m}=J$n(),[p,f]=j.useState("my"),[x,y]=j.useState(""),[v,b]=j.useState(null),[N,S]=j.useState(!1),[A,T]=j.useState(!1),[L,M]=j.useState(!1),[I,R]=j.useState(!1),[z,$]=j.useState(!1),[H,V]=j.useState(""),[K,Z]=j.useState(!1),[Q,le]=j.useState(!1),[ue,se]=j.useState(!1),[ne,ie]=j.useState(!1),[ce,je]=j.useState(""),[be,he]=j.useState({}),ge=zt=>{if(!zt)return"Unassigned";const bt=i==null?void 0:i.find(As=>As.id===zt);return bt?`${bt.first_name} ${bt.last_name||""}`.trim():"Unknown"},ke=zt=>{if(!zt)return"0:00";const bt=Math.floor(zt/60),As=zt%60;return`${bt}:${As.toString().padStart(2,"0")}`},[Te,Me]=j.useState("all"),Oe=t==null?void 0:t.filter(zt=>{const bt=zt.category||"general";if(Te==="general"&&bt!=="general"||Te==="open_house"&&bt!=="open_house")return!1;if(!x)return!0;const As=ge(zt.contact_id).toLowerCase(),vt=(zt.title||"").toLowerCase(),Ws=(zt.notes||"").toLowerCase();return As.includes(x.toLowerCase())||vt.includes(x.toLowerCase())||Ws.includes(x.toLowerCase())}),Se=(t==null?void 0:t.filter(zt=>(zt.category||"general")==="open_house").length)||0,Qe=(t==null?void 0:t.filter(zt=>(zt.category||"general")==="general").length)||0,Ae=(t||[]).filter(zt=>zt.status==="processing"&&zt.bunny_video_id).map(zt=>zt.id).join(",");j.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const bt=t.filter(vt=>vt.status==="processing"&&vt.bunny_video_id);if(!bt.length)return;let As=!1;for(const vt of bt)try{const{data:Ws,error:on}=await q.functions.invoke("bunny-upload",{body:{action:"status",videoId:vt.bunny_video_id,isAgentVideo:!0}});if(on||!Ws)continue;Ws.status===4&&(await q.from("agent_videos").update({status:"ready",playback_url:Ws.directPlayUrl,thumbnail_url:Ws.thumbnailUrl,preview_url:Ws.previewUrl,duration_seconds:Ws.length||vt.duration_seconds,updated_at:new Date().toISOString()}).eq("id",vt.id),As=!0)}catch(Ws){console.warn("Reconcile check failed for video",vt.id,Ws)}As&&r()})()},[Ae,r]),j.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const bt=t.filter(Ms=>(Ms==null?void 0:Ms.bunny_video_id)&&!be[Ms.id]);if(!bt.length)return;const As=bt.map(Ms=>Ms.bunny_video_id),{data:vt,error:Ws}=await q.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:As,isAgentVideo:!0}});if(Ws)throw Ws;const on=(vt==null?void 0:vt.assets)||{};he(Ms=>{const dn={...Ms};for(const rn of bt)on[rn.bunny_video_id]&&(dn[rn.id]={previewUrl:on[rn.bunny_video_id].previewUrl,thumbnailUrl:on[rn.bunny_video_id].thumbnailUrl});return dn})})().catch(bt=>console.warn("Failed to load signed Bunny asset URLs",bt))},[t,be]);const Fe=(a==null?void 0:a.total_storage_mb)||0,Ne=(a==null?void 0:a.max_storage_mb)||1024,$e=Fe/Ne*100,Ve=$e>=80,qe=$e>=100,Ze=async(zt,bt)=>{await navigator.clipboard.writeText(zt),re.success(`${bt} copied to clipboard`)},Ue=zt=>zt.share_token?`https://video.relevelup.com/${zt.share_token}`:zt.playback_url||"",Ye=zt=>{const bt=Ue(zt),As=i==null?void 0:i.find(rn=>rn.id===zt.contact_id),vt=ge(zt.contact_id),Ws=vt!=="Unassigned"?vt.split(" ")[0]:"",on=(As==null?void 0:As.phone)||"",Ms=`Hey${Ws?` ${Ws}`:""}! I recorded a quick video message for you. Check it out: ${bt}`,dn=on?`sms:${on}?body=${encodeURIComponent(Ms)}`:`sms:?body=${encodeURIComponent(Ms)}`;window.open(dn,"_self")},Ge=zt=>{const bt=i==null?void 0:i.find(dn=>dn.id===zt.contact_id),As=(bt==null?void 0:bt.email)||"",vt=Ue(zt),Ws="Check out this video",on=`I recorded a quick video for you: ${vt}`,Ms=As?`mailto:${As}?subject=${encodeURIComponent(Ws)}&body=${encodeURIComponent(on)}`:`mailto:?subject=${encodeURIComponent(Ws)}&body=${encodeURIComponent(on)}`;window.open(Ms,"_self")},He=zt=>{var Ws;const bt=Ue(zt),As=zt.title||"Video Message",vt=zt.share_token?`https://video.relevelup.com/thumb/${zt.share_token}`:((Ws=be[zt.id])==null?void 0:Ws.thumbnailUrl)||zt.thumbnail_url||"";return``},tt=async zt=>{if(!zt.thumbnail_url&&!zt.share_token){re.error("Video thumbnail not available yet");return}const bt=He(zt),As=Ue(zt),vt=`Watch: ${zt.title||"Video Message"} ${As}`;try{const Ws=new Blob([bt],{type:"text/html"}),on=new Blob([vt],{type:"text/plain"}),Ms=new ClipboardItem({"text/html":Ws,"text/plain":on});await navigator.clipboard.write([Ms]),re.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(vt+` `+bt),re.success("Copied! Paste into your email.")}},pt=async zt=>{try{re.loading("Preparing download...",{id:"download"});const{data:bt,error:As}=await q.functions.invoke("bunny-upload",{body:{action:"download-url",videoId:zt.bunny_video_id,isAgentVideo:!0}});if(As||!(bt!=null&&bt.downloadUrl))throw new Error((As==null?void 0:As.message)||"Failed to get download URL");const Ws=`${((zt.title||"video").toString().trim()||"video").replace(/[\\/:*?"<>|]+/g,"-")}.mp4`,on=await fetch(bt.downloadUrl);if(!on.ok)throw new Error("Failed to fetch video file");const Ms=await on.blob(),dn=URL.createObjectURL(Ms),rn=document.createElement("a");rn.href=dn,rn.download=Ws,rn.rel="noreferrer",document.body.appendChild(rn),rn.click(),rn.remove(),URL.revokeObjectURL(dn),re.success("Download started",{id:"download"})}catch(bt){console.error("Download error:",bt),re.error("Could not force download (your browser may block it).",{id:"download"})}},ft=async zt=>{b(zt),Z(!0),V(""),$(!0);try{const{data:bt,error:As}=await q.functions.invoke("bunny-upload",{body:{action:"crm-embed",videoId:zt.bunny_video_id,title:zt.title,isAgentVideo:!0,shareToken:zt.share_token}});if(As||!(bt!=null&&bt.html))throw new Error("Failed to generate CRM embed code");V(bt.html)}catch(bt){console.error("CRM embed error:",bt),re.error("Failed to generate CRM embed code"),$(!1)}finally{Z(!1)}},qt=zt=>{b(zt),S(!0)},Ut=async()=>{if(v)try{await l.mutateAsync({id:v.id,bunnyVideoId:v.bunny_video_id,hardDelete:!0}),T(!1),b(null),re.success("Video deleted successfully")}catch{re.error("Failed to delete video")}};return e.jsx(qs,{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:()=>f("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${p==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Videos"}),u&&((Wt=u.team)==null?void 0:Wt.shared_videos_enabled)&&e.jsxs("button",{onClick:()=>f("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${p==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Bn,{className:"h-3.5 w-3.5"}),"Team"]}),e.jsxs("button",{onClick:()=>f("analytics"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${p==="analytics"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Cl,{className:"h-3.5 w-3.5"}),"Analytics"]})]})]}),p==="my"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(U,{variant:"outline",onClick:()=>M(!0),children:[e.jsx(qa,{className:"h-4 w-4 mr-2"}),"Upload Video"]}),e.jsxs(U,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Record New Video"]})]})]}),p==="team"?e.jsx(iVn,{videos:h,isLoading:m,searchTerm:x,setSearchTerm:y}):p==="analytics"?e.jsx(sVn,{}):e.jsxs(e.Fragment,{children:[e.jsx(we,{className:Ve?"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(qX,{className:`h-5 w-5 ${qe?"text-destructive":Ve?"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:[Fe.toFixed(1)," MB / ",Ne>=1024?`${(Ne/1024).toFixed(0)} GB`:`${Ne} MB`]})]}),e.jsx(ro,{value:Math.min($e,100),className:`h-2 ${qe?"[&>div]:bg-destructive":Ve?"[&>div]:bg-amber-500":""}`})]}),Ve&&!qe&&e.jsxs(Be,{variant:"outline",className:"border-amber-500 text-amber-600",children:[e.jsx(Vo,{className:"h-3 w-3 mr-1"}),"Near Limit"]}),qe&&e.jsxs(Be,{variant:"destructive",children:[e.jsx(Vo,{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:Qe},{id:"open_house",label:"Open House Tours",count:Se}].map(zt=>e.jsxs("button",{onClick:()=>Me(zt.id),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${Te===zt.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[zt.label," ",e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:zt.count})]},zt.id))}),e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search videos by contact, title, or notes...",value:x,onChange:zt=>y(zt.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"})}):(Oe==null?void 0:Oe.length)===0?e.jsx(we,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(Wr,{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(U,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(an,{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:Oe==null?void 0:Oe.map(zt=>{var bt,As;return e.jsx(rVn,{video:zt,previewSrc:(bt=be[zt.id])==null?void 0:bt.previewUrl,thumbnailSrc:(As=be[zt.id])==null?void 0:As.thumbnailUrl,onOpen:()=>qt(zt),onDelete:()=>{b(zt),T(!0)},onRename:()=>{b(zt),je(zt.title||""),ie(!0)},onNavigateToContact:()=>s(`/mission-control/contacts/${zt.contact_id}`),onGetEmbedCode:()=>{b(zt),R(!0)},onCopyEmailHtml:()=>tt(zt),onEmbedToCrm:()=>ft(zt),onShareWithTemplate:()=>{b(zt),le(!0)},onSendViaGmail:()=>{b(zt),se(!0)},isGmailConnected:c,getContactName:ge,getShareUrl:Ue,copyToClipboard:Ze,formatDuration:ke},zt.id)})}),e.jsx(zs,{open:N,onOpenChange:S,children:e.jsxs(Ds,{className:"max-w-2xl",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(So,{className:"h-3 w-3"}),ge(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(Et,{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(U,{variant:"outline",size:"sm",onClick:()=>{S(!1),r()},children:[e.jsx(no,{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 zt=v.playback_url;return zt.includes("iframe.mediadelivery.net/play/")&&(zt=zt.replace("/play/","/embed/"),zt+=(zt.includes("?")?"&":"?")+"autoplay=false&responsive=true"),zt.includes("iframe.mediadelivery.net")?e.jsx("iframe",{src:zt,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(Wr,{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(U,{variant:"outline",onClick:()=>Ye(v),children:[e.jsx(Ki,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),!c&&e.jsxs(U,{variant:"outline",onClick:()=>Ge(v),children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(U,{variant:"outline",onClick:()=>Ze(Ue(v),"Share link"),children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(U,{variant:"outline",onClick:()=>tt(v),children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(U,{variant:"outline",onClick:()=>pt(v),children:[e.jsx(pi,{className:"h-4 w-4 mr-2"}),"Download Video"]}),e.jsxs(U,{variant:"outline",onClick:()=>{S(!1),ft(v)},children:[e.jsx(Sr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),e.jsxs(U,{variant:"outline",onClick:()=>{S(!1),le(!0)},children:[e.jsx($c,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]}),c&&(v==null?void 0:v.share_token)&&e.jsxs(U,{variant:"outline",onClick:()=>{S(!1),se(!0)},children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]})]}),e.jsx("div",{className:"flex justify-end pt-2 border-t",children:e.jsxs(U,{variant:"destructive",onClick:()=>{S(!1),T(!0)},children:[e.jsx(In,{className:"h-4 w-4 mr-2"}),"Delete Video"]})})]})]})}),e.jsx(zs,{open:A,onOpenChange:T,children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Delete Video"}),e.jsx(Pr,{children:"Are you sure you want to delete this video? This action cannot be undone."})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>T(!1),children:"Cancel"}),e.jsx(U,{variant:"destructive",onClick:Ut,disabled:l.isPending,children:l.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(rWt,{open:L,onOpenChange:M}),e.jsx(zs,{open:I,onOpenChange:R,children:e.jsxs(Ds,{className:"sm:max-w-lg",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{children:"Embed Code"}),e.jsx(Fs,{readOnly:!0,rows:5,value:``,className:"font-mono text-xs"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(U,{className:"flex-1",onClick:()=>{const zt=``;Ze(zt,"Embed code")},children:[e.jsx(Pa,{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(wJt,{open:Q,onOpenChange:le,video:v,contactName:ge(v.contact_id)}),v&&e.jsx(Q$n,{open:ue,onOpenChange:se,video:v,gmailEmail:d,signedThumbnailUrl:(us=be[v.id])==null?void 0:us.thumbnailUrl}),e.jsx(zs,{open:ne,onOpenChange:ie,children:e.jsxs(Ds,{className:"max-w-sm",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Rename Video"}),e.jsx(Pr,{children:"Enter a new title for this video."})]}),e.jsx(xe,{value:ce,onChange:zt=>je(zt.target.value),placeholder:"Video title",autoFocus:!0,onKeyDown:zt=>{zt.key==="Enter"&&ce.trim()&&o.mutate({id:v.id,title:ce.trim()},{onSuccess:()=>{re.success("Video renamed"),ie(!1)}})}}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>ie(!1),children:"Cancel"}),e.jsx(U,{disabled:!ce.trim()||o.isPending,onClick:()=>{o.mutate({id:v.id,title:ce.trim()},{onSuccess:()=>{re.success("Video renamed"),ie(!1)}})},children:o.isPending?"Saving...":"Save"})]})]})}),e.jsx(zs,{open:z,onOpenChange:$,children:e.jsxs(Ds,{className:"sm:max-w-lg",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Sr,{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."})]}),K?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Et,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):H?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"CRM Email HTML"}),e.jsx(Fs,{readOnly:!0,rows:12,value:H,className:"font-mono text-xs"})]}),e.jsxs(U,{className:"w-full",onClick:()=>{Ze(H,"CRM embed code")},children:[e.jsx(Pa,{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 iVn({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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{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(we,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(Bn,{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(Ea,{className:"h-7 w-7",children:[e.jsx(Ci,{src:c.avatar||""}),e.jsx(Ta,{children:(c.name||"?").charAt(0).toUpperCase()})]}),e.jsx("h3",{className:"font-semibold text-sm",children:c.name}),e.jsx(Be,{variant:"secondary",className:"text-xs",children:c.videos.length})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:c.videos.map(d=>e.jsxs(we,{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(Wr,{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(So,{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(xa,{className:"h-3 w-3"}),d.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yr,{className:"h-3 w-3"}),Gs(new Date(d.created_at),"MMM d")]})]})]})]},d.id))})]},o))})]})}const oVn=()=>{const{user:s}=vs();return ct({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})},KNt=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function lVn({open:s,onOpenChange:t}){const{data:n,isLoading:r}=oVn(),[a,i]=j.useState(""),[l,o]=j.useState("all"),c=j.useMemo(()=>{if(!n)return new Map;const f=new Map;let x=0;return n.forEach(y=>{f.has(y.owner_user_id)||(f.set(y.owner_user_id,{name:y.owner_name||"Unknown",avatar:y.owner_avatar_url,color:KNt[x%KNt.length]}),x++)}),f},[n]),d=j.useMemo(()=>Array.from(c.entries()).map(([f,x])=>({id:f,...x})),[c]),u=j.useMemo(()=>{if(!n)return[];let f=n;if(l!=="all"&&(f=f.filter(x=>x.owner_user_id===l)),a.trim()){const x=a.toLowerCase();f=f.filter(y=>{var v,b,N,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))||((N=y.city)==null?void 0:N.toLowerCase().includes(x))||((S=y.owner_name)==null?void 0:S.toLowerCase().includes(x))})}return f},[n,a,l]),h=j.useMemo(()=>{const f=new Map;return u.forEach(x=>{const y=x.stage_name||"Unknown";f.has(y)||f.set(y,{name:y,color:x.stage_color,icon:x.stage_icon,deals:[],totalValue:0});const v=f.get(y);v.deals.push(x),v.totalValue+=x.sale_price||0}),Array.from(f.values())},[u]),m=f=>f>=1e6?`$${(f/1e6).toFixed(1)}M`:f>=1e3?`$${(f/1e3).toFixed(0)}K`:`$${f.toFixed(0)}`,p=f=>f?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(f):null;return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-[95vw] w-full max-h-[90vh] flex flex-col",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Bn,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search deals...",value:a,onChange:f=>i(f.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:l,onValueChange:o,children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{placeholder:"All Members"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Members"}),d.map(f=>e.jsx(et,{value:f.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:f.color}}),f.name]})},f.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(f=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:f.color}}),f.name.split(" ")[0]]},f.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(f=>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"})]},f))}):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(Bn,{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(f=>{const x=f.icon&&b6e[f.icon]||Nf;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:f.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:f.color?`${f.color}20`:void 0},children:e.jsx(x,{className:"h-3.5 w-3.5",style:{color:f.color||void 0}})}),e.jsx("h3",{className:"font-semibold text-sm",children:f.name})]}),e.jsx(Be,{variant:"secondary",className:"text-xs px-2",children:f.deals.length})]}),f.totalValue>0&&e.jsx("p",{className:"text-xs text-muted-foreground ml-8",children:m(f.totalValue)})]}),e.jsx(Gi,{className:"flex-1 p-2",children:e.jsx("div",{className:"space-y-2",children:f.deals.map(y=>{const v=c.get(y.owner_user_id);return e.jsx(cVn,{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:p},y.id)})})})]},f.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 cVn({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(Ea,{className:"h-4 w-4",children:[e.jsx(Ci,{src:r||""}),e.jsx(Ta,{className:"text-[8px] font-semibold text-white",style:{backgroundColor:t},children:n.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-[10px] font-medium truncate",style:{color:t},children:n})]}),e.jsxs("div",{className:"flex items-start justify-between gap-1",children:[e.jsx("h4",{className:"font-medium text-sm leading-tight line-clamp-2",children:s.deal_name}),l&&e.jsx(Be,{variant:"outline",className:Mt("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(ra,{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(yu,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:a(s.sale_price)})]})]})}function dVn({members:s,enabledMembers:t,onToggleMember:n,isOpen:r,onToggleOpen:a}){const i=t.size;return e.jsxs("div",{className:Mt("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(U,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 px-2",onClick:a,children:[e.jsx(Bn,{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"}),i>0&&e.jsx("span",{className:"text-[10px] bg-primary text-primary-foreground rounded-full px-1.5 py-0.5",children:i}),e.jsx(rd,{className:"h-3 w-3 text-muted-foreground"})]}),!r&&i>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[9px] bg-primary text-primary-foreground rounded-full w-4 h-4 flex items-center justify-center",children:i})]})}),r?e.jsxs(Gi,{className:"flex-1 p-2",children:[e.jsx("div",{className:"space-y-1",children:s.map(l=>{const o=t.has(l.id);return e.jsxs("button",{onClick:()=>n(l.id),className:Mt("w-full flex items-center gap-2 px-2 py-2 rounded-lg text-left transition-colors",o?"bg-primary/10 hover:bg-primary/15":"hover:bg-muted/50"),children:[e.jsxs("div",{className:"relative",children:[e.jsxs(Ea,{className:"h-7 w-7",children:[e.jsx(Ci,{src:l.avatar_url||""}),e.jsx(Ta,{className:"text-[10px] font-semibold text-white",style:{backgroundColor:l.color},children:l.name.charAt(0).toUpperCase()})]}),o&&e.jsx("div",{className:"absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full border-2 border-background",style:{backgroundColor:l.color}})]}),e.jsx("span",{className:Mt("text-xs truncate flex-1",o?"font-medium text-foreground":"text-muted-foreground"),children:l.name}),e.jsx(wn,{checked:o,onCheckedChange:()=>n(l.id),className:"scale-75",onClick:c=>c.stopPropagation()})]},l.id)})}),s.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-4",children:"No team members"})]}):e.jsxs("div",{className:"flex-1 flex flex-col items-center pt-2 gap-2",children:[s.slice(0,5).map(l=>{const o=t.has(l.id);return e.jsx("button",{onClick:()=>n(l.id),className:"relative",title:l.name,children:e.jsxs(Ea,{className:Mt("h-7 w-7 transition-all",o?"ring-2 ring-offset-1 ring-offset-background":"opacity-50"),style:o?{"--tw-ring-color":l.color}:{},children:[e.jsx(Ci,{src:l.avatar_url||""}),e.jsx(Ta,{className:"text-[10px] font-semibold text-white",style:{backgroundColor:l.color},children:l.name.charAt(0).toUpperCase()})]})},l.id)}),s.length>5&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["+",s.length-5]})]})]})}const YNt=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function uVn(){const s=Sa(),{data:t}=Sj(),n=(t==null?void 0:t.role)==="team_leader",r=t==null?void 0:t.teamId,a=ct({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:YNt[h%YNt.length]}))},enabled:!!r&&!!s&&n,staleTime:5*60*1e3});return{isTeamLeader:n,teamMembers:a.data||[],isLoadingMembers:a.isLoading}}function hVn(s){return ct({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 mVn(){const s=Sa();return ct({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 jJt({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(Ku,{open:a,onOpenChange:i,children:[e.jsx(Yu,{asChild:!0,children:e.jsxs(U,{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(gi,{className:"h-3 w-3 shrink-0"})]})}),e.jsx(Eu,{align:"end",className:"w-48 z-50 bg-popover",onClick:c=>c.stopPropagation(),children:s.map(c=>{const d=c.icon&&b6e[c.icon]||Nf,u=c.id===t;return e.jsxs(La,{onClick:()=>o(c),className:Mt("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(Xr,{className:"h-4 w-4 text-primary"})]},c.id)})})]})}const pVn={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"}},fVn={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 NJt({deal:s,onClick:t,isDragging:n,stages:r,onStageChange:a,showStagePicker:i=!1,isWonStage:l=!1,ownerInfo:o=null,tags:c=[],overdueTaskCount:d=0}){var S,A;const u=JG(),h=pVn[s.deal_type],m=fVn[s.priority],p=j.useMemo(()=>s.target_close_date?hN(Su(s.target_close_date),new Date):null,[s.target_close_date]),f=p!==null&&p<0,x=p!==null&&p<=7&&p>=0,y=j.useMemo(()=>{var M;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const T=((M=s.listing)==null?void 0:M.created_at)||s.listing_date;if(!T)return null;const L=s.contract_date?Su(s.contract_date):new Date;return hN(L,Su(T))},[s]),v=l&&!s.scorecard_transaction_id,b=!!s.scorecard_transaction_id,N=T=>T?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(T):null;return e.jsxs(we,{className:Mt("cursor-pointer transition-all duration-200 hover:shadow-md hover:border-primary/30 group overflow-hidden",n&&"opacity-50 rotate-2 shadow-xl",f&&"border-red-200 bg-red-50/30",v&&"border-amber-300 bg-amber-50/30 dark:bg-amber-950/20"),onClick:t,style:o?{borderLeftWidth:4,borderLeftColor:o.color}:void 0,children:[!o&&e.jsx("div",{className:Mt("h-1 w-full",m.stripe),"aria-hidden":!0}),e.jsxs(Ie,{className:"p-3 space-y-2.5",children:[o&&e.jsxs("div",{className:"flex items-center gap-1.5 -mt-0.5 mb-1",children:[e.jsxs(Ea,{className:"h-4 w-4",children:[e.jsx(Ci,{src:o.avatar_url||""}),e.jsx(Ta,{className:"text-[8px] font-semibold text-white",style:{backgroundColor:o.color},children:o.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-[10px] font-medium",style:{color:o.color},children:o.name})]}),e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("h4",{className:"font-medium text-sm leading-tight line-clamp-2 group-hover:text-primary transition-colors",children:s.deal_name})}),e.jsx(Be,{variant:"outline",className:Mt("text-[10px] px-1.5 py-0 shrink-0",h.color),children:h.label})]}),s.contact&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Ea,{className:"h-5 w-5",children:e.jsxs(Ta,{className:"text-[10px] bg-primary/10 text-primary",children:[(S=s.contact.first_name)==null?void 0:S[0],(A=s.contact.last_name)==null?void 0:A[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(ad,{className:"h-3 w-3 text-primary shrink-0"}),e.jsx("span",{className:"text-primary truncate",children:"Linked to Listing Exchange"})]}),v&&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(Al,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate font-medium",children:"Add to Scorecard"})]}),b&&l&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-green-600 dark:text-green-400",children:[e.jsx(zr,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:"Synced to Scorecard"})]}),y!==null&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(ch,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsxs("span",{className:Mt("font-medium",y>90?"text-red-600":y>60?"text-amber-600":"text-muted-foreground"),children:[y," DOM"]}),s.contract_date&&e.jsx("span",{className:"text-muted-foreground",children:"(final)"})]}),!s.listing&&(s.property_address||s.city)&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(ra,{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(yu,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:N(s.expected_price)}),s.expected_commission&&e.jsxs("span",{className:"text-muted-foreground",children:["• ",N(s.expected_commission)," GCI"]}),(()=>{const T=g_(s);return T!==null&&T!==s.expected_commission?e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:["• ",N(T)," Net"]}):null})()]}),d>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(cy,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{children:[d," overdue task",d>1?"s":""]})]}),c.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[c.slice(0,3).map(T=>e.jsx(lWt,{label:T},T)),c.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:["+",c.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:Mt("flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px]",m.color),children:[e.jsx("div",{className:Mt("w-1.5 h-1.5 rounded-full",m.dot)}),e.jsx("span",{className:"capitalize",children:s.priority})]})}),i&&u&&r&&a?e.jsx(jJt,{stages:r,currentStageId:s.stage_id||"",onStageSelect:(T,L)=>a(s.id,T,L)}):s.target_close_date?e.jsxs("div",{className:Mt("flex items-center gap-1 text-[10px]",f&&"text-red-600",x&&!f&&"text-amber-600",!f&&!x&&"text-muted-foreground"),children:[f?e.jsx(Vo,{className:"h-3 w-3"}):e.jsx(pa,{className:"h-3 w-3"}),e.jsx("span",{children:f?`${Math.abs(p)}d overdue`:x?`${p}d left`:Gs(Su(s.target_close_date),"MMM d")})]}):null]})]})]})}function gVn({stage:s,deals:t,onDealClick:n,onAddDeal:r,onDragStart:a,onDragOver:i,onDrop:l,isDragOver:o,isWonStage:c=!1,getOwnerInfo:d,tagsByDeal:u={},overdueTasksByDeal:h={}}){const m=j.useRef(null),[p,f]=j.useState(!1),x=t.reduce((S,A)=>S+(A.expected_price||0),0),y=t.reduce((S,A)=>S+(A.expected_commission||0),0),v=t.reduce((S,A)=>S+(g_(A)||0),0),b=S=>S>=1e6?`$${(S/1e6).toFixed(1)}M`:S>=1e3?`$${(S/1e3).toFixed(0)}K`:`$${S.toFixed(0)}`,N=s.icon&&b6e[s.icon]||Nf;return p?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:()=>f(!1),"aria-label":`Expand ${s.name}`,className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx(Be,{variant:"secondary",className:"px-1.5 text-[10px]",children:t.length}),e.jsx("span",{className:"mt-1 whitespace-nowrap text-xs font-semibold",style:{writingMode:"vertical-rl",color:s.color},children:s.name})]}):e.jsxs("div",{ref:m,className:Mt("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:S=>i(S,s.id),onDrop:S=>l(S,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(N,{className:"h-4 w-4",style:{color:s.color}})}),e.jsx("div",{children:e.jsx("h3",{className:"font-semibold text-sm",children:s.name})})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Be,{variant:"secondary",className:"text-xs font-medium px-2",children:t.length}),e.jsx("button",{onClick:()=>f(!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(rd,{className:"h-3.5 w-3.5"})})]})]}),x>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:b(x)}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[b(y)," GCI"]}),v>0&&v!==y&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:[b(v)," Net"]})]})]})]}),e.jsx(Gi,{className:"flex-1 p-2",children:e.jsxs("div",{className:"space-y-2",children:[t.map(S=>e.jsx("div",{draggable:!0,onDragStart:A=>{A.dataTransfer.effectAllowed="move",a(S.id,s.id)},children:e.jsx(NJt,{deal:S,onClick:()=>n(S),isWonStage:c,ownerInfo:(d==null?void 0:d(S))||null,tags:u[S.id]||[],overdueTaskCount:h[S.id]||0})},S.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(U,{variant:"ghost",size:"sm",className:"w-full justify-start text-muted-foreground hover:text-foreground",onClick:()=>r(s.id),children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Add Deal"]})})]})}function xVn({formData:s,onChange:t,isEditing:n}){const{isAdmin:r}=vs(),[a,i]=j.useState(s.portal_enabled);if(!r)return e.jsxs("div",{className:"border rounded-lg p-4 opacity-60",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cn,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Be,{variant:"secondary",className:"text-xs",children:"Coming Soon"})]})}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Give your clients a premium, real-time view of their transaction — coming soon!"})]});const l=o=>{t({...s,...o})};return e.jsx(ub,{open:a,onOpenChange:i,children:e.jsxs("div",{className:"border rounded-lg",children:[e.jsxs(hb,{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(cn,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),s.portal_enabled&&e.jsx(Be,{className:"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200",variant:"outline",children:"Enabled"})]}),e.jsx(rl,{className:Mt("h-4 w-4 text-muted-foreground transition-transform",a&&"rotate-180")})]}),e.jsx(mb,{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(te,{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(wn,{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(te,{className:"text-sm font-medium",children:"Portal Visibility"}),e.jsxs(y_,{value:s.visibility,onValueChange:o=>l({visibility:o}),className:"grid grid-cols-2 gap-3",children:[e.jsxs("label",{className:Mt("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(Fh,{value:"private"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ql,{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:Mt("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(Fh,{value:"public"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(fl,{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(xi,{id:"require_onboarding",checked:s.require_onboarding,onCheckedChange:o=>l({require_onboarding:!!o}),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx(te,{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(xi,{id:"allow_spouse",checked:s.allow_spouse,onCheckedChange:o=>l({allow_spouse:!!o})}),e.jsx(te,{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(te,{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(te,{className:"text-xs text-muted-foreground",children:"Client Full Name"}),e.jsx(xe,{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(te,{className:"text-xs text-muted-foreground",children:"Email"}),e.jsx(xe,{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(te,{className:"text-xs text-muted-foreground",children:"Phone"}),e.jsx(xe,{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(te,{className:"text-xs text-muted-foreground",children:"Preferred Invite Method"}),e.jsxs(Ns,{value:s.invite_method,onValueChange:o=>l({invite_method:o}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"email",children:"Email"}),e.jsxs(et,{value:"sms",disabled:!s.client_phone,children:["SMS ",!s.client_phone&&"(add phone first)"]})]})]})]})]})]})]})]})})]})})}const yVn=[{value:"buyer",label:"Buyer"},{value:"seller",label:"Seller"},{value:"dual",label:"Dual Agency"},{value:"referral",label:"Referral"},{value:"lease",label:"Lease"}],vVn=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"urgent",label:"Urgent"}];function V9e({label:s,date:t,onChange:n,placeholder:r="Pick a date",disabled:a}){const[i,l]=j.useState(t?Gs(t,"MM/dd/yyyy"):"");j.useEffect(()=>{const c=Hpt(i);t&&c&&c.getTime()===t.getTime()||l(t?Gs(t,"MM/dd/yyyy"):"")},[t]);const o=c=>{l(c);const d=Hpt(c);d?n(d):c.trim()||n(void 0)};return e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:s}),e.jsxs(md,{children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{variant:"outline",className:Mt("w-full justify-start text-left font-normal",!t&&"text-muted-foreground"),disabled:a,children:[e.jsx(pa,{className:"mr-2 h-4 w-4"}),t?Gs(t,"PPP"):r]})}),e.jsxs(id,{className:"w-auto p-0",align:"start",children:[e.jsx("div",{className:"p-3 border-b",children:e.jsx(xe,{type:"text",placeholder:"MM/DD/YYYY",value:i,onChange:c=>o(c.target.value),className:"h-8 text-sm"})}),e.jsx(yj,{mode:"single",selected:t,onSelect:c=>{n(c),l(c?Gs(c,"MM/dd/yyyy"):"")},initialFocus:!0,className:"pointer-events-auto",captionLayout:"dropdown",fromYear:1900,toYear:2100})]})]})]})}function bVn({open:s,onOpenChange:t,deal:n,defaultStageId:r}){const{data:a}=nae(),{data:i}=Cb(),{data:l}=TQe(),o=ePe(),c=yJt(),d=vJt(),u=est(),[h,m]=j.useState({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"}),[p,f]=j.useState(""),[x,y]=j.useState(!1),[v,b]=j.useState(!1),[N,S]=j.useState({first_name:"",last_name:"",email:"",phone:""}),A=(l==null?void 0:l.filter(H=>((n==null?void 0:n.listing_id)===H.id,!0)))||[],[T,L]=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 H,V,K,Z,Q,le,ue,se,ne,ie;s&&(n?(L({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:((H=n.expected_price)==null?void 0:H.toString())||"",commission_percentage:((V=n.commission_percentage)==null?void 0:V.toString())||"3",brokerage_split_pct:((K=n.brokerage_split_pct)==null?void 0:K.toString())||"",team_split_pct:((Z=n.team_split_pct)==null?void 0:Z.toString())||"",referral_fee_pct:((Q=n.referral_fee_pct)==null?void 0:Q.toString())||"",franchise_fee_pct:((le=n.franchise_fee_pct)==null?void 0:le.toString())||"",transaction_fee:((ue=n.transaction_fee)==null?void 0:ue.toString())||"",bonus_amount:((se=n.bonus_amount)==null?void 0:se.toString())||"",commission_calc_method:n.commission_calc_method||"standard",target_close_date:n.target_close_date?Su(n.target_close_date):void 0,contract_date:n.contract_date?Su(n.contract_date):void 0,listing_date:n.listing_date?Su(n.listing_date):void 0,priority:n.priority,probability:n.probability.toString(),notes:n.notes||""}),n.contact&&f(`${n.contact.first_name} ${n.contact.last_name}`)):(L({deal_name:"",deal_type:"buyer",stage_id:r||((ne=a==null?void 0:a[0])==null?void 0:ne.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:String(((ie=a==null?void 0:a.find(ce=>{var je;return ce.id===(r||((je=a==null?void 0:a[0])==null?void 0:je.id))}))==null?void 0:ie.default_probability)??50),notes:""}),f(""),m({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 M=i==null?void 0:i.filter(H=>{var ie,ce,je,be,he;const V=p.toLowerCase().trim();if(!V)return!0;const K=((ie=H.first_name)==null?void 0:ie.toLowerCase())||"",Z=((ce=H.last_name)==null?void 0:ce.toLowerCase())||"",Q=((je=H.email)==null?void 0:je.toLowerCase())||"",le=((he=(be=H.phone)==null?void 0:be.toLowerCase)==null?void 0:he.call(be))||"",ue=`${K} ${Z}`.trim(),se=`${Z} ${K}`.trim();if(ue.includes(V)||se.includes(V)||K.includes(V)||Z.includes(V)||Q.includes(V)||le.includes(V))return!0;const ne=V.split(/\s+/).filter(Boolean);return ne.length>1?ne.every(ge=>K.includes(ge)||Z.includes(ge)||Q.includes(ge)||le.includes(ge)):!1}).slice(0,8),I=()=>{const H=parseFloat(T.expected_price)||0,V=parseFloat(T.commission_percentage)||0;return H*(V/100)},R=()=>{const H=I(),V=parseFloat(T.bonus_amount)||0;if(!H)return V>0?V:null;const K=parseFloat(T.brokerage_split_pct)||0,Z=parseFloat(T.team_split_pct)||0,Q=parseFloat(T.referral_fee_pct)||0,le=parseFloat(T.franchise_fee_pct)||0,ue=parseFloat(T.transaction_fee)||0,se=parseFloat(T.bonus_amount)||0;if(T.commission_calc_method==="referral_first"){let ie=H;Q&&(ie-=H*Q/100);let ce=ie;return K&&(ce-=ie*K/100),Z&&(ce-=H*Z/100),le&&(ce-=H*le/100),ue&&(ce-=ue),Math.max(0,ce)+se}let ne=H;return K&&(ne=ne*((100-K)/100)),Z&&(ne=ne*((100-Z)/100)),Q&&(ne=ne-H*Q/100),le&&(ne=ne-H*le/100),ue&&(ne=ne-ue),Math.max(0,ne)+se},z=async H=>{var V,K,Z;if(H.preventDefault(),!T.deal_name.trim()){re.error("Please enter a deal name");return}try{const Q={deal_name:T.deal_name,deal_type:T.deal_type,stage_id:T.stage_id||null,contact_id:T.contact_id||null,listing_id:T.listing_id||null,property_address:T.property_address||null,city:T.city||null,state:T.state||null,zip_code:T.zip_code||null,expected_price:T.expected_price?parseFloat(T.expected_price):null,expected_commission:I()||null,commission_percentage:T.commission_percentage?parseFloat(T.commission_percentage):3,brokerage_split_pct:T.brokerage_split_pct?parseFloat(T.brokerage_split_pct):null,team_split_pct:T.team_split_pct?parseFloat(T.team_split_pct):null,referral_fee_pct:T.referral_fee_pct?parseFloat(T.referral_fee_pct):null,franchise_fee_pct:T.franchise_fee_pct?parseFloat(T.franchise_fee_pct):null,transaction_fee:T.transaction_fee?parseFloat(T.transaction_fee):null,bonus_amount:T.bonus_amount?parseFloat(T.bonus_amount):null,commission_calc_method:T.commission_calc_method,target_close_date:((V=T.target_close_date)==null?void 0:V.toISOString().split("T")[0])||null,contract_date:((K=T.contract_date)==null?void 0:K.toISOString().split("T")[0])||null,listing_date:((Z=T.listing_date)==null?void 0:Z.toISOString().split("T")[0])||null,priority:T.priority,probability:parseInt(T.probability)||50,notes:T.notes||null};if(n)await d.mutateAsync({id:n.id,...Q}),re.success("Deal updated successfully");else{const le=await c.mutateAsync(Q);if(re.success("Deal created successfully"),h.portal_enabled&&(le!=null&&le.id))try{await u.mutateAsync({deal_id:le.id,visibility:h.visibility,require_onboarding:h.require_onboarding,allow_spouse:h.allow_spouse,client_name:h.client_name||null,client_email:h.client_email||null,client_phone:h.client_phone||null,invite_method:h.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")}},$=c.isPending||d.isPending;return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{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:z,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(te,{htmlFor:"deal_name",children:"Deal Name *"}),e.jsx(xe,{id:"deal_name",value:T.deal_name,onChange:H=>L(V=>({...V,deal_name:H.target.value})),placeholder:"e.g., Smith Family - 123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Deal Type"}),e.jsxs(Ns,{value:T.deal_type,onValueChange:H=>L(V=>({...V,deal_type:H})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:yVn.map(H=>e.jsx(et,{value:H.value,children:H.label},H.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Stage"}),e.jsxs(Ns,{value:T.stage_id||"none",onValueChange:H=>{const V=H==="none"?"":H,K=a==null?void 0:a.find(Z=>Z.id===V);L(Z=>({...Z,stage_id:V,probability:typeof(K==null?void 0:K.default_probability)=="number"?String(K.default_probability):Z.probability}))},children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select stage"})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"No Stage"}),a==null?void 0:a.map(H=>e.jsx(et,{value:H.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:H.color}}),H.name]})},H.id))]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Link to Contact"}),e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:p,onChange:H=>{f(H.target.value),y(!0),b(!1),H.target.value||L(V=>({...V,contact_id:""}))},onFocus:()=>y(!0),placeholder:"Search contacts...",className:"pl-9"}),x&&p&&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:[M&&M.length>0?M.map(H=>e.jsxs("button",{type:"button",className:"w-full px-3 py-2 text-left hover:bg-muted flex items-center gap-2",onClick:()=>{L(V=>({...V,contact_id:H.id})),f(`${H.first_name} ${H.last_name}`),y(!1)},children:[e.jsx(So,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:[H.first_name," ",H.last_name]}),H.email&&e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:H.email})]},H.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 H=p.trim().split(/\s+/);S({first_name:H[0]||"",last_name:H.slice(1).join(" ")||"",email:"",phone:""}),b(!0),y(!1)},children:[e.jsx(zl,{className:"h-4 w-4"}),e.jsxs("span",{children:['Create new contact "',p.trim(),'"']})]})]})]}),v&&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(zl,{className:"h-3.5 w-3.5"}),"Quick Add Contact"]}),e.jsx(U,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>b(!1),children:"Cancel"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(xe,{placeholder:"First name *",value:N.first_name,onChange:H=>S(V=>({...V,first_name:H.target.value})),className:"h-8 text-sm"}),e.jsx(xe,{placeholder:"Last name",value:N.last_name,onChange:H=>S(V=>({...V,last_name:H.target.value})),className:"h-8 text-sm"}),e.jsx(xe,{placeholder:"Email",type:"email",value:N.email,onChange:H=>S(V=>({...V,email:H.target.value})),className:"h-8 text-sm"}),e.jsx(xe,{placeholder:"Phone",type:"tel",value:N.phone,onChange:H=>S(V=>({...V,phone:H.target.value})),className:"h-8 text-sm"})]}),e.jsx(U,{type:"button",size:"sm",className:"w-full h-8",disabled:!N.first_name.trim()||o.isPending,onClick:async()=>{try{const H=await o.mutateAsync({first_name:N.first_name.trim(),last_name:N.last_name.trim()||null,email:N.email.trim()||null,phone:N.phone.trim()||null});H&&(L(V=>({...V,contact_id:H.id})),f(`${H.first_name} ${H.last_name||""}`.trim()),b(!1))}catch{}},children:o.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-3.5 w-3.5 mr-1 animate-spin"})," Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(zl,{className:"h-3.5 w-3.5 mr-1"})," Add & Link Contact"]})})]})]}),A.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{className:"flex items-center gap-2",children:[e.jsx(ad,{className:"h-4 w-4"}),"Link to Listing Exchange"]}),e.jsxs(Ns,{value:T.listing_id||"none",onValueChange:H=>{const V=H==="none"?"":H,K=A.find(Z=>Z.id===V);L(K?Z=>{var Q;return{...Z,listing_id:V,deal_type:"seller",property_address:K.property_address||Z.property_address,city:K.city||Z.city,state:K.state||Z.state,expected_price:((Q=K.price)==null?void 0:Q.toString())||Z.expected_price}}:Z=>({...Z,listing_id:V}))},children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select a listing to sync status..."})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"None"}),A.map(H=>e.jsx(et,{value:H.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:H.property_address||`${H.city}, ${H.state}`}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["$",(H.price/1e3).toFixed(0),"K"]})]})},H.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(te,{htmlFor:"property_address",children:"Address"}),e.jsx(xe,{id:"property_address",value:T.property_address,onChange:H=>L(V=>({...V,property_address:H.target.value})),placeholder:"123 Main Street"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"city",children:"City"}),e.jsx(xe,{id:"city",value:T.city,onChange:H=>L(V=>({...V,city:H.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"state",children:"State"}),e.jsx(xe,{id:"state",value:T.state,onChange:H=>L(V=>({...V,state:H.target.value})),maxLength:2,placeholder:"TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"zip_code",children:"ZIP"}),e.jsx(xe,{id:"zip_code",value:T.zip_code,onChange:H=>L(V=>({...V,zip_code:H.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(te,{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(xe,{id:"expected_price",type:"number",value:T.expected_price,onChange:H=>L(V=>({...V,expected_price:H.target.value})),className:"pl-7",placeholder:"500000"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"commission_percentage",children:"Commission %"}),e.jsxs("div",{className:"relative",children:[e.jsx(xe,{id:"commission_percentage",type:"number",step:"0.1",value:T.commission_percentage,onChange:H=>L(V=>({...V,commission_percentage:H.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(te,{children:"Expected GCI"}),e.jsx(xe,{value:I()?`$${I().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(te,{className:"text-xs whitespace-nowrap",children:"Calculation Method:"}),e.jsxs(Ns,{value:T.commission_calc_method,onValueChange:H=>L(V=>({...V,commission_calc_method:H})),children:[e.jsx(ws,{className:"h-7 text-xs",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"standard",children:"Standard (all splits on GCI)"}),e.jsx(et,{value:"referral_first",children:"Referral First (brokerage split after referral)"})]})]})]}),T.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(te,{className:"text-xs",children:"Brokerage Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(xe,{type:"number",step:"1",min:"0",max:"100",value:T.brokerage_split_pct,onChange:H=>L(V=>({...V,brokerage_split_pct:H.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(te,{className:"text-xs",children:"Team Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(xe,{type:"number",step:"1",min:"0",max:"100",value:T.team_split_pct,onChange:H=>L(V=>({...V,team_split_pct:H.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(te,{className:"text-xs",children:"Referral Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(xe,{type:"number",step:"1",min:"0",max:"100",value:T.referral_fee_pct,onChange:H=>L(V=>({...V,referral_fee_pct:H.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(te,{className:"text-xs",children:"Franchise Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(xe,{type:"number",step:"1",min:"0",max:"100",value:T.franchise_fee_pct,onChange:H=>L(V=>({...V,franchise_fee_pct:H.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(te,{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(xe,{type:"number",step:"1",min:"0",value:T.transaction_fee,onChange:H=>L(V=>({...V,transaction_fee:H.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(te,{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(xe,{type:"number",step:"1",min:"0",value:T.bonus_amount,onChange:H=>L(V=>({...V,bonus_amount:H.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(te,{className:"text-xs",children:"Net to Agent"}),e.jsx(xe,{value:R()?`$${Math.round(R()).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(V9e,{label:"Target Close Date",date:T.target_close_date,onChange:H=>L(V=>({...V,target_close_date:H}))}),e.jsx(V9e,{label:"Contract Date",date:T.contract_date,onChange:H=>L(V=>({...V,contract_date:H}))}),(T.deal_type==="seller"||T.deal_type==="dual")&&!T.listing_id&&e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(V9e,{label:"Listing Date (for Days on Market)",date:T.listing_date,onChange:H=>L(V=>({...V,listing_date:H}))}),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(te,{children:"Priority"}),e.jsxs(Ns,{value:T.priority,onValueChange:H=>L(V=>({...V,priority:H})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:vVn.map(H=>e.jsx(et,{value:H.value,children:H.label},H.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Win Probability"}),e.jsxs("div",{className:"relative",children:[e.jsx(xe,{type:"number",min:"0",max:"100",value:T.probability,onChange:H=>L(V=>({...V,probability:H.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(te,{htmlFor:"notes",children:"Notes"}),e.jsx(Fs,{id:"notes",value:T.notes,onChange:H=>L(V=>({...V,notes:H.target.value})),placeholder:"Add any additional notes about this deal...",rows:3})]}),!n&&e.jsx(xVn,{formData:h,onChange:m}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{type:"submit",disabled:$,children:[$&&e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),n?"Update Deal":"Create Deal"]})]})]})]})})}function _Vn({dealId:s}){const t=Sa(),n=Qt(),[r,a]=j.useState(""),[i,l]=j.useState(!1),{data:o=[]}=ct({queryKey:["deal-tags",s],queryFn:async()=>{const{data:f,error:x}=await q.from("deal_tags").select("*").eq("deal_id",s).order("created_at");if(x)throw x;return f},enabled:!!s}),{data:c=[]}=ct({queryKey:["all-deal-tags",t],queryFn:async()=>{if(!t)return[];const{data:f,error:x}=await q.from("deal_tags").select("tag").eq("owner_user_id",t);if(x)throw x;return[...new Set(f.map(v=>v.tag))].sort()},enabled:!!t}),d=yt({mutationFn:async f=>{if(!t)throw new Error("Not authenticated");const{error:x}=await q.from("deal_tags").insert({deal_id:s,owner_user_id:t,tag:f.trim()});if(x)throw x},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]}),n.invalidateQueries({queryKey:["all-deal-tags"]}),a("")}}),u=yt({mutationFn:async f=>{const{error:x}=await q.from("deal_tags").delete().eq("id",f);if(x)throw x},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]})}}),h=()=>{const f=r.trim();f&&(o.some(x=>x.tag.toLowerCase()===f.toLowerCase())||d.mutate(f))},m=o.map(f=>f.tag.toLowerCase()),p=c.filter(f=>f.toLowerCase().includes(r.toLowerCase())&&!m.includes(f.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(f=>e.jsxs(Be,{variant:"secondary",className:"gap-1 text-xs",children:[f.tag,e.jsx("button",{type:"button",onClick:()=>u.mutate(f.id),className:"ml-0.5 hover:text-destructive",children:e.jsx(er,{className:"h-3 w-3"})})]},f.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(an,{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(xe,{value:r,onChange:f=>a(f.target.value),onKeyDown:f=>{f.key==="Enter"&&(f.preventDefault(),h()),f.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&&p.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:p.map(f=>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(f)},children:f},f))})]})]})}function wVn(s){return ct({queryKey:["deal-files",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_files").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function jVn(){const s=Sa(),t=Qt();return yt({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}).select().single();if(c)throw c;return o},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["deal-files",r.dealId]})}})}function NVn(){const s=Qt();return yt({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 kVn(){const s=Qt();return yt({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 SVn(s){const{data:t,error:n}=await q.storage.from("deal-files").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}/*! ***************************************************************************** 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 aKe=function(s,t){return aKe=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])},aKe(s,t)};function ai(s,t){aKe(s,t);function n(){this.constructor=s}s.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var ec=function(){return ec=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+=LU[(s[r]&3)<<4|s[r+1]>>4],t+=LU[(s[r+1]&15)<<2|s[r+2]>>6],t+=LU[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},ZNt=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},EVn=/^(data)?:?([\w\/\+]+)?;?(charset=[\w-]+|base64)?.*,/i,TVn=function(s){var t=s.trim(),n=t.substring(0,100),r=n.match(EVn);if(!r)return ZNt(t);var a=r[0],i=t.substring(a.length);return ZNt(i)},Jl=function(s){return s.charCodeAt(0)},MVn=function(s){return s.codePointAt(0)},aae=function(s,t){return Bk(s.toString(16),t,"0").toUpperCase()},SIe=function(s){return aae(s,2)},UA=function(s){return String.fromCharCode(s)},PVn=function(s){return UA(parseInt(s,16))},Bk=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]},RVn=function(s){for(var t=[],n=0,r=s.length;nn&&d(),l+=m,o+=p}}return d(),c},FVn=/^D:(\d\d\d\d)(\d\d)?(\d\d)?(\d\d)?(\d\d)?(\d\d)?([+\-Z])?(\d\d)?'?(\d\d)?'?$/,EJt=function(s){var t=s.match(FVn);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,p=t[7],f=p===void 0?"Z":p,x=t[8],y=x===void 0?"00":x,v=t[9],b=v===void 0?"00":v,N=f==="Z"?"Z":""+f+y+":"+b,S=new Date(n+"-"+a+"-"+l+"T"+c+":"+u+":"+m+N);return S}},Lnt=function(s,t){for(var n,r=0,a;r=0&&s<=65535},YVn=function(s){return s>=65536&&s<=1114111},MJt=function(s){return Math.floor((s-65536)/1024)+55296},PJt=function(s){return(s-65536)%1024+56320},QM;(function(s){s.BigEndian="BigEndian",s.LittleEndian="LittleEndian"})(QM||(QM={}));var DY="�".codePointAt(0),LJt=function(s,t){if(t===void 0&&(t=!0),s.length<=1)return String.fromCodePoint(DY);for(var n=t?XVn(s):QM.BigEndian,r=t?2:0,a=[];s.length-r>=2;){var i=QNt(s[r++],s[r++],n);if(ZVn(i))if(s.length-r<2)a.push(DY);else{var l=QNt(s[r++],s[r++],n);XNt(l)?a.push(i,l):a.push(DY)}else XNt(i)?(r+=2,a.push(DY)):a.push(i)}return r=55296&&s<=56319},XNt=function(s){return s>=56320&&s<=57343},QNt=function(s,t,n){if(n===QM.LittleEndian)return t<<8|s;if(n===QM.BigEndian)return s<<8|t;throw new Error("Invalid byteOrder: "+n)},XVn=function(s){return IJt(s)?QM.BigEndian:RJt(s)?QM.LittleEndian:QM.BigEndian},IJt=function(s){return s[0]===254&&s[1]===255},RJt=function(s){return s[0]===255&&s[1]===254},DJt=function(s){return IJt(s)||RJt(s)},QVn=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},B4e=function(s){return Math.ceil(s.toString(2).length/8)},gB=function(s){for(var t=new Uint8Array(B4e(s)),n=1;n<=t.length;n++)t[n-1]=s>>(t.length-n)*8;return t},oae=function(s){throw new Error(s)},SE={};(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 sHn=0,OJt=1,nHn=2,rHn=3,aHn=258,Int=29,cae=256,Ite=cae+1+Int,n$=30,Rnt=19,FJt=2*Ite+1,cO=15,H9e=16,iHn=7,Dnt=256,zJt=16,BJt=17,UJt=18,oKe=[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],U4e=[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],oHn=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],qJt=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],lHn=512,DC=new Array((Ite+2)*2);vW(DC);var pJ=new Array(n$*2);vW(pJ);var Rte=new Array(lHn);vW(Rte);var Dte=new Array(aHn-rHn+1);vW(Dte);var Ont=new Array(Int);vW(Ont);var lTe=new Array(n$);vW(lTe);function G9e(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 $Jt,VJt,HJt;function W9e(s,t){this.dyn_tree=s,this.max_code=0,this.stat_desc=t}function GJt(s){return s<256?Rte[s]:Rte[256+(s>>>7)]}function Ote(s,t){s.pending_buf[s.pending++]=t&255,s.pending_buf[s.pending++]=t>>>8&255}function __(s,t,n){s.bi_valid>H9e-n?(s.bi_buf|=t<>H9e-s.bi_valid,s.bi_valid+=n-H9e):(s.bi_buf|=t<>>=1,n<<=1;while(--t>0);return n>>>1}function cHn(s){s.bi_valid===16?(Ote(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 dHn(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,p,f,x=0;for(m=0;m<=cO;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]++,p=0,u>=o&&(p=l[u-o]),f=n[u*2],s.opt_len+=f*(m+p),i&&(s.static_len+=f*(a[u*2+1]+p)));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 KJt(s,t,n){var r=new Array(cO+1),a=0,i,l;for(i=1;i<=cO;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]=WJt(r[o]++,o))}}function uHn(){var s,t,n,r,a,i=new Array(cO+1);for(n=0,r=0;r>=7;r8?Ote(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 hHn(s,t,n,r){ZJt(s),Ote(s,n),Ote(s,~n),JVn.arraySet(s.pending_buf,s.window,t,n,s.pending),s.pending+=n}function tkt(s,t,n,r){var a=t*2,i=n*2;return s[a]>1;l>=1;l--)K9e(s,n,l);d=i;do l=s.heap[1],s.heap[1]=s.heap[s.heap_len--],K9e(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++,K9e(s,n,1);while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1],dHn(s,t),KJt(n,c,s.bl_count)}function nkt(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[qJt[t]*2+1]===0;t--);return s.opt_len+=3*(t+1)+5+5+4,t}function pHn(s,t,n,r){var a;for(__(s,t-257,5),__(s,n-1,5),__(s,r-4,4),a=0;a>>=1)if(t&1&&s.dyn_ltree[n*2]!==0)return JNt;if(s.dyn_ltree[9*2]!==0||s.dyn_ltree[10*2]!==0||s.dyn_ltree[13*2]!==0)return ekt;for(n=32;n0?(s.strm.data_type===tHn&&(s.strm.data_type=fHn(s)),lKe(s,s.l_desc),lKe(s,s.d_desc),l=mHn(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?XJt(s,t,n,r):s.strategy===eHn||i===a?(__(s,(OJt<<1)+(r?1:0),3),skt(s,DC,pJ)):(__(s,(nHn<<1)+(r?1:0),3),pHn(s,s.l_desc.max_code+1,s.d_desc.max_code+1,l+1),skt(s,s.dyn_ltree,s.dyn_dtree)),YJt(s),r&&ZJt(s)}function vHn(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[(Dte[n]+cae+1)*2]++,s.dyn_dtree[GJt(t)*2]++),s.last_lit===s.lit_bufsize-1}yW._tr_init=gHn;yW._tr_stored_block=XJt;yW._tr_flush_block=yHn;yW._tr_tally=vHn;yW._tr_align=xHn;function bHn(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 QJt=bHn;function _Hn(){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 wHn=_Hn();function jHn(s,t,n,r){var a=wHn,i=r+n;s^=-1;for(var l=r;l>>8^a[(s^t[l])&255];return s^-1}var JJt=jHn,Fnt={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"},Q1=SE,oN=yW,ees=QJt,IT=JJt,NHn=Fnt,$9=0,kHn=1,SHn=3,JM=4,ikt=5,h4=0,okt=1,lN=-2,CHn=-3,Y9e=-5,AHn=-1,EHn=1,fce=2,THn=3,MHn=4,PHn=0,LHn=2,CIe=8,IHn=9,RHn=15,DHn=8,OHn=29,FHn=256,cKe=FHn+1+OHn,zHn=30,BHn=19,UHn=2*cKe+1,qHn=15,Wd=3,lM=258,dS=lM+Wd+1,$Hn=32,AIe=42,dKe=69,q4e=73,$4e=91,V4e=103,dO=113,sX=666,a0=1,dae=2,t9=3,bW=4,VHn=3;function cM(s,t){return s.msg=NHn[t],t}function lkt(s){return(s<<1)-(s>4?9:0)}function u6(s){for(var t=s.length;--t>=0;)s[t]=0}function RT(s){var t=s.state,n=t.pending;n>s.avail_out&&(n=s.avail_out),n!==0&&(Q1.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 ov(s,t){oN._tr_flush_block(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,t),s.block_start=s.strstart,RT(s.strm)}function ku(s,t){s.pending_buf[s.pending++]=t}function OY(s,t){s.pending_buf[s.pending++]=t>>>8&255,s.pending_buf[s.pending++]=t&255}function HHn(s,t,n,r){var a=s.avail_in;return a>r&&(a=r),a===0?0:(s.avail_in-=a,Q1.arraySet(t,s.input,s.next_in,a,n),s.state.wrap===1?s.adler=ees(s.adler,t,a,n):s.state.wrap===2&&(s.adler=IT(s.adler,t,a,n)),s.next_in+=a,s.total_in+=a,a)}function tes(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-dS?s.strstart-(s.w_size-dS):0,d=s.window,u=s.w_mask,h=s.prev,m=s.strstart+lM,p=d[r+l-1],f=d[r+l];s.prev_length>=s.good_match&&(n>>=2),o>s.lookahead&&(o=s.lookahead);do if(a=t,!(d[a+l]!==f||d[a+l-1]!==p||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;p=d[r+l-1],f=d[r+l]}}while((t=h[t&u])>c&&--n!==0);return l<=s.lookahead?l:s.lookahead}function s9(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-dS)){Q1.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=HHn(s.strm,s.window,s.strstart+s.lookahead,i),s.lookahead+=r,s.lookahead+s.insert>=Wd)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(s9(s),s.lookahead===0&&t===$9)return a0;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,ov(s,!1),s.strm.avail_out===0)||s.strstart-s.block_start>=s.w_size-dS&&(ov(s,!1),s.strm.avail_out===0))return a0}return s.insert=0,t===JM?(ov(s,!0),s.strm.avail_out===0?t9:bW):(s.strstart>s.block_start&&(ov(s,!1),s.strm.avail_out===0),a0)}function Z9e(s,t){for(var n,r;;){if(s.lookahead=Wd&&(s.ins_h=(s.ins_h<=Wd)if(r=oN._tr_tally(s,s.strstart-s.match_start,s.match_length-Wd),s.lookahead-=s.match_length,s.match_length<=s.max_lazy_match&&s.lookahead>=Wd){s.match_length--;do s.strstart++,s.ins_h=(s.ins_h<=Wd&&(s.ins_h=(s.ins_h<4096)&&(s.match_length=Wd-1)),s.prev_length>=Wd&&s.match_length<=s.prev_length){a=s.strstart+s.lookahead-Wd,r=oN._tr_tally(s,s.strstart-1-s.prev_match,s.prev_length-Wd),s.lookahead-=s.prev_length-1,s.prev_length-=2;do++s.strstart<=a&&(s.ins_h=(s.ins_h<=Wd&&s.strstart>0&&(a=s.strstart-1,r=l[a],r===l[++a]&&r===l[++a]&&r===l[++a])){i=s.strstart+lM;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>=Wd?(n=oN._tr_tally(s,1,s.match_length-Wd),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0):(n=oN._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++),n&&(ov(s,!1),s.strm.avail_out===0))return a0}return s.insert=0,t===JM?(ov(s,!0),s.strm.avail_out===0?t9:bW):s.last_lit&&(ov(s,!1),s.strm.avail_out===0)?a0:dae}function KHn(s,t){for(var n;;){if(s.lookahead===0&&(s9(s),s.lookahead===0)){if(t===$9)return a0;break}if(s.match_length=0,n=oN._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,n&&(ov(s,!1),s.strm.avail_out===0))return a0}return s.insert=0,t===JM?(ov(s,!0),s.strm.avail_out===0?t9:bW):s.last_lit&&(ov(s,!1),s.strm.avail_out===0)?a0:dae}function h5(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 IU;IU=[new h5(0,0,0,0,GHn),new h5(4,4,8,4,Z9e),new h5(4,5,16,8,Z9e),new h5(4,6,32,32,Z9e),new h5(4,4,16,16,xB),new h5(8,16,32,32,xB),new h5(8,16,128,128,xB),new h5(8,32,128,256,xB),new h5(32,128,258,1024,xB),new h5(32,258,258,4096,xB)];function YHn(s){s.window_size=2*s.w_size,u6(s.head),s.max_lazy_match=IU[s.level].max_lazy,s.good_match=IU[s.level].good_length,s.nice_match=IU[s.level].nice_length,s.max_chain_length=IU[s.level].max_chain,s.strstart=0,s.block_start=0,s.lookahead=0,s.insert=0,s.match_length=s.prev_length=Wd-1,s.match_available=0,s.ins_h=0}function ZHn(){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=CIe,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 Q1.Buf16(UHn*2),this.dyn_dtree=new Q1.Buf16((2*zHn+1)*2),this.bl_tree=new Q1.Buf16((2*BHn+1)*2),u6(this.dyn_ltree),u6(this.dyn_dtree),u6(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Q1.Buf16(qHn+1),this.heap=new Q1.Buf16(2*cKe+1),u6(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Q1.Buf16(2*cKe+1),u6(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 ses(s){var t;return!s||!s.state?cM(s,lN):(s.total_in=s.total_out=0,s.data_type=LHn,t=s.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?AIe:dO,s.adler=t.wrap===2?0:1,t.last_flush=$9,oN._tr_init(t),h4)}function nes(s){var t=ses(s);return t===h4&&YHn(s.state),t}function XHn(s,t){return!s||!s.state||s.state.wrap!==2?lN:(s.state.gzhead=t,h4)}function res(s,t,n,r,a,i){if(!s)return lN;var l=1;if(t===AHn&&(t=6),r<0?(l=0,r=-r):r>15&&(l=2,r-=16),a<1||a>IHn||n!==CIe||r<8||r>15||t<0||t>9||i<0||i>MHn)return cM(s,lN);r===8&&(r=9);var o=new ZHn;return s.state=o,o.strm=s,o.wrap=l,o.gzhead=null,o.w_bits=r,o.w_size=1<ikt||t<0)return s?cM(s,lN):lN;if(r=s.state,!s.output||!s.input&&s.avail_in!==0||r.status===sX&&t!==JM)return cM(s,s.avail_out===0?Y9e:lN);if(r.strm=s,n=r.last_flush,r.last_flush=t,r.status===AIe)if(r.wrap===2)s.adler=0,ku(r,31),ku(r,139),ku(r,8),r.gzhead?(ku(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)),ku(r,r.gzhead.time&255),ku(r,r.gzhead.time>>8&255),ku(r,r.gzhead.time>>16&255),ku(r,r.gzhead.time>>24&255),ku(r,r.level===9?2:r.strategy>=fce||r.level<2?4:0),ku(r,r.gzhead.os&255),r.gzhead.extra&&r.gzhead.extra.length&&(ku(r,r.gzhead.extra.length&255),ku(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(s.adler=IT(s.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=dKe):(ku(r,0),ku(r,0),ku(r,0),ku(r,0),ku(r,0),ku(r,r.level===9?2:r.strategy>=fce||r.level<2?4:0),ku(r,VHn),r.status=dO);else{var l=CIe+(r.w_bits-8<<4)<<8,o=-1;r.strategy>=fce||r.level<2?o=0:r.level<6?o=1:r.level===6?o=2:o=3,l|=o<<6,r.strstart!==0&&(l|=$Hn),l+=31-l%31,r.status=dO,OY(r,l),r.strstart!==0&&(OY(r,s.adler>>>16),OY(r,s.adler&65535)),s.adler=1}if(r.status===dKe)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=IT(s.adler,r.pending_buf,r.pending-a,a)),RT(s),a=r.pending,r.pending===r.pending_buf_size));)ku(r,r.gzhead.extra[r.gzindex]&255),r.gzindex++;r.gzhead.hcrc&&r.pending>a&&(s.adler=IT(s.adler,r.pending_buf,r.pending-a,a)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=q4e)}else r.status=q4e;if(r.status===q4e)if(r.gzhead.name){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(s.adler=IT(s.adler,r.pending_buf,r.pending-a,a)),RT(s),a=r.pending,r.pending===r.pending_buf_size)){i=1;break}r.gzindexa&&(s.adler=IT(s.adler,r.pending_buf,r.pending-a,a)),i===0&&(r.gzindex=0,r.status=$4e)}else r.status=$4e;if(r.status===$4e)if(r.gzhead.comment){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(s.adler=IT(s.adler,r.pending_buf,r.pending-a,a)),RT(s),a=r.pending,r.pending===r.pending_buf_size)){i=1;break}r.gzindexa&&(s.adler=IT(s.adler,r.pending_buf,r.pending-a,a)),i===0&&(r.status=V4e)}else r.status=V4e;if(r.status===V4e&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&RT(s),r.pending+2<=r.pending_buf_size&&(ku(r,s.adler&255),ku(r,s.adler>>8&255),s.adler=0,r.status=dO)):r.status=dO),r.pending!==0){if(RT(s),s.avail_out===0)return r.last_flush=-1,h4}else if(s.avail_in===0&&lkt(t)<=lkt(n)&&t!==JM)return cM(s,Y9e);if(r.status===sX&&s.avail_in!==0)return cM(s,Y9e);if(s.avail_in!==0||r.lookahead!==0||t!==$9&&r.status!==sX){var c=r.strategy===fce?KHn(r,t):r.strategy===THn?WHn(r,t):IU[r.level].func(r,t);if((c===t9||c===bW)&&(r.status=sX),c===a0||c===t9)return s.avail_out===0&&(r.last_flush=-1),h4;if(c===dae&&(t===kHn?oN._tr_align(r):t!==ikt&&(oN._tr_stored_block(r,0,0,!1),t===SHn&&(u6(r.head),r.lookahead===0&&(r.strstart=0,r.block_start=0,r.insert=0))),RT(s),s.avail_out===0))return r.last_flush=-1,h4}return t!==JM?h4:r.wrap<=0?okt:(r.wrap===2?(ku(r,s.adler&255),ku(r,s.adler>>8&255),ku(r,s.adler>>16&255),ku(r,s.adler>>24&255),ku(r,s.total_in&255),ku(r,s.total_in>>8&255),ku(r,s.total_in>>16&255),ku(r,s.total_in>>24&255)):(OY(r,s.adler>>>16),OY(r,s.adler&65535)),RT(s),r.wrap>0&&(r.wrap=-r.wrap),r.pending!==0?h4:okt)}function eGn(s){var t;return!s||!s.state?lN:(t=s.state.status,t!==AIe&&t!==dKe&&t!==q4e&&t!==$4e&&t!==V4e&&t!==dO&&t!==sX?cM(s,lN):(s.state=null,t===dO?cM(s,CHn):h4))}function tGn(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!==AIe||r.lookahead))return lN;for(l===1&&(s.adler=ees(s.adler,t,n,0)),r.wrap=0,n>=r.w_size&&(l===0&&(u6(r.head),r.strstart=0,r.block_start=0,r.insert=0),u=new Q1.Buf8(r.w_size),Q1.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,s9(r);r.lookahead>=Wd;){a=r.strstart,i=r.lookahead-(Wd-1);do r.ins_h=(r.ins_h<=252?6:hT>=248?5:hT>=240?4:hT>=224?3:hT>=192?2:1;Fte[254]=Fte[254]=1;V9.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 oes(s,t){if(t<65534&&(s.subarray&&ies||!s.subarray&&aes))return String.fromCharCode.apply(null,EIe.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 oes(o,r)};V9.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+Fte[s[n]]>t?n:t};function sGn(){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 les=sGn,fJ=j3,gJ=SE,uKe=V9,hKe=Fnt,nGn=les,ces=Object.prototype.toString,rGn=0,X9e=4,r$=0,ckt=1,dkt=2,aGn=-1,iGn=0,oGn=8;function n9(s){if(!(this instanceof n9))return new n9(s);this.options=gJ.assign({level:aGn,method:oGn,chunkSize:16384,windowBits:15,memLevel:8,strategy:iGn,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 nGn,this.strm.avail_out=0;var n=fJ.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(n!==r$)throw new Error(hKe[n]);if(t.header&&fJ.deflateSetHeader(this.strm,t.header),t.dictionary){var r;if(typeof t.dictionary=="string"?r=uKe.string2buf(t.dictionary):ces.call(t.dictionary)==="[object ArrayBuffer]"?r=new Uint8Array(t.dictionary):r=t.dictionary,n=fJ.deflateSetDictionary(this.strm,r),n!==r$)throw new Error(hKe[n]);this._dict_set=!0}}n9.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?X9e:rGn,typeof s=="string"?n.input=uKe.string2buf(s):ces.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 gJ.Buf8(r),n.next_out=0,n.avail_out=r),a=fJ.deflate(n,i),a!==ckt&&a!==r$)return this.onEnd(a),this.ended=!0,!1;(n.avail_out===0||n.avail_in===0&&(i===X9e||i===dkt))&&(this.options.to==="string"?this.onData(uKe.buf2binstring(gJ.shrinkBuf(n.output,n.next_out))):this.onData(gJ.shrinkBuf(n.output,n.next_out)))}while((n.avail_in>0||n.avail_out===0)&&a!==ckt);return i===X9e?(a=fJ.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===r$):(i===dkt&&(this.onEnd(r$),n.avail_out=0),!0)};n9.prototype.onData=function(s){this.chunks.push(s)};n9.prototype.onEnd=function(s){s===r$&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=gJ.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};function znt(s,t){var n=new n9(t);if(n.push(s,!0),n.err)throw n.msg||hKe[n.err];return n.result}function lGn(s,t){return t=t||{},t.raw=!0,znt(s,t)}function cGn(s,t){return t=t||{},t.gzip=!0,znt(s,t)}lae.Deflate=n9;lae.deflate=znt;lae.deflateRaw=lGn;lae.gzip=cGn;var uae={},LS={},gce=30,dGn=12,uGn=function(t,n){var r,a,i,l,o,c,d,u,h,m,p,f,x,y,v,b,N,S,A,T,L,M,I,R,z;r=t.state,a=t.next_in,R=t.input,i=a+(t.avail_in-5),l=t.next_out,z=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,p=r.window,f=r.hold,x=r.bits,y=r.lencode,v=r.distcode,b=(1<>>24,f>>>=A,x-=A,A=S>>>16&255,A===0)z[l++]=S&65535;else if(A&16){T=S&65535,A&=15,A&&(x>>=A,x-=A),x<15&&(f+=R[a++]<>>24,f>>>=A,x-=A,A=S>>>16&255,A&16){if(L=S&65535,A&=15,xd){t.msg="invalid distance too far back",r.mode=gce;break e}if(f>>>=A,x-=A,A=l-o,L>A){if(A=L-A,A>h&&r.sane){t.msg="invalid distance too far back",r.mode=gce;break e}if(M=0,I=p,m===0){if(M+=u-A,A2;)z[l++]=I[M++],z[l++]=I[M++],z[l++]=I[M++],T-=3;T&&(z[l++]=I[M++],T>1&&(z[l++]=I[M++]))}else{M=l-L;do z[l++]=z[M++],z[l++]=z[M++],z[l++]=z[M++],T-=3;while(T>2);T&&(z[l++]=z[M++],T>1&&(z[l++]=z[M++]))}}else if(A&64){t.msg="invalid distance code",r.mode=gce;break e}else{S=v[(S&65535)+(f&(1<>3,a-=T,x-=T<<3,f&=(1<=1&&$[p]===0;p--);if(f>p&&(f=p),p===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===pkt||p!==1))return-1;for(H[1]=0,u=1;uhkt||t===fkt&&b>mkt)return 1;for(;;){Z=u-y,o[h]z?(Q=V[K+o[h]],le=I[R+o[h]]):(Q=96,le=0),S=1<>y)+A]=Z<<24|Q<<16|le|0;while(A!==0);for(S=1<>=1;if(S!==0?(N&=S-1,N+=S):N=0,h++,--$[u]===0){if(u===p)break;u=n[r+o[h]]}if(u>f&&(N&L)!==T){for(y===0&&(y=f),M+=m,x=u-y,v=1<hkt||t===fkt&&b>mkt)return 1;T=N&L,i[T]=f<<24|x<<16|M-l|0}}return N!==0&&(i[M+N]=u-y<<24|64<<16|0),c.bits=f,0},Ww=SE,mKe=QJt,m5=JJt,xGn=uGn,xJ=gGn,yGn=0,des=1,ues=2,gkt=4,vGn=5,xce=6,r9=0,bGn=1,_Gn=2,yN=-2,hes=-3,mes=-4,wGn=-5,xkt=8,pes=1,ykt=2,vkt=3,bkt=4,_kt=5,wkt=6,jkt=7,Nkt=8,kkt=9,Skt=10,cTe=11,lC=12,J9e=13,Ckt=14,eze=15,Akt=16,Ekt=17,Tkt=18,Mkt=19,yce=20,vce=21,Pkt=22,Lkt=23,Ikt=24,Rkt=25,Dkt=26,tze=27,Okt=28,Fkt=29,Ap=30,fes=31,jGn=32,NGn=852,kGn=592,SGn=15,CGn=SGn;function zkt(s){return(s>>>24&255)+(s>>>8&65280)+((s&65280)<<8)+((s&255)<<24)}function AGn(){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 Ww.Buf16(320),this.work=new Ww.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function ges(s){var t;return!s||!s.state?yN:(t=s.state,s.total_in=s.total_out=t.total=0,s.msg="",t.wrap&&(s.adler=t.wrap&1),t.mode=pes,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Ww.Buf32(NGn),t.distcode=t.distdyn=new Ww.Buf32(kGn),t.sane=1,t.back=-1,r9)}function xes(s){var t;return!s||!s.state?yN:(t=s.state,t.wsize=0,t.whave=0,t.wnext=0,ges(s))}function yes(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))?yN:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,xes(s))}function ves(s,t){var n,r;return s?(r=new AGn,s.state=r,r.window=null,n=yes(s,t),n!==r9&&(s.state=null),n):yN}function EGn(s){return ves(s,CGn)}var Bkt=!0,sze,nze;function TGn(s){if(Bkt){var t;for(sze=new Ww.Buf32(512),nze=new Ww.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(xJ(des,s.lens,0,288,sze,0,s.work,{bits:9}),t=0;t<32;)s.lens[t++]=5;xJ(ues,s.lens,0,32,nze,0,s.work,{bits:5}),Bkt=!1}s.lencode=sze,s.lenbits=9,s.distcode=nze,s.distbits=5}function bes(s,t,n,r){var a,i=s.state;return i.window===null&&(i.wsize=1<=i.wsize?(Ww.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),Ww.arraySet(i.window,t,n-r,a,i.wnext),r-=a,r?(Ww.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=m5(n.check,I,2,0),d=0,u=0,n.mode=ykt;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=Ap;break}if((d&15)!==xkt){s.msg="unknown compression method",n.mode=Ap;break}if(d>>>=4,u-=4,L=(d&15)+8,n.wbits===0)n.wbits=L;else if(L>n.wbits){s.msg="invalid window size",n.mode=Ap;break}n.dmax=1<>8&1),n.flags&512&&(I[0]=d&255,I[1]=d>>>8&255,n.check=m5(n.check,I,2,0)),d=0,u=0,n.mode=vkt;case vkt:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>8&255,I[2]=d>>>16&255,I[3]=d>>>24&255,n.check=m5(n.check,I,4,0)),d=0,u=0,n.mode=bkt;case bkt:for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>8),n.flags&512&&(I[0]=d&255,I[1]=d>>>8&255,n.check=m5(n.check,I,2,0)),d=0,u=0,n.mode=_kt;case _kt:if(n.flags&1024){for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=m5(n.check,I,2,0)),d=0,u=0}else n.head&&(n.head.extra=null);n.mode=wkt;case wkt:if(n.flags&1024&&(p=n.length,p>o&&(p=o),p&&(n.head&&(L=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Array(n.head.extra_len)),Ww.arraySet(n.head.extra,r,i,p,L)),n.flags&512&&(n.check=m5(n.check,r,p,i)),o-=p,i+=p,n.length-=p),n.length))break e;n.length=0,n.mode=jkt;case jkt:if(n.flags&2048){if(o===0)break e;p=0;do L=r[i+p++],n.head&&L&&n.length<65536&&(n.head.name+=String.fromCharCode(L));while(L&&p>9&1,n.head.done=!0),s.adler=n.check=0,n.mode=lC;break;case Skt:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>=u&7,u-=u&7,n.mode=tze;break}for(;u<3;){if(o===0)break e;o--,d+=r[i++]<>>=1,u-=1,d&3){case 0:n.mode=Ckt;break;case 1:if(TGn(n),n.mode=yce,t===xce){d>>>=2,u-=2;break e}break;case 2:n.mode=Ekt;break;case 3:s.msg="invalid block type",n.mode=Ap}d>>>=2,u-=2;break;case Ckt: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=Ap;break}if(n.length=d&65535,d=0,u=0,n.mode=eze,t===xce)break e;case eze:n.mode=Akt;case Akt:if(p=n.length,p){if(p>o&&(p=o),p>c&&(p=c),p===0)break e;Ww.arraySet(a,r,i,p,l),o-=p,i+=p,c-=p,l+=p,n.length-=p;break}n.mode=lC;break;case Ekt: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=Ap;break}n.have=0,n.mode=Tkt;case Tkt:for(;n.have>>=3,u-=3}for(;n.have<19;)n.lens[$[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,R={bits:n.lenbits},M=xJ(yGn,n.lens,0,19,n.lencode,0,n.work,R),n.lenbits=R.bits,M){s.msg="invalid code lengths set",n.mode=Ap;break}n.have=0,n.mode=Mkt;case Mkt:for(;n.have>>24,b=y>>>16&255,N=y&65535,!(v<=u);){if(o===0)break e;o--,d+=r[i++]<>>=v,u-=v,n.lens[n.have++]=N;else{if(N===16){for(z=v+2;u>>=v,u-=v,n.have===0){s.msg="invalid bit length repeat",n.mode=Ap;break}L=n.lens[n.have-1],p=3+(d&3),d>>>=2,u-=2}else if(N===17){for(z=v+3;u>>=v,u-=v,L=0,p=3+(d&7),d>>>=3,u-=3}else{for(z=v+7;u>>=v,u-=v,L=0,p=11+(d&127),d>>>=7,u-=7}if(n.have+p>n.nlen+n.ndist){s.msg="invalid bit length repeat",n.mode=Ap;break}for(;p--;)n.lens[n.have++]=L}}if(n.mode===Ap)break;if(n.lens[256]===0){s.msg="invalid code -- missing end-of-block",n.mode=Ap;break}if(n.lenbits=9,R={bits:n.lenbits},M=xJ(des,n.lens,0,n.nlen,n.lencode,0,n.work,R),n.lenbits=R.bits,M){s.msg="invalid literal/lengths set",n.mode=Ap;break}if(n.distbits=6,n.distcode=n.distdyn,R={bits:n.distbits},M=xJ(ues,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,R),n.distbits=R.bits,M){s.msg="invalid distances set",n.mode=Ap;break}if(n.mode=yce,t===xce)break e;case yce:n.mode=vce;case vce: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,xGn(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===lC&&(n.back=-1);break}for(n.back=0;y=n.lencode[d&(1<>>24,b=y>>>16&255,N=y&65535,!(v<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],v=y>>>24,b=y>>>16&255,N=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=N,b===0){n.mode=Dkt;break}if(b&32){n.back=-1,n.mode=lC;break}if(b&64){s.msg="invalid literal/length code",n.mode=Ap;break}n.extra=b&15,n.mode=Pkt;case Pkt:if(n.extra){for(z=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=Lkt;case Lkt:for(;y=n.distcode[d&(1<>>24,b=y>>>16&255,N=y&65535,!(v<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],v=y>>>24,b=y>>>16&255,N=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=Ap;break}n.offset=N,n.extra=b&15,n.mode=Ikt;case Ikt:if(n.extra){for(z=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=Ap;break}n.mode=Rkt;case Rkt:if(c===0)break e;if(p=m-c,n.offset>p){if(p=n.offset-p,p>n.whave&&n.sane){s.msg="invalid distance too far back",n.mode=Ap;break}p>n.wnext?(p-=n.wnext,f=n.wsize-p):f=n.wnext-p,p>n.length&&(p=n.length),x=n.window}else x=a,f=l-n.offset,p=n.length;p>c&&(p=c),c-=p,n.length-=p;do a[l++]=x[f++];while(--p);n.length===0&&(n.mode=vce);break;case Dkt:if(c===0)break e;a[l++]=n.length,c--,n.mode=vce;break;case tze: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 OGn,this.strm.avail_out=0;var n=a$.inflateInit2(this.strm,t.windowBits);if(n!==Sg.Z_OK)throw new Error(pKe[n]);if(this.header=new FGn,a$.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=H4e.string2buf(t.dictionary):wes.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=a$.inflateSetDictionary(this.strm,t.dictionary),n!==Sg.Z_OK)))throw new Error(pKe[n])}a9.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?Sg.Z_FINISH:Sg.Z_NO_FLUSH,typeof s=="string"?n.input=H4e.binstring2buf(s):wes.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 yJ.Buf8(r),n.next_out=0,n.avail_out=r),i=a$.inflate(n,Sg.Z_NO_FLUSH),i===Sg.Z_NEED_DICT&&a&&(i=a$.inflateSetDictionary(this.strm,a)),i===Sg.Z_BUF_ERROR&&u===!0&&(i=Sg.Z_OK,u=!1),i!==Sg.Z_STREAM_END&&i!==Sg.Z_OK)return this.onEnd(i),this.ended=!0,!1;n.next_out&&(n.avail_out===0||i===Sg.Z_STREAM_END||n.avail_in===0&&(l===Sg.Z_FINISH||l===Sg.Z_SYNC_FLUSH))&&(this.options.to==="string"?(o=H4e.utf8border(n.output,n.next_out),c=n.next_out-o,d=H4e.buf2string(n.output,o),n.next_out=c,n.avail_out=r-c,c&&yJ.arraySet(n.output,n.output,o,c,0),this.onData(d)):this.onData(yJ.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!==Sg.Z_STREAM_END);return i===Sg.Z_STREAM_END&&(l=Sg.Z_FINISH),l===Sg.Z_FINISH?(i=a$.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===Sg.Z_OK):(l===Sg.Z_SYNC_FLUSH&&(this.onEnd(Sg.Z_OK),n.avail_out=0),!0)};a9.prototype.onData=function(s){this.chunks.push(s)};a9.prototype.onEnd=function(s){s===Sg.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=yJ.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};function Bnt(s,t){var n=new a9(t);if(n.push(s,!0),n.err)throw n.msg||pKe[n.err];return n.result}function zGn(s,t){return t=t||{},t.raw=!0,Bnt(s,t)}uae.Inflate=a9;uae.inflate=Bnt;uae.inflateRaw=zGn;uae.ungzip=Bnt;var BGn=SE.assign,UGn=lae,qGn=uae,$Gn=_es,jes={};BGn(jes,UGn,qGn,$Gn);var VGn=jes;const TIe=od(VGn);var Ukt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",nX=new Uint8Array(256);for(var bce=0;bce>4,d[a++]=(l&15)<<4|o>>2,d[a++]=(o&3)<<6|c&63;return d},GGn=function(s){for(var t="",n=0;nr)throw new Error(Kx(t)+" must be at least "+n+" and at most "+r+", but was actually "+s)},ok=function(s,t,n,r){gr(s,t,["number","undefined"]),typeof s=="number"&&Kw(s,t,n,r)},Ses=function(s,t,n){if(gr(s,t,["number"]),s%n!==0)throw new Error(Kx(t)+" must be a multiple of "+n+", but was actually "+s)},vWn=function(s,t){if(!Number.isInteger(s))throw new Error(Kx(t)+" must be an integer, but was actually "+s)},PIe=function(s,t){if(![1,0].includes(Math.sign(s)))throw new Error(Kx(t)+" must be a positive number or 0, but was actually "+s)},ac=new Uint16Array(256);for(var jce=0;jce<256;jce++)ac[jce]=jce;ac[22]=Jl("");ac[24]=Jl("˘");ac[25]=Jl("ˇ");ac[26]=Jl("ˆ");ac[27]=Jl("˙");ac[28]=Jl("˝");ac[29]=Jl("˛");ac[30]=Jl("˚");ac[31]=Jl("˜");ac[127]=Jl("�");ac[128]=Jl("•");ac[129]=Jl("†");ac[130]=Jl("‡");ac[131]=Jl("…");ac[132]=Jl("—");ac[133]=Jl("–");ac[134]=Jl("ƒ");ac[135]=Jl("⁄");ac[136]=Jl("‹");ac[137]=Jl("›");ac[138]=Jl("−");ac[139]=Jl("‰");ac[140]=Jl("„");ac[141]=Jl("“");ac[142]=Jl("”");ac[143]=Jl("‘");ac[144]=Jl("’");ac[145]=Jl("‚");ac[146]=Jl("™");ac[147]=Jl("fi");ac[148]=Jl("fl");ac[149]=Jl("Ł");ac[150]=Jl("Œ");ac[151]=Jl("Š");ac[152]=Jl("Ÿ");ac[153]=Jl("Ž");ac[154]=Jl("ı");ac[155]=Jl("ł");ac[156]=Jl("œ");ac[157]=Jl("š");ac[158]=Jl("ž");ac[159]=Jl("�");ac[160]=Jl("€");ac[173]=Jl("�");var Ces=function(s){for(var t=new Array(s.length),n=0,r=s.length;n=tn.ExclamationPoint&&s<=tn.Tilde&&!Vnt[s]},Kkt={},Ykt=new Map,Ys=function(s){ai(t,s);function t(n,r){var a=this;if(n!==Kkt)throw new Unt("PDFName");a=s.call(this)||this;for(var i="/",l=0,o=r.length;l=tn.Zero&&d<=tn.Nine||d>=tn.a&&d<=tn.f||d>=tn.A&&d<=tn.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===tn.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+=iv(this.encodedName,n,r),this.encodedName.length},t.of=function(n){var r=OWn(n),a=Ykt.get(r);return a||(a=new t(Kkt,r),Ykt.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}(gb),zWn=function(s){ai(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++]=tn.n,n[r++]=tn.u,n[r++]=tn.l,n[r++]=tn.l,4},t}(gb);const h_=new zWn;var xc=function(s){ai(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===h_&&!r))return a},t.prototype.has=function(n){var r=this.dict.get(n);return r!==void 0&&r!==h_},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,Hu.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:Hu.of(0,65535),offset:0,deleted:!0})},s.createEmpty=function(){return new s},s}(),Gnt=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++]=tn.s,t[n++]=tn.t,t[n++]=tn.a,t[n++]=tn.r,t[n++]=tn.t,t[n++]=tn.x,t[n++]=tn.r,t[n++]=tn.e,t[n++]=tn.f,t[n++]=tn.Newline,n+=iv(this.lastXRefOffset,t,n),t[n++]=tn.Newline,t[n++]=tn.Percent,t[n++]=tn.Percent,t[n++]=tn.E,t[n++]=tn.O,t[n++]=tn.F,n-r},s.forLastCrossRefSectionOffset=function(t){return new s(t)},s}(),qWn=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++]=tn.t,t[n++]=tn.r,t[n++]=tn.a,t[n++]=tn.i,t[n++]=tn.l,t[n++]=tn.e,t[n++]=tn.r,t[n++]=tn.Newline,n+=this.dict.copyBytesInto(t,n),n-r},s.of=function(t){return new s(t)},s}(),Tes=function(s){ai(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(Ys.of("Type"),Ys.of("ObjStm")),i.dict.set(Ys.of("N"),ql.of(i.objects.length)),i.dict.set(Ys.of("First"),ql.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]=f),x>o[1]&&(o[1]=x),y>o[2]&&(o[2]=y)}return o},i.entries=r||[],i.entryTuplesCache=qA.populatedBy(i.computeEntryTuples),i.maxByteWidthsCache=qA.populatedBy(i.computeMaxEntryByteWidths),i.indexCache=qA.populatedBy(i.computeIndex),n.set(Ys.of("Type"),Ys.of("XRef")),i}return t.prototype.addDeletedEntry=function(n,r){var a=XT.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=XT.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=XT.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;f--)a+=(h[f]||0).toString(2);for(var f=r[1]-1;f>=0;f--)a+=(m[f]||0).toString(2);for(var f=r[2]-1;f>=0;f--)a+=(p[f]||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++]=p[x]||0;for(var x=r[2]-1;x>=0;x--)a[i++]=f[x]||0}return a},t.prototype.getUnencodedContentsSize=function(){var n=this.maxByteWidthsCache.access(),r=$Vn(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(Ys.of("W"),a.obj(n)),this.dict.set(Ys.of("Index"),a.obj(r))},t.create=function(n,r){r===void 0&&(r=!0);var a=new t(n,[],r);return a.addDeletedEntry(Hu.of(0,65535),0),a},t.of=function(n,r,a){return a===void 0&&(a=!0),new t(n,r,a)},t}(Hnt),VWn=function(s){ai(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 Nc(this,void 0,void 0,function(){var n,r,a,i,l,o,c,d,f,x,u,v,h,m,y,p,f,x,y,v,b,N,S,A;return kc(this,function(T){switch(T.label){case 0:n=this.context.largestObjectNumber+1,r=LIe.forVersion(1,7),a=r.sizeInBytes()+2,i=$Wn.create(this.createTrailerDict(),this.encodeStreams),l=[],o=[],c=[],d=this.context.enumerateIndirectObjects(),f=0,x=d.length,T.label=1;case 1:return f"},t.prototype.sizeInBytes=function(){return this.value.length+2},t.prototype.copyBytesInto=function(n,r){return n[r++]=tn.LessThan,r+=iv(this.value,n,r),n[r++]=tn.GreaterThan,this.value.length+2},t.of=function(n){return new t(n)},t.fromText=function(n){for(var r=WVn(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`},Jkt=function(){for(var s=[],t=0;t"},G4e=function(s){return aae(s,4)},WWn=function(s){if(KVn(s))return G4e(s);if(YVn(s)){var t=MJt(s),n=PJt(s);return""+G4e(t)+G4e(n)}var r=SIe(s),a="0x"+r+" is not a valid UTF-8 or UTF-16 codepoint.";throw new Error(a)},KWn=function(s){var t=0,n=function(r){t|=1<=tn.Zero&&d<=tn.Seven?(r+=c,(r.length===3||!(u>="0"&&u<="7"))&&(i(parseInt(r,8)),r="")):i(d):d===tn.BackSlash?a=!0:i(d)}return new Uint8Array(n)},t.prototype.decodeText=function(){var n=this.asBytes();return DJt(n)?LJt(n):Ces(n)},t.prototype.decodeDate=function(){var n=this.decodeText(),r=EJt(n);if(!r)throw new Aes(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++]=tn.LeftParen,r+=iv(this.value,n,r),n[r++]=tn.RightParen,this.value.length+2},t.of=function(n){return new t(n)},t.fromDate=function(n){var r=Bk(String(n.getUTCFullYear()),4,"0"),a=Bk(String(n.getUTCMonth()+1),2,"0"),i=Bk(String(n.getUTCDate()),2,"0"),l=Bk(String(n.getUTCHours()),2,"0"),o=Bk(String(n.getUTCMinutes()),2,"0"),c=Bk(String(n.getUTCSeconds()),2,"0");return new t("D:"+r+a+i+l+o+c+"Z")},t}(gb),Wnt=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-((p&7)<<0)&1,z=3*R;o[N]=S[z],o[N+1]=S[z+1],o[N+2]=S[z+2],o[N+3]=R>2)]>>6-((p&3)<<1)&3,z=3*R;o[N]=S[z],o[N+1]=S[z+1],o[N+2]=S[z+2],o[N+3]=R>1)]>>4-((p&1)<<2)&15,z=3*R;o[N]=S[z],o[N+1]=S[z+1],o[N+2]=S[z+2],o[N+3]=R>>3)]>>>7-(Z&7)&1),Q=H==y*255?0:255;c[K+Z]=Q<<24|H<<16|H<<8|H}else if(u==2)for(var Z=0;Z>>2)]>>>6-((Z&3)<<1)&3),Q=H==y*85?0:255;c[K+Z]=Q<<24|H<<16|H<<8|H}else if(u==4)for(var Z=0;Z>>1)]>>>4-((Z&1)<<2)&15),Q=H==y*17?0:255;c[K+Z]=Q<<24|H<<16|H<<8|H}else if(u==8)for(var Z=0;Z>>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 M=(m>>>3)+4,I=t[M-4]|t[M-3]<<8;L&&(n=s.H.W(n,h+I)),n.set(new r(t.buffer,t.byteOffset+M,I),h),m=M+I<<3,h+=I;continue}if(L&&(n=s.H.W(n,h+(1<<17))),i==1&&(p=T.J,f=T.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 R=1,z=0;z<38;z+=2)T.Q[z]=0,T.Q[z+1]=0;for(var z=0;zR&&(R=$)}m+=3*c,N(T.Q,R),S(T.Q,R,T.u),p=T.w,f=T.d,m=b(T.u,(1<>>4;if(!(Z>>>8))n[h++]=Z;else{if(Z==256)break;var Q=h+Z-254;if(Z>264){var le=T.q[Z-257];Q=h+(le>>>3)+v(t,m,le&7),m+=le&7}var ue=f[A(t,m)&u];m+=ue&15;var se=ue>>>4,ne=T.c[se],ie=(ne>>>4)+y(t,m,ne&15);for(m+=ne&15;h>>4;if(h<=15)l[d]=h,d++;else{var m=0,p=0;h==16?(p=3+o(a,i,2),i+=2,m=l[d-1]):h==17?(p=3+o(a,i,3),i+=3):h==18&&(p=11+o(a,i,7),i+=7);for(var f=d+p;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[f]=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}();Ca.decode._readInterlace=function(s,t){for(var n=t.width,r=t.height,a=Ca.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],p=0;p<7;){for(var f=h[p],x=m[p],y=0,v=0,b=d[p];b>3];I=I>>7-(M&7)&1,o[T*l+(L>>3)]|=I<<7-((L&7)<<0)}if(a==2){var I=s[M>>3];I=I>>6-(M&7)&3,o[T*l+(L>>2)]|=I<<6-((L&3)<<1)}if(a==4){var I=s[M>>3];I=I>>4-(M&7)&15,o[T*l+(L>>1)]|=I<<4-((L&1)<<2)}if(a>=8)for(var R=T*l+L*i,z=0;z>3)+z];M+=a,L+=x}A++,T+=f}y*v!=0&&(c+=v*(1+S)),p=p+1}return o};Ca.decode._getBPP=function(s){var t=[1,null,3,1,2,null,4][s.ctype];return t*s.depth};Ca.decode._filterZero=function(s,t,n,r,a){var i=Ca.decode._getBPP(t),l=Math.ceil(r*i/8),o=Ca.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=p*t+f<<2,m=(o+p)*a+l+f<<2):(h=(-o+p)*t-l+f<<2,m=p*a+f<<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,N=r[m+3]*(1/255),S=r[m]*N,A=r[m+1]*N,T=r[m+2]*N,L=1-x,M=x+N*L,I=M==0?0:1/M;r[m+3]=255*M,r[m+0]=(y+S*L)*I,r[m+1]=(v+A*L)*I,r[m+2]=(b+T*L)*I}else if(c==2){var x=s[h+3],y=s[h],v=s[h+1],b=s[h+2],N=r[m+3],S=r[m],A=r[m+1],T=r[m+2];x==N&&y==S&&v==A&&b==T?(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],N=r[m+3],S=r[m],A=r[m+1],T=r[m+2];if(x==N&&y==S&&v==A&&b==T)continue;if(x<220&&N>20)return!1}return!0};Ca.encode=function(s,t,n,r,a,i,l){r==null&&(r=0),l==null&&(l=!1);var o=Ca.encode.compress(s,t,n,r,[!1,!1,!1,0,l]);return Ca.encode.compressPNG(o,-1),Ca.encode._main(o,t,n,a,i)};Ca.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 p=s.plte.length,f=0;f>>24!=255&&(h=!0);m+=8+p*3+4+(h?8+p*1+4:0)}for(var x=0;x>>8&255,L=S>>>16&255;v[d+N+0]=A,v[d+N+1]=T,v[d+N+2]=L}if(d+=p*3,l(v,d,i(v,d-p*3-4,p*3+4)),d+=4,h){l(v,d,p),d+=4,c(v,d,"tRNS"),d+=4;for(var f=0;f>>24&255;d+=p,l(v,d,i(v,d-p-4,p+4)),d+=4}}for(var M=0,x=0;x>2,$>>2));for(var p=0;p<$;p+=4)z[p]=R[I+p],z[p+1]=R[I+p+1],z[p+2]=R[I+p+2],z[p+3]=R[I+p+3];I+=$}for(var y=0;yK&&Q==V[y-K])Z[y]=Z[y-K];else{var le=N[Q];if(le==null&&(N[Q]=le=S.length,S.push(Q),S.length>=300))break;Z[y]=le}}}var ue=S.length;ue<=256&&d==!1&&(ue<=2?h=1:ue<=4?h=2:ue<=16?h=4:h=8,h=Math.max(h,c));for(var p=0;p>1)]|=be[ge+ke]<<4-(ke&1)*4;else if(h==2)for(var ke=0;ke>2)]|=be[ge+ke]<<6-(ke&3)*2;else if(h==1)for(var ke=0;ke>3)]|=be[ge+ke]<<7-(ke&7)*1}ne=je,u=3,ce=1}else if(v==!1&&b.length==1){for(var je=new Uint8Array(K*se*3),Te=K*se,y=0;yL&&(L=R),IM&&(M=I))}L==-1&&(A=T=L=M=0),a&&((A&1)==1&&A--,(T&1)==1&&T--);var $=(L-A+1)*(M-T+1);$y&&(y=S),Av&&(v=A))}y==-1&&(f=x=y=v=0),l&&((f&1)==1&&f--,(x&1)==1&&x--),i={x:f,y:x,width:y-f+1,height:v-x+1};var M=r[a];M.rect=i,M.blend=1,M.img=new Uint8Array(i.width*i.height*4),r[a-1].dispose==0?(Ca._copyTile(d,t,n,M.img,i.width,i.height,-i.x,-i.y,0),Ca.encode._prepareDiff(m,t,n,M.img,i)):Ca._copyTile(m,t,n,M.img,i.width,i.height,-i.x,-i.y,0)};Ca.encode._prepareDiff=function(s,t,n,r,a){Ca._copyTile(s,t,n,r,a.width,a.height,-a.x,-a.y,2)};Ca.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:TIe,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 Ca.crc.update(4294967295,s,t,n)^4294967295}};Ca.quantize=function(s,t){var n=new Uint8Array(s),r=n.slice(0),a=new Uint32Array(r.buffer),i=Ca.quantize.getKDtree(r,t),l=i[0],o=i[1];Ca.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}};Ca.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=Ca.quantize.stats(s,a.i0,a.i1),a.est=Ca.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=Ca.quantize.stats(s,m.i0,m.i1),m.est=Ca.quantize.estats(m.bst);var p={i0:u,i1:d.i1,bst:null,est:null,tdst:0,left:null,right:null};p.bst={R:[],m:[],N:d.bst.N-m.bst.N};for(var c=0;c<16;c++)p.bst.R[c]=d.bst.R[c]-m.bst.R[c];for(var c=0;c<4;c++)p.bst.m[c]=d.bst.m[c]-m.bst.m[c];p.est=Ca.quantize.estats(p.bst),d.left=m,d.right=p,i[o]=m,i.push(p)}i.sort(function(f,x){return x.bst.N-f.bst.N});for(var c=0;c0&&(l=s.right,o=s.left);var c=Ca.quantize.getNearest(l,t,n,r,a);if(c.tdst<=i*i)return c;var d=Ca.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};Ca.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]};Ca.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}};Ca.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]]}};Ca.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=eKn(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=JWn(n.ctype),this.width=n.width,this.height=n.height,this.bitsPerComponent=8}return s.load=function(t){return new s(t)},s}(),Ies=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 Nc(this,void 0,void 0,function(){var n;return kc(this,function(r){return n=tKn.load(t),[2,new s(n)]})})},s.prototype.embedIntoContext=function(t,n){return Nc(this,void 0,void 0,function(){var r,a;return kc(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}(),Res=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}(),sKn=new Uint8Array(0),hae=function(){function s(t){if(this.pos=0,this.bufferLength=0,this.eof=!1,this.buffer=sKn,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 Res(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 $2(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}(hae),rKn=function(s){ai(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}(hae),sSt=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),aKn=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]),iKn=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]),oKn=[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],lKn=[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],cKn=function(s){ai(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++]=M}m=this.generateHuffmanTable(A.subarray(0,f)),p=this.generateHuffmanTable(A.subarray(f,S))}else throw new Error("Unknown block type in flate stream");n=this.buffer;for(var z=n?n.length:0,$=this.bufferLength;;){var H=this.getCode(m);if(H<256){$+1>=z&&(n=this.ensureBuffer($+1),z=n.length),n[$++]=H;continue}if(H===256){this.bufferLength=$;return}H-=257,H=aKn[H];var V=H>>16;V>0&&(V=this.getBits(V)),r=(H&65535)+V,H=this.getCode(p),H=iKn[H],V=H>>16,V>0&&(V=this.getBits(V));var K=(H&65535)+V;$+r>=z&&(n=this.ensureBuffer($+r),z=n.length);for(var Z=0;Z>n,this.codeSize=a-=n,l},t.prototype.getCode=function(n){for(var r=this.stream,a=n[0],i=n[1],l=this.codeSize,o=this.codeBuf,c;l>16,h=d&65535;if(u<1||l>u,this.codeSize=l-u,h},t.prototype.generateHuffmanTable=function(n){var r=n.length,a=0,i;for(i=0;ia&&(a=n[i]);for(var l=1<>=1;for(i=m;i0;if(!A||A<256)y[0]=A,v=1;else if(A>=258)if(A=0;l--)y[l]=h[o],o=p[o];else y[v++]=y[0];else if(A===256){f=9,u=258,v=0;continue}else{this.eof=!0,delete this.lzwState;break}if(T&&(p[u]=x,m[u]=m[x]+1,h[u]=y[0],u++,f=u+d&u+d-1?f: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 uTe(n,0,r.size());r.remove(n)}else{if(n!==0)throw new uTe(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(Ys.of("Kids"),n)),{Kids:n}},t.fromDict=function(n,r){return new t(n,r)},t}(Fes),Knt=function(s){ai(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.Opt=function(){return this.dict.lookupMaybe(Ys.of("Opt"),$u,Sl,gu)},t.prototype.setOpt=function(n){this.dict.set(Ys.of("Opt"),this.dict.context.obj(n))},t.prototype.getExportValues=function(){var n=this.Opt();if(n){if(n instanceof $u||n instanceof Sl)return[n];for(var r=[],a=0,i=n.size();ar.size())throw new uTe(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(Uu.MultiSelect))throw new kWn;this.dict.set(Ys.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,$u,Sl),c=l.lookupMaybe(1,$u,Sl);r.push({value:o,display:c||o})}}return r}return[]},t}(_W),RIe=function(s){ai(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:Uu.Combo,Kids:[]}),a=n.register(r);return new t(r,a)},t}(zes),pTe=function(s){ai(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(Ys.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}(Fes),Ynt=function(s){ai(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.fromDict=function(n,r){return new t(n,r)},t}(_W),DIe=function(s){ai(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.MaxLen=function(){var n=this.dict.lookup(Ys.of("MaxLen"));if(n instanceof ql)return n},t.prototype.Q=function(){var n=this.dict.lookup(Ys.of("Q"));if(n instanceof ql)return n},t.prototype.setMaxLength=function(n){this.dict.set(Ys.of("MaxLen"),ql.of(n))},t.prototype.removeMaxLength=function(){this.dict.delete(Ys.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(Ys.of("Q"),ql.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(Ys.of("V"),n)},t.prototype.removeValue=function(){this.dict.delete(Ys.of("V"))},t.prototype.getValue=function(){var n=this.V();if(n instanceof $u||n instanceof Sl)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}(_W),OIe=function(s){ai(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:E2.PushButton,Kids:[]}),a=n.register(r);return new t(r,a)},t}(Knt),FIe=function(s){ai(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!==Ys.of("Off"))throw new $nt;this.dict.set(Ys.of("V"),n);for(var a=this.getWidgets(),i=0,l=a.length;ii)throw new Hkt(r,i);for(var l=r,o=0,c=a.size();ol)return u.insertLeafNode(n,l)||d;l-=u.Count().asNumber()}u instanceof $A&&(l-=1)}if(l===0){this.insertLeafKid(a.size(),n);return}throw new Gkt(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 Hkt(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 $A)if(l===0){this.removeKid(o);return}else l-=1}throw new Gkt(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()&&CE[this.bytes.peek()];)this.bytes.next()},s.prototype.skipLine=function(){for(;!this.bytes.done();){var t=this.bytes.peek();if(t===aSt||t===iSt)return;this.bytes.next()}},s.prototype.skipComment=function(){if(this.bytes.peek()!==tn.Percent)return!1;for(;!this.bytes.done();){var t=this.bytes.peek();if(t===aSt||t===iSt)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(Des(t).decode())},s}(),wKn=tn.Space,BY=tn.CarriageReturn,UY=tn.Newline,qY=[tn.s,tn.t,tn.r,tn.e,tn.a,tn.m],kce=[tn.e,tn.n,tn.d,tn.s,tn.t,tn.r,tn.e,tn.a,tn.m],Dh={header:[tn.Percent,tn.P,tn.D,tn.F,tn.Dash],eof:[tn.Percent,tn.Percent,tn.E,tn.O,tn.F],obj:[tn.o,tn.b,tn.j],endobj:[tn.e,tn.n,tn.d,tn.o,tn.b,tn.j],xref:[tn.x,tn.r,tn.e,tn.f],trailer:[tn.t,tn.r,tn.a,tn.i,tn.l,tn.e,tn.r],startxref:[tn.s,tn.t,tn.a,tn.r,tn.t,tn.x,tn.r,tn.e,tn.f],true:[tn.t,tn.r,tn.u,tn.e],false:[tn.f,tn.a,tn.l,tn.s,tn.e],null:[tn.n,tn.u,tn.l,tn.l],stream:qY,streamEOF1:Kd(qY,[wKn,BY,UY]),streamEOF2:Kd(qY,[BY,UY]),streamEOF3:Kd(qY,[BY]),streamEOF4:Kd(qY,[UY]),endstream:kce,EOF1endstream:Kd([BY,UY],kce),EOF2endstream:Kd([BY],kce),EOF3endstream:Kd([UY],kce)},Ves=function(s){ai(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(Dh.true))return Bte.True;if(this.matchKeyword(Dh.false))return Bte.False;if(this.matchKeyword(Dh.null))return h_;var n=this.bytes.peek();if(n===tn.LessThan&&this.bytes.peekAhead(1)===tn.LessThan)return this.parseDictOrStream();if(n===tn.LessThan)return this.parseHexString();if(n===tn.LeftParen)return this.parseString();if(n===tn.ForwardSlash)return this.parseName();if(n===tn.LeftSquareBracket)return this.parseArray();if(Qnt[n])return this.parseNumberOrRef();throw new EWn(this.bytes.position(),n)},t.prototype.parseNumberOrRef=function(){var n=this.parseRawNumber();this.skipWhitespaceAndComments();var r=this.bytes.offset();if(m1[this.bytes.peek()]){var a=this.parseRawNumber();if(this.skipWhitespaceAndComments(),this.bytes.peek()===tn.R)return this.bytes.assertNext(tn.R),Hu.of(n,a)}return this.bytes.moveTo(r),ql.of(n)},t.prototype.parseHexString=function(){var n="";for(this.bytes.assertNext(tn.LessThan);!this.bytes.done()&&this.bytes.peek()!==tn.GreaterThan;)n+=UA(this.bytes.next());return this.bytes.assertNext(tn.GreaterThan),Sl.of(n)},t.prototype.parseString=function(){for(var n=0,r=!1,a="";!this.bytes.done();){var i=this.bytes.next();if(a+=UA(i),r||(i===tn.LeftParen&&(n+=1),i===tn.RightParen&&(n-=1)),i===tn.BackSlash?r=!r:r&&(r=!1),n===0)return $u.of(a.substring(1,a.length-1))}throw new PWn(this.bytes.position())},t.prototype.parseName=function(){this.bytes.assertNext(tn.ForwardSlash);for(var n="";!this.bytes.done();){var r=this.bytes.peek();if(CE[r]||MN[r])break;n+=UA(r),this.bytes.next()}return Ys.of(n)},t.prototype.parseArray=function(){this.bytes.assertNext(tn.LeftSquareBracket),this.skipWhitespaceAndComments();for(var n=gu.withContext(this.context);this.bytes.peek()!==tn.RightSquareBracket;){var r=this.parseObject();n.push(r),this.skipWhitespaceAndComments()}return this.bytes.assertNext(tn.RightSquareBracket),n},t.prototype.parseDict=function(){this.bytes.assertNext(tn.LessThan),this.bytes.assertNext(tn.LessThan),this.skipWhitespaceAndComments();for(var n=new Map;!this.bytes.done()&&this.bytes.peek()!==tn.GreaterThan&&this.bytes.peekAhead(1)!==tn.GreaterThan;){var r=this.parseName(),a=this.parseObject();n.set(r,a),this.skipWhitespaceAndComments()}this.skipWhitespaceAndComments(),this.bytes.assertNext(tn.GreaterThan),this.bytes.assertNext(tn.GreaterThan);var i=n.get(Ys.of("Type"));return i===Ys.of("Catalog")?qes.fromMapWithContext(n,this.context):i===Ys.of("Pages")?$es.fromMapWithContext(n,this.context):i===Ys.of("Page")?$A.fromMapWithContext(n,this.context):xc.fromMapWithContext(n,this.context)},t.prototype.parseDictOrStream=function(){var n=this.bytes.position(),r=this.parseDict();if(this.skipWhitespaceAndComments(),!this.matchKeyword(Dh.streamEOF1)&&!this.matchKeyword(Dh.streamEOF2)&&!this.matchKeyword(Dh.streamEOF3)&&!this.matchKeyword(Dh.streamEOF4)&&!this.matchKeyword(Dh.stream))return r;var a=this.bytes.offset(),i,l=r.get(Ys.of("Length"));l instanceof ql?(i=a+l.asNumber(),this.bytes.moveTo(i),this.skipWhitespaceAndComments(),this.matchKeyword(Dh.endstream)||(this.bytes.moveTo(a),i=this.findEndOfStreamFallback(n))):i=this.findEndOfStreamFallback(n);var o=this.bytes.slice(a,i);return Ute.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(Dh.stream)?r+=1:this.matchKeyword(Dh.EOF1endstream)||this.matchKeyword(Dh.EOF2endstream)||this.matchKeyword(Dh.EOF3endstream)||this.matchKeyword(Dh.endstream)?r-=1:this.bytes.next(),r!==0););if(r!==0)throw new MWn(n);return a},t.forBytes=function(n,r,a){return new t(UIe.of(n),r,a)},t.forByteStream=function(n,r,a){return a===void 0&&(a=!1),new t(n,r,a)},t}(_Kn),jKn=function(s){ai(t,s);function t(n,r){var a=s.call(this,UIe.fromPDFRawStream(n),n.dict.context)||this,i=n.dict;return a.alreadyParsed=!1,a.shouldWaitForTick=r||function(){return!1},a.firstOffset=i.lookup(Ys.of("First"),ql).asNumber(),a.objectCount=i.lookup(Ys.of("N"),ql).asNumber(),a}return t.prototype.parseIntoContext=function(){return Nc(this,void 0,void 0,function(){var n,r,a,i,l,o,c,d;return kc(this,function(u){switch(u.label){case 0:if(this.alreadyParsed)throw new qnt("PDFObjectStreamParser","parseIntoContext");this.alreadyParsed=!0,n=this.parseOffsetsAndObjectNumbers(),r=0,a=n.length,u.label=1;case 1:return r=tn.Space&&r<=tn.Tilde;if(a&&(this.matchKeyword(Dh.xref)||this.matchKeyword(Dh.trailer)||this.matchKeyword(Dh.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}(Ves),p5=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},FKn=function(s){Mo=Po=Md=Pd=rX=aX=0;for(var t=[],n=0;n1&&(m=Math.sqrt(m),n*=m,r*=m);var p=h/n,f=u/n,x=-u/r,y=h/r,v=p*o+f*c,b=x*o+y*c,N=p*s+f*t,S=x*s+y*t,A=(N-v)*(N-v)+(S-b)*(S-b),T=1/A-.25;T<0&&(T=0);var L=Math.sqrt(T);i===a&&(L=-L);var M=.5*(v+N)-L*(S-b),I=.5*(b+S)+L*(N-v),R=Math.atan2(b-I,v-M),z=Math.atan2(S-I,N-M),$=z-R;$<0&&i===1?$+=2*Math.PI:$>0&&i===0&&($-=2*Math.PI);for(var H=Math.ceil(Math.abs($/(Math.PI*.5+.001))),V=[],K=0;Ks.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},iYn=function(s,t,n,r){for(var a=n.width/r,i=n.height,l=lts,o=RVn(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},oYn=function(s){for(var t=s.length;t>0;t--)if(/\s/.test(s[t]))return t},lYn=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=L+A),f+o>p&&(p=f+o),d.push({text:N,encoded:S,width:A,height:o,x:L,y:f}),v=T==null?void 0:T.trim()}return{fontSize:r,lineHeight:c,lines:d,bounds:{x:u,y:h,width:m-u,height:p-h}}},cYn=function(s,t){var n=t.fontSize,r=t.font,a=t.bounds,i=t.cellCount,l=CJt(iae(s));if(l.length>i)throw new nYn(l.length,i);(n===void 0||n===0)&&(n=iYn(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,p=a.x+a.width,f=a.y+a.height,x=0,y=0;xp&&(p=L+A),d+c>f&&(f=d+c),u.push({text:l,encoded:S,width:A,height:c,x:L,y:d}),x+=1,y+=N}return{fontSize:n,cells:u,bounds:{x:h,y:m,width:p-h,height:f-m}}},bTe=function(s,t){var n=t.alignment,r=t.fontSize,a=t.font,i=t.bounds,l=CJt(iae(s));(r===void 0||r===0)&&(r=dts([l],a,i));var o=a.encodeText(l),c=a.widthOfTextAtSize(l,r),d=a.heightAtSize(r,{descender:!1}),u=n===Jx.Left?i.x:n===Jx.Center?i.x+i.width/2-c/2:n===Jx.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}}},jW=function(s){return"normal"in s?s:{normal:s}},dYn=/\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]+(\d*\.\d+|\d+)[\0\t\n\f\r\ ]+Tf/,kP=function(s){var t,n,r=(t=s.getDefaultAppearance())!==null&&t!==void 0?t:"",a=(n=Lnt(r,dYn).match)!==null&&n!==void 0?n:[],i=Number(a[2]);return isFinite(i)?i:void 0},uYn=/(\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)/,vN=function(s){var t,n=(t=s.getDefaultAppearance())!==null&&t!==void 0?t:"",r=Lnt(n,uYn).match,a=r??[],i=a[1],l=a[2],o=a[3],c=a[4],d=a[5];if(d==="g"&&i)return nts(Number(i));if(d==="rg"&&i&&l&&o)return Au(Number(i),Number(l),Number(o));if(d==="k"&&i&&l&&o&&c)return rts(Number(i),Number(l),Number(o),Number(c))},bN=function(s,t,n,r){var a;r===void 0&&(r=0);var i=[W9(t).toString(),srt((a=n==null?void 0:n.name)!==null&&a!==void 0?a:"dummy__noop",r).toString()].join(` `);s.setDefaultAppearance(i)},hYn=function(s,t){var n,r,a,i=vN(t),l=vN(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=AE(c==null?void 0:c.getRotation()),m=H9(o,h),p=m.width,f=m.height,x=fL(ec(ec({},o),{rotation:h})),y=Au(0,0,0),v=(r=xb(c==null?void 0:c.getBorderColor()))!==null&&r!==void 0?r:y,b=xb(c==null?void 0:c.getBackgroundColor()),N=xb(c==null?void 0:c.getBackgroundColor(),.8),S=(a=i??l)!==null&&a!==void 0?a:y;bN(i?t:s.acroField,S);var A={x:0+u/2,y:0+u/2,width:p-u,height:f-u,thickness:1.5,borderWidth:u,borderColor:v,markColor:S};return{normal:{on:Kd(x,Ace(ec(ec({},A),{color:b,filled:!0}))),off:Kd(x,Ace(ec(ec({},A),{color:b,filled:!1})))},down:{on:Kd(x,Ace(ec(ec({},A),{color:N,filled:!0}))),off:Kd(x,Ace(ec(ec({},A),{color:N,filled:!1})))}}},mYn=function(s,t){var n,r,a,i=vN(t),l=vN(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=AE(c==null?void 0:c.getRotation()),m=H9(o,h),p=m.width,f=m.height,x=fL(ec(ec({},o),{rotation:h})),y=Au(0,0,0),v=(r=xb(c==null?void 0:c.getBorderColor()))!==null&&r!==void 0?r:y,b=xb(c==null?void 0:c.getBackgroundColor()),N=xb(c==null?void 0:c.getBackgroundColor(),.8),S=(a=i??l)!==null&&a!==void 0?a:y;bN(i?t:s.acroField,S);var A={x:p/2,y:f/2,width:p-u,height:f-u,borderWidth:u,borderColor:v,dotColor:S};return{normal:{on:Kd(x,Ece(ec(ec({},A),{color:b,filled:!0}))),off:Kd(x,Ece(ec(ec({},A),{color:b,filled:!1})))},down:{on:Kd(x,Ece(ec(ec({},A),{color:N,filled:!0}))),off:Kd(x,Ece(ec(ec({},A),{color:N,filled:!1})))}}},pYn=function(s,t,n){var r,a,i,l,o,c=vN(t),d=vN(s.acroField),u=kP(t),h=kP(s.acroField),m=t.getRectangle(),p=t.getAppearanceCharacteristics(),f=t.getBorderStyle(),x=p==null?void 0:p.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=f==null?void 0:f.getWidth())!==null&&l!==void 0?l:0,N=AE(p==null?void 0:p.getRotation()),S=H9(m,N),A=S.width,T=S.height,L=fL(ec(ec({},m),{rotation:N})),M=Au(0,0,0),I=xb(p==null?void 0:p.getBorderColor()),R=xb(p==null?void 0:p.getBackgroundColor()),z=xb(p==null?void 0:p.getBackgroundColor(),.8),$={x:b,y:b,width:A-b*2,height:T-b*2},H=bTe(y,{alignment:Jx.Center,fontSize:u??h,font:n,bounds:$}),V=bTe(v,{alignment:Jx.Center,fontSize:u??h,font:n,bounds:$}),K=Math.min(H.fontSize,V.fontSize),Z=(o=c??d)!==null&&o!==void 0?o:M;bN(c||u!==void 0?t:s.acroField,Z,n,K);var Q={x:0+b/2,y:0+b/2,width:A-b,height:T-b,borderWidth:b,borderColor:I,textColor:Z,font:n.name,fontSize:K};return{normal:Kd(L,mSt(ec(ec({},Q),{color:R,textLines:[H.line]}))),down:Kd(L,mSt(ec(ec({},Q),{color:z,textLines:[V.line]})))}},fYn=function(s,t,n){var r,a,i,l,o=vN(t),c=vN(s.acroField),d=kP(t),u=kP(s.acroField),h=t.getRectangle(),m=t.getAppearanceCharacteristics(),p=t.getBorderStyle(),f=(r=s.getText())!==null&&r!==void 0?r:"",x=(a=p==null?void 0:p.getWidth())!==null&&a!==void 0?a:0,y=AE(m==null?void 0:m.getRotation()),v=H9(h,y),b=v.width,N=v.height,S=fL(ec(ec({},h),{rotation:y})),A=Au(0,0,0),T=xb(m==null?void 0:m.getBorderColor()),L=xb(m==null?void 0:m.getBackgroundColor()),M,I,R=s.isCombed()?0:1,z={x:x+R,y:x+R,width:b-(x+R)*2,height:N-(x+R)*2};if(s.isMultiline()){var $=uts(f,{alignment:s.getAlignment(),fontSize:d??u,font:n,bounds:z});M=$.lines,I=$.fontSize}else if(s.isCombed()){var $=cYn(f,{fontSize:d??u,font:n,bounds:z,cellCount:(i=s.getMaxLength())!==null&&i!==void 0?i:0});M=$.cells,I=$.fontSize}else{var $=bTe(f,{alignment:s.getAlignment(),fontSize:d??u,font:n,bounds:z});M=[$.line],I=$.fontSize}var H=(l=o??c)!==null&&l!==void 0?l:A;bN(o||d!==void 0?t:s.acroField,H,n,I);var V={x:0+x/2,y:0+x/2,width:b-x,height:N-x,borderWidth:x??0,borderColor:T,textColor:H,font:n.name,fontSize:I,color:L,textLines:M,padding:R};return Kd(S,its(V))},gYn=function(s,t,n){var r,a,i,l=vN(t),o=vN(s.acroField),c=kP(t),d=kP(s.acroField),u=t.getRectangle(),h=t.getAppearanceCharacteristics(),m=t.getBorderStyle(),p=(r=s.getSelected()[0])!==null&&r!==void 0?r:"",f=(a=m==null?void 0:m.getWidth())!==null&&a!==void 0?a:0,x=AE(h==null?void 0:h.getRotation()),y=H9(u,x),v=y.width,b=y.height,N=fL(ec(ec({},u),{rotation:x})),S=Au(0,0,0),A=xb(h==null?void 0:h.getBorderColor()),T=xb(h==null?void 0:h.getBackgroundColor()),L=1,M={x:f+L,y:f+L,width:v-(f+L)*2,height:b-(f+L)*2},I=bTe(p,{alignment:Jx.Left,fontSize:c??d,font:n,bounds:M}),R=I.line,z=I.fontSize,$=(i=l??o)!==null&&i!==void 0?i:S;bN(l||c!==void 0?t:s.acroField,$,n,z);var H={x:0+f/2,y:0+f/2,width:v-f,height:b-f,borderWidth:f??0,borderColor:A,textColor:$,font:n.name,fontSize:z,color:T,textLines:[R],padding:L};return Kd(N,its(H))},xYn=function(s,t,n){var r,a,i=vN(t),l=vN(s.acroField),o=kP(t),c=kP(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,p=AE(u==null?void 0:u.getRotation()),f=H9(d,p),x=f.width,y=f.height,v=fL(ec(ec({},d),{rotation:p})),b=Au(0,0,0),N=xb(u==null?void 0:u.getBorderColor()),S=xb(u==null?void 0:u.getBackgroundColor()),A=s.getOptions(),T=s.getSelected();s.isSorted()&&A.sort();for(var L="",M=0,I=A.length;M1||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 rYn(n.length,r,this.getName());this.markAsDirty(),this.disableRichFormatting(),n?this.acroField.setValue(Sl.fromText(n)):this.acroField.removeValue()},t.prototype.getAlignment=function(){var n=this.acroField.getQuadding();return n===0?Jx.Left:n===1?Jx.Center:n===2?Jx.Right:Jx.Left},t.prototype.setAlignment=function(n){dM(n,"alignment",Jx),this.markAsDirty(),this.acroField.setQuadding(n)},t.prototype.getMaxLength=function(){return this.acroField.getMaxLength()},t.prototype.setMaxLength=function(n){if(ok(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 aYn(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===Jx.Center?eP.Center:r===Jx.Right?eP.Right:eP.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:mts(i),page:l}})}catch{r=[]}return{pageCount:n.length,hasAcroform:r.length>0,fields:r}}function pSt(s,t){return s.mapping_mode==="blank"?"":s.mapping_mode==="static"||!s.merge_key?s.static_value||"":t[s.merge_key]??""}async function CYn(s,t,n){const r=await uE.load(s,{updateMetadata:!1}),a=await r.embedFont(Vte.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=pSt(h,n),p=h.pdf_field_name;if(!m){l.push(p);continue}try{const f=u.getField(p),x=mts(f);if(x==="text")f.setText(m);else if(x==="checkbox")/^(true|yes|x|1|checked)$/i.test(m.trim())?f.check():f.uncheck();else if(x==="dropdown"||x==="optionlist")f.select(m);else if(x==="radio")f.select(m);else{l.push(p);continue}i[p]=m}catch{l.push(p)}}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=pSt(h,n),p=h.pdf_field_name||h.merge_key||h.field_kind||"overlay",f=u[h.page_index??0];if(!m||!f||h.pos_x==null||h.pos_y==null){l.push(p);continue}const{width:x,height:y}=f.getSize(),v=!!h.coords_normalized,b=Number(h.pos_x)*(v?x:1),N=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),T=v?y-A-S:A,L=Number(h.font_size)||(v?Math.min(11,Math.max(7,S*.7)):10);f.drawText(m,{x:v?b+1:b,y:v?T+Math.max(2,(S-L)/2):T,size:L,font:a,color:Au(0,0,0),maxWidth:v?Math.max(10,N-2):void 0}),i[p]=m}}return{bytes:await r.save(),applied:i,skipped:l}}function pts(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 fts=20*1024*1024,lrt=[{value:"purchase",label:"Purchase"},{value:"listing",label:"Listing"},{value:"disclosure",label:"Disclosure"},{value:"addendum",label:"Addendum"},{value:"other",label:"Other"}];function gx(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 crt(s=!1){const t=Sa();return ct({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 AYn(s,t=!1){return ct({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 EYn(){const s=Sa(),t=Qt();return yt({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>fts)throw new Error("That PDF is larger than the 20MB limit.");let c;try{c=await SYn(await i.arrayBuffer())}catch(b){throw new Error(pts(b))}let d=l;if(!d){const{data:b,error:N}=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(N)throw N;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,p=`${s}/${d}/v${m}-${crypto.randomUUID()}.pdf`,{error:f}=await q.storage.from("form-templates").upload(p,i,{contentType:"application/pdf"});if(f)throw f;const{data:x,error:y}=await q.from("form_template_versions").insert({template_id:d,version_number:m,storage_path:p,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([p]),y;return{templateId:d,version:x}},onSuccess:()=>{t.invalidateQueries({queryKey:["form-templates"]}),t.invalidateQueries({queryKey:["form-template"]})}})}function gts(){const s=Qt();return yt({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 TYn(){const s=Sa(),t=Qt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r=gx(n);if(!r)throw new Error("That template has no uploaded PDF yet.");const a=await drt(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:f,created_at:x,updated_at:y,version_id:v,...b})=>({...b,version_id:d.id})),{error:p}=await q.from("form_field_mappings").insert(m);if(p)throw p}return i.id},onSuccess:()=>{t.invalidateQueries({queryKey:["form-templates"]})}})}function xts(){const s=Qt();return yt({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 drt(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 rk(s){if(!s)return"";try{const t=Su(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 MYn(){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 PYn(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 urt(s){return s?s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`:"0 KB"}const HH=[{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"]}],LYn=new Map(HH.map(s=>[s.key,s])),IYn={buyer:"Buyer",seller:"Seller",dual:"Dual",referral:"Referral",lease:"Lease"};function RYn(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":IYn[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":PYn(l),"deal.contract_date":rk(t.contract_date),"deal.target_close_date":rk(t.target_close_date),"deal.actual_close_date":rk(t.actual_close_date),"deal.listing_date":rk(t.listing_date),"deal.inspection_date":rk(t.inspection_date),"deal.inspection_contingency_date":rk(t.inspection_contingency_date),"deal.appraisal_date":rk(t.appraisal_date),"deal.loan_approval_date":rk(t.loan_approval_date),"deal.earnest_money_due_date":rk(t.earnest_money_due_date),"deal.title_docs_due_date":rk(t.title_docs_due_date),"deal.final_walkthrough_date":rk(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:MYn()}}function yts(s){const t=Sa();return ct({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:RYn(o)}}})}function DYn(s){return ct({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 OYn(){const s=Sa(),t=Qt();return yt({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 drt(a.storage_path);let d;try{d=await CYn(c,l,i)}catch(N){throw new Error(pts(N))}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),p=new Blob([m],{type:"application/pdf"}),f=`${s}/${n}/${crypto.randomUUID()}.pdf`,{error:x}=await q.storage.from("deal-files").upload(f,p,{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:p.size,file_type:"application/pdf",storage_path:f}).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:p,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 GIe(s){return ct({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 FYn(){const s=Qt();return yt({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 vts({open:s,onOpenChange:t,dealId:n,dealName:r,initialTemplateId:a}){const{data:i=[],isLoading:l}=crt(),[o,c]=j.useState(a),{data:d,isLoading:u,error:h}=yts(s?n:void 0),m=OYn(),p=j.useMemo(()=>i.find(T=>T.id===o),[i,o]),f=gx(p),{data:x=[],isLoading:y}=GIe(s?f==null?void 0:f.id:void 0);j.useEffect(()=>{s&&a&&c(a)},[s,a]);const v=i.filter(T=>{var L;return((L=gx(T))==null?void 0:L.mapping_status)==="mapped"}),b=j.useMemo(()=>d?x.filter(T=>T.merge_key||T.static_value).map(T=>{var L;return{field:T.pdf_field_name||T.merge_key||"",label:T.merge_key?((L=LYn.get(T.merge_key))==null?void 0:L.label)||T.merge_key:"Fixed text",value:T.mapping_mode==="static"?T.static_value||"":d.values[T.merge_key||""]||""}}):[],[x,d]),N=b.filter(T=>!T.value).length,S=async()=>{if(!(!p||!f||!d))try{const T=await m.mutateAsync({dealId:n,template:p,version:f,values:d.values});re.success(`${T.fileName} saved to this deal's files`),t(!1)}catch(T){re.error((T==null?void 0:T.message)||"Could not generate the form")}},A=(f==null?void 0:f.mapping_status)==="mapped";return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-2xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(Ns,{value:o,onValueChange:c,disabled:l,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:l?"Loading templates…":"Choose a template"})}),e.jsx(js,{children:i.map(T=>{const L=gx(T);return e.jsxs(et,{value:T.id,disabled:(L==null?void 0:L.mapping_status)!=="mapped",children:[T.name,T.scope==="brokerage"?" · Brokerage":"",(L==null?void 0:L.mapping_status)!=="mapped"?" — needs mapping":""]},T.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."}),p&&e.jsxs(e.Fragment,{children:[(u||y)&&e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(Et,{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"}),N>0&&e.jsxs(Be,{variant:"outline",className:"gap-1 text-[10px]",children:[e.jsx(tc,{className:"h-3 w-3"})," ",N," blank"]})]}),e.jsx(Gi,{className:"max-h-[280px]",children:e.jsxs("div",{className:"divide-y",children:[b.map((T,L)=>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:T.label}),e.jsx("span",{className:T.value?"truncate":"truncate italic text-muted-foreground/60",children:T.value||"not set"})]},`${T.field}-${L}`)),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&&f&&e.jsx("p",{className:"rounded-lg bg-muted/50 p-3 text-sm text-muted-foreground",children:f.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(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{onClick:S,disabled:!A||m.isPending||b.length===0,children:[m.isPending?e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(IX,{className:"mr-2 h-4 w-4"}),m.isPending?"Generating…":"Generate & save to deal"]})]})]})})}const zYn=["Client","Co-Buyer","Co-Seller","Spouse","Lender","Title Company","Inspector","Appraiser","Attorney","Contractor","Other"];function bts(s){return ct({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 BYn(){const s=Qt();return yt({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 UYn(){const s=Qt();return yt({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 hrt=[{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 mrt(s){var t;return((t=hrt.find(n=>n.value===s))==null?void 0:t.label)||s||"Signer"}function qYn(s){const t=Sa();return ct({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 $Yn(){const s=Sa(),t=Qt();return yt({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 VYn(){const s=Qt();return yt({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 _ts(){const s=Sa();return ct({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 prt(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 HYn(){const s=Sa(),t=Qt();return yt({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 GYn(){const s=Qt();return yt({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 WYn(){const s=Sa(),t=Qt();return yt({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=prt(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;mT.field_kind&&T.field_kind!=="data"&&T.signer_role).map(T=>T.signer_role)),N=c.filter(T=>b.has(T.signer_role));if(!N.length)throw new Error(`${p.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:N.map((T,L)=>({...T,order_index:L})),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 wts({open:s,onOpenChange:t,dealId:n,dealName:r,initialTemplateId:a}){const{data:i=[],isLoading:l}=crt(),[o,c]=j.useState(a),{data:d,isLoading:u}=yts(s?n:void 0),{data:h=[]}=bts(n),{data:m=[]}=_ts(),p=$Yn(),f=WYn(),[x,y]=j.useState("single"),[v,b]=j.useState(void 0),N=j.useMemo(()=>m.find(ce=>ce.id===v),[m,v]),S=j.useMemo(()=>prt(N,i),[N,i]),{data:A=[],isLoading:T}=ct({queryKey:["packet-signer-roles",v,S.map(ce=>{var je;return(je=gx(ce))==null?void 0:je.id}).join(",")],enabled:x==="packet"&&S.length>0,queryFn:async()=>{const ce=S.map(ge=>{var ke;return(ke=gx(ge))==null?void 0:ke.id}).filter(Boolean);if(!ce.length)return[];const{data:je,error:be}=await q.from("form_field_mappings").select("field_kind, signer_role").in("version_id",ce);if(be)throw be;const he=new Set;for(const ge of je||[])ge.field_kind&&ge.field_kind!=="data"&&ge.signer_role&&he.add(ge.signer_role);return[...he]}}),L=j.useMemo(()=>i.find(ce=>ce.id===o),[i,o]),M=gx(L),{data:I=[],isLoading:R}=GIe(s?M==null?void 0:M.id:void 0),[z,$]=j.useState(""),[H,V]=j.useState(""),[K,Z]=j.useState({});j.useEffect(()=>{s&&a&&c(a)},[s,a]);const Q=j.useMemo(()=>{const ce=new Set;if(x==="packet")for(const be of A)ce.add(be);else for(const be of I)be.field_kind&&be.field_kind!=="data"&&be.signer_role&&ce.add(be.signer_role);const je=hrt.map(be=>be.value);return[...ce].sort((be,he)=>je.indexOf(be)-je.indexOf(he))},[I,x,A]);j.useEffect(()=>{var he,ge,ke;const ce={},je=h.filter(Te=>Te.contact);let be=0;for(const Te of Q)if(Te==="agent"){const Me=(he=d==null?void 0:d.sources)==null?void 0:he.profile;ce[Te]={name:(Me==null?void 0:Me.full_name)||"",email:(Me==null?void 0:Me.email)||"",contact_id:null}}else{const Me=je[be++],Oe=Me!=null&&Me.contact?`${Me.contact.first_name||""} ${Me.contact.last_name||""}`.trim():"";ce[Te]={name:Oe,email:((ge=Me==null?void 0:Me.contact)==null?void 0:ge.email)||"",contact_id:((ke=Me==null?void 0:Me.contact)==null?void 0:ke.id)||null}}Z(ce),x==="single"&&L&&!z&&$(r?`${L.name} – ${r}`:L.name)},[Q,h,d,o,v,x]);const le=(M==null?void 0:M.mapping_status)==="mapped",ue=(ce,je)=>Z(be=>({...be,[ce]:{...be[ce],...je}})),se=Q.length>0&&Q.every(ce=>{var je,be,he;return((be=(je=K[ce])==null?void 0:je.name)==null?void 0:be.trim())&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(((he=K[ce])==null?void 0:he.email)||"")}),ne=p.isPending||f.isPending,ie=async()=>{if(!d)return;const ce=Q.map((je,be)=>({full_name:K[je].name.trim(),email:K[je].email.trim(),signer_role:je,contact_id:K[je].contact_id,is_agent:je==="agent",order_index:be}));try{if(x==="packet"){if(!N)return;await f.mutateAsync({dealId:n,packet:N,templates:i,titlePrefix:r||"",message:H.trim()||void 0,values:d.values,signers:ce}),re.success(`${S.length} documents sent to ${ce[0].full_name}`)}else{if(!L||!M)return;await p.mutateAsync({dealId:n,template:L,version:M,title:z.trim()||L.name,message:H.trim()||void 0,values:d.values,signers:ce}),re.success(`Signature request sent to ${ce[0].full_name}`)}t(!1)}catch(je){re.error((je==null?void 0:je.message)||"Could not send the signature request")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"flex max-h-[90vh] max-w-xl flex-col overflow-hidden",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(Ns,{value:v,onValueChange:b,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Choose a packet"})}),e.jsx(js,{children:m.map(ce=>{var je;return e.jsxs(et,{value:ce.id,children:[ce.name," (",((je=ce.items)==null?void 0:je.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 je;return e.jsxs("li",{children:[ce.name,((je=gx(ce))==null?void 0:je.mapping_status)!=="mapped"?" — not ready":""]},ce.id)})})]})]}):e.jsxs(Ns,{value:o,onValueChange:c,disabled:l,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:l?"Loading templates…":"Choose a template"})}),e.jsx(js,{children:i.map(ce=>{const je=gx(ce);return e.jsxs(et,{value:ce.id,disabled:(je==null?void 0:je.mapping_status)!=="mapped",children:[ce.name,ce.scope==="brokerage"?" · Brokerage":"",(je==null?void 0:je.mapping_status)!=="mapped"?" — not ready":""]},ce.id)})})]}),(x==="packet"?N:L)&&(u||R||T)&&e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(Et,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),(x==="packet"?!!N&&!T:!!L&&!R&&le)&&Q.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(tc,{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."]})]}),Q.length>0&&e.jsxs(e.Fragment,{children:[x==="single"&&L&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Document title"}),e.jsx(xe,{value:z,onChange:ce=>$(ce.target.value),placeholder:L.name})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{className:"text-xs",children:"Signers (sign in this order)"}),e.jsxs(Be,{variant:"outline",className:"text-[10px]",children:[Q.length," signer",Q.length===1?"":"s"]})]}),Q.map((ce,je)=>{var be,he,ge;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:[je+1,". ",mrt(ce)]}),ce!=="agent"&&h.length>0&&e.jsxs(Ns,{value:((be=K[ce])==null?void 0:be.contact_id)||"",onValueChange:ke=>{const Te=h.find(Me=>{var Oe;return((Oe=Me.contact)==null?void 0:Oe.id)===ke});Te!=null&&Te.contact&&ue(ce,{contact_id:ke,name:`${Te.contact.first_name||""} ${Te.contact.last_name||""}`.trim(),email:Te.contact.email||""})},children:[e.jsx(ws,{className:"h-7 w-44 text-[11px]",children:e.jsx(ks,{placeholder:"Pick deal contact…"})}),e.jsx(js,{children:h.map(ke=>ke.contact?e.jsxs(et,{value:ke.contact.id,className:"text-xs",children:[ke.contact.first_name," ",ke.contact.last_name]},ke.contact.id):null)})]})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsx(xe,{className:"h-8 text-xs",placeholder:"Full name",value:((he=K[ce])==null?void 0:he.name)||"",onChange:ke=>ue(ce,{name:ke.target.value,contact_id:null})}),e.jsx(xe,{className:"h-8 text-xs",type:"email",placeholder:"Email address",value:((ge=K[ce])==null?void 0:ge.email)||"",onChange:ke=>ue(ce,{email:ke.target.value,contact_id:null})})]})]},ce)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Message (optional)"}),e.jsx(Fs,{rows:2,placeholder:"Added to the signature request email",value:H,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(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{onClick:ie,disabled:!se||ne||u,children:[ne?e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Pg,{className:"mr-2 h-4 w-4"}),ne?"Sending…":x==="packet"?`Send ${S.length||""} document${S.length===1?"":"s"}`.replace(" "," "):"Send signature request"]})]})]})})}function KYn({status:s}){switch(s){case"completed":return e.jsx(Be,{className:"bg-emerald-500/15 text-emerald-600 hover:bg-emerald-500/15",children:"Completed"});case"partially_signed":return e.jsx(Be,{className:"bg-amber-500/15 text-amber-600 hover:bg-amber-500/15",children:"Partially signed"});case"sent":return e.jsx(Be,{variant:"secondary",children:"Sent"});case"declined":return e.jsx(Be,{variant:"destructive",children:"Declined"});case"voided":return e.jsx(Be,{variant:"outline",children:"Voided"});case"expired":return e.jsx(Be,{variant:"outline",children:"Expired"});case"finalize_failed":return e.jsx(Be,{variant:"destructive",children:"Needs attention"});default:return e.jsx(Be,{variant:"secondary",children:s})}}function YYn({envelope:s}){const t=Wn(),n=VYn(),r=[...s.signers||[]].sort((m,p)=>m.order_index-p.order_index),a=r.some((m,p)=>m.is_agent&&m.status!=="signed"&&r.slice(0,p).every(f=>f.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 p=atob(m.pdf_base64),f=new Uint8Array(p.length);for(let v=0;v{if(!s.completed_storage_path)return;const{data:m,error:p}=await q.storage.from("deal-files").createSignedUrl(s.completed_storage_path,300);if(p||!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(p){re.error((p==null?void 0:p.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(Pg,{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} (${mrt(m.signer_role)}): ${m.status.replace("_"," ")}`).join(" · ")})]}),e.jsx(KYn,{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(U,{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(A4,{className:"mr-1 h-3 w-3"})," Remind"]}),a&&e.jsxs(U,{size:"sm",className:"h-7 text-xs",disabled:n.isPending,onClick:u,children:[e.jsx(TA,{className:"mr-1 h-3 w-3"})," Countersign now"]}),s.status==="completed"&&e.jsxs(U,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:d,children:[e.jsx(pi,{className:"mr-1 h-3 w-3"})," Signed PDF"]}),e.jsxs(U,{variant:"ghost",size:"sm",className:"h-7 text-xs",disabled:n.isPending,onClick:c,children:[e.jsx(mq,{className:"mr-1 h-3 w-3"})," Audit trail"]}),i&&e.jsxs(U,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",disabled:n.isPending,onClick:h,children:[e.jsx(_F,{className:"mr-1 h-3 w-3"})," Void"]})]})]})}function ZYn({dealId:s,dealName:t}){const[n,r]=j.useState(!1),[a,i]=j.useState(!1),{data:l=[],isLoading:o,error:c}=DYn(s),{data:d=[]}=qYn(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(U,{className:"flex-1",onClick:()=>i(!0),children:[e.jsx(Pg,{className:"mr-2 h-4 w-4"})," Send for signature"]}),e.jsxs(U,{variant:"outline",className:"flex-1",onClick:()=>r(!0),children:[e.jsx(YU,{className:"mr-2 h-4 w-4"})," Prepare a form"]}),e.jsxs(U,{variant:"outline",className:"sm:w-auto",onClick:()=>window.open("/mission-control/forms","_blank","noopener,noreferrer"),children:[e.jsx(Sr,{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(YYn,{envelope:u},u.id))]}),o&&e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(Et,{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(Ur,{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)??"—"," · ",Gs(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(vts,{open:n,onOpenChange:r,dealId:s,dealName:t}),e.jsx(wts,{open:a,onOpenChange:i,dealId:s,dealName:t})]})}const fSt={text:"Short Text",textarea:"Long Text",dropdown:"Dropdown",toggle:"Yes / No"};function jts({open:s,onOpenChange:t}){const{data:n,isLoading:r}=Y8n(),a=Z8n(),i=X8n(),l=Q8n(),[o,c]=j.useState(!1),[d,u]=j.useState({question_text:"",field_type:"text",options:[],is_required:!1}),[h,m]=j.useState(""),p=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")}},f=async b=>{try{await l.mutateAsync(b),re.success("Question removed")}catch{re.error("Failed to remove question")}},x=async(b,N)=>{try{await i.mutateAsync({id:b,is_required:N})}catch{re.error("Failed to update question")}},y=()=>{h.trim()&&(u(b=>({...b,options:[...b.options,h.trim()]})),m(""))},v=b=>{u(N=>({...N,options:N.options.filter((S,A)=>A!==b)}))};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-md max-h-[85vh] flex flex-col",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Custom Intake Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"These questions appear on all your portal onboarding forms."})]}),e.jsx(Gi,{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(Et,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),n==null?void 0:n.map(b=>{var N;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(kf,{className:"h-4 w-4 text-muted-foreground/40 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:b.question_text}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Be,{variant:"secondary",className:"text-xs",children:fSt[b.field_type]||b.field_type}),b.is_required&&e.jsx(Be,{variant:"outline",className:"text-xs",children:"Required"})]}),b.field_type==="dropdown"&&((N=b.options)==null?void 0:N.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(wn,{checked:b.is_required,onCheckedChange:S=>x(b.id,S),className:"scale-75"}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:()=>f(b.id),children:e.jsx(In,{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(te,{className:"text-sm font-medium",children:"Question"}),e.jsx(xe,{value:d.question_text,onChange:b=>u(N=>({...N,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(te,{className:"text-sm font-medium",children:"Answer Type"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:Object.entries(fSt).map(([b,N])=>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:N},b))})]}),d.field_type==="dropdown"&&e.jsxs("div",{children:[e.jsx(te,{className:"text-sm font-medium",children:"Options"}),e.jsxs("div",{className:"space-y-1.5 mt-1.5",children:[d.options.map((b,N)=>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(N),className:"text-muted-foreground hover:text-destructive",children:e.jsx(er,{className:"h-3.5 w-3.5"})})]},N)),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{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(U,{variant:"outline",size:"sm",onClick:y,disabled:!h.trim(),className:"h-8",children:e.jsx(an,{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(wn,{checked:d.is_required,onCheckedChange:b=>u(N=>({...N,is_required:b}))}),e.jsx(te,{className:"text-xs text-muted-foreground",children:"Required"})]})}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(U,{variant:"outline",size:"sm",onClick:()=>c(!1),className:"flex-1",children:"Cancel"}),e.jsxs(U,{size:"sm",onClick:p,disabled:!d.question_text.trim()||a.isPending,className:"flex-1",children:[a.isPending?e.jsx(Et,{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(U,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-1"})," Add Question"]}),e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Done"})]})]})})}function XYn({override:s,onChange:t}){const n=Sa(),{data:r}=MOt(),[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 POt(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(cn,{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(gSt,{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(gSt,{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(xSt,{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(xSt,{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(te,{className:"text-sm font-medium",children:"Tagline"}),e.jsx(xe,{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(U,{variant:"ghost",size:"sm",onClick:()=>t({}),className:"text-xs text-muted-foreground hover:text-destructive",children:[e.jsx(In,{className:"h-3 w-3 mr-1"}),"Clear all overrides"]})]})}function gSt({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(te,{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:Mt("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(pc,{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(Et,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(qa,{className:"h-3.5 w-3.5"}),t?"Replace":"Override"]})]}),t&&e.jsx(U,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(In,{className:"h-3.5 w-3.5"})})]})]})]})}function xSt({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(te,{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:Mt("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(xe,{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(U,{variant:"ghost",size:"sm",onClick:()=>r(null),className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",children:e.jsx(In,{className:"h-3 w-3"})})]})]})}function QYn({portalId:s,agentUserId:t}){const n=Qt(),{data:r,isLoading:a}=ct({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,p=q.from("vendors").select("*").eq("is_active",!0),f=m?p.or(`and(owner_type.eq.agent,owner_user_id.eq.${t}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${m})`):p.eq("owner_type","agent").eq("owner_user_id",t),[{data:x,error:y},{data:v},{data:b}]=await Promise.all([f.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 N=new Map;(v||[]).forEach(A=>N.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:N,overrideMap:S}}}),i=yt({mutationFn:async({vendorId:h,isVisible:m})=>{const{data:p}=await q.from("portal_vendor_overrides").select("id").eq("portal_id",s).eq("vendor_id",h).maybeSingle();if(p){const{error:f}=await q.from("portal_vendor_overrides").update({is_visible:m}).eq("id",p.id);if(f)throw f}else{const{error:f}=await q.from("portal_vendor_overrides").insert({portal_id:s,vendor_id:h,is_visible:m});if(f)throw f}},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(Et,{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(a1,{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 p=o.get(h.id);return p===void 0?!0:p!==!1},u=h=>{var m;return((m=wG.find(p=>p.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(Gi,{className:"h-[400px] rounded-lg border",children:e.jsx("div",{className:"divide-y",children:l.map(h=>{const m=d(h);return e.jsxs("div",{className:"flex items-center gap-3 p-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-muted border flex items-center justify-center overflow-hidden shrink-0",children:h.logo_url?e.jsx("img",{src:h.logo_url,alt:h.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-sm font-semibold text-muted-foreground",children:h.name.charAt(0)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:h.company||h.name}),e.jsx(Be,{variant:"outline",className:"text-[10px] shrink-0",children:u(h.category)}),h.owner_type==="brokerage"&&e.jsx(Be,{variant:"secondary",className:"text-[10px] shrink-0",children:"Brokerage"}),h.is_required&&e.jsx(Be,{className:"text-[10px] shrink-0",children:"Required"})]}),h.company&&h.name&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:h.name})]}),e.jsx(wn,{checked:m,disabled:h.is_required||i.isPending,onCheckedChange:p=>i.mutate({vendorId:h.id,isVisible:p})})]},h.id)})})})]})}function JYn({portalId:s,ownerId:t,clientEmail:n,linkedPortalId:r,onLink:a}){const[i,l]=j.useState(""),[o,c]=j.useState(!1),{data:d,isLoading:u}=ct({queryKey:["all-owner-portals",t],queryFn:async()=>{const{data:f,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 f},enabled:o||!!r}),h=j.useMemo(()=>!r||!d?null:d.find(f=>f.id===r),[r,d]),m=j.useMemo(()=>!d||!n?[]:d.filter(f=>{var x;return((x=f.client_email)==null?void 0:x.toLowerCase())===n.toLowerCase()&&f.id!==s}),[d,n,s]),p=j.useMemo(()=>{if(!d||!i.trim())return[];const f=i.toLowerCase();return d.filter(x=>{var v,b,N,S;const y=x.deal_pipeline;return((v=x.client_name)==null?void 0:v.toLowerCase().includes(f))||((b=x.client_email)==null?void 0:b.toLowerCase().includes(f))||((N=y==null?void 0:y.deal_name)==null?void 0:N.toLowerCase().includes(f))||((S=y==null?void 0:y.property_address)==null?void 0:S.toLowerCase().includes(f))})},[d,i]);if(r){const f=h==null?void 0:h.deal_pipeline;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{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(ad,{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)||(f==null?void 0:f.deal_name)||"Linked Portal"}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[(f==null?void 0:f.deal_type)==="listing"?"🏠 Listing":"🔑 Purchase"," · ",(f==null?void 0:f.property_address)||"No address"]})]}),e.jsxs(U,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive shrink-0",onClick:()=>a(null),children:[e.jsx(qF,{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(te,{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(U,{variant:"outline",size:"sm",className:"text-xs",onClick:()=>c(!o),children:[e.jsx(ad,{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(f=>{const x=f.deal_pipeline;return e.jsxs("button",{onClick:()=>a(f.id),className:"w-full flex items-center gap-2 bg-amber-50 border border-amber-200 rounded-lg p-2.5 hover:bg-amber-100 transition-colors text-left",children:[e.jsx(Be,{variant:"outline",className:"text-[10px] shrink-0 bg-amber-100 border-amber-300 text-amber-700",children:(x==null?void 0:x.deal_type)==="listing"?"Listing":"Purchase"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:(x==null?void 0:x.deal_name)||f.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:x==null?void 0:x.property_address})]}),e.jsx(ad,{className:"h-3.5 w-3.5 text-amber-600 shrink-0"})]},f.id)})]}),o&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(xe,{value:i,onChange:f=>l(f.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(Et,{className:"h-4 w-4 animate-spin text-muted-foreground"})}),p.length>0&&e.jsx("div",{className:"space-y-1 max-h-[200px] overflow-y-auto",children:p.map(f=>{const x=f.deal_pipeline;return e.jsxs("button",{onClick:()=>{a(f.id),c(!1),l("")},className:"w-full flex items-center gap-2 border rounded-lg p-2 hover:bg-muted/50 transition-colors text-left",children:[e.jsx(Be,{variant:"outline",className:"text-[10px] shrink-0",children:(x==null?void 0:x.deal_type)==="listing"?"Listing":"Purchase"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:(x==null?void 0:x.deal_name)||f.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:f.client_email})]})]},f.id)})}),i&&p.length===0&&!u&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No portals found"})]})]})}function frt({contactId:s,onVideoReady:t}){const[n,r]=j.useState(!1),[a,i]=j.useState("record"),[l,o]=j.useState(0),[c,d]=j.useState(0),u=f3(),h=()=>{i("record"),o(0),d(0)},m=f=>{!f&&(a==="uploading"||a==="processing")||(r(f),f||h())},p=j.useCallback(async(f,x)=>{i("uploading");try{const y="Card Video",{videoId:v,libraryId:b}=await cL(y),{uploadUrl:N,apiKey:S}=await dL(v),A=new XMLHttpRequest;A.upload.onprogress=$=>{$.lengthComputable&&o($.loaded/$.total*100)},await new Promise(($,H)=>{A.onload=()=>A.status>=200&&A.status<300?$():H(new Error("Upload failed")),A.onerror=()=>H(new Error("Upload failed")),A.open("PUT",N),A.setRequestHeader("AccessKey",S),A.send(f)}),i("processing");let T=0;const L=Date.now(),M=9e4,I=`https://iframe.mediadelivery.net/embed/${b}/${v}`;for(;T<4;){if(await new Promise(H=>setTimeout(H,3e3)),Date.now()-L>M){const H=f.size/1048576;await u.mutateAsync({bunny_video_id:v,playback_url:`https://iframe.mediadelivery.net/play/${b}/${v}`,file_size_mb:H,title:y,contact_id:s||void 0,status:"processing",touch_type:"video"}),t(I),re.success("Video saved — still encoding. It will be ready shortly."),i("done"),setTimeout(()=>{r(!1),h()},1500);return}const $=await fN(v);if(T=$.status,d($.encodeProgress||0),T===5||T===6)throw new Error("Video processing failed")}const R=await fN(v),z=(R.storageSize||f.size)/(1024*1024);await u.mutateAsync({bunny_video_id:v,contact_id:s||void 0,playback_url:R.directPlayUrl||I,thumbnail_url:R.thumbnailUrl,preview_url:R.previewUrl||null,duration_seconds:R.length||x,file_size_mb:z,title:y,status:"ready",touch_type:"video"}),t(I),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(al,{asChild:!0,children:e.jsxs(U,{variant:"outline",size:"sm",className:"gap-1.5 w-full",children:[e.jsx(Wr,{className:"h-3.5 w-3.5"}),"Record Video"]})}),e.jsxs(Ds,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Record a Video for Your Card"})}),a==="record"&&e.jsx(kE,{maxDurationSeconds:600,onRecordingComplete:p,onError:f=>re.error(f)}),a==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Et,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(ro,{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(Et,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(ro,{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(Yo,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your card!"})]})]})]})}const eZn=s=>`portal-settings-draft:${s}`;function grt({open:s,onOpenChange:t,portal:n,dealOwnerId:r}){const a=eW(),[i,l]=j.useState(!1),o=j.useMemo(()=>eZn(n.id),[n.id]),[c,d]=j.useState(!1),[u,h]=j.useState(n.next_step_text||""),[m,p]=j.useState(n.next_step_video_url||""),[f,x]=j.useState(n.inspection_date||""),[y,v]=j.useState(n.appraisal_date||""),[b,N]=j.useState(n.welcome_message||""),[S,A]=j.useState(n.review_url||""),[T,L]=j.useState(n.show_post_close_tips),[M,I]=j.useState(n.notify_client),[R,z]=j.useState(n.require_onboarding),[$,H]=j.useState(n.allow_spouse),[V,K]=j.useState(n.visibility),[Z,Q]=j.useState(n.stage_mapping||[]),[le,ue]=j.useState(null),[se,ne]=j.useState(n.linked_portal_id||null),[ie,ce]=j.useState(n.referral_enabled??!0),[je,be]=j.useState(n.referral_reward_text||""),[he,ge]=j.useState(n.referral_cta_headline||""),[ke,Te]=j.useState(n.homeowner_hub_video_url||""),[Me,Oe]=j.useState(n.branding_override||{}),Se=()=>{h(n.next_step_text||""),p(n.next_step_video_url||""),x(n.inspection_date||""),v(n.appraisal_date||""),N(n.welcome_message||""),A(n.review_url||""),L(n.show_post_close_tips),I(n.notify_client),z(n.require_onboarding),H(n.allow_spouse),K(n.visibility),Q(n.stage_mapping||[]),ne(n.linked_portal_id||null),ce(n.referral_enabled??!0),be(n.referral_reward_text||""),ge(n.referral_cta_headline||""),Te(n.homeowner_hub_video_url||""),Oe(n.branding_override||{})};j.useEffect(()=>{d(!1);const qe=localStorage.getItem(o);if(qe)try{const Ze=JSON.parse(qe);h(Ze.nextStepText||""),p(Ze.nextStepVideo||""),x(Ze.inspectionDate||""),v(Ze.appraisalDate||""),N(Ze.welcomeMessage||""),A(Ze.reviewUrl||""),L(!!Ze.showPostClose),I(!!Ze.notifyClient),z(!!Ze.requireOnboarding),H(!!Ze.allowSpouse),K(Ze.visibility||n.visibility),Q(Ze.stageMapping||[]),ne(Ze.linkedPortalId??null),ce(Ze.referralEnabled??!0),be(Ze.referralRewardText||""),ge(Ze.referralCtaHeadline||""),Te(Ze.homeownerHubVideoUrl||""),Oe(Ze.brandingOverride||{}),d(!0);return}catch{localStorage.removeItem(o)}Se(),d(!0)},[o,n]),j.useEffect(()=>{if(!c)return;const qe={nextStepText:u,nextStepVideo:m,inspectionDate:f,appraisalDate:y,welcomeMessage:b,reviewUrl:S,showPostClose:T,notifyClient:M,requireOnboarding:R,allowSpouse:$,visibility:V,stageMapping:Z,linkedPortalId:se,referralEnabled:ie,referralRewardText:je,referralCtaHeadline:he,homeownerHubVideoUrl:ke,brandingOverride:Me};u!==(n.next_step_text||"")||m!==(n.next_step_video_url||"")||f!==(n.inspection_date||"")||y!==(n.appraisal_date||"")||b!==(n.welcome_message||"")||S!==(n.review_url||"")||T!==n.show_post_close_tips||M!==n.notify_client||R!==n.require_onboarding||$!==n.allow_spouse||V!==n.visibility||JSON.stringify(Z)!==JSON.stringify(n.stage_mapping||[])||se!==(n.linked_portal_id||null)||ie!==(n.referral_enabled??!0)||je!==(n.referral_reward_text||"")||he!==(n.referral_cta_headline||"")||ke!==(n.homeowner_hub_video_url||"")||JSON.stringify(Me)!==JSON.stringify(n.branding_override||{})?localStorage.setItem(o,JSON.stringify(qe)):localStorage.removeItem(o)},[u,m,f,y,b,S,T,M,R,$,V,Z,se,ie,je,he,ke,Me,o,c,n]);const Qe=()=>{localStorage.removeItem(o),Se()},Ae=async()=>{try{await a.mutateAsync({id:n.id,next_step_text:u||null,next_step_video_url:m||null,inspection_date:f||null,appraisal_date:y||null,welcome_message:b||null,review_url:S||null,show_post_close_tips:T,notify_client:M,require_onboarding:R,allow_spouse:$,visibility:V,stage_mapping:Z.length>0?Z:null,linked_portal_id:se,referral_enabled:ie,referral_reward_text:je||null,referral_cta_headline:he||null,homeowner_hub_video_url:ke||null,branding_override:Object.values(Me).some(Ze=>Ze!=null&&Ze!=="")?Me:null});const qe=n.linked_portal_id;se&&se!==qe&&await q.from("client_portals").update({linked_portal_id:n.id}).eq("id",se),!se&&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")}},Fe=()=>{Q([...Z,{label:""}])},Ne=qe=>{Q(Z.filter((Ze,Ue)=>Ue!==qe)),le===qe&&ue(null)},$e=(qe,Ze,Ue)=>{const Ye=[...Z];Ye[qe]={...Ye[qe],[Ze]:Ue},Q(Ye)},Ve=()=>{const Ze=RMe(null).map(Ue=>({label:Ue.label,description:Ue.description,stageId:void 0}));Q(Ze)};return e.jsxs(e.Fragment,{children:[e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-lg max-h-[85vh] flex flex-col",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Portal Settings"})}),e.jsxs(oa,{defaultValue:"general",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(la,{className:"grid grid-cols-5 shrink-0",children:[e.jsx(Kt,{value:"general",children:"General"}),e.jsx(Kt,{value:"timeline",children:"Timeline"}),e.jsx(Kt,{value:"content",children:"Content"}),e.jsx(Kt,{value:"vendors",children:"Vendors"}),e.jsx(Kt,{value:"branding",children:"Branding"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-4 min-h-0",children:[e.jsxs(Zt,{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(te,{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:()=>K(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(te,{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(wn,{checked:R,onCheckedChange:z})]}),R&&e.jsxs("div",{className:"flex items-center justify-between pl-4 border-l-2 border-primary/20",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-sm font-medium",children:"Custom Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Manage intake form questions"})]}),e.jsx(U,{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(te,{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(wn,{checked:$,onCheckedChange:H})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(te,{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(wn,{checked:T,onCheckedChange:L})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(te,{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(wn,{checked:M,onCheckedChange:I})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx(JYn,{portalId:n.id,ownerId:r,clientEmail:n.client_email,linkedPortalId:se,onLink:ne})}),e.jsx("div",{children:e.jsx(xe,{type:"date",value:f,onChange:qe=>x(qe.target.value),className:"mt-1"})}),e.jsxs("div",{children:[e.jsx(te,{className:"text-sm font-medium",children:"Appraisal Date"}),e.jsx(xe,{type:"date",value:y,onChange:qe=>v(qe.target.value),className:"mt-1"})]})]}),e.jsx(Zt,{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(te,{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(U,{variant:"outline",size:"sm",onClick:Ve,className:"text-xs",children:"Auto-map"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground bg-muted/50 rounded-md p-2",children:'💡 These labels are what clients see. Click "More" on any stage to customize its description and add a video link. Internal pipeline stages are automatically translated to friendly names.'}),Z.length===0&&e.jsxs("div",{className:"border border-dashed rounded-lg p-4 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"No custom mapping — using default client-friendly journey stages"}),e.jsx(U,{variant:"outline",size:"sm",onClick:Ve,children:"Customize journey labels"})]}),e.jsx("div",{className:"space-y-2 mt-2",children:Z.map((qe,Ze)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kf,{className:"h-4 w-4 text-muted-foreground/50 flex-shrink-0"}),e.jsx(xe,{value:qe.label,onChange:Ue=>$e(Ze,"label",Ue.target.value),placeholder:`Stage ${Ze+1} label`,className:"flex-1 h-9 text-sm"}),e.jsx(U,{variant:"ghost",size:"sm",className:"h-9 px-2 text-xs text-muted-foreground hover:text-primary",onClick:()=>ue(le===Ze?null:Ze),children:le===Ze?"Less":"More"}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-9 w-9 text-muted-foreground hover:text-destructive",onClick:()=>Ne(Ze),children:e.jsx(In,{className:"h-3.5 w-3.5"})})]}),le===Ze&&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(te,{className:"text-xs text-muted-foreground",children:"Description"}),e.jsx("textarea",{value:qe.description||"",onChange:Ue=>$e(Ze,"description",Ue.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(te,{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(U,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive hover:text-destructive",onClick:()=>$e(Ze,"video_url",""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(frt,{onVideoReady:Ue=>$e(Ze,"video_url",Ue)}),e.jsx(T9,{userId:r,onSelect:Ue=>$e(Ze,"video_url",Ue),triggerSize:"sm",triggerClassName:"gap-1.5 shrink-0 flex-1"}),e.jsxs(U,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1",onClick:()=>{const Ue=prompt("Paste a YouTube or Loom URL:");Ue&&$e(Ze,"video_url",Ue)},children:[e.jsx(Rc,{className:"h-3 w-3"}),"Paste URL"]})]})]})]})]},Ze))}),Z.length>0&&e.jsxs(U,{variant:"outline",size:"sm",onClick:Fe,className:"mt-2 text-xs w-full",children:[e.jsx(an,{className:"h-3 w-3 mr-1"})," Add Stage"]})]})}),e.jsxs(Zt,{value:"content",className:"space-y-4 mt-0 px-1",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-sm font-medium",children:"Welcome Message"}),e.jsx("textarea",{value:b,onChange:qe=>N(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(te,{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(te,{className:"text-sm font-medium",children:"Next Step Video (optional)"}),e.jsx(xe,{value:m,onChange:qe=>p(qe.target.value),className:"mt-1",placeholder:"YouTube or Loom URL"})]}),e.jsxs("div",{children:[e.jsx(te,{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(xe,{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(te,{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(te,{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(wn,{checked:ie,onCheckedChange:ce})]}),ie&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-sm font-medium",children:"Headline"}),e.jsx(xe,{value:he,onChange:qe=>ge(qe.target.value),className:"mt-1",placeholder:"Know someone buying or selling?"})]}),e.jsxs("div",{children:[e.jsx(te,{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(xe,{value:je,onChange:qe=>be(qe.target.value),className:"mt-1",placeholder:"$250 gift card • Donation to your charity • Closing gift"})]}),e.jsxs("div",{children:[e.jsx(te,{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(xe,{value:ke,onChange:qe=>Te(qe.target.value),className:"mt-1",placeholder:"YouTube, Loom, or direct video URL"})]})]})]})]}),e.jsx(Zt,{value:"vendors",className:"space-y-4 mt-0 px-1",children:e.jsx(QYn,{portalId:n.id,agentUserId:r})}),e.jsx(Zt,{value:"branding",className:"space-y-4 mt-0 px-1",children:e.jsx(XYn,{override:Me,onChange:Oe})})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-4 border-t shrink-0",children:[e.jsx(U,{variant:"ghost",onClick:Qe,children:"Reset Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(U,{onClick:Ae,disabled:a.isPending,children:[a.isPending?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-2"}),"Save Settings"]})]})]})]})}),e.jsx(jts,{open:i,onOpenChange:l})]})}const tZn=s=>`portal-update-draft:${s}`;function xrt({open:s,onOpenChange:t,portalId:n,portalSlug:r,notifyClient:a}){const i=j.useMemo(()=>tZn(n),[n]),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,p]=j.useState(!1),[f,x]=j.useState(a??!0),[y,v]=j.useState(!1),b=vWt();j.useEffect(()=>{v(!1);const A=localStorage.getItem(i);if(A)try{const T=JSON.parse(A);o(T.title||""),d(T.content||""),h(T.videoUrl||""),p(!!T.isStageChange),x(typeof T.sendNotification=="boolean"?T.sendNotification:a??!0),v(!0);return}catch{localStorage.removeItem(i)}o(""),d(""),h(""),p(!1),x(a??!0),v(!0)},[i,a]),j.useEffect(()=>{if(!y)return;const A={title:l,content:c,videoUrl:u,isStageChange:m,sendNotification:f};l.trim()||c.trim()||u.trim()||m||f!==(a??!0)?localStorage.setItem(i,JSON.stringify(A)):localStorage.removeItem(i)},[l,c,u,m,f,y,i,a]);const N=()=>{localStorage.removeItem(i),o(""),d(""),h(""),p(!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}),f&&r)try{const A=lS(r),{data:T,error:L}=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(L)throw L;T!=null&&T.emailSent?re.success("Update posted & client emailed"):re.success(`Update posted (${(T==null?void 0:T.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");N(),t(!1)}catch{re.error("Failed to post update")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-sm font-medium",children:"Title *"}),e.jsx(xe,{value:l,onChange:A=>o(A.target.value),className:"mt-1",placeholder:"Inspection cleared!"})]}),e.jsxs("div",{children:[e.jsx(te,{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(te,{className:"text-sm font-medium",children:"Video URL (optional)"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(xe,{value:u,onChange:A=>h(A.target.value),className:"pl-9",placeholder:"YouTube or Loom link"}),e.jsx(Wr,{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:()=>p(!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(!f),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors flex items-center gap-1.5 ${f?"bg-blue-500/10 text-blue-700 border-blue-200":"bg-background text-muted-foreground border-input"}`,children:[f?e.jsx(bx,{className:"h-3 w-3"}):e.jsx(Zk,{className:"h-3 w-3"}),f?"Notify Client":"No Notification"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-2",children:[e.jsx(U,{variant:"ghost",onClick:N,children:"Clear Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(U,{onClick:S,disabled:!l.trim()||b.isPending,children:[b.isPending?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx($r,{className:"h-4 w-4 mr-2"}),"Post Update"]})]})]})]})})}function yrt({open:s,onOpenChange:t,portal:n,dealName:r}){const a=eW(),{isGmailConnected:i,gmailEmail:l}=Ax(),[o,c]=j.useState(n.client_name||""),[d,u]=j.useState(n.client_email||""),[h,m]=j.useState(!1),[p,f]=j.useState(!1),x=lS(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!`,N=()=>{navigator.clipboard.writeText(x),f(!0),setTimeout(()=>f(!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:T}=await q.functions.invoke("gmail-send",{body:{to:d,subject:v,body:b.replace(/\n/g,"
")}});if(T){let L="";try{const M=T==null?void 0:T.context;if(M&&typeof M.json=="function"){const I=await M.json();L=(I==null?void 0:I.message)||(I==null?void 0:I.error)||""}}catch{}throw new Error(L||T.message||"Failed to send invite")}re.success(`Invite sent to ${d}`),t(!1)}catch(T){re.error(T.message||"Failed to send invite")}finally{m(!1)}},A=()=>{const T=encodeURIComponent(v),L=encodeURIComponent(b);window.open(`mailto:${d}?subject=${T}&body=${L}`,"_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(Ds,{className:"max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Invite Client to Portal"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-sm font-medium",children:"Client Name"}),e.jsx(xe,{value:o,onChange:T=>c(T.target.value),className:"mt-1",placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-sm font-medium",children:"Client Email"}),e.jsx(xe,{type:"email",value:d,onChange:T=>u(T.target.value),className:"mt-1",placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(te,{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(U,{variant:"outline",size:"icon",onClick:N,className:"shrink-0",children:p?e.jsx(Xr,{className:"h-4 w-4 text-emerald-600"}):e.jsx(Pa,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[i?e.jsxs(U,{onClick:S,disabled:h||!d.trim(),className:"w-full",children:[h?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Send via Gmail (",l,")"]}):e.jsxs(U,{onClick:A,disabled:!d.trim(),className:"w-full",variant:"outline",children:[e.jsx(Sr,{className:"h-4 w-4 mr-2"}),"Open in Email App"]}),e.jsxs(U,{variant:"ghost",onClick:N,className:"w-full text-muted-foreground",children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Just Copy Link"]})]})]})]})})}function sZn({deal:s}){const{isAdmin:t,user:n}=vs(),{data:r,isLoading:a}=W8n(s.id),i=est(),l=eW(),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[p,f]=j.useState(!1),x=`portal-management-ui:${s.id}`;if(j.useEffect(()=>{const T=sessionStorage.getItem(x);if(T)try{const L=JSON.parse(T);u(!!L.settingsOpen),m(!!L.composerOpen),f(!!L.inviteOpen)}catch{sessionStorage.removeItem(x)}},[x]),j.useEffect(()=>{d||h||p?sessionStorage.setItem(x,JSON.stringify({settingsOpen:d,composerOpen:h,inviteOpen:p})):sessionStorage.removeItem(x)},[d,h,p,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(cn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Et,{className:"h-3 w-3 animate-spin ml-auto"})]})});const y=async()=>{var T,L;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:((T=s.contact)==null?void 0:T.email)||void 0,client_phone:((L=s.contact)==null?void 0:L.phone)||void 0}),re.success("Client portal enabled!")}catch{re.error("Failed to create portal")}finally{c(!1)}},v=async T=>{if(r)try{await l.mutateAsync({id:r.id,is_enabled:T}),re.success(T?"Portal enabled":"Portal disabled")}catch{re.error("Failed to update portal")}},b=()=>{if(!r)return;const T=lS(r.slug);navigator.clipboard.writeText(T),re.success("Portal link copied!")},N=()=>{if(!r)return;const T=lS(r.slug);window.open(T,"_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(cn,{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(U,{onClick:y,disabled:o,size:"sm",className:"w-full",children:[o?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Enable Client Portal"]})]});const S=lS(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(cn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Be,{variant:"outline",className:r.is_enabled?"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-xs bg-muted text-muted-foreground",children:r.is_enabled?"Active":"Disabled"})]}),e.jsx(wn,{checked:r.is_enabled,onCheckedChange:v})]}),e.jsxs("div",{className:"space-y-1.5 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Visibility:"}),e.jsx(Be,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:r.visibility==="private"?"Private":"Public"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Onboarding:"}),e.jsx("span",{className:"text-foreground",children:r.require_onboarding?"Required":"Disabled"})]}),r.client_name&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Client:"}),e.jsx("span",{className:"text-foreground",children:r.client_name})]})]}),e.jsx("div",{className:"bg-muted/50 rounded-md p-2 mb-3",children:e.jsx("p",{className:"text-xs font-mono text-muted-foreground truncate",children:S})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 mb-2 w-full",children:[e.jsxs(U,{variant:"outline",size:"sm",onClick:b,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Pa,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Copy"})]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:N,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Sr,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Preview"})]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>f(!0),className:"text-xs w-full min-w-0 px-2",children:[e.jsx($r,{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(U,{variant:"ghost",size:"sm",onClick:()=>m(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(p4,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Post Update"})]}),e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>u(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(qc,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Settings"})]})]}),e.jsxs(xr,{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(Ro,{className:"h-3 w-3"}),"View incoming referrals"]})]}),e.jsx(grt,{open:d,onOpenChange:u,portal:r,dealOwnerId:A}),e.jsx(xrt,{open:h,onOpenChange:m,portalId:r.id,portalSlug:r.slug,notifyClient:r.notify_client}),e.jsx(yrt,{open:p,onOpenChange:f,portal:r,dealName:s.deal_name})]})}function nZn({dealId:s,primaryContactId:t}){const n=Wn(),{data:r,isLoading:a}=bts(s),{data:i}=Cb(),l=BYn(),o=UYn(),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,p]=j.useState("Client"),f=new Set((r==null?void 0:r.map(N=>N.contact_id))||[]);t&&f.add(t);const x=i==null?void 0:i.filter(N=>{var A,T,L;if(f.has(N.id))return!1;if(!u.trim())return!0;const S=u.toLowerCase();return((A=N.first_name)==null?void 0:A.toLowerCase().includes(S))||((T=N.last_name)==null?void 0:T.toLowerCase().includes(S))||((L=N.email)==null?void 0:L.toLowerCase().includes(S))}).slice(0,8),y=N=>{l.mutate({dealId:s,contactId:N,role:m}),d(!1),h("")},v=N=>{o.mutate({id:N,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(Bn,{className:"h-4 w-4"}),"Additional Contacts"]})}),e.jsxs(md,{open:c,onOpenChange:d,children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{variant:"outline",size:"sm",className:"w-full text-muted-foreground",children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1"}),"Link a contact (lender, spouse, vendor...)"]})}),e.jsx(id,{className:"w-80 p-3",align:"start",children:e.jsx(ySt,{search:u,setSearch:h,selectedRole:m,setSelectedRole:p,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(Bn,{className:"h-4 w-4"}),"Linked Contacts",r&&r.length>0&&e.jsx(Be,{variant:"secondary",className:"text-[10px] px-1.5",children:r.length})]}),e.jsxs(md,{open:c,onOpenChange:d,children:[e.jsx(pd,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"sm",className:"h-7 px-2",children:e.jsx(an,{className:"h-3.5 w-3.5"})})}),e.jsx(id,{className:"w-80 p-3",align:"end",children:e.jsx(ySt,{search:u,setSearch:h,selectedRole:m,setSelectedRole:p,filteredContacts:x,onAdd:y})})]})]}),e.jsx("div",{className:"space-y-1.5",children:r==null?void 0:r.map(N=>{var S,A,T,L,M,I,R,z;return e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md bg-muted/40 group",children:[e.jsx(Ea,{className:"h-7 w-7",children:e.jsxs(Ta,{className:"text-[10px] bg-primary/10 text-primary",children:[(A=(S=N.contact)==null?void 0:S.first_name)==null?void 0:A[0],(L=(T=N.contact)==null?void 0:T.last_name)==null?void 0:L[0]]})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("button",{onClick:()=>n(`/mission-control/contacts/${N.contact_id}`),className:"text-sm font-medium hover:underline text-primary truncate block",children:[(M=N.contact)==null?void 0:M.first_name," ",(I=N.contact)==null?void 0:I.last_name]})}),e.jsx(Be,{variant:"outline",className:`text-[10px] px-1.5 py-0 shrink-0 ${b[N.role]||b.Other}`,children:N.role}),e.jsxs("div",{className:"flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[((R=N.contact)==null?void 0:R.phone)&&e.jsx(U,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`tel:${N.contact.phone}`,children:e.jsx(ba,{className:"h-3 w-3"})})}),((z=N.contact)==null?void 0:z.email)&&e.jsx(U,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`mailto:${N.contact.email}`,children:e.jsx(ln,{className:"h-3 w-3"})})}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>v(N.id),children:e.jsx(In,{className:"h-3 w-3"})})]})]},N.id)})})]})}function ySt({search:s,setSearch:t,selectedRole:n,setSelectedRole:r,filteredContacts:a,onAdd:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(Ns,{value:n,onValueChange:r,children:[e.jsx(ws,{className:"h-8 text-sm",children:e.jsx(ks,{placeholder:"Role"})}),e.jsx(js,{children:zYn.map(l=>e.jsx(et,{value:l,children:l},l))})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(xe,{value:s,onChange:l=>t(l.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(Gi,{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 lX=[{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"}],rZn=[{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 aZn(){const s=Qt();return yt({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 iZn(){const s=Qt();return yt({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 oZn(){return ct({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 lZn(){const s=Sa(),t=Qt();return yt({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(f=>String(f.title).toLowerCase())),u=a,h=(f,x)=>{const y=f==="stage_entry"?null:u[f],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(f=>!d.has(String(f.title).toLowerCase())).map((f,x)=>({owner_user_id:s,deal_id:r,contact_id:u.contact_id,stage_id:u.stage_id,title:f.title,description:f.description,priority:f.priority,status:"todo",due_date:h(f.due_anchor,f.due_offset_days),sort_order:x}));if(m.length===0)return 0;const{error:p}=await q.from("deal_tasks").insert(m);if(p)throw p;return m.length},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]}),t.invalidateQueries({queryKey:["tc-dashboard"]})}})}function cZn(){const s=Sa(),t=Qt();return yt({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 dZn(){const s=Sa();return ct({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 vrt(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 T5(s){const t=vrt(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 uZn(s){return s===null?"none":s<0?"overdue":s===0?"today":s<=3?"soon":"upcoming"}const hZn={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 mZn(s){const t=vrt(s);return t?t.toLocaleDateString("en-US",{month:"short",day:"numeric"}):null}function vSt(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 pZn({deal:s,compact:t=!1}){const n=aZn(),r=iZn(),[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 p=d,f=()=>{const K={};lX.forEach(Z=>{K[Z.key]=(s==null?void 0:s[Z.key])??""}),o(K),i(!0)},x=async()=>{try{await n.mutateAsync({dealId:s.id,dates:l}),re.success("Transaction dates updated"),i(!1)}catch(K){re.error((K==null?void 0:K.message)||"Could not save dates")}},y=async(K,Z)=>{const Q=p;u(K);try{await r.mutateAsync({dealId:s.id,completed:K}),re.success(Z)}catch(le){u(Q),re.error((le==null?void 0:le.message)||"Could not update milestone")}},v=j.useMemo(()=>lX.map(K=>{const Z=(s==null?void 0:s[K.key])??null,Q=T5(Z),le=p.includes(K.key),ue=Z?le?"done":uZn(Q):"none";return{...K,value:Z,days:Q,isDone:le,state:ue}}),[s,p.join(",")]),b=v.filter(K=>K.value).length,N=v.filter(K=>K.state==="done").length,S=T5(s==null?void 0:s.target_close_date),A=v.filter(K=>K.value&&!K.isDone&&K.days!==null&&K.days>=0).sort((K,Z)=>(K.days??0)-(Z.days??0))[0],T=v.filter(K=>K.state==="overdue"),L=()=>{const K=Array.from(new Set([...p,...T.map(Z=>Z.key)]));y(K,"Past milestones marked complete")},M=(K,Z)=>{const Q=Z?p.filter(le=>le!==K):[...p,K];y(Q,Z?"Marked as not complete":"Milestone completed")},[I,R]=j.useState(null),[z,$]=j.useState(""),H=K=>{$((s==null?void 0:s[K])??""),R(K)},V=async(K,Z)=>{try{await n.mutateAsync({dealId:s.id,dates:{[K]:Z}}),re.success(Z?"Date saved":"Date cleared"),R(null)}catch(Q){re.error((Q==null?void 0:Q.message)||"Could not save date")}};return e.jsx(wN,{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(ch,{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:S!==null?S>=0?`${S} day${S===1?"":"s"} to closing · ${N}/${b} milestones done`:`Closing was ${Math.abs(S)} day${Math.abs(S)===1?"":"s"} ago`:`${b} of ${lX.length} key dates set`})]})]}),e.jsxs(zs,{open:a,onOpenChange:K=>K?f():i(!1),children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{variant:"outline",size:"sm",className:"shrink-0 gap-1.5",children:[e.jsx(ri,{className:"h-3.5 w-3.5"}),t?"":"Edit dates"]})}),e.jsxs(Ds,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Key transaction dates"})}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-3 max-h-[60vh] overflow-y-auto pr-1",children:lX.map(K=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{htmlFor:`kd-${K.key}`,className:"text-xs text-muted-foreground",children:K.label}),e.jsx(xe,{id:`kd-${K.key}`,type:"date",value:l[K.key]??"",onChange:Z=>o(Q=>({...Q,[K.key]:Z.target.value})),className:"h-9"})]},K.key))}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>i(!1),children:"Cancel"}),e.jsxs(U,{size:"sm",onClick:x,disabled:n.isPending,children:[n.isPending?e.jsx(Et,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(Xr,{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(K=>{const Z=!!K.value;return e.jsxs("div",{className:"relative",children:[e.jsxs(Bg,{children:[e.jsx(Ug,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:r.isPending,onClick:()=>Z?M(K.key,K.isDone):H(K.key),className:Mt("relative text-left rounded-lg border px-2.5 py-2 transition-colors w-full",hZn[K.state],"hover:brightness-105 cursor-pointer"),children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide opacity-70 truncate pr-10",children:K.short}),e.jsx("p",{className:"text-sm font-semibold leading-tight truncate",children:mZn(K.value)??"Set date"}),K.value&&e.jsx("p",{className:"text-[10px] opacity-80 truncate",children:vSt(K.state,K.days)}),Z&&e.jsx("span",{className:Mt("absolute top-1.5 right-7 h-4 w-4 rounded-full border flex items-center justify-center",K.isDone?"bg-emerald-500 border-emerald-500 text-white":"border-current opacity-40"),children:K.isDone&&e.jsx(Xr,{className:"h-2.5 w-2.5"})})]})}),e.jsx(ng,{side:"top",children:K.value?K.isDone?`${K.label} completed — click to reopen`:`Click to mark ${K.label} complete`:`${K.label} — click to set the date`})]}),e.jsxs(md,{open:I===K.key,onOpenChange:Q=>Q?H(K.key):R(null),children:[e.jsx(pd,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":`Edit ${K.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(ri,{className:"h-3 w-3"})})}),e.jsxs(id,{className:"w-64 p-3",align:"end",children:[e.jsx(te,{className:"text-xs text-muted-foreground",children:K.label}),e.jsx(xe,{type:"date",autoFocus:!0,value:z,onChange:Q=>$(Q.target.value),className:"h-9 mt-1"}),e.jsxs("div",{className:"flex items-center justify-between gap-2 mt-3",children:[e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>V(K.key,""),disabled:n.isPending||!K.value,children:"Clear"}),e.jsxs(U,{size:"sm",onClick:()=>V(K.key,z),disabled:n.isPending,children:[n.isPending?e.jsx(Et,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(Xr,{className:"h-3.5 w-3.5 mr-1"}),"Save"]})]})]})]})]},K.key)})}),(T.length>0||A||N>0)&&e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2 text-xs",children:[N>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(jF,{className:"h-3 w-3"}),N," completed"]}),T.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(tc,{className:"h-3 w-3"}),T.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," · ",vSt(A.state,A.days)]}),T.length>0&&e.jsxs("button",{type:"button",onClick:L,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(jF,{className:"h-3 w-3"}),"Mark past dates complete"]})]}),T.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 fZn={Home:ra,FileSignature:Iw,Handshake:a1,CalendarClock:ch,Sparkles:cn,ClipboardCheck:T4},gZn={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 xZn(s,t){var a;const n=((a=rZn.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 Nts({open:s,onOpenChange:t,dealId:n,dealName:r}){const{data:a,isLoading:i}=oZn(),{data:l}=nae(),o=lZn(),c=cZn(),[d,u]=j.useState(null),[h,m]=j.useState({}),p=y=>{if(h[y.id])return h[y.id];const v=l==null?void 0:l.find(b=>{var N,S;return((N=b.name)==null?void 0:N.toLowerCase())===((S=y.target_stage_name)==null?void 0:S.toLowerCase())});return(v==null?void 0:v.id)??""},f=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=p(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(Ds,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0",children:[e.jsx(Vs,{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(ig,{className:"h-4.5 w-4.5 text-primary"})}),e.jsxs("div",{children:[e.jsx($s,{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(Gi,{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(Et,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsx(y9,{type:"single",collapsible:!0,className:"space-y-3",children:(a||[]).map(y=>{const v=fZn[y.icon||"ClipboardCheck"]||T4,b=y.accent_color||"hsl(var(--primary))";return e.jsxs(WP,{value:y.id,className:"border rounded-xl px-0 overflow-hidden bg-card",children:[e.jsx(KP,{className:"px-4 py-3 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-3 text-left flex-1 min-w-0",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg flex items-center justify-center shrink-0",style:{backgroundColor:`${b}1a`},children:e.jsx(v,{className:"h-5 w-5",style:{color:b}})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm",children:y.name}),e.jsxs(Be,{variant:"secondary",className:"text-[10px]",children:[y.tasks.length," steps"]}),y.deal_type&&e.jsx(Be,{variant:"outline",className:"text-[10px] capitalize",children:y.deal_type})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:y.description})]})]})}),e.jsxs(YP,{className:"px-4 pb-4",children:[e.jsx("div",{className:"space-y-1.5 mb-4",children:y.tasks.map((N,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:N.title}),N.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:N.description}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:xZn(N.due_anchor,N.due_offset_days)})]}),e.jsx("span",{className:Mt("text-[10px] px-1.5 py-0.5 rounded-full shrink-0 capitalize",gZn[N.priority]),children:N.priority})]},N.id))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 pt-2 border-t",children:[n&&e.jsxs(U,{size:"sm",className:"gap-1.5",onClick:()=>f(y),disabled:d===y.id,children:[d===y.id?e.jsx(Et,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Af,{className:"h-3.5 w-3.5"}),"Add to this deal"]}),e.jsxs("div",{className:"flex gap-2 flex-1",children:[e.jsxs(Ns,{value:p(y),onValueChange:N=>m(S=>({...S,[y.id]:N})),children:[e.jsx(ws,{className:"h-9 text-xs flex-1",children:e.jsx(ks,{placeholder:"Trigger stage"})}),e.jsx(js,{children:(l||[]).map(N=>e.jsx(et,{value:N.id,children:N.name},N.id))})]}),e.jsxs(U,{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(Et,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(IA,{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(zr,{className:"h-3 w-3"}),"Automating adds these steps to every future deal that reaches that stage."]})]})]},y.id)})})})})]})})}const yZn={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"}},vZn={note:Ki,call:ba,email:ln,meeting:pa,stage_change:Sr,task_completed:zr,document:ra,system:Yr};function bZn({deal:s,open:t,onOpenChange:n,onEdit:r,onAddToScorecard:a,isWonStage:i}){var Me,Oe;const l=Wn(),{data:o,isLoading:c}=w$n((s==null?void 0:s.id)||""),{data:d,isLoading:u}=N$n((s==null?void 0:s.id)||""),h=j$n(),m=S$n(),p=k$n(),f=_$n(),{data:x,isLoading:y}=wVn((s==null?void 0:s.id)||""),v=jVn(),b=NVn(),N=kVn(),S=j.useRef(null),[A,T]=j.useState(""),[L,M]=j.useState(""),[I,R]=j.useState(!1),[z,$]=j.useState(!1),[H,V]=j.useState(!1);if(!s)return null;const K=yZn[s.deal_type],Z=(()=>{var Ae;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const Se=((Ae=s.listing)==null?void 0:Ae.created_at)||s.listing_date;if(!Se)return null;const Qe=s.contract_date?Su(s.contract_date):new Date;return hN(Qe,Su(Se))})(),Q=Se=>Se?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Se):"-",le=async()=>{if(A.trim())try{await h.mutateAsync({deal_id:s.id,activity_type:"note",title:"Note added",description:A}),T(""),re.success("Note added")}catch{re.error("Failed to add note")}},ue=async()=>{if(L.trim())try{await m.mutateAsync({deal_id:s.id,title:L,sort_order:((d==null?void 0:d.length)||0)+1}),M(""),re.success("Task added")}catch{re.error("Failed to add task")}},se=async(Se,Qe)=>{try{await p.mutateAsync({id:Se,is_completed:Qe,deal_id:s.id})}catch{re.error("Failed to update task")}},ne=async()=>{try{await f.mutateAsync(s.id),re.success("Deal deleted"),n(!1)}catch{re.error("Failed to delete deal")}},ie=(d==null?void 0:d.filter(Se=>Se.is_completed).length)||0,ce=(d==null?void 0:d.length)||0,je=(x==null?void 0:x.length)||0,be=Se=>Se<1024?`${Se} B`:Se<1024*1024?`${(Se/1024).toFixed(1)} KB`:`${(Se/(1024*1024)).toFixed(1)} MB`,he=Se=>Se?Se.startsWith("image/")?pc:Se.includes("pdf")?Ur:ZU:ZU,ge=async Se=>{const Qe=Se.target.files;if(!(!Qe||!s)){V(!0);try{for(const Ae of Array.from(Qe)){if(Ae.size>20*1024*1024){re.error(`${Ae.name} exceeds 20MB limit`);continue}await v.mutateAsync({dealId:s.id,file:Ae})}re.success("File(s) uploaded")}catch{re.error("Failed to upload file")}finally{V(!1),S.current&&(S.current.value="")}}},ke=async(Se,Qe)=>{if(s)try{await b.mutateAsync({fileId:Se,storagePath:Qe,dealId:s.id}),re.success("File deleted")}catch{re.error("Failed to delete file")}},Te=async(Se,Qe)=>{try{const Ae=await SVn(Se),Fe=document.createElement("a");Fe.href=Ae,Fe.download=Qe,Fe.target="_blank",document.body.appendChild(Fe),Fe.click(),document.body.removeChild(Fe)}catch{re.error("Failed to download file")}};return e.jsxs(e.Fragment,{children:[e.jsx(my,{open:t,onOpenChange:n,children:e.jsxs(g0,{className:"w-full sm:max-w-xl p-0 flex flex-col",children:[e.jsx(vv,{className:"p-6 pb-4 border-b shrink-0",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Be,{variant:"outline",className:Mt("text-xs",K.color),children:K.label}),e.jsxs(Be,{variant:"secondary",className:"text-xs capitalize",children:[s.priority," priority"]})]}),e.jsx(bv,{className:"text-xl",children:s.deal_name}),e.jsx("div",{className:"mt-2",children:e.jsx(_Vn,{dealId:s.id})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{variant:"outline",size:"icon",onClick:()=>r(s),children:e.jsx(sp,{className:"h-4 w-4"})}),e.jsx(U,{variant:"outline",size:"icon",className:"text-destructive hover:bg-destructive/10",onClick:()=>$(!0),children:e.jsx(In,{className:"h-4 w-4"})})]})]})}),e.jsx(Gi,{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(Ea,{className:"h-10 w-10",children:e.jsxs(Ta,{className:"bg-primary/10 text-primary",children:[(Me=s.contact.first_name)==null?void 0:Me[0],(Oe=s.contact.last_name)==null?void 0:Oe[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(U,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`tel:${s.contact.phone}`,children:e.jsx(ba,{className:"h-4 w-4"})})}),s.contact.email&&e.jsx(U,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`mailto:${s.contact.email}`,children:e.jsx(ln,{className:"h-4 w-4"})})}),e.jsx(U,{variant:"outline",size:"icon",title:"Open contact record",onClick:()=>{n(!1),l(`/mission-control/contacts/${s.contact_id}`)},children:e.jsx(Sr,{className:"h-4 w-4"})})]})]}),e.jsx(nZn,{dealId:s.id,primaryContactId:s.contact_id}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[(s.property_address||s.city)&&e.jsxs("div",{className:"col-span-2 flex items-start gap-2 text-sm",children:[e.jsx(ra,{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:Q(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:Q(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?` (${Q(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:Q(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:["+",Q(s.bonus_amount)]})]}),g_(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:Q(g_(s))})]})})]}),i&&!s.scorecard_transaction_id&&a&&e.jsxs(U,{onClick:()=>a(s),className:"w-full bg-green-600 hover:bg-green-700",children:[e.jsx(Al,{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(zr,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{children:"Synced to Scorecard"})]}),Z!==null&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 col-span-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Days on Market"}),e.jsxs("p",{className:Mt("text-lg font-bold",Z>90?"text-red-600":Z>60?"text-amber-600":"text-foreground"),children:[Z," ",s.contract_date?"(final)":"days"]})]}),s.target_close_date&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(pa,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Close: ",Gs(Su(s.target_close_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(yu,{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(pZn,{deal:s}),e.jsx(sZn,{deal:s}),e.jsxs(oa,{defaultValue:"tasks",className:"w-full",children:[e.jsxs(la,{className:"w-full grid grid-cols-4",children:[e.jsxs(Kt,{value:"tasks",className:"gap-1",children:[e.jsx(zr,{className:"h-4 w-4"}),"Tasks ",ce>0&&`(${ie}/${ce})`]}),e.jsxs(Kt,{value:"files",className:"gap-1",children:[e.jsx(MM,{className:"h-4 w-4"}),"Files ",je>0&&`(${je})`]}),e.jsxs(Kt,{value:"forms",className:"gap-1",children:[e.jsx(Iw,{className:"h-4 w-4"}),"Forms"]}),e.jsxs(Kt,{value:"activity",className:"gap-1",children:[e.jsx(Yr,{className:"h-4 w-4"}),"Activity"]})]}),e.jsx(Zt,{value:"forms",className:"mt-4",children:e.jsx(ZYn,{dealId:s.id,dealName:s.deal_name})}),e.jsxs(Zt,{value:"tasks",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{placeholder:"Add a new task...",value:L,onChange:Se=>M(Se.target.value),onKeyDown:Se=>Se.key==="Enter"&&ue()}),e.jsx(U,{onClick:ue,disabled:!L.trim(),children:e.jsx(an,{className:"h-4 w-4"})}),e.jsxs(U,{variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>R(!0),children:[e.jsx(ig,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"space-y-2",children:[d==null?void 0:d.map(Se=>e.jsxs("div",{className:Mt("flex items-center gap-3 p-3 rounded-lg border transition-colors",Se.is_completed?"bg-muted/50 border-border":"bg-background"),children:[e.jsx(xi,{checked:Se.is_completed,onCheckedChange:Qe=>se(Se.id,!!Qe)}),e.jsx("span",{className:Mt("flex-1 text-sm",Se.is_completed&&"line-through text-muted-foreground"),children:Se.title}),Se.due_date&&e.jsx("span",{className:"text-xs text-muted-foreground",children:Gs(new Date(Se.due_date),"MMM d")})]},Se.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(Zt,{value:"files",className:"mt-4 space-y-3",children:[e.jsx("input",{type:"file",ref:S,className:"hidden",multiple:!0,onChange:ge,accept:".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.webp,.gif,.txt,.csv"}),e.jsxs(U,{variant:"outline",className:"w-full border-dashed",onClick:()=>{var Se;return(Se=S.current)==null?void 0:Se.click()},disabled:H,children:[H?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(qa,{className:"h-4 w-4 mr-2"}),H?"Uploading...":"Upload Files"]}),e.jsxs("div",{className:"space-y-2",children:[x==null?void 0:x.map(Se=>{const Qe=he(Se.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(Qe,{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:Se.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[be(Se.file_size)," · ",Gs(new Date(Se.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(wN,{children:e.jsxs(Bg,{children:[e.jsx(Ug,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:`h-8 w-8 transition-colors ${Se.visible_on_portal?"text-primary bg-primary/10 hover:bg-primary/20":"text-muted-foreground/40 hover:text-muted-foreground"}`,onClick:()=>N.mutate({fileId:Se.id,visible:!Se.visible_on_portal,dealId:s.id}),children:Se.visible_on_portal?e.jsx(xa,{className:"h-4 w-4"}):e.jsx(Vg,{className:"h-4 w-4"})})}),e.jsx(ng,{side:"top",children:Se.visible_on_portal?"Visible on client portal":"Hidden from client portal"})]})}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>Te(Se.storage_path,Se.file_name),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>ke(Se.id,Se.storage_path),children:e.jsx(er,{className:"h-4 w-4"})})]})]},Se.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(Zt,{value:"activity",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Fs,{placeholder:"Add a note...",value:A,onChange:Se=>T(Se.target.value),rows:2}),e.jsxs(U,{onClick:le,disabled:!A.trim(),size:"sm",className:"w-full",children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),"Add Note"]})]}),e.jsxs("div",{className:"space-y-3",children:[o==null?void 0:o.map(Se=>{const Qe=vZn[Se.activity_type]||Yr;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(Qe,{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:Se.title}),Se.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:Se.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Nd(new Date(Se.created_at),{addSuffix:!0})})]})]},Se.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(Nts,{open:I,onOpenChange:R,dealId:s==null?void 0:s.id,dealName:s==null?void 0:s.deal_name}),e.jsx(Fl,{open:z,onOpenChange:$,children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Delete Deal?"}),e.jsxs(Ll,{children:['This will permanently delete "',s.deal_name,'" and all associated data. This action cannot be undone.']})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:ne,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function _Zn({open:s,onOpenChange:t,deal:n,onComplete:r}){const a=iPe(),i=vJt(),{data:l}=g9(),{data:o}=F_(),[c,d]=j.useState({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:Gs(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",p=n.expected_price||0,f=n.commission_percentage||3,x=n.expected_commission||p*f/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||Gs(new Date,"yyyy-MM-dd"),sale_price:p,commission_amount:x,lead_source_id:"",client_type_id:"",notes:n.notes||""})}},[n,s]);const u=async m=>{if(m.preventDefault(),!!n)try{const p=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:p.id,actual_close_date:c.close_date}),re.success("Deal added to Scorecard! 🎉"),t(!1),r==null||r()}catch(p){console.error("Error syncing to scorecard:",p),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(Ds,{className:"sm:max-w-[550px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{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(Al,{className:"h-6 w-6 text-green-600 dark:text-green-400"})}),e.jsx($s,{className:"text-center text-xl",children:"Congratulations on Closing! 🎉"}),e.jsx(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(te,{htmlFor:"property_address",className:"flex items-center gap-2",children:[e.jsx(ra,{className:"h-4 w-4 text-muted-foreground"}),"Property Address *"]}),e.jsx(xe,{id:"property_address",value:c.property_address,onChange:m=>d(p=>({...p,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(te,{htmlFor:"city",children:"City"}),e.jsx(xe,{id:"city",value:c.city,onChange:m=>d(p=>({...p,city:m.target.value})),placeholder:"City"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"state",children:"State"}),e.jsx(xe,{id:"state",value:c.state,onChange:m=>d(p=>({...p,state:m.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"zip",children:"Zip"}),e.jsx(xe,{id:"zip",value:c.zip,onChange:m=>d(p=>({...p,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(te,{children:"Transaction Type *"}),e.jsxs(Ns,{value:c.transaction_type,onValueChange:m=>d(p=>({...p,transaction_type:m})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"buyer",children:"Buyer"}),e.jsx(et,{value:"seller",children:"Seller"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"close_date",className:"flex items-center gap-2",children:[e.jsx(pa,{className:"h-4 w-4 text-muted-foreground"}),"Close Date *"]}),e.jsx(xe,{id:"close_date",type:"date",value:c.close_date,onChange:m=>d(p=>({...p,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(te,{htmlFor:"sale_price",className:"flex items-center gap-2",children:[e.jsx(yu,{className:"h-4 w-4 text-muted-foreground"}),"Sale Price *"]}),e.jsx(xe,{id:"sale_price",type:"number",value:c.sale_price||"",onChange:m=>d(p=>({...p,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(te,{htmlFor:"commission_amount",className:"flex items-center gap-2",children:[e.jsx(PM,{className:"h-4 w-4 text-muted-foreground"}),"GCI (Commission)"]}),e.jsx(xe,{id:"commission_amount",type:"number",value:c.commission_amount||"",onChange:m=>d(p=>({...p,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(te,{children:"Lead Source"}),e.jsxs(Ns,{value:c.lead_source_id,onValueChange:m=>d(p=>({...p,lead_source_id:m})),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select source"})}),e.jsx(js,{children:l==null?void 0:l.map(m=>e.jsx(et,{value:m.id,children:m.name},m.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Client Type"}),e.jsxs(Ns,{value:c.client_type_id,onValueChange:m=>d(p=>({...p,client_type_id:m})),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select type"})}),e.jsx(js,{children:o==null?void 0:o.map(m=>e.jsx(et,{value:m.id,children:m.name},m.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"notes",children:"Notes"}),e.jsx(Fs,{id:"notes",value:c.notes,onChange:m=>d(p=>({...p,notes:m.target.value})),placeholder:"Any additional notes about this transaction...",rows:2})]}),e.jsxs(Mr,{className:"gap-2 sm:gap-0 pt-4",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Skip for now"}),e.jsx(U,{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(Oa,{className:"ml-2 h-4 w-4"})]})})]})]})]})})}const wZn={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"}},bSt={urgent:0,high:1,medium:2,low:3};function jZn({deals:s,stages:t,onDealClick:n,onStageChange:r}){const[a,i]=j.useState("target_close_date"),[l,o]=j.useState("asc"),c=p=>{a===p?o(f=>f==="asc"?"desc":"asc"):(i(p),o("asc"))},d=j.useMemo(()=>[...s].sort((p,f)=>{var y,v;let x=0;switch(a){case"deal_name":x=p.deal_name.localeCompare(f.deal_name);break;case"stage":{const b=((y=t.find(S=>S.id===p.stage_id))==null?void 0:y.sort_order)||0,N=((v=t.find(S=>S.id===f.stage_id))==null?void 0:v.sort_order)||0;x=b-N;break}case"expected_price":x=(p.expected_price||0)-(f.expected_price||0);break;case"expected_commission":x=(p.expected_commission||0)-(f.expected_commission||0);break;case"target_close_date":{const b=p.target_close_date?Su(p.target_close_date).getTime():1/0,N=f.target_close_date?Su(f.target_close_date).getTime():1/0;x=b-N;break}case"priority":x=bSt[p.priority]-bSt[f.priority];break}return l==="asc"?x:-x}),[s,t,a,l]),u=p=>p?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(p):"—",h=p=>p?t.find(f=>f.id===p):null,m=({field:p,children:f})=>e.jsxs(U,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>c(p),children:[f,a===p?l==="asc"?e.jsx(cp,{className:"ml-2 h-4 w-4"}):e.jsx(ag,{className:"ml-2 h-4 w-4"}):e.jsx(xx,{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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{className:"bg-muted/50",children:[e.jsx(Lt,{className:"w-[250px]",children:e.jsx(m,{field:"deal_name",children:"Deal Name"})}),e.jsx(Lt,{className:"w-[150px]",children:e.jsx(m,{field:"stage",children:"Stage"})}),e.jsx(Lt,{className:"w-[100px]",children:"Type"}),e.jsx(Lt,{className:"w-[120px]",children:e.jsx(m,{field:"expected_price",children:"Price"})}),e.jsx(Lt,{className:"w-[120px]",children:e.jsx(m,{field:"expected_commission",children:"GCI"})}),e.jsx(Lt,{className:"w-[130px]",children:e.jsx(m,{field:"target_close_date",children:"Close Date"})}),e.jsx(Lt,{className:"w-[100px]",children:e.jsx(m,{field:"priority",children:"Priority"})})]})}),e.jsx(Xa,{children:d.map(p=>{h(p.stage_id);const f=wZn[p.deal_type],x=p.target_close_date?hN(Su(p.target_close_date),new Date):null,y=x!==null&&x<0,v=x!==null&&x<=7&&x>=0;return e.jsxs(gn,{className:Mt("cursor-pointer hover:bg-muted/50 transition-colors",y&&"bg-red-50/50"),onClick:()=>n(p),children:[e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{children:[e.jsx("p",{className:"truncate max-w-[230px]",children:p.deal_name}),p.contact&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[p.contact.first_name," ",p.contact.last_name]})]})}),e.jsx(gt,{onClick:b=>b.stopPropagation(),children:e.jsx(jJt,{stages:t,currentStageId:p.stage_id||"",onStageSelect:(b,N)=>r(p.id,b,N)})}),e.jsx(gt,{children:e.jsx(Be,{variant:"outline",className:Mt("text-xs",f.color),children:f.label})}),e.jsx(gt,{children:e.jsx("span",{className:"font-medium",children:u(p.expected_price)})}),e.jsx(gt,{children:e.jsx("span",{className:"text-emerald-600",children:u(p.expected_commission)})}),e.jsx(gt,{children:p.target_close_date?e.jsxs("div",{className:Mt("flex items-center gap-1 text-sm",y&&"text-red-600",v&&!y&&"text-amber-600"),children:[y&&e.jsx(Vo,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:Gs(Su(p.target_close_date),"MMM d, yyyy")})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{children:e.jsx(Be,{variant:"outline",className:Mt("text-xs capitalize",p.priority==="urgent"&&"border-red-200 bg-red-50 text-red-700",p.priority==="high"&&"border-orange-200 bg-orange-50 text-orange-700",p.priority==="medium"&&"border-amber-200 bg-amber-50 text-amber-700",p.priority==="low"&&"border-slate-200 bg-slate-50 text-slate-600"),children:p.priority})})]},p.id)})})]})})}function kts(){const s=Sa();return ct({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 NZn(s){const t=Sa();return ct({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 kZn(){const s=Sa(),t=Qt();return yt({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 SZn(){const s=Qt();return yt({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 CZn(){const s=Qt();return yt({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 WIe(){const s=Qt();return yt({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 AZn(){const s=Qt();return yt({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 EZn(s){const t=Sa();return ct({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 TZn(){const s=Sa(),t=Qt();return yt({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 MZn(){const s=Qt();return yt({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 PZn(){const s=Sa(),t=Qt();return yt({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 LZn={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function IZn({open:s,onOpenChange:t,dealId:n,dealName:r,fromStageName:a,toStageName:i,toStageId:l,onConfirm:o}){const{data:c,isLoading:d}=NZn(s?n:void 0),u=AZn(),h=PZn(),[m,p]=j.useState(new Set),[f,x]=j.useState(!1),y=(c||[]).filter(S=>S.status!=="done");j.useEffect(()=>{y.length>0&&p(new Set(y.map(S=>S.id)))},[c]);const v=S=>{p(A=>{const T=new Set(A);return T.has(S)?T.delete(S):T.add(S),T})},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)}},N=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(Ds,{className:"sm:max-w-[480px]",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(Be,{variant:"outline",className:"text-sm",children:a}),e.jsx(Oa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Be,{className:"text-sm bg-primary",children:i})]}),d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Et,{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(Gi,{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(xi,{checked:m.has(S.id),onCheckedChange:()=>v(S.id)}),e.jsxs("span",{className:"text-sm flex-1",children:[LZn[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(U,{variant:"ghost",size:"sm",onClick:()=>{m.size===y.length?p(new Set):p(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(U,{variant:"outline",size:"sm",onClick:N,disabled:f,children:"Skip"}),e.jsxs(U,{size:"sm",onClick:b,disabled:f,children:[f&&e.jsx(Et,{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(zr,{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(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{onClick:b,disabled:f,children:[f&&e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}),"Move to ",i]})]})]})]})})}const RZn=[{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"}],DZn=[{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 Sts({open:s,onOpenChange:t}){const n=Sa(),{data:r,isLoading:a}=MOt(),i=LIs(),[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=p=>o(f=>({...f,...p})),h=async(p,f)=>{if(n){if(p.size>5*1024*1024){re.error("Image must be under 5MB");return}d(f);try{const x=await POt(n,p,f);u(f==="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(Ds,{className:"max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx($c,{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(Gi,{className:"flex-1 pr-3 -mr-3",children:a?e.jsx("div",{className:"py-12 flex justify-center",children:e.jsx(Et,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6 py-2",children:[e.jsx(OZn,{draft:l}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(te,{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:DZn.map(p=>{const f=(l.portal_theme??"noir")===p.id;return e.jsxs("button",{type:"button",onClick:()=>u({portal_theme:p.id}),className:Mt("rounded-xl border-2 p-3 text-left transition-all",f?"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:p.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:p.accent}}),e.jsx("div",{className:"h-2.5 w-20 rounded",style:{background:p.ink,opacity:.85}}),e.jsx("div",{className:"h-6 rounded-md",style:{background:p.surface,border:`1px solid ${p.accent}44`}})]})}),e.jsx("div",{className:"text-sm font-medium text-foreground",children:p.name}),e.jsx("div",{className:"text-[11px] text-muted-foreground leading-snug",children:p.description})]},p.id)})})]}),e.jsx(_St,{label:"Logo",hint:"Shown above your name on the portal. PNG with transparent background works best.",value:l.logo_url,uploading:c==="logo",onUpload:p=>h(p,"logo"),onClear:()=>u({logo_url:null}),aspect:"square"}),e.jsx(_St,{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:p=>h(p,"cover"),onClear:()=>u({cover_photo_url:null}),aspect:"cover"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(te,{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:RZn.map(p=>{const f=l.brand_color===p.brand&&l.accent_color===p.accent;return e.jsxs("button",{type:"button",onClick:()=>u({brand_color:p.brand,accent_color:p.accent}),className:Mt("group relative rounded-lg border-2 p-2 text-left transition-all",f?"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:p.brand}}),e.jsx("div",{className:"flex-1",style:{background:p.accent}})]}),e.jsx("div",{className:"text-[11px] mt-1.5 font-medium text-foreground",children:p.name})]},p.name)})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(wSt,{label:"Brand",value:l.brand_color,onChange:p=>u({brand_color:p})}),e.jsx(wSt,{label:"Accent",value:l.accent_color,onChange:p=>u({accent_color:p})})]})]}),e.jsxs("div",{children:[e.jsx(te,{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(xe,{value:l.tagline||"",onChange:p=>u({tagline:p.target.value}),placeholder:"Your trusted real estate advisor",maxLength:80})]}),e.jsxs("div",{children:[e.jsx(te,{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:p=>u({welcome_message:p.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(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{onClick:m,disabled:i.isPending,children:[i.isPending?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-2"}),"Save Branding"]})]})]})})}function OZn({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 _St({label:s,hint:t,value:n,uploading:r,onUpload:a,onClear:i,aspect:l}){return e.jsxs("div",{children:[e.jsx(te,{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:Mt("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(pc,{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(Et,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(qa,{className:"h-3.5 w-3.5"}),n?"Replace":"Upload"]})]}),n&&e.jsx(U,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(In,{className:"h-3.5 w-3.5"})})]})]})]})}function wSt({label:s,value:t,onChange:n}){const r=t||"#000000";return e.jsxs("div",{children:[e.jsx(te,{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(xe,{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 FZn(){const s=Sa();return ct({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 zZn({dealId:s,dealName:t,contactName:n,portal:r,onSettingsOpen:a,onComposerOpen:i,onInviteOpen:l,onDeleteConfirm:o}){const c=est(),d=eW(),u=gWt(),h=xWt(),[m,p]=j.useState(!1),f=!!(r!=null&&r.archived_at),x=async()=>{p(!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{p(!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(lS(r.slug)),re.success("Link copied!"))},b=()=>{r&&window.open(lS(r.slug),"_blank")},N=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?f?e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg opacity-60 bg-muted/30",children:[e.jsxs(xr,{to:`/mission-control/client-portals/${r.id}`,className:"flex-1 min-w-0 hover:opacity-80",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:t}),e.jsx(Be,{variant:"outline",className:"text-[10px] bg-muted text-muted-foreground",children:"Archived"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r.client_name||n||"No client name"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsxs(U,{variant:"ghost",size:"sm",onClick:S,className:"text-xs gap-1",children:[e.jsx(jM,{className:"h-3.5 w-3.5"}),"Restore"]}),e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>o(r),className:"text-xs gap-1 text-destructive hover:text-destructive",children:[e.jsx(In,{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(xr,{to:`/mission-control/client-portals/${r.id}`,className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate group-hover:text-primary transition-colors",children:t}),e.jsx(Be,{variant:"outline",className:r.is_enabled?"text-[10px] bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-[10px] bg-muted text-muted-foreground",children:r.is_enabled?"Active":"Disabled"}),e.jsx(gi,{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(U,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:v,title:"Copy link",children:e.jsx(Pa,{className:"h-3.5 w-3.5"})}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:b,title:"Preview",children:e.jsx(Sr,{className:"h-3.5 w-3.5"})}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(r,t),title:"Invite client",children:e.jsx($r,{className:"h-3.5 w-3.5"})}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>i(r),title:"Post update",children:e.jsx(p4,{className:"h-3.5 w-3.5"})}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>a(r),title:"Settings",children:e.jsx(qc,{className:"h-3.5 w-3.5"})}),e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Z1,{className:"h-3.5 w-3.5"})})}),e.jsx(Eu,{align:"end",children:e.jsxs(La,{onClick:N,children:[e.jsx(n1,{className:"h-4 w-4 mr-2"}),"Archive Portal"]})})]}),e.jsx(wn,{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(U,{size:"sm",onClick:x,disabled:m,className:"shrink-0 ml-4",children:[m?e.jsx(Et,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(cn,{className:"h-3 w-3 mr-1"}),"Enable Portal"]})]})}function Cts(){const{data:s,isLoading:t}=rae(),{data:n,isLoading:r}=FZn(),[a,i]=j.useState(""),[l,o]=j.useState("all"),c=yWt(),[d,u]=j.useState(null),[h,m]=j.useState(null),[p,f]=j.useState(null),[x,y]=j.useState(null),[v,b]=j.useState(!1),N=Sa(),S=t||r,A=new Map;n==null||n.forEach($=>A.set($.deal_id,$));const L=[...(s||[]).filter($=>{var Q,le,ue,se,ne;const H=A.get($.id),V=a.toLowerCase(),K=!V||$.deal_name.toLowerCase().includes(V)||((le=(Q=$.contact)==null?void 0:Q.first_name)==null?void 0:le.toLowerCase().includes(V))||((se=(ue=$.contact)==null?void 0:ue.last_name)==null?void 0:se.toLowerCase().includes(V))||((ne=H==null?void 0:H.client_name)==null?void 0:ne.toLowerCase().includes(V));let Z=!0;return l==="active"?Z=!!(H!=null&&H.is_enabled)&&!(H!=null&&H.archived_at):l==="disabled"?Z=!!H&&!H.is_enabled&&!H.archived_at:l==="archived"?Z=!!(H!=null&&H.archived_at):l==="none"?Z=!H:l==="all"&&(Z=!(H!=null&&H.archived_at)||!H),K&&Z})].sort(($,H)=>{const V=A.get($.id),K=A.get(H.id);if(V!=null&&V.archived_at&&!(K!=null&&K.archived_at))return 1;if(!(V!=null&&V.archived_at)&&(K!=null&&K.archived_at)||V&&!K)return-1;if(!V&&K)return 1;if(V&&K){if(V.is_enabled&&!K.is_enabled)return-1;if(!V.is_enabled&&K.is_enabled)return 1}return 0}),M=(n==null?void 0:n.filter($=>!$.archived_at).length)||0,I=(n==null?void 0:n.filter($=>$.is_enabled&&!$.archived_at).length)||0,R=(n==null?void 0:n.filter($=>$.archived_at).length)||0,z=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(Et,{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(cn,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"font-medium",children:[M," Portals"]})]}),e.jsxs("span",{className:"text-muted-foreground",children:[I," active · ",M-I," disabled",R>0&&` · ${R} archived`]})]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>b(!0),className:"gap-1.5",children:[e.jsx($c,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search deals or clients...",value:a,onChange:$=>i($.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(er,{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($=>e.jsx(U,{variant:l===$?"secondary":"ghost",size:"sm",onClick:()=>o($),className:"text-xs px-3 capitalize",children:$==="none"?"No Portal":$},$))})]}),e.jsx(Gi,{className:"h-[calc(100vh-22rem)]",children:e.jsxs("div",{className:"space-y-2 pb-4",children:[L.map($=>{const H=A.get($.id)||null,V=$.contact?`${$.contact.first_name||""} ${$.contact.last_name||""}`.trim():"";return e.jsx(zZn,{dealId:$.id,dealName:$.deal_name,contactName:V,portal:H,onSettingsOpen:u,onComposerOpen:K=>m(K),onInviteOpen:(K,Z)=>f({portal:K,dealName:Z}),onDeleteConfirm:y},$.id)}),L.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(cn,{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(grt,{open:!!d,onOpenChange:$=>!$&&u(null),portal:d,dealOwnerId:N||""}),h&&e.jsx(xrt,{open:!!h,onOpenChange:$=>!$&&m(null),portalId:h.id,portalSlug:h.slug,notifyClient:h.notify_client}),p&&e.jsx(yrt,{open:!!p,onOpenChange:$=>!$&&f(null),portal:p.portal,dealName:p.dealName}),e.jsx(Sts,{open:v,onOpenChange:b}),e.jsx(Fl,{open:!!x,onOpenChange:$=>!$&&y(null),children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Permanently delete this portal?"}),e.jsx(Ll,{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(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:z,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function BZn({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(an,{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(Bn,{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(no,{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(p=>{const f=p.onClick?"button":"div";return e.jsxs(f,{type:p.onClick?"button":void 0,onClick:p.onClick,title:p.hint,className:Mt("hub-glass min-w-[130px] shrink-0 rounded-xl px-3 py-2.5 text-left transition-all sm:min-w-0",p.onClick&&"hover:scale-[1.02]",p.active&&"ring-2"),style:p.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:p.label}),e.jsx("p",{className:"mt-0.5 text-lg font-bold leading-tight",children:p.value}),p.subtitle&&e.jsx("p",{className:"text-[11px] hub-ink-muted",children:p.subtitle})]},p.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(Fr,{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:p=>r(p.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(er,{className:"h-4 w-4"})})]}),c]}),(d.length>0||h)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[d.map(p=>e.jsxs("button",{onClick:p.onClear,className:"hub-glass inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium",children:[p.label,e.jsx(er,{className:"h-3 w-3 opacity-70"})]},p.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 UZn={closing_soon:{label:"Closing in 7 days",icon:ch,tone:"text-primary"},past_due:{label:"Past close date",icon:tc,tone:"text-destructive"},overdue_tasks:{label:"Overdue tasks",icon:t4,tone:"text-amber-600 dark:text-amber-400"},stalled:{label:"Stalled 14+ days",icon:VX,tone:"text-muted-foreground"}};function qZn({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=UZn[a],o=l.icon,c=t===a;return e.jsxs("button",{onClick:()=>n(a),className:Mt("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:Mt("h-3.5 w-3.5",!c&&l.tone)}),l.label,e.jsx("span",{className:Mt("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)})]})}class $Zn 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(qs,{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 $Y="deal-pipeline-detail-sheet";function VY(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:s>=1e3?`$${(s/1e3).toFixed(0)}K`:`$${Math.round(s).toLocaleString()}`}function VZn(){var Zn;const s=JG(),{data:t,isLoading:n}=nae(),{data:r,isLoading:a,refetch:i}=rae(),{data:l,isLoading:o}=C$n(),c=xJt(),d=b$n(),[u,h]=j.useState("board"),[m,p]=j.useState(!1),[f,x]=j.useState(!1),[y,v]=j.useState(null),[b,N]=j.useState(null),[S,A]=j.useState(null),[T,L]=j.useState(null),[M,I]=j.useState(!1),[R,z]=j.useState(null),[$,H]=j.useState(""),[V,K]=j.useState("all"),[Z,Q]=j.useState("all"),[le,ue]=j.useState("all"),[se,ne]=j.useState(null),{data:ie}=kts(),{data:ce}=mVn(),[je,be]=j.useState(!1),[he,ge]=j.useState(!1),[ke,Te]=j.useState(new Set),Me=j.useRef(!1),[Oe,Se]=j.useState(null),{data:Qe}=Sj(),{isTeamLeader:Ae,teamMembers:Fe}=uVn(),Ne=j.useMemo(()=>Array.from(ke),[ke]),{data:$e}=hVn(Ne),Ve=j.useMemo(()=>{const es=new Map;return Fe.forEach(ar=>es.set(ar.id,{name:ar.name,avatar_url:ar.avatar_url,color:ar.color})),es},[Fe]),qe=j.useCallback(es=>es.owner_user_id&&Ve.get(es.owner_user_id)||null,[Ve]),Ze=j.useCallback(es=>{Te(ar=>{const Hn=new Set(ar);return Hn.has(es)?Hn.delete(es):Hn.add(es),Hn})},[]);j.useEffect(()=>{!n&&t&&t.length===0&&c.mutate()},[n,t]);const[Ue,Ye]=fc(),Ge=j.useRef(!1);j.useEffect(()=>{const es=Ue.get("deal");if(es&&r&&r.length>0&&!Ge.current){const ar=r.find(Hn=>Hn.id===es);ar&&(Ge.current=!0,v(ar),x(!0),Ue.delete("deal"),Ye(Ue,{replace:!0}))}},[r,Ue]);const He=j.useMemo(()=>{if(!$e||!t)return[];const es=new Map(t.map(ar=>[ar.name,ar.id]));return $e.map(ar=>{const Hn=ar._stage_name&&es.get(ar._stage_name)||null;return{...ar,stage_id:Hn||ar.stage_id}})},[$e,t]),tt=j.useMemo(()=>[...r||[],...He],[r,He]);j.useEffect(()=>{if(Me.current||tt.length===0)return;Me.current=!0;const es=sessionStorage.getItem($Y);if(es)try{const ar=JSON.parse(es);if(!ar.open||!ar.dealId)return;const Hn=tt.find(kn=>kn.id===ar.dealId);Hn&&(v(Hn),x(!0))}catch{sessionStorage.removeItem($Y)}},[tt]),j.useEffect(()=>{f&&(y!=null&&y.id)?sessionStorage.setItem($Y,JSON.stringify({dealId:y.id,open:!0})):sessionStorage.removeItem($Y)},[f,y==null?void 0:y.id]);const pt=j.useMemo(()=>{const es={},ar=new Date;return ar.setHours(0,0,0,0),(ie||[]).forEach(Hn=>{!Hn.deal_id||Hn.status==="done"||!Hn.due_date||Su(Hn.due_date){const es=new Set((t||[]).filter(un=>un.is_won_stage).map(un=>un.id)),ar=new Set((t||[]).filter(un=>un.is_lost_stage).map(un=>un.id)),Hn=new Date;Hn.setHours(0,0,0,0);const kn=new Date(Hn);kn.setDate(kn.getDate()+7);const Un=new Date(Hn);Un.setDate(Un.getDate()-14);const sn={closing_soon:new Set,past_due:new Set,overdue_tasks:new Set,stalled:new Set};return tt.forEach(un=>{if(!(un.stage_id&&(es.has(un.stage_id)||ar.has(un.stage_id)))){if(un.target_close_date){const fs=Su(un.target_close_date);fs[{key:"closing_soon",count:Ut.closing_soon.size},{key:"past_due",count:Ut.past_due.size},{key:"overdue_tasks",count:Ut.overdue_tasks.size},{key:"stalled",count:Ut.stalled.size}],[Ut]),us=tt.filter(es=>{var mt,Nt,Pt,ts,ls,Is;const ar=$.toLowerCase(),Hn=ft[es.id]||[],kn=!ar||es.deal_name.toLowerCase().includes(ar)||((Nt=(mt=es.contact)==null?void 0:mt.first_name)==null?void 0:Nt.toLowerCase().includes(ar))||((ts=(Pt=es.contact)==null?void 0:Pt.last_name)==null?void 0:ts.toLowerCase().includes(ar))||((ls=es.property_address)==null?void 0:ls.toLowerCase().includes(ar))||((Is=es.city)==null?void 0:Is.toLowerCase().includes(ar))||Hn.some(ps=>ps.toLowerCase().includes(ar)),Un=V==="all"||es.deal_type===V,sn=Z==="all"||Hn.includes(Z),un=es.actual_close_date||es.target_close_date||es.contract_date||es.created_at,Ar=un?String(un).slice(0,4):null,fs=le==="all"||Ar===le,ot=!se||Ut[se].has(es.id);return kn&&Un&&sn&&fs&&ot}),zt=j.useMemo(()=>{const es=new Set;return es.add(String(new Date().getFullYear())),tt.forEach(ar=>{const Hn=ar.actual_close_date||ar.target_close_date||ar.contract_date||ar.created_at;Hn&&es.add(String(Hn).slice(0,4))}),Array.from(es).sort((ar,Hn)=>Number(Hn)-Number(ar))},[tt]),bt=j.useMemo(()=>{if(!t)return l||null;const es=new Set(t.filter(un=>un.is_won_stage).map(un=>un.id)),ar=new Set(t.filter(un=>un.is_lost_stage).map(un=>un.id)),Hn=tt.filter(un=>un.stage_id&&!es.has(un.stage_id)&&!ar.has(un.stage_id)),kn=tt.filter(un=>un.stage_id&&es.has(un.stage_id)),Un=new Date().getFullYear(),sn=kn.filter(un=>un.actual_close_date?new Date(un.actual_close_date).getFullYear()===Un:!0);return{totalDeals:tt.length,activeDeals:Hn.length,wonDeals:kn.length,pipelineValue:Hn.reduce((un,Ar)=>un+(Ar.expected_price||0),0),expectedCommission:Hn.reduce((un,Ar)=>un+(Ar.expected_commission||0),0),expectedNetToAgent:Hn.reduce((un,Ar)=>un+(g_(Ar)||0),0),wonValue:kn.reduce((un,Ar)=>un+(Ar.expected_price||0),0),weightedGCI:Hn.reduce((un,Ar)=>un+(Ar.expected_commission||0)*((Ar.probability??50)/100),0),weightedNet:Hn.reduce((un,Ar)=>un+(g_(Ar)||0)*((Ar.probability??50)/100),0),ytdWonDeals:sn.length,ytdWonGCI:sn.reduce((un,Ar)=>un+(Ar.expected_commission||0),0),ytdWonNet:sn.reduce((un,Ar)=>un+(g_(Ar)||0),0),projectedAnnualNet:sn.reduce((un,Ar)=>un+(g_(Ar)||0),0)+Hn.reduce((un,Ar)=>un+(g_(Ar)||0)*((Ar.probability??50)/100),0)}},[tt,t,l]),As=es=>{v(es),x(!0)},vt=es=>{N(es||null),v(null),p(!0)},Ws=es=>{v(es),x(!1),p(!0)},on=es=>{x(es),es||sessionStorage.removeItem($Y)},Ms=(es,ar)=>{A(es)},dn=(es,ar)=>{es.preventDefault(),es.dataTransfer.dropEffect="move",L(ar)},rn=async(es,ar)=>{if(es.preventDefault(),L(null),!S)return;const Hn=r==null?void 0:r.find(sn=>sn.id===S),kn=t==null?void 0:t.find(sn=>sn.id===ar),Un=t==null?void 0:t.find(sn=>sn.id===(Hn==null?void 0:Hn.stage_id));if(!Hn||!kn||Hn.stage_id===ar){A(null);return}Se({dealId:S,dealName:Hn.deal_name,fromStageName:(Un==null?void 0:Un.name)||"Unknown",toStageName:kn.name,toStageId:ar,isWonStage:kn.is_won_stage,deal:Hn}),A(null)},br=async()=>{if(!Oe)return;const{dealId:es,toStageId:ar,toStageName:Hn,isWonStage:kn,deal:Un}=Oe;if(await d.mutateAsync({dealId:es,stageId:ar,stageName:Hn}),re.success(`Moved to ${Hn}`),kn&&!Un.scorecard_transaction_id){const sn={...Un,stage_id:ar};z(sn),I(!0)}},Gn=j.useCallback(async(es,ar,Hn)=>{const kn=r==null?void 0:r.find(un=>un.id===es),Un=t==null?void 0:t.find(un=>un.id===ar),sn=t==null?void 0:t.find(un=>un.id===(kn==null?void 0:kn.stage_id));!kn||!Un||kn.stage_id===ar||Se({dealId:es,dealName:kn.deal_name,fromStageName:(sn==null?void 0:sn.name)||"Unknown",toStageName:Hn,toStageId:ar,isWonStage:Un.is_won_stage,deal:kn})},[r,t]),On=es=>us.filter(ar=>ar.stage_id===es),Rr=n||a,cr=s?"list":u,Hs=[{label:"Active Deals",value:(bt==null?void 0:bt.activeDeals)||0,hint:"Deals still in play"},{label:"Weighted GCI",value:VY((bt==null?void 0:bt.weightedGCI)||0),hint:"GCI adjusted by each deal's win probability"},{label:"Weighted Net",value:VY((bt==null?void 0:bt.weightedNet)||0),hint:"Net to agent adjusted by each deal's win probability"},{label:"YTD Closed Net",value:VY((bt==null?void 0:bt.ytdWonNet)||0),subtitle:`${(bt==null?void 0:bt.ytdWonDeals)||0} deals`,hint:"Net commission from deals closed this year"},{label:"Projected Annual",value:VY((bt==null?void 0:bt.projectedAnnualNet)||0),hint:"YTD closed net + weighted active net"}],_r=[...V!=="all"?[{key:"type",label:`Type: ${V}`,onClear:()=>K("all")}]:[],...le!=="all"?[{key:"year",label:`Year: ${le}`,onClear:()=>ue("all")}]:[],...Z!=="all"?[{key:"tag",label:`Tag: ${Z}`,onClear:()=>Q("all")}]:[],...$?[{key:"search",label:`"${$}"`,onClear:()=>H("")}]:[],...se?[{key:"attention",label:"Needs attention",onClear:()=>ne(null)}]:[]],nn=()=>{H(""),K("all"),Q("all"),ue("all"),ne(null)};return e.jsxs(qs,{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(BZn,{summary:`${(bt==null?void 0:bt.activeDeals)||0} active deals • ${VY((bt==null?void 0:bt.weightedNet)||0)} weighted net`,stats:cr==="portals"?[]:Hs,search:$,onSearchChange:H,onAddDeal:()=>vt(),onRefresh:()=>i(),onTeam:Qe&&!Ae?()=>be(!0):void 0,showSearch:cr!=="portals",activeFilters:_r,onClearAll:nn,resultLabel:_r.length>0?`${us.length} of ${tt.length} deals`:null,viewControls:s?null:e.jsx(wN,{children:e.jsx("div",{className:"hub-glass flex items-center gap-0.5 rounded-full p-1",children:[{mode:"board",icon:Hg,label:"Board",hint:"Kanban board view"},{mode:"list",icon:m0,label:"List",hint:"Grouped list view"},{mode:"table",icon:yq,label:"Table",hint:"Sortable table view"},{mode:"portals",icon:cn,label:"Portals",hint:"Client portal management"}].map(({mode:es,icon:ar,label:Hn,hint:kn})=>e.jsxs(Bg,{children:[e.jsx(Ug,{asChild:!0,children:e.jsxs("button",{onClick:()=>h(es),className:Mt("inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium transition-colors",u===es?"bg-background text-foreground shadow-sm":"opacity-80 hover:opacity-100"),children:[e.jsx(ar,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:Hn})]})}),e.jsx(ng,{children:kn})]},es))})}),filters:cr!=="portals"?e.jsxs(e.Fragment,{children:[e.jsxs(Ns,{value:V,onValueChange:K,children:[e.jsx(ws,{className:"hub-glass h-10 w-[130px] rounded-full border-0 text-sm",children:e.jsx(ks,{placeholder:"All Types"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Types"}),e.jsx(et,{value:"buyer",children:"Buyer"}),e.jsx(et,{value:"seller",children:"Seller"}),e.jsx(et,{value:"dual",children:"Dual"}),e.jsx(et,{value:"referral",children:"Referral"}),e.jsx(et,{value:"lease",children:"Lease"})]})]}),e.jsxs(Ns,{value:le,onValueChange:ue,children:[e.jsx(ws,{className:"hub-glass h-10 w-[110px] rounded-full border-0 text-sm",children:e.jsx(ks,{placeholder:"Year"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Years"}),zt.map(es=>e.jsx(et,{value:es,children:es},es))]})]}),e.jsxs(Ns,{value:Z,onValueChange:Q,children:[e.jsxs(ws,{className:"hub-glass h-10 w-[150px] rounded-full border-0 text-sm",children:[e.jsx(Cf,{className:"mr-1.5 h-3.5 w-3.5 opacity-70"}),e.jsx(ks,{placeholder:"All Tags"})]}),e.jsxs(js,{className:"max-h-[300px]",children:[e.jsx(et,{value:"all",children:"All Tags"}),qt.length===0&&e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No tags yet"}),qt.map(es=>e.jsx(et,{value:es,children:es},es))]})]})]}):null}),cr!=="portals"&&e.jsx(qZn,{items:Wt,active:se,onToggle:es=>ne(ar=>ar===es?null:es)})]}),e.jsxs("div",{className:"flex-1 min-h-0 flex",children:[Ae&&!s&&Fe.length>0&&e.jsx(dVn,{members:Fe,enabledMembers:ke,onToggleMember:Ze,isOpen:he,onToggleOpen:()=>ge(es=>!es)}),e.jsx("div",{className:"flex-1 min-w-0 min-h-0 p-4 md:p-6 pt-4",children:Rr?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(es=>e.jsx("div",{className:"min-w-[280px] max-w-[320px] flex-shrink-0",children:e.jsx(xn,{className:"h-full rounded-xl"})},es))}):cr==="board"?e.jsxs(Gi,{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(es=>e.jsx(gVn,{stage:es,deals:On(es.id),onDealClick:As,onAddDeal:vt,onDragStart:Ms,onDragOver:dn,onDrop:rn,isDragOver:T===es.id,isWonStage:es.is_won_stage,getOwnerInfo:qe,tagsByDeal:ft,overdueTasksByDeal:pt},es.id))}),e.jsx(Vne,{orientation:"horizontal"})]}):cr==="table"?e.jsx(Gi,{className:"h-full",children:e.jsx(jZn,{deals:us,stages:t||[],onDealClick:As,onStageChange:Gn})}):cr==="portals"?e.jsx(Cts,{}):e.jsx(Gi,{className:"h-full",children:e.jsxs("div",{className:"space-y-6",children:[t==null?void 0:t.map(es=>{const ar=On(es.id);return ar.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:es.color}}),e.jsx("h3",{className:"font-semibold",children:es.name}),e.jsxs("span",{className:"text-muted-foreground text-sm",children:["(",ar.length,")"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:ar.map(Hn=>e.jsx(NJt,{deal:Hn,onClick:()=>As(Hn),stages:t,onStageChange:Gn,showStagePicker:!0,isWonStage:es.is_won_stage,ownerInfo:qe(Hn),tags:ft[Hn.id]||[],overdueTaskCount:pt[Hn.id]||0},Hn.id))})]},es.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(Hg,{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(U,{onClick:()=>vt(),children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Add Your First Deal"]})]}),((r==null?void 0:r.length)||0)>0&&us.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(Fr,{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(U,{variant:"outline",onClick:nn,children:"Clear Filters"})]})]})})})]})]}),e.jsx(bVn,{open:m,onOpenChange:p,deal:y,defaultStageId:b}),e.jsx(bZn,{deal:y,open:f,onOpenChange:on,onEdit:Ws,isWonStage:y?(Zn=t==null?void 0:t.find(es=>es.id===y.stage_id))==null?void 0:Zn.is_won_stage:!1,onAddToScorecard:es=>{z(es),I(!0),x(!1)}}),e.jsx(_Zn,{open:M,onOpenChange:I,deal:R,onComplete:()=>{i(),z(null)}}),Oe&&e.jsx(IZn,{open:!!Oe,onOpenChange:es=>{es||Se(null)},dealId:Oe.dealId,dealName:Oe.dealName,fromStageName:Oe.fromStageName,toStageName:Oe.toStageName,toStageId:Oe.toStageId,onConfirm:br}),e.jsx(lVn,{open:je,onOpenChange:be})]})}function HZn(){return e.jsx($Zn,{children:e.jsx(VZn,{})})}function _Te({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,p]=j.useState(""),[f,x]=j.useState("other"),[y,v]=j.useState(!1),b=EYn(),N=()=>{d(null),h(""),p(""),x("other"),v(!1),o.current&&(o.current.value="")},S=T=>{if(T){if(T.type!=="application/pdf"&&!T.name.toLowerCase().endsWith(".pdf")){re.error("Only PDF files can be uploaded.");return}if(T.size>fts){re.error("That PDF is larger than the 20MB limit.");return}d(T),!u&&!l&&h(T.name.replace(/\.pdf$/i,""))}},A=async()=>{if(c)try{const T=await b.mutateAsync({name:u.trim()||c.name.replace(/\.pdf$/i,""),description:m,category:f,file:c,templateId:n,brokerageId:a});re.success(T.version.has_acroform?`Found ${T.version.detected_fields.length} fillable fields — map them next.`:"Uploaded. This PDF has no fillable fields yet."),i==null||i(T.templateId,T.version.id),N(),t(!1)}catch(T){re.error((T==null?void 0:T.message)||"Upload failed")}};return e.jsx(zs,{open:s,onOpenChange:T=>{T||N(),t(T)},children:e.jsxs(Ds,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{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:T=>{var L;return S((L=T.target.files)==null?void 0:L[0])}}),e.jsx("button",{type:"button",onClick:()=>{var T;return(T=o.current)==null?void 0:T.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(Ur,{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:urt(c.size)})]})]}):e.jsxs("div",{className:"flex flex-col items-center gap-2 text-muted-foreground",children:[e.jsx(qa,{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(te,{htmlFor:"tpl-name",children:"Template name"}),e.jsx(xe,{id:"tpl-name",value:u,onChange:T=>h(T.target.value),placeholder:"Residential Purchase Agreement"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(te,{children:"Category"}),e.jsxs(Ns,{value:f,onValueChange:T=>x(T),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:lrt.map(T=>e.jsx(et,{value:T.value,children:T.label},T.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"tpl-desc",children:"Description (optional)"}),e.jsx(Fs,{id:"tpl-desc",rows:2,value:m,onChange:T=>p(T.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(xi,{checked:y,onCheckedChange:T=>v(!!T),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(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{onClick:A,disabled:!c||!y||b.isPending,children:[b.isPending&&e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}),b.isPending?"Reading PDF…":"Upload"]})]})]})})}function kKe(s){return s.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[^a-zA-Z0-9]+/g," ").toLowerCase().trim()}function jSt(s){return kKe(s).split(" ").filter(Boolean)}function GZn(s,t,n){const r=kKe(s),a=new Set(jSt(s));let i=0;const l=[t,...n];for(const o of l){const c=kKe(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=jSt(o),u=d.filter(h=>a.has(h)).length;u>0&&(i=Math.max(i,Math.round(u/d.length*45)))}return i}function WZn(s){if(!s)return null;let t=null;for(const n of HH){const r=GZn(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 KZn=["Deal","Contact","Agent","Other"],cze="__blank__",dze="__static__";function Ats({version:s}){const{data:t,isLoading:n}=GIe(s.id),r=FYn(),[a,i]=j.useState([]),[l,o]=j.useState("");j.useEffect(()=>{if(n)return;const p=new Map((t||[]).map(f=>[f.pdf_field_name||"",f]));i((s.detected_fields||[]).map(f=>{const x=p.get(f.name),y=WZn(f.name);return{pdf_field_name:f.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 p=l.toLowerCase();return a.filter(f=>(f.pdf_field_name||"").toLowerCase().includes(p))},[a,l]),d=a.filter(p=>p.merge_key||p.mapping_mode==="static"&&p.static_value).length,u=(p,f)=>{i(x=>x.map(y=>y.pdf_field_name===p?{...y,...f}:y))},h=()=>{let p=0;i(f=>f.map(x=>x.merge_key||!x.suggested?x:(p+=1,{...x,mapping_mode:"acroform",merge_key:x.suggested}))),re.success(p?`Applied ${p} suggestion${p===1?"":"s"}`:"No new suggestions to apply")},m=async()=>{try{await r.mutateAsync({versionId:s.id,hasAcroform:s.has_acroform,mappings:a.map(({suggested:p,...f})=>f)}),re.success("Field mapping saved")}catch(p){re.error((p==null?void 0:p.message)||"Could not save the mapping")}};return s.has_acroform?n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(Et,{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(U,{variant:"outline",size:"sm",onClick:h,children:[e.jsx(cn,{className:"mr-1.5 h-4 w-4"})," Apply suggestions"]}),e.jsxs(U,{size:"sm",onClick:m,disabled:r.isPending,children:[r.isPending?e.jsx(Et,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Ho,{className:"mr-1.5 h-4 w-4"}),"Save mapping"]})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{className:"pl-9",placeholder:"Search fields…",value:l,onChange:p=>o(p.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[c.map(p=>{var x;const f=p.mapping_mode==="static"?dze:p.merge_key?p.merge_key:cze;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:p.pdf_field_name}),p.suggested&&!p.merge_key&&e.jsxs(Be,{variant:"secondary",className:"mt-1 text-[10px]",children:["Suggested: ",(x=HH.find(y=>y.key===p.suggested))==null?void 0:x.label]})]}),e.jsxs("div",{className:"flex w-full gap-2 sm:w-[420px]",children:[e.jsxs(Ns,{value:f,onValueChange:y=>{y===cze?u(p.pdf_field_name,{mapping_mode:"blank",merge_key:null,static_value:null}):y===dze?u(p.pdf_field_name,{mapping_mode:"static",merge_key:null}):u(p.pdf_field_name,{mapping_mode:"acroform",merge_key:y,static_value:null})},children:[e.jsx(ws,{className:"flex-1",children:e.jsx(ks,{placeholder:"Leave blank"})}),e.jsxs(js,{className:"max-h-[320px]",children:[e.jsx(et,{value:cze,children:"Leave blank"}),e.jsx(et,{value:dze,children:"Fixed text…"}),KZn.map(y=>e.jsxs(USs,{children:[e.jsx(IIt,{children:y}),HH.filter(v=>v.group===y).map(v=>e.jsx(et,{value:v.key,children:v.label},v.key))]},y))]})]}),p.mapping_mode==="static"&&e.jsx(xe,{className:"flex-1",placeholder:"Fixed text",value:p.static_value||"",onChange:y=>u(p.pdf_field_name,{static_value:y.target.value})})]})]},p.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(we,{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."})]})})}Snt.workerSrc=Cnt;const X4e={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"}},uze=["signature","initials","date_signed","printed_name","text"],NSt=12,YZn={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"},Tce=s=>Math.min(1,Math.max(0,s));function Ets({version:s,templateName:t,open:n,onOpenChange:r}){const a=Qt(),{data:i=[],isLoading:l}=GIe(n?s.id:void 0),[o,c]=j.useState(null),[d,u]=j.useState(null),[h,m]=j.useState([]),[p,f]=j.useState("select"),[x,y]=j.useState(null),[v,b]=j.useState(!1),[N,S]=j.useState(!1),A=j.useRef(null),T=j.useRef([]),L=j.useRef(null),M=Math.min(s.page_count||1,NSt);j.useEffect(()=>{if(!n)return;let Q=!1;return c(null),u(null),drt(s.storage_path).then(le=>{Q||c(new Blob([le],{type:"application/pdf"}))}).catch(()=>!Q&&u("Could not load the template PDF.")),()=>{Q=!0}},[n,s.storage_path]),j.useEffect(()=>{let Q=!1;const le=A.current;return!o||!le?void 0:((async()=>{try{const se=await o.arrayBuffer(),ne=await rTe({data:se}).promise;if(Q)return;le.innerHTML="",T.current=[];const ie=Math.min(le.clientWidth-32||720,860);for(let ce=1;ce<=ne.numPages;ce++){const je=await ne.getPage(ce);if(Q)return;const be=je.getViewport({scale:1}),he=ie/be.width,ge=je.getViewport({scale:he*(window.devicePixelRatio||1)}),ke=document.createElement("div");ke.className="relative mx-auto shadow-sm",ke.style.width=`${ie}px`,ke.style.height=`${be.height*he}px`,ke.dataset.pageIndex=String(ce-1);const Te=document.createElement("canvas");Te.width=Math.floor(ge.width),Te.height=Math.floor(ge.height),Te.style.width="100%",Te.style.height="100%",Te.className="rounded-md border border-border bg-white",ke.appendChild(Te),le.appendChild(ke),T.current[ce-1]=ke;const Me=Te.getContext("2d");Me&&await je.render({canvasContext:Me,viewport:ge}).promise}Q||m(ce=>[...ce])}catch(se){Q||u((se==null?void 0:se.message)||"Could not render the PDF")}})(),()=>{Q=!0})},[o]),j.useEffect(()=>{if(!n||l)return;const Q=i.filter(le=>le.field_kind!=="data"||le.mapping_mode==="overlay").filter(le=>le.pos_x!=null&&le.pos_y!=null).map(le=>({key:le.id,page_index:le.page_index??0,x:Number(le.pos_x),y:Number(le.pos_y),w:Number(le.width??.2),h:Number(le.height??.03),field_kind:le.field_kind||"data",merge_key:le.merge_key,static_value:le.static_value,signer_role:le.signer_role,label:le.label,is_required:le.is_required??!0,font_size:le.font_size,source:le.source||"manual"}));m(Q),y(null)},[n,l,i]),j.useEffect(()=>{const Q=ue=>{const se=L.current;if(!se)return;const ne=(ue.clientX-se.startX)/se.pageW,ie=(ue.clientY-se.startY)/se.pageH;m(ce=>ce.map(je=>je.key!==se.key?je:se.mode==="move"?{...je,x:Tce(Math.min(se.orig.x+ne,1-je.w)),y:Tce(Math.min(se.orig.y+ie,1-je.h))}:{...je,w:Math.min(Math.max(.04,se.orig.w+ne),1-je.x),h:Math.min(Math.max(.015,se.orig.h+ie),1-je.y)}))},le=()=>{L.current=null};return window.addEventListener("pointermove",Q),window.addEventListener("pointerup",le),()=>{window.removeEventListener("pointermove",Q),window.removeEventListener("pointerup",le)}},[]);const I=(Q,le,ue)=>{Q.stopPropagation(),Q.preventDefault();const se=T.current[le.page_index];if(!se)return;const ne=se.getBoundingClientRect();L.current={key:le.key,mode:ue,startX:Q.clientX,startY:Q.clientY,orig:le,pageW:ne.width,pageH:ne.height},y(le.key)},R=(Q,le)=>{if(p==="select"){y(null);return}const ue=T.current[le];if(!ue)return;const se=ue.getBoundingClientRect(),ne=X4e[p],ie=Tce((Q.clientX-se.left)/se.width-ne.w/2),ce=Tce((Q.clientY-se.top)/se.height-ne.h/2),je={key:crypto.randomUUID(),page_index:le,x:Math.min(ie,1-ne.w),y:Math.min(ce,1-ne.h),w:ne.w,h:ne.h,field_kind:p,merge_key:null,static_value:null,signer_role:uze.includes(p)?"buyer_1":null,label:null,is_required:!0,font_size:null};m(be=>[...be,je]),y(je.key),f("select")},z=h.find(Q=>Q.key===x)||null,$=Q=>{z&&m(le=>le.map(ue=>ue.key===z.key?{...ue,...Q}:ue))},H=async(Q=!1)=>{if(o){S(!0);try{const le=await o.arrayBuffer(),ue=await rTe({data:le}).promise,se=Math.min(ue.numPages,NSt),ne=[];for(let he=1;he<=se;he++){const ge=await ue.getPage(he),ke=ge.getViewport({scale:1}),Te=ge.getViewport({scale:Math.min(1e3/ke.width,1.6)}),Me=document.createElement("canvas");Me.width=Math.floor(Te.width),Me.height=Math.floor(Te.height);const Oe=Me.getContext("2d");Oe&&(Oe.fillStyle="#ffffff",Oe.fillRect(0,0,Me.width,Me.height),await ge.render({canvasContext:Oe,viewport:Te}).promise,ne.push({index:he-1,image:Me.toDataURL("image/jpeg",.7)}))}const{data:ie,error:ce}=await q.functions.invoke("forms-autoplace",{body:{version_id:s.id,pages:ne,force:Q}});if(ce)throw new Error(ce.message||"The field scan failed.");if(ie!=null&&ie.error)throw new Error(ie.error);const je=(ie==null?void 0:ie.fields)||[];if(!je.length){re.info("The scan did not find any blank fields on this form. Place them manually below.");return}const be=je.map(he=>({key:crypto.randomUUID(),page_index:he.page_index,x:he.x,y:he.y,w:he.w,h:he.h,field_kind:he.field_kind,merge_key:null,static_value:null,signer_role:he.signer_role||"buyer_1",label:he.label,is_required:!0,font_size:null,source:"ai"}));m(he=>[...he,...be]),y(null),re.success(`${be.length} field${be.length===1?"":"s"} placed${ie!=null&&ie.cached?" (from the earlier scan)":""}. Review, nudge, then save.`)}catch(le){re.error((le==null?void 0:le.message)||"Could not scan this document. You can still place fields manually.")}finally{S(!1)}}},V=async()=>{const Q=h.filter(le=>uze.includes(le.field_kind));for(const le of Q)if(!le.signer_role){re.error("Every signer field needs a role (Buyer 1, Seller 1, Agent…)");return}b(!0);try{const{error:le}=await q.from("form_field_mappings").delete().eq("version_id",s.id).or("field_kind.neq.data,mapping_mode.eq.overlay");if(le)throw le;const ue=h.map((ce,je)=>({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:uze.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:je}));if(ue.length){const{error:ce}=await q.from("form_field_mappings").insert(ue);if(ce)throw ce}const ne=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"))||Q.length?"mapped":s.has_acroform?"needs_mapping":"needs_placement",{error:ie}=await q.from("form_template_versions").update({mapping_status:ne}).eq("id",s.id);if(ie)throw ie;re.success("Placement saved"),a.invalidateQueries({queryKey:["form-field-mappings",s.id]}),a.invalidateQueries({queryKey:["form-templates"]}),r(!1)}catch(le){re.error((le==null?void 0:le.message)||"Could not save placement")}finally{b(!1)}},K=[{tool:"select",label:"Select",icon:JX},{tool:"data",label:"Merge field",icon:FT},{tool:"signature",label:"Signature",icon:Pg},{tool:"initials",label:"Initials",icon:wq},{tool:"date_signed",label:"Date signed",icon:nc},{tool:"printed_name",label:"Printed name",icon:So},{tool:"text",label:"Text input",icon:_q}],Z=s.page_count||1;return e.jsx(zs,{open:n,onOpenChange:r,children:e.jsxs(Ds,{className:"flex h-[94vh] max-w-6xl flex-col overflow-hidden p-0",children:[e.jsxs(Vs,{className:"border-b px-5 py-3 text-left",children:[e.jsxs($s,{className:"text-base",children:["Place fields — ",t," (v",s.version_number,")"]}),e.jsx("p",{className:"text-xs font-normal text-muted-foreground",children:"Pick a field type on the left, then click on the document where it belongs. Drag to move, pull the corner to resize."})]}),e.jsxs("div",{className:"flex min-h-0 flex-1",children:[e.jsxs("div",{className:"w-36 shrink-0 space-y-1 overflow-y-auto border-r p-3 sm:w-44",children:[e.jsxs(U,{size:"sm",variant:"secondary",className:"mb-2 h-auto w-full flex-col items-start gap-0.5 py-2 text-left",disabled:N||!o,onClick:()=>H(!!s.autoplace_ran_at),children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs font-semibold",children:[N?e.jsx(Et,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(cn,{className:"h-3.5 w-3.5"}),N?"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 ${M} page${M===1?"":"s"}`})]}),K.map(Q=>e.jsxs("button",{onClick:()=>f(Q.tool),className:`flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-xs font-medium transition-colors ${p===Q.tool?"bg-primary text-primary-foreground":"hover:bg-muted"}`,children:[e.jsx(Q.icon,{className:"h-3.5 w-3.5 shrink-0"}),Q.label]},Q.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(Et,{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:Q=>{const le=Q.target.closest("[data-page-index]");le&&R(Q,Number(le.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:z?X4e[z.field_kind].label:"Field settings"}),e.jsx(Gi,{className:"flex-1 p-4",children:z?e.jsxs("div",{className:"space-y-4",children:[z.field_kind==="data"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Merge value"}),e.jsxs(Ns,{value:z.merge_key||"",onValueChange:Q=>$({merge_key:Q||null,static_value:null}),children:[e.jsx(ws,{className:"h-8 text-xs",children:e.jsx(ks,{placeholder:"Choose data…"})}),e.jsx(js,{children:["Deal","Contact","Agent","Other"].map(Q=>e.jsxs("div",{children:[e.jsx("div",{className:"px-2 py-1 text-[10px] font-semibold uppercase text-muted-foreground",children:Q}),HH.filter(le=>le.group===Q).map(le=>e.jsx(et,{value:le.key,className:"text-xs",children:le.label},le.key))]},Q))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"…or fixed text"}),e.jsx(xe,{className:"h-8 text-xs",placeholder:"Printed exactly as typed",value:z.merge_key?"":z.static_value||"",disabled:!!z.merge_key,onChange:Q=>$({static_value:Q.target.value||null})})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Who signs this?"}),e.jsxs(Ns,{value:z.signer_role||"",onValueChange:Q=>$({signer_role:Q}),children:[e.jsx(ws,{className:"h-8 text-xs",children:e.jsx(ks,{placeholder:"Choose signer…"})}),e.jsx(js,{children:hrt.map(Q=>e.jsx(et,{value:Q.value,className:"text-xs",children:Q.label},Q.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Label shown to signer"}),e.jsx(xe,{className:"h-8 text-xs",placeholder:X4e[z.field_kind].label,value:z.label||"",onChange:Q=>$({label:Q.target.value||null})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{className:"text-xs",children:"Required"}),e.jsx(wn,{checked:z.is_required,onCheckedChange:Q=>$({is_required:Q})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Font size (optional)"}),e.jsx(xe,{className:"h-8 text-xs",type:"number",min:6,max:24,value:z.font_size??"",onChange:Q=>$({font_size:Q.target.value?Number(Q.target.value):null})})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[z.page_index+1{const Q={...z,key:crypto.randomUUID(),page_index:z.page_index+1};m(le=>[...le,Q]),y(Q.key)},children:[e.jsx(Pa,{className:"mr-1 h-3 w-3"})," Next page"]}),e.jsxs(U,{variant:"outline",size:"sm",className:"h-8 flex-1 text-xs text-destructive",onClick:()=>{m(Q=>Q.filter(le=>le.key!==z.key)),y(null)},children:[e.jsx(In,{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(U,{className:"w-full",onClick:V,disabled:v,children:[v?e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ho,{className:"mr-2 h-4 w-4"}),"Save placement"]})})]})]}),e.jsx(ZZn,{boxes:h,pageRefs:T,selectedKey:x,onSelect:y,onDragStart:I})]})})}function ZZn({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(XZn,{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":YZn[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=HH.find(d=>d.key===l.merge_key))==null?void 0:c.label)||l.merge_key:l.static_value||"Data":`${l.label||X4e[l.field_kind].label} · ${mrt(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 XZn({target:s,children:t}){return tv.createPortal(t,s)}function QZn({templates:s}){const{data:t=[],isLoading:n}=_ts(),r=HYn(),a=GYn(),[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 p=s.filter(v=>{var b;return((b=gx(v))==null?void 0:b.mapping_status)==="mapped"}),f=v=>m(b=>b.includes(v)?b.filter(N=>N!==v):[...b,v]),x=(v,b)=>m(N=>{const S=[...N],A=v+b;return A<0||A>=S.length?N:([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(L4,{className:"h-4 w-4 text-primary"})," Form packets"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Bundle the forms you always send together. Signers sign the whole packet in one session."})]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>l("new"),disabled:p.length===0,children:[e.jsx(an,{className:"mr-2 h-4 w-4"})," New packet"]})]}),n?e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(Et,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):t.length===0?e.jsx(we,{className:"border-dashed",children:e.jsx(Ie,{className:"p-6 text-center text-sm text-muted-foreground",children:p.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=prt(v,s);return e.jsx(we,{children:e.jsxs(Ie,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(L4,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate font-medium",children:v.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.length," form",b.length===1?"":"s"]})]})]}),e.jsx("ol",{className:"ml-4 list-decimal space-y-0.5 text-xs text-muted-foreground",children:b.map(N=>e.jsx("li",{className:"truncate",children:N.name},N.id))}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Be,{variant:"outline",className:"text-[10px]",children:"Send from any deal"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(U,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>l(v),children:[e.jsx(ri,{className:"mr-1 h-3 w-3"})," Edit"]}),e.jsx(U,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:async()=>{await Yi(`Delete the "${v.name}" packet? The forms themselves are kept.`)&&(await a.mutateAsync(v.id),re.success("Packet deleted"))},children:e.jsx(In,{className:"h-3 w-3"})})]})]})]})},v.id)})}),e.jsx(zs,{open:!!i,onOpenChange:v=>!v&&l(null),children:e.jsxs(Ds,{className:"flex max-h-[88vh] max-w-lg flex-col overflow-hidden",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{className:"text-xs",children:"Packet name"}),e.jsx(xe,{value:o,onChange:v=>c(v.target.value),placeholder:"New Buyer Packet"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Description (optional)"}),e.jsx(Fs,{rows:2,value:d,onChange:v=>u(v.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Forms in this packet"}),e.jsx(Gi,{className:"max-h-56 rounded-lg border",children:e.jsx("div",{className:"divide-y",children:p.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(xi,{checked:h.includes(v.id),onCheckedChange:()=>f(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(te,{className:"text-xs",children:"Signing order"}),e.jsx("div",{className:"space-y-1 rounded-lg border p-2",children:h.map((v,b)=>{const N=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:(N==null?void 0:N.name)||"Removed template"}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>x(b,-1),children:e.jsx(cp,{className:"h-3 w-3"})}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>x(b,1),children:e.jsx(ag,{className:"h-3 w-3"})})]},v)})})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>l(null),children:"Cancel"}),e.jsxs(U,{onClick:y,disabled:r.isPending,children:[r.isPending&&e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}),"Save packet"]})]})]})})]})}function JZn({status:s}){return s==="mapped"?e.jsx(Be,{className:"bg-emerald-500/15 text-emerald-600 hover:bg-emerald-500/15",children:"Ready"}):s==="needs_placement"?e.jsx(Be,{variant:"outline",children:"Needs field placement"}):e.jsx(Be,{variant:"secondary",children:"Needs mapping"})}function eXn(){var K,Z;const{data:s=[],isLoading:t,error:n}=crt(),{data:r=[]}=rae(),a=gts(),i=xts(),l=TYn(),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(null),[p,f]=j.useState(""),[x,y]=j.useState(null),[v,b]=j.useState(""),[N,S]=j.useState(null),[A,T]=j.useState("generate"),[L,M]=j.useState("all"),I=s.some(Q=>Q.scope==="brokerage"),R=s.filter(Q=>Q.name.toLowerCase().includes(p.trim().toLowerCase())).filter(Q=>L==="all"||(Q.scope||"mine")===L).sort((Q,le)=>(Q.scope==="brokerage"?1:0)-(le.scope==="brokerage"?1:0)),z=async Q=>{try{await l.mutateAsync(Q),re.success(`"${Q.name}" copied to your forms`)}catch(le){re.error((le==null?void 0:le.message)||"Could not copy that form")}},$=h?s.find(Q=>Q.id===h.id)||h:null,H=gx($),V=async Q=>{if(await Yi(`Delete "${Q.name}" and all of its versions? Forms already generated stay on their deals.`))try{await i.mutateAsync(Q),(h==null?void 0:h.id)===Q.id&&m(null),re.success("Template deleted")}catch(le){re.error((le==null?void 0:le.message)||"Could not delete the template")}};return e.jsxs(qs,{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(U,{onClick:()=>c(!0),children:[e.jsx(an,{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(Fr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{className:"pl-9",placeholder:"Search templates…",value:p,onChange:Q=>f(Q.target.value)})]}),I&&e.jsx("div",{className:"flex gap-1 rounded-lg border p-1",children:[["all","All"],["mine","My forms"],["brokerage","Brokerage forms"]].map(([Q,le])=>e.jsx(U,{size:"sm",variant:L===Q?"secondary":"ghost",className:"h-7 text-xs",onClick:()=>M(Q),children:le},Q))})]}),t&&e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Et,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),n&&e.jsx(we,{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(we,{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(Ur,{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(U,{onClick:()=>c(!0),children:[e.jsx(qa,{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:[R.map(Q=>{var se;const le=gx(Q),ue=Q.scope==="brokerage";return e.jsx(we,{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(Ur,{className:"h-5 w-5 text-primary"})}),e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>m(Q),children:[e.jsx("p",{className:"truncate font-medium",children:Q.name}),ue&&e.jsxs(Be,{variant:"outline",className:"mt-1 gap-1 text-[10px]",children:[e.jsx(_i,{className:"h-3 w-3"})," Brokerage form"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(se=lrt.find(ne=>ne.value===Q.category))==null?void 0:se.label," · v",(le==null?void 0:le.version_number)??1,le?` · ${le.page_count} page${le.page_count===1?"":"s"}`:""]})]}),e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(ey,{className:"h-4 w-4"})})}),e.jsx(Eu,{align:"end",children:ue?e.jsxs(e.Fragment,{children:[e.jsx(La,{onClick:()=>m(Q),children:"View details"}),e.jsxs(La,{disabled:l.isPending,onClick:()=>z(Q),children:[e.jsx(Pa,{className:"mr-2 h-4 w-4"})," Copy to my forms"]})]}):e.jsxs(e.Fragment,{children:[e.jsx(La,{onClick:()=>m(Q),children:"Open & map fields"}),e.jsxs(La,{onClick:()=>S(Q),children:[e.jsx(Hg,{className:"mr-2 h-4 w-4"})," Place fields & signatures"]}),e.jsxs(La,{disabled:(le==null?void 0:le.mapping_status)!=="mapped",onClick:()=>{T("sign"),y(Q),b("")},children:[e.jsx(Pg,{className:"mr-2 h-4 w-4"})," Send for signature"]}),e.jsxs(La,{onClick:()=>u(Q),children:[e.jsx(qa,{className:"mr-2 h-4 w-4"})," Upload new version"]}),e.jsxs(La,{onClick:()=>a.mutate({id:Q.id,patch:{is_archived:!0}}),children:[e.jsx(n1,{className:"mr-2 h-4 w-4"})," Archive"]}),e.jsxs(La,{className:"text-destructive",onClick:()=>V(Q),children:[e.jsx(In,{className:"mr-2 h-4 w-4"})," Delete"]})]})})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(JZn,{status:le==null?void 0:le.mapping_status}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(U,{variant:"ghost",size:"sm",disabled:(le==null?void 0:le.mapping_status)!=="mapped",onClick:()=>{T("sign"),y(Q),b("")},children:[e.jsx(Pg,{className:"mr-1.5 h-4 w-4"})," Sign"]}),e.jsxs(U,{variant:"ghost",size:"sm",disabled:(le==null?void 0:le.mapping_status)!=="mapped",onClick:()=>{T("generate"),y(Q),b("")},children:[e.jsx(YU,{className:"mr-1.5 h-4 w-4"})," Use"]})]})]})]})},Q.id)}),R.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(QZn,{templates:s})})]}),e.jsx(my,{open:!!$,onOpenChange:Q=>!Q&&m(null),children:e.jsxs(g0,{side:"right",className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(vv,{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(Aa,{className:"h-3 w-3"})," Back"]}),e.jsx(bv,{children:$==null?void 0:$.name}),H&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["v",H.version_number," · ",H.file_name," · ",urt(H.file_size)," · uploaded ",Gs(new Date(H.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"mt-5 space-y-4",children:[($==null?void 0:$.description)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:$.description}),H?e.jsx(e.Fragment,{children:($==null?void 0:$.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(_i,{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(U,{variant:"outline",className:"mt-3 w-full",disabled:l.isPending,onClick:()=>$&&z($),children:[e.jsx(Pa,{className:"mr-2 h-4 w-4"})," Copy to my forms"]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(U,{variant:"outline",className:"w-full",onClick:()=>$&&S($),children:[e.jsx(Hg,{className:"mr-2 h-4 w-4"})," Place fields & signatures on the document"]}),e.jsx(Ats,{version:H})]})}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"This template has no uploaded version yet."})]})]})}),e.jsx(_Te,{open:o,onOpenChange:c}),e.jsx(_Te,{open:!!d,onOpenChange:Q=>!Q&&u(null),templateId:d==null?void 0:d.id,templateName:d==null?void 0:d.name}),e.jsx(my,{open:!!x&&!v,onOpenChange:Q=>!Q&&y(null),children:e.jsxs(g0,{side:"bottom",className:"space-y-4",children:[e.jsx(vv,{className:"text-left",children:e.jsx(bv,{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(Ns,{value:v,onValueChange:b,children:[e.jsx(ws,{className:"max-w-md",children:e.jsx(ks,{placeholder:"Select a deal"})}),e.jsx(js,{children:r.map(Q=>e.jsx(et,{value:Q.id,children:Q.deal_name},Q.id))})]})]})}),x&&v&&A==="generate"&&e.jsx(vts,{open:!0,onOpenChange:Q=>{Q||(y(null),b(""))},dealId:v,dealName:(K=r.find(Q=>Q.id===v))==null?void 0:K.deal_name,initialTemplateId:x.id}),x&&v&&A==="sign"&&e.jsx(wts,{open:!0,onOpenChange:Q=>{Q||(y(null),b(""))},dealId:v,dealName:(Z=r.find(Q=>Q.id===v))==null?void 0:Z.deal_name,initialTemplateId:x.id}),N&&gx(N)&&e.jsx(Ets,{open:!0,onOpenChange:Q=>!Q&&S(null),version:gx(N),templateName:N.name})]})}function Tts({open:s,onOpenChange:t,editTask:n,defaultDealId:r,defaultStageId:a}){var H;const i=kZn(),l=SZn(),{data:o}=rae(),c=Sa(),{data:d}=ct({queryKey:["contacts-for-tasks",c],queryFn:async()=>{if(!c)return[];const{data:V,error:K}=await q.from("innercircle_contacts").select("id, first_name, last_name").eq("owner_user_id",c).order("first_name").limit(500);if(K)throw K;return V},enabled:!!c&&s}),[u,h]=j.useState(""),[m,p]=j.useState(""),[f,x]=j.useState("none"),[y,v]=j.useState("none"),[b,N]=j.useState("medium"),[S,A]=j.useState("todo"),[T,L]=j.useState(),[M,I]=j.useState(!1),[R,z]=j.useState(!1);j.useEffect(()=>{n?(h(n.title),p(n.description||""),x(n.deal_id||"none"),v(n.contact_id||"none"),N(n.priority),A(n.status),L(n.due_date?ty(n.due_date):void 0)):(h(""),p(""),x(r||"none"),v("none"),N("medium"),A("todo"),L(void 0))},[n,s,r]);const $=async()=>{if(!u.trim()){re.error("Task title is required");return}try{const V={title:u.trim(),description:m.trim()||null,deal_id:f==="none"?null:f,contact_id:y==="none"?null:y,stage_id:a||null,priority:b,status:S,due_date:T?Gs(T,"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(Ds,{className:"sm:max-w-[480px]",children:[e.jsx(Vs,{children:e.jsx($s,{children:n?"Edit Task":"New Task"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Title *"}),e.jsx(xe,{value:u,onChange:V=>h(V.target.value),placeholder:"e.g., Send inspection report"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Description"}),e.jsx(Fs,{value:m,onChange:V=>p(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(te,{children:"Priority"}),e.jsxs(Ns,{value:b,onValueChange:V=>N(V),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"low",children:"🟢 Low"}),e.jsx(et,{value:"medium",children:"🟡 Medium"}),e.jsx(et,{value:"high",children:"🟠 High"}),e.jsx(et,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Status"}),e.jsxs(Ns,{value:S,onValueChange:V=>A(V),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"todo",children:"To Do"}),e.jsx(et,{value:"in_progress",children:"In Progress"}),e.jsx(et,{value:"done",children:"Done"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Due Date"}),e.jsxs(md,{children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{variant:"outline",className:Mt("w-full justify-start text-left font-normal",!T&&"text-muted-foreground"),children:[e.jsx(pa,{className:"mr-2 h-4 w-4"}),T?Gs(T,"PPP"):"Pick a date"]})}),e.jsx(id,{className:"w-auto p-0",align:"start",children:e.jsx(yj,{mode:"single",selected:T,onSelect:L,initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Link to Deal"}),e.jsxs(md,{open:M,onOpenChange:I,children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{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(_i,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),f!=="none"?((H=o==null?void 0:o.find(V=>V.id===f))==null?void 0:H.deal_name)||"Select deal":"No Deal"]}),e.jsx(Jw,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(id,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(pj,{children:[e.jsx(fj,{placeholder:"Search deals..."}),e.jsxs(gj,{children:[e.jsx(xj,{children:"No deals found."}),e.jsxs(I_,{children:[e.jsxs(e1,{value:"no-deal",onSelect:()=>{x("none"),I(!1)},children:[e.jsx(Xr,{className:Mt("mr-2 h-4 w-4",f==="none"?"opacity-100":"opacity-0")}),"No Deal"]}),o==null?void 0:o.map(V=>e.jsxs(e1,{value:V.deal_name,onSelect:()=>{x(V.id),I(!1)},children:[e.jsx(Xr,{className:Mt("mr-2 h-4 w-4",f===V.id?"opacity-100":"opacity-0")}),V.deal_name]},V.id))]})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Link to Contact"}),e.jsxs(md,{open:R,onOpenChange:z,children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{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(So,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),y!=="none"?(()=>{const V=d==null?void 0:d.find(K=>K.id===y);return V?`${V.first_name} ${V.last_name}`:"Select contact"})():"No Contact"]}),e.jsx(Jw,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(id,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(pj,{children:[e.jsx(fj,{placeholder:"Search contacts..."}),e.jsxs(gj,{children:[e.jsx(xj,{children:"No contacts found."}),e.jsxs(I_,{children:[e.jsxs(e1,{value:"no-contact",onSelect:()=>{v("none"),z(!1)},children:[e.jsx(Xr,{className:Mt("mr-2 h-4 w-4",y==="none"?"opacity-100":"opacity-0")}),"No Contact"]}),d==null?void 0:d.map(V=>e.jsxs(e1,{value:`${V.first_name} ${V.last_name}`,onSelect:()=>{v(V.id),z(!1)},children:[e.jsx(Xr,{className:Mt("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(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(U,{onClick:$,disabled:i.isPending||l.isPending,children:n?"Save Changes":"Create Task"})]})]})]})})}const tXn={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 sXn({tasks:s}){const t=WIe(),n=CZn(),r=Wn(),[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(zr,{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(kSt,{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(_i,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("h3",{className:"font-medium text-sm",children:h.dealName}),e.jsxs(Be,{variant:"secondary",className:"ml-auto text-xs",children:[h.tasks.filter(m=>m.status==="done").length,"/",h.tasks.length]}),e.jsx(gi,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),h.tasks.map(m=>e.jsx(kSt,{task:m,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:p=>r(`/mission-control/pipeline?deal=${p}`)},m.id))]},u)),a&&e.jsx(Tts,{open:!!a,onOpenChange:()=>i(null),editTask:a})]})}function kSt({task:s,onToggle:t,onDelete:n,onEdit:r,onNavigateDeal:a}){const i=s.status==="done",l=!i&&s.due_date&&z4(ty(s.due_date))&&!ry(ty(s.due_date)),o=!i&&s.due_date&&ry(ty(s.due_date)),c=tXn[s.priority];return e.jsxs("div",{className:Mt("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(zr,{className:"h-5 w-5 text-emerald-500"}):e.jsx(Nf,{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:Mt("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(So,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]})]}),e.jsxs(Be,{variant:"outline",className:Mt("text-[10px] shrink-0",c.color),children:[c.dot," ",c.label]}),s.due_date&&e.jsxs("span",{className:Mt("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(Yr,{className:"h-3 w-3"}),Gs(ty(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(sp,{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(In,{className:"h-3.5 w-3.5 text-destructive"})})]})]})}const nXn=[{status:"todo",label:"To Do",icon:Nf,color:"border-t-slate-400"},{status:"in_progress",label:"In Progress",icon:$h,color:"border-t-blue-500"},{status:"done",label:"Done",icon:zr,color:"border-t-emerald-500"}],rXn={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function aXn({tasks:s}){const t=WIe(),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:nXn.map(i=>e.jsxs("div",{className:Mt("border rounded-lg border-t-4 bg-muted/20",i.color),onDragOver:l=>l.preventDefault(),onDrop:l=>a(l,i.status),children:[e.jsxs("div",{className:"px-4 py-3 flex items-center gap-2",children:[e.jsx(i.icon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-sm",children:i.label}),e.jsx(Be,{variant:"secondary",className:"ml-auto text-xs",children:n[i.status].length})]}),e.jsxs("div",{className:"p-2 space-y-2 min-h-[200px]",children:[n[i.status].map(l=>e.jsx(iXn,{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 iXn({task:s,onDragStart:t}){const n=s.status==="done",r=!n&&s.due_date&&z4(ty(s.due_date))&&!ry(ty(s.due_date)),a=!n&&s.due_date&&ry(ty(s.due_date));return e.jsx("div",{draggable:!0,onDragStart:i=>t(i,s.id),className:Mt("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:rXn[s.priority]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:Mt("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(_i,{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(So,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]}),s.due_date&&e.jsxs("div",{className:Mt("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(Yr,{className:"h-2.5 w-2.5"}),r?"Overdue — ":a?"Due today — ":"",Gs(ty(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 SSt={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function oXn({tasks:s}){const[t,n]=j.useState(new Date),r=WIe(),a=Bh(t),i=u_(t),l=c1(a),o=mMe(i),c=a5s({start:l,end:o}),d=j.useMemo(()=>{const m=new Map;return s.forEach(p=>{if(!p.due_date)return;const f=p.due_date,x=m.get(f)||[];x.push(p),m.set(f,x)}),m},[s]),u=j.useMemo(()=>s.filter(m=>!m.due_date),[s]),h=async m=>{const p=m.status==="done"?"todo":"done";try{await r.mutateAsync({id:m.id,status:p})}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(U,{variant:"ghost",size:"icon",onClick:()=>n($D(t,1)),children:e.jsx(rd,{className:"h-4 w-4"})}),e.jsx("h3",{className:"font-semibold",children:Gs(t,"MMMM yyyy")}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>n(dy(t,1)),children:e.jsx(gi,{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 p=Gs(m,"yyyy-MM-dd"),f=d.get(p)||[],x=Kne(m,t),y=ry(m);return e.jsxs("div",{className:Mt("border-r border-b min-h-[100px] p-1",!x&&"bg-muted/30",y&&"bg-primary/5"),children:[e.jsx("div",{className:Mt("text-xs font-medium mb-1 text-right px-1",!x&&"text-muted-foreground/40",y&&"text-primary font-bold"),children:Gs(m,"d")}),e.jsxs("div",{className:"space-y-0.5",children:[f.slice(0,3).map(v=>e.jsxs("button",{onClick:()=>h(v),className:Mt("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(zr,{className:"h-2.5 w-2.5 text-emerald-500 shrink-0"}):e.jsx(Nf,{className:"h-2.5 w-2.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[SSt[v.priority]," ",v.title]})]},v.id)),f.length>3&&e.jsxs("p",{className:"text-[9px] text-muted-foreground text-center",children:["+",f.length-3," more"]})]})]},p)})}),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:Mt("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(zr,{className:"h-3.5 w-3.5 text-emerald-500 shrink-0"}):e.jsx(Nf,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[SSt[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 lXn={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function cXn({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}=EZn(r||void 0),o=TZn(),c=MZn(),[d,u]=j.useState(""),[h,m]=j.useState("medium"),[p,f]=j.useState(""),x=async()=>{if(!(!d.trim()||!r))try{await o.mutateAsync({stage_id:r,title:d.trim(),priority:h,default_due_offset_days:p?parseInt(p):null,sort_order:((i==null?void 0:i.length)||0)+1}),u(""),f(""),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(Ds,{className:"sm:max-w-[560px]",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(OX,{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(te,{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:Mt("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(Gi,{className:"max-h-[250px]",children:e.jsxs("div",{className:"space-y-1.5",children:[i==null?void 0:i.map((b,N)=>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:lXn[b.priority]}),e.jsx("span",{className:"text-sm flex-1 truncate",children:b.title}),b.default_due_offset_days&&e.jsxs(Be,{variant:"outline",className:"text-[10px]",children:["+",b.default_due_offset_days,"d"]}),e.jsx("button",{onClick:()=>y(b.id),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:e.jsx(In,{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(te,{className:"text-xs text-muted-foreground",children:"Add Template Task"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{placeholder:"Task title...",value:d,onChange:b=>u(b.target.value),className:"flex-1",onKeyDown:b=>b.key==="Enter"&&x()}),e.jsxs(Ns,{value:h,onValueChange:b=>m(b),children:[e.jsx(ws,{className:"w-[100px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"low",children:"🟢 Low"}),e.jsx(et,{value:"medium",children:"🟡 Med"}),e.jsx(et,{value:"high",children:"🟠 High"}),e.jsx(et,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(te,{className:"text-xs",children:"Due offset (days from entering stage)"}),e.jsx(xe,{type:"number",placeholder:"e.g., 7",value:p,onChange:b=>f(b.target.value)})]}),e.jsxs(U,{onClick:x,disabled:!d.trim()||o.isPending,children:[e.jsx(an,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})})}function dXn(){const{data:s,isLoading:t}=kts(),{data:n}=nae(),[r,a]=j.useState("list"),[i,l]=j.useState(""),[o,c]=j.useState("active"),[d,u]=j.useState("all"),[h,m]=j.useState("all"),[p,f]=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,T])=>({id:A,name:T}))},[s]),b=j.useMemo(()=>s?s.filter(S=>{var R,z,$,H;const A=i.toLowerCase(),T=!A||S.title.toLowerCase().includes(A)||((z=(R=S.deal)==null?void 0:R.deal_name)==null?void 0:z.toLowerCase().includes(A))||`${(($=S.contact)==null?void 0:$.first_name)||""} ${((H=S.contact)==null?void 0:H.last_name)||""}`.toLowerCase().includes(A),L=o==="all"||o==="active"&&S.status!=="done"||o==="todo"&&S.status==="todo"||o==="in_progress"&&S.status==="in_progress"||o==="done"&&S.status==="done"||o==="overdue"&&S.status!=="done"&&S.due_date&&z4(ty(S.due_date))&&!ry(ty(S.due_date)),M=d==="all"||S.priority===d,I=h==="all"||h==="no_deal"&&!S.deal_id||S.deal_id===h;return T&&L&&M&&I}):[],[s,i,o,d,h]),N=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&&z4(ty(A.due_date))&&!ry(ty(A.due_date))).length,dueToday:S.filter(A=>A.due_date&&ry(ty(A.due_date))).length,dueThisWeek:S.filter(A=>A.due_date&&s3s(ty(A.due_date))).length,completed:s.filter(A=>A.status==="done").length}},[s]);return e.jsx(qs,{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(U,{variant:"outline",size:"sm",onClick:()=>y(!0),children:[e.jsx(K2,{className:"h-4 w-4 mr-1"}),"Templates"]}),e.jsxs(U,{size:"sm",onClick:()=>f(!0),children:[e.jsx(an,{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(m0,{className:"h-3.5 w-3.5"}),"Active"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:N.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(tc,{className:"h-3.5 w-3.5"}),"Overdue"]}),e.jsx("p",{className:"text-xl font-bold mt-1 text-destructive",children:N.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(Yr,{className:"h-3.5 w-3.5"}),"Due Today"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:N.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(nc,{className:"h-3.5 w-3.5"}),"This Week"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:N.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(zr,{className:"h-3.5 w-3.5"}),"Completed"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:N.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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search tasks...",value:i,onChange:S=>l(S.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:d,onValueChange:u,children:[e.jsx(ws,{className:"w-[130px]",children:e.jsx(ks,{placeholder:"Priority"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Priorities"}),e.jsx(et,{value:"urgent",children:"🔴 Urgent"}),e.jsx(et,{value:"high",children:"🟠 High"}),e.jsx(et,{value:"medium",children:"🟡 Medium"}),e.jsx(et,{value:"low",children:"🟢 Low"})]})]}),e.jsxs(Ns,{value:h,onValueChange:m,children:[e.jsx(ws,{className:"w-[160px]",children:e.jsx(ks,{placeholder:"Deal"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Deals"}),e.jsx(et,{value:"no_deal",children:"No Deal"}),v.map(S=>e.jsx(et,{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(m0,{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(P4,{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(nc,{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(sXn,{tasks:b}),r==="kanban"&&e.jsx(aXn,{tasks:b}),r==="calendar"&&e.jsx(oXn,{tasks:b})]}),e.jsx(Tts,{open:p,onOpenChange:f}),e.jsx(cXn,{open:x,onOpenChange:y,stages:n||[]})]})})}function uXn(s){const t=vrt(s);return t?t.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}):""}function hXn({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 Mce({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:Mt("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 mXn(){const s=Wn(),{data:t,isLoading:n}=dZn(),r=WIe(),[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 N=a.trim().toLowerCase();return N&&(b=b.filter(S=>{var A,T,L,M;return((A=S.deal_name)==null?void 0:A.toLowerCase().includes(N))||((T=S.property_address)==null?void 0:T.toLowerCase().includes(N))||`${((L=S.contact)==null?void 0:L.first_name)??""} ${((M=S.contact)==null?void 0:M.last_name)??""}`.toLowerCase().includes(N)})),b},[t,a,c]),h=j.useMemo(()=>{const b=[];return(u||[]).forEach(N=>{lX.forEach(S=>{const A=N[S.key],T=T5(A);A&&T!==null&&T<=30&&b.push({id:`${N.id}-${S.key}`,kind:"date",label:S.label,dealId:N.id,dealName:N.deal_name,date:A,days:T})}),N.tasks.filter(S=>S.status!=="done"&&S.due_date).forEach(S=>{const A=T5(S.due_date);A!==null&&A<=30&&b.push({id:S.id,kind:"task",label:S.title,dealId:N.id,dealName:N.deal_name,date:S.due_date,days:A,priority:S.priority})})}),b.sort((N,S)=>N.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]),p=j.useMemo(()=>{const b=t||[],N=b.filter(T=>{const L=T5(T.target_close_date);return L!==null&&L>=0&&L<=7}).length,S=b.reduce((T,L)=>T+L.tasks.filter(M=>{const I=T5(M.due_date);return M.status!=="done"&&I!==null&&I<0}).length,0),A=b.reduce((T,L)=>T+(Number(L.expected_price)||0),0);return{active:b.length,closingSoon:N,overdueTasks:S,volume:A}},[t]),f=b=>b.tasks.length===0?0:b.tasks.filter(N=>N.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:N,tone:S})=>{if(N.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:Mt("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:["(",N.length,")"]})]}),N.slice(0,12).map(T=>e.jsxs("div",{className:Mt("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:[T.kind==="task"?e.jsx(xi,{className:"shrink-0",onCheckedChange:()=>y(T.id),"aria-label":`Complete ${T.label}`}):e.jsx(ch,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{type:"button",onClick:()=>x(T.dealId),className:"flex-1 min-w-0 text-left",children:[e.jsx("p",{className:"text-sm font-medium leading-tight truncate",children:T.label}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[T.dealName," · ",uXn(T.date)]})]}),e.jsx("span",{className:Mt("text-[11px] font-semibold shrink-0 tabular-nums",T.days<0?"text-destructive":T.days<=3?"text-amber-600":"text-muted-foreground"),children:T.days<0?`${Math.abs(T.days)}d late`:T.days===0?"Today":`${T.days}d`})]},T.id))]})};return e.jsxs(qs,{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(U,{onClick:()=>o(!0),className:"gap-2 shrink-0",children:[e.jsx(ig,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsx(Mce,{icon:iy,label:"Active transactions",value:p.active}),e.jsx(Mce,{icon:Xd,label:"Closing within 7 days",value:p.closingSoon,tone:"warn"}),e.jsx(Mce,{icon:tc,label:"Overdue tasks",value:p.overdueTasks,tone:p.overdueTasks>0?"danger":"good"}),e.jsx(Mce,{icon:rc,label:"Pipeline volume",value:p.volume>=1e6?`$${(p.volume/1e6).toFixed(1)}M`:`$${Math.round(p.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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{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(U,{size:"sm",variant:c==="all"?"default":"ghost",onClick:()=>d("all"),className:"h-8",children:"All active"}),e.jsx(U,{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(Et,{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(ch,{className:"h-4 w-4 text-primary"}),e.jsx("h2",{className:"text-sm font-semibold",children:"Deadline Radar"}),e.jsx(Be,{variant:"secondary",className:"text-[10px] ml-auto",children:"next 30 days"})]}),h.length===0?e.jsxs("div",{className:"text-center py-10",children:[e.jsx(zr,{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(ra,{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(U,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/pipeline"),children:"Go to Deal Pipeline"})]}):u.map(b=>{const N=f(b),S=T5(b.target_close_date),A=b.tasks.filter(M=>M.status!=="done"),T=A.filter(M=>{const I=T5(M.due_date);return I!==null&&I<0}),L=A.filter(M=>M.due_date).sort((M,I)=>(T5(M.due_date)??0)-(T5(I.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(hXn,{value:N}),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(gi,{className:"h-4 w-4 text-muted-foreground shrink-0 mt-0.5"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-2",children:[b.stage&&e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full font-medium",style:{backgroundColor:`${b.stage.color}1f`,color:b.stage.color},children:b.stage.name}),e.jsx(Be,{variant:"outline",className:"text-[10px] capitalize",children:b.deal_type}),S!==null&&e.jsx(Be,{variant:"secondary",className:Mt("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`}),T.length>0&&e.jsxs(Be,{className:"text-[10px] bg-destructive/10 text-destructive hover:bg-destructive/10",children:[T.length," overdue"]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(ro,{value:N,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(M=>M.status==="done").length," of"," ",b.tasks.length," steps complete"]}),L&&e.jsxs("p",{className:"text-[11px] text-muted-foreground truncate max-w-[55%]",children:["Next: ",L.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(Nts,{open:l,onOpenChange:o})]})}function Mts(){const s=Sa();return ct({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 pXn(){const s=Qt();return yt({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 fXn(){const s=Qt();return yt({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 gXn=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)),hze=[{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"}],xXn={buying:"Buying",selling:"Selling",both:"Buying & Selling",unsure:"Not sure yet"};function Pts(){const{data:s=[],isLoading:t}=Mts(),n=pXn(),r=fXn(),[a,i]=j.useState("all"),[l,o]=j.useState({}),c=j.useMemo(()=>a==="all"?s:s.filter(p=>p.status===a),[s,a]),d=j.useMemo(()=>({total:s.length,new:s.filter(p=>p.status==="new").length,converted:s.filter(p=>p.status==="converted").length}),[s]),u=(p,f)=>{n.mutate({id:p.id,status:f}),re.success("Status updated")},h=p=>{const f=l[p.id];n.mutate({id:p.id,agent_notes:f}),o(x=>{const{[p.id]:y,...v}=x;return v}),re.success("Notes saved")},m=async p=>{await Yi(`Delete referral for ${p.friend_name}?`)&&r.mutate(p.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(Ro,{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"},...hze.map(p=>({v:p.value,l:p.label}))].map(p=>e.jsx("button",{onClick:()=>i(p.v),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${a===p.v?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:p.l},p.v))}),t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Et,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):c.length===0?e.jsx(we,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(Ro,{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(p=>{var v,b;const f=hze.find(N=>N.value===p.status),x=(v=p.client_portals)==null?void 0:v.slug,y=p.referrer_name||((b=p.client_portals)==null?void 0:b.client_name)||"Anonymous client";return e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsx(It,{className:"text-lg",children:p.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1.5",children:[e.jsx(pa,{className:"h-3 w-3"}),"Referred by ",e.jsx("span",{className:"font-medium text-foreground",children:y})," ·"," ",gXn(p.created_at)]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Be,{variant:"outline",className:f==null?void 0:f.className,children:(f==null?void 0:f.label)||p.status}),e.jsxs(Ns,{value:p.status,onValueChange:N=>u(p,N),children:[e.jsx(ws,{className:"h-8 w-[130px] text-xs",children:e.jsx(ks,{})}),e.jsx(js,{children:hze.map(N=>e.jsx(et,{value:N.value,className:"text-xs",children:N.label},N.value))})]})]})]})}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[p.friend_interest&&e.jsx(Be,{variant:"secondary",className:"text-xs",children:xXn[p.friend_interest]||p.friend_interest}),p.friend_email&&e.jsxs("a",{href:`mailto:${p.friend_email}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(ln,{className:"h-3 w-3"}),p.friend_email]}),p.friend_phone&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${p.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(ba,{className:"h-3 w-3"}),p.friend_phone]}),e.jsxs("a",{href:`sms:${p.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(vu,{className:"h-3 w-3"}),"Text"]})]})]}),p.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:['"',p.friend_message,'"']})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Your notes"}),l[p.id]!==void 0?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Fs,{value:l[p.id],onChange:N=>o(S=>({...S,[p.id]:N.target.value})),rows:3,className:"text-sm"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{size:"sm",onClick:()=>h(p),children:"Save"}),e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>o(N=>{const{[p.id]:S,...A}=N;return A}),children:"Cancel"})]})]}):e.jsx("button",{onClick:()=>o(N=>({...N,[p.id]:p.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:p.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(Sr,{className:"h-3 w-3"}),"View source portal"]}),e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>m(p),className:"text-destructive hover:text-destructive ml-auto h-8",children:e.jsx(In,{className:"h-3.5 w-3.5"})})]})]})]},p.id)})})]})}function Lts({vendor:s,onEdit:t,onDelete:n,onToggleVisible:r,isVisible:a,showOwnerBadge:i,clickCount:l}){var c;const o=((c=wG.find(d=>d.value===s.category))==null?void 0:c.label)||s.category;return e.jsxs(we,{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(Ql,{className:"w-3.5 h-3.5 text-amber-600","aria-label":"Required"}),s.is_featured&&e.jsx(Ua,{className:"w-3.5 h-3.5 text-amber-500 fill-amber-500","aria-label":"Featured"})]}),s.company&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:s.company}),e.jsxs("div",{className:"flex items-center gap-1 mt-1 flex-wrap",children:[e.jsx(Be,{variant:"secondary",className:"text-[10px]",children:o}),i==="brokerage"&&e.jsx(Be,{variant:"outline",className:"text-[10px]",children:"Brokerage"}),i==="agent"&&e.jsx(Be,{variant:"outline",className:"text-[10px]",children:"Personal"}),!s.is_active&&e.jsx(Be,{variant:"destructive",className:"text-[10px]",children:"Inactive"}),typeof l=="number"&&l>0&&e.jsxs(Be,{variant:"outline",className:"text-[10px]",children:[l," clicks"]})]})]})]}),s.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:s.description}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-1",children:[s.phone&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ba,{className:"w-3 h-3"}),s.phone]}),s.email&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ln,{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(fl,{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(pa,{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(ni,{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(U,{size:"sm",variant:a?"default":"outline",onClick:()=>r(!a),disabled:s.is_required&&!a,className:"flex-1",children:[a?e.jsx(xa,{className:"w-3.5 h-3.5 mr-1.5"}):e.jsx(Vg,{className:"w-3.5 h-3.5 mr-1.5"}),a?"Showing in portals":"Hidden"]}),t&&e.jsx(U,{size:"sm",variant:"ghost",onClick:t,children:e.jsx(sp,{className:"w-3.5 h-3.5"})}),n&&e.jsx(U,{size:"sm",variant:"ghost",onClick:n,className:"text-destructive",children:e.jsx(In,{className:"w-3.5 h-3.5"})})]})]})}function Its({open:s,onOpenChange:t,vendor:n,ownerType:r,brokerageId:a,agentUserId:i,showBrokerageOnlyFields:l}){const o=bIs(),[c,d]=j.useState({}),[u,h]=j.useState(!1),m=j.useRef(null),p=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:N}=await q.storage.from("vendor-logos").upload(b,y,{upsert:!0,contentType:y.type});if(N)throw N;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 f=(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(Ds,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:n?"Edit Vendor":"Add Vendor"})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(te,{children:"Contact Name *"}),e.jsx(xe,{value:c.name||"",onChange:y=>f("name",y.target.value),placeholder:"Bob Smith"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Company"}),e.jsx(xe,{value:c.company||"",onChange:y=>f("company",y.target.value),placeholder:"Smith Inspections"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Category"}),e.jsxs(Ns,{value:c.category,onValueChange:y=>f("category",y),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:wG.map(y=>e.jsx(et,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Phone"}),e.jsx(xe,{value:c.phone||"",onChange:y=>f("phone",y.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Email"}),e.jsx(xe,{type:"email",value:c.email||"",onChange:y=>f("email",y.target.value),placeholder:"bob@smithinsp.com"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Website"}),e.jsx(xe,{value:c.website||"",onChange:y=>f("website",y.target.value),placeholder:"https://..."})]}),e.jsxs("div",{children:[e.jsx(te,{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&&p(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:()=>f("logo_url",""),className:"absolute -top-2 -right-2 bg-background border rounded-full p-0.5 shadow","aria-label":"Remove logo",children:e.jsx(er,{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(qa,{className:"h-5 w-5"})}),e.jsxs(U,{type:"button",variant:"outline",size:"sm",onClick:()=>{var y;return(y=m.current)==null?void 0:y.click()},disabled:u,children:[u?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(qa,{className:"h-4 w-4 mr-2"}),c.logo_url?"Replace":"Upload Logo"]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(te,{children:"Address"}),e.jsx(xe,{value:c.address||"",onChange:y=>f("address",y.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(te,{children:"Description"}),e.jsx(Fs,{rows:3,value:c.description||"",onChange:y=>f("description",y.target.value),placeholder:"Why your clients should use this vendor..."})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Primary Action"}),e.jsxs(Ns,{value:c.action_type,onValueChange:y=>f("action_type",y),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:xIs.map(y=>e.jsx(et,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Booking URL (Calendly etc.)"}),e.jsx(xe,{value:c.booking_url||"",onChange:y=>f("booking_url",y.target.value),placeholder:"https://calendly.com/..."})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(te,{children:"Compliance Disclosure (optional)"}),e.jsx(Fs,{rows:2,value:c.disclosure_text||"",onChange:y=>f("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(te,{className:"font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show this vendor in client portals"})]}),e.jsx(wn,{checked:!!c.is_active,onCheckedChange:y=>f("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(te,{className:"font-medium",children:"Featured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlight in agent library"})]}),e.jsx(wn,{checked:!!c.is_featured,onCheckedChange:y=>f("is_featured",y)})]}),e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(te,{className:"font-medium",children:"Required"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents cannot hide"})]}),e.jsx(wn,{checked:!!c.is_required,onCheckedChange:y=>f("is_required",y)})]})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(U,{onClick:x,disabled:o.isPending,children:o.isPending?"Saving...":"Save Vendor"})]})]})})}function Rts({embedded:s=!1}={}){const t=Sa(),{brokerageId:n}=vs(),{data:r,isLoading:a}=vIs(),{data:i={}}=NOt("agent",t),l=wOt(),o=_Is(),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,p]=j.useState(""),[f,x]=j.useState("all"),y=(r==null?void 0:r.vendors)||[],v=(r==null?void 0:r.selections)||[],b=j.useMemo(()=>{const R=new Map;return v.forEach(z=>R.set(z.vendor_id,z.is_visible)),R},[v]),N=j.useMemo(()=>y.filter(R=>!(f!=="all"&&R.category!==f||m&&!`${R.name} ${R.company||""}`.toLowerCase().includes(m.toLowerCase()))),[y,m,f]),S=N.filter(R=>R.owner_type==="agent"),A=N.filter(R=>R.owner_type==="brokerage"),T=async R=>{if(await Yi("Delete this vendor?"))try{await l.mutateAsync(R),re.success("Vendor deleted")}catch(z){re.error(z.message)}},L=async(R,z)=>{try{await o.mutateAsync({vendorId:R,isVisible:z})}catch($){re.error($.message)}},M=R=>R.is_required?!0:b.get(R.id)??R.owner_type==="agent",I=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(og,{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(U,{onClick:()=>{d(null),h(!0)},children:[e.jsx(an,{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(Fr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{className:"pl-9",placeholder:"Search vendors...",value:m,onChange:R=>p(R.target.value)})]}),e.jsxs("select",{value:f,onChange:R=>x(R.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),wG.map(R=>e.jsx("option",{value:R.value,children:R.label},R.value))]})]}),a?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):e.jsxs(oa,{defaultValue:n?"all":"personal",children:[e.jsxs(la,{children:[e.jsxs(Kt,{value:"all",children:["All (",N.length,")"]}),n&&e.jsxs(Kt,{value:"brokerage",children:["From Brokerage (",A.length,")"]}),e.jsxs(Kt,{value:"personal",children:["My Personal (",S.length,")"]})]}),e.jsx(Zt,{value:"all",className:"mt-4",children:e.jsx(mze,{vendors:N,isVisibleInPortals:M,onToggle:L,onEdit:R=>{d(R),h(!0)},onDelete:T,userId:t,clicks:i})}),n&&e.jsx(Zt,{value:"brokerage",className:"mt-4",children:A.length===0?e.jsx(CSt,{icon:e.jsx(cn,{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(mze,{vendors:A,isVisibleInPortals:M,onToggle:L,userId:t,clicks:i})}),e.jsx(Zt,{value:"personal",className:"mt-4",children:S.length===0?e.jsx(CSt,{icon:e.jsx(og,{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(U,{onClick:()=>{d(null),h(!0)},children:[e.jsx(an,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})}):e.jsx(mze,{vendors:S,isVisibleInPortals:M,onToggle:L,onEdit:R=>{d(R),h(!0)},onDelete:T,userId:t,clicks:i})})]}),e.jsx(Its,{open:u,onOpenChange:h,vendor:c,ownerType:"agent",agentUserId:t})]});return s?I:e.jsx(qs,{children:I})}function mze({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(Lts,{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 CSt({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 yXn({status:s}){return s==="mapped"?e.jsx(Be,{className:"bg-emerald-500/15 text-emerald-600 hover:bg-emerald-500/15",children:"Ready"}):s==="needs_placement"?e.jsx(Be,{variant:"outline",children:"Needs field placement"}):e.jsx(Be,{variant:"secondary",children:"Needs mapping"})}function vXn(){const{brokerageId:s,isBrokerageManager:t,isAdmin:n,loading:r}=vs(),{data:a=[],isLoading:i}=AYn(s),l=gts(),o=xts(),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,p]=j.useState(null),[f,x]=j.useState(null),[y,v]=j.useState("");if(r)return e.jsx(qs,{children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t&&!n)return e.jsx(qs,{children:e.jsx("div",{className:"p-8 text-center",children:e.jsx("h2",{className:"text-xl font-semibold",children:"Brokerage managers only"})})});const b=a.filter(L=>L.name.toLowerCase().includes(y.trim().toLowerCase())),N=m?a.find(L=>L.id===m.id)||m:null,S=gx(N),A=async(L,M)=>{const I=gx(L);if(M&&(I==null?void 0:I.mapping_status)!=="mapped"){re.error("Map and place the fields before publishing this form to your agents.");return}try{await l.mutateAsync({id:L.id,patch:{is_published:M}}),re.success(M?"Published to your agents":"Unpublished — agents can no longer use it")}catch(R){re.error((R==null?void 0:R.message)||"Could not update the form")}},T=async L=>{if(await Yi(`Delete "${L.name}"? Agents will lose access. Forms already generated stay on their deals.`))try{await o.mutateAsync(L),(m==null?void 0:m.id)===L.id&&p(null),re.success("Form deleted")}catch(M){re.error((M==null?void 0:M.message)||"Could not delete the form")}};return e.jsxs(qs,{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(U,{onClick:()=>d(!0),children:[e.jsx(an,{className:"mr-2 h-4 w-4"})," Upload form"]})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Fr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{className:"pl-9",placeholder:"Search forms…",value:y,onChange:L=>v(L.target.value)})]}),i&&e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Et,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),!i&&a.length===0&&e.jsx(we,{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(_i,{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(U,{onClick:()=>d(!0),children:[e.jsx(qa,{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:[b.map(L=>{var I;const M=gx(L);return e.jsx(we,{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(Ur,{className:"h-5 w-5 text-primary"})}),e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>p(L),children:[e.jsx("p",{className:"truncate font-medium",children:L.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(I=lrt.find(R=>R.value===L.category))==null?void 0:I.label," · v",(M==null?void 0:M.version_number)??1,M?` · ${M.page_count} page${M.page_count===1?"":"s"}`:""]})]}),e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(ey,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",children:[e.jsx(La,{onClick:()=>p(L),children:"Open & map fields"}),e.jsxs(La,{onClick:()=>x(L),children:[e.jsx(Hg,{className:"mr-2 h-4 w-4"})," Place fields & signatures"]}),e.jsxs(La,{onClick:()=>h(L),children:[e.jsx(qa,{className:"mr-2 h-4 w-4"})," Upload new version"]}),e.jsxs(La,{onClick:()=>l.mutate({id:L.id,patch:{is_archived:!0,is_published:!1}}),children:[e.jsx(n1,{className:"mr-2 h-4 w-4"})," Archive"]}),e.jsxs(La,{className:"text-destructive",onClick:()=>T(L),children:[e.jsx(In,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(yXn,{status:M==null?void 0:M.mapping_status}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[L.is_published?"Published":"Draft",e.jsx(wn,{checked:!!L.is_published,onCheckedChange:R=>A(L,R)})]})]})]})},L.id)}),b.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(my,{open:!!N,onOpenChange:L=>!L&&p(null),children:e.jsxs(g0,{side:"right",className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(vv,{className:"space-y-1 text-left",children:[e.jsx(bv,{children:N==null?void 0:N.name}),S&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["v",S.version_number," · ",S.file_name," ·"," ",urt(S.file_size)," · uploaded"," ",Gs(new Date(S.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"mt-5 space-y-4",children:[(N==null?void 0:N.description)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:N.description}),S?e.jsxs(e.Fragment,{children:[e.jsxs(U,{variant:"outline",className:"w-full",onClick:()=>N&&x(N),children:[e.jsx(Hg,{className:"mr-2 h-4 w-4"})," Place fields & signatures on the document"]}),e.jsx(Ats,{version:S})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"This form has no uploaded version yet."})]})]})}),e.jsx(_Te,{open:c,onOpenChange:d,brokerageId:s}),e.jsx(_Te,{open:!!u,onOpenChange:L=>!L&&h(null),templateId:u==null?void 0:u.id,templateName:u==null?void 0:u.name,brokerageId:s}),f&&gx(f)&&e.jsx(Ets,{open:!0,onOpenChange:L=>!L&&x(null),version:gx(f),templateName:f.name})]})}function bXn(){const{brokerageId:s,isBrokerageManager:t,isAdmin:n,loading:r}=vs(),{data:a=[],isLoading:i}=yIs(s),{data:l={}}=NOt("brokerage",s),o=wOt(),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,p]=j.useState(""),[f,x]=j.useState("all");if(r)return e.jsx(qs,{children:e.jsx("div",{className:"p-8",children:"Loading..."})});if(!t&&!n)return e.jsx(qs,{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=>!(f!=="all"&&b.category!==f||m&&!`${b.name} ${b.company||""}`.toLowerCase().includes(m.toLowerCase()))),v=async b=>{if(await Yi("Delete this vendor? This will remove it from all agent libraries."))try{await o.mutateAsync(b),re.success("Vendor deleted")}catch(N){re.error(N.message)}};return e.jsx(qs,{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(_i,{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(U,{onClick:()=>{d(null),h(!0)},children:[e.jsx(an,{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(Fr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{className:"pl-9",placeholder:"Search vendors...",value:m,onChange:b=>p(b.target.value)})]}),e.jsxs("select",{value:f,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"}),wG.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(_i,{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(U,{onClick:()=>{d(null),h(!0)},children:[e.jsx(an,{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(Lts,{vendor:b,onEdit:()=>{d(b),h(!0)},onDelete:()=>v(b.id),clickCount:l[b.id]},b.id))}),e.jsx(Its,{open:u,onOpenChange:h,vendor:c,ownerType:"brokerage",brokerageId:s,showBrokerageOnlyFields:!0})]})})}const _Xn=[{value:"overview",label:"Portals",icon:Hg},{value:"vendors",label:"Vendors",icon:a1},{value:"referrals",label:"Referrals",icon:Ro},{value:"branding",label:"Branding",icon:$c},{value:"questions",label:"Onboarding",icon:cy}];function wXn(){const[s,t]=fc(),n=s.get("tab")||"overview",[r,a]=j.useState(n),[i,l]=j.useState(!1),[o,c]=j.useState(!1);return j.useEffect(()=>{t(d=>{const u=new URLSearchParams(d);return u.set("tab",r),u},{replace:!0})},[r,t]),e.jsxs(qs,{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(cn,{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($F,{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(U,{asChild:!0,variant:"outline",size:"sm",className:"shrink-0",children:e.jsx(xr,{to:"/mission-control/pipeline",children:"Open Deal Pipeline"})})]})}),e.jsxs(oa,{value:r,onValueChange:a,className:"w-full",children:[e.jsx(la,{className:"w-full justify-start overflow-x-auto h-auto flex-wrap",children:_Xn.map(d=>e.jsxs(Kt,{value:d.value,className:"gap-2",children:[e.jsx(d.icon,{className:"w-4 h-4"}),d.label]},d.value))}),e.jsx(Zt,{value:"overview",className:"mt-6",children:e.jsx(Cts,{})}),e.jsx(Zt,{value:"vendors",className:"mt-6",children:e.jsx(jXn,{})}),e.jsx(Zt,{value:"referrals",className:"mt-6",children:e.jsx(NXn,{})}),e.jsx(Zt,{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($c,{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(U,{onClick:()=>l(!0),children:[e.jsx(qc,{className:"w-4 h-4 mr-2"}),"Edit Branding Defaults"]})]})]})})}),e.jsx(Zt,{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(cy,{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(U,{onClick:()=>c(!0),children:[e.jsx(qc,{className:"w-4 h-4 mr-2"}),"Manage Questions"]})]})]})})})]})]}),e.jsx(Sts,{open:i,onOpenChange:l}),e.jsx(jts,{open:o,onOpenChange:c})]})}function jXn(){return e.jsx(Rts,{embedded:!0})}function NXn(){return e.jsx(Pts,{})}function kXn({portalId:s,portalSlug:t,clientName:n,agentName:r}){const{data:a,isLoading:i}=COt(s),l=AOt(),o=NIs(),[c,d]=j.useState(""),u=j.useRef(null),h=(a||[]).filter(p=>p.sender_type==="client"&&!p.read_at).length;j.useEffect(()=>{h>0&&o.mutate(s)},[h,s]),j.useEffect(()=>{var p;(p=u.current)==null||p.scrollIntoView({block:"nearest"})},[a==null?void 0:a.length]);const m=async()=>{const p=c.trim();if(p)try{await l.mutateAsync({portalId:s,senderType:"agent",senderName:r||null,body:p,portalUrl:t?`https://clients.relevelup.com/${t}`:void 0}),d(""),re.success("Message sent — your client was emailed")}catch(f){re.error((f==null?void 0:f.message)||"Could not send message")}};return e.jsx(we,{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(Et,{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(p=>{const f=p.sender_type==="agent";return e.jsx("div",{className:`flex ${f?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[80%] rounded-lg px-3 py-2 border ${f?"bg-primary/10 border-primary/20":"bg-muted border-border"}`,children:[e.jsxs("p",{className:"text-[11px] text-muted-foreground mb-1",children:[f?r||"You":p.sender_name||n||"Client"," ·"," ",Gs(new Date(p.created_at),"MMM d, h:mm a")]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:p.body})]})},p.id)}),e.jsx("div",{ref:u})]}),e.jsxs("div",{className:"mt-4 space-y-2",children:[e.jsx(Fs,{value:c,onChange:p=>d(p.target.value),rows:3,placeholder:`Reply to ${n||"your client"}...`}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(U,{onClick:m,disabled:l.isPending||!c.trim(),size:"sm",children:[l.isPending?e.jsx(Et,{className:"w-4 h-4 mr-1.5 animate-spin"}):e.jsx($r,{className:"w-4 h-4 mr-1.5"}),"Send & notify"]})})]})]})})}const _B=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s));function SXn(s){return ct({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 CXn(){const{portalId:s}=Di(),t=Wn(),n=Sa(),{data:r,isLoading:a}=SXn(s),{data:i=[]}=K8n(s),{data:l=[]}=Mts(),o=eW(),c=gWt(),d=xWt(),u=yWt(),[h,m]=j.useState(!1),[p,f]=j.useState(!1),[x,y]=j.useState(!1),[v,b]=j.useState(!1),N=(r==null?void 0:r.portal)??null,S=(r==null?void 0:r.deal)??null,A=j.useMemo(()=>N?l.filter(Z=>Z.portal_id===N.id):[],[l,N==null?void 0:N.id]);if(a)return e.jsx(qs,{children:e.jsx("div",{className:"flex items-center justify-center py-24",children:e.jsx(Et,{className:"h-6 w-6 animate-spin text-muted-foreground"})})});if(!N)return e.jsx(qs,{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(U,{asChild:!0,variant:"outline",children:e.jsxs(xr,{to:"/mission-control/client-portals",children:[e.jsx(Aa,{className:"w-4 h-4 mr-2"}),"Back to Portals"]})})]})});const T=lS(N.slug),L=(S==null?void 0:S.deal_name)||"Untitled deal",M=S==null?void 0:S.contact,I=M?`${M.first_name||""} ${M.last_name||""}`.trim():"",R=!!N.archived_at,z=()=>{navigator.clipboard.writeText(T),re.success("Portal link copied!")},$=async Z=>{try{await o.mutateAsync({id:N.id,is_enabled:Z}),re.success(Z?"Portal enabled":"Portal disabled")}catch{re.error("Failed to update")}},H=async()=>{try{await c.mutateAsync(N.id),re.success("Portal archived")}catch{re.error("Failed to archive")}},V=async()=>{try{await d.mutateAsync(N.id),re.success("Portal restored")}catch{re.error("Failed to restore")}},K=async()=>{try{await u.mutateAsync({id:N.id,dealId:N.deal_id}),re.success("Portal deleted"),t("/mission-control/client-portals")}catch{re.error("Failed to delete")}};return e.jsxs(qs,{children:[e.jsx(dl,{children:e.jsxs("title",{children:[L," — 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(U,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2 text-muted-foreground",children:e.jsxs(xr,{to:"/mission-control/client-portals?tab=overview",children:[e.jsx(Aa,{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(cn,{className:"w-5 h-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold truncate",children:L}),e.jsx(Be,{variant:"outline",className:R?"bg-muted text-muted-foreground":N.is_enabled?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-muted text-muted-foreground",children:R?"Archived":N.is_enabled?"Active":"Disabled"}),e.jsx(Be,{variant:"outline",className:"capitalize text-xs",children:N.visibility})]}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-2 flex-wrap",children:[e.jsx(So,{className:"w-3.5 h-3.5"}),N.client_name||I||"No client name set",(M==null?void 0:M.email)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(ln,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"truncate",children:M.email})]}),(M==null?void 0:M.phone)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(ba,{className:"w-3.5 h-3.5"}),M.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:T})})]}),!R&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Live"}),e.jsx(wn,{checked:N.is_enabled,onCheckedChange:$})]})]}),e.jsxs("div",{className:"mt-5 flex items-center gap-2 flex-wrap",children:[e.jsxs(U,{onClick:z,variant:"outline",size:"sm",children:[e.jsx(Pa,{className:"w-4 h-4 mr-1.5"})," Copy Link"]}),e.jsxs(U,{onClick:()=>window.open(T,"_blank"),variant:"outline",size:"sm",children:[e.jsx(Sr,{className:"w-4 h-4 mr-1.5"})," Preview"]}),e.jsxs(U,{onClick:()=>y(!0),size:"sm",children:[e.jsx($r,{className:"w-4 h-4 mr-1.5"})," Invite Client"]}),e.jsxs(U,{onClick:()=>f(!0),variant:"outline",size:"sm",children:[e.jsx(p4,{className:"w-4 h-4 mr-1.5"})," Post Update"]}),e.jsxs(U,{onClick:()=>m(!0),variant:"outline",size:"sm",children:[e.jsx(qc,{className:"w-4 h-4 mr-1.5"})," Settings"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[R?e.jsxs(U,{onClick:V,variant:"outline",size:"sm",children:[e.jsx(jM,{className:"w-4 h-4 mr-1.5"})," Restore"]}):e.jsxs(U,{onClick:H,variant:"ghost",size:"sm",children:[e.jsx(n1,{className:"w-4 h-4 mr-1.5"})," Archive"]}),e.jsx(U,{onClick:()=>b(!0),variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",children:e.jsx(In,{className:"w-4 h-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(Pce,{icon:p4,label:"Updates Posted",value:i.length}),e.jsx(Pce,{icon:Ro,label:"Referrals",value:A.length}),e.jsx(Pce,{icon:pa,label:"Inspection",value:N.inspection_date?_B(N.inspection_date):"—"}),e.jsx(Pce,{icon:pa,label:"Appraisal",value:N.appraisal_date?_B(N.appraisal_date):"—"})]}),e.jsxs(oa,{defaultValue:"updates",className:"w-full",children:[e.jsxs(la,{children:[e.jsxs(Kt,{value:"updates",children:["Updates (",i.length,")"]}),e.jsx(Kt,{value:"messages",children:"Messages"}),e.jsxs(Kt,{value:"referrals",children:["Referrals (",A.length,")"]}),e.jsx(Kt,{value:"branding",children:"Branding"}),e.jsx(Kt,{value:"details",children:"Details"})]}),e.jsx(Zt,{value:"messages",className:"mt-4",children:e.jsx(kXn,{portalId:N.id,portalSlug:N.slug,clientName:N.client_name})}),e.jsx(Zt,{value:"updates",className:"mt-4",children:e.jsx(we,{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(U,{size:"sm",onClick:()=>f(!0),children:[e.jsx(p4,{className:"w-4 h-4 mr-1.5"})," New Update"]})]}),i.length===0?e.jsxs("div",{className:"text-center py-12 border-2 border-dashed rounded-lg",children:[e.jsx(p4,{className:"w-10 h-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No updates posted yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Keep your client in the loop — post your first update."})]}):e.jsx("div",{className:"space-y-3",children:i.map(Z=>e.jsx("div",{className:"border rounded-lg p-4",children:e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h4",{className:"font-medium text-sm",children:Z.title}),Z.is_stage_change&&e.jsx(Be,{variant:"outline",className:"text-[10px] bg-emerald-500/10 text-emerald-700 border-emerald-200",children:"Stage Change"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:_B(Z.created_at)}),Z.content&&e.jsx("p",{className:"text-sm text-muted-foreground mt-2 whitespace-pre-wrap",children:Z.content}),Z.video_url&&e.jsxs("a",{href:Z.video_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline mt-2",children:[e.jsx(Wr,{className:"w-3 h-3"})," View video"]})]})})},Z.id))})]})})}),e.jsx(Zt,{value:"referrals",className:"mt-4",children:e.jsx(we,{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(Ro,{className:"w-10 h-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No referrals yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"When your client refers a friend, they'll show up here."})]}):e.jsx("div",{className:"space-y-2",children:A.map(Z=>e.jsx(xr,{to:"/mission-control/client-portals?tab=referrals",className:"block border rounded-lg p-3 hover:bg-muted/50 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:Z.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Z.friend_email||Z.friend_phone||"No contact info"," · ",_B(Z.created_at)]})]}),e.jsx(Be,{variant:"outline",className:"text-xs capitalize",children:Z.status})]})},Z.id))})]})})}),e.jsx(Zt,{value:"branding",className:"mt-4",children:e.jsx(we,{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($c,{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(U,{onClick:()=>m(!0),children:[e.jsx(qc,{className:"w-4 h-4 mr-2"}),"Edit Branding (in Settings)"]})]})]})})})}),e.jsx(Zt,{value:"details",className:"mt-4",children:e.jsx(we,{children:e.jsxs(Ie,{className:"p-6 space-y-4",children:[e.jsx(pT,{label:"Visibility",value:N.visibility}),e.jsx(pT,{label:"Onboarding Required",value:N.require_onboarding?"Yes":"No"}),e.jsx(pT,{label:"Allow Spouse",value:N.allow_spouse?"Yes":"No"}),e.jsx(pT,{label:"Notify Client on Updates",value:N.notify_client?"Yes":"No"}),e.jsx(pT,{label:"Show Post-Close Tips",value:N.show_post_close_tips?"Yes":"No"}),e.jsx(pT,{label:"Slug",value:N.slug,mono:!0}),e.jsx(pT,{label:"Created",value:_B(N.created_at)}),e.jsx(pT,{label:"Last Updated",value:_B(N.updated_at)}),e.jsx("div",{className:"pt-2",children:e.jsxs(U,{variant:"outline",onClick:()=>m(!0),children:[e.jsx(qc,{className:"w-4 h-4 mr-2"})," Edit All Settings"]})})]})})})]})]}),e.jsx(grt,{open:h,onOpenChange:m,portal:N,dealOwnerId:n||""}),e.jsx(xrt,{open:p,onOpenChange:f,portalId:N.id,portalSlug:N.slug,notifyClient:N.notify_client}),e.jsx(yrt,{open:x,onOpenChange:y,portal:N,dealName:L}),e.jsx(Fl,{open:v,onOpenChange:b,children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Permanently delete this portal?"}),e.jsx(Ll,{children:"This removes the portal and all its updates. The client will lose access. This action cannot be undone."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:K,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function Pce({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 pT({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 SKe=[{value:"video_intro",label:"Video Intro",icon:Wr,description:"Add an intro video"},{value:"testimonials",label:"Testimonials",icon:EA,description:"Client testimonials carousel"},{value:"specialties",label:"Specialties",icon:Cf,description:"Tags for your specialties"},{value:"custom_links",label:"Custom Links",icon:ad,description:"Custom CTA buttons"},{value:"social_media",label:"Social Media",icon:jd,description:"Links to your social profiles"}],AXn=["First-Time Buyers","Luxury Homes","Investment Properties","Relocation","New Construction","Condos & Townhomes","Waterfront","Commercial","Land & Lots","Senior Living","Military/VA","Short Sales & Foreclosures"],EXn={video_intro:{video_url:""},testimonials:{testimonials:[{name:"",quote:"",role:""}]},specialties:{tags:[]},custom_links:{links:[{label:"",url:""}]},social_media:{platforms:[]}};function Dts({cardId:s}){const{data:t,isLoading:n}=qAs(s),r=$As(),a=VAs(),i=HAs(),[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:EXn[c]||{}},{onSuccess:()=>{o(!1),d("")}})},p=b=>{a.mutate({id:b.id,is_visible:!b.is_visible})},f=(b,N)=>{if(!t)return;const S=t.findIndex(L=>L.id===b.id),A=N==="up"?S-1:S+1;if(A<0||A>=t.length)return;const T=t[A];a.mutate({id:b.id,sort_order:T.sort_order}),a.mutate({id:T.id,sort_order:b.sort_order})},x=async b=>{await Yi("Remove this block from this card?")&&i.mutate(b.id)},y=(b,N)=>{a.mutate({id:b.id,config:N},{onSuccess:()=>h(null)})},v=b=>SKe.find(N=>N.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(U,{size:"sm",onClick:()=>o(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-1"})," Add Block"]})]}):e.jsxs(e.Fragment,{children:[t.map((b,N)=>{const S=v(b.block_type),A=(S==null?void 0:S.icon)||Cf;return e.jsx(we,{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(kf,{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:TXn(b)})]}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(U,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>f(b,"up"),disabled:N===0,children:e.jsx(cp,{className:"h-3 w-3"})}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>f(b,"down"),disabled:N===t.length-1,children:e.jsx(ag,{className:"h-3 w-3"})}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>p(b),children:b.is_visible?e.jsx(xa,{className:"h-3 w-3"}):e.jsx(Vg,{className:"h-3 w-3"})}),e.jsx(U,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>h(b),children:"Edit"}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>x(b),children:e.jsx(In,{className:"h-3 w-3"})})]})]})})},b.id)}),e.jsxs(U,{variant:"outline",size:"sm",className:"w-full",onClick:()=>o(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-1"})," Add Block"]})]}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Add Block"})}),e.jsx("div",{className:"grid gap-3",children:SKe.map(b=>{const N=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(N,{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(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(U,{onClick:m,disabled:!c||r.isPending,children:"Add Block"})]})]})}),u&&e.jsx(MXn,{block:u,onSave:b=>y(u,b),onClose:()=>h(null)})]})}function TXn(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 MXn({block:s,onSave:t,onClose:n}){const[r,a]=j.useState(s.config),i=SKe.find(l=>l.value===s.block_type);return e.jsx(zs,{open:!0,onOpenChange:n,children:e.jsxs(Ds,{className:"max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsxs($s,{children:["Edit ",i==null?void 0:i.label]})}),s.block_type==="video_intro"&&e.jsx(PXn,{config:r,onChange:a,cardId:s.card_id}),s.block_type==="testimonials"&&e.jsx(LXn,{config:r,onChange:a}),s.block_type==="specialties"&&e.jsx(IXn,{config:r,onChange:a}),s.block_type==="custom_links"&&e.jsx(RXn,{config:r,onChange:a}),s.block_type==="social_media"&&e.jsx(DXn,{config:r,onChange:a}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(U,{onClick:()=>t(r),children:"Save"})]})]})})}function PXn({config:s,onChange:t,cardId:n}){var p,f;const[r,a]=j.useState(""),[i,l]=j.useState((p=s.video_url)!=null&&p.includes("youtube")||(f=s.video_url)!=null&&f.includes("youtu.be")?"youtube":"library"),{data:o}=ct({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}=ct({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 N;const y=(N=x.playback_url)==null?void 0:N.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(oa,{value:i,onValueChange:l,children:[e.jsxs(la,{className:"w-full",children:[e.jsx(Kt,{value:"library",className:"flex-1",children:"Video Library"}),e.jsx(Kt,{value:"youtube",className:"flex-1",children:"YouTube URL"})]}),e.jsxs(Zt,{value:"library",className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search videos...",value:r,onChange:x=>a(x.target.value),className:"pl-9"})]}),e.jsx(Gi,{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(Wr,{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(Xr,{className:"h-4 w-4 text-primary flex-shrink-0"})]},x.id))})})]}),e.jsx(Zt,{value:"youtube",className:"space-y-3 mt-3",children:e.jsxs("div",{children:[e.jsx(te,{children:"YouTube URL"}),e.jsx(xe,{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 LXn({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(we,{children:e.jsxs(Ie,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(te,{className:"text-xs font-medium",children:["Testimonial ",o+1]}),n.length>1&&e.jsx(U,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>i(o),children:e.jsx(In,{className:"h-3 w-3"})})]}),e.jsx(xe,{placeholder:"Client name",value:l.name,onChange:c=>r(o,"name",c.target.value)}),e.jsx(xe,{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(U,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(an,{className:"h-4 w-4 mr-1"})," Add Testimonial"]})]})}function IXn({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(te,{className:"text-sm mb-2 block",children:"Preset Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:AXn.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(te,{className:"text-sm mb-2 block",children:"Custom Tag"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{placeholder:"Add your own...",value:r,onChange:o=>a(o.target.value),onKeyDown:o=>o.key==="Enter"&&(o.preventDefault(),l())}),e.jsx(U,{variant:"outline",size:"sm",onClick:l,children:"Add"})]})]}),n.length>0&&e.jsxs("div",{children:[e.jsxs(te,{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 RXn({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(xe,{placeholder:"Button label",value:l.label,onChange:c=>r(o,"label",c.target.value)}),e.jsx(xe,{placeholder:"https://...",value:l.url,onChange:c=>r(o,"url",c.target.value)})]}),n.length>1&&e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8 mt-1 text-destructive",onClick:()=>i(o),children:e.jsx(In,{className:"h-3 w-3"})})]},o)),e.jsxs(U,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(an,{className:"h-4 w-4 mr-1"})," Add Link"]})]})}const ASt=[{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 DXn({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=ASt.filter(c=>!n.find(d=>d.platform===c.value)),o=c=>{const d=Aqe[c],u=ASt.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(xe,{placeholder:`Your ${u.label} profile URL`,value:c.url,onChange:h=>a(d,h.target.value)})}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive flex-shrink-0",onClick:()=>i(d),children:e.jsx(In,{className:"h-3.5 w-3.5"})})]},d)})}),l.length>0&&e.jsxs("div",{children:[e.jsx(te,{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=Aqe[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 OXn({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(te,{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(fS,{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(U,{variant:"outline",size:"sm",onClick:a,className:"gap-1.5",children:[e.jsx(pi,{className:"h-3.5 w-3.5"}),"Download PNG"]})]})]})]})}function pze(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 FXn(){const{user:s}=vs(),{data:t,isLoading:n}=zAs(s==null?void 0:s.id),r=JG(),[a,i]=j.useState(null),l=j.useMemo(()=>a||(t?pze(t):null),[a,t]);if(n)return e.jsx(qs,{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(qs,{children:e.jsx(BXn,{userId:s==null?void 0:s.id})});const o=l||pze(t),c=d=>{i(u=>{const h=u||pze(t);return typeof d=="function"?d(h):d})};return e.jsx(qs,{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(UXn,{card:t}),e.jsx(HXn,{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(X2,{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(zXn,{card:t,form:o})})]})})]})})}function zXn({card:s,form:t}){const{data:n}=ct({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(UXe,{card:r})})}function BXn({userId:s}){var c;const[t,n]=j.useState(""),r=pRt(),{data:a}=ct({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:fl,title:"Shareable Link",desc:"One link that works everywhere"},{icon:Af,title:"Lead Capture",desc:"Collect leads automatically"},{icon:Im,title:"Always Up-to-Date",desc:"Edit anytime, changes are instant"},{icon:$c,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(cn,{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(we,{className:"shadow-lg border-2",children:[e.jsxs(Tt,{className:"text-center pb-2",children:[e.jsx(It,{className:"text-xl",children:"Set Up Your Card"}),e.jsx(Jn,{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(te,{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(xe,{value:t||i,onChange:d=>n(d.target.value),placeholder:"your-name",className:"rounded-l-none"})]})]}),e.jsxs(U,{onClick:l,disabled:r.isPending,className:"w-full h-11 text-base font-semibold",size:"lg",children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),r.isPending?"Creating...":"Create My Card"]})]})]})]})}function UXn({card:s}){const n=`https://cards.relevelup.com/${s.slug}`,r=()=>{navigator.clipboard.writeText(n),re.success("Card link copied!")};return e.jsx("div",{className:"rounded-xl border bg-card p-5",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-xl font-bold",children:"My Digital Card"}),e.jsx(Be,{variant:s.is_published?"default":"secondary",className:"text-[10px] uppercase tracking-wider",children:s.is_published?"Live":"Draft"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(fl,{className:"h-3.5 w-3.5"}),"cards.relevelup.com/",s.slug]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{variant:"outline",size:"sm",onClick:r,className:"gap-1.5",children:[e.jsx(Pa,{className:"h-3.5 w-3.5"})," Copy Link"]}),e.jsx(U,{size:"sm",asChild:!0,className:"gap-1.5",children:e.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Sr,{className:"h-3.5 w-3.5"})," Preview"]})})]})]})})}function qXn({userId:s}){const t=Qt(),n=j.useRef(null),[r,a]=j.useState(!1),[i,l]=j.useState(""),{data:o,isLoading:c}=ct({queryKey:["card-editor-profile",s],queryFn:async()=>{const{data:z}=await q.from("profiles").select("name, email, phone, avatar_url").eq("id",s).single();let $=(z==null?void 0:z.avatar_url)||null;if(!$){const{data:H}=await q.storage.from("avatars").list(`${s}`);if(H&&H.length>0){const{data:V}=q.storage.from("avatars").getPublicUrl(`${s}/${H[0].name}`);$=`${V.publicUrl}?t=${Date.now()}`,await q.from("profiles").update({avatar_url:$}).eq("id",s)}}return{...z,avatar_url:$}}}),[d,u]=j.useState(null),[h,m]=j.useState(null),[p,f]=j.useState(null),[x,y]=j.useState(!1),v=d??(o==null?void 0:o.name)??"",b=h??(o==null?void 0:o.phone)??"",N=p??(o==null?void 0:o.email)??"",S=o==null?void 0:o.avatar_url,A=((o==null?void 0:o.name)||"A").split(" ").map(z=>z[0]).join("").toUpperCase().slice(0,2),T=!(o!=null&&o.avatar_url)||!(o!=null&&o.phone),L=yt({mutationFn:async z=>{const{error:$}=await q.from("profiles").update(z).eq("id",s);if($)throw $},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")}),M=()=>{const z={};if(d!==null&&d!==(o==null?void 0:o.name)&&(z.name=d),h!==null&&h!==(o==null?void 0:o.phone)&&(z.phone=h||null),p!==null&&p!==(o==null?void 0:o.email)&&(z.email=p),Object.keys(z).length===0){re.info("No changes to save");return}L.mutate(z)},I=z=>{var V;const $=(V=z.target.files)==null?void 0:V[0];if(!$)return;if(!$.type.startsWith("image/")){re.error("Please select an image file");return}const H=new FileReader;H.onloadend=()=>{l(H.result),a(!0)},H.readAsDataURL($),z.target.value=""},R=async z=>{y(!0);try{const{data:$}=await q.storage.from("avatars").list(`${s}`);$&&$.length>0&&await q.storage.from("avatars").remove($.map(Q=>`${s}/${Q.name}`));const H=`${s}/avatar.jpg`,{error:V}=await q.storage.from("avatars").upload(H,z,{upsert:!0,contentType:"image/jpeg"});if(V)throw V;const{data:K}=q.storage.from("avatars").getPublicUrl(H),Z=K.publicUrl+"?t="+Date.now();await q.from("profiles").update({avatar_url:Z}).eq("id",s),t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),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(we,{className:T?"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(te,{className:"text-sm font-semibold",children:"Profile Info"}),T&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400 font-medium",children:[e.jsx(Vo,{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 z;return(z=n.current)==null?void 0:z.click()},children:[e.jsxs(Ea,{className:"h-16 w-16 ring-2 ring-muted",children:[e.jsx(Ci,{src:S||void 0,alt:v}),e.jsx(Ta,{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(_x,{className:"h-5 w-5 text-white"})}),e.jsx("input",{ref:n,type:"file",accept:"image/*",className:"hidden",onChange:I})]}),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(te,{className:"text-xs font-medium text-muted-foreground",children:"Full Name"}),e.jsx(xe,{value:v,onChange:z=>u(z.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(te,{className:"text-xs font-medium text-muted-foreground",children:"Phone Number"}),e.jsx(xe,{value:b,onChange:z=>m(z.target.value),placeholder:"(555) 123-4567",className:"h-10",type:"tel"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs font-medium text-muted-foreground",children:"Email"}),e.jsx(xe,{value:N,onChange:z=>f(z.target.value),placeholder:"you@example.com",className:"h-10",type:"email"})]})]})]}),e.jsx(U,{variant:"outline",size:"sm",onClick:M,disabled:L.isPending,className:"w-full",children:L.isPending?"Saving...":"Update Profile Info"})]})}),e.jsx(LJe,{open:r,onClose:()=>a(!1),imageSrc:i,onCropComplete:R,aspectRatio:1})]})}function $Xn({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=p=>{l(p),t(p==="name"?f=>({...f,brokerage_logo_url:""}):f=>({...f,brokerage_display_name:""}))},u=p=>{c(p),t(p==="name"?f=>({...f,team_logo_url:""}):f=>({...f,team_name:""}))},h=async(p,f)=>{var y;const x=(y=p.target.files)==null?void 0:y[0];if(x){if(!x.type.startsWith("image/")){re.error("Please select an image file");return}a(f);try{const v=x.name.split(".").pop()||"png",N=`${n}/${f==="brokerage_logo_url"?"brokerage-logo":"team-logo"}.${v}`,{error:S}=await q.storage.from("card-logos").upload(N,x,{upsert:!0});if(S)throw S;const{data:A}=q.storage.from("card-logos").getPublicUrl(N),T=A.publicUrl+"?t="+Date.now();t(f==="brokerage_logo_url"?L=>({...L,[f]:T,brokerage_display_name:""}):L=>({...L,[f]:T,team_name:""})),re.success("Logo uploaded!")}catch{re.error("Failed to upload logo")}finally{a(null),p.target.value=""}}},m=p=>{t(f=>({...f,[p]:""}))};return e.jsx(we,{children:e.jsxs(Ie,{className:"p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx(te,{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(te,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{type:"button",variant:i==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>d("name"),children:"Use Name"}),e.jsx(U,{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(te,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Name"}),e.jsx(xe,{value:s.brokerage_display_name,onChange:p=>t(f=>({...f,brokerage_display_name:p.target.value})),placeholder:"e.g. Keller Williams Realty",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(te,{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(_x,{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:p=>h(p,"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(te,{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(rg,{value:[s.brokerage_logo_size||56],onValueChange:([p])=>t(f=>({...f,brokerage_logo_size:p})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(te,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{type:"button",variant:o==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>u("name"),children:"Use Name"}),e.jsx(U,{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(te,{className:"text-xs font-medium text-muted-foreground",children:"Team Name"}),e.jsx(xe,{value:s.team_name,onChange:p=>t(f=>({...f,team_name:p.target.value})),placeholder:"e.g. The Smith Group",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(te,{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(_x,{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:p=>h(p,"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(te,{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(rg,{value:[s.team_logo_size||56],onValueChange:([p])=>t(f=>({...f,team_logo_size:p})),min:24,max:120,step:4})]})]})]})]})})}function VXn({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(te,{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx($c,{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(U,{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(xe,{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 HXn({card:s,form:t,setForm:n}){var x;const r=fRt(),a=Qt(),{data:i}=gRt(s.id),[l,o]=j.useState(s.slug),[c,d]=j.useState(!1),[u,h]=j.useState("idle"),m=j.useRef(JSON.stringify(t)),p=j.useRef(null);j.useEffect(()=>{const y=JSON.stringify(t);if(y!==m.current)return p.current&&clearTimeout(p.current),p.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),()=>{p.current&&clearTimeout(p.current)}},[t]);const f=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(oa,{defaultValue:"content",children:[e.jsxs(la,{className:"w-full h-11 p-1",children:[e.jsxs(Kt,{value:"content",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(oy,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Content"]}),e.jsxs(Kt,{value:"sections",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(xa,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Sections"]}),e.jsxs(Kt,{value:"blocks",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Af,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Blocks"]}),e.jsxs(Kt,{value:"qrcode",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Sf,{className:"h-3.5 w-3.5 hidden sm:inline"}),"QR Code"]}),e.jsxs(Kt,{value:"analytics",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Ch,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Analytics"]})]}),e.jsxs(Zt,{value:"content",className:"mt-4 space-y-4",children:[e.jsx(qXn,{userId:s.user_id}),e.jsx($Xn,{form:t,setForm:n,userId:s.user_id}),e.jsx(we,{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(te,{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(wn,{checked:t.is_published,onCheckedChange:y=>n(v=>({...v,is_published:y}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{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(xe,{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(U,{variant:"outline",size:"sm",onClick:f,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(te,{className:"text-sm font-medium",children:"Card Email (Override)"}),e.jsx(xe,{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(te,{className:"text-sm font-medium",children:"Theme"}),e.jsxs(Ns,{value:t.theme,onValueChange:y=>n(v=>({...v,theme:y})),children:[e.jsx(ws,{className:"h-11",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"standard",children:"✨ Standard — Modern & Clean"}),e.jsx(et,{value:"luxury",children:"🌙 Luxury — Dark & Gold"}),e.jsx(et,{value:"bold",children:"🔥 Bold — Vibrant & Punchy"}),e.jsx(et,{value:"classic",children:"📋 Classic — Professional"})]})]})]}),t.theme==="bold"&&e.jsx(VXn,{form:t,setForm:n}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-sm font-medium",children:"Title / Tagline"}),e.jsx(xe,{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(te,{className:"text-sm font-medium",children:"Positioning Statement"}),e.jsx(xe,{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(te,{className:"text-sm font-medium",children:"Bio"}),e.jsx(Fs,{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(te,{className:"text-sm font-medium",children:"Review Snippet"}),e.jsx(xe,{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(te,{className:"text-sm font-medium",children:"Review Source URL"}),e.jsx(xe,{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(te,{className:"text-sm font-medium",children:"Booking URL"}),e.jsx(xe,{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(te,{className:"text-sm font-medium",children:"Custom CTA Label"}),e.jsx(xe,{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(Zt,{value:"sections",className:"mt-4",children:e.jsx(we,{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(te,{className:"text-sm font-medium",children:v}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b})]}),e.jsx(wn,{checked:t[y],onCheckedChange:N=>n(S=>({...S,[y]:N}))})]},y))})})}),e.jsx(Zt,{value:"blocks",className:"mt-4",children:e.jsx(Dts,{cardId:s.id})}),e.jsx(Zt,{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:xa,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:Ch,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:zl,color:"text-emerald-600 bg-emerald-100 dark:text-emerald-400 dark:bg-emerald-900/30"}].map(y=>e.jsx(we,{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(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsx(It,{className:"text-base",children:"Recent Leads"})}),e.jsx(Ie,{className:"pt-0 space-y-2",children:i.leads.slice(0,5).map(y=>e.jsxs("div",{className:"flex items-center justify-between text-sm p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:y.name}),y.phone&&e.jsx("span",{className:"text-muted-foreground ml-2",children:y.phone})]}),y.intent&&e.jsx(Be,{variant:"secondary",className:"text-xs",children:y.intent})]},y.id))})]}),(!i||i.leads.length===0)&&e.jsx(we,{children:e.jsxs(Ie,{className:"p-8 text-center",children:[e.jsx(Ch,{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(Zt,{value:"qrcode",className:"mt-4 space-y-4",children:e.jsx(we,{children:e.jsx(Ie,{className:"p-6",children:e.jsx(OXn,{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 GXn(){const s=Qt(),[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),[p,f]=j.useState(null),[x,y]=j.useState(null),[v,b]=j.useState(0),[N,S]=j.useState(""),[A,T]=j.useState(!1),{data:L,isLoading:M}=ct({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:ue,error:se}=await q.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(se)throw se;return ue}}),I=yt({mutationFn:async ue=>{const{data:se,error:ne}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_token",api_token:ue}});if(ne)throw ne;if(se!=null&&se.error)throw new Error(se.error);return se},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),n(""),re.success("BoldTrail connected successfully!")},onError:ue=>{re.error(ue.message||"Failed to connect BoldTrail")}}),R=yt({mutationFn:async()=>{const{data:ue,error:se}=await q.functions.invoke("boldtrail-sync",{body:{action:"disconnect"}});if(se)throw se;return ue},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),re.success("BoldTrail disconnected")},onError:()=>re.error("Failed to disconnect")}),z=yt({mutationFn:async ue=>{const{data:se,error:ne}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_direction",sync_direction:ue}});if(ne)throw ne;if(se!=null&&se.error)throw new Error(se.error);return se},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),re.success("Sync direction saved")},onError:ue=>{re.error(ue.message||"Failed to save sync direction")}}),$=yt({mutationFn:async()=>{const{data:ue,error:se}=await q.functions.invoke("boldtrail-sync",{body:{action:"detect_owner"}});if(se)throw se;if(ue!=null&&ue.error)throw new Error(ue.error);return ue},onSuccess:ue=>{if(s.invalidateQueries({queryKey:["boldtrail-status"]}),ue.kvcore_user_id){const se=ue.detected_name||ue.detected_email||`ID ${ue.kvcore_user_id}`;re.success(`Detected your BoldTrail account: ${se}`)}else if(ue.candidates&&ue.candidates.length>0){const se=ue.candidates.slice(0,5).map(ne=>`${ne.id} (${ne.count} contacts)`).join(", ");re.warning(`Couldn't auto-detect your ID. Owner IDs found in your contacts: ${se}. Pick yours and enter it below.`,{duration:12e3}),T(!0)}else re.warning("Couldn't auto-detect your BoldTrail user ID. Please find it in BoldTrail (My Profile URL) and enter it manually."),T(!0)},onError:ue=>re.error(ue.message||"Detection failed")}),H=yt({mutationFn:async ue=>{const{data:se,error:ne}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_owner_settings",...ue}});if(ne)throw ne;if(se!=null&&se.error)throw new Error(se.error);return se},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),re.success("Settings saved"),T(!1)},onError:ue=>re.error(ue.message||"Failed to save settings")}),V=yt({mutationFn:async()=>{const{data:ue,error:se}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(se)throw se;if(ue!=null&&ue.error)throw new Error(ue.error);return ue},onSuccess:ue=>{f(null),c(ue),a(!0)},onError:ue=>{re.error(ue.message||"Failed to generate sync preview")}}),K=yt({mutationFn:async()=>{y("Initializing sync..."),b(5);const{data:ue,error:se}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:le}});if(se)throw se;if(ue!=null&&ue.error)throw new Error(ue.error);const ne=ue;let ie=ne.sync_log_id,ce=ne.next_phase,je=ne.next_offset,be=ne.push_total||0,he=ne.pull_total||0,ge=0,ke=0;for(;ce!=="finalize";){const Oe=be+he;ce==="fetch_bt"?y("Fetching BoldTrail contacts..."):ce==="analyze"?(y("Analyzing contacts..."),b(15)):ce==="push"?(y(`Pushing contacts to BoldTrail... (${ge}/${be})`),b(Oe>0?ge/Oe*100:0)):ce==="pull"&&(y(`Pulling contacts from BoldTrail... (${ke}/${he})`),b(Oe>0?(be+ke)/Oe*100:0));const{data:Se,error:Qe}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:ce,offset:je,sync_log_id:ie,sync_direction:le}});if(Qe)throw Qe;if(Se!=null&&Se.error)throw new Error(Se.error);const Ae=Se;ge+=Ae.chunk_pushed||0,ke+=Ae.chunk_pulled||0,Ae.push_total!==void 0&&(be=Ae.push_total||0),Ae.pull_total!==void 0&&(he=Ae.pull_total||0),Ae.progress&&y(Ae.progress),ce==="pull"&&he>0?b(Math.min(95,ke/he*100)):ce==="push"&&be>0&&b(Math.min(95,ge/be*100)),ce=Ae.next_phase,je=Ae.next_offset}y("Finalizing sync..."),b(95);const{data:Te,error:Me}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:ie,sync_direction:le}});if(Me)throw Me;return b(100),Te},onSuccess:ue=>{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 ${ue.contacts_pushed||0}, pulled ${ue.contacts_pulled||0}, skipped ${ue.contacts_skipped||0} duplicates.`)},onError:ue=>{y(null),b(0),re.error(ue.message||"Sync failed")}}),Z=L==null?void 0:L.connected,Q=(L==null?void 0:L.sync_direction)||"bidirectional",le=p??Q;return e.jsxs(e.Fragment,{children:[e.jsxs(we,{children:[e.jsx(Tt,{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(xx,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsxs(It,{className:"text-lg flex items-center gap-2",children:["BoldTrail",Z&&e.jsx(Be,{variant:"default",className:"text-xs bg-green-600",children:"Connected"}),e.jsxs("button",{onClick:()=>l(!0),className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx($h,{className:"h-3.5 w-3.5"}),"Learn More"]})]}),e.jsx(Jn,{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(Yo,{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(Yo,{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(Yo,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Syncs name, email, phone, address, notes, and lead source"})]}),Z?e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsx("div",{className:"rounded-lg border p-3 space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"BoldTrail Connected"}),(L==null?void 0:L.last_sync_at)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sync: ",new Date(L.last_sync_at).toLocaleString(),L.last_sync_status&&e.jsx(Be,{variant:L.last_sync_status==="success"?"default":"secondary",className:"ml-2 text-[10px]",children:L.last_sync_status})]}),(L==null?void 0:L.boldtrail_contact_count)!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[L.boldtrail_contact_count," contacts in BoldTrail"]}),(L==null?void 0:L.last_sync_message)&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:L.last_sync_message})]}),e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(In,{className:"h-4 w-4"})})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Disconnect BoldTrail?"}),e.jsx(Ll,{children:"This will remove your API token. Previously synced contacts will remain in both systems."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>R.mutate(),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]})}),e.jsxs("div",{className:"rounded-lg border p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(tN,{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(wn,{checked:!!(L!=null&&L.sync_only_owned),onCheckedChange:ue=>H.mutate({sync_only_owned:ue}),disabled:H.isPending})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{className:"text-xs",children:"Your BoldTrail Agent ID"}),A?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"number",placeholder:"e.g. 12345",value:N,onChange:ue=>S(ue.target.value),className:"h-8 text-sm"}),e.jsx(U,{size:"sm",onClick:()=>{const ue=N.trim()===""?null:Number(N);H.mutate({kvcore_user_id:ue})},disabled:H.isPending,children:"Save"}),e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>T(!1),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-mono",children:(L==null?void 0:L.kvcore_user_id)??e.jsx("span",{className:"text-muted-foreground",children:"Not set"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>$.mutate(),disabled:$.isPending,children:[$.isPending?e.jsx(no,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Auto-detect"]}),e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>{var ue;S(((ue=L==null?void 0:L.kvcore_user_id)==null?void 0:ue.toString())??""),T(!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(REe,{value:Q,onChange:ue=>z.mutate(ue)})}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(U,{onClick:()=>V.mutate(),disabled:V.isPending||K.isPending,variant:"outline",className:"gap-2",children:[V.isPending?e.jsx(no,{className:"h-4 w-4 animate-spin"}):e.jsx(xa,{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(xe,{type:"password",placeholder:"Paste your BoldTrail API token",value:t,onChange:ue=>n(ue.target.value),className:"flex-1"}),e.jsxs(U,{onClick:()=>I.mutate(t),disabled:!t||t.length<10||I.isPending,children:[I.isPending?e.jsx(no,{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:ue=>{K.isPending||a(ue)},children:e.jsxs(Ds,{className:"sm:max-w-lg",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(xx,{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 ue=le==="pull_only"?0:o.to_push,se=le==="push_only"?0:o.to_pull;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(REe,{value:le,onChange:f,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(tN,{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 ${le==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:ue}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(cp,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${le==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:se}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(ag,{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(Bn,{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"]}),K.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(ro,{value:v||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:x||"Sync in progress..."})]}),ue>0&&e.jsxs(ub,{open:d,onOpenChange:u,children:[e.jsx(hb,{asChild:!0,children:e.jsxs(U,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(cp,{className:"h-3 w-3 text-emerald-600"}),ue," contacts to push to BoldTrail"]}),e.jsx(rl,{className:`h-3 w-3 transition-transform ${d?"rotate-180":""}`})]})}),e.jsx(mb,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.push_preview.map((ne,ie)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:ne.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:ne.email})]},ie)),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"]})]})})]}),se>0&&e.jsxs(ub,{open:h,onOpenChange:m,children:[e.jsx(hb,{asChild:!0,children:e.jsxs(U,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ag,{className:"h-3 w-3 text-blue-600"}),se," contacts to pull from BoldTrail"]}),e.jsx(rl,{className:`h-3 w-3 transition-transform ${h?"rotate-180":""}`})]})}),e.jsx(mb,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.pull_preview.map((ne,ie)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:ne.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:ne.email})]},ie)),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"]})]})})]}),ue===0&&se===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(U,{variant:"outline",onClick:()=>a(!1),disabled:K.isPending,children:"Cancel"}),e.jsxs(U,{onClick:()=>K.mutate(),disabled:K.isPending||ue===0&&se===0,className:"gap-2",children:[K.isPending?e.jsx(no,{className:"h-4 w-4 animate-spin"}):e.jsx(xx,{className:"h-4 w-4"}),K.isPending?"Syncing...":"Sync Now"]})]})]})})()]})}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Ds,{className:"sm:max-w-2xl p-0 overflow-hidden",children:[e.jsx(Vs,{className:"p-6 pb-0",children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(xx,{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 wB=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 WXn(){const s=Qt(),[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:p,isLoading:f}=ct({queryKey:["lofty-status"],queryFn:async()=>await wB({action:"status"})}),x=()=>s.invalidateQueries({queryKey:["lofty-status"]}),y=yt({mutationFn:async()=>wB({action:"save_token",api_token:t.trim()}),onSuccess:T=>{re.success(T!=null&&T.contact_count?`Connected to Lofty — ${T.contact_count} contacts found`:"Connected to Lofty"),n(""),x()},onError:T=>re.error(T.message)}),v=yt({mutationFn:async()=>wB({action:"disconnect"}),onSuccess:()=>{re.success("Lofty disconnected"),x()},onError:T=>re.error(T.message)}),b=yt({mutationFn:async T=>wB({action:"save_settings",...T}),onSuccess:()=>x(),onError:T=>re.error(T.message)}),N=yt({mutationFn:async()=>wB({action:"detect_owner"}),onSuccess:T=>{const L=(T==null?void 0:T.candidates)||[];m(L),L.length===0?re.info("No assigned-agent IDs found on your Lofty contacts."):L.length===1?(b.mutate({lofty_user_id:L[0].id}),re.success(`Using Lofty agent ID ${L[0].id}`)):re.success("Pick which Lofty agent ID is yours below.")},onError:T=>re.error(T.message)}),S=async()=>{l(!0),c(2),u("Starting Lofty sync…");try{let T="start",L=0,M=null,I=0;for(;T&&I<400;){I++;const R=await wB({action:"sync",phase:T,offset:L,sync_log_id:M});M=R.sync_log_id||M,R.progress&&u(R.progress),c(z=>Math.min(95,z+4)),T=R.next_phase,L=R.next_offset||0,T||(c(100),u(R.message||"Sync complete"),re.success(R.message||"Lofty sync complete"))}}catch(T){re.error(T.message||"Lofty sync failed"),u(null)}finally{l(!1),setTimeout(()=>c(0),2500),x()}},A=!!(p!=null&&p.connected);return e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(It,{className:"flex items-center gap-2",children:["Lofty",A?e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Yo,{className:"h-3 w-3"})," Connected"]}):e.jsx(Be,{variant:"outline",children:"Not connected"})]}),e.jsx(Jn,{children:"Sync your Lofty (formerly Chime) contacts — names, emails, phones, address, source, stage, tags and notes — into Agent OS."})]}),A&&e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon","aria-label":"Disconnect Lofty",children:e.jsx(In,{className:"h-4 w-4"})})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Disconnect Lofty?"}),e.jsx(Ll,{children:"Your API key and sync settings will be removed. Contacts already imported into Agent OS stay put."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>v.mutate(),children:"Disconnect"})]})]})]})]})}),e.jsx(Ie,{className:"space-y-5",children:f?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Et,{className:"h-4 w-4 animate-spin"})," Loading…"]}):A?e.jsxs("div",{className:"space-y-5",children:[e.jsx(REe,{value:(p==null?void 0:p.sync_direction)||"pull_only",onChange:T=>b.mutate({sync_direction:T}),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(wn,{checked:!!(p!=null&&p.sync_only_owned),onCheckedChange:T=>b.mutate({sync_only_owned:T})})]}),(p==null?void 0:p.sync_only_owned)&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>N.mutate(),disabled:N.isPending,children:[N.isPending?e.jsx(Et,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Bn,{className:"h-3.5 w-3.5"}),"Detect my Lofty agent ID"]}),(p==null?void 0:p.lofty_user_id)&&e.jsxs(Be,{variant:"secondary",children:["Agent ID ",p.lofty_user_id]})]}),h&&h.length>1&&e.jsx("div",{className:"flex flex-wrap gap-2",children:h.map(T=>e.jsxs(U,{size:"sm",variant:(p==null?void 0:p.lofty_user_id)===T.id?"default":"outline",onClick:()=>b.mutate({lofty_user_id:T.id}),children:[T.id," · ",T.count," contacts"]},T.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(wn,{checked:!!(p!=null&&p.import_notes),onCheckedChange:T=>b.mutate({import_notes:T})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"lofty-tags",className:"text-sm",children:"Tag filter (optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{id:"lofty-tags",placeholder:((p==null?void 0:p.pull_tag_filter)||[]).join(", ")||"e.g. Sphere, Buyer",value:r,onChange:T=>a(T.target.value)}),e.jsx(U,{variant:"outline",onClick:()=>b.mutate({pull_tag_filter:r.split(",").map(T=>T.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(U,{onClick:S,disabled:i,children:[i?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(no,{className:"h-4 w-4"}),i?"Syncing…":"Sync Now"]}),(p==null?void 0:p.last_sync_at)&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Last sync ",new Date(p.last_sync_at).toLocaleString("en-US",{timeZone:"America/New_York"})]})]}),(i||o>0)&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(ro,{value:o}),d&&e.jsx("p",{className:"text-xs text-muted-foreground",children:d})]}),(p==null?void 0:p.last_sync_message)&&!i&&e.jsx("p",{className:"text-xs text-muted-foreground",children:p.last_sync_message})]}),((p==null?void 0:p.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:p.logs.map(T=>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(T.created_at).toLocaleString("en-US",{timeZone:"America/New_York"})}),e.jsxs("span",{children:[T.contacts_pulled," imported · ",T.contacts_pushed," pushed ·"," ",T.contacts_skipped," skipped"]}),e.jsx(Be,{variant:T.status==="completed"?"secondary":"destructive",children:T.status})]},T.id))})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"lofty-key",children:"Lofty API Key"}),e.jsx(xe,{id:"lofty-key",type:"password",placeholder:"Paste your Lofty API key",value:t,onChange:T=>n(T.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(U,{onClick:()=>y.mutate(),disabled:t.trim().length<10||y.isPending,children:[y.isPending?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(J2,{className:"h-4 w-4"}),"Connect Lofty"]}),e.jsx(U,{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(Sr,{className:"ml-1 h-3 w-3"})]})})]})]})})]})}function KXn(){const s=Qt(),[t,n]=j.useState(""),[r,a]=j.useState(!1),[i,l]=j.useState(0),[o,c]=j.useState(null),{data:d,isLoading:u}=ct({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=yt({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=yt({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"]})}}),p=yt({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"]})}),f=async()=>{a(!0),l(0),c("Pulling from FUB…");let x=0,y=0,v=0,b=0;try{for(;;){const{data:T,error:L}=await q.functions.invoke("followupboss-sync",{body:{action:"sync",offset:x}});if(L)throw L;if(T!=null&&T.error)throw new Error(T.error);y+=T.chunk_created||0,v+=T.chunk_updated||0,b+=T.chunk_skipped||0,x=T.next_offset;const M=T.total?Math.min(100,Math.round(x/T.total*100)):100;if(l(M),c(`Pulling · ${x} / ${T.total||"?"}`),T.done)break;await new Promise(I=>setTimeout(I,400))}let N=0,S=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let T=0;for(l(0),c("Pushing to FUB…");;){const{data:L,error:M}=await q.functions.invoke("followupboss-sync",{body:{action:"push",offset:T}});if(M)throw M;if(L!=null&&L.error)throw new Error(L.error);N+=L.chunk_pushed||0,S+=L.chunk_failed||0,T=L.next_offset;const I=L.total?Math.min(100,Math.round(T/L.total*100)):100;if(l(I),c(`Pushing · ${T} / ${L.total||"?"}`),L.done)break;await new Promise(R=>setTimeout(R,400))}}const A=N||S?` · pushed ${N}${S?`, ${S} failed`:""}`:"";re.success(`Sync complete · ${y} new, ${v} updated${b?`, ${b} skipped`:""}${A}`),s.invalidateQueries({queryKey:["fub-status"]})}catch(N){re.error(N.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(J2,{className:"h-5 w-5 text-primary"}),"Follow Up Boss",(d==null?void 0:d.connected)&&e.jsxs(Be,{variant:"default",className:"ml-1",children:[e.jsx(Yo,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Jn,{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(wn,{checked:d.sync_direction==="bidirectional",onCheckedChange:x=>p.mutate(x?"bidirectional":"pull_only"),disabled:r||p.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(ro,{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(U,{onClick:f,disabled:r,children:[e.jsx(no,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsxs(U,{variant:"outline",disabled:r,children:[e.jsx(In,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Disconnect Follow Up Boss?"}),e.jsx(Ll,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>m.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(te,{htmlFor:"fub-key",children:"Follow Up Boss API Key"}),e.jsx(xe,{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(Sr,{className:"h-3 w-3"})]})]})]}),e.jsx(U,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function YXn(){var V;const s=Qt(),[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),[p,f]=j.useState(null),[x,y]=j.useState(!1),[v,b]=j.useState(new Set),{data:N,isLoading:S}=ct({queryKey:["cloze-status"],queryFn:async()=>{const{data:K,error:Z}=await q.functions.invoke("cloze-sync",{body:{action:"status"}});if(Z)throw Z;return K}}),A=yt({mutationFn:async()=>{const{data:K,error:Z}=await q.functions.invoke("cloze-sync",{body:{action:"save_token",api_key:t.trim(),account_email:r.trim()}});if(Z)throw Z;if(K!=null&&K.error)throw new Error(K.error);return K},onSuccess:()=>{re.success("Connected to Cloze"),n(""),a(""),s.invalidateQueries({queryKey:["cloze-status"]})},onError:K=>re.error(K.message)}),T=yt({mutationFn:async()=>{const{error:K}=await q.functions.invoke("cloze-sync",{body:{action:"disconnect"}});if(K)throw K},onSuccess:()=>{re.success("Cloze disconnected"),s.invalidateQueries({queryKey:["cloze-status"]})}}),L=yt({mutationFn:async K=>{const{error:Z}=await q.functions.invoke("cloze-sync",{body:{action:"set_direction",sync_direction:K}});if(Z)throw Z},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),M=yt({mutationFn:async K=>{const{error:Z}=await q.functions.invoke("cloze-sync",{body:{action:"set_scope",...K}});if(Z)throw Z},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),I=async()=>{y(!0);try{const{data:K,error:Z}=await q.functions.invoke("cloze-sync",{body:{action:"list_segments"}});if(Z)throw Z;if(K!=null&&K.error)throw new Error(K.error);f(K.segments||[]),b(new Set((N==null?void 0:N.selected_segments)||[])),m(!0)}catch(K){re.error(K.message||"Failed to load segments")}finally{y(!1)}},R=async()=>{const K=Array.from(v);await M.mutateAsync({sync_scope:"segments",selected_segments:K}),re.success(`Saved · ${K.length} segment(s) selected`),m(!1)},z=async()=>{const K=(N==null?void 0:N.sync_direction)||"pull_only";l(!0),c(0);try{if(K==="pull_only"||K==="bidirectional"){u("Pulling from Cloze…");let Z=0,Q=0,le=0;for(;;){const{data:ue,error:se}=await q.functions.invoke("cloze-sync",{body:{action:"sync",offset:Z}});if(se)throw se;if(ue!=null&&ue.error)throw new Error(ue.error);if(Q+=ue.chunk_created||0,le+=ue.chunk_updated||0,Z=ue.next_offset,u(`Pulling · ${Q+le} contacts processed`),c(ue.done?100:Math.min(95,(Q+le)%200/2)),ue.done)break;await new Promise(ne=>setTimeout(ne,300))}re.success(`Pulled · ${Q} new, ${le} updated`)}if(K==="push_only"||K==="bidirectional"){c(0),u("Pushing to Cloze…");let Z=0,Q=0,le=0;for(;;){const{data:ue,error:se}=await q.functions.invoke("cloze-sync",{body:{action:"push",offset:Z}});if(se)throw se;if(ue!=null&&ue.error)throw new Error(ue.error);Q+=ue.chunk_pushed||0,le+=ue.chunk_failed||0,Z=ue.next_offset;const ne=ue.total?Math.min(100,Math.round(Z/ue.total*100)):100;if(c(ne),u(`Pushing · ${Z} / ${ue.total||"?"}`),ue.done)break;await new Promise(ie=>setTimeout(ie,300))}re.success(`Pushed · ${Q}${le?`, ${le} failed`:""}`)}s.invalidateQueries({queryKey:["cloze-status"]})}catch(Z){re.error(Z.message||"Sync failed")}finally{l(!1),setTimeout(()=>{c(0),u(null)},2e3)}},$=(N==null?void 0:N.sync_scope)||"all",H=((V=N==null?void 0:N.selected_segments)==null?void 0:V.length)||0;return e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(J2,{className:"h-5 w-5 text-primary"}),"Cloze",(N==null?void 0:N.connected)&&e.jsxs(Be,{variant:"default",className:"ml-1",children:[e.jsx(Yo,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Jn,{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…"}):N!=null&&N.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:N.account_email})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last sync"}),e.jsx("p",{className:"font-medium",children:N.last_sync_at?new Date(N.last_sync_at).toLocaleString():"Never"})]})]}),N.last_sync_status==="error"&&e.jsx("p",{className:"text-sm text-destructive",children:N.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(Ns,{value:N.sync_direction||"pull_only",onValueChange:K=>L.mutate(K),disabled:i||L.isPending,children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"pull_only",children:"Pull from Cloze"}),e.jsx(et,{value:"push_only",children:"Push to Cloze"}),e.jsx(et,{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:$==="all"?"All Cloze contacts.":`${H} segment${H===1?"":"s"} selected.`})]}),e.jsxs(Ns,{value:$,onValueChange:K=>{K==="all"?M.mutate({sync_scope:"all",selected_segments:[]}):(M.mutate({sync_scope:"segments",selected_segments:N.selected_segments||[]}),I())},disabled:i||M.isPending,children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All contacts"}),e.jsx(et,{value:"segments",children:"Selected segments"})]})]})]}),$==="segments"&&e.jsxs("div",{children:[e.jsxs(U,{variant:"outline",size:"sm",onClick:I,disabled:x,children:[e.jsx(dQ,{className:"h-4 w-4 mr-2"}),x?"Loading segments…":"Choose segments"]}),h&&p&&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:[p.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-3",children:"No segments found in your Cloze account."}),p.map(K=>{const Z=v.has(K.id);return e.jsxs("label",{className:"flex items-center gap-3 p-2 cursor-pointer hover:bg-muted/50",children:[e.jsx(xi,{checked:Z,onCheckedChange:Q=>{const le=new Set(v);Q?le.add(K.id):le.delete(K.id),b(le)}}),e.jsx("span",{className:"flex-1 text-sm",children:K.name}),K.count!=null&&e.jsx(Be,{variant:"secondary",className:"text-xs",children:K.count})]},K.id)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{size:"sm",onClick:R,disabled:M.isPending,children:["Save selection (",v.size,")"]}),e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>m(!1),children:"Cancel"})]})]})]})]}),d&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(ro,{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(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsxs(U,{disabled:i,children:[e.jsx(no,{className:`h-4 w-4 mr-2 ${i?"animate-spin":""}`}),i?"Syncing…":"Sync Now"]})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Preview sync"}),e.jsx(Ll,{asChild:!0,children:e.jsx(ZXn,{segments:p})})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:z,children:"Start Sync"})]})]})]}),e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsxs(U,{variant:"outline",disabled:i,children:[e.jsx(In,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Disconnect Cloze?"}),e.jsx(Ll,{children:"Your API key will be removed. Contacts already synced will remain."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>T.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(te,{htmlFor:"cloze-email",children:"Cloze Account Email"}),e.jsx(xe,{id:"cloze-email",type:"email",placeholder:"you@example.com",value:r,onChange:K=>a(K.target.value)})]}),e.jsxs("div",{children:[e.jsx(te,{htmlFor:"cloze-key",children:"Cloze API Key"}),e.jsx(xe,{id:"cloze-key",type:"password",placeholder:"Your personal Cloze API key",value:t,onChange:K=>n(K.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(Sr,{className:"h-3 w-3"})]})]})]}),e.jsx(U,{onClick:()=>A.mutate(),disabled:!t.trim()||!r.trim()||A.isPending,children:A.isPending?"Connecting…":"Connect Cloze"})]})})]})}function ZXn({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:p}=await q.functions.invoke("cloze-sync",{body:{action:"preview"}});if(p)throw p;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 XXn(){const s=Qt(),[t,n]=j.useState(""),[r,a]=j.useState(!1),[i,l]=j.useState(0),[o,c]=j.useState(null),{data:d,isLoading:u}=ct({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=yt({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=yt({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"]})}}),p=yt({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"]})}),f=async()=>{a(!0),l(0),c("Pulling from Boomtown…");let x=0,y=0,v=0,b=0;try{for(;;){const{data:T,error:L}=await q.functions.invoke("boomtown-sync",{body:{action:"sync",offset:x}});if(L)throw L;if(T!=null&&T.error)throw new Error(T.error);y+=T.chunk_created||0,v+=T.chunk_updated||0,b+=T.chunk_skipped||0,x=T.next_offset;const M=T.total?Math.min(100,Math.round(x/T.total*100)):100;if(l(M),c(`Pulling · ${x} / ${T.total||"?"}`),T.done)break;await new Promise(I=>setTimeout(I,400))}let N=0,S=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let T=0;for(l(0),c("Pushing to Boomtown…");;){const{data:L,error:M}=await q.functions.invoke("boomtown-sync",{body:{action:"push",offset:T}});if(M)throw M;if(L!=null&&L.error)throw new Error(L.error);N+=L.chunk_pushed||0,S+=L.chunk_failed||0,T=L.next_offset;const I=L.total?Math.min(100,Math.round(T/L.total*100)):100;if(l(I),c(`Pushing · ${T} / ${L.total||"?"}`),L.done)break;await new Promise(R=>setTimeout(R,400))}}const A=N||S?` · pushed ${N}${S?`, ${S} failed`:""}`:"";re.success(`Sync complete · ${y} new, ${v} updated${b?`, ${b} skipped`:""}${A}`),s.invalidateQueries({queryKey:["boomtown-status"]})}catch(N){re.error(N.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(J2,{className:"h-5 w-5 text-primary"}),"Boomtown",(d==null?void 0:d.connected)&&e.jsxs(Be,{variant:"default",className:"ml-1",children:[e.jsx(Yo,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Jn,{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(wn,{checked:d.sync_direction==="bidirectional",onCheckedChange:x=>p.mutate(x?"bidirectional":"pull_only"),disabled:r||p.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(ro,{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(U,{onClick:f,disabled:r,children:[e.jsx(no,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsxs(U,{variant:"outline",disabled:r,children:[e.jsx(In,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Disconnect Boomtown?"}),e.jsx(Ll,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>m.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(te,{htmlFor:"boomtown-key",children:"Boomtown API Key"}),e.jsx(xe,{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(Sr,{className:"h-3 w-3"})]})]}),e.jsx(U,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function Ots(){const s=Wn(),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState("Test from ReLevelUp"),[o,c]=j.useState(!1),{data:d,isLoading:u}=ct({queryKey:["ses-config"],queryFn:async()=>{const p=await vte();return(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`},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 p=await vte(),x=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`},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(p){re.error(p.message||"Failed to send test email")}finally{c(!1)}},m=(d==null?void 0:d.configured)===!0;return e.jsxs(we,{children:[e.jsx(Tt,{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(ln,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsx(It,{className:"text-lg",children:"Amazon SES — Mass Email"}),e.jsx(Jn,{children:"Send bulk email campaigns via Amazon SES"})]})]}),e.jsx(Be,{variant:m?"default":"secondary",children:u?"Checking...":m?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yo,{className:"h-3 w-3"})," Connected"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vo,{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(te,{className:"text-xs",children:"From Email"}),e.jsx(xe,{placeholder:"notifications@mail.relevelup.com",value:r,onChange:p=>a(p.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{className:"text-xs",children:"To Email"}),e.jsx(xe,{placeholder:"your@email.com",value:t,onChange:p=>n(p.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{className:"text-xs",children:"Subject"}),e.jsx(xe,{value:i,onChange:p=>l(p.target.value),className:"text-sm"})]})]}),e.jsxs(U,{onClick:h,disabled:o,size:"sm",children:[o?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx($r,{className:"h-4 w-4 mr-2"}),"Send Test"]})]}),e.jsxs(U,{onClick:()=>s("/admin/email-campaigns"),className:"w-full",children:[e.jsx(Th,{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 fze(s){const t=await vte(),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 QXn({status:s}){return s==="verified"?e.jsxs(Be,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(zr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(Be,{variant:"secondary",children:[e.jsx(Yr,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(Be,{variant:"destructive",children:[e.jsx(Vo,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(Be,{variant:"outline",children:[e.jsx(Vo,{className:"h-3 w-3 mr-1"})," Not started"]})}function Fts({brokerageId:s,onVerifiedSelect:t}){const n=Qt(),[r,a]=j.useState(""),[i,l]=j.useState(""),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(null),{data:p,isLoading:f}=ct({queryKey:["brokerage-verified-senders",s],queryFn:async()=>{const{data:b,error:N}=await q.from("brokerage_verified_senders").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(N)throw N;return b||[]}}),x=yt({mutationFn:async()=>fze({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 N,S;u(b.id);try{const A=await fze({action:"check_status",sender_id:b.id});n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),((N=A.sender)==null?void 0:N.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=yt({mutationFn:async b=>fze({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."})]}),f?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):p&&p.length>0?e.jsx("div",{className:"space-y-2",children:p.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(ln,{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(QXn,{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(U,{size:"sm",variant:"outline",onClick:()=>t(b.email),children:"Use"}),b.status!=="verified"&&e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>y(b),disabled:d===b.id,title:"Refresh status from AWS",children:d===b.id?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(no,{className:"h-4 w-4"})}),e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>m(b),className:"text-destructive hover:text-destructive",children:e.jsx(In,{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(te,{className:"text-xs",children:"Email Address *"}),e.jsx(xe,{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(te,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(xe,{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(U,{size:"sm",onClick:()=>x.mutate(),disabled:!r.trim()||x.isPending,children:[x.isPending?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Fl,{open:!!h,onOpenChange:b=>!b&&m(null),children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Remove this sender?"}),e.jsxs(Ll,{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(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>h&&v.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}async function gze(s){const t=await vte(),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 JXn({status:s}){return s==="verified"?e.jsxs(Be,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(zr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(Be,{variant:"secondary",children:[e.jsx(Yr,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(Be,{variant:"destructive",children:[e.jsx(Vo,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(Be,{variant:"outline",children:[e.jsx(Vo,{className:"h-3 w-3 mr-1"})," Not started"]})}function eQn({userId:s,onVerifiedSelect:t}){const n=Qt(),[r,a]=j.useState(""),[i,l]=j.useState(""),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(null),{data:p,isLoading:f}=ct({queryKey:["user-verified-senders",s],queryFn:async()=>{const{data:b,error:N}=await q.from("user_verified_senders").select("*").eq("user_id",s).order("created_at",{ascending:!1});if(N)throw N;return b||[]}}),x=yt({mutationFn:async()=>gze({action:"request_verification",scope:"user",email:r,display_name:i||void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["user-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 N,S;u(b.id);try{const A=await gze({action:"check_status",sender_id:b.id});n.invalidateQueries({queryKey:["user-verified-senders",s]}),((N=A.sender)==null?void 0:N.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=yt({mutationFn:async b=>gze({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."]})]}),f?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):p&&p.length>0?e.jsx("div",{className:"space-y-2",children:p.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(ln,{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(JXn,{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(U,{size:"sm",variant:"outline",onClick:()=>t(b.email),children:"Use"}),b.status!=="verified"&&e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>y(b),disabled:d===b.id,title:"Refresh status from AWS",children:d===b.id?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(no,{className:"h-4 w-4"})}),e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>m(b),className:"text-destructive hover:text-destructive",children:e.jsx(In,{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(te,{className:"text-xs",children:"Email Address *"}),e.jsx(xe,{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(te,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(xe,{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(U,{size:"sm",onClick:()=>x.mutate(),disabled:!r.trim()||x.isPending,children:[x.isPending?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Fl,{open:!!h,onOpenChange:b=>!b&&m(null),children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Remove this sender?"}),e.jsxs(Ll,{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(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>h&&v.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function tQn(){var S,A,T,L,M;const{user:s,isBrokerageManager:t,isAdmin:n,managedBrokerages:r,selectedBrokerageId:a}=vs(),i=a||((S=r==null?void 0:r[0])==null?void 0:S.id)||null,l=(t||n)&&!!i,o=Qt(),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,p]=j.useState(""),{data:f}=ct({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:I,error:R}=await q.from("mass_email_settings").select("*").eq("user_id",s.id).maybeSingle();if(R)throw R;return I}}),{data:x}=ct({queryKey:["agent-profile-email",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:I,error:R}=await q.from("profiles").select("email, name").eq("id",s.id).single();if(R)throw R;return I}}),y=((A=f==null?void 0:f.reply_to_email)==null?void 0:A.trim())||((T=x==null?void 0:x.email)==null?void 0:T.trim())||"",v=((L=f==null?void 0:f.display_name)==null?void 0:L.trim())||((M=x==null?void 0:x.name)==null?void 0:M.trim())||"";j.useEffect(()=>{c||(h(y),p(v))},[c,y,v]);const b=yt({mutationFn:async()=>{if(!s||!u.trim())throw new Error("Please enter a reply-to email");const I={reply_to_email:u.trim(),display_name:m.trim()||null,updated_at:new Date().toISOString()};if(f){const{error:R}=await q.from("mass_email_settings").update(I).eq("user_id",s.id);if(R)throw R}else{const{error:R}=await q.from("mass_email_settings").insert({user_id:s.id,...I});if(R)throw R}},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:I=>re.error(I.message)}),N=!!y;return e.jsxs(we,{children:[e.jsx(Tt,{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($r,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsxs(It,{className:"text-lg flex items-center gap-2",children:["Mass Email",N?e.jsxs(Be,{variant:"default",className:"text-xs bg-green-600",children:[e.jsx(Yo,{className:"h-3 w-3 mr-1"})," Set Up"]}):e.jsx(Be,{variant:"secondary",className:"text-xs",children:"Setup Required"})]}),e.jsx(Jn,{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:[N&&!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(U,{variant:"ghost",size:"sm",onClick:()=>d(!0),children:[e.jsx(ri,{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(te,{className:"text-xs",children:"Display Name"}),e.jsx(xe,{placeholder:"e.g. 🏡 Karen Hall",value:m,onChange:I=>p(I.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(te,{className:"text-xs",children:"Reply-To Email *"}),e.jsx(xe,{type:"email",placeholder:"your@email.com",value:u,onChange:I=>h(I.target.value)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{size:"sm",onClick:()=>b.mutate(),disabled:b.isPending||!u.trim(),children:[e.jsx(Ho,{className:"h-4 w-4 mr-1"})," Save"]}),c&&e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>{d(!1),h(y),p(v)},children:[e.jsx(er,{className:"h-4 w-4 mr-1"})," Cancel"]})]})]}),s&&e.jsxs(e.Fragment,{children:[e.jsx(hc,{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(cg,{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(eQn,{userId:s.id,onVerifiedSelect:I=>{h(I),d(!0)}})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx(hc,{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(cg,{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(Fts,{brokerageId:i})]})]})]})]})}function sQn({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}}function nQn(){const s=Wn(),{isAdmin:t,user:n}=vs(),{actingAsAgent:r,effectiveUserId:a}=Fne(),i=Qt(),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState(!1),{scopeUserId:m,isDelegated:p}=sQn({authUserId:n==null?void 0:n.id,actingAsUserId:(r==null?void 0:r.id)??a}),{data:f,isLoading:x}=ct({queryKey:["gmail-integration",m],enabled:!!m&&!p,queryFn:async()=>{const{data:R,error:z}=await q.from("gmail_integrations").select("*").eq("user_id",m).maybeSingle();if(z)throw z;return R}}),{data:y}=ct({queryKey:["social-accounts",m],enabled:!!m&&!p,queryFn:async()=>{const{data:R,error:z}=await q.from("social_accounts").select("*").eq("user_id",m).order("created_at",{ascending:!1});if(z)throw z;return R}}),v=async()=>{if(p){re.error("Account connections must be made by the agent from their own login.");return}o(!0);try{const{data:R,error:z}=await q.functions.invoke("gmail-oauth",{body:{action:"get_auth_url"}});if(z)throw z;if(R!=null&&R.authUrl)window.location.href=R.authUrl;else throw new Error("Failed to get authorization URL")}catch(R){console.error("Gmail OAuth error:",R),re.error("Failed to start Gmail connection"),o(!1)}},b=async R=>{if(p){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:z,error:$}=await q.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:R}});if($)throw $;if(z!=null&&z.authUrl)window.location.href=z.authUrl;else throw new Error("Failed to get authorization URL")}catch(z){console.error("Meta OAuth error:",z),re.error("Failed to start connection. Make sure Meta App credentials are configured."),d(!1)}},N=async()=>{if(p){re.error("Account connections must be made by the agent from their own login.");return}h(!0);try{const{data:R,error:z}=await q.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(z)throw z;if(R!=null&&R.authUrl)window.location.href=R.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(R){console.error("LinkedIn OAuth error:",R),re.error("Failed to start LinkedIn connection. Please try again."),h(!1)}},S=yt({mutationFn:async R=>{const{error:z}=await q.from("gmail_integrations").delete().eq("id",R).eq("user_id",m);if(z)throw z},onSuccess:()=>{i.invalidateQueries({queryKey:["gmail-integration",m]}),re.success("Gmail disconnected")},onError:()=>{re.error("Failed to disconnect Gmail")}}),A=yt({mutationFn:async R=>{const{error:z}=await q.from("social_accounts").delete().eq("id",R).eq("user_id",m);if(z)throw z},onSuccess:()=>{i.invalidateQueries({queryKey:["social-accounts",m]}),re.success("Account disconnected")},onError:()=>{re.error("Failed to disconnect account")}}),T=!p&&!!(f!=null&&f.is_active),L=(y==null?void 0:y.filter(R=>R.platform==="facebook"))||[],M=(y==null?void 0:y.filter(R=>R.platform==="instagram"))||[],I=(y==null?void 0:y.filter(R=>R.platform==="linkedin"))||[];return e.jsx(qs,{children:e.jsxs("div",{className:"max-w-3xl mx-auto space-y-6 animate-fade-in",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Integrations"}),e.jsx("p",{className:"text-muted-foreground",children:"Connect third-party services to supercharge your Agent OS workflow."})]}),p&&e.jsx(we,{className:"border-amber-500/40 bg-amber-500/5",children:e.jsxs(Tt,{className:"flex flex-row items-start gap-3 space-y-0",children:[e.jsx(Ql,{className:"h-5 w-5 text-amber-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx(It,{className:"text-base",children:"Connected accounts are hidden"}),e.jsxs(Jn,{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(we,{children:[e.jsx(Tt,{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(E4,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(It,{className:"text-lg",children:"ChatGPT"}),e.jsx(Jn,{children:"Connect ChatGPT to LevelUp so it can use LevelUp tools on your behalf."})]})]})}),e.jsx(Ie,{children:e.jsxs(U,{variant:"outline",onClick:()=>s("/connect-chatgpt"),children:["View connection instructions ",e.jsx(Oa,{className:"h-4 w-4 ml-1"})]})})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-destructive/10 flex items-center justify-center",children:e.jsx(ln,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsxs(It,{className:"text-lg flex items-center gap-2",children:["Gmail",T&&e.jsx(Be,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Jn,{children:"Send emails directly from your contact pages and auto-log them as touchpoints."})]})]})}),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(Yo,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Send personalized emails from your Gmail account"})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Yo,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Automatically log emails as activity touchpoints"})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Yo,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Quick compose from any contact detail page"})]}),T?e.jsxs("div",{className:"flex items-center justify-between mt-4 p-3 rounded-lg border",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:f.gmail_email}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Gmail account"})]}),e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(In,{className:"h-4 w-4"})})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Disconnect Gmail?"}),e.jsx(Ll,{children:"This will remove your Gmail connection. You'll need to reconnect to send emails."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>S.mutate(f.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}):e.jsxs(U,{className:"mt-4",onClick:v,disabled:l||x,children:[l?e.jsx(no,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Connect Gmail",e.jsx(Oa,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsxs(we,{children:[e.jsx(Tt,{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(zp,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsxs(It,{className:"text-lg flex items-center gap-2",children:["Facebook",L.length>0&&e.jsx(Be,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Jn,{children:"Connect Facebook Pages to post content and reach your audience."})]})]})}),e.jsxs(Ie,{className:"space-y-3",children:[L.length>0&&e.jsx("div",{className:"space-y-2",children:L.map(R=>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(Ea,{className:"h-8 w-8",children:[e.jsx(Ci,{src:R.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(zp,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:R.page_name||R.platform_username||"Facebook Page"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Facebook Page"})]})]}),e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(In,{className:"h-4 w-4"})})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Disconnect Facebook?"}),e.jsx(Ll,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>A.mutate(R.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},R.id))}),e.jsxs(U,{onClick:()=>b("facebook"),disabled:c,variant:"outline",className:"gap-2",children:[c?e.jsx(no,{className:"h-4 w-4 animate-spin"}):e.jsx(an,{className:"h-4 w-4"}),"Connect Facebook Page"]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-pink-500/10 flex items-center justify-center",children:e.jsx(gm,{className:"h-5 w-5 text-pink-600"})}),e.jsxs("div",{children:[e.jsxs(It,{className:"text-lg flex items-center gap-2",children:["Instagram",M.length>0&&e.jsx(Be,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Jn,{children:"Connect an Instagram Business or Creator account to schedule and publish posts. Personal accounts are not supported by Meta's API."})]})]})}),e.jsxs(Ie,{className:"space-y-3",children:[M.length>0&&e.jsx("div",{className:"space-y-2",children:M.map(R=>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(Ea,{className:"h-8 w-8",children:[e.jsx(Ci,{src:R.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(gm,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium text-sm",children:["@",R.platform_username||"Instagram Account"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Instagram account"})]})]}),e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(In,{className:"h-4 w-4"})})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Disconnect Instagram?"}),e.jsx(Ll,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>A.mutate(R.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},R.id))}),e.jsxs(U,{onClick:()=>b("instagram"),disabled:c,variant:"outline",className:"gap-2",children:[c?e.jsx(no,{className:"h-4 w-4 animate-spin"}):e.jsx(an,{className:"h-4 w-4"}),"Connect Instagram Professional"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Uses Instagram's professional login for Business or Creator accounts. Personal accounts cannot post via Meta's API — convert your account in the Instagram app (Profile → Menu → Settings → Account type → Switch to Professional)."})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-blue-700/10 flex items-center justify-center",children:e.jsx(Gg,{className:"h-5 w-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsxs(It,{className:"text-lg flex items-center gap-2",children:["LinkedIn",I.length>0&&e.jsx(Be,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Jn,{children:"Connect your LinkedIn profile to share content and grow your professional network."})]})]})}),e.jsxs(Ie,{className:"space-y-3",children:[I.length>0&&e.jsx("div",{className:"space-y-2",children:I.map(R=>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(Ea,{className:"h-8 w-8",children:[e.jsx(Ci,{src:R.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(Gg,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:R.platform_username||"LinkedIn Account"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected LinkedIn profile"})]})]}),e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(In,{className:"h-4 w-4"})})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Disconnect LinkedIn?"}),e.jsx(Ll,{children:"This will remove your LinkedIn connection. You'll need to reconnect to post content."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>A.mutate(R.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},R.id))}),e.jsxs(U,{onClick:N,disabled:u,variant:"outline",className:"gap-2",children:[u?e.jsx(no,{className:"h-4 w-4 animate-spin"}):e.jsx(an,{className:"h-4 w-4"}),"Connect LinkedIn"]})]})]}),e.jsx(GXn,{}),e.jsx(WXn,{}),e.jsx(KXn,{}),e.jsx(YXn,{}),e.jsx(XXn,{}),e.jsx(tQn,{}),t&&e.jsx(Ots,{})]})})}const rQn="https://chromewebstore.google.com/detail/levelup-companion/lppakdeaencigddecnkcifdcemlfpkkk";function aQn(){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()},p=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"}),N=URL.createObjectURL(b),S=document.createElement("a");S.href=N,S.download="levelup-extension.zip",document.body.appendChild(S),S.click(),S.remove(),setTimeout(()=>URL.revokeObjectURL(N),1e3)}catch(y){re.error(y.message||"Download failed")}finally{o(!1)}},f=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 N=setInterval(()=>{i(S=>S<=1?(clearInterval(N),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(qs,{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(NF,{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(we,{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(U,{size:"lg",className:"w-full",onClick:()=>window.open(rQn,"_blank","noopener,noreferrer"),children:[e.jsx(NF,{className:"w-4 h-4 mr-2"}),"Add to Chrome",e.jsx(Sr,{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(we,{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(U,{onClick:x,variant:"outline",className:"flex-1",children:[e.jsx(Pa,{className:"w-4 h-4 mr-2"})," Copy"]}),e.jsxs(U,{onClick:f,variant:"outline",className:"flex-1",children:[e.jsx(no,{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(Xr,{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(U,{onClick:f,disabled:n,size:"lg",className:"w-full",children:n?e.jsxs(e.Fragment,{children:[e.jsx(no,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating…"]}):"Generate pairing code"})]}),e.jsxs(we,{className:"p-6 space-y-4 bg-muted/30 border-dashed",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dh,{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(U,{variant:"link",className:"h-auto p-0 text-sm",onClick:p,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 iQn(){const[s]=fc(),t=Wn(),[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(we,{className:"w-full max-w-md",children:[e.jsxs(Tt,{className:"text-center",children:[n==="loading"&&e.jsx(Et,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Yo,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(ou,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(It,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Jn,{children:a})]}),e.jsx(Ie,{className:"flex justify-center",children:n!=="loading"&&e.jsx(U,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"Back to Integrations":"Try Again"})})]})})}function oQn(){const s=Wn();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 lQn(){const[s]=fc(),t=Wn(),[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:p,error:f}=await q.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:c,state:h,callbackPath:"/mission-control/integrations/meta/callback"}});if(p&&p.success===!1)throw new Error(p.error||"Failed to connect accounts");if(f){let x=f.message||"Failed to connect accounts";try{const y=f.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(p!=null&&p.success)r("success"),l(`Successfully connected ${((m=p.accounts)==null?void 0:m.length)||0} account(s)!`),re.success("Social accounts connected successfully!");else throw new Error((p==null?void 0:p.error)||"Unknown error")}catch(p){console.error("OAuth callback error:",p),r("error"),l(p instanceof Error?p.message:"Failed to connect accounts"),re.error("Failed to connect: "+(p instanceof Error?p.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(we,{className:"w-full max-w-md",children:[e.jsxs(Tt,{className:"text-center",children:[n==="loading"&&e.jsx(Et,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Yo,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(ou,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(It,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Jn,{children:i})]}),e.jsx(Ie,{className:"flex justify-center",children:n!=="loading"&&e.jsx(U,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"View Integrations":"Try Again"})})]})})}const zts=new Date().getFullYear(),cQn=Array.from({length:5},(s,t)=>zts-t);function dQn(){const[s,t]=j.useState(zts),n=Wn(),{data:r,isLoading:a}=Lzs();return a?e.jsx(qs,{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(qs,{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(Ns,{value:String(s),onValueChange:i=>t(Number(i)),children:[e.jsx(ws,{className:"w-[120px]",children:e.jsx(ks,{})}),e.jsx(js,{children:cQn.map(i=>e.jsx(et,{value:String(i),children:i},i))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(we,{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(Bn,{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(we,{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(Cl,{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(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"Agents with Scorecards"}),e.jsx(Jn,{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(Cl,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents have added transactions yet"})]}):e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Agent"}),e.jsx(Lt,{children:"Email"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:r.map(i=>e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium",children:i.name}),e.jsx(gt,{className:"text-muted-foreground",children:i.email}),e.jsx(gt,{className:"text-right",children:e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>n(`/admin/scorecard/${i.id}`),children:[e.jsx(xa,{className:"h-4 w-4 mr-2"}),"View Scorecard"]})})]},i.id))})]})})]})]})})}const Bts=new Date().getFullYear(),uQn=Array.from({length:10},(s,t)=>Bts-t);function ESt(){var x;const{userId:s}=Di(),t=Wn(),r=Od().pathname.startsWith("/mission-control"),[a,i]=j.useState(Bts),{data:l,isLoading:o}=ct({queryKey:["agent-profile",s],queryFn:async()=>{const{data:y,error:v}=await q.from("profiles").select("id, name, email").eq("id",s).single();if(v)throw v;return y},enabled:!!s}),{data:c,isLoading:d}=KQe(a,s),{yearStats:u,lifetimeStats:h,isLoading:m,showCommission:p}=j7t(a,s),{data:f}=w7t(a,s);return o?e.jsx(qs,{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(y=>e.jsx(xn,{className:"h-24"},y))})]})}):e.jsx(qs,{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(U,{variant:"ghost",size:"icon",onClick:()=>t(r?"/mission-control/scorecard":"/admin/scorecard"),children:e.jsx(Aa,{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(Ns,{value:String(a),onValueChange:y=>i(Number(y)),children:[e.jsx(ws,{className:"w-[120px]",children:e.jsx(ks,{})}),e.jsx(js,{children:uQn.map(y=>e.jsx(et,{value:String(y),children:y},y))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4",children:[e.jsx(we,{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(ra,{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(we,{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(Bn,{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(we,{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(yu,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:Uh(u.totalVolume,!0)})]})}),e.jsx(we,{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(rc,{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:Uh(u.averagePrice,!0)})]})}),e.jsx(we,{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(Eh,{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:((x=u.topLeadSource)==null?void 0:x.name)||"-"})]})})]}),f&&e.jsx(oJt,{goals:f,stats:u,year:a,showCommission:p}),e.jsxs(oa,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(la,{children:[e.jsx(Kt,{value:"transactions",children:"Transactions"}),e.jsx(Kt,{value:"charts",children:"Charts"}),e.jsxs(Kt,{value:"map",children:[e.jsx(ni,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(Zt,{value:"transactions",children:e.jsx(Ant,{transactions:c||[],showCommission:p,isLoading:d})}),e.jsx(Zt,{value:"charts",children:e.jsx(Ent,{stats:u,year:a})}),e.jsx(Zt,{value:"map",children:e.jsx(Tnt,{transactions:c||[],isLoading:d})})]})]})})}function hQn(){const s=Qt(),[t,n]=j.useState(""),[r,a]=j.useState("all"),[i,l]=j.useState(null);qne();const{data:o,refetch:c}=ct({queryKey:["listing-exchange-flag"],queryFn:async()=>{const{data:I}=await q.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").single();return(I==null?void 0:I.enabled)??!1}}),{data:d,isLoading:u}=ct({queryKey:["admin-listings"],queryFn:async()=>{const{data:I,error:R}=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(R)throw R;return I}}),{data:h}=ct({queryKey:["admin-listing-stats"],queryFn:async()=>{const{data:I}=await q.from("listings").select("id, is_approved, status"),{data:R}=await q.from("listing_shares").select("id"),{data:z}=await q.from("listing_views").select("id"),{count:$}=await q.from("listing_leads").select("id",{count:"exact",head:!0}),H=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",H);return{total:(I==null?void 0:I.length)||0,pending:(I==null?void 0:I.filter(K=>!K.is_approved).length)||0,active:(I==null?void 0:I.filter(K=>K.status==="active").length)||0,totalShares:(R==null?void 0:R.length)||0,totalViews:(z==null?void 0:z.length)||0,totalLeads:$||0,leadsLast7:V||0}}}),{data:m}=ct({queryKey:["admin-listing-lead-counts"],queryFn:async()=>{const I={};let R=0;const z=1e3;for(;;){const{data:$,error:H}=await q.from("listing_leads").select("listing_id").range(R,R+z-1);if(H)throw H;if(!$||$.length===0)break;for(const V of $)V.listing_id&&(I[V.listing_id]=(I[V.listing_id]||0)+1);if($.length{const{data:I,error:R}=await q.from("listing_leads").select("*").eq("listing_id",i.listingId).order("created_at",{ascending:!1});if(R)throw R;return I}}),x=async(I,R,z="submit_url")=>{try{const{data:{session:$}}=await q.auth.getSession();if(!$)return;const{data:H,error:V}=await q.functions.invoke("google-indexing",{body:{action:z,listing_id:I,listing_slug:R}});if(V)throw V;if((H==null?void 0:H.configured)===!1)return;H!=null&&H.success&&re.success("Submitted to Google for indexing")}catch($){console.error("Google indexing submission failed:",$)}},y=yt({mutationFn:async()=>{const{data:{session:I}}=await q.auth.getSession();if(!I)throw new Error("Not authenticated");const{data:R,error:z}=await q.functions.invoke("google-indexing",{body:{action:"submit_all"}});if(z)throw z;return R},onSuccess:I=>{if((I==null?void 0:I.configured)===!1){re.error("Google Indexing API not configured. Add the GOOGLE_INDEXING_SERVICE_ACCOUNT secret.");return}re.success(`Submitted ${(I==null?void 0:I.succeeded)||0} URLs to Google (${(I==null?void 0:I.failed)||0} failed)`)},onError:I=>{re.error("Failed to submit to Google"),console.error(I)}}),v=yt({mutationFn:async({id:I,approved:R,slug:z})=>{const{error:$}=await q.from("listings").update({is_approved:R}).eq("id",I);if($)throw $;return{id:I,approved:R,slug:z}},onSuccess:I=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),re.success(I.approved?"Listing approved":"Listing unapproved"),I.approved?x(I.id,I.slug||null,"submit_url"):x(I.id,I.slug||null,"remove_url")}}),b=yt({mutationFn:async({id:I,featured:R})=>{const{error:z}=await q.from("listings").update({is_featured:R}).eq("id",I);if(z)throw z},onSuccess:(I,{featured:R})=>{s.invalidateQueries({queryKey:["admin-listings"]}),re.success(R?"Listing featured":"Listing unfeatured")}}),N=yt({mutationFn:async I=>{const{error:R}=await q.from("listings").delete().eq("id",I);if(R)throw R},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),re.success("Listing deleted")}}),S=yt({mutationFn:async I=>{const{error:R}=await q.from("feature_flags").update({enabled:I}).eq("key","listing_exchange_enabled");if(R)throw R},onSuccess:()=>{c(),re.success("Feature flag updated")}}),A=o??!1,T=d==null?void 0:d.filter(I=>{var $,H,V,K;const R=(($=I.city)==null?void 0:$.toLowerCase().includes(t.toLowerCase()))||((V=(H=I.agent)==null?void 0:H.name)==null?void 0:V.toLowerCase().includes(t.toLowerCase()))||((K=I.property_address)==null?void 0:K.toLowerCase().includes(t.toLowerCase())),z=r==="all"||r==="pending"&&!I.is_approved||r==="approved"&&I.is_approved;return R&&z}),L=I=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(I),M=I=>{const R={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 R[I]||R.active};return e.jsxs(qs,{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(U,{variant:"outline",size:"sm",onClick:()=>y.mutate(),disabled:y.isPending,className:"gap-2",children:[y.isPending?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(fl,{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(wn,{checked:A,onCheckedChange:I=>S.mutate(I)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-4",children:[e.jsx(we,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_i,{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(we,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rc,{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(we,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bn,{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(we,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xa,{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(we,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jd,{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(we,{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-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(we,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by city, address, or agent...",value:t,onChange:I=>n(I.target.value),className:"pl-9"})]}),e.jsx(oa,{value:r,onValueChange:I=>a(I),children:e.jsxs(la,{children:[e.jsx(Kt,{value:"all",children:"All"}),e.jsx(Kt,{value:"pending",children:"Pending"}),e.jsx(Kt,{value:"approved",children:"Approved"})]})})]})})}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{children:["Listings (",(T==null?void 0:T.length)||0,")"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Property"}),e.jsx(Lt,{children:"Agent"}),e.jsx(Lt,{children:"Price"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{className:"text-center",children:"Approved"}),e.jsx(Lt,{className:"text-center",children:"Featured"}),e.jsx(Lt,{children:"Views"}),e.jsx(Lt,{children:"Shares"}),e.jsx(Lt,{children:"Leads"}),e.jsx(Lt,{children:"Date"}),e.jsx(Lt,{})]})}),e.jsx(Xa,{children:u?e.jsx(gn,{children:e.jsx(gt,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):(T==null?void 0:T.length)===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"No listings found"})}):T==null?void 0:T.map(I=>{var R,z,$,H,V;return e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[(z=(R=I.photos)==null?void 0:R[0])!=null&&z.photo_url?e.jsx("img",{src:I.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(_i,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:I.property_address||`${I.city}, ${I.state}`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:($=I.property_type)==null?void 0:$.replace("_"," ")})]})]})}),e.jsx(gt,{children:e.jsx("p",{className:"text-sm",children:((H=I.agent)==null?void 0:H.name)||"Unknown"})}),e.jsx(gt,{className:"font-medium",children:L(I.price)}),e.jsx(gt,{children:e.jsx(Be,{variant:"outline",className:M(I.status),children:(V=I.status)==null?void 0:V.replace("_"," ")})}),e.jsx(gt,{className:"text-center",children:e.jsx(wn,{checked:I.is_approved??!1,onCheckedChange:K=>v.mutate({id:I.id,approved:K,slug:I.slug})})}),e.jsx(gt,{className:"text-center",children:e.jsx(wn,{checked:I.is_featured??!1,onCheckedChange:K=>b.mutate({id:I.id,featured:K})})}),e.jsx(gt,{children:I.view_count||0}),e.jsx(gt,{children:I.share_count||0}),e.jsx(gt,{children:((m==null?void 0:m[I.id])??0)>0?e.jsx(U,{variant:"link",size:"sm",className:"px-0 h-auto font-semibold text-teal-600",onClick:()=>l({listingId:I.id,label:I.property_address||`${I.city}, ${I.state}`}),children:m==null?void 0:m[I.id]}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Gs(new Date(I.created_at),"MMM d, yyyy")}),e.jsx(gt,{children:e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",children:e.jsx(Z1,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",children:[e.jsxs(La,{onClick:()=>window.open(`/mission-control/listings/${I.id}`,"_blank"),children:[e.jsx(xa,{className:"h-4 w-4 mr-2"}),"View Listing"]}),e.jsxs(La,{onClick:()=>b.mutate({id:I.id,featured:!I.is_featured}),children:[e.jsx(Ua,{className:"h-4 w-4 mr-2"}),I.is_featured?"Unfeature":"Feature"]}),e.jsxs(La,{className:"text-destructive",onClick:async()=>{await Yi("Are you sure you want to delete this listing?")&&N.mutate(I.id)},children:[e.jsx(er,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},I.id)})})]})})})]})]}),e.jsx(zs,{open:!!i,onOpenChange:I=>!I&&l(null),children:e.jsxs(Ds,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Leads from listing"}),e.jsx(Pr,{children:i==null?void 0:i.label})]}),f?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(Et,{className:"h-5 w-5 animate-spin inline mr-2"}),"Loading leads..."]}):!p||p.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No leads yet."}):e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Name"}),e.jsx(Lt,{children:"Email"}),e.jsx(Lt,{children:"Phone"}),e.jsx(Lt,{children:"Type"}),e.jsx(Lt,{children:"Captured"})]})}),e.jsx(Xa,{children:p.map(I=>{var R;return e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium",children:[I.first_name,I.last_name].filter(Boolean).join(" ")||"—"}),e.jsx(gt,{children:I.email}),e.jsx(gt,{children:I.phone||"—"}),e.jsx(gt,{children:e.jsx(Be,{variant:"outline",children:(R=I.lead_type)==null?void 0:R.replace("_"," ")})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Gs(new Date(I.created_at),"MMM d, yyyy h:mm a")})]},I.id)})})]})]})})]})}function mQn(s){return s?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s):"—"}function pQn(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),[a,i]=j.useState("all"),{data:l,isLoading:o}=ct({queryKey:["admin-all-listing-leads"],queryFn:async()=>{const h=[];let m=0;const p=1e3;for(;;){const{data:f,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+p-1);if(x)throw x;if(!f||f.length===0||(h.push(...f),f.length{if(!l)return[];const h=n==="all"?0:Date.now()-parseInt(n)*24*60*60*1e3,m=s.trim().toLowerCase();return l.filter(p=>{var x,y,v,b,N,S;return h&&new Date(p.created_at).getTime(){const h=c.length,m=c.filter(x=>x.lead_type==="showing_request").length,p=new Set(c.map(x=>x.agent_id)).size,f=new Set(c.map(x=>x.listing_id)).size;return{total:h,showings:m,uniqueAgents:p,uniqueListings:f}},[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,N,S,A,T;return[Gs(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)||"",(N=y.listing)!=null&&N.price?String(y.listing.price):"",((S=y.agent)==null?void 0:S.name)||"",((A=y.agent)==null?void 0:A.email)||"",((T=y.referrer)==null?void 0:T.name)||"",(y.message||"").replace(/[\r\n]+/g," ")]})].map(y=>y.map(v=>`"${String(v).replace(/"/g,'""')}"`).join(",")).join(` `),p=new Blob([m],{type:"text/csv"}),f=URL.createObjectURL(p),x=document.createElement("a");x.href=f,x.download=`listing-leads-${Gs(new Date,"yyyy-MM-dd")}.csv`,x.click(),URL.revokeObjectURL(f)};return e.jsx(qs,{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(U,{variant:"outline",onClick:u,disabled:!c.length,className:"gap-2",children:[e.jsx(pi,{className:"h-4 w-4"}),"Export CSV"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(we,{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-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(we,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pa,{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(we,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ra,{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(we,{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-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(we,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search name, email, property, agent...",value:s,onChange:h=>t(h.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:a,onValueChange:h=>i(h),children:[e.jsx(ws,{className:"w-full sm:w-48",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Types"}),e.jsx(et,{value:"info_request",children:"Info Request"}),e.jsx(et,{value:"showing_request",children:"Showing Request"})]})]}),e.jsxs(Ns,{value:n,onValueChange:h=>r(h),children:[e.jsx(ws,{className:"w-full sm:w-40",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Time"}),e.jsx(et,{value:"7",children:"Last 7 days"}),e.jsx(et,{value:"30",children:"Last 30 days"}),e.jsx(et,{value:"90",children:"Last 90 days"})]})]})]})})}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{children:["Leads (",c.length,")"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Date"}),e.jsx(Lt,{children:"Lead"}),e.jsx(Lt,{children:"Contact"}),e.jsx(Lt,{children:"Property"}),e.jsx(Lt,{children:"Type"}),e.jsx(Lt,{children:"Assigned To"}),e.jsx(Lt,{children:"Referred By"}),e.jsx(Lt,{children:"Message"})]})}),e.jsx(Xa,{children:o?e.jsx(gn,{children:e.jsx(gt,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):c.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"No leads found"})}):c.map(h=>{var m,p;return e.jsxs(gn,{children:[e.jsxs(gt,{className:"whitespace-nowrap text-sm",children:[Gs(new Date(h.created_at),"MMM d, yyyy"),e.jsx("div",{className:"text-xs text-muted-foreground",children:Gs(new Date(h.created_at),"h:mm a")})]}),e.jsx(gt,{children:e.jsx("div",{className:"font-medium",children:`${h.first_name||""} ${h.last_name||""}`.trim()||"—"})}),e.jsx(gt,{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(ln,{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(ba,{className:"h-3 w-3"}),h.phone]})]})}),e.jsx(gt,{children:h.listing?e.jsxs(xr,{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(Sr,{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(", ")," · ",mQn(h.listing.price)]})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsxs(gt,{children:[e.jsx(Be,{variant:h.lead_type==="showing_request"?"default":"secondary",className:"text-xs",children:h.lead_type==="showing_request"?"Showing":"Info"}),h.preferred_date&&e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:[h.preferred_date," ",h.preferred_time||""]}),h.showing_mode&&e.jsx("div",{className:"text-xs text-muted-foreground capitalize",children:h.showing_mode.replace("_"," ")})]}),e.jsxs(gt,{children:[e.jsx("div",{className:"text-sm font-medium",children:((m=h.agent)==null?void 0:m.name)||"—"}),((p=h.agent)==null?void 0:p.email)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:h.agent.email})]}),e.jsx(gt,{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(gt,{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(Ki,{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 jB={new_listing_alerts:{label:"New Listing Alerts",icon:bx,color:"bg-amber-100 text-amber-800"},exit_intent:{label:"Exit Intent",icon:TF,color:"bg-rose-100 text-rose-800"},saved_listing:{label:"Saved Home",icon:ko,color:"bg-pink-100 text-pink-800"},saved_search:{label:"Saved Search",icon:Fr,color:"bg-blue-100 text-blue-800"},buyer_guide:{label:"Buyer's Guide",icon:ig,color:"bg-emerald-100 text-emerald-800"}},TSt=[{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 MSt(s){return new Date(s).toLocaleString("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})}function fQn(){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 p=!1;return(async()=>{r(!0);let f=q.from("public_site_leads").select("*").order("created_at",{ascending:!1}).limit(2e3);const x=TSt.find(b=>b.key===a);if(x&&x.days>0){const b=new Date(Date.now()-x.days*864e5).toISOString();f=f.gte("created_at",b)}const{data:y,error:v}=await f;p||(v?(console.error(v),t([])):t(y||[]),r(!1))})(),()=>{p=!0}},[a]);const u=j.useMemo(()=>s.filter(p=>{if(l!=="all"&&p.lead_type!==l)return!1;if(c){const f=c.toLowerCase();if(![p.email,p.first_name,p.last_name,p.phone,p.source_page,p.referrer].filter(Boolean).join(" ").toLowerCase().includes(f))return!1}return!0}),[s,l,c]),h=j.useMemo(()=>{const p=u.length,f=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:p,uniqueEmails:f,byType:x}},[u]),m=()=>{const f=[["Date (ET)","Type","Email","First","Last","Phone","Listing ID","Source Page","Referrer","Criteria"].join(",")];u.forEach(b=>{var S;const N=[MSt(b.created_at),((S=jB[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,'""')}"`);f.push(N.join(","))});const x=new Blob([f.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(xr,{to:"/admin",children:e.jsxs(U,{variant:"ghost",size:"sm",children:[e.jsx(Aa,{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(U,{onClick:m,variant:"outline",size:"sm",children:[e.jsx(pi,{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(we,{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(jB).map(p=>{const f=jB[p],x=f.icon;return e.jsx(we,{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"}),f.label]}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:h.byType[p]||0})]})},p)})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Ns,{value:a,onValueChange:p=>i(p),children:[e.jsx(ws,{className:"w-[160px] bg-white",children:e.jsx(ks,{})}),e.jsx(js,{children:TSt.map(p=>e.jsx(et,{value:p.key,children:p.label},p.key))})]}),e.jsxs(Ns,{value:l,onValueChange:o,children:[e.jsx(ws,{className:"w-[200px] bg-white",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All lead types"}),Object.keys(jB).map(p=>e.jsx(et,{value:p,children:jB[p].label},p))]})]}),e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(xe,{placeholder:"Search name, email, phone…",value:c,onChange:p=>d(p.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(we,{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(p=>{const f=jB[p.lead_type],x=f==null?void 0:f.icon,y=[p.first_name,p.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:MSt(p.created_at)}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:e.jsxs(Be,{className:`${(f==null?void 0:f.color)||""} font-normal`,variant:"secondary",children:[x?e.jsx(x,{className:"h-3 w-3 mr-1"}):null,(f==null?void 0:f.label)||p.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:${p.email}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(ln,{className:"h-3 w-3"}),p.email]})]}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:p.phone?e.jsxs("a",{href:`tel:${p.phone}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(ba,{className:"h-3 w-3"}),p.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:[p.listing_id&&e.jsxs("div",{className:"mb-0.5",children:["Listing: ",e.jsxs("span",{className:"font-mono text-[10px]",children:[p.listing_id.slice(0,8),"…"]})]}),p.criteria&&Object.keys(p.criteria).length>0&&e.jsx("div",{className:"text-slate-500 line-clamp-2",children:Object.entries(p.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:[p.source_page&&e.jsxs("div",{className:"inline-flex items-center gap-1",children:[e.jsx(Sr,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:p.source_page})]}),p.referrer&&e.jsxs("div",{className:"text-slate-400 truncate",children:["from ",p.referrer]})]})]},p.id)})})]})})})]})]})}const gQn=()=>{var h,m;const[s,t]=j.useState(""),[n,r]=j.useState(null),{data:a,isLoading:i}=ct({queryKey:["membership-reviews"],queryFn:async()=>{const{data:p,error:f}=await q.from("membership_reviews").select("*").order("created_at",{ascending:!1});if(f)throw f;const x=(p==null?void 0:p.map(b=>b.user_id))||[],{data:y}=await q.from("profiles").select("id, name, email").in("id",x);return p==null?void 0:p.map(b=>({...b,profiles:(y==null?void 0:y.find(N=>N.id===b.user_id))||null}))}}),l=a==null?void 0:a.filter(p=>{var x,y,v,b,N;const f=s.toLowerCase();return((y=(x=p.profiles)==null?void 0:x.name)==null?void 0:y.toLowerCase().includes(f))||((b=(v=p.profiles)==null?void 0:v.email)==null?void 0:b.toLowerCase().includes(f))||((N=p.review_text)==null?void 0:N.toLowerCase().includes(f))}),o=a!=null&&a.length?(a.reduce((p,f)=>p+f.rating,0)/a.length).toFixed(1):"0.0",c=a==null?void 0:a.reduce((p,f)=>(p[f.rating]=(p[f.rating]||0)+1,p),{}),d=(a==null?void 0:a.filter(p=>p.posted_to_google).length)||0,u=p=>e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(f=>e.jsx(Ua,{className:Mt("h-4 w-4",p>=f?"fill-yellow-400 text-yellow-400":"text-muted-foreground")},f))});return e.jsx(qs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{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(we,{children:e.jsxs(Tt,{className:"pb-2",children:[e.jsx(Jn,{children:"Total Reviews"}),e.jsx(It,{className:"text-3xl",children:(a==null?void 0:a.length)||0})]})}),e.jsx(we,{children:e.jsxs(Tt,{className:"pb-2",children:[e.jsx(Jn,{children:"Average Rating"}),e.jsxs(It,{className:"flex items-center gap-2 text-3xl",children:[o,e.jsx(Ua,{className:"h-6 w-6 fill-yellow-400 text-yellow-400"})]})]})}),e.jsx(we,{children:e.jsxs(Tt,{className:"pb-2",children:[e.jsx(Jn,{children:"5-Star Reviews"}),e.jsx(It,{className:"text-3xl",children:(c==null?void 0:c[5])||0})]})}),e.jsx(we,{children:e.jsxs(Tt,{className:"pb-2",children:[e.jsx(Jn,{children:"Posted to Google"}),e.jsxs(It,{className:"flex items-center gap-2 text-3xl",children:[d,e.jsx(Sr,{className:"h-5 w-5 text-muted-foreground"})]})]})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name, email, or review...",value:s,onChange:p=>t(p.target.value),className:"pl-9"})]}),e.jsx(we,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Member"}),e.jsx(Lt,{children:"Rating"}),e.jsx(Lt,{className:"hidden md:table-cell",children:"Review"}),e.jsx(Lt,{children:"Google"}),e.jsx(Lt,{children:"Date"})]})}),e.jsx(Xa,{children:i?e.jsx(gn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:"Loading reviews..."})}):(l==null?void 0:l.length)===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No reviews found"})}):l==null?void 0:l.map(p=>{var f,x;return e.jsxs(gn,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>r(p),children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:((f=p.profiles)==null?void 0:f.name)||"Unknown"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:(x=p.profiles)==null?void 0:x.email})]})}),e.jsx(gt,{children:u(p.rating)}),e.jsx(gt,{className:"hidden md:table-cell max-w-xs",children:e.jsx("p",{className:"truncate text-sm text-muted-foreground",children:p.review_text||"-"})}),e.jsx(gt,{children:p.posted_to_google?e.jsx(Be,{variant:"secondary",className:"bg-green-100 text-green-800",children:"Posted"}):e.jsx(Be,{variant:"outline",children:"No"})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Gs(new Date(p.created_at),"MMM d, yyyy")})]},p.id)})})]})})}),e.jsx(zs,{open:!!n,onOpenChange:()=>r(null),children:e.jsxs(Ds,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Review Details"})}),n&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg",children:((h=n.profiles)==null?void 0:h.name)||"Unknown Member"}),((m=n.profiles)==null?void 0:m.email)&&e.jsxs("a",{href:`mailto:${n.profiles.email}`,className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-primary",children:[e.jsx(ln,{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(pa,{className:"h-4 w-4"}),Gs(new Date(n.created_at),"MMMM d, yyyy 'at' h:mm a")]}),n.posted_to_google?e.jsxs(Be,{variant:"secondary",className:"bg-green-100 text-green-800",children:[e.jsx(Sr,{className:"h-3 w-3 mr-1"}),"Posted to Google"]}):e.jsx(Be,{variant:"outline",children:"Not posted to Google"})]})]})]})})]})})},PSt={agent_card:"Agent Card",listing:"Listing",lead_site:"Lead Site",guest_book:"Guest Book",landing_page:"Landing Page",connect_page:"Connect Page",booking:"Booking"},xQn={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 yQn(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),[a,i]=j.useState("all"),[l,o]=j.useState("7"),{data:c,isLoading:d}=ct({queryKey:["lead-notification-log",l],queryFn:async()=>{const m=new Date(Date.now()-Number(l)*864e5).toISOString(),{data:p,error:f}=await q.from("lead_notification_log").select("*").gte("created_at",m).order("created_at",{ascending:!1}).limit(2e3);if(f)throw f;return p||[]}}),u=j.useMemo(()=>{const m=s.trim().toLowerCase();return(c||[]).filter(p=>n!=="all"&&p.source!==n||a!=="all"&&p.status!==a?!1:m?[p.agent_name,p.agent_email,p.lead_name,p.lead_email,p.lead_phone,p.subject].some(f=>(f||"").toLowerCase().includes(m)):!0)},[c,s,n,a]),h=j.useMemo(()=>{const m=u.length,p=u.filter(y=>y.status==="sent"||y.status==="backfilled").length,f=u.filter(y=>y.status==="failed").length,x=new Set(u.map(y=>y.agent_user_id).filter(Boolean)).size;return{total:m,sent:p,failed:f,agents:x}},[u]);return e.jsx(qs,{children:e.jsxs("div",{className:"container mx-auto py-6 space-y-6",children:[e.jsx(Xh,{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(we,{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(we,{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(we,{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(we,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search agent or lead name, email, phone…",value:s,onChange:m=>t(m.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:n,onValueChange:r,children:[e.jsx(ws,{className:"w-full md:w-48",children:e.jsx(ks,{placeholder:"Source"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Sources"}),Object.entries(PSt).map(([m,p])=>e.jsx(et,{value:m,children:p},m))]})]}),e.jsxs(Ns,{value:a,onValueChange:i,children:[e.jsx(ws,{className:"w-full md:w-40",children:e.jsx(ks,{placeholder:"Status"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Statuses"}),e.jsx(et,{value:"sent",children:"Sent"}),e.jsx(et,{value:"backfilled",children:"Backfilled"}),e.jsx(et,{value:"failed",children:"Failed"})]})]}),e.jsxs(Ns,{value:l,onValueChange:o,children:[e.jsx(ws,{className:"w-full md:w-36",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"1",children:"Last 24h"}),e.jsx(et,{value:"7",children:"Last 7 days"}),e.jsx(et,{value:"14",children:"Last 14 days"}),e.jsx(et,{value:"30",children:"Last 30 days"})]})]})]}),e.jsx(we,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"When"}),e.jsx(Lt,{children:"Source"}),e.jsx(Lt,{children:"Agent"}),e.jsx(Lt,{children:"Lead"}),e.jsx(Lt,{children:"Status"})]})}),e.jsx(Xa,{children:d?e.jsx(gn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"Loading…"})}):u.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No notifications match the current filters."})}):u.map(m=>e.jsxs(gn,{children:[e.jsx(gt,{className:"whitespace-nowrap text-sm",children:Gs(new Date(m.created_at),"MMM d, yyyy h:mm a")}),e.jsx(gt,{children:e.jsx(Be,{variant:"secondary",children:PSt[m.source]||m.source})}),e.jsxs(gt,{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(gt,{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(ln,{className:"h-3 w-3"}),m.lead_email]}),m.lead_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ba,{className:"h-3 w-3"}),m.lead_phone]})]})]}),e.jsxs(gt,{children:[e.jsx(Be,{className:xQn[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 vQn=[{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"}],bQn=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 _Qn(){const s=Qt(),{user:t}=vs(),[n,r]=j.useState(!1),[a,i]=j.useState(!1),[l,o]=j.useState(!1),{data:c,isLoading:d}=ct({queryKey:["weekly-digest-settings"],queryFn:async()=>{const{data:M,error:I}=await q.from("weekly_digest_settings").select("*").single();if(I)throw I;return M}}),{data:u,isLoading:h}=ct({queryKey:["weekly-digest-logs"],queryFn:async()=>{const{data:M,error:I}=await q.from("weekly_digest_logs").select("*").order("sent_at",{ascending:!1}).limit(100);if(I)throw I;return M}}),{data:m}=ct({queryKey:["digest-subscriber-count"],queryFn:async()=>{const{count:M,error:I}=await q.from("profiles").select("id",{count:"exact",head:!0}).eq("digest_opt_out",!1).not("email","is",null);if(I)throw I;return M||0}}),{data:p,refetch:f}=ct({queryKey:["digest-queue-status"],queryFn:async()=>{const M=new Date;M.setUTCHours(0,0,0,0);const[I,R,z,$]=await Promise.all([q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","pending").gte("created_at",M.toISOString()),q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","processing").gte("created_at",M.toISOString()),q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","sent").gte("created_at",M.toISOString()),q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","failed").gte("created_at",M.toISOString())]);return{pending:I.count||0,processing:R.count||0,sent:z.count||0,failed:$.count||0,total:(I.count||0)+(R.count||0)+(z.count||0)+($.count||0)}},refetchInterval:5e3});j.useEffect(()=>{if(p&&(p.pending>0||p.processing>0)){const M=setInterval(()=>{f(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})},5e3);return()=>clearInterval(M)}},[p,f,s]);const{data:x=0}=ct({queryKey:["digest-today-failed-count"],queryFn:async()=>{const M=new Date;M.setUTCHours(0,0,0,0);const{count:I,error:R}=await q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",M.toISOString());if(R)throw R;return I||0}}),y=yt({mutationFn:async M=>{const{error:I}=await q.from("weekly_digest_settings").update(M).eq("id",c==null?void 0:c.id);if(I)throw I},onSuccess:()=>{s.invalidateQueries({queryKey:["weekly-digest-settings"]}),re.success("Settings updated")},onError:M=>{re.error("Failed to update settings: "+M.message)}}),v=async()=>{r(!0);try{const{data:M,error:I}=await q.functions.invoke("send-weekly-digest",{body:{manual:!0}});if(I)throw I;M.queued?re.success(`${M.queued.toLocaleString()} emails queued! They'll be sent automatically (~80/minute).`):M.sent!==void 0&&re.success(`Digest sent! ${M.sent} emails delivered, ${M.failed} failed`),f(),s.invalidateQueries({queryKey:["weekly-digest-logs"]})}catch(M){re.error("Failed to send digest: "+M.message)}finally{r(!1)}},b=async()=>{var M,I,R,z,$,H;if(!(t!=null&&t.email)){re.error("No email found for your account");return}i(!0);try{const{data:V,error:K}=await q.functions.invoke("send-weekly-digest",{body:{preview:!0,previewEmail:t.email}});if(K)throw K;const Z=V==null?void 0:V.resendId,Q=V==null?void 0:V.resendDetails,le=Q==null?void 0:Q.status,ue=((M=Q==null?void 0:Q.body)==null?void 0:M.status)||((R=(I=Q==null?void 0:Q.body)==null?void 0:I.data)==null?void 0:R.status),se=(($=(z=Q==null?void 0:Q.body)==null?void 0:z.error)==null?void 0:$.message)||((H=Q==null?void 0:Q.body)==null?void 0:H.message);re.success(Z?`Preview accepted by email provider (id: ${Z})${le?`, status check: ${le}`:""}${ue?`, provider: ${ue}`:""}${se?` (${se})`:""}. 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)}},N=async()=>{o(!0);try{const{data:M,error:I}=await q.functions.invoke("send-weekly-digest",{body:{retryFailed:!0}});if(I)throw I;M.queued===0||M.sent===0&&M.failed===0&&!M.queued?re.info("No failed emails to retry"):M.queued?re.success(`${M.queued} emails queued for retry!`):re.success(`Retry complete! ${M.sent} emails delivered, ${M.failed} failed`),f(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})}catch(M){re.error("Failed to retry: "+M.message)}finally{o(!1)}},S=p!=null&&p.total?Math.round((p.sent+p.failed)/p.total*100):0,A=((p==null?void 0:p.pending)||0)>0||((p==null?void 0:p.processing)||0)>0,{data:T}=ct({queryKey:["digest-delivery-stats"],queryFn:async()=>{var H,V;const M=new Date;M.setUTCHours(0,0,0,0);const[I,R,z,$]=await Promise.all([q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","sent").gte("sent_at",M.toISOString()),q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",M.toISOString()),q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("has_agent_os_activity",!0).gte("sent_at",M.toISOString()),q.from("weekly_digest_logs").select("sent_at").order("sent_at",{ascending:!1}).limit(1)]);return{totalSent:I.count||0,totalFailed:R.count||0,agentOsEngaged:z.count||0,lastSent:((V=(H=$.data)==null?void 0:H[0])==null?void 0:V.sent_at)||null}},refetchInterval:A?5e3:!1}),L={totalSent:(T==null?void 0:T.totalSent)||0,totalFailed:(T==null?void 0:T.totalFailed)||0,lastSent:T==null?void 0:T.lastSent,agentOsEngaged:(T==null?void 0:T.agentOsEngaged)||0};return d?e.jsx(qs,{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(qs,{title:"Weekly Digest",description:"Configure and manage automated weekly email digests for members",children:e.jsxs(oa,{defaultValue:"settings",className:"space-y-6",children:[e.jsxs(la,{children:[e.jsxs(Kt,{value:"settings",className:"flex items-center gap-2",children:[e.jsx(qc,{className:"h-4 w-4"}),"Settings"]}),e.jsxs(Kt,{value:"stats",className:"flex items-center gap-2",children:[e.jsx(Cl,{className:"h-4 w-4"}),"Delivery Stats"]})]}),e.jsxs(Zt,{value:"settings",className:"space-y-6",children:[A&&p&&e.jsx(we,{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(Et,{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:[p.sent.toLocaleString()," sent, ",p.pending.toLocaleString()," pending",p.failed>0&&`, ${p.failed} failed`]})]}),e.jsxs("span",{className:"text-sm font-medium",children:[S,"%"]})]}),e.jsx(ro,{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(p.pending/80)," min"]})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(we,{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(Bn,{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(we,{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(zr,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:L.totalSent}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Delivered"})]})]})})}),e.jsx(we,{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(ou,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:L.totalFailed}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed"})]})]})})}),e.jsx(we,{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(Yr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:L.lastSent?Gs(new Date(L.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(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Yr,{className:"h-5 w-5"}),"Schedule"]}),e.jsx(Jn,{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(te,{children:"Enable Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Send automated weekly emails to members"})]}),e.jsx(wn,{checked:c==null?void 0:c.is_enabled,onCheckedChange:M=>y.mutate({is_enabled:M})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Cron Frequency"}),e.jsxs(Ns,{value:(c==null?void 0:c.cron_frequency)||"daily",onValueChange:M=>y.mutate({cron_frequency:M}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"daily",children:"Daily (runs once at selected time)"}),e.jsx(et,{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(te,{children:"Day of Week"}),e.jsxs(Ns,{value:String(c==null?void 0:c.send_day),onValueChange:M=>y.mutate({send_day:parseInt(M)}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:vQn.map(M=>e.jsx(et,{value:M.value,children:M.label},M.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Time (UTC)"}),e.jsxs(Ns,{value:String(c==null?void 0:c.send_hour),onValueChange:M=>y.mutate({send_hour:parseInt(M)}),disabled:(c==null?void 0:c.cron_frequency)==="daily",children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:bQn.map(M=>e.jsx(et,{value:M.value,children:M.label},M.value))})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{onClick:b,disabled:a,variant:"outline",className:"flex-1",children:[e.jsx(xa,{className:"h-4 w-4 mr-2"}),a?"Sending...":"Send Preview to Me"]}),e.jsxs(U,{onClick:v,disabled:n,className:"flex-1",children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),n?"Sending...":"Send to All"]})]}),x>0&&e.jsxs(U,{onClick:N,disabled:l,variant:"outline",className:"w-full",children:[e.jsx(no,{className:`h-4 w-4 mr-2 ${l?"animate-spin":""}`}),l?"Retrying...":`Retry ${x} Failed`]})]})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Ur,{className:"h-5 w-5"}),"Content Sections"]}),e.jsx(Jn,{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(Ur,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(te,{children:"New Resources"})]}),e.jsx(wn,{checked:c==null?void 0:c.include_new_resources,onCheckedChange:M=>y.mutate({include_new_resources:M})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(te,{children:"Community Highlights"})]}),e.jsx(wn,{checked:c==null?void 0:c.include_community_posts,onCheckedChange:M=>y.mutate({include_community_posts:M})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Cl,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(te,{children:"Agent OS Stats"})]}),e.jsx(wn,{checked:c==null?void 0:c.include_agent_os_stats,onCheckedChange:M=>y.mutate({include_agent_os_stats:M})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(te,{children:"Upcoming Events"})]}),e.jsx(wn,{checked:c==null?void 0:c.include_upcoming_events,onCheckedChange:M=>y.mutate({include_upcoming_events:M})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gu,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(te,{children:"Goals Progress"})]}),e.jsx(wn,{checked:c==null?void 0:c.include_goals_progress,onCheckedChange:M=>y.mutate({include_goals_progress:M})})]})]})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"Custom Introduction"}),e.jsx(Jn,{children:"Personalize the intro message (optional)"})]}),e.jsx(Ie,{children:e.jsx(Fs,{placeholder:"Here's what's new this week to help you grow your business...",value:(c==null?void 0:c.custom_intro_text)||"",onChange:M=>y.mutate({custom_intro_text:M.target.value||null}),rows:3})})]})]}),e.jsx(Zt,{value:"stats",children:e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5"}),"Delivery History"]}),e.jsx(Jn,{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(M=>e.jsx("div",{className:"h-12 bg-muted rounded"},M))}):u&&u.length>0?e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Email"}),e.jsx(Lt,{children:"Sent At"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{children:"Resources"}),e.jsx(Lt,{children:"Agent OS"})]})}),e.jsx(Xa,{children:u.map(M=>e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium",children:M.email_sent_to}),e.jsx(gt,{children:Gs(new Date(M.sent_at),"MMM d, yyyy h:mm a")}),e.jsx(gt,{children:e.jsx(Be,{variant:M.delivery_status==="sent"?"default":"destructive",children:M.delivery_status})}),e.jsx(gt,{children:M.resources_count}),e.jsx(gt,{children:M.has_agent_os_activity?e.jsx(Be,{variant:"secondary",children:"Active"}):e.jsx(Be,{variant:"outline",children:"Not Started"})})]},M.id))})]}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ln,{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 wQn={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 jQn(){var ie,ce,je;const s=Qt(),[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(""),[p,f]=j.useState(!0),[x,y]=j.useState(!1),[v,b]=j.useState(""),[N,S]=j.useState(null),{data:A,isLoading:T}=ct({queryKey:["admin-agent-points"],queryFn:async()=>{const{data:be,error:he}=await q.from("agent_attendance_stats").select("*").order("total_points",{ascending:!1});if(he)throw he;const ge=(be==null?void 0:be.map(Me=>Me.user_id))||[],{data:ke}=await q.from("profiles").select("id, name, email").in("id",ge),Te=new Map((ke==null?void 0:ke.map(Me=>[Me.id,{name:Me.name,email:Me.email}]))||[]);return be==null?void 0:be.map(Me=>({...Me,profile:Te.get(Me.user_id)||null}))}}),{data:L}=ct({queryKey:["all-profiles-for-points",A],queryFn:async()=>{const he=[];let ge=0;for(;;){const{data:ke,error:Te}=await q.from("profiles").select("id, name, email").order("name").range(ge,ge+1e3-1);if(Te)throw Te;if(he.push(...ke),!ke||ke.length<1e3)break;ge+=1e3}return he}}),I=((L==null?void 0:L.filter(be=>!(A!=null&&A.some(he=>he.user_id===be.id))))||[]).filter(be=>{var ge,ke;if(!v)return!0;const he=v.toLowerCase();return((ge=be.name)==null?void 0:ge.toLowerCase().includes(he))||((ke=be.email)==null?void 0:ke.toLowerCase().includes(he))}),{data:R,isLoading:z}=ct({queryKey:["agent-point-history",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:be,error:he}=await q.from("agent_points").select("*").eq("user_id",r.user_id).order("created_at",{ascending:!1});if(he)throw he;return be},enabled:!!(r!=null&&r.user_id)&&o}),{data:$}=ct({queryKey:["agent-badges",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:be,error:he}=await q.from("agent_badges").select("*").eq("user_id",r.user_id).order("earned_at",{ascending:!1});if(he)throw he;return be},enabled:!!(r!=null&&r.user_id)}),H=yt({mutationFn:async({userId:be,points:he,reason:ge})=>{const{error:ke}=await q.from("agent_points").insert({user_id:be,points:he,reason:ge});if(ke)throw ke;const{data:Te}=await q.from("agent_attendance_stats").select("total_points, spendable_points").eq("user_id",be).maybeSingle(),Me=((Te==null?void 0:Te.total_points)||0)+he,Oe=((Te==null?void 0:Te.spendable_points)||0)+he,{error:Se}=await q.from("agent_attendance_stats").upsert({user_id:be,total_points:Math.max(0,Me),spendable_points:Math.max(0,Oe),updated_at:new Date().toISOString()},{onConflict:"user_id"});if(Se)throw Se},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-agent-points"]}),s.invalidateQueries({queryKey:["agent-point-history"]}),l(!1),u(""),m(""),re.success(p?"Points awarded successfully!":"Points deducted successfully!")},onError:be=>{console.error("Error modifying points:",be),re.error("Failed to modify points")}}),V=()=>{if(!r||!d||!h){re.error("Please fill in all fields");return}const be=parseInt(d);if(isNaN(be)||be<=0){re.error("Please enter a valid positive number");return}H.mutate({userId:r.user_id,points:p?be:-be,reason:h})},K=()=>{if(!N||!d||!h){re.error("Please fill in all fields");return}const be=parseInt(d);if(isNaN(be)||be<=0){re.error("Please enter a valid positive number");return}H.mutate({userId:N.id,points:be,reason:h},{onSuccess:()=>{y(!1),S(null),b("")}})},Z=(be,he)=>{a(be),f(he),l(!0)},Q=be=>{a(be),c(!0)},le=A==null?void 0:A.filter(be=>{var Te,Me,Oe,Se;const he=((Me=(Te=be.profile)==null?void 0:Te.name)==null?void 0:Me.toLowerCase())||"",ge=((Se=(Oe=be.profile)==null?void 0:Oe.email)==null?void 0:Se.toLowerCase())||"",ke=t.toLowerCase();return he.includes(ke)||ge.includes(ke)}),ue=(A==null?void 0:A.reduce((be,he)=>be+he.total_points,0))||0,se=(A==null?void 0:A.length)||0,ne=se>0?Math.round(ue/se):0;return T?e.jsx(qs,{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(be=>e.jsx(xn,{className:"h-24"},be))}),e.jsx(xn,{className:"h-96"})]})}):e.jsx(qs,{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(we,{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(Bn,{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:se}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with points tracked"})]})}),e.jsx(we,{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(Al,{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:ue.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"awarded across all agents"})]})}),e.jsx(we,{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(rc,{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:ne}),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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search agents...",value:t,onChange:be=>n(be.target.value),className:"pl-10"})]}),e.jsxs(U,{onClick:()=>y(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Award Points to New Agent"]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"Agent Leaderboard"}),e.jsx(Jn,{children:"All agents with their points, events, and streaks"})]}),e.jsx(Ie,{children:!le||le.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Al,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents with points yet"})]}):e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{className:"w-12",children:"#"}),e.jsx(Lt,{children:"Agent"}),e.jsx(Lt,{className:"text-center",children:"Total Points"}),e.jsx(Lt,{className:"text-center",children:"Spendable"}),e.jsx(Lt,{className:"text-center",children:"Events"}),e.jsx(Lt,{className:"text-center",children:"Streak"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:le.map((be,he)=>{var ge,ke,Te,Me;return e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium",children:he<3?e.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center ${he===0?"bg-yellow-100 text-yellow-700":he===1?"bg-gray-100 text-gray-600":"bg-amber-100 text-amber-700"}`,children:he+1}):e.jsx("span",{className:"text-muted-foreground",children:he+1})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ea,{className:"h-8 w-8",children:e.jsx(Ta,{children:((ke=(ge=be.profile)==null?void 0:ge.name)==null?void 0:ke.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Te=be.profile)==null?void 0:Te.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(Me=be.profile)==null?void 0:Me.email})]})]})}),e.jsx(gt,{className:"text-center",children:e.jsxs(Be,{variant:"secondary",className:"font-bold",children:[e.jsx(Ua,{className:"h-3 w-3 mr-1"}),be.total_points]})}),e.jsx(gt,{className:"text-center",children:e.jsxs(Be,{variant:"outline",className:"font-bold text-primary",children:[e.jsx(Ro,{className:"h-3 w-3 mr-1"}),be.spendable_points||0]})}),e.jsx(gt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(pa,{className:"h-3 w-3 text-muted-foreground"}),be.total_events_attended]})}),e.jsx(gt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Xd,{className:"h-3 w-3 text-orange-500"}),be.current_streak]})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>Z(be,!0),title:"Award points",children:e.jsx(an,{className:"h-4 w-4 text-green-600"})}),e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>Z(be,!1),title:"Deduct points",children:e.jsx(Z2,{className:"h-4 w-4 text-red-600"})}),e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>Q(be),title:"View history",children:e.jsx(Y2,{className:"h-4 w-4"})})]})})]},be.user_id)})})]})})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:p?"Award Points":"Deduct Points"}),e.jsxs(Pr,{children:[p?"Award":"Deduct"," points ",p?"to":"from"," ",((ie=r==null?void 0:r.profile)==null?void 0:ie.name)||"this agent"]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"points",children:"Points Amount"}),e.jsx(xe,{id:"points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:be=>u(be.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"reason",children:"Reason"}),e.jsx(Fs,{id:"reason",placeholder:"Enter reason for this adjustment...",value:h,onChange:be=>m(be.target.value)})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(U,{onClick:V,disabled:H.isPending,className:p?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700",children:H.isPending?"Saving...":p?"Award Points":"Deduct Points"})]})]})}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Ds,{className:"max-w-2xl",children:[e.jsxs(Vs,{children:[e.jsxs($s,{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(oa,{defaultValue:"history",className:"w-full",children:[e.jsxs(la,{className:"grid w-full grid-cols-2",children:[e.jsx(Kt,{value:"history",children:"Point History"}),e.jsx(Kt,{value:"badges",children:"Badges"})]}),e.jsx(Zt,{value:"history",className:"mt-4",children:z?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(be=>e.jsx(xn,{className:"h-12"},be))}):!R||R.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Y2,{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:R.map(be=>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:be.reason}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Gs(new Date(be.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(Be,{variant:be.points>=0?"default":"destructive",className:be.points>=0?"bg-green-100 text-green-800":"",children:[be.points>=0?"+":"",be.points]})]},be.id))})}),e.jsx(Zt,{value:"badges",className:"mt-4",children:!$||$.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Eh,{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:$.map(be=>e.jsxs("div",{className:`p-3 rounded-lg ${wQn[be.badge_type]||"bg-gray-100"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Eh,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:be.badge_name})]}),be.badge_description&&e.jsx("p",{className:"text-xs mt-1 opacity-80",children:be.badge_description}),e.jsxs("p",{className:"text-xs mt-1 opacity-60",children:["Earned ",Gs(new Date(be.earned_at),"MMM d, yyyy")]})]},be.id))})})]})]})}),e.jsx(zs,{open:x,onOpenChange:be=>{y(be),be||(S(null),b(""),u(""),m(""))},children:e.jsxs(Ds,{className:"max-w-md",children:[e.jsxs(Vs,{children:[e.jsx($s,{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:N?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/50 rounded-lg",children:[e.jsx(Ea,{className:"h-10 w-10",children:e.jsx(Ta,{children:((je=N.name)==null?void 0:je.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:N.name||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:N.email})]}),e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>S(null),children:"Change"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"new-points",children:"Points Amount"}),e.jsx(xe,{id:"new-points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:be=>u(be.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"new-reason",children:"Reason"}),e.jsx(Fs,{id:"new-reason",placeholder:"Enter reason for awarding points...",value:h,onChange:be=>m(be.target.value)})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Search Agent"}),e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name or email...",value:v,onChange:be=>b(be.target.value),className:"pl-10"})]})]}),e.jsx("div",{className:"max-h-60 overflow-y-auto border rounded-lg",children:I.length===0?e.jsxs("div",{className:"text-center py-4 text-muted-foreground",children:[e.jsx(Bn,{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"})]}):I.slice(0,20).map(be=>{var he;return e.jsxs("button",{onClick:()=>S(be),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(Ea,{className:"h-8 w-8",children:e.jsx(Ta,{children:((he=be.name)==null?void 0:he.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:be.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:be.email})]})]},be.id)})})]})}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),N&&e.jsxs(U,{onClick:K,disabled:H.isPending,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Award Points"]})]})]})})]})})}function NQn(){const{data:s,isLoading:t}=FAs(),[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,p]=j.useState("table"),f=j.useMemo(()=>(s==null?void 0:s.map(N=>N.user_id))||[],[s]),x=j.useMemo(()=>(s==null?void 0:s.map(N=>N.id))||[],[s]),{data:y}=ct({queryKey:["card-profiles-lookup",f],queryFn:async()=>{if(f.length===0)return{};const{data:N}=await q.from("profiles").select("id, name, email").in("id",f),S={};return N==null||N.forEach(A=>{S[A.id]={name:A.name||"",email:A.email||""}}),S},enabled:f.length>0}),{data:v}=ct({queryKey:["card-stats-all",x],queryFn:async()=>{if(x.length===0)return{};const N={};x.forEach(T=>{N[T]={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(T=>{N[T.card_id]&&N[T.card_id].views++});const{data:A}=await q.from("agent_card_leads").select("card_id").in("card_id",x);return A==null||A.forEach(T=>{N[T.card_id]&&N[T.card_id].leads++}),N},enabled:x.length>0}),b=j.useMemo(()=>{if(!s)return[];let N=[...s];if(c==="live"?N=N.filter(S=>S.is_published):c==="draft"&&(N=N.filter(S=>!S.is_published)),l.trim()){const S=l.toLowerCase();N=N.filter(A=>{var L,M;const T=y==null?void 0:y[A.user_id];return A.slug.toLowerCase().includes(S)||((L=T==null?void 0:T.name)==null?void 0:L.toLowerCase().includes(S))||((M=T==null?void 0:T.email)==null?void 0:M.toLowerCase().includes(S))})}return u==="newest"?N.sort((S,A)=>new Date(A.created_at).getTime()-new Date(S.created_at).getTime()):u==="oldest"?N.sort((S,A)=>new Date(S.created_at).getTime()-new Date(A.created_at).getTime()):u==="name"?N.sort((S,A)=>{var T,L;return(((T=y==null?void 0:y[S.user_id])==null?void 0:T.name)||"").localeCompare(((L=y==null?void 0:y[A.user_id])==null?void 0:L.name)||"")}):u==="slug"?N.sort((S,A)=>S.slug.localeCompare(A.slug)):u==="views_desc"?N.sort((S,A)=>{var T,L;return(((T=v==null?void 0:v[A.id])==null?void 0:T.views)||0)-(((L=v==null?void 0:v[S.id])==null?void 0:L.views)||0)}):u==="views_asc"?N.sort((S,A)=>{var T,L;return(((T=v==null?void 0:v[S.id])==null?void 0:T.views)||0)-(((L=v==null?void 0:v[A.id])==null?void 0:L.views)||0)}):u==="leads_desc"?N.sort((S,A)=>{var T,L;return(((T=v==null?void 0:v[A.id])==null?void 0:T.leads)||0)-(((L=v==null?void 0:v[S.id])==null?void 0:L.leads)||0)}):u==="leads_asc"&&N.sort((S,A)=>{var T,L;return(((T=v==null?void 0:v[S.id])==null?void 0:T.leads)||0)-(((L=v==null?void 0:v[A.id])==null?void 0:L.leads)||0)}),N},[s,c,l,u,y]);return e.jsxs(qs,{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(U,{onClick:()=>i(!0),children:[e.jsx(an,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name, email, or slug...",value:l,onChange:N=>o(N.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:c,onValueChange:d,children:[e.jsx(ws,{className:"w-full sm:w-36",children:e.jsx(ks,{placeholder:"Status"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All Status"}),e.jsx(et,{value:"live",children:"Live"}),e.jsx(et,{value:"draft",children:"Draft"})]})]}),e.jsxs(Ns,{value:u,onValueChange:h,children:[e.jsx(ws,{className:"w-full sm:w-44",children:e.jsx(ks,{placeholder:"Sort by"})}),e.jsxs(js,{children:[e.jsx(et,{value:"newest",children:"Newest First"}),e.jsx(et,{value:"oldest",children:"Oldest First"}),e.jsx(et,{value:"name",children:"Name A–Z"}),e.jsx(et,{value:"slug",children:"Slug A–Z"}),e.jsx(et,{value:"views_desc",children:"Most Views"}),e.jsx(et,{value:"views_asc",children:"Fewest Views"}),e.jsx(et,{value:"leads_desc",children:"Most Leads"}),e.jsx(et,{value:"leads_asc",children:"Fewest Leads"})]})]}),e.jsxs("div",{className:"flex border rounded-md",children:[e.jsx(U,{variant:m==="table"?"default":"ghost",size:"sm",onClick:()=>p("table"),className:"rounded-r-none",children:e.jsx(yq,{className:"h-4 w-4"})}),e.jsx(U,{variant:m==="grid"?"default":"ghost",size:"sm",onClick:()=>p("grid"),className:"rounded-l-none",children:e.jsx(Hg,{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(N=>e.jsx(xn,{className:"h-48"},N))}):b.length>0?m==="table"?e.jsx(kQn,{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(N=>e.jsx(SQn,{card:N,onEdit:()=>r(N),stats:v==null?void 0:v[N.id]},N.id))}):s&&s.length>0?e.jsx(we,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Fr,{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(we,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Bn,{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(U,{onClick:()=>i(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Create Card"]})]})})]}),e.jsx(CQn,{open:a,onOpenChange:i}),n&&e.jsx(AQn,{card:n,open:!!n,onOpenChange:N=>!N&&r(null)})]})}function kQn({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(ag,{className:"h-3 w-3"}):a===`${c}_asc`?e.jsx(cp,{className:"h-3 w-3"}):e.jsx(xx,{className:"h-3 w-3 opacity-40"});return e.jsx(we,{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(cp,{className:"h-3 w-3"})]})}),e.jsx("th",{className:"text-left p-3 font-medium text-muted-foreground hidden md:table-cell",children:"Slug"}),e.jsx("th",{className:"text-center p-3 font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"text-right p-3 font-medium",children:e.jsxs("button",{onClick:()=>l("views"),className:"flex items-center gap-1 ml-auto hover:text-foreground text-muted-foreground",children:["Views ",e.jsx(o,{field:"views"})]})}),e.jsx("th",{className:"text-right p-3 font-medium",children:e.jsxs("button",{onClick:()=>l("leads"),className:"flex items-center gap-1 ml-auto hover:text-foreground text-muted-foreground",children:["Leads ",e.jsx(o,{field:"leads"})]})}),e.jsx("th",{className:"text-right p-3 font-medium text-muted-foreground",children:"Actions"})]})}),e.jsx("tbody",{children:s.map(c=>{const d=t==null?void 0:t[c.user_id],u=n==null?void 0:n[c.id],h=`https://cards.relevelup.com/${c.slug}`;return e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30 transition-colors",children:[e.jsx("td",{className:"p-3",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:(d==null?void 0:d.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(d==null?void 0:d.email)||""})]})}),e.jsx("td",{className:"p-3 hidden md:table-cell",children:e.jsxs("span",{className:"text-xs text-muted-foreground font-mono",children:["/",c.slug]})}),e.jsx("td",{className:"p-3 text-center",children:e.jsx(Be,{variant:c.is_published?"default":"secondary",className:"text-xs",children:c.is_published?"Live":"Draft"})}),e.jsx("td",{className:"p-3 text-right tabular-nums font-medium",children:(u==null?void 0:u.views)??0}),e.jsx("td",{className:"p-3 text-right tabular-nums font-medium",children:(u==null?void 0:u.leads)??0}),e.jsx("td",{className:"p-3",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>r(c),className:"h-8 w-8 p-0",children:e.jsx(ri,{className:"h-3.5 w-3.5"})}),e.jsx(U,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{navigator.clipboard.writeText(h),re.success("Link copied!")},children:e.jsx(Pa,{className:"h-3.5 w-3.5"})}),e.jsx(U,{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(Sr,{className:"h-3.5 w-3.5"})})})]})})]},c.id)})})]})})})}function SQn({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(we,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-3",children:[e.jsxs(Ea,{className:"h-10 w-10",children:[e.jsx(Ci,{src:(r==null?void 0:r.avatar_url)||void 0}),e.jsx(Ta,{children:((r==null?void 0:r.name)||"U")[0]})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold truncate",children:(r==null?void 0:r.name)||"Loading..."}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:["/card/",s.slug]})]}),e.jsx(Be,{variant:s.is_published?"default":"secondary",children:s.is_published?"Live":"Draft"})]}),e.jsxs("div",{className:"flex items-center gap-3 mb-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(xa,{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(Bn,{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(U,{variant:"outline",size:"sm",onClick:t,className:"flex-1",children:[e.jsx(ri,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsx(U,{variant:"outline",size:"sm",onClick:l,children:e.jsx(Pa,{className:"h-3 w-3"})}),e.jsx(U,{variant:"outline",size:"sm",asChild:!0,children:e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",children:e.jsx(Sr,{className:"h-3 w-3"})})})]})]})})}function CQn({open:s,onOpenChange:t}){const[n,r]=j.useState(""),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(!1),u=pRt(),h=l.trim(),{data:m}=ct({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:N}=await b;return N||[]},enabled:s}),[p,f]=j.useState(null),x=(m==null?void 0:m.find(b=>b.id===n))||p,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 N=m==null?void 0:m.find(A=>A.id===b);N&&(f(N),i(((S=N.name)==null?void 0:S.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||""))};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{children:"Agent"}),e.jsxs(md,{open:c,onOpenChange:d,children:[e.jsx(pd,{asChild:!0,children:e.jsxs(U,{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(Jw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(id,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(pj,{shouldFilter:!1,children:[e.jsx(fj,{placeholder:"Search by name or email...",value:l,onValueChange:o}),e.jsxs(gj,{children:[e.jsx(xj,{children:"No agents found."}),e.jsx(I_,{children:(m||[]).map(b=>e.jsxs(e1,{value:b.id,onSelect:v,children:[e.jsx(Xr,{className:Mt("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(te,{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(xe,{value:a,onChange:b=>i(b.target.value),placeholder:"john-doe"})]})]}),e.jsx(U,{onClick:y,disabled:u.isPending,className:"w-full",children:u.isPending?"Creating...":"Create Card"})]})]})})}function AQn({card:s,open:t,onOpenChange:n}){const r=fRt(),{data:a}=gRt(s.id),i=Qt(),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,p]=j.useState(""),[f,x]=j.useState(s.slug),[y,v]=j.useState(!1),[b,N]=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:R}=await q.storage.from("avatars").list(`${s.user_id}`);if(R&&R.length>0){const{data:z}=q.storage.from("avatars").getPublicUrl(`${s.user_id}/${R[0].name}`);o(`${z.publicUrl}?t=${Date.now()}`)}}catch{}})()},[s.user_id,t]);const S=I=>{var $;const R=($=I.target.files)==null?void 0:$[0];if(!R)return;if(!R.type.startsWith("image/")){re.error("Please select an image file");return}if(R.size>5*1024*1024){re.error("Image must be under 5MB");return}const z=new FileReader;z.onloadend=()=>{p(z.result),h(!0)},z.readAsDataURL(R),I.target.value=""},A=async I=>{d(!0);try{const{data:R}=await q.storage.from("avatars").list(`${s.user_id}`);R&&R.length>0&&await q.storage.from("avatars").remove(R.map(K=>`${s.user_id}/${K.name}`));const z=`${s.user_id}/avatar.jpg`,{error:$}=await q.storage.from("avatars").upload(z,I,{upsert:!0,contentType:"image/jpeg"});if($)throw $;const{data:H}=q.storage.from("avatars").getPublicUrl(z),V=`${H.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(R){re.error(R.message||"Upload failed")}finally{d(!1)}},T=async()=>{const I=f.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!I){re.error("Please enter a valid URL");return}if(I===s.slug){re.info("No changes to save");return}v(!0);try{const{data:R}=await q.from("agent_cards").select("id").eq("slug",I).neq("id",s.id).maybeSingle();if(R){re.error("This URL is already taken. Try another one.");return}const{error:z}=await q.from("agent_cards").update({slug:I}).eq("id",s.id);if(z)throw z;x(I),i.invalidateQueries({queryKey:["agent-cards-admin"]}),re.success("Card address updated!")}catch{re.error("Failed to update card address")}finally{v(!1)}},L=async(I,R)=>{var $;const z=($=I.target.files)==null?void 0:$[0];if(z){if(!z.type.startsWith("image/")){re.error("Please select an image file");return}try{const H=z.name.split(".").pop()||"png",V=R==="brokerage_logo_url"?"brokerage-logo":"team-logo",K=`${s.user_id}/${V}.${H}`,{error:Z}=await q.storage.from("card-logos").upload(K,z,{upsert:!0});if(Z)throw Z;const{data:Q}=q.storage.from("card-logos").getPublicUrl(K),le=Q.publicUrl+"?t="+Date.now();N(R==="brokerage_logo_url"?ue=>({...ue,[R]:le,brokerage_display_name:""}):ue=>({...ue,[R]:le,team_name:""})),re.success("Logo uploaded!")}catch{re.error("Failed to upload logo")}finally{I.target.value=""}}},M=()=>{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(Ds,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Edit Agent Card"}),e.jsxs(Pr,{children:["/card/",s.slug]})]}),e.jsxs(oa,{defaultValue:"content",children:[e.jsxs(la,{className:"w-full",children:[e.jsx(Kt,{value:"content",className:"flex-1",children:"Content"}),e.jsx(Kt,{value:"sections",className:"flex-1",children:"Sections"}),e.jsx(Kt,{value:"blocks",className:"flex-1",children:"Blocks"}),e.jsx(Kt,{value:"analytics",className:"flex-1",children:"Analytics"})]}),e.jsxs(Zt,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{children:"Published"}),e.jsx(wn,{checked:b.is_published,onCheckedChange:I=>N(R=>({...R,is_published:I}))})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-4 mt-1",children:[e.jsxs(Ea,{className:"h-16 w-16",children:[e.jsx(Ci,{src:l||void 0}),e.jsx(Ta,{children:"?"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:S,disabled:c}),e.jsx(U,{variant:"outline",size:"sm",asChild:!0,disabled:c,children:e.jsx("span",{children:c?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-3 w-3 mr-1 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qa,{className:"h-3 w-3 mr-1"}),"Change Photo"]})})})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{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(xe,{value:f,onChange:I=>x(I.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"agent-name",className:"rounded-l-none"})]}),e.jsx(U,{variant:"outline",size:"sm",onClick:T,disabled:y||f===s.slug,className:"shrink-0",children:y?"Saving...":"Update"})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Theme"}),e.jsxs(Ns,{value:b.theme,onValueChange:I=>N(R=>({...R,theme:I})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"standard",children:"✨ Standard (Modern Clean)"}),e.jsx(et,{value:"luxury",children:"🌙 Luxury (Dark & Gold)"}),e.jsx(et,{value:"bold",children:"🔥 Bold (Vibrant & Punchy)"}),e.jsx(et,{value:"classic",children:"📋 Classic (Professional)"})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Title / Tagline"}),e.jsx(xe,{value:b.title,onChange:I=>N(R=>({...R,title:I.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(te,{children:"Positioning Statement"}),e.jsx(xe,{value:b.positioning_statement,onChange:I=>N(R=>({...R,positioning_statement:I.target.value})),placeholder:"Your home journey, handled with care."})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Bio"}),e.jsx(Fs,{value:b.bio,onChange:I=>N(R=>({...R,bio:I.target.value})),placeholder:"Short about me...",rows:3})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Review Snippet"}),e.jsx(xe,{value:b.review_snippet,onChange:I=>N(R=>({...R,review_snippet:I.target.value})),placeholder:"Best agent we've ever worked with..."})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Review Source URL"}),e.jsx(xe,{value:b.review_source_url,onChange:I=>N(R=>({...R,review_source_url:I.target.value})),placeholder:"https://g.page/your-business/review"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Booking URL (optional — if empty, shows lead form)"}),e.jsx(xe,{value:b.booking_url,onChange:I=>N(R=>({...R,booking_url:I.target.value})),placeholder:"https://calendly.com/your-link"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Custom CTA Label (optional)"}),e.jsx(xe,{value:b.custom_cta_label,onChange:I=>N(R=>({...R,custom_cta_label:I.target.value})),placeholder:"Book a Call"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Custom CTA URL (optional)"}),e.jsx(xe,{value:b.custom_cta_url,onChange:I=>N(R=>({...R,custom_cta_url:I.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(te,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{value:b.brokerage_display_name,onChange:I=>N(R=>({...R,brokerage_display_name:I.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:()=>N(I=>({...I,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(qa,{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:I=>L(I,"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(te,{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(rg,{value:[b.brokerage_logo_size||56],onValueChange:([I])=>N(R=>({...R,brokerage_logo_size:I})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(te,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{value:b.team_name,onChange:I=>N(R=>({...R,team_name:I.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:()=>N(I=>({...I,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(qa,{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:I=>L(I,"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(te,{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(rg,{value:[b.team_logo_size||56],onValueChange:([I])=>N(R=>({...R,team_logo_size:I})),min:24,max:120,step:4})]})]})]})]}),e.jsx(Zt,{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:I,label:R,hint:z})=>e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsxs("div",{children:[e.jsx(te,{children:R}),z&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[z," ",I==="show_photo"&&e.jsx("a",{href:"/profile",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:no-underline",children:"Update Profile"})]})]}),e.jsx(wn,{checked:b[I],onCheckedChange:$=>N(H=>({...H,[I]:$}))})]},I))}),e.jsx(Zt,{value:"blocks",className:"mt-4",children:e.jsx(Dts,{cardId:s.id})}),e.jsx(Zt,{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(we,{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(we,{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(we,{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(I=>e.jsxs("div",{className:"text-sm p-2 bg-muted/50 rounded-lg",children:[e.jsx("span",{className:"font-medium",children:I.name}),I.phone&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",I.phone]}),I.intent&&e.jsx(Be,{variant:"secondary",className:"ml-2 text-xs",children:I.intent})]},I.id))})]})]}):e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No analytics data yet"})})]}),e.jsx(U,{onClick:M,disabled:r.isPending,className:"w-full mt-4",children:r.isPending?"Saving...":"Save Changes"})]})}),e.jsx(LJe,{open:u,onClose:()=>h(!1),imageSrc:m,onCropComplete:A,aspectRatio:1})]})}const o$={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"},brt={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 _rt(s=!0){return ct({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 EQn(){const s=Qt();return yt({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 TQn(){const s=Qt();return yt({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 MQn(){const s=Qt();return yt({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 Uts(s,t=!0){return ct({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 PQn(s){return ct({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 LQn(){const s=Qt();return yt({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 IQn(){const s=Qt();return yt({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 RQn(){const s=Qt();return yt({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 DQn(){const s=Qt();return yt({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 OQn(){const s=Qt();return yt({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 FQn(){const s=Qt();return yt({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 zQn(){const s=Qt();return yt({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 BQn(){const s=Qt();return yt({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 UQn(){const s=Qt();return yt({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 qQn(s){const{isAdmin:t}=vs();return ct({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 $Qn(){const{user:s}=vs();return ct({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 VQn(s){return ct({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 HQn(){const s=Qt(),{user:t}=vs();return yt({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 GQn(){const s=Qt();return yt({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 WQn(){const s=Qt();return yt({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 KQn(){const s=Qt();return yt({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 YQn(){const{data:s,isLoading:t}=_rt(!1),n=EQn(),r=TQn(),a=MQn(),[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)},p=async x=>{x.preventDefault(),o?await r.mutateAsync({id:o.id,...d}):await n.mutateAsync(d),l(!1),h()},f=async x=>{await Yi("Are you sure you want to delete this category?")&&await a.mutateAsync(x)};return t?e.jsxs(we,{children:[e.jsx(Tt,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsx(It,{children:"Categories"}),e.jsxs(zs,{open:i,onOpenChange:x=>{l(x),x||h()},children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Add Category"]})}),e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:o?"Edit Category":"Add Category"})}),e.jsxs("form",{onSubmit:p,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"name",children:"Name"}),e.jsx(xe,{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(te,{htmlFor:"description",children:"Description"}),e.jsx(Fs,{id:"description",value:d.description,onChange:x=>u({...d,description:x.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"image_url",children:"Image URL"}),e.jsx(xe,{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(te,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(xe,{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(wn,{id:"is_active",checked:d.is_active,onCheckedChange:x=>u({...d,is_active:x})}),e.jsx(te,{htmlFor:"is_active",children:"Active"})]}),e.jsx(U,{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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Name"}),e.jsx(Lt,{children:"Description"}),e.jsx(Lt,{children:"Sort Order"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:s.map(x=>e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium",children:x.name}),e.jsx(gt,{className:"max-w-xs truncate",children:x.description}),e.jsx(gt,{children:x.sort_order}),e.jsx(gt,{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(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>m(x),children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>f(x.id),disabled:a.isPending,children:e.jsx(In,{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 ZQn(){var ne,ie;const{data:s,isLoading:t}=Uts(void 0,!1),{data:n}=_rt(!1),r=LQn(),a=IQn(),i=RQn(),l=DQn(),o=OQn(),c=FQn(),d=zQn(),u=BQn(),h=UQn(),[m,p]=j.useState(!1),[f,x]=j.useState(!1),[y,v]=j.useState(!1),[b,N]=j.useState(null),[S,A]=j.useState(null),[T,L]=j.useState(!1),[M,I]=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}),[R,z]=j.useState({name:"",price_adjustment:0}),[$,H]=j.useState(""),V=()=>{I({name:"",description:"",base_price:0,shipping_fee:0,category_id:"",allow_artwork_upload:!1,requires_proof_approval:!1,is_active:!0,sort_order:0}),N(null)},K=ce=>{N(ce),I({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}),p(!0)},Z=async ce=>{ce.preventDefault();const je={...M,category_id:M.category_id||null};b?await a.mutateAsync({id:b.id,...je}):await r.mutateAsync(je),p(!1),V()},Q=async ce=>{await Yi("Are you sure you want to delete this product?")&&await i.mutateAsync(ce)},le=async ce=>{if(!S||!ce.target.files||ce.target.files.length===0)return;L(!0);const je=ce.target.files[0],be=je.name.split(".").pop(),he=`products/${S.id}/${Date.now()}.${be}`;try{const{error:ge}=await q.storage.from("marketplace").upload(he,je);if(ge)throw ge;const{data:{publicUrl:ke}}=q.storage.from("marketplace").getPublicUrl(he);await l.mutateAsync({product_id:S.id,image_url:ke,is_primary:!S.images||S.images.length===0}),re.success("Image uploaded successfully")}catch(ge){re.error("Failed to upload image: "+ge.message)}finally{L(!1)}},ue=async ce=>{ce.preventDefault(),S&&(await d.mutateAsync({product_id:S.id,name:R.name,price_adjustment:R.price_adjustment}),z({name:"",price_adjustment:0}))},se=async()=>{!S||!$||(await h.mutateAsync({productId:S.id,videoUrl:$}),H(""))};return t?e.jsxs(we,{children:[e.jsx(Tt,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsx(It,{children:"Products"}),e.jsxs(zs,{open:m,onOpenChange:ce=>{p(ce),ce||V()},children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Add Product"]})}),e.jsxs(Ds,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:b?"Edit Product":"Add Product"})}),e.jsxs("form",{onSubmit:Z,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"name",children:"Product Name"}),e.jsx(xe,{id:"name",value:M.name,onChange:ce=>I({...M,name:ce.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"category",children:"Category"}),e.jsxs(Ns,{value:M.category_id,onValueChange:ce=>I({...M,category_id:ce}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select category"})}),e.jsx(js,{children:n==null?void 0:n.map(ce=>e.jsx(et,{value:ce.id,children:ce.name},ce.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"description",children:"Description"}),e.jsx(Fs,{id:"description",value:M.description,onChange:ce=>I({...M,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(te,{htmlFor:"base_price",children:"Base Price ($)"}),e.jsx(xe,{id:"base_price",type:"number",step:"0.01",min:"0",value:M.base_price,onChange:ce=>I({...M,base_price:parseFloat(ce.target.value)||0}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"shipping_fee",children:"Shipping Fee ($)"}),e.jsx(xe,{id:"shipping_fee",type:"number",step:"0.01",min:"0",value:M.shipping_fee,onChange:ce=>I({...M,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(te,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(xe,{id:"sort_order",type:"number",value:M.sort_order,onChange:ce=>I({...M,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(wn,{id:"allow_artwork_upload",checked:M.allow_artwork_upload,onCheckedChange:ce=>I({...M,allow_artwork_upload:ce})}),e.jsx(te,{htmlFor:"allow_artwork_upload",children:"Allow customer to upload artwork"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wn,{id:"requires_proof_approval",checked:M.requires_proof_approval,onCheckedChange:ce=>I({...M,requires_proof_approval:ce})}),e.jsx(te,{htmlFor:"requires_proof_approval",children:"Requires proof approval"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wn,{id:"is_active",checked:M.is_active,onCheckedChange:ce=>I({...M,is_active:ce})}),e.jsx(te,{htmlFor:"is_active",children:"Active"})]})]}),e.jsx(U,{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 je,be;return e.jsxs(we,{className:"overflow-hidden",children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[ce.images&&ce.images.length>0?e.jsx("img",{src:((je=ce.images.find(he=>he.is_primary))==null?void 0:je.image_url)||ce.images[0].image_url,alt:ce.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:"No image"}),!ce.is_active&&e.jsx(Be,{variant:"secondary",className:"absolute top-2 right-2",children:"Inactive"})]}),e.jsxs(Ie,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1",children:ce.name}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:((be=ce.category)==null?void 0:be.name)||"No category"}),e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("span",{className:"font-bold",children:["$",Number(ce.base_price).toFixed(2)]}),Number(ce.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["+$",Number(ce.shipping_fee).toFixed(2)," shipping"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[ce.allow_artwork_upload&&e.jsx(Be,{variant:"outline",className:"text-xs",children:"Artwork Upload"}),ce.requires_proof_approval&&e.jsx(Be,{variant:"outline",className:"text-xs",children:"Proof Required"}),ce.variants&&ce.variants.length>0&&e.jsxs(Be,{variant:"outline",className:"text-xs",children:[ce.variants.length," Variants"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>K(ce),children:[e.jsx(ri,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>{A(ce),x(!0)},children:[e.jsx(ly,{className:"h-3 w-3 mr-1"}),"Images"]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>{A(ce),v(!0)},children:[e.jsx(Cf,{className:"h-3 w-3 mr-1"}),"Variants"]}),e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>Q(ce.id),children:e.jsx(In,{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:f,onOpenChange:x,children:e.jsxs(Ds,{className:"max-w-2xl",children:[e.jsx(Vs,{children:e.jsxs($s,{children:["Manage Images - ",S==null?void 0:S.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-3 gap-4",children:(ne=S==null?void 0:S.images)==null?void 0:ne.map(ce=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:ce.image_url,alt:"",className:"w-full aspect-square object-cover rounded-lg"}),ce.is_primary&&e.jsx(Be,{className:"absolute top-2 left-2",variant:"default",children:"Primary"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[!ce.is_primary&&e.jsx(U,{variant:"secondary",size:"icon",onClick:async()=>{var je;await c.mutateAsync({imageId:ce.id,productId:S.id}),A({...S,images:(je=S.images)==null?void 0:je.map(be=>({...be,is_primary:be.id===ce.id}))})},disabled:c.isPending,title:"Set as primary",children:e.jsx(Ua,{className:"h-4 w-4"})}),e.jsx(U,{variant:"destructive",size:"icon",onClick:async()=>{var be;await o.mutateAsync({id:ce.id,productId:S.id});const je=s==null?void 0:s.find(he=>he.id===S.id);je&&A({...je,images:(be=je.images)==null?void 0:be.filter(he=>he.id!==ce.id)})},disabled:o.isPending,children:e.jsx(In,{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:le,className:"hidden",id:"image-upload",disabled:T}),e.jsxs("label",{htmlFor:"image-upload",className:"cursor-pointer",children:[e.jsx(ly,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:T?"Uploading...":"Click to upload an image"})]})]}),e.jsxs("div",{className:"border-t pt-4 mt-4",children:[e.jsx(te,{children:"Product Video (optional)"}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(xe,{placeholder:"Enter video URL (YouTube, Vimeo, etc.)",value:$,onChange:ce=>H(ce.target.value)}),e.jsxs(U,{onClick:se,disabled:!$,children:[e.jsx(Wr,{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(Ds,{children:[e.jsx(Vs,{children:e.jsxs($s,{children:["Manage Variants - ",S==null?void 0:S.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("form",{onSubmit:ue,className:"flex gap-2",children:[e.jsx(xe,{placeholder:"Variant name (e.g., 500 count)",value:R.name,onChange:ce=>z({...R,name:ce.target.value}),required:!0}),e.jsx(xe,{type:"number",step:"0.01",placeholder:"Price adj.",value:R.price_adjustment,onChange:ce=>z({...R,price_adjustment:parseFloat(ce.target.value)||0}),className:"w-32"}),e.jsx(U,{type:"submit",children:"Add"})]}),e.jsxs("div",{className:"space-y-2",children:[(ie=S==null?void 0:S.variants)==null?void 0:ie.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(U,{variant:"ghost",size:"icon",onClick:()=>u.mutateAsync({id:ce.id,productId:S.id}),children:e.jsx(In,{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 XQn=["pending_payment","order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed","cancelled","refunded"];function QQn(){var x,y,v;const{data:s,isLoading:t}=qQn(),n=HQn(),r=GQn(),[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)},p=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))},f=async(b,N)=>{if(!a||!b.target.files||b.target.files.length===0)return;h(!0);const S=b.target.files[0],A=S.name.split(".").pop(),T=`proofs/${a.id}/${N}/${Date.now()}.${A}`;try{const{error:L}=await q.storage.from("marketplace").upload(T,S);if(L)throw L;const{data:{publicUrl:M}}=q.storage.from("marketplace").getPublicUrl(T);await r.mutateAsync({itemId:N,proofUrl:M,orderId:a.id}),re.success("Proof uploaded successfully")}catch(L){re.error("Failed to upload proof: "+L.message)}finally{h(!1)}};return t?e.jsxs(we,{children:[e.jsx(Tt,{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(we,{children:[e.jsx(Tt,{children:e.jsx(It,{children:"Orders"})}),e.jsx(Ie,{children:s&&s.length>0?e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Order #"}),e.jsx(Lt,{children:"Customer"}),e.jsx(Lt,{children:"Date"}),e.jsx(Lt,{children:"Total"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:s.map(b=>{var N,S;return e.jsxs(gn,{children:[e.jsx(gt,{className:"font-mono",children:b.order_number}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((N=b.user)==null?void 0:N.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(S=b.user)==null?void 0:S.email})]})}),e.jsx(gt,{children:Gs(new Date(b.created_at),"MMM d, yyyy")}),e.jsxs(gt,{className:"font-bold",children:["$",Number(b.total).toFixed(2)]}),e.jsx(gt,{children:e.jsx(Be,{className:brt[b.status],children:o$[b.status]})}),e.jsx(gt,{className:"text-right",children:e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>m(b),children:[e.jsx(xa,{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(Ds,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsxs($s,{children:["Order ",a==null?void 0:a.order_number]})}),a&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Customer"}),e.jsx("p",{children:(x=a.user)==null?void 0:x.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(y=a.user)==null?void 0:y.email})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Shipping Address"}),e.jsx("p",{children:a.shipping_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[a.shipping_address,e.jsx("br",{}),a.shipping_city,", ",a.shipping_state," ",a.shipping_zip]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Order Items"}),e.jsx("div",{className:"space-y-3",children:(v=a.items)==null?void 0:v.map(b=>e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:b.product_name}),b.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:b.variant_name})]}),e.jsxs("p",{className:"font-bold",children:["$",Number(b.unit_price).toFixed(2)," x ",b.quantity]})]}),b.artwork_url&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:"Customer Artwork:"}),e.jsx("a",{href:b.artwork_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-sm",children:"View Artwork"})]}),e.jsx("div",{className:"mt-3 pt-3 border-t",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Proof Status: "}),e.jsx(Be,{variant:b.proof_status==="approved"?"default":"secondary",children:b.proof_status||"No proof yet"})]}),b.proof_url?e.jsx("a",{href:b.proof_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-sm",children:"View Proof"}):e.jsxs("div",{children:[e.jsx("input",{type:"file",accept:"image/*,.pdf",onChange:N=>f(N,b.id),className:"hidden",id:`proof-${b.id}`,disabled:u}),e.jsx("label",{htmlFor:`proof-${b.id}`,children:e.jsx(U,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("span",{children:[e.jsx(qa,{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(te,{children:"Status"}),e.jsxs(Ns,{value:c.status,onValueChange:b=>d({...c,status:b}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:XQn.map(b=>e.jsx(et,{value:b,children:o$[b]},b))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Tracking Number"}),e.jsx(xe,{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(te,{children:"Tracking URL"}),e.jsx(xe,{value:c.trackingUrl,onChange:b=>d({...c,trackingUrl:b.target.value}),placeholder:"https://..."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Notes (optional)"}),e.jsx(Fs,{value:c.notes,onChange:b=>d({...c,notes:b.target.value}),placeholder:"Add a note about this status change..."})]}),e.jsxs(U,{onClick:p,disabled:n.isPending,className:"w-full",children:[e.jsx(dh,{className:"h-4 w-4 mr-2"}),"Update Status"]})]})]}),a.status_history&&a.status_history.length>0&&e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:"Status History"}),e.jsx("div",{className:"space-y-2",children:a.status_history.map(b=>e.jsxs("div",{className:"flex justify-between text-sm p-2 bg-muted rounded",children:[e.jsxs("div",{children:[e.jsx(Be,{variant:"outline",children:o$[b.status]}),b.notes&&e.jsx("p",{className:"text-muted-foreground mt-1",children:b.notes})]}),e.jsx("span",{className:"text-muted-foreground",children:Gs(new Date(b.created_at),"MMM d, h:mm a")})]},b.id))})]})]})]})})]})}function JQn(){const[s,t]=j.useState("products"),n=Wn();return e.jsx(qs,{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(U,{variant:"outline",onClick:()=>n("/marketplace"),children:[e.jsx(Sr,{className:"h-4 w-4 mr-2"}),"View Store"]})]}),e.jsxs(oa,{value:s,onValueChange:t,children:[e.jsxs(la,{className:"grid w-full grid-cols-3",children:[e.jsxs(Kt,{value:"products",className:"flex items-center gap-2",children:[e.jsx(dh,{className:"h-4 w-4"}),"Products"]}),e.jsxs(Kt,{value:"categories",className:"flex items-center gap-2",children:[e.jsx(r1,{className:"h-4 w-4"}),"Categories"]}),e.jsxs(Kt,{value:"orders",className:"flex items-center gap-2",children:[e.jsx(sS,{className:"h-4 w-4"}),"Orders"]})]}),e.jsx(Zt,{value:"products",children:e.jsx(ZQn,{})}),e.jsx(Zt,{value:"categories",children:e.jsx(YQn,{})}),e.jsx(Zt,{value:"orders",children:e.jsx(QQn,{})})]})]})})}function qts(){return ct({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 eJn(s){return ct({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 tJn(s){return ct({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 sJn(s){return ct({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 nJn(){return ct({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 rJn(s){return ct({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 aJn(){const s=Qt();return yt({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 iJn(){const s=Qt();return yt({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 oJn(){const s=Qt();return yt({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 lJn(){const s=Qt();return yt({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 cJn(){const s=Qt();return yt({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 dJn(){const s=Qt();return yt({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 uJn(){const s=Qt();return yt({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 hJn(s){const t=s.match(/\/storage\/v1\/object\/public\/([^/]+)\/(.+)$/);return t?{bucket:t[1],path:t[2]}:null}async function xze(s,t){const n=hJn(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 $ts(){return ct({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 mJn(){const s=Qt();return yt({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 pJn(){const{user:s}=vs(),[t,n]=j.useState("items"),[r,a]=j.useState(!1),[i,l]=j.useState(null),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,f]=j.useState(null),[x,y]=j.useState(!1),[v,b]=j.useState(null),[N,S]=j.useState(""),[A,T]=j.useState(""),[L,M]=j.useState(null),[I,R]=j.useState(""),[z,$]=j.useState("file"),[H,V]=j.useState(""),[K,Z]=j.useState(""),[Q,le]=j.useState(""),[ue,se]=j.useState(!0),[ne,ie]=j.useState(null),[ce,je]=j.useState(!1),[be,he]=j.useState(!1),ge=j.useRef(null),ke=j.useRef(null),{data:Te,isLoading:Me}=qts(),{data:Oe,isLoading:Se}=eJn(),{data:Qe,isLoading:Ae}=nJn(),{data:Fe,isLoading:Ne}=$ts(),$e=iJn(),Ve=oJn(),qe=lJn(),Ze=cJn(),Ue=dJn(),Ye=uJn(),Ge=mJn(),[He,tt]=j.useState({}),pt=vt=>{vt?(l(vt),c(vt.name),u(vt.description||""),m(vt.icon||"")):(l(null),c(""),u(""),m("")),a(!0)},ft=async()=>{if(!o.trim()){re.error("Please enter a category name");return}try{i?(await Ve.mutateAsync({id:i.id,name:o,description:d||null,icon:h||null}),re.success("Category updated successfully")):(await $e.mutateAsync({name:o,description:d||null,icon:h||null,sort_order:((Te==null?void 0:Te.length)||0)+1}),re.success("Category created successfully")),a(!1)}catch(vt){console.error("Error saving category:",vt),re.error("Failed to save category")}},qt=async()=>{if(p)try{await qe.mutateAsync(p),re.success("Category deleted successfully"),f(null)}catch(vt){console.error("Error deleting category:",vt),re.error("Failed to delete category")}},Ut=vt=>{var Ws;vt?(b(vt),S(vt.name),T(vt.description||""),M(vt.category_id),R(vt.points_cost.toString()),$(vt.item_type),V(vt.file_url||""),Z(vt.preview_image_url||""),le(((Ws=vt.max_quantity)==null?void 0:Ws.toString())||""),se(vt.is_active)):(b(null),S(""),T(""),M(null),R(""),$("file"),V(""),Z(""),le(""),se(!0)),y(!0)},Wt=async(vt,Ws)=>{Ws==="file"?je(!0):he(!0);try{const on=vt.name.split(".").pop(),Ms=`${Date.now()}-${Math.random().toString(36).substring(7)}.${on}`,dn=`${Ws==="file"?"items":"previews"}/${Ms}`,{error:rn}=await q.storage.from("reward-store").upload(dn,vt);if(rn)throw rn;const{data:{publicUrl:br}}=q.storage.from("reward-store").getPublicUrl(dn);Ws==="file"?V(br):Z(br),re.success("File uploaded successfully")}catch(on){console.error("Error uploading file:",on),re.error("Failed to upload file")}finally{Ws==="file"?je(!1):he(!1)}},us=async()=>{if(!N.trim()){re.error("Please enter an item name");return}if(!I||parseInt(I)<0){re.error("Please enter a valid points cost");return}try{const vt={name:N,description:A||null,category_id:L,points_cost:parseInt(I),item_type:z,file_url:H||null,preview_image_url:K||null,max_quantity:Q?parseInt(Q):null,current_quantity:Q?parseInt(Q):null,is_active:ue,created_by:s==null?void 0:s.id};v?(await Ue.mutateAsync({id:v.id,...vt,current_quantity:v.max_quantity!==(Q?parseInt(Q):null)?Q?parseInt(Q):null:v.current_quantity}),re.success("Item updated successfully")):(await Ze.mutateAsync(vt),re.success("Item created successfully")),y(!1)}catch(vt){console.error("Error saving item:",vt),re.error("Failed to save item")}},zt=async()=>{if(ne)try{await Ye.mutateAsync(ne),re.success("Item deleted successfully"),ie(null)}catch(vt){console.error("Error deleting item:",vt),re.error("Failed to delete item")}},bt=async(vt,Ws)=>{const on=He[vt];if(on===void 0||on===Ws.toString())return;const Ms=parseInt(on);if(isNaN(Ms)||Ms<0){re.error("Please enter a valid positive number");return}try{await Ge.mutateAsync({id:vt,points:Ms}),re.success("Points updated successfully"),tt(dn=>{const rn={...dn};return delete rn[vt],rn})}catch(dn){console.error("Error updating points:",dn),re.error("Failed to update points")}};return Me||Se||Ae||Ne?e.jsx(qs,{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(qs,{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(we,{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(dh,{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:(Oe==null?void 0:Oe.length)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(Oe==null?void 0:Oe.filter(vt=>vt.is_active).length)||0," active"]})]})}),e.jsx(we,{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(r1,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Categories"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(Te==null?void 0:Te.length)||0})]})}),e.jsx(we,{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(Ua,{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:[Oe&&Oe.length>0?Math.round(Oe.reduce((vt,Ws)=>vt+Ws.points_cost,0)/Oe.length):0," pts"]})]})})]}),e.jsxs(oa,{value:t,onValueChange:n,children:[e.jsxs(la,{children:[e.jsx(Kt,{value:"items",children:"Items"}),e.jsx(Kt,{value:"categories",children:"Categories"}),e.jsx(Kt,{value:"purchases",children:"Purchases"}),e.jsx(Kt,{value:"point-settings",children:"Point Settings"})]}),e.jsx(Zt,{value:"items",className:"mt-4",children:e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Store Items"}),e.jsx(Jn,{children:"Manage rewards that agents can purchase"})]}),e.jsxs(U,{onClick:()=>Ut(),children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Add Item"]})]}),e.jsx(Ie,{children:!Oe||Oe.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Ro,{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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Item"}),e.jsx(Lt,{children:"Category"}),e.jsx(Lt,{className:"text-center",children:"Cost"}),e.jsx(Lt,{className:"text-center",children:"Type"}),e.jsx(Lt,{className:"text-center",children:"Quantity"}),e.jsx(Lt,{className:"text-center",children:"Status"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:Oe.map(vt=>e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[vt.preview_image_url?e.jsx("img",{src:vt.preview_image_url,alt:vt.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(Ro,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:vt.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:vt.description||"No description"})]})]})}),e.jsx(gt,{children:vt.category?e.jsx(Be,{variant:"outline",children:vt.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{className:"text-center",children:e.jsxs(Be,{variant:"secondary",className:"font-bold",children:[e.jsx(Ua,{className:"h-3 w-3 mr-1"}),vt.points_cost]})}),e.jsx(gt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[vt.item_type==="file"?e.jsx(Ur,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Rc,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs capitalize",children:vt.item_type})]})}),e.jsx(gt,{className:"text-center",children:vt.max_quantity!==null?e.jsxs("span",{className:vt.current_quantity===0?"text-red-500":"",children:[vt.current_quantity,"/",vt.max_quantity]}):e.jsx("span",{className:"text-muted-foreground",children:"Unlimited"})}),e.jsx(gt,{className:"text-center",children:e.jsx(Be,{variant:vt.is_active?"default":"secondary",children:vt.is_active?"Active":"Inactive"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>Ut(vt),children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>ie(vt.id),children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]})})]},vt.id))})]})})]})}),e.jsx(Zt,{value:"categories",className:"mt-4",children:e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Categories"}),e.jsx(Jn,{children:"Organize your store items into categories"})]}),e.jsxs(U,{onClick:()=>pt(),children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(Ie,{children:!Te||Te.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(r1,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No categories yet. Add your first category!"})]}):e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Name"}),e.jsx(Lt,{children:"Description"}),e.jsx(Lt,{className:"text-center",children:"Items"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Xa,{children:Te.map(vt=>e.jsxs(gn,{children:[e.jsxs(gt,{className:"font-medium",children:[vt.icon&&e.jsx("span",{className:"mr-2",children:vt.icon}),vt.name]}),e.jsx(gt,{className:"text-muted-foreground",children:vt.description||"—"}),e.jsx(gt,{className:"text-center",children:(Oe==null?void 0:Oe.filter(Ws=>Ws.category_id===vt.id).length)||0}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>pt(vt),children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>f(vt.id),children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]})})]},vt.id))})]})})]})}),e.jsx(Zt,{value:"purchases",className:"mt-4",children:e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(sS,{className:"h-5 w-5"}),"Purchase History"]}),e.jsx(Jn,{children:"View all reward redemptions by agents"})]}),e.jsx(Ie,{children:!Qe||Qe.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(sS,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No purchases yet."})]}):e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Date"}),e.jsx(Lt,{children:"Agent"}),e.jsx(Lt,{children:"Item"}),e.jsx(Lt,{className:"text-center",children:"Points Spent"})]})}),e.jsx(Xa,{children:Qe.map(vt=>{var Ws,on,Ms,dn;return e.jsxs(gn,{children:[e.jsx(gt,{className:"text-muted-foreground",children:Gs(new Date(vt.purchased_at),"MMM d, yyyy 'at' h:mm a")}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center",children:e.jsx(So,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Ws=vt.user)==null?void 0:Ws.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:((on=vt.user)==null?void 0:on.email)||"—"})]})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[(Ms=vt.item)!=null&&Ms.preview_image_url?e.jsx("img",{src:vt.item.preview_image_url,alt:vt.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(Ro,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{children:((dn=vt.item)==null?void 0:dn.name)||"Deleted item"})]})}),e.jsx(gt,{className:"text-center",children:e.jsxs(Be,{variant:"secondary",className:"font-bold",children:[e.jsx(Ua,{className:"h-3 w-3 mr-1"}),vt.points_spent]})})]},vt.id)})})]})})]})})]})]}),e.jsx(zs,{open:r,onOpenChange:a,children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{htmlFor:"categoryName",children:"Name"}),e.jsx(xe,{id:"categoryName",value:o,onChange:vt=>c(vt.target.value),placeholder:"e.g., Templates, Resources"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"categoryDescription",children:"Description"}),e.jsx(Fs,{id:"categoryDescription",value:d,onChange:vt=>u(vt.target.value),placeholder:"Optional description..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"categoryIcon",children:"Icon (emoji)"}),e.jsx(xe,{id:"categoryIcon",value:h,onChange:vt=>m(vt.target.value),placeholder:"e.g., 📄, 🎁"})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(U,{onClick:ft,disabled:$e.isPending||Ve.isPending,children:$e.isPending||Ve.isPending?"Saving...":"Save"})]})]})}),e.jsx(zs,{open:x,onOpenChange:y,children:e.jsxs(Ds,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{htmlFor:"itemName",children:"Name *"}),e.jsx(xe,{id:"itemName",value:N,onChange:vt=>S(vt.target.value),placeholder:"e.g., Premium Template Pack"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"itemDescription",children:"Description"}),e.jsx(Fs,{id:"itemDescription",value:A,onChange:vt=>T(vt.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(te,{htmlFor:"itemCategory",children:"Category"}),e.jsxs(Ns,{value:L||"none",onValueChange:vt=>M(vt==="none"?null:vt),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select category"})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"No category"}),Te==null?void 0:Te.map(vt=>e.jsxs(et,{value:vt.id,children:[vt.icon&&`${vt.icon} `,vt.name]},vt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"itemPointsCost",children:"Points Cost *"}),e.jsx(xe,{id:"itemPointsCost",type:"number",min:"0",value:I,onChange:vt=>R(vt.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(te,{htmlFor:"itemType",children:"Type"}),e.jsxs(Ns,{value:z,onValueChange:$,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"file",children:"File Download"}),e.jsx(et,{value:"link",children:"External Link"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"itemMaxQuantity",children:"Max Quantity"}),e.jsx(xe,{id:"itemMaxQuantity",type:"number",min:"1",value:Q,onChange:vt=>le(vt.target.value),placeholder:"Leave empty for unlimited"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"File / Link URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:H,onChange:vt=>V(vt.target.value),placeholder:z==="file"?"Upload a file or paste URL":"Paste external link"}),z==="file"&&e.jsxs(e.Fragment,{children:[e.jsx(U,{type:"button",variant:"outline",size:"icon",onClick:()=>{var vt;return(vt=ge.current)==null?void 0:vt.click()},disabled:ce,children:e.jsx(qa,{className:"h-4 w-4"})}),e.jsx("input",{ref:ge,type:"file",className:"hidden",onChange:vt=>{var on;const Ws=(on=vt.target.files)==null?void 0:on[0];Ws&&Wt(Ws,"file")}})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Preview Image"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:K,onChange:vt=>Z(vt.target.value),placeholder:"Upload an image or paste URL"}),e.jsx(U,{type:"button",variant:"outline",size:"icon",onClick:()=>{var vt;return(vt=ke.current)==null?void 0:vt.click()},disabled:be,children:e.jsx(pc,{className:"h-4 w-4"})}),e.jsx("input",{ref:ke,type:"file",accept:"image/*",className:"hidden",onChange:vt=>{var on;const Ws=(on=vt.target.files)==null?void 0:on[0];Ws&&Wt(Ws,"preview")}})]}),K&&e.jsx("img",{src:K,alt:"Preview",className:"mt-2 h-24 rounded object-cover"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wn,{id:"itemIsActive",checked:ue,onCheckedChange:se}),e.jsx(te,{htmlFor:"itemIsActive",children:"Active (visible to agents)"})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx(U,{onClick:us,disabled:Ze.isPending||Ue.isPending,children:Ze.isPending||Ue.isPending?"Saving...":"Save"})]})]})}),e.jsx(Fl,{open:!!p,onOpenChange:()=>f(null),children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Delete Category"}),e.jsx(Ll,{children:"Are you sure you want to delete this category? Items in this category will become uncategorized."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:qt,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(Fl,{open:!!ne,onOpenChange:()=>ie(null),children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Delete Item"}),e.jsx(Ll,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:zt,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),t==="point-settings"&&e.jsxs(we,{className:"mt-4",children:[e.jsx(Tt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qc,{className:"h-5 w-5"}),e.jsxs("div",{children:[e.jsx(It,{children:"Point Reward Settings"}),e.jsx(Jn,{children:"Configure how many points agents earn for various actions. Adjust these values to run double-points promotions."})]})]})}),e.jsx(Ie,{children:!Fe||Fe.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(qc,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No point settings configured."})]}):e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Action"}),e.jsx(Lt,{children:"Description"}),e.jsx(Lt,{className:"text-center w-32",children:"Points"}),e.jsx(Lt,{className:"text-right w-24",children:"Save"})]})}),e.jsx(Xa,{children:Fe.map(vt=>e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsx("p",{className:"font-medium",children:vt.action_name})}),e.jsx(gt,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:vt.description})}),e.jsx(gt,{className:"text-center",children:e.jsx(xe,{type:"number",min:"0",className:"w-20 mx-auto text-center",value:He[vt.id]??vt.points.toString(),onChange:Ws=>tt(on=>({...on,[vt.id]:Ws.target.value}))})}),e.jsx(gt,{className:"text-right",children:e.jsx(U,{size:"sm",variant:"outline",disabled:He[vt.id]===void 0||He[vt.id]===vt.points.toString()||Ge.isPending,onClick:()=>bt(vt.id,vt.points),children:e.jsx(Ho,{className:"h-4 w-4"})})})]},vt.id))})]})})]})]})}const LSt=()=>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"})]}),ISt=[{value:"template",label:"Templates"},{value:"brand",label:"Brand Assets"},{value:"listing",label:"Listing Assets"},{value:"social",label:"Social Media"},{value:"general",label:"General"}];function fJn(){const s=Qt(),[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}=ct({queryKey:["canva-integration"],queryFn:async()=>{const{data:b,error:N}=await q.from("canva_integration").select("*").eq("is_active",!0).maybeSingle();if(N)throw N;return b}}),{data:h}=ct({queryKey:["brokerages-list"],queryFn:async()=>{const{data:b,error:N}=await q.from("brokerages").select("id, name").order("name");if(N)throw N;return b}}),{data:m}=ct({queryKey:["canva-brokerage-folders"],queryFn:async()=>{const{data:b,error:N}=await q.from("canva_brokerage_folders").select("*, brokerages(name)").order("sort_order");if(N)throw N;return b}}),p=async()=>{var b;n(!0);try{const{data:N}=await q.auth.getSession(),S=(b=N==null?void 0:N.session)==null?void 0:b.access_token;if(!S)throw new Error("Not authenticated");const L=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"})}),M=await L.json();if(!L.ok||M!=null&&M.error)throw new Error((M==null?void 0:M.error)||"Failed to get authorization URL");if(M!=null&&M.authUrl){localStorage.setItem("canva_code_verifier",M.codeVerifier),localStorage.setItem("canva_oauth_state",M.state);const I=window.open(M.authUrl,"canva-oauth","width=600,height=700,scrollbars=yes,resizable=yes");if(!I){re.error("Popup was blocked. Please allow popups for this site and try again."),n(!1);return}const R=$=>{var H,V;$.origin===window.location.origin&&(((H=$.data)==null?void 0:H.type)==="canva-oauth-success"?(window.removeEventListener("message",R),re.success("Canva connected successfully!"),s.invalidateQueries({queryKey:["canva-integration"]}),n(!1)):((V=$.data)==null?void 0:V.type)==="canva-oauth-error"&&(window.removeEventListener("message",R),re.error("Canva connection failed: "+($.data.error||"Unknown error")),n(!1)))};window.addEventListener("message",R);const z=setInterval(()=>{I.closed&&(clearInterval(z),window.removeEventListener("message",R),s.invalidateQueries({queryKey:["canva-integration"]}),n(!1))},500)}else throw new Error("Failed to get authorization URL")}catch(N){console.error("Canva connect error:",N);const S=(N==null?void 0:N.message)||"";S.includes("CANVA_CLIENT_ID")?re.error("Canva app credentials not configured yet."):re.error(S||"Failed to start Canva connection"),n(!1)}},f=yt({mutationFn:async b=>{var I;const{data:N}=await q.auth.getSession(),S=(I=N==null?void 0:N.session)==null?void 0:I.access_token;if(!S)throw new Error("Not authenticated");const L=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})}),M=await L.json();if(!L.ok||M!=null&&M.error)throw new Error((M==null?void 0:M.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=yt({mutationFn:async b=>{const{error:N}=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(N)throw N},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=yt({mutationFn:async b=>{const{error:N}=await q.from("canva_brokerage_folders").delete().eq("id",b);if(N)throw N},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(we,{children:[e.jsx(Tt,{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(LSt,{})}),e.jsxs("div",{children:[e.jsxs(It,{className:"text-lg flex items-center gap-2",children:["Canva Connect",v&&e.jsx(Be,{variant:"default",className:"text-xs",children:"Connected"}),e.jsx(Be,{variant:"outline",className:"text-xs",children:"Admin Only"})]}),e.jsx(Jn,{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(Yo,{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(Yo,{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(Yo,{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(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(In,{className:"h-4 w-4"})})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Disconnect Canva?"}),e.jsx(Ll,{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(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>f.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(r1,{className:"h-4 w-4 text-primary"}),"Brokerage Folder Mappings",m&&m.length>0&&e.jsx(Be,{variant:"secondary",className:"text-xs",children:m.length})]}),r?e.jsx(dv,{className:"h-4 w-4"}):e.jsx(rl,{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 N,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(Be,{variant:"outline",className:"text-xs shrink-0",children:((N=ISt.find(A=>A.value===b.folder_type))==null?void 0:N.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(U,{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(er,{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(U,{variant:"outline",size:"sm",className:"w-full gap-1.5 mt-1",onClick:()=>l(!0),children:[e.jsx(an,{className:"h-3.5 w-3.5"}),"Add Folder Mapping"]})]})]})]}):e.jsxs(U,{className:"mt-4",onClick:p,disabled:t||u,children:[t?e.jsx(no,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx("div",{className:"mr-2",children:e.jsx(LSt,{})}),"Connect Canva",e.jsx(Oa,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Add Brokerage Folder Mapping"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Brokerage"}),e.jsxs(Ns,{value:o.brokerage_id,onValueChange:b=>c(N=>({...N,brokerage_id:b})),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select a brokerage…"})}),e.jsx(js,{children:h==null?void 0:h.map(b=>e.jsx(et,{value:b.id,children:b.name},b.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Canva Folder ID"}),e.jsx(xe,{placeholder:"e.g. FABCdef123456",value:o.folder_id,onChange:b=>c(N=>({...N,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(te,{children:"Folder Display Name"}),e.jsx(xe,{placeholder:"e.g. Brand Templates 2024",value:o.folder_name,onChange:b=>c(N=>({...N,folder_name:b.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Folder Type"}),e.jsxs(Ns,{value:o.folder_type,onValueChange:b=>c(N=>({...N,folder_type:b})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:ISt.map(b=>e.jsx(et,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(te,{children:["Description ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(xe,{placeholder:"What's in this folder?",value:o.description,onChange:b=>c(N=>({...N,description:b.target.value}))})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(U,{onClick:()=>x.mutate(o),disabled:!o.brokerage_id||!o.folder_id||!o.folder_name||x.isPending,children:[x.isPending?e.jsx(no,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Add Folder"]})]})]})})]})}function gJn(){const s=Wn();return e.jsx(qs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Xh,{title:"Integrations",description:"Manage platform-level service connections"}),e.jsxs(we,{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(jd,{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(U,{onClick:()=>s("/admin/social-connections"),children:["View ",e.jsx(Oa,{className:"h-4 w-4 ml-1"})]})]}),e.jsx(fJn,{}),e.jsx(Ots,{})]})})}const RSt=s=>{const t="h-4 w-4";return s==="facebook"?e.jsx(zp,{className:t}):s==="instagram"?e.jsx(gm,{className:t}):s==="linkedin"?e.jsx(Gg,{className:t}):s==="google"?e.jsx(ln,{className:t}):null},xJn=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric",month:"short",day:"numeric"}).format(new Date(s)):"—";function yJn(){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:p}=await q.rpc("admin_get_social_connections");if(p){re.error(p.message),r(!1);return}t(m||[]),r(!1)})()},[]);const c=j.useMemo(()=>{const m=a.trim().toLowerCase();return s.filter(p=>l!=="all"&&p.platform!==l?!1:m?(p.user_name||"").toLowerCase().includes(m)||(p.user_email||"").toLowerCase().includes(m)||(p.page_name||"").toLowerCase().includes(m)||(p.platform_username||"").toLowerCase().includes(m):!0)},[s,a,l]),d=j.useMemo(()=>{const m=new Map;return s.forEach(p=>{const f=m.get(p.user_id)||{name:p.user_name,email:p.user_email,platforms:new Set,count:0};f.platforms.add(p.platform),f.count+=1,m.set(p.user_id,f)}),Array.from(m.entries()).map(([p,f])=>({user_id:p,...f}))},[s]),u=j.useMemo(()=>{const m=new Map;return s.forEach(p=>m.set(p.platform,(m.get(p.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(we,{className:"p-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground capitalize flex items-center gap-2",children:[RSt(m)," ",m]}),e.jsx("div",{className:"text-2xl font-bold",children:p})]},m))]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3",children:[e.jsx(xe,{placeholder:"Search by user, email, page, or handle…",value:a,onChange:m=>i(m.target.value),className:"md:max-w-md"}),e.jsxs(Ns,{value:l,onValueChange:o,children:[e.jsx(ws,{className:"md:w-48",children:e.jsx(ks,{placeholder:"All platforms"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All platforms"}),e.jsx(et,{value:"facebook",children:"Facebook"}),e.jsx(et,{value:"instagram",children:"Instagram"}),e.jsx(et,{value:"linkedin",children:"LinkedIn"}),e.jsx(et,{value:"google",children:"Google"})]})]})]}),e.jsx(we,{children:n?e.jsx("div",{className:"flex items-center justify-center p-12",children:e.jsx(Et,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"User"}),e.jsx(Lt,{children:"Platform"}),e.jsx(Lt,{children:"Page / Account"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{children:"Connected"})]})}),e.jsx(Xa,{children:c.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:5,className:"text-center text-muted-foreground py-8",children:"No connections found."})}):c.map(m=>{const p=h(m.token_expires_at);return e.jsxs(gn,{children:[e.jsxs(gt,{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(gt,{children:e.jsxs("div",{className:"flex items-center gap-2 capitalize",children:[RSt(m.platform)," ",m.platform]})}),e.jsxs(gt,{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(gt,{children:m.is_active?p?e.jsxs(Be,{variant:"destructive",className:"gap-1",children:[e.jsx(Vo,{className:"h-3 w-3"})," Expired"]}):e.jsx(Be,{children:"Active"}):e.jsx(Be,{variant:"secondary",children:"Inactive"})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:xJn(m.created_at)})]},m.id)})})]})})]})})}const vJn={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 HY(s,t=18,n=10){return s.length<=t+n+3?s:`${s.slice(0,t)}…${s.slice(-n)}`}function bJn(){var z,$,H,V,K;const s=Qt(),[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}),[p,f]=j.useState(null),[x,y]=j.useState(null),{data:v,isLoading:b}=ct({queryKey:["push-notification-settings"],queryFn:async()=>{const{data:Z,error:Q}=await q.from("push_notification_settings").select("*").order("setting_key");if(Q)throw Q;return Z}}),{data:N,isLoading:S}=ct({queryKey:["push-subscription-stats"],queryFn:async()=>{const{count:Z,error:Q}=await q.from("push_subscriptions").select("*",{count:"exact",head:!0});if(Q)throw Q;return{totalSubscriptions:Z||0}}}),A=yt({mutationFn:async({settingKey:Z,isEnabled:Q})=>{const{error:le}=await q.from("push_notification_settings").update({is_enabled:Q}).eq("setting_key",Z);if(le)throw le},onSuccess:()=>{s.invalidateQueries({queryKey:["push-notification-settings"]}),re.success("Notification setting updated")},onError:Z=>{re.error("Failed to update setting: "+Z.message)}}),T=j.useMemo(()=>{var Z,Q;return h.isSupported?`perm=${h.permission??"unknown"} · controller=${h.controllerPresent?"yes":"no"} · sw=${((Z=h.serviceWorker)==null?void 0:Z.activeState)??"unknown"} · sub=${(Q=h.subscription)!=null&&Q.endpoint?"yes":"no"}`:"Push not supported in this browser."},[h]);j.useEffect(()=>{let Z=!0;const Q=async()=>{var ne,ie,ce,je,be,he,ge;const ue="serviceWorker"in navigator&&"PushManager"in window,se={isSupported:ue,permission:typeof Notification<"u"?Notification.permission:void 0,controllerPresent:!!((ne=navigator.serviceWorker)!=null&&ne.controller)};if(!ue){Z&&m(se);return}try{const{data:ke,error:Te}=await q.functions.invoke("get-vapid-public-key",{body:{}});if(Te)throw Te;se.vapidPublicKey=ke==null?void 0:ke.vapidPublicKey;const Oe=(await navigator.serviceWorker.getRegistrations()).find(Se=>{var Ae,Fe,Ne;return(((Ae=Se.active)==null?void 0:Ae.scriptURL)||((Fe=Se.waiting)==null?void 0:Fe.scriptURL)||((Ne=Se.installing)==null?void 0:Ne.scriptURL)||"").includes("/sw.js")});if(Oe){se.pushWorkerScriptUrl=((ie=Oe.active)==null?void 0:ie.scriptURL)||((ce=Oe.waiting)==null?void 0:ce.scriptURL)||((je=Oe.installing)==null?void 0:je.scriptURL),se.serviceWorker={scope:Oe.scope,activeState:(be=Oe.active)==null?void 0:be.state};const Se=await Oe.pushManager.getSubscription();if(Se){const Qe=Se.toJSON();se.subscription={endpoint:Qe.endpoint,p256dh:(he=Qe.keys)==null?void 0:he.p256dh,auth:(ge=Qe.keys)==null?void 0:ge.auth}}}}catch(ke){se.error=(ke==null?void 0:ke.message)||String(ke)}Z&&m(se)};Q();const le=window.setInterval(Q,4e3);return()=>{Z=!1,window.clearInterval(le)}},[]);const L=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(Z){re.error(`Local notification failed: ${(Z==null?void 0:Z.message)||String(Z)}`)}},M=async()=>{c(!0),f(null);try{const{data:Z,error:Q}=await q.functions.invoke("send-push-notification",{body:{title:t,body:r,url:i}});if(Q)throw Q;f({sent:Z==null?void 0:Z.sent,failed:Z==null?void 0:Z.failed,expiredCleaned:Z==null?void 0:Z.expiredCleaned,vapidPublicKey:Z==null?void 0:Z.vapidPublicKey}),(Z==null?void 0:Z.sent)>0?re.success(`Test notification sent to ${Z.sent} subscriber(s)`):(Z==null?void 0:Z.failed)>0?re.warning(`Notification failed for ${Z.failed} subscriber(s). ${Z.expired||0} expired subscriptions cleaned up.`):re.info("No active subscriptions to send to")}catch(Z){console.error("Error sending test notification:",Z),f({error:(Z==null?void 0:Z.message)||String(Z)}),re.error("Failed to send test notification: "+(Z.message||"Unknown error"))}finally{c(!1)}},I=async()=>{u(!0),y(null);try{const{data:Z,error:Q}=await q.functions.invoke("generate-vapid-keys",{body:{}});if(Q)throw Q;const le=Z==null?void 0:Z.publicKey,ue=Z==null?void 0:Z.privateKey;if(!le||!ue)throw new Error("generate-vapid-keys did not return keys");y({publicKey:le,privateKey:ue}),re.success("Generated new VAPID keys. Update backend secrets, then clear + re-subscribe.")}catch(Z){console.error("Error generating VAPID keys:",Z),re.error("Failed to generate VAPID keys: "+((Z==null?void 0:Z.message)||"Unknown error"))}finally{u(!1)}},R=yt({mutationFn:async()=>{const{error:Z}=await q.from("push_subscriptions").delete().neq("id","00000000-0000-0000-0000-000000000000");if(Z)throw Z},onSuccess:()=>{re.success("All subscriptions cleared. Users will need to re-enable notifications."),s.invalidateQueries({queryKey:["push-subscription-stats"]})},onError:Z=>{re.error("Failed to clear subscriptions: "+Z.message)}});return e.jsx(qs,{title:"Notification Settings",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{title:"Notification Settings",description:"Manage push notifications and test the notification system"}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-5 w-5"}),"Push Notification Subscribers"]}),e.jsx(Jn,{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?"...":(N==null?void 0:N.totalSubscriptions)||0}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"active subscriptions"})]})})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(qc,{className:"h-5 w-5"}),"Notification Types"]}),e.jsx(Jn,{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(Z=>{const Q=vJn[Z.setting_key]||{label:Z.setting_key,icon:"🔔"};return e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-2xl",children:Q.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Q.label}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Z.description})]})]}),e.jsx(wn,{checked:Z.is_enabled,onCheckedChange:le=>A.mutate({settingKey:Z.setting_key,isEnabled:le}),disabled:A.isPending})]},Z.id)})})})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(bx,{className:"h-5 w-5"}),"Send Test Notification"]}),e.jsx(Jn,{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:T}),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?HY(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: ",(z=h.serviceWorker)!=null&&z.scope?HY(h.serviceWorker.scope,24,8):"none"]}),e.jsxs("div",{children:["active: ",(($=h.serviceWorker)==null?void 0:$.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: ",(H=h.subscription)!=null&&H.endpoint?HY(h.subscription.endpoint,40,12):"none"]}),e.jsxs("div",{children:["p256dh: ",(V=h.subscription)!=null&&V.p256dh?HY(h.subscription.p256dh,22,10):"none"]}),e.jsxs("div",{children:["auth: ",(K=h.subscription)!=null&&K.auth?HY(h.subscription.auth,22,10):"none"]})]})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(U,{variant:"outline",onClick:L,children:"Local notification test"}),e.jsx(U,{variant:"outline",onClick:()=>window.location.reload(),children:"Reload page"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"test-title",children:"Notification Title"}),e.jsx(xe,{id:"test-title",value:t,onChange:Z=>n(Z.target.value),placeholder:"Enter notification title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"test-body",children:"Notification Body"}),e.jsx(Fs,{id:"test-body",value:r,onChange:Z=>a(Z.target.value),placeholder:"Enter notification message",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"test-url",children:"Click URL (optional)"}),e.jsx(xe,{id:"test-url",value:i,onChange:Z=>l(Z.target.value),placeholder:"/community or full URL"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Where users will be taken when they click the notification"})]}),e.jsxs(U,{onClick:M,disabled:o||!t||!r,className:"w-full sm:w-auto",children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),o?"Sending...":"Send Test Notification"]}),p&&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"}),p.error?e.jsxs("div",{className:"mt-1 text-destructive",children:["Error: ",p.error]}):e.jsxs("div",{className:"mt-1 space-y-1 text-muted-foreground",children:[e.jsxs("div",{children:["Result: ",p.sent??0," sent, ",p.failed??0," failed, ",p.expiredCleaned??0," expired cleaned"]}),p.vapidPublicKey?e.jsxs("div",{className:"break-all",children:["Backend VAPID public key: ",e.jsx("span",{className:"font-mono",children:p.vapidPublicKey})]}):e.jsx("div",{children:"Backend VAPID public key: (not returned)"})]})]})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(In,{className:"h-5 w-5"}),"Subscription Maintenance"]}),e.jsx(Jn,{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(U,{variant:"destructive",onClick:()=>R.mutate(),disabled:R.isPending,children:[e.jsx(In,{className:"h-4 w-4 mr-2"}),R.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(U,{variant:"outline",onClick:I,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 _Jn(){const{toast:s}=Ai(),[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}=Sre("presentation_count","desc"),h=u(t,{name:f=>{var x;return((x=f.name)==null?void 0:x.toLowerCase())||""},presentations:f=>f.presentation_count,views:f=>f.total_views,leads:f=>f.total_leads,cta_clicks:f=>f.total_cta_clicks,conversion:f=>f.total_views>0?f.total_leads/f.total_views*100:0});j.useEffect(()=>{m()},[]);const m=async()=>{try{l(!0);const{data:f,error:x}=await q.rpc("get_admin_presentation_stats");if(x)throw x;if(!f||f.length===0){l(!1);return}const y=f.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 N=new Map((v==null?void 0:v.map(A=>[A.id,A]))||[]),S=f.map(A=>{const T=N.get(A.owner_user_id);return{owner_user_id:A.owner_user_id,name:(T==null?void 0:T.name)||"Unknown",email:(T==null?void 0:T.email)||"",avatar_url:(T==null?void 0:T.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,T)=>A+T.presentation_count,0),totalViews:S.reduce((A,T)=>A+T.total_views,0),totalLeads:S.reduce((A,T)=>A+T.total_leads,0),totalCtaClicks:S.reduce((A,T)=>A+T.total_cta_clicks,0),agentsUsing:S.length})}catch(f){console.error("Error loading presentation stats:",f),s({title:"Error",description:"Failed to load presentation analytics",variant:"destructive"})}finally{l(!1)}},p=[{label:"Agents Using",value:r.agentsUsing,icon:Bn,color:"text-blue-600"},{label:"Total Presentations",value:r.totalPresentations,icon:hv,color:"text-violet-600"},{label:"Total Views",value:r.totalViews,icon:xa,color:"text-emerald-600"},{label:"Total Leads",value:r.totalLeads,icon:zl,color:"text-amber-600"},{label:"CTA Clicks",value:r.totalCtaClicks,icon:Ch,color:"text-rose-600"}];return e.jsx(qs,{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:p.map(f=>e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{className:"text-sm font-medium",children:f.label}),e.jsx(f.icon,{className:`h-4 w-4 ${f.color}`})]}),e.jsx(Ie,{children:i?e.jsx(xn,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:f.value.toLocaleString()})})]},f.label))}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(rc,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Ie,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((f,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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Sh,{sortKey:"name",currentSortKey:o,currentDirection:c,onSort:d,children:"Agent"}),e.jsx(Sh,{sortKey:"presentations",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Presentations"}),e.jsx(Sh,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Views"}),e.jsx(Sh,{sortKey:"leads",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Leads"}),e.jsx(Sh,{sortKey:"cta_clicks",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"CTA Clicks"}),e.jsx(Sh,{sortKey:"conversion",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Conversion"})]})}),e.jsx(Xa,{children:h.map(f=>{var y,v;const x=f.total_views>0?(f.total_leads/f.total_views*100).toFixed(1):"0.0";return e.jsxs(gn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center overflow-hidden",children:f.avatar_url?e.jsx("img",{src:f.avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((v=(y=f.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:f.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:f.email})]})]})}),e.jsx(gt,{className:"text-center font-medium",children:f.presentation_count}),e.jsx(gt,{className:"text-center",children:f.total_views.toLocaleString()}),e.jsx(gt,{className:"text-center",children:f.total_leads>0?e.jsx(Be,{variant:"secondary",children:f.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(gt,{className:"text-center",children:f.total_cta_clicks}),e.jsx(gt,{className:"text-center",children:e.jsxs("span",{className:Number(x)>0?"text-emerald-600 font-medium":"text-muted-foreground",children:[x,"%"]})})]},f.owner_user_id)})})]})})]})]})})}const yze=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)):"—",wJn=s=>s==null?"—":`$${Number(s).toLocaleString("en-US",{maximumFractionDigits:0})}`;function jJn(){const{toast:s}=Ai(),[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:T}=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(T)throw T;if(y.push(...A??[]),!A||A.lengthS.owner_user_id))),N={};for(let S=0;S{N[T.id]={name:T.name??"Unknown",email:T.email??""}})}l(N)}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,p=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,f=[{label:"Total presentations",value:d.total,icon:Ur,sub:"All time"},{label:"Agents using it",value:d.agents,icon:Bn,sub:"Created at least one"},{label:"PDFs generated",value:d.generated,icon:cn,sub:"Rendered at least once"},{label:"Created last 30 days",value:d.thisMonth,icon:ch,sub:`${d.thisWeek} in last 7 days`}];return e.jsx(qs,{title:"Listing Presentation Studio",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{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:f.map(x=>e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{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(Fr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{className:"pl-9",placeholder:"Search agents, addresses, titles...",value:o,onChange:x=>c(x.target.value)})]}),e.jsxs(oa,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(la,{children:[e.jsxs(Kt,{value:"agents",children:["By agent (",m.length,")"]}),e.jsxs(Kt,{value:"all",children:["All presentations (",p.length,")"]})]}),e.jsx(Zt,{value:"agents",children:e.jsx(we,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Agent"}),e.jsx(Lt,{className:"text-right",children:"Presentations"}),e.jsx(Lt,{className:"text-right",children:"Generated"}),e.jsx(Lt,{children:"Last activity"})]})}),e.jsxs(Xa,{children:[m.map(x=>e.jsxs(gn,{children:[e.jsxs(gt,{children:[e.jsx("div",{className:"font-medium",children:x.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:x.email})]}),e.jsx(gt,{className:"text-right font-semibold",children:x.total}),e.jsx(gt,{className:"text-right",children:x.generated}),e.jsx(gt,{children:yze(x.last_activity)})]},x.user_id)),!t&&m.length===0&&e.jsx(gn,{children:e.jsx(gt,{colSpan:4,className:"py-10 text-center text-muted-foreground",children:"No agents have created a listing presentation yet."})})]})]})})})}),e.jsx(Zt,{value:"all",children:e.jsx(we,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Presentation"}),e.jsx(Lt,{children:"Agent"}),e.jsx(Lt,{children:"Property"}),e.jsx(Lt,{children:"Price"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{children:"Created"}),e.jsx(Lt,{children:"Last generated"})]})}),e.jsxs(Xa,{children:[p.slice(0,300).map(x=>{var y,v;return e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium",children:x.title||"Untitled"}),e.jsxs(gt,{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(gt,{className:"text-sm",children:[x.property_address_line1,x.city,x.state].filter(Boolean).join(", ")||"—"}),e.jsx(gt,{children:wJn(x.list_price)}),e.jsx(gt,{children:e.jsx(Be,{variant:x.last_generated_at?"default":"secondary",children:x.last_generated_at?"Generated":x.status||"Draft"})}),e.jsx(gt,{children:yze(x.created_at)}),e.jsx(gt,{children:yze(x.last_generated_at)})]},x.id)}),!t&&p.length===0&&e.jsx(gn,{children:e.jsx(gt,{colSpan:7,className:"py-10 text-center text-muted-foreground",children:"No presentations found."})})]})]})})})})]})]})})}const NJ="listing_revival";function NJn(){const{user:s,loading:t,isAdmin:n}=vs(),{data:r}=ct({queryKey:["feature-entitlement",NJ,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",NJ).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 kJn=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)):"—";function SJn(){var u,h;const{user:s}=vs(),t=Qt(),[n,r]=j.useState(""),a=ct({queryKey:["lr-admin-stats"],queryFn:async()=>{const{data:m,error:p}=await q.rpc("get_admin_listing_revival_stats");if(p)throw p;return m??[]}}),i=ct({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:p,error:f}=await m;if(f)throw f;const x=(p??[]).map(b=>b.id),{data:y}=await q.from("feature_entitlements").select("user_id, enabled, tier").eq("feature_key",NJ).in("user_id",x.length?x:["00000000-0000-0000-0000-000000000000"]),v=new Map((y??[]).map(b=>[b.user_id,b]));return(p??[]).map(b=>{var N;return{user_id:b.id,name:b.name,email:b.email,enabled:!!((N=v.get(b.id))!=null&&N.enabled)}})}}),l=yt({mutationFn:async({userId:m,enabled:p})=>{const{error:f}=await q.from("feature_entitlements").upsert({user_id:m,feature_key:NJ,enabled:p,tier:"member",enabled_by:s.id,enabled_at:new Date().toISOString()},{onConflict:"user_id,feature_key"});if(f)throw f;await q.from("feature_entitlement_audit").insert({feature_key:NJ,target_user_id:m,action:p?"grant":"revoke",performed_by:s.id})},onSuccess:(m,p)=>{t.invalidateQueries({queryKey:["lr-admin-members"]}),re.success(p.enabled?"Access granted":"Access revoked")},onError:m=>re.error(m.message)}),o=ct({queryKey:["lr-admin-stat-profiles",(a.data??[]).length],enabled:!!((u=a.data)!=null&&u.length),queryFn:async()=>{const m=(a.data??[]).map(f=>f.owner_user_id),{data:p}=await q.from("profiles").select("id, name, email").in("id",m);return new Map((p??[]).map(f=>[f.id,f]))}}),c=j.useMemo(()=>{const m=a.data??[];return{agents:m.length,campaigns:m.reduce((p,f)=>p+Number(f.campaign_count),0),leads:m.reduce((p,f)=>p+Number(f.lead_count),0),hot:m.reduce((p,f)=>p+Number(f.hot_lead_count),0)}},[a.data]),d=[{label:"Agents using it",value:c.agents,icon:Bn},{label:"Campaigns built",value:c.campaigns,icon:cn},{label:"Seller leads",value:c.leads,icon:pv},{label:"Hot leads",value:c.hot,icon:Xd}];return e.jsxs(qs,{title:"Listing Revival Admin",children:[e.jsx(Xh,{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(we,{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(oa,{defaultValue:"usage",className:"mt-6",children:[e.jsxs(la,{children:[e.jsx(Kt,{value:"usage",children:"Agent usage"}),e.jsx(Kt,{value:"access",children:"Access"})]}),e.jsx(Zt,{value:"usage",className:"mt-4",children:e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Agent"}),e.jsx(Lt,{className:"text-right",children:"Campaigns"}),e.jsx(Lt,{className:"text-right",children:"Live pages"}),e.jsx(Lt,{className:"text-right",children:"Leads"}),e.jsx(Lt,{className:"text-right",children:"Hot"}),e.jsx(Lt,{className:"text-right",children:"Engagement"}),e.jsx(Lt,{className:"text-right",children:"Last activity"})]})}),e.jsx(Xa,{children:[...a.data].sort((m,p)=>Number(p.campaign_count)-Number(m.campaign_count)).map(m=>{var f;const p=(f=o.data)==null?void 0:f.get(m.owner_user_id);return e.jsxs(gn,{children:[e.jsxs(gt,{children:[e.jsx("div",{className:"font-medium",children:(p==null?void 0:p.name)??"Agent"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(p==null?void 0:p.email)??m.owner_user_id.slice(0,8)})]}),e.jsx(gt,{className:"text-right tabular-nums",children:m.campaign_count}),e.jsx(gt,{className:"text-right tabular-nums",children:m.published_count}),e.jsx(gt,{className:"text-right tabular-nums",children:m.lead_count}),e.jsx(gt,{className:"text-right",children:Number(m.hot_lead_count)>0?e.jsx(Be,{className:"bg-red-500/15 text-red-600 hover:bg-red-500/15",children:m.hot_lead_count}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(gt,{className:"text-right tabular-nums",children:m.event_count}),e.jsx(gt,{className:"text-right text-sm text-muted-foreground",children:kJn(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(Zt,{value:"access",className:"mt-4",children:e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(Fr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Agent"}),e.jsx(Lt,{children:"Email"}),e.jsx(Lt,{className:"text-right",children:"Access"})]})}),e.jsx(Xa,{children:(i.data??[]).map(m=>e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium",children:m.name??"—"}),e.jsx(gt,{className:"text-muted-foreground",children:m.email??"—"}),e.jsx(gt,{className:"text-right",children:e.jsx(wn,{checked:m.enabled,onCheckedChange:p=>l.mutate({userId:m.user_id,enabled:p})})})]},m.user_id))})]})]})]})})]})]})}function CJn(){const{toast:s}=Ai(),[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:p}=await q.from("profiles").select("id, name, email, avatar_url").in("id",h);if(p)throw p;const f=new Map((m==null?void 0:m.map(y=>[y.id,y]))||[]),x=d.map(y=>{const v=f.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:Bn,color:"text-blue-600"},{label:"Total Open Houses",value:r.totalOpenHouses,icon:ra,color:"text-violet-600"},{label:"Active Now",value:r.activeOpenHouses,icon:Yo,color:"text-emerald-600"},{label:"Total Visitors",value:r.totalVisitors,icon:xa,color:"text-amber-600"},{label:"Leads Created",value:r.totalLeads,icon:zl,color:"text-rose-600"}];return e.jsx(qs,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(It,{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(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(rc,{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(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Agent"}),e.jsx(Lt,{className:"text-center",children:"Open Houses"}),e.jsx(Lt,{className:"text-center",children:"Active"}),e.jsx(Lt,{className:"text-center",children:"Visitors"}),e.jsx(Lt,{className:"text-center",children:"Leads"}),e.jsx(Lt,{className:"text-center",children:"Conversion"})]})}),e.jsx(Xa,{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(gn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center overflow-hidden",children:d.avatar_url?e.jsx("img",{src:d.avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((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(gt,{className:"text-center font-medium",children:d.open_house_count}),e.jsx(gt,{className:"text-center",children:d.active_count>0?e.jsx(Be,{variant:"secondary",className:"bg-emerald-100 text-emerald-700",children:d.active_count}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(gt,{className:"text-center",children:d.total_visitors.toLocaleString()}),e.jsx(gt,{className:"text-center",children:d.total_leads>0?e.jsx(Be,{variant:"secondary",children:d.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(gt,{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 AJn(){const[s]=fc(),t=Wn(),[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:p}=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(p){let f=p.message||"Failed to connect accounts";try{const x=p.context;if(x&&typeof x.json=="function"){const y=await x.json();y!=null&&y.error&&(f=y.error)}}catch{}throw new Error(f)}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(we,{className:"w-full max-w-md",children:[e.jsxs(Tt,{className:"text-center",children:[e.jsxs("div",{className:"mx-auto mb-4",children:[n==="loading"&&e.jsx(Et,{className:"h-12 w-12 animate-spin text-primary"}),n==="success"&&e.jsx(Yo,{className:"h-12 w-12 text-green-500"}),n==="error"&&e.jsx(ou,{className:"h-12 w-12 text-destructive"})]}),e.jsxs(It,{children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Jn,{children:i})]}),e.jsx(Ie,{className:"flex justify-center",children:e.jsx(U,{onClick:()=>t("/admin/integrations"),children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function EJn(){const s=Qt(),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState([]),o=j.useRef(null),{data:c,isLoading:d}=ct({queryKey:["prospect-emails"],queryFn:async()=>{const{data:b,error:N}=await q.from("prospect_emails").select("*").order("sent_at",{ascending:!1});if(N)throw N;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=yt({mutationFn:async b=>{const{data:N,error:S}=await q.functions.invoke("send-prospect-email",{body:{emails:b}});if(S)throw S;return N},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)}}),p=yt({mutationFn:async()=>{var A,T;const{data:{user:b}}=await q.auth.getUser();if(!(b!=null&&b.email))throw new Error("Could not get your email");const{data:N,error:S}=await q.functions.invoke("send-prospect-email",{body:{emails:[{email:b.email,first_name:(T=(A=b.user_metadata)==null?void 0:A.name)==null?void 0:T.split(" ")[0]}],test_mode:!0}});if(S)throw S;return N},onSuccess:()=>{re.success("Test email sent to your inbox!")},onError:b=>{re.error("Failed to send test: "+b.message)}}),f=yt({mutationFn:async()=>{const{data:b,error:N}=await q.functions.invoke("send-prospect-email",{body:{mode:"live_leads"}});if(N)throw N;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(N=>N.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 N=(A=b.target.files)==null?void 0:A[0];if(!N)return;const S=new FileReader;S.onload=T=>{var z,$;const M=((z=T.target)==null?void 0:z.result).split(` `).filter(H=>H.trim()),I=[],R=($=M[0])!=null&&$.toLowerCase().includes("email")?1:0;for(let H=R;HQ.trim().replace(/"/g,"")),K=V[0],Z=V[1];K&&K.includes("@")&&I.push({email:K,first_name:Z||void 0})}l(I),re.success(`${I.length} entries loaded from CSV`)},S.readAsText(N),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()))||[]),N=i.filter(S=>!b.has(S.email.toLowerCase()));if(N.length===0){re.error("All emails have already been prospected");return}N.length0&&e.jsxs(we,{className:"border-red-200/50 bg-red-500/[0.02]",children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(mv,{className:"h-5 w-5 text-red-600"}),"Live Event Leads",e.jsx(Be,{variant:"secondary",className:"ml-2",children:h.liveLeads})]}),e.jsx(Jn,{children:"These agents registered on a LevelUp Live page but haven't received a free trial invite yet."})]}),e.jsx(Ie,{children:e.jsxs(U,{onClick:()=>f.mutate(),disabled:f.isPending,className:"gap-2",children:[f.isPending?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx($r,{className:"h-4 w-4"}),"Send free trial invite to all live leads"]})})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Gu,{className:"h-5 w-5"}),"Send Prospect Email"]}),e.jsxs(Jn,{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Send a beautiful free trial invitation email to potential members"}),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>p.mutate(),disabled:p.isPending,className:"gap-2 ml-4 shrink-0",children:[p.isPending?e.jsx(Et,{className:"h-3 w-3 animate-spin"}):e.jsx(ln,{className:"h-3 w-3"}),"Send Test to Me"]})]})]}),e.jsx(Ie,{children:e.jsxs(oa,{defaultValue:"single",children:[e.jsxs(la,{className:"mb-4",children:[e.jsxs(Kt,{value:"single",children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),"Single Send"]}),e.jsxs(Kt,{value:"bulk",children:[e.jsx(qa,{className:"h-4 w-4 mr-2"}),"Bulk CSV"]})]}),e.jsx(Zt,{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(te,{htmlFor:"prospect-email",className:"sr-only",children:"Email"}),e.jsx(xe,{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(te,{htmlFor:"prospect-name",className:"sr-only",children:"First Name"}),e.jsx(xe,{id:"prospect-name",placeholder:"First name (optional)",value:r,onChange:b=>a(b.target.value),onKeyDown:b=>b.key==="Enter"&&x()})]}),e.jsxs(U,{onClick:x,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx($r,{className:"h-4 w-4"}),"Send Invite"]})]})}),e.jsx(Zt,{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(U,{variant:"outline",onClick:()=>{var b;return(b=o.current)==null?void 0:b.click()},className:"gap-2",children:[e.jsx(Ur,{className:"h-4 w-4"}),"Upload CSV"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Format: email, first_name (one per line)"})]}),i.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Bn,{className:"h-3 w-3"}),i.length," entries ready"]}),e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>l([]),children:[e.jsx(er,{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,N)=>e.jsxs("div",{className:"text-muted-foreground",children:[b.email,b.first_name?` — ${b.first_name}`:""]},N)),i.length>20&&e.jsxs("div",{className:"text-muted-foreground/60",children:["...and ",i.length-20," more"]})]}),e.jsxs(U,{onClick:v,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx($r,{className:"h-4 w-4"}),"Send ",i.length," Invites"]})]})]})})]})})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5"}),"Prospect Log"]}),e.jsx(Jn,{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,N)=>e.jsx(xn,{className:"h-12 w-full"},N))}):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 N;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:Gs(new Date(b.sent_at),"MMM d, yyyy")}),e.jsx("td",{className:"py-3 px-4",children:b.status==="converted"?e.jsxs(Be,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-0",children:[e.jsx(zr,{className:"h-3 w-3 mr-1"}),"Converted"]}):b.status==="live_lead"?e.jsxs(Be,{className:"bg-red-500/10 text-red-700 hover:bg-red-500/20 border-0 gap-1",children:[e.jsx(mv,{className:"h-3 w-3"}),"Live lead"]}):e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Yr,{className:"h-3 w-3"}),"Sent"]})}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:(N=b.utm_source)!=null&&N.startsWith("toolbox:")?e.jsxs(Be,{variant:"outline",className:"gap-1 font-normal",children:[e.jsx(Ur,{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?Gs(new Date(b.converted_at),"MMM d, yyyy"):"—"})]},b.id)})})]})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Gu,{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 gae(s){const t=Qt(),{toast:n}=Ai(),r=ct({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=ct({queryKey:["recruit-prospects",s],queryFn:async()=>{if(!s)return[];const c=1e3;let d=[],u=0,h=!0;for(;h;){const{data:m,error:p}=await q.from("recruit_prospects").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).range(u,u+c-1);if(p)throw p;d=d.concat(m),h=m.length===c,u+=c}return d},enabled:!!s}),i=yt({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=yt({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=yt({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 TJn(s){const t=Qt(),{toast:n}=Ai(),r=ct({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=yt({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 DSt=(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 Vts({open:s,onOpenChange:t,stages:n,defaultStageId:r,onSubmit:a,isSubmitting:i}){const[l,o]=j.useState(DSt(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(DSt(r,n)),t(!1)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Add Recruit Prospect"})}),e.jsxs("form",{onSubmit:d,className:"space-y-4",children:[e.jsxs(oa,{defaultValue:"basic",className:"w-full",children:[e.jsxs(la,{className:"grid w-full grid-cols-4",children:[e.jsx(Kt,{value:"basic",children:"Basic Info"}),e.jsx(Kt,{value:"production",children:"Production"}),e.jsx(Kt,{value:"social",children:"Social & Web"}),e.jsx(Kt,{value:"personal",children:"Personal"})]}),e.jsxs(Zt,{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(te,{children:"First Name *"}),e.jsx(xe,{required:!0,value:l.first_name,onChange:c("first_name")})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Last Name"}),e.jsx(xe,{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(te,{children:"Email"}),e.jsx(xe,{type:"email",value:l.email,onChange:c("email")})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Phone"}),e.jsx(xe,{value:l.phone,onChange:c("phone")})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Current Brokerage"}),e.jsx(xe,{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(te,{children:"License #"}),e.jsx(xe,{value:l.license_number,onChange:c("license_number")})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Experience (years)"}),e.jsx(xe,{type:"number",min:"0",value:l.experience_years,onChange:c("experience_years")})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Address"}),e.jsx(xe,{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(te,{children:"City"}),e.jsx(xe,{value:l.city,onChange:c("city")})]}),e.jsxs("div",{children:[e.jsx(te,{children:"State"}),e.jsx(xe,{value:l.state,onChange:c("state")})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Zip"}),e.jsx(xe,{value:l.zip_code,onChange:c("zip_code")})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Pipeline Stage"}),e.jsxs(Ns,{value:l.stage_id,onValueChange:u=>o(h=>({...h,stage_id:u})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:n.map(u=>e.jsx(et,{value:u.id,children:u.name},u.id))})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Referred By"}),e.jsx(xe,{placeholder:"Who referred this prospect?",value:l.referred_by,onChange:c("referred_by")})]})]}),e.jsxs(Zt,{value:"production",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Annual Production Volume"}),e.jsx(xe,{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(te,{children:"Last Year Volume"}),e.jsx(xe,{placeholder:"e.g. $8.2M",value:l.last_year_volume,onChange:c("last_year_volume")})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Last Year Transactions"}),e.jsx(xe,{type:"number",min:"0",placeholder:"e.g. 24",value:l.last_year_transactions,onChange:c("last_year_transactions")})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Avg Sale Price"}),e.jsx(xe,{placeholder:"e.g. $350K",value:l.avg_sale_price,onChange:c("avg_sale_price")})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Specialties / Niche"}),e.jsx(xe,{placeholder:"e.g. Luxury, First-time buyers, Investment",value:l.specialties,onChange:c("specialties")})]})]}),e.jsxs(Zt,{value:"social",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"LinkedIn URL"}),e.jsx(xe,{type:"url",placeholder:"https://linkedin.com/in/...",value:l.linkedin_url,onChange:c("linkedin_url")})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Website URL"}),e.jsx(xe,{type:"url",placeholder:"https://...",value:l.website_url,onChange:c("website_url")})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Instagram Handle"}),e.jsx(xe,{placeholder:"@handle",value:l.instagram_handle,onChange:c("instagram_handle")})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Facebook URL"}),e.jsx(xe,{type:"url",placeholder:"https://facebook.com/...",value:l.facebook_url,onChange:c("facebook_url")})]})]}),e.jsxs(Zt,{value:"personal",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Birthday"}),e.jsx(xe,{type:"date",value:l.birthday,onChange:c("birthday")})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Spouse / Partner Name"}),e.jsx(xe,{value:l.spouse_name,onChange:c("spouse_name")})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Interests / Hobbies"}),e.jsx(xe,{placeholder:"Golf, travel, community events...",value:l.interests,onChange:c("interests")})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Notes"}),e.jsx(Fs,{value:l.notes,onChange:c("notes"),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(U,{type:"submit",disabled:i,children:"Add Prospect"})]})]})]})})}function KIe(){const{user:s}=vs();return ct({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 wrt({value:s,onChange:t}){const{data:n,isLoading:r}=KIe();return e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Send from"}),e.jsxs(Ns,{value:s,onValueChange:a=>t(a),disabled:r,children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"default",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(_i,{className:"h-3.5 w-3.5"})," Brokerage default sender"]})}),e.jsx(et,{value:"mass_email",disabled:!(n!=null&&n.massEmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(AM,{className:"h-3.5 w-3.5"}),"Mass Email",n!=null&&n.massEmail?` (${n.massEmail.email})`:" — not configured"]})}),e.jsx(et,{value:"gmail",disabled:!(n!=null&&n.gmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ln,{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 Hts({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(""),[p,f]=j.useState("default"),[x,y]=j.useState(!1),v=Qt(),{data:b}=KIe();j.useEffect(()=>{s&&(u(`${c}, I made you a quick video 🎥`),m(o||""),f(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 N=async()=>{var S,A;if(!i){re.error("This prospect has no email address on file.");return}y(!0);try{const{data:T,error:L}=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:p}});if(L)throw L;if(((T==null?void 0:T.sent)??0)>0)re.success(`Email sent to ${i}`),v.invalidateQueries({queryKey:["recruit-videos"]}),v.invalidateQueries({queryKey:["recruit-videos-prospect"]}),t(!1);else{const I=((A=(S=T==null?void 0:T.results)==null?void 0:S[0])==null?void 0:A.error)||"Failed to send";re.error(I)}}catch(T){re.error((T==null?void 0:T.message)||"Failed to send email")}finally{y(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5"})," Email video to ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"To"}),e.jsx(xe,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(wrt,{value:p,onChange:f}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Subject"}),e.jsx(xe,{value:d,onChange:S=>u(S.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Personal message (optional)"}),e.jsx(Fs,{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(Mr,{children:[e.jsx(U,{variant:"ghost",onClick:()=>t(!1),disabled:x,children:"Cancel"}),e.jsxs(U,{onClick:N,disabled:x||!i,children:[x?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx($r,{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 CKe=[{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 MJn(s){return ct({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 PJn(s){return ct({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 Gts(){const s=Qt(),{toast:t}=Ai();return yt({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 Wts(){const s=Qt();return yt({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 Kts(s){return ct({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 LJn(){const s=Qt(),{toast:t}=Ai();return yt({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 IJn(){const s=Qt();return yt({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 RJn({prospectId:s,prospectName:t,prospectEmail:n,brokerageId:r}){var K;const{data:a=[],isLoading:i}=PJn(s),{data:l=[]}=Kts(r),o=Gts(),c=f3();Wts();const[d,u]=j.useState("idle"),[h,m]=j.useState(0),[p,f]=j.useState(0),[x,y]=j.useState(""),[v,b]=j.useState(""),[N,S]=j.useState(!1),[A,T]=j.useState(null),[L,M]=j.useState(null),[I,R]=j.useState(null),z=((K=l.find(Z=>Z.id===x))==null?void 0:K.script_text)||"",$=()=>{u("idle"),m(0),f(0),y(""),b("")},H=j.useCallback(async(Z,Q)=>{u("uploading");try{const le=`Recruiting: ${t}`,{videoId:ue,libraryId:se}=await cL(le),{uploadUrl:ne,apiKey:ie}=await dL(ue),ce=new XMLHttpRequest;ce.upload.onprogress=Oe=>{Oe.lengthComputable&&m(Oe.loaded/Oe.total*100)},await new Promise((Oe,Se)=>{ce.onload=()=>ce.status>=200&&ce.status<300?Oe():Se(new Error("Upload failed")),ce.onerror=()=>Se(new Error("Upload failed")),ce.open("PUT",ne),ce.setRequestHeader("AccessKey",ie),ce.send(Z)}),u("processing");let je=0;const be=Date.now(),he=9e4,ge=`https://iframe.mediadelivery.net/embed/${se}/${ue}`;for(;je<4&&(await new Promise(Se=>setTimeout(Se,3e3)),!(Date.now()-be>he));){const Oe=await fN(ue);if(je=Oe.status,f(Oe.encodeProgress||0),je===5||je===6)throw new Error("Video processing failed")}const ke=await fN(ue),Te=(ke.storageSize||Z.size)/(1024*1024),Me=await c.mutateAsync({bunny_video_id:ue,playback_url:ke.directPlayUrl||ge,thumbnail_url:ke.thumbnailUrl,preview_url:ke.previewUrl||null,duration_seconds:ke.length||Q,file_size_mb:Te,title:le,status:je>=4?"ready":"processing",touch_type:"recruiting"});await o.mutateAsync({prospect_id:s,video_id:Me.id,brokerage_id:r,message:v||void 0}),u("done"),re.success("Video recorded and linked to prospect!"),setTimeout(()=>{S(!1),$()},1500)}catch(le){re.error(le.message||"Failed to upload video"),u("record")}},[s,t,r,v,c,o]),V=Z=>{Z&&(navigator.clipboard.writeText(`${window.location.origin}/recruit-video/${Z}`),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(Wr,{className:"h-4 w-4"})," Video Outreach"]}),e.jsxs(zs,{open:N,onOpenChange:Z=>{!Z&&(d==="uploading"||d==="processing")||(S(Z),Z||$())},children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>u("script"),children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1"})," Record Video"]})}),e.jsxs(Ds,{className:"max-w-2xl",children:[e.jsx(Vs,{children:e.jsxs($s,{children:["Record Video for ",t]})}),d==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Choose a Script (optional)"}),e.jsxs(Ns,{value:x,onValueChange:y,children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{placeholder:"No script — speak freely"})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"No script"}),l.map(Z=>{var Q;return e.jsx(et,{value:Z.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[Z.title,e.jsx(Be,{variant:"outline",className:"text-[9px] ml-1",children:(Q=CKe.find(le=>le.value===Z.category))==null?void 0:Q.label})]})},Z.id)})]})]}),z&&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:z})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Personal Message (shown on landing page)"}),e.jsx(Fs,{value:v,onChange:Z=>b(Z.target.value),placeholder:`Hi ${t.split(" ")[0]}, I'd love to chat about what we're building here...`,rows:3,className:"mt-1"})]}),e.jsxs(U,{onClick:()=>u("record"),className:"w-full",children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"})," Start Recording"]})]}),d==="record"&&e.jsx(kE,{maxDurationSeconds:600,onRecordingComplete:H,teleprompterContent:z||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(ro,{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(ro,{value:p,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(p),"%"]})]}),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(lu,{className:"h-6 w-6 text-emerald-600"})}),e.jsx("p",{className:"font-medium text-emerald-600",children:"Video ready!"})]})]})]})]}),i?e.jsx("div",{className:"text-center py-4",children:e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent mx-auto"})}):a.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No videos sent yet"}):e.jsx("div",{className:"space-y-2",children:a.map(Z=>{var Q;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(Z.video)?e.jsx("img",{src:_4(Z.video),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(Wr,{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:((Q=Z.video)==null?void 0:Q.title)||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[Z.view_count>0?e.jsxs(Be,{variant:"secondary",className:"text-[9px] h-4",children:[e.jsx(xa,{className:"h-2.5 w-2.5 mr-0.5"}),Z.view_count]}):Z.sent_at?e.jsxs(Be,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx($r,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]}):e.jsxs(Be,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(Yr,{className:"h-2.5 w-2.5 mr-0.5"}),"Draft"]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Gs(new Date(Z.created_at),"MMM d")})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(U,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>V(Z.share_token),title:"Copy link",children:e.jsx(Pa,{className:"h-3 w-3"})}),e.jsxs(U,{variant:Z.sent_at?"ghost":"default",size:"sm",className:"h-7 gap-1",disabled:!n,onClick:()=>{var le;T(Z.id),M(((le=Z.video)==null?void 0:le.title)||null),R(Z.message||null)},title:n?"Email video to prospect":"No email on file",children:[e.jsx(ln,{className:"h-3 w-3"}),e.jsx("span",{className:"text-[10px]",children:Z.sent_at?"Resend":"Email"})]})]})]},Z.id)})}),A&&e.jsx(Hts,{open:!!A,onOpenChange:Z=>{Z||T(null)},recruitVideoId:A,brokerageId:r,prospectName:t,prospectEmail:n,videoTitle:L,defaultMessage:I})]})}function DJn({brokerageId:s,onSelect:t}){const{data:n=[],isLoading:r}=ct({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(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsxs(U,{variant:"outline",size:"sm",className:"gap-2",type:"button",children:[e.jsx(Ur,{className:"h-4 w-4"}),"Use Template",e.jsx(rl,{className:"h-3.5 w-3.5 opacity-60"})]})}),e.jsx(Eu,{align:"end",className:"w-80 max-h-[420px] overflow-y-auto",children:r?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Et,{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(l1,{}),e.jsx(DV,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:i}),l.map(c=>e.jsxs(La,{onClick:()=>t(c),className:"flex flex-col items-start gap-0.5 py-2",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:c.title}),c.brokerage_id===null&&e.jsx(Be,{variant:"secondary",className:"text-[9px] shrink-0",children:"Built-in"})]}),e.jsx("span",{className:"text-xs text-muted-foreground line-clamp-1",children:c.subject})]},c.id))]},i))})]})}function OJn({open:s,onOpenChange:t,prospectId:n,brokerageId:r,prospectName:a,prospectEmail:i}){const{user:l}=vs(),o=(a||"").split(" ")[0]||"there",[c,d]=j.useState(""),[u,h]=j.useState(""),[m,p]=j.useState("default"),[f,x]=j.useState(!1),[y,v]=j.useState(null),[b,N]=j.useState(!1),S=Qt(),{data:A}=KIe();j.useEffect(()=>{if(s){d(`Hi ${o}`),h("");const z=A!=null&&A.massEmail?"mass_email":A!=null&&A.gmail?"gmail":"default";p(z),v(null),N(!1)}},[s,o,A==null?void 0:A.massEmail,A==null?void 0:A.gmail]);const{data:T=[],isLoading:L}=ct({queryKey:["prospect-email-video-library",l==null?void 0:l.id],queryFn:async()=>{const{data:z,error:$}=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($)throw $;return z??[]},enabled:s&&!!(l!=null&&l.id)}),M=T.find(z=>z.id===y)||null,I=async()=>{var z,$;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:H}=await q.from("recruit_videos").select("id").eq("prospect_id",n).eq("video_id",y).maybeSingle();let V=H==null?void 0:H.id;if(!V){const{data:le,error:ue}=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(ue)throw ue;V=le.id}const{data:K,error:Z}=await q.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[V],brokerage_id:r,subject_override:c.trim(),message_override:u.trim(),send_via:m}});if(Z)throw Z;if(((K==null?void 0:K.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 le=(($=(z=K==null?void 0:K.results)==null?void 0:z[0])==null?void 0:$.error)||"Failed to send";re.error(le)}}else{const{data:H,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;H!=null&&H.success?(re.success(`Email sent to ${i}`),S.invalidateQueries({queryKey:["recruit-activities",n]}),S.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1)):re.error((H==null?void 0:H.error)||"Failed to send")}}catch(H){re.error((H==null?void 0:H.message)||"Failed to send email")}finally{x(!1)}},R=z=>{const $=H=>H.replace(/\[First Name\]/gi,o);d($(z.subject)),h($(z.body)),re.success(`Loaded "${z.title}"`)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5"})," Email ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"To"}),e.jsx(xe,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(wrt,{value:m,onChange:p}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(te,{className:"text-xs",children:"Subject"}),e.jsx(DJn,{brokerageId:r,onSelect:R})]}),e.jsx(xe,{value:c,onChange:z=>d(z.target.value)}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Message"}),e.jsx(Fs,{value:u,onChange:z=>h(z.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(te,{className:"text-xs flex items-center gap-1.5",children:[e.jsx(Wr,{className:"h-3.5 w-3.5"})," Include a video"]}),M?e.jsxs(U,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{v(null),N(!1)},children:[e.jsx(er,{className:"h-3 w-3 mr-1"})," Remove"]}):e.jsx(U,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>N(z=>!z),children:b?"Hide library":"Pick from library"})]}),M&&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(M)?e.jsx("img",{src:_4(M),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(Wr,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx("p",{className:"text-xs font-medium truncate flex-1",children:M.title||"Untitled video"})]}),!M&&b&&e.jsx("div",{className:"max-h-56 overflow-y-auto space-y-1 -mx-1 px-1",children:L?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Et,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):T.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."}):T.map(z=>e.jsxs("button",{type:"button",onClick:()=>{v(z.id),N(!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(z)?e.jsx("img",{src:_4(z),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(Wr,{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:z.title||"Untitled video"}),z.duration_seconds&&e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[Math.floor(z.duration_seconds/60),":",String(Math.floor(z.duration_seconds%60)).padStart(2,"0")]})]})]},z.id))}),M&&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(Mr,{children:[e.jsx(U,{variant:"ghost",onClick:()=>t(!1),disabled:f,children:"Cancel"}),e.jsxs(U,{onClick:I,disabled:f||!i,children:[f?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx($r,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function FJn(s){return ct({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 OSt=[{value:"call",label:"Phone Call",icon:ba},{value:"email",label:"Email",icon:ln},{value:"text",label:"Text Message",icon:Ki},{value:"meeting",label:"Meeting",icon:pa},{value:"note",label:"Note",icon:Ur},{value:"campaign_email",label:"Campaign Email",icon:$r}];function uw({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 Lce({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(Sr,{className:"h-3 w-3 opacity-50"})]}):null}function Qm({label:s,value:t,onChange:n,type:r="text",placeholder:a}){return e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:s}),e.jsx(xe,{type:r,value:t,onChange:i=>n(i.target.value),placeholder:a,className:"mt-1 h-8 text-sm"})]})}function Yts({prospect:s,stages:t,brokerageId:n,open:r,onOpenChange:a,onUpdate:i,onDelete:l}){const{activities:o,addActivity:c}=TJn((s==null?void 0:s.id)||null),{data:d=[]}=FJn((s==null?void 0:s.id)||null),[u,h]=j.useState({type:"note",title:"",description:""}),[m,p]=j.useState(!1),[f,x]=j.useState(!1),[y,v]=j.useState({}),[b,N]=j.useState(!1);if(!s)return null;const S=()=>{var V,K;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:((K=s.last_year_transactions)==null?void 0:K.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[K,Z]of Object.entries(y))K==="experience_years"||K==="last_year_transactions"?V[K]=Z?parseInt(Z):null:V[K]=Z||null;i(V),x(!1)},T=()=>x(!1),L=V=>K=>v(Z=>({...Z,[V]:K})),M=()=>{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:""}),p(!1))},I=t.find(V=>V.id===s.stage_id),R=s.address||s.city||s.state,z=s.last_year_volume||s.last_year_transactions||s.avg_sale_price||s.specialties||s.annual_production,$=s.linkedin_url||s.website_url||s.instagram_handle||s.facebook_url,H=s.birthday||s.spouse_name||s.interests||s.referred_by;return e.jsxs(my,{open:r,onOpenChange:V=>{V||x(!1),a(V)},children:[e.jsx(g0,{className:"w-full sm:max-w-lg p-0",children:e.jsx(Gi,{className:"h-full",children:e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsx(vv,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(bv,{className:"text-xl",children:[s.first_name," ",s.last_name]}),I&&e.jsx(Be,{variant:"outline",style:{borderColor:I.color,color:I.color},className:"mt-1",children:I.name})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[f?e.jsxs(e.Fragment,{children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:T,children:e.jsx(er,{className:"h-4 w-4"})}),e.jsx(U,{variant:"default",size:"icon",onClick:A,children:e.jsx(Ho,{className:"h-4 w-4"})})]}):e.jsx(U,{variant:"ghost",size:"icon",onClick:S,title:"Edit prospect",children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(In,{className:"h-4 w-4"})})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Delete prospect?"}),e.jsx(Ll,{children:"This will permanently remove this prospect and all their activity history."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>{l(s.id),a(!1)},children:"Delete"})]})]})]})]})]})}),!f&&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(ln,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:s.email})]}),e.jsxs(U,{size:"sm",variant:"outline",className:"h-7 gap-1.5 flex-shrink-0",onClick:()=>N(!0),children:[e.jsx(ln,{className:"h-3 w-3"})," Email"]})]}),s.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ba,{className:"h-3.5 w-3.5"})," ",s.phone]}),R&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ni,{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(te,{className:"text-xs text-muted-foreground",children:"Move to Stage"}),e.jsxs(Ns,{value:s.stage_id||"",onValueChange:V=>i({id:s.id,stage_id:V}),children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{})}),e.jsx(js,{children:t.map(V=>e.jsx(et,{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(oa,{defaultValue:"details",className:"w-full",children:[e.jsxs(la,{className:"grid w-full grid-cols-4 h-8 text-xs",children:[e.jsx(Kt,{value:"details",className:"text-xs",children:"Details"}),e.jsx(Kt,{value:"production",className:"text-xs",children:"Production"}),e.jsx(Kt,{value:"social",className:"text-xs",children:"Social"}),e.jsx(Kt,{value:"personal",className:"text-xs",children:"Personal"})]}),f?e.jsxs(e.Fragment,{children:[e.jsxs(Zt,{value:"details",className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Qm,{label:"First Name",value:y.first_name,onChange:L("first_name")}),e.jsx(Qm,{label:"Last Name",value:y.last_name,onChange:L("last_name")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Qm,{label:"Email",value:y.email,onChange:L("email"),type:"email"}),e.jsx(Qm,{label:"Phone",value:y.phone,onChange:L("phone")})]}),e.jsx(Qm,{label:"Current Brokerage",value:y.current_brokerage,onChange:L("current_brokerage")}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Qm,{label:"License #",value:y.license_number,onChange:L("license_number")}),e.jsx(Qm,{label:"Experience (years)",value:y.experience_years,onChange:L("experience_years"),type:"number"})]}),e.jsx(Qm,{label:"Address",value:y.address,onChange:L("address"),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(Qm,{label:"City",value:y.city,onChange:L("city")}),e.jsx(Qm,{label:"State",value:y.state,onChange:L("state")}),e.jsx(Qm,{label:"Zip",value:y.zip_code,onChange:L("zip_code")})]}),e.jsx(Qm,{label:"Source",value:y.source,onChange:L("source")}),e.jsx(Qm,{label:"Referred By",value:y.referred_by,onChange:L("referred_by")}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Notes"}),e.jsx(Fs,{value:y.notes,onChange:V=>v(K=>({...K,notes:V.target.value})),rows:3,className:"mt-1 text-sm"})]})]}),e.jsxs(Zt,{value:"production",className:"mt-3 space-y-3",children:[e.jsx(Qm,{label:"Annual Production",value:y.annual_production,onChange:L("annual_production"),placeholder:"e.g. $5M"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Qm,{label:"Last Year Volume",value:y.last_year_volume,onChange:L("last_year_volume"),placeholder:"e.g. $8.2M"}),e.jsx(Qm,{label:"Last Year Transactions",value:y.last_year_transactions,onChange:L("last_year_transactions"),type:"number",placeholder:"e.g. 24"})]}),e.jsx(Qm,{label:"Avg Sale Price",value:y.avg_sale_price,onChange:L("avg_sale_price"),placeholder:"e.g. $350K"}),e.jsx(Qm,{label:"Specialties / Niche",value:y.specialties,onChange:L("specialties"),placeholder:"e.g. Luxury, Investment"})]}),e.jsxs(Zt,{value:"social",className:"mt-3 space-y-3",children:[e.jsx(Qm,{label:"LinkedIn URL",value:y.linkedin_url,onChange:L("linkedin_url"),type:"url",placeholder:"https://linkedin.com/in/..."}),e.jsx(Qm,{label:"Website URL",value:y.website_url,onChange:L("website_url"),type:"url",placeholder:"https://..."}),e.jsx(Qm,{label:"Instagram Handle",value:y.instagram_handle,onChange:L("instagram_handle"),placeholder:"@handle"}),e.jsx(Qm,{label:"Facebook URL",value:y.facebook_url,onChange:L("facebook_url"),type:"url",placeholder:"https://facebook.com/..."})]}),e.jsxs(Zt,{value:"personal",className:"mt-3 space-y-3",children:[e.jsx(Qm,{label:"Birthday",value:y.birthday,onChange:L("birthday"),type:"date"}),e.jsx(Qm,{label:"Spouse / Partner",value:y.spouse_name,onChange:L("spouse_name")}),e.jsx(Qm,{label:"Interests / Hobbies",value:y.interests,onChange:L("interests"),placeholder:"Golf, travel, community events..."})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Zt,{value:"details",className:"mt-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(uw,{label:"Current Brokerage",value:s.current_brokerage}),e.jsx(uw,{label:"License #",value:s.license_number}),e.jsx(uw,{label:"Experience",value:s.experience_years!=null?`${s.experience_years} years`:null}),e.jsx(uw,{label:"Referred By",value:s.referred_by}),e.jsx(uw,{label:"Source",value:s.source})]}),s.notes&&e.jsxs("div",{className:"mt-3",children:[e.jsx(te,{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("p",{className:"text-sm mt-1 whitespace-pre-wrap",children:s.notes})]})]}),e.jsx(Zt,{value:"production",className:"mt-3",children:z?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(uw,{label:"Annual Production",value:s.annual_production}),e.jsx(uw,{label:"Last Year Volume",value:s.last_year_volume}),e.jsx(uw,{label:"Last Year Transactions",value:s.last_year_transactions}),e.jsx(uw,{label:"Avg Sale Price",value:s.avg_sale_price}),e.jsx(uw,{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(Zt,{value:"social",className:"mt-3",children:$?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Lce,{label:"LinkedIn",url:s.linkedin_url,icon:Gg}),e.jsx(Lce,{label:"Website",url:s.website_url,icon:fl}),s.instagram_handle&&e.jsx(Lce,{label:s.instagram_handle,url:`https://instagram.com/${s.instagram_handle.replace("@","")}`,icon:gm}),e.jsx(Lce,{label:"Facebook",url:s.facebook_url,icon:zp})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No social profiles added yet"})}),e.jsx(Zt,{value:"personal",className:"mt-3",children:H?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(uw,{label:"Birthday",value:s.birthday?Gs(new Date(s.birthday+"T00:00:00"),"MMMM d, yyyy"):null,icon:Ro}),e.jsx(uw,{label:"Spouse / Partner",value:s.spouse_name,icon:ko}),e.jsx("div",{className:"col-span-2",children:e.jsx(uw,{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(RJn,{prospectId:s.id,prospectName:`${s.first_name} ${s.last_name||""}`,prospectEmail:s.email,brokerageId:n}),e.jsx(hc,{}),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(U,{size:"sm",variant:"outline",onClick:()=>p(!m),children:[e.jsx(an,{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(Ns,{value:u.type,onValueChange:V=>h(K=>({...K,type:V})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:OSt.map(V=>e.jsx(et,{value:V.value,children:V.label},V.value))})]}),e.jsx(xe,{placeholder:"Subject / Title",value:u.title,onChange:V=>h(K=>({...K,title:V.target.value}))}),e.jsx(Fs,{placeholder:"Details (optional)",value:u.description,onChange:V=>h(K=>({...K,description:V.target.value})),rows:2}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>p(!1),children:"Cancel"}),e.jsx(U,{size:"sm",onClick:M,disabled:!u.title.trim(),children:"Save"})]})]}),e.jsx("div",{className:"space-y-3",children:(()=>{const V=[...o.map(K=>({type:"manual",data:K,date:K.created_at})),...d.map(K=>({type:"campaign_email",data:K,date:K.sent_at||K.created_at}))].sort((K,Z)=>new Date(Z.date).getTime()-new Date(K.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(K=>{if(K.type==="manual"){const Q=K.data,le=OSt.find(se=>se.value===Q.activity_type),ue=(le==null?void 0:le.icon)||Ur;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(ue,{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:Q.title}),Q.description&&e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:Q.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Gs(new Date(Q.created_at),"MMM d, yyyy h:mm a")})]})]},`activity-${Q.id}`)}const Z=K.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($r,{className:"h-3.5 w-3.5 text-primary"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"font-medium",children:["Campaign Email #",Z.email_number]}),e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:Z.subject}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1.5",children:[Z.status==="failed"?e.jsx(Be,{variant:"destructive",className:"text-[10px] px-1.5 py-0 h-4",children:"Failed"}):e.jsxs(Be,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-green-500 text-green-600",children:[e.jsx($r,{className:"h-2.5 w-2.5 mr-0.5"})," Sent"]}),Z.opened_at?e.jsxs(Be,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-blue-500 text-blue-600",children:[e.jsx(xa,{className:"h-2.5 w-2.5 mr-0.5"})," Opened ",Gs(new Date(Z.opened_at),"MMM d, h:mm a")]}):Z.status!=="failed"?e.jsx(Be,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 text-muted-foreground",children:"Not opened"}):null,Z.clicked_at&&e.jsxs(Be,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-purple-500 text-purple-600",children:[e.jsx(n0,{className:"h-2.5 w-2.5 mr-0.5"})," Clicked ",Gs(new Date(Z.clicked_at),"MMM d, h:mm a")]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Gs(new Date(Z.sent_at||Z.created_at),"MMM d, yyyy h:mm a")})]})]},`send-${Z.id}`)})})()})]})]})})}),e.jsx(OJn,{open:b,onOpenChange:N,prospectId:s.id,brokerageId:s.brokerage_id,prospectName:`${s.first_name} ${s.last_name??""}`.trim(),prospectEmail:s.email})]})}const zJn=["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 Zts({open:s,onOpenChange:t,brokerageId:n,stages:r}){var R;const{toast:a}=Ai(),i=Qt(),l=j.useRef(null),[o,c]=j.useState([]),[d,u]=j.useState([]),[h,m]=j.useState({}),[p,f]=j.useState(((R=r[0])==null?void 0:R.id)||""),[x,y]=j.useState(!1),[v,b]=j.useState("upload"),[N,S]=j.useState(0),A=()=>{c([]),u([]),m({}),b("upload"),S(0)},T=z=>{var V;const $=(V=z.target.files)==null?void 0:V[0];if(!$)return;const H=new FileReader;H.onload=K=>{var ie;const Q=((ie=K.target)==null?void 0:ie.result).split(/\r?\n/).filter(ce=>ce.trim());if(Q.length<2){a({title:"Invalid CSV",description:"File must have a header row and at least one data row",variant:"destructive"});return}const le=L(Q[0]);u(le);const ue={},se=new Set;le.forEach((ce,je)=>{const be=ce.toLowerCase().replace(/[^a-z0-9]/g,"");let he=null;/^firstname$/.test(be)||be==="first"?he="first_name":/^lastname$/.test(be)||be==="last"?he="last_name":/^email$/.test(be)||be==="emailaddress"?he="email":/^mobile$|^phone$|^cellphone$|^mobilephone$/.test(be)?he="phone":/officename|currentbrokerage|brokerage|company/.test(be)?he="current_brokerage":/membernumber|licensenumber|license/.test(be)?he="license_number":/experienceyears|yearsexperience/.test(be)?he="experience_years":/^totalvolume$|annualproduction/.test(be)?he="annual_production":/^address$/.test(be)?he="address":/^city$/.test(be)?he="city":/^state$/.test(be)?he="state":/^postalcode$|^zip$|^zipcode$/.test(be)?he="zip_code":/listsidevolume|lastyearvolume/.test(be)?he="last_year_volume":/^totalcount$|lastyeartransactions/.test(be)?he="last_year_transactions":/avgsaleprice|averageprice/.test(be)?he="avg_sale_price":/linkedin/.test(be)?he="linkedin_url":/website/.test(be)?he="website_url":/specialt/.test(be)?he="specialties":/referr/.test(be)?he="referred_by":/^notes$|^note$/.test(be)&&(he="notes"),he&&!se.has(he)&&(ue[String(je)]=he,se.add(he))}),m(ue);const ne=Q.slice(1).map(ce=>{const je=L(ce),be={};return le.forEach((he,ge)=>{be[String(ge)]=je[ge]||""}),be});c(ne),b("map")},H.readAsText($)},L=z=>{const $=[];let H="",V=!1;for(const K of z)K==='"'?V=!V:K===","&&!V?($.push(H.trim()),H=""):H+=K;return $.push(H.trim()),$},M=async()=>{y(!0);try{const{data:{user:z}}=await q.auth.getUser();if(!z)throw new Error("Not authenticated");const $=o.map(V=>{const K={brokerage_id:n,created_by:z.id,stage_id:p,source:"csv_import",first_name:"Unknown"},Z=K;return Object.entries(h).forEach(([Q,le])=>{var se;const ue=(se=V[Q])==null?void 0:se.trim();ue&&(le==="experience_years"||le==="last_year_transactions"?Z[le]=parseInt(ue.replace(/[^0-9.-]/g,""))||null:le==="annual_production"||le==="last_year_volume"||le==="avg_sale_price"?Z[le]=ue.replace(/[^0-9.$,.-]/g,""):Z[le]=ue)}),K});let H=0;for(let V=0;V<$.length;V+=100){const K=$.slice(V,V+100),{error:Z}=await q.from("recruit_prospects").insert(K);if(Z)throw Z;H+=K.length}S(H),b("done"),i.invalidateQueries({queryKey:["recruit-prospects",n]}),a({title:`${H} prospects imported!`})}catch(z){a({title:"Import failed",description:z.message,variant:"destructive"})}finally{y(!1)}},I=()=>{const z=`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`,$=new Blob([z],{type:"text/csv"}),H=URL.createObjectURL($),V=document.createElement("a");V.href=H,V.download="recruit-prospects-template.csv",V.click(),URL.revokeObjectURL(H)};return e.jsx(zs,{open:s,onOpenChange:z=>{z||A(),t(z)},children:e.jsxs(Ds,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{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(Qk,{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:T}),e.jsxs(U,{onClick:()=>{var z;return(z=l.current)==null?void 0:z.click()},children:[e.jsx(qa,{className:"h-4 w-4 mr-2"})," Choose File"]})]}),e.jsx(U,{variant:"link",className:"text-xs",onClick:I,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(Ns,{value:p,onValueChange:f,children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{})}),e.jsx(js,{children:r.map(z=>e.jsx(et,{value:z.id,children:z.name},z.id))})]})]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{className:"w-[140px]",children:"CSV Column"}),e.jsx(Lt,{className:"w-[160px]",children:"Map To"}),e.jsx(Lt,{children:"Preview"})]})}),e.jsx(Xa,{children:d.map((z,$)=>{var H;return e.jsxs(gn,{children:[e.jsx(gt,{className:"font-medium text-xs",children:z}),e.jsx(gt,{children:e.jsxs(Ns,{value:h[String($)]||"skip",onValueChange:V=>m(K=>({...K,[String($)]:V==="skip"?"":V})),children:[e.jsx(ws,{className:"h-8 text-xs",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"skip",children:"— Skip —"}),zJn.map(V=>e.jsx(et,{value:V,children:V.replace(/_/g," ")},V))]})]})}),e.jsx(gt,{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:((H=o[0])==null?void 0:H[String($)])||"—"})]},$)})})]})}),!Object.values(h).includes("first_name")&&e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-sm",children:[e.jsx(Vo,{className:"h-4 w-4"}),' Map at least "first name" to proceed']}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(U,{variant:"outline",onClick:()=>{A()},children:"Back"}),e.jsx(U,{onClick:M,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(Xr,{className:"h-6 w-6 text-green-600"})}),e.jsxs("p",{className:"font-semibold",children:[N," prospects imported successfully!"]}),e.jsx(U,{onClick:()=>{A(),t(!1)},children:"Close"})]})]})})}function Xts({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=gae(s),[o,c]=j.useState(!1),[d,u]=j.useState(),[h,m]=j.useState(null),[p,f]=j.useState(!1),[x,y]=j.useState(!1),[v,b]=j.useState(null);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 N=I=>n.filter(R=>R.stage_id===I),S=(I,R)=>{b(R),I.dataTransfer.effectAllowed="move"},A=I=>{I.preventDefault(),I.dataTransfer.dropEffect="move"},T=(I,R)=>{I.preventDefault(),v&&(i.mutate({id:v,stage_id:R}),b(null))},L=I=>{u(I),c(!0)},M=I=>{m(I),f(!0)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[n.length," prospect",n.length!==1?"s":""]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{variant:"outline",onClick:()=>y(!0),children:[e.jsx(qa,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(U,{onClick:()=>{u(void 0),c(!0)},children:[e.jsx(an,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs(Gi,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:t.length*300},children:t.map(I=>{const R=N(I.id);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:A,onDrop:z=>T(z,I.id),children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 px-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-3 w-3 rounded-full",style:{backgroundColor:I.color}}),e.jsx("h3",{className:"font-semibold text-sm",children:I.name}),e.jsx(Be,{variant:"secondary",className:"text-xs h-5 px-1.5",children:R.length})]}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>L(I.id),children:e.jsx(an,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"space-y-2 min-h-[200px] bg-muted/30 rounded-lg p-2",children:R.map(z=>e.jsx(we,{className:"p-3 cursor-pointer hover:shadow-md transition-shadow border-l-4 group",style:{borderLeftColor:I.color},draggable:!0,onDragStart:$=>S($,z.id),onClick:()=>M(z),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(kf,{className:"h-4 w-4 text-muted-foreground/40 mt-0.5 opacity-0 group-hover:opacity-100 transition-opacity cursor-grab"}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(So,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("span",{className:"font-medium text-sm truncate",children:[z.first_name," ",z.last_name]})]}),z.current_brokerage&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(_i,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:z.current_brokerage})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[z.email&&e.jsx(ln,{className:"h-3 w-3 text-muted-foreground"}),z.phone&&e.jsx(ba,{className:"h-3 w-3 text-muted-foreground"}),z.experience_years!=null&&e.jsxs(Be,{variant:"secondary",className:"text-[10px] h-4 px-1",children:[z.experience_years,"yr"]})]})]})]})},z.id))})]},I.id)})}),e.jsx(Vne,{orientation:"horizontal"})]}),e.jsx(Vts,{open:o,onOpenChange:c,stages:t,defaultStageId:d,onSubmit:I=>a.mutate(I),isSubmitting:a.isPending}),e.jsx(Yts,{prospect:h,stages:t,brokerageId:s,open:p,onOpenChange:f,onUpdate:I=>{i.mutate(I),m(R=>R?{...R,...I}:null)},onDelete:I=>l.mutate(I)}),e.jsx(Zts,{open:x,onOpenChange:y,brokerageId:s,stages:t})]})}function wTe({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=gae(s),{user:o}=vs(),c=Qt(),[d,u]=j.useState(!1),[h,m]=j.useState(null),[p,f]=j.useState(!1),[x,y]=j.useState(!1),[v,b]=j.useState(""),[N,S]=j.useState("all"),[A,T]=j.useState("all"),[L,M]=j.useState("all"),[I,R]=j.useState(null),[z,$]=j.useState("asc"),[H,V]=j.useState(new Set),[K,Z]=j.useState(!1),[Q,le]=j.useState(""),ue=j.useMemo(()=>{const Se=new Set;return n.forEach(Qe=>{Qe.current_brokerage&&Se.add(Qe.current_brokerage)}),Array.from(Se).sort()},[n]),{data:se=[]}=ct({queryKey:["recruit-campaigns-list",s],queryFn:async()=>{const{data:Se,error:Qe}=await q.from("recruit_campaigns").select("id, name, warmth_level").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("name");if(Qe)throw Qe;return Se}}),{data:ne=[]}=ct({queryKey:["recruit-campaign-assignments-lookup",s],queryFn:async()=>{let Qe=[],Ae=0;for(;;){const{data:Fe,error:Ne}=await q.from("recruit_campaign_assignments").select("prospect_id, campaign_id, status").eq("brokerage_id",s).range(Ae,Ae+1e3-1);if(Ne)throw Ne;if(Qe=Qe.concat(Fe??[]),!Fe||Fe.length<1e3)break;Ae+=1e3}return Qe}}),ie=j.useMemo(()=>{const Se=new Map;return ne.forEach(Qe=>{Se.has(Qe.prospect_id)||Se.set(Qe.prospect_id,new Set),Se.get(Qe.prospect_id).add(Qe.campaign_id)}),Se},[ne]),ce=Se=>{I===Se?$(Qe=>Qe==="asc"?"desc":"asc"):(R(Se),$("asc"))},je=({column:Se})=>I!==Se?e.jsx(xx,{className:"h-3.5 w-3.5 ml-1 text-muted-foreground/50"}):z==="asc"?e.jsx(cp,{className:"h-3.5 w-3.5 ml-1 text-primary"}):e.jsx(ag,{className:"h-3.5 w-3.5 ml-1 text-primary"}),be=Se=>t.find(Qe=>Qe.id===Se),he=j.useMemo(()=>{let Se=n.filter(Qe=>{var Ve,qe,Ze;const Ae=!v||`${Qe.first_name} ${Qe.last_name}`.toLowerCase().includes(v.toLowerCase())||((Ve=Qe.email)==null?void 0:Ve.toLowerCase().includes(v.toLowerCase()))||((qe=Qe.current_brokerage)==null?void 0:qe.toLowerCase().includes(v.toLowerCase())),Fe=N==="all"||Qe.stage_id===N,Ne=A==="all"||Qe.current_brokerage===A;let $e=!0;return L==="in_campaign"?$e=ie.has(Qe.id):L==="not_in_campaign"?$e=!ie.has(Qe.id):L!=="all"&&($e=((Ze=ie.get(Qe.id))==null?void 0:Ze.has(L))??!1),Ae&&Fe&&Ne&&$e});return I&&(Se=[...Se].sort((Qe,Ae)=>{var Ve,qe;let Fe=null,Ne=null;switch(I){case"name":Fe=`${Qe.first_name} ${Qe.last_name||""}`.toLowerCase(),Ne=`${Ae.first_name} ${Ae.last_name||""}`.toLowerCase();break;case"stage":Fe=((Ve=be(Qe.stage_id))==null?void 0:Ve.sort_order)??999,Ne=((qe=be(Ae.stage_id))==null?void 0:qe.sort_order)??999;break;case"brokerage":Fe=(Qe.current_brokerage||"").toLowerCase(),Ne=(Ae.current_brokerage||"").toLowerCase();break;case"experience":Fe=Qe.experience_years??-1,Ne=Ae.experience_years??-1;break;case"production":Fe=(Qe.annual_production||"").toLowerCase(),Ne=(Ae.annual_production||"").toLowerCase();break;case"source":Fe=(Qe.source||"").toLowerCase(),Ne=(Ae.source||"").toLowerCase();break;default:return 0}if(Fe===Ne)return 0;if(Fe==null)return 1;if(Ne==null)return-1;const $e=Fe0&&he.every(Se=>H.has(Se.id)),ke=he.some(Se=>H.has(Se.id)),Te=()=>{V(ge?new Set:new Set(he.map(Se=>Se.id)))},Me=Se=>{V(Qe=>{const Ae=new Set(Qe);return Ae.has(Se)?Ae.delete(Se):Ae.add(Se),Ae})},Oe=yt({mutationFn:async()=>{if(!Q||!(o!=null&&o.id))throw new Error("Select a campaign");const Se=new Set(ne.filter(Fe=>Fe.campaign_id===Q).map(Fe=>Fe.prospect_id)),Qe=Array.from(H).filter(Fe=>!Se.has(Fe)).map(Fe=>({prospect_id:Fe,campaign_id:Q,brokerage_id:s,assigned_by:o.id,status:"active",current_email_number:0}));if(Qe.length===0)throw new Error("All selected prospects are already in this campaign");const{error:Ae}=await q.from("recruit_campaign_assignments").insert(Qe);if(Ae)throw Ae;return Qe.length},onSuccess:Se=>{re.success(`${Se} prospect(s) added to campaign`),Z(!1),V(new Set),le(""),c.invalidateQueries({queryKey:["recruit-campaign-assignments-lookup"]})},onError:Se=>re.error(Se.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(Fr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search prospects...",value:v,onChange:Se=>b(Se.target.value),className:"pl-8"})]}),e.jsxs("div",{className:"flex gap-2",children:[H.size>0&&e.jsxs(U,{variant:"secondary",onClick:()=>Z(!0),className:"gap-1.5",children:[e.jsx($r,{className:"h-4 w-4"})," Add ",H.size," to Campaign"]}),e.jsxs(U,{variant:"outline",onClick:()=>y(!0),children:[e.jsx(qa,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(U,{onClick:()=>u(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(K2,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs(Ns,{value:N,onValueChange:S,children:[e.jsx(ws,{className:"w-[160px] h-8 text-xs",children:e.jsx(ks,{placeholder:"All stages"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All stages"}),t.map(Se=>e.jsx(et,{value:Se.id,children:Se.name},Se.id))]})]}),e.jsxs(Ns,{value:A,onValueChange:T,children:[e.jsxs(ws,{className:"w-[200px] h-8 text-xs",children:[e.jsx(_i,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(ks,{placeholder:"All brokerages"})]}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All brokerages"}),ue.map(Se=>e.jsx(et,{value:Se,children:Se},Se))]})]}),e.jsxs(Ns,{value:L,onValueChange:M,children:[e.jsxs(ws,{className:"w-[200px] h-8 text-xs",children:[e.jsx(ln,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(ks,{placeholder:"Campaign status"})]}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All contacts"}),e.jsx(et,{value:"in_campaign",children:"In any campaign"}),e.jsx(et,{value:"not_in_campaign",children:"Not in any campaign"}),se.map(Se=>e.jsxs(et,{value:Se.id,children:["In: ",Se.name]},Se.id))]})]}),(N!=="all"||A!=="all"||L!=="all")&&e.jsx(U,{variant:"ghost",size:"sm",className:"h-8 text-xs text-muted-foreground",onClick:()=>{S("all"),T("all"),M("all")},children:"Clear filters"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{className:"w-[40px]",children:e.jsx(xi,{checked:ge,onCheckedChange:Te,"aria-label":"Select all",...ke&&!ge?{"data-state":"indeterminate"}:{}})}),e.jsx(Lt,{className:"cursor-pointer select-none",onClick:()=>ce("name"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Name ",e.jsx(je,{column:"name"})]})}),e.jsx(Lt,{className:"cursor-pointer select-none",onClick:()=>ce("stage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Stage ",e.jsx(je,{column:"stage"})]})}),e.jsx(Lt,{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(je,{column:"brokerage"})]})}),e.jsx(Lt,{className:"hidden md:table-cell",children:"Contact"}),e.jsx(Lt,{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(je,{column:"experience"})]})}),e.jsx(Lt,{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(je,{column:"production"})]})}),e.jsx(Lt,{className:"hidden lg:table-cell",children:"Campaigns"}),e.jsx(Lt,{className:"w-[50px]"})]})}),e.jsx(Xa,{children:he.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:9,className:"text-center text-muted-foreground py-8",children:"No prospects found"})}):he.map(Se=>{const Qe=be(Se.stage_id),Ae=ie.get(Se.id),Fe=(Ae==null?void 0:Ae.size)??0;return e.jsxs(gn,{className:"cursor-pointer",onClick:()=>{m(Se),f(!0)},children:[e.jsx(gt,{onClick:Ne=>Ne.stopPropagation(),children:e.jsx(xi,{checked:H.has(Se.id),onCheckedChange:()=>Me(Se.id),"aria-label":`Select ${Se.first_name}`})}),e.jsxs(gt,{className:"font-medium",children:[Se.first_name," ",Se.last_name]}),e.jsx(gt,{children:Qe?e.jsxs(Be,{variant:"outline",className:"text-xs gap-1 whitespace-nowrap",style:{borderColor:Qe.color,color:Qe.color,backgroundColor:`${Qe.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:Qe.color}}),Qe.name]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})}),e.jsx(gt,{className:"hidden md:table-cell",children:Se.current_brokerage?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm",children:[e.jsx(_i,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[150px]",children:Se.current_brokerage})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{className:"hidden md:table-cell",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Se.email&&e.jsx(ln,{className:"h-3.5 w-3.5 text-muted-foreground"}),Se.phone&&e.jsx(ba,{className:"h-3.5 w-3.5 text-muted-foreground"}),!Se.email&&!Se.phone&&e.jsx("span",{className:"text-muted-foreground",children:"—"})]})}),e.jsx(gt,{className:"hidden lg:table-cell",children:Se.experience_years!=null?`${Se.experience_years} yr`:"—"}),e.jsx(gt,{className:"hidden lg:table-cell",children:Se.annual_production||"—"}),e.jsx(gt,{className:"hidden lg:table-cell",children:Fe>0?e.jsxs(Be,{variant:"secondary",className:"text-xs",children:[Fe," campaign",Fe>1?"s":""]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"None"})}),e.jsx(gt,{children:e.jsx(U,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:Ne=>{Ne.stopPropagation(),l.mutate(Se.id)},children:e.jsx(In,{className:"h-3.5 w-3.5"})})})]},Se.id)})})]})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[H.size>0&&e.jsxs("span",{className:"font-medium text-foreground",children:[H.size," selected · "]}),he.length," of ",n.length," prospects"]}),e.jsx(zs,{open:K,onOpenChange:Z,children:e.jsxs(Ds,{className:"sm:max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Add to Campaign"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Add ",e.jsx("span",{className:"font-medium text-foreground",children:H.size})," selected prospect(s) to a recruiting campaign drip."]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Campaign"}),e.jsxs(Ns,{value:Q,onValueChange:le,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select a campaign..."})}),e.jsx(js,{children:se.map(Se=>e.jsxs(et,{value:Se.id,children:[Se.name," ",e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",Se.warmth_level,")"]})]},Se.id))})]})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>Z(!1),children:"Cancel"}),e.jsx(U,{onClick:()=>Oe.mutate(),disabled:!Q||Oe.isPending,children:Oe.isPending?"Adding...":"Add to Campaign"})]})]})}),e.jsx(Vts,{open:d,onOpenChange:u,stages:t,onSubmit:Se=>a.mutate(Se),isSubmitting:a.isPending}),e.jsx(Yts,{prospect:h,stages:t,brokerageId:s,open:p,onOpenChange:f,onUpdate:Se=>{i.mutate(Se),m(Qe=>Qe?{...Qe,...Se}:null)},onDelete:Se=>l.mutate(Se)}),e.jsx(Zts,{open:x,onOpenChange:y,brokerageId:s,stages:t})]})}function Qts({brokerageId:s}){const{stages:t,prospects:n,isLoading:r}=gae(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+hN(u,new Date(b.created_at)),0)/i):0,m=t.map(v=>({...v,count:n.filter(b=>b.stage_id===v.id).length})),p={};n.forEach(v=>{const b=v.source||"unknown";p[b]=(p[b]||0)+1});const f=Object.entries(p).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:f,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(we,{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(Bn,{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(we,{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(rc,{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(we,{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(Yr,{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(we,{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(Gu,{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(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Ie,{className:"space-y-3",children:[a.bySrc.map(([i,l])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Be,{variant:"secondary",className:"capitalize",children:i.replace(/_/g," ")}),e.jsx("span",{className:"text-sm font-medium",children:l})]},i)),a.bySrc.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No source data"})]})]})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No prospect data yet. Add prospects to see metrics."})}const BJn=["Outreach","Follow-up","Interview","Offer","Referral","Other"];function Jts({brokerageId:s}){const{toast:t}=Ai(),{user:n}=vs(),r=Qt(),[a,i]=j.useState(null),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(null),{data:m=[],isLoading:p}=ct({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}}),f=yt({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=yt({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)},N=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(U,{onClick:v,size:"sm",className:"gap-1.5",children:[e.jsx(an,{className:"h-4 w-4"})," New Template"]})]}),p?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Et,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):N.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(ln,{className:"h-4 w-4"})," ",S]}),m.filter(A=>A.category===S).map(A=>{const T=A.brokerage_id!==null;return e.jsxs(we,{className:`transition-all ${l===A.id?"ring-2 ring-primary/20":"hover:shadow-sm"}`,children:[e.jsx(Tt,{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(It,{className:"text-sm flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:A.title}),!T&&e.jsx(Be,{variant:"secondary",className:"text-[10px] shrink-0",children:"Built-in"}),T&&e.jsx(Be,{className:"text-[10px] shrink-0",children:"Custom"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:["Subject: ",A.subject]})]}),e.jsx(Be,{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(U,{size:"sm",variant:"outline",onClick:()=>y(A.subject,A.id+"-s"),children:[a===A.id+"-s"?e.jsx(Xr,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1"}),"Copy Subject"]}),e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>y(A.body,A.id+"-b"),children:[a===A.id+"-b"?e.jsx(Xr,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1"}),"Copy Body"]}),T&&e.jsxs(e.Fragment,{children:[e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>b(A),children:[e.jsx(ri,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs(U,{size:"sm",variant:"outline",className:"text-destructive hover:text-destructive",onClick:async()=>{await Yi("Delete this template?")&&x.mutate(A.id)},children:[e.jsx(In,{className:"h-3.5 w-3.5 mr-1"})," Delete"]})]})]})]})]},A.id)})]},S)),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Ds,{className:"max-w-2xl",children:[e.jsx(Vs,{children:e.jsx($s,{children:u!=null&&u.id?"Edit Template":"New Template"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Title"}),e.jsx(xe,{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(te,{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:BJn.map(S=>e.jsx("option",{value:S,children:S},S))})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Subject"}),e.jsx(xe,{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(te,{className:"text-xs",children:"Body"}),e.jsx(Fs,{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(Mr,{children:[e.jsx(U,{variant:"ghost",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(U,{onClick:()=>f.mutate(u||{}),disabled:f.isPending||!(u!=null&&u.title)||!(u!=null&&u.subject)||!(u!=null&&u.body),children:[f.isPending&&e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Template"]})]})]})})]})}const FSt={call:ba,email:ln,text:Ki,meeting:pa,note:Ur};function ess({brokerageId:s}){const{data:t,isLoading:n}=ct({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(p=>p.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(p=>p.created_by),...(l||[]).map(p=>p.created_by)])],{data:d}=await q.from("profiles").select("id, name, email").in("id",c),u=Object.fromEntries((d||[]).map(p=>[p.id,p])),h=N5e(new Date,30);return{recruiters:c.map(p=>{var b,N;const f=(l||[]).filter(S=>S.created_by===p),x=f.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===p).length;return{id:p,name:((b=u[p])==null?void 0:b.name)||"Unknown",email:((N=u[p])==null?void 0:N.email)||"",totalActivities:f.length,recentActivities:x.length,byType:y,prospectsCreated:v}}).sort((p,f)=>f.recentActivities-p.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(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(So,{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=FSt[i]||Ur;return e.jsxs(Be,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(o,{className:"h-2.5 w-2.5"})," ",l," ",i,l!==1?"s":""]},i)})})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-lg font-bold",children:r.recentActivities}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"activities"})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-lg font-bold",children:r.prospectsCreated}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"prospects"})]})]},r.id))})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Recent Activity"})}),e.jsx(Ie,{className:"space-y-3",children:t.recentActivities.map(r=>{const a=FSt[r.activity_type]||Ur;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:Gs(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 tss({brokerageId:s}){const{toast:t}=Ai(),n=Qt(),[r,a]=j.useState(!1),[i,l]=j.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),{data:o=[],isLoading:c}=ct({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=[]}=ct({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=yt({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"})}),p=yt({mutationFn:async({id:y,status:v,incentive_status:b})=>{const N={updated_at:new Date().toISOString()};v&&(N.status=v),b&&(N.incentive_status=b);const{error:S}=await q.from("recruit_referrals").update(N).eq("id",y);if(S)throw S},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-referrals",s]})}),f=y=>y==="approved"||y==="signed"?e.jsx(Xr,{className:"h-3 w-3"}):y==="rejected"?e.jsx(ou,{className:"h-3 w-3"}):e.jsx(Yr,{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(U,{onClick:()=>a(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-2"})," Submit Referral"]})]}),o.length===0?e.jsxs(we,{className:"py-12 text-center",children:[e.jsx(zl,{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(we,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("span",{className:"font-medium",children:[y.referee_first_name," ",y.referee_last_name]}),e.jsxs(Be,{variant:"outline",className:x(y.status),children:[f(y.status)," ",y.status]}),y.incentive_status&&e.jsxs(Be,{variant:"outline",className:x(y.incentive_status),children:[e.jsx(Ro,{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"," • ",Gs(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(Ns,{value:y.status,onValueChange:b=>p.mutate({id:y.id,status:b}),children:[e.jsx(ws,{className:"h-7 text-xs w-[110px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"pending",children:"Pending"}),e.jsx(et,{value:"contacted",children:"Contacted"}),e.jsx(et,{value:"approved",children:"Approved"}),e.jsx(et,{value:"signed",children:"Signed"}),e.jsx(et,{value:"rejected",children:"Rejected"})]})]}),e.jsxs(Ns,{value:y.incentive_status||"pending",onValueChange:b=>p.mutate({id:y.id,incentive_status:b}),children:[e.jsx(ws,{className:"h-7 text-xs w-[100px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"pending",children:"Unpaid"}),e.jsx(et,{value:"paid",children:"Paid"}),e.jsx(et,{value:"n/a",children:"N/A"})]})]})]})]})},y.id)})}),e.jsx(zs,{open:r,onOpenChange:a,children:e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{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(te,{children:"First Name *"}),e.jsx(xe,{required:!0,value:i.first_name,onChange:y=>l(v=>({...v,first_name:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Last Name"}),e.jsx(xe,{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(te,{children:"Email"}),e.jsx(xe,{type:"email",value:i.email,onChange:y=>l(v=>({...v,email:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Phone"}),e.jsx(xe,{value:i.phone,onChange:y=>l(v=>({...v,phone:y.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Current Brokerage"}),e.jsx(xe,{value:i.current_brokerage,onChange:y=>l(v=>({...v,current_brokerage:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Notes"}),e.jsx(Fs,{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(U,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(U,{type:"submit",disabled:m.isPending,children:"Submit"})]})]})]})})]})}function sss({brokerageId:s}){const{toast:t}=Ai(),n=Qt(),[r,a]=j.useState(!1),{data:i}=ct({queryKey:["brokerage-recruit-form",s],queryFn:async()=>{const{data:m,error:p}=await q.from("brokerages").select("id, name, recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(p)throw p;return m}}),{data:l=[]}=ct({queryKey:["recruit-interest-submissions",s],queryFn:async()=>{const{data:m,error:p}=await q.from("recruit_interest_submissions").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(p)throw p;return m}}),o=yt({mutationFn:async m=>{const{error:p}=await q.from("brokerages").update({recruit_form_enabled:m}).eq("id",s);if(p)throw p},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-recruit-form",s]}),t({title:i!=null&&i.recruit_form_enabled?"Form disabled":"Form enabled"})}}),c=yt({mutationFn:async({id:m,status:p})=>{const{error:f}=await q.from("recruit_interest_submissions").update({status:p}).eq("id",m);if(f)throw f},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(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(te,{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(wn,{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(U,{size:"sm",variant:"outline",onClick:u,children:r?e.jsx(Xr,{className:"h-3.5 w-3.5"}):e.jsx(Pa,{className:"h-3.5 w-3.5"})}),e.jsx(U,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer",children:e.jsx(Sr,{className:"h-3.5 w-3.5"})})})]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{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(zl,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No submissions yet"})]}):e.jsx("div",{className:"space-y-3",children:l.map(m=>e.jsxs("div",{className:"flex items-start justify-between gap-4 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("span",{className:"font-medium text-sm",children:[m.first_name," ",m.last_name]}),e.jsx(Be,{variant:"outline",className:h(m.status),children:m.status})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs text-muted-foreground",children:[m.email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ln,{className:"h-3 w-3"}),m.email]}),m.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ba,{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:Gs(new Date(m.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(Ns,{value:m.status,onValueChange:p=>c.mutate({id:m.id,status:p}),children:[e.jsx(ws,{className:"h-7 text-xs w-[110px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"new",children:"New"}),e.jsx(et,{value:"contacted",children:"Contacted"}),e.jsx(et,{value:"converted",children:"Converted"}),e.jsx(et,{value:"dismissed",children:"Dismissed"})]})]})]},m.id))})})]})]})}function nss({brokerageId:s}){const{toast:t}=Ai(),n=Qt(),[r,a]=j.useState(!1),[i,l]=j.useState({prospect_id:"",title:"",description:"",due_date:Gs(jh(new Date,1),"yyyy-MM-dd'T'HH:mm")}),[o,c]=j.useState("pending"),{data:d=[]}=ct({queryKey:["recruit-prospects-list",s],queryFn:async()=>{const{data:A,error:T}=await q.from("recruit_prospects").select("id, first_name, last_name").eq("brokerage_id",s).order("first_name");if(T)throw T;return A}}),{data:u=[],isLoading:h}=ct({queryKey:["recruit-follow-ups",s],queryFn:async()=>{const A=d.map(M=>M.id);if(!A.length)return[];const{data:T,error:L}=await q.from("recruit_follow_ups").select("*").in("prospect_id",A).order("due_date");if(L)throw L;return T},enabled:d.length>0}),m=Object.fromEntries(d.map(A=>[A.id,A])),p=yt({mutationFn:async A=>{const{data:{user:T}}=await q.auth.getUser();if(!T)throw new Error("Not authenticated");const{error:L}=await q.from("recruit_follow_ups").insert({prospect_id:A.prospect_id,assigned_to:T.id,title:A.title,description:A.description||null,due_date:new Date(A.due_date).toISOString()});if(L)throw L},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-follow-ups",s]}),t({title:"Follow-up scheduled"}),l({prospect_id:"",title:"",description:"",due_date:Gs(jh(new Date,1),"yyyy-MM-dd'T'HH:mm")}),a(!1)},onError:A=>t({title:"Error",description:A.message,variant:"destructive"})}),f=yt({mutationFn:async({id:A,completed:T})=>{const{error:L}=await q.from("recruit_follow_ups").update({completed_at:T?new Date().toISOString():null}).eq("id",A);if(L)throw L},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&&z4(new Date(A.due_date))&&!ry(new Date(A.due_date))),v=x.filter(A=>!A.completed_at&&ry(new Date(A.due_date))),b=x.filter(A=>!A.completed_at&&!z4(new Date(A.due_date))&&!ry(new Date(A.due_date))),N=x.filter(A=>!!A.completed_at),S=A=>{const T=m[A.prospect_id],L=!A.completed_at&&z4(new Date(A.due_date))&&!ry(new Date(A.due_date));return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(xi,{checked:!!A.completed_at,onCheckedChange:M=>f.mutate({id:A.id,completed:M}),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:[T&&e.jsxs(Be,{variant:"secondary",className:"text-[10px]",children:[T.first_name," ",T.last_name]}),e.jsxs("span",{className:`flex items-center gap-1 ${L?"text-destructive font-medium":""}`,children:[L?e.jsx(Vo,{className:"h-3 w-3"}):e.jsx(pa,{className:"h-3 w-3"}),Gs(new Date(A.due_date),"MMM d, h:mm a")]}),A.is_automated&&e.jsx(Be,{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(U,{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(U,{size:"sm",onClick:()=>a(!0),children:[e.jsx(an,{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(Vo,{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(Yr,{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(pa,{className:"h-3.5 w-3.5"})," Upcoming (",b.length,")"]}),b.map(S)]}),o!=="pending"&&N.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(Xr,{className:"h-3.5 w-3.5"})," Completed (",N.length,")"]}),N.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(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Schedule Follow-up"})}),e.jsxs("form",{onSubmit:A=>{A.preventDefault(),p.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(te,{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(T=>({...T,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(te,{children:"Task *"}),e.jsx(xe,{required:!0,value:i.title,onChange:A=>l(T=>({...T,title:A.target.value})),placeholder:"e.g. Follow-up call"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Details"}),e.jsx(Fs,{value:i.description,onChange:A=>l(T=>({...T,description:A.target.value})),rows:2})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Due Date *"}),e.jsx(xe,{type:"datetime-local",required:!0,value:i.due_date,onChange:A=>l(T=>({...T,due_date:A.target.value}))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(U,{type:"submit",disabled:p.isPending,children:"Schedule"})]})]})]})})]})}const UJn=[{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 rss({brokerageId:s}){const{toast:t}=Ai(),n=Qt(),[r,a]=j.useState(null),{data:i,isLoading:l}=ct({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:UJn,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=yt({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(),N=`${s}/${v}-${Date.now()}.${b}`,{error:S}=await q.storage.from("recruit-landing").upload(N,y);if(S)throw S;const{data:{publicUrl:A}}=q.storage.from("recruit-landing").getPublicUrl(N);return A},h=async(y,v)=>{var N;const b=(N=y.target.files)==null?void 0:N[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 N=await u(v,"gallery");c(S=>({...S,gallery_images:[...S.gallery_images,N]})),t({title:"Gallery image added!"})}catch(N){t({title:"Upload failed",description:N.message,variant:"destructive"})}finally{a(null)}}},p=async(y,v)=>{var N;const b=(N=y.target.files)==null?void 0:N[0];if(b){a(`testimonial-${v}`);try{const S=await u(b,`testimonial-${v}`);c(A=>{const T=[...A.testimonials];return T[v]={...T[v],photo_url:S},{...A,testimonials:T}})}catch(S){t({title:"Upload failed",description:S.message,variant:"destructive"})}finally{a(null)}}},{data:f}=ct({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/${(f==null?void 0:f.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:[(f==null?void 0:f.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(U,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:x,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Sr,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(te,{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(U,{variant:"outline",size:"sm",asChild:!0,disabled:r==="logo_url",children:e.jsxs("span",{children:[e.jsx(qa,{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(te,{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(xe,{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(te,{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(xe,{value:o.accent_color,onChange:y=>c(v=>({...v,accent_color:y.target.value})),className:"font-mono text-xs"})]})]})]})]})})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Hero Section"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Headline"}),e.jsx(xe,{value:o.hero_headline,onChange:y=>c(v=>({...v,hero_headline:y.target.value})),placeholder:"Join Our Team"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Subtext"}),e.jsx(Fs,{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(te,{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(U,{variant:"outline",size:"sm",asChild:!0,disabled:r==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(qa,{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(U,{variant:"ghost",size:"sm",onClick:()=>c(y=>({...y,hero_image_url:null})),children:e.jsx(In,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsx(It,{className:"text-base",children:"Benefits / Why Join Us"}),e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>c(y=>({...y,benefits:[...y.benefits,{title:"",description:"",icon:"✨"}]})),children:[e.jsx(an,{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(kf,{className:"h-4 w-4 mt-2 text-muted-foreground"}),e.jsx(xe,{value:y.icon,onChange:b=>{const N=[...o.benefits];N[v]={...y,icon:b.target.value},c(S=>({...S,benefits:N}))},className:"w-14 text-center"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(xe,{value:y.title,onChange:b=>{const N=[...o.benefits];N[v]={...y,title:b.target.value},c(S=>({...S,benefits:N}))},placeholder:"Benefit title"}),e.jsx(xe,{value:y.description,onChange:b=>{const N=[...o.benefits];N[v]={...y,description:b.target.value},c(S=>({...S,benefits:N}))},placeholder:"Short description"})]}),e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>c(b=>({...b,benefits:b.benefits.filter((N,S)=>S!==v)})),children:e.jsx(In,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsx(It,{className:"text-base",children:"Testimonials"}),e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>c(y=>({...y,testimonials:[...y.testimonials,{name:"",role:"",quote:""}]})),children:[e.jsx(an,{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:N=>p(N,v)})]})]}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(xe,{value:y.name,onChange:N=>{const S=[...o.testimonials];S[v]={...y,name:N.target.value},c(A=>({...A,testimonials:S}))},placeholder:"Name"}),e.jsx(xe,{value:y.role,onChange:N=>{const S=[...o.testimonials];S[v]={...y,role:N.target.value},c(A=>({...A,testimonials:S}))},placeholder:"Role / Title"})]}),e.jsx(Fs,{value:y.quote,onChange:N=>{const S=[...o.testimonials];S[v]={...y,quote:N.target.value},c(A=>({...A,testimonials:S}))},placeholder:"What they say about working here...",rows:2})]}),e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>c(N=>({...N,testimonials:N.testimonials.filter((S,A)=>A!==v)})),children:e.jsx(In,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsx(It,{className:"text-base",children:"Team & Culture Gallery"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(U,{size:"sm",variant:"outline",asChild:!0,disabled:r==="gallery",children:e.jsxs("span",{children:[e.jsx(pc,{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(U,{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((N,S)=>S!==v)})),children:e.jsx(In,{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(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(cn,{className:"h-4 w-4 text-primary"})," Form Style & Trust"]})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Application Form Style"}),e.jsxs(Ns,{value:o.form_style,onValueChange:y=>c(v=>({...v,form_style:y})),children:[e.jsx(ws,{className:"mt-1.5",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"classic",children:"Classic — single-page form (all fields visible)"}),e.jsx(et,{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(Ql,{className:"h-4 w-4 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx(te,{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(wn,{checked:o.confidential_messaging,onCheckedChange:y=>c(v=>({...v,confidential_messaging:y}))})]})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(Qw,{className:"h-4 w-4 text-primary"})," Split & Income Calculator"]}),e.jsx(wn,{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(te,{className:"text-xs",children:"Calculator Headline"}),e.jsx(xe,{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(te,{className:"text-xs",children:"Subtext"}),e.jsx(xe,{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(te,{className:"text-xs",children:"Pre-Cap Split % (agent keeps)"}),e.jsx(xe,{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(te,{className:"text-xs",children:"Cap Amount ($)"}),e.jsx(xe,{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(te,{className:"text-xs",children:"Post-Cap Split % (agent keeps)"}),e.jsx(xe,{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(te,{className:"text-xs",children:"Monthly Fee ($)"}),e.jsx(xe,{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(te,{className:"text-xs",children:"Per-Transaction Fee ($)"}),e.jsx(xe,{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(te,{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(wn,{checked:o.calculator_config.show_email_capture!==!1,onCheckedChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,show_email_capture:y}}))})]})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(W2,{className:"h-4 w-4 text-primary"})," Lead Magnet (Gated PDF)"]}),e.jsx(wn,{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(te,{className:"text-xs",children:"Title"}),e.jsx(xe,{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(te,{className:"text-xs",children:"Description"}),e.jsx(Fs,{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(te,{className:"text-xs",children:"Button Text"}),e.jsx(xe,{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(te,{className:"text-xs",children:"PDF / File URL"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(xe,{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(U,{variant:"outline",size:"sm",asChild:!0,disabled:r==="lead_magnet_pdf",children:e.jsxs("span",{children:[e.jsx(qa,{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 N=await u(v,"lead-magnet");c(S=>({...S,lead_magnet_config:{...S.lead_magnet_config,pdf_url:N}})),t({title:"PDF uploaded!"})}catch(N){t({title:"Upload failed",description:N.message,variant:"destructive"})}finally{a(null)}}}})]})]})]})]})]})]}),e.jsx(qJn,{brokerageId:s}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(U,{onClick:()=>d.mutate(),disabled:d.isPending,size:"lg",children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"}),d.isPending?"Saving...":"Save Landing Page"]})})]})}function qJn({brokerageId:s}){const{data:t=[]}=ct({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(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(pi,{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:[Gs(new Date(n.created_at),"MMM d, yyyy h:mm a")," · via ",n.source]})]})},n.id))})})]})}function ass({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]:[])),[p,f]=j.useState("all"),[x,y]=j.useState(""),[v,b]=j.useState(null),[N,S]=j.useState(""),[A,T]=j.useState(0),[L,M]=j.useState(0),[I,R]=j.useState(""),[z,$]=j.useState(""),{data:H}=KIe(),[V,K]=j.useState("default");j.useEffect(()=>{K(H!=null&&H.massEmail?"mass_email":H!=null&&H.gmail?"gmail":"default")},[H==null?void 0:H.massEmail,H==null?void 0:H.gmail]);const[Z,Q]=j.useState(null),{prospects:le,stages:ue}=gae(s),se=Gts(),ne=f3(),{data:ie=[]}=ct({queryKey:["brokerage-recruit-video-pool",s],queryFn:async()=>{const{data:Se,error:Qe}=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(Qe)throw Qe;return Se??[]},enabled:o&&d==="pick-video"}),ce=j.useCallback(()=>{u("pick-recipients"),m(new Set(n?[n]:[])),f("all"),y(""),b(null),S(""),T(0),M(0),R(""),$(""),K("default"),Q(null)},[n]),je=Se=>{!Se&&(d==="uploading"||d==="processing"||d==="sending")||(c(Se),Se||setTimeout(ce,200))},be=j.useMemo(()=>le.filter(Se=>{if(!Se.email||p!=="all"&&Se.stage_id!==p)return!1;if(x){const Qe=x.toLowerCase();if(!`${Se.first_name} ${Se.last_name??""}`.toLowerCase().includes(Qe)&&!Se.email.toLowerCase().includes(Qe))return!1}return!0}),[le,p,x]),he=Se=>{m(Qe=>{const Ae=new Set(Qe);return Ae.has(Se)?Ae.delete(Se):Ae.add(Se),Ae})},ge=()=>{h.size===be.length?m(new Set):m(new Set(be.map(Se=>Se.id)))},ke=j.useCallback(async(Se,Qe)=>{u("uploading");try{const Ae=`Recruiting blast (${h.size} recipients)`,{videoId:Fe,libraryId:Ne}=await cL(Ae),{uploadUrl:$e,apiKey:Ve}=await dL(Fe),qe=new XMLHttpRequest;qe.upload.onprogress=ft=>{ft.lengthComputable&&T(ft.loaded/ft.total*100)},await new Promise((ft,qt)=>{qe.onload=()=>qe.status>=200&&qe.status<300?ft():qt(new Error("Upload failed")),qe.onerror=()=>qt(new Error("Upload failed")),qe.open("PUT",$e),qe.setRequestHeader("AccessKey",Ve),qe.send(Se)}),u("processing");const Ze=`https://iframe.mediadelivery.net/embed/${Ne}/${Fe}`;let Ue=0;const Ye=Date.now(),Ge=9e4;for(;Ue<4&&(await new Promise(qt=>setTimeout(qt,3e3)),!(Date.now()-Ye>Ge));){const ft=await fN(Fe);if(Ue=ft.status,M(ft.encodeProgress||0),Ue===5||Ue===6)throw new Error("Video processing failed")}const He=await fN(Fe),tt=(He.storageSize||Se.size)/(1024*1024),pt=await ne.mutateAsync({bunny_video_id:Fe,playback_url:He.directPlayUrl||Ze,thumbnail_url:He.thumbnailUrl,preview_url:He.previewUrl||null,duration_seconds:He.length||Qe,file_size_mb:tt,title:Ae,status:Ue>=4?"ready":"processing",touch_type:"recruiting"});b(pt.id),S(Ae),u("compose")}catch(Ae){re.error((Ae==null?void 0:Ae.message)||"Failed to upload video"),u("pick-video")}},[h.size,ne]),Te=j.useCallback(async()=>{if(!(!v||h.size===0)){u("sending");try{const Se=[];for(const Fe of h){const Ne=await se.mutateAsync({prospect_id:Fe,video_id:v,brokerage_id:s,message:z||void 0});Se.push(Ne.id)}const{data:Qe,error:Ae}=await q.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:Se,brokerage_id:s,subject_override:I||void 0,message_override:z||void 0,send_via:V}});if(Ae)throw new Error(Ae.message);Q({sent:(Qe==null?void 0:Qe.sent)??0,total:(Qe==null?void 0:Qe.total)??Se.length}),u("done"),re.success(`Sent ${(Qe==null?void 0:Qe.sent)??0} of ${(Qe==null?void 0:Qe.total)??Se.length} videos`)}catch(Se){re.error((Se==null?void 0:Se.message)||"Failed to send"),u("compose")}}},[v,h,s,z,I,V,se]),Me=h.size,Oe=le.filter(Se=>!Se.email).length;return e.jsxs(zs,{open:o,onOpenChange:je,children:[t&&e.jsx(al,{asChild:!0,children:t}),e.jsxs(Ds,{className:"max-w-3xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Wr,{className:"h-5 w-5 text-primary"}),"Send Recruiting Video",Me>0&&e.jsxs(Be,{variant:"secondary",className:"ml-2",children:[e.jsx(Bn,{className:"h-3 w-3 mr-1"}),Me," ",Me===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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search prospects...",value:x,onChange:Se=>y(Se.target.value),className:"pl-9"})]}),e.jsxs(Ns,{value:p,onValueChange:f,children:[e.jsx(ws,{className:"w-48",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All stages"}),ue.map(Se=>e.jsx(et,{value:Se.id,children:Se.name},Se.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("button",{onClick:ge,className:"hover:underline",children:[h.size===be.length&&be.length>0?"Deselect all":"Select all"," ","(",be.length,")"]}),Oe>0&&e.jsxs("span",{children:[Oe," prospect(s) hidden — no email on file"]})]}),e.jsx(Gi,{className:"flex-1 border rounded-md",children:be.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:be.map(Se=>{const Qe=h.has(Se.id),Ae=ue.find(Fe=>Fe.id===Se.stage_id);return e.jsxs("label",{className:"flex items-center gap-3 p-3 hover:bg-muted/30 cursor-pointer",children:[e.jsx(xi,{checked:Qe,onCheckedChange:()=>he(Se.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:[Se.first_name," ",Se.last_name]}),Ae&&e.jsx(Be,{variant:"outline",className:"text-[10px]",style:{borderColor:Ae.color,color:Ae.color},children:Ae.name})]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Se.email," ",Se.current_brokerage&&`· ${Se.current_brokerage}`]})]})]},Se.id)})})}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>je(!1),children:"Cancel"}),e.jsx(U,{disabled:Me===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(oa,{defaultValue:"record",className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(la,{className:"self-start",children:[e.jsxs(Kt,{value:"record",children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1"}),"Record New"]}),e.jsxs(Kt,{value:"library",children:[e.jsx(tj,{className:"h-3.5 w-3.5 mr-1"}),"Use Existing"]})]}),e.jsx(Zt,{value:"record",className:"flex-1 overflow-auto",children:e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx(Gh,{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 ",Me," ",Me===1?"recipient":"recipients"," — each gets their own tracked link."]})]}),e.jsxs(U,{onClick:()=>u("record"),children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Start Recording"]})]})}),e.jsx(Zt,{value:"library",className:"flex-1 overflow-auto",children:ie.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:ie.map(Se=>e.jsxs("button",{onClick:()=>{b(Se.id),S(Se.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(Se)?e.jsx("img",{src:_4(Se),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(Wr,{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:Se.title||"Untitled"})})]},Se.id))})})]}),e.jsx(Mr,{children:e.jsx(U,{variant:"outline",onClick:()=>u("pick-recipients"),children:"Back"})})]}),d==="record"&&e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx(kE,{maxDurationSeconds:600,onRecordingComplete:ke}),e.jsx("div",{className:"mt-2 flex justify-start",children:e.jsx(U,{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(Et,{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(ro,{value:d==="uploading"?A:L,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(d==="uploading"?A:L),"%"]})]}),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(zr,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"flex-1 text-sm",children:[e.jsx("span",{className:"font-medium",children:N})," selected · sending to ",e.jsx("strong",{children:Me})," recipient",Me===1?"":"s"]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Subject (optional override)"}),e.jsx(xe,{value:I,onChange:Se=>R(Se.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(te,{className:"text-xs",children:"Personal message shown in the email & on the landing page"}),e.jsx(Fs,{value:z,onChange:Se=>$(Se.target.value),placeholder:"Hey there — wanted to share a quick thought on what we're building here...",rows:5,className:"mt-1"})]}),e.jsx(wrt,{value:V,onChange:K}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>u("pick-video"),children:"Back"}),e.jsxs(U,{onClick:Te,disabled:!v||Me===0,children:[e.jsx($r,{className:"h-4 w-4 mr-2"})," Send to ",Me," ",Me===1?"prospect":"prospects"]})]})]}),d==="sending"&&e.jsxs("div",{className:"py-12 text-center space-y-3",children:[e.jsx(Et,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending to ",Me," recipient",Me===1?"":"s","…"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Each prospect gets their own tracked share link."})]}),d==="done"&&Z&&e.jsxs("div",{className:"py-12 text-center space-y-4",children:[e.jsx("div",{className:`h-16 w-16 rounded-full mx-auto flex items-center justify-center ${Z.sent===Z.total?"bg-primary/10":"bg-muted"}`,children:Z.sent===Z.total?e.jsx(zr,{className:"h-8 w-8 text-primary"}):e.jsx(Vo,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-lg",children:[Z.sent," of ",Z.total," sent"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"View engagement under the Video Outreach tab."})]}),e.jsx(U,{onClick:()=>je(!1),children:"Done"})]})]})]})}function $Jn(s){if(!s)return"—";const t=Math.floor(s/60),n=s%60;return t>0?`${t}m ${n}s`:`${n}s`}function VJn({video:s}){return s.cta_clicked_at?e.jsx(Be,{className:"bg-emerald-500/10 text-emerald-600 border-emerald-200",children:"CTA Clicked"}):s.view_count>0?e.jsxs(Be,{className:"bg-blue-500/10 text-blue-600 border-blue-200",children:[e.jsx(xa,{className:"h-3 w-3 mr-1"}),s.view_count," views"]}):s.sent_at?e.jsxs(Be,{variant:"secondary",children:[e.jsx($r,{className:"h-3 w-3 mr-1"}),"Sent"]}):e.jsxs(Be,{variant:"outline",children:[e.jsx(Yr,{className:"h-3 w-3 mr-1"}),"Draft"]})}function iss({brokerageId:s}){var N,S,A,T;const{data:t=[],isLoading:n}=MJn(s),{data:r=[]}=Kts(s),a=LJn(),i=IJn(),l=Wts(),[o,c]=j.useState(""),[d,u]=j.useState(!1),[h,m]=j.useState({title:"",script_text:"",category:"general"}),[p,f]=j.useState(null),x=t.filter(L=>{var I,R,z,$;return o?`${((I=L.prospect)==null?void 0:I.first_name)||""} ${((R=L.prospect)==null?void 0:R.last_name)||""}`.toLowerCase().includes(o.toLowerCase())||(($=(z=L.video)==null?void 0:z.title)==null?void 0:$.toLowerCase().includes(o.toLowerCase())):!0}),y={total:t.length,sent:t.filter(L=>L.sent_at).length,viewed:t.filter(L=>L.view_count>0).length,ctaClicked:t.filter(L=>L.cta_clicked_at).length},v=j.useCallback(L=>{if(!L)return;const M=`${window.location.origin}/recruit-video/${L}`;navigator.clipboard.writeText(M),re.success("Share link copied")},[]);j.useCallback((L,M)=>{l.mutate({id:L,sent_via:M})},[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:Wr,color:"text-primary"},{label:"Sent",value:y.sent,icon:$r,color:"text-blue-500"},{label:"Viewed",value:y.viewed,icon:xa,color:"text-amber-500"},{label:"CTA Clicked",value:y.ctaClicked,icon:zr,color:"text-emerald-500"}].map(L=>e.jsx(we,{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 ${L.color}`,children:e.jsx(L.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:L.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:L.label})]})]})},L.label))}),e.jsxs(oa,{defaultValue:"videos",className:"space-y-4",children:[e.jsxs(la,{children:[e.jsxs(Kt,{value:"videos",children:[e.jsx(Wr,{className:"h-4 w-4 mr-1.5"}),"All Videos"]}),e.jsxs(Kt,{value:"scripts",children:[e.jsx(Ur,{className:"h-4 w-4 mr-1.5"}),"Script Library"]}),e.jsxs(Kt,{value:"analytics",children:[e.jsx(Cl,{className:"h-4 w-4 mr-1.5"}),"Engagement"]})]}),e.jsx(Zt,{value:"videos",children:e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(It,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name or title...",value:o,onChange:L=>c(L.target.value),className:"pl-9"})]}),e.jsx(ass,{brokerageId:s,trigger:e.jsxs(U,{size:"sm",className:"gap-1.5",children:[e.jsx(ln,{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(Wr,{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(L=>{var M,I,R,z,$,H,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(L.video)?e.jsx("img",{src:_4(L.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(Wr,{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:$Jn(((M=L.video)==null?void 0:M.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:[(I=L.prospect)==null?void 0:I.first_name," ",(R=L.prospect)==null?void 0:R.last_name]}),e.jsx(VJn,{video:L})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:((z=L.video)==null?void 0:z.title)||"Untitled video"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[Gs(new Date(L.created_at),"MMM d, yyyy"),(($=L.prospect)==null?void 0:$.current_brokerage)&&` · ${L.prospect.current_brokerage}`]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>v(L.share_token),title:"Copy share link",children:e.jsx(Pa,{className:"h-4 w-4"})}),e.jsxs(U,{variant:L.sent_at?"ghost":"default",size:"sm",className:"h-8 gap-1.5",onClick:()=>f(L),disabled:!((H=L.prospect)!=null&&H.email),title:(V=L.prospect)!=null&&V.email?"Email this video to the prospect":"Prospect has no email",children:[e.jsx(ln,{className:"h-4 w-4"}),L.sent_at?"Resend":"Email"]}),L.share_token&&e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>window.open(`/recruit-video/${L.share_token}`,"_blank"),title:"Preview landing page",children:e.jsx(Sr,{className:"h-4 w-4"})})]})]},L.id)})})})]})}),e.jsx(Zt,{value:"scripts",children:e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(It,{className:"text-lg",children:"Recruiting Scripts"}),e.jsxs(zs,{open:d,onOpenChange:u,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{size:"sm",children:[e.jsx(an,{className:"h-4 w-4 mr-1.5"}),"New Script"]})}),e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Create Recruiting Script"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Title"}),e.jsx(xe,{value:h.title,onChange:L=>m(M=>({...M,title:L.target.value})),placeholder:"e.g., Why Switch to Our Brokerage"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Category"}),e.jsxs(Ns,{value:h.category,onValueChange:L=>m(M=>({...M,category:L})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:CKe.map(L=>e.jsx(et,{value:L.value,children:L.label},L.value))})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Script"}),e.jsx(Fs,{value:h.script_text,onChange:L=>m(M=>({...M,script_text:L.target.value})),placeholder:"Hi [Name], I noticed you've been doing great work at [Brokerage]...",rows:8})]}),e.jsx(U,{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(Ur,{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(L=>{var I;const M=((I=CKe.find(R=>R.value===L.category))==null?void 0:I.label)||L.category;return e.jsx(we,{className:"relative group",children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(Be,{variant:"outline",className:"text-[10px] mb-2",children:M}),e.jsx("h4",{className:"font-medium text-sm",children:L.title})]}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity text-destructive",onClick:()=>i.mutate(L.id),children:e.jsx(In,{className:"h-3.5 w-3.5"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 line-clamp-3",children:L.script_text}),L.is_global&&e.jsx(Be,{variant:"secondary",className:"mt-2 text-[10px]",children:"Template"})]})},L.id)})})})]})}),e.jsx(Zt,{value:"analytics",children:e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(L=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:L.label}),e.jsxs("span",{className:"font-medium",children:[L.count," (",L.pct,"%)"]})]}),e.jsx("div",{className:"h-3 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full ${L.color} rounded-full transition-all`,style:{width:`${L.pct}%`}})})]},L.label))}),t.filter(L=>L.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(L=>L.view_count>0).sort((L,M)=>M.view_count-L.view_count).slice(0,5).map(L=>{var M,I;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:[(M=L.prospect)==null?void 0:M.first_name," ",(I=L.prospect)==null?void 0:I.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(xa,{className:"h-3.5 w-3.5"})," ",L.view_count]}),L.cta_clicked_at&&e.jsx(zr,{className:"h-4 w-4 text-emerald-500"})]})]},L.id)})})]})]})]})})]}),p&&e.jsx(Hts,{open:!!p,onOpenChange:L=>{L||f(null)},recruitVideoId:p.id,brokerageId:s,prospectName:`${((N=p.prospect)==null?void 0:N.first_name)||""} ${((S=p.prospect)==null?void 0:S.last_name)||""}`.trim(),prospectEmail:(A=p.prospect)==null?void 0:A.email,videoTitle:(T=p.video)==null?void 0:T.title,defaultMessage:p.message})]})}function oss({brokerageId:s}){const{toast:t}=Ai(),n=Qt(),{stages:r,prospects:a}=gae(s),[i,l]=j.useState(!1),[o,c]=j.useState({title:"",target_count:"10",target_stage_id:"",period_start:Gs(new Date,"yyyy-MM-dd"),period_end:Gs(new Date(new Date().getFullYear(),new Date().getMonth()+3,0),"yyyy-MM-dd")}),{data:d=[],isLoading:u}=ct({queryKey:["recruit-goals",s],queryFn:async()=>{const{data:f,error:x}=await q.from("recruit_goals").select("*").eq("brokerage_id",s).order("period_end",{ascending:!1});if(x)throw x;return f}}),h=yt({mutationFn:async f=>{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:f.title,target_count:parseInt(f.target_count),target_stage_id:f.target_stage_id||null,period_start:f.period_start,period_end:f.period_end,created_by:x.id});if(y)throw y},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal created"}),l(!1)},onError:f=>t({title:"Error",description:f.message,variant:"destructive"})}),m=yt({mutationFn:async f=>{const{error:x}=await q.from("recruit_goals").delete().eq("id",f);if(x)throw x},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal removed"})}}),p=f=>{const x=r.find(v=>v.id===f.target_stage_id);return{count:a.filter(v=>Pk(new Date(v.created_at),{start:new Date(f.period_start),end:new Date(f.period_end)})?f.target_stage_id?v.stage_id===f.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(U,{size:"sm",onClick:()=>l(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),d.length===0?e.jsxs(we,{className:"py-12 text-center",children:[e.jsx(Gu,{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(f=>{const{count:x,stage:y}=p(f),v=Math.min(100,x/f.target_count*100),b=Pk(new Date,{start:new Date(f.period_start),end:new Date(f.period_end)});return e.jsxs(we,{className:b?"":"opacity-60",children:[e.jsx(Tt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{className:"text-sm",children:f.title}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[Gs(new Date(f.period_start),"MMM d")," – ",Gs(new Date(f.period_end),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[b?e.jsx(Be,{className:"text-[10px]",children:"Active"}):e.jsx(Be,{variant:"secondary",className:"text-[10px]",children:"Ended"}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-6 w-6 text-muted-foreground",onClick:()=>m.mutate(f.id),children:e.jsx(In,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Ie,{className:"space-y-2",children:[y&&e.jsxs(Be,{variant:"outline",className:"text-[10px]",style:{borderColor:y.color,color:y.color},children:["Stage: ",y.name]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-bold text-lg",children:x}),e.jsxs("span",{className:"text-muted-foreground",children:["/ ",f.target_count]})]}),e.jsx(ro,{value:v,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[v.toFixed(0),"% complete"]})]})]},f.id)})}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Create Recruiting Goal"})}),e.jsxs("form",{onSubmit:f=>{f.preventDefault(),h.mutate(o)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Goal Title *"}),e.jsx(xe,{required:!0,value:o.title,onChange:f=>c(x=>({...x,title:f.target.value})),placeholder:"e.g. Q2 Recruiting Target"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Target Count *"}),e.jsx(xe,{type:"number",min:"1",required:!0,value:o.target_count,onChange:f=>c(x=>({...x,target_count:f.target.value}))})]}),e.jsxs("div",{children:[e.jsx(te,{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:f=>c(x=>({...x,target_stage_id:f.target.value})),children:[e.jsx("option",{value:"",children:"All stages (total prospects)"}),r.map(f=>e.jsx("option",{value:f.id,children:f.name},f.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(te,{children:"Start Date"}),e.jsx(xe,{type:"date",required:!0,value:o.period_start,onChange:f=>c(x=>({...x,period_start:f.target.value}))})]}),e.jsxs("div",{children:[e.jsx(te,{children:"End Date"}),e.jsx(xe,{type:"date",required:!0,value:o.period_end,onChange:f=>c(x=>({...x,period_end:f.target.value}))})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(U,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(U,{type:"submit",disabled:h.isPending,children:"Create Goal"})]})]})]})})]})}const HJn={first_name:"Sarah",brokerage_name:"ABC Realty",city:"Austin",sender_name:"Jeremy"};function lss({email:s,mergeValues:t=HJn,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(Ds,{className:"max-w-2xl max-h-[85vh] overflow-y-auto p-0",children:[e.jsxs(Vs,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs($s,{className:"text-base",children:["Email #",s.email_number," — ",s.title]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2",children:[e.jsxs(Be,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(Yr,{className:"h-3 w-3"}),s.email_number===1?"Sent immediately":`Day ${s.delay_days}`]}),i.length>1&&e.jsxs(Be,{variant:"secondary",className:"text-xs",children:[i.length," subject variants"]})]})]}),e.jsxs("div",{className:"space-y-0",children:[i.length>1&&e.jsxs("div",{className:"px-6 py-3 border-b bg-muted/20",children:[e.jsx("p",{className:"text-[10px] font-medium text-muted-foreground uppercase tracking-wider mb-2",children:"Subject Line Options"}),e.jsx("div",{className:"flex flex-col gap-1.5",children:i.map((d,u)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-[10px] font-bold uppercase px-1.5 py-0.5 rounded ${u===l?"bg-primary/10 text-primary":"bg-muted text-muted-foreground"}`,children:u===l?"Selected":u===0?"Primary":`Alt ${u}`}),e.jsx("span",{className:"text-sm",children:a(d)})]},u))})]}),e.jsxs("div",{className:"border-b",children:[e.jsxs("div",{className:"px-6 py-2 flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium w-14",children:"From:"}),e.jsxs("span",{children:[t.sender_name," "]})]}),e.jsxs("div",{className:"px-6 py-2 flex items-center gap-2 text-xs text-muted-foreground border-t",children:[e.jsx("span",{className:"font-medium w-14",children:"To:"}),e.jsxs("span",{children:[t.first_name," "]})]}),e.jsxs("div",{className:"px-6 py-2 flex items-center gap-2 text-xs border-t",children:[e.jsx("span",{className:"font-medium w-14 text-muted-foreground",children:"Subject:"}),e.jsx("span",{className:"font-medium",children:a(o)})]})]}),e.jsx("div",{className:"bg-white px-8 py-6",children:e.jsx("div",{className:"prose prose-sm max-w-none [&_p]:my-3 [&_p+p]:mt-4 [&_br]:block [&_br]:mt-2",style:{fontSize:"15px",lineHeight:"1.75",color:"#1a1a1a"},dangerouslySetInnerHTML:{__html:a(s.body_html)}})})]})]})})}function jrt({brokerageId:s}){const t=Qt(),{user:n}=vs(),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState({brokerage_id:s,sender_name:"LevelUp",sender_email:"recruiting@relevelup.com",reply_to_email:"",merge_fields:{city:"",broker_name:""}}),{data:d}=ct({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:f,error:x}=await q.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(x)throw x;return f}}),{data:u}=ct({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:f,error:x}=await q.from("brokerages").select("name, city, state").eq("id",s).single();if(x)throw x;return f}});j.useEffect(()=>{d?c({...d,merge_fields:d.merge_fields||{city:"",broker_name:""}}):u&&c(f=>({...f,merge_fields:{...f.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:f})=>a((f==null?void 0:f.recruit_cta_url)||""))},[n==null?void 0:n.id]);const h=async()=>{if(!(n!=null&&n.id))return;l(!0);const{error:f}=await q.from("profiles").update({recruit_cta_url:r.trim()||null}).eq("id",n.id);l(!1),f?re.error(f.message):re.success("Scheduling link saved!")},m=yt({mutationFn:async()=>{const f={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(f).eq("id",d.id);if(x)throw x}else{const{error:x}=await q.from("brokerage_recruit_settings").insert(f);if(x)throw x}},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-recruit-settings",s]}),re.success("Recruiting email settings saved!")},onError:f=>re.error(f.message)}),p=(f,x)=>{c(y=>({...y,merge_fields:{...y.merge_fields,[f]: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(pa,{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(xe,{value:r,onChange:f=>a(f.target.value),placeholder:"https://calendly.com/your-name/intro"}),e.jsxs(U,{onClick:h,disabled:i,size:"sm",children:[e.jsx(Ho,{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(te,{className:"text-xs",children:"Sender Display Name"}),e.jsx(xe,{value:o.sender_name,onChange:f=>c({...o,sender_name:f.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{className:"text-xs",children:"Sender Email Address"}),e.jsx(xe,{value:o.sender_email,onChange:f=>c({...o,sender_email:f.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(te,{className:"text-xs",children:"Reply-To Email (optional)"}),e.jsx(xe,{value:o.reply_to_email,onChange:f=>c({...o,reply_to_email:f.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(cg,{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(Fts,{brokerageId:s,onVerifiedSelect:f=>{c(x=>({...x,sender_email:f})),re.success(`Sender set to ${f}`)}})]}),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(te,{className:"text-xs",children:"{{brokerage_name}}"}),e.jsx(xe,{value:o.merge_fields.brokerage_name||"",onChange:f=>p("brokerage_name",f.target.value),placeholder:(u==null?void 0:u.name)||"Brokerage Name"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{className:"text-xs",children:"{{city}}"}),e.jsx(xe,{value:o.merge_fields.city||"",onChange:f=>p("city",f.target.value),placeholder:"e.g. Austin"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{className:"text-xs",children:"{{sender_name}}"}),e.jsx(xe,{value:o.merge_fields.sender_name||"",onChange:f=>p("sender_name",f.target.value),placeholder:"e.g. Jeremy"})]})]})]}),e.jsxs(U,{onClick:()=>m.mutate(),disabled:m.isPending,className:"w-full",children:[e.jsx(Ho,{className:"h-4 w-4 mr-1"})," Save Settings"]})]})}const css=gS.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",Dm(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()}}}),zSt=[{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 zy({onClick:s,active:t,disabled:n,icon:r,tooltip:a}){return e.jsxs(Bg,{children:[e.jsx(Ug,{asChild:!0,children:e.jsx(U,{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(ng,{side:"bottom",className:"text-xs",children:a})]})}function GJn({content:s,onChange:t}){const n=wPe({extensions:[jPe.configure({heading:{levels:[1,2,3]}}),css,kPe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline cursor-pointer"}}),SPe.configure({types:["heading","paragraph"]}),MJe,iGt],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(wN,{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(zy,{onClick:()=>n.chain().focus().toggleBold().run(),active:n.isActive("bold"),icon:wA,tooltip:"Bold"}),e.jsx(zy,{onClick:()=>n.chain().focus().toggleItalic().run(),active:n.isActive("italic"),icon:kA,tooltip:"Italic"}),e.jsx(zy,{onClick:()=>n.chain().focus().toggleUnderline().run(),active:n.isActive("underline"),icon:UF,tooltip:"Underline"}),e.jsx(zy,{onClick:()=>n.chain().focus().toggleStrike().run(),active:n.isActive("strike"),icon:cQ,tooltip:"Strikethrough"}),e.jsx(hc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(zy,{onClick:()=>n.chain().focus().toggleHeading({level:1}).run(),active:n.isActive("heading",{level:1}),icon:QU,tooltip:"Heading 1"}),e.jsx(zy,{onClick:()=>n.chain().focus().toggleHeading({level:2}).run(),active:n.isActive("heading",{level:2}),icon:AF,tooltip:"Heading 2"}),e.jsx(zy,{onClick:()=>n.chain().focus().toggleHeading({level:3}).run(),active:n.isActive("heading",{level:3}),icon:JU,tooltip:"Heading 3"}),e.jsx(hc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(zy,{onClick:()=>n.chain().focus().toggleBulletList().run(),active:n.isActive("bulletList"),icon:m0,tooltip:"Bullet List"}),e.jsx(zy,{onClick:()=>n.chain().focus().toggleOrderedList().run(),active:n.isActive("orderedList"),icon:sj,tooltip:"Numbered List"}),e.jsx(zy,{onClick:()=>n.chain().focus().toggleBlockquote().run(),active:n.isActive("blockquote"),icon:tS,tooltip:"Blockquote"}),e.jsx(zy,{onClick:()=>n.chain().focus().setHorizontalRule().run(),icon:Z2,tooltip:"Divider"}),e.jsx(hc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(zy,{onClick:()=>n.chain().focus().setTextAlign("left").run(),active:n.isActive({textAlign:"left"}),icon:_M,tooltip:"Align Left"}),e.jsx(zy,{onClick:()=>n.chain().focus().setTextAlign("center").run(),active:n.isActive({textAlign:"center"}),icon:bM,tooltip:"Align Center"}),e.jsx(zy,{onClick:()=>n.chain().focus().setTextAlign("right").run(),active:n.isActive({textAlign:"right"}),icon:wM,tooltip:"Align Right"}),e.jsx(hc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(zy,{onClick:r,active:n.isActive("link"),icon:Rc,tooltip:"Insert Link"}),e.jsx(hc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(zy,{onClick:()=>n.chain().focus().undo().run(),disabled:!n.can().undo(),icon:RA,tooltip:"Undo"}),e.jsx(zy,{onClick:()=>n.chain().focus().redo().run(),disabled:!n.can().redo(),icon:LA,tooltip:"Redo"}),e.jsx("div",{className:"flex-1"}),e.jsx(U,{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(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsxs(U,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",children:[e.jsx(kq,{className:"h-3.5 w-3.5"}),"Merge Tags"]})}),e.jsx(Eu,{align:"end",className:"w-56",children:zSt.map(i=>e.jsxs(La,{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(_Pe,{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:"}),zSt.map(i=>e.jsx(Be,{variant:"secondary",className:"cursor-pointer hover:bg-secondary/80 font-mono text-[10px] px-2 py-0.5",onClick:()=>a(i.key),children:`{{${i.key}}}`},i.key))]})})]})}):null}function WJn({open:s,onClose:t,campaignName:n,stat:r}){return e.jsx(zs,{open:s,onOpenChange:a=>!a&&t(),children:e.jsxs(Ds,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(rc,{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($r,{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(Ice,{icon:ln,color:"text-blue-500",label:"Total Sent",value:r.sent.toLocaleString()}),e.jsx(Ice,{icon:xa,color:"text-amber-500",label:"Opens",value:`${r.opened.toLocaleString()}`,sub:`${r.openRate.toFixed(1)}% open rate`}),e.jsx(Ice,{icon:Ch,color:"text-green-500",label:"Clicks",value:`${r.clicked.toLocaleString()}`,sub:`${r.clickRate.toFixed(1)}% click rate`}),e.jsx(Ice,{icon:tc,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(Yr,{className:"h-3 w-3"})," Last sent: ",Gs(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(we,{className:"overflow-hidden",children:e.jsxs(Ie,{className:"py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"h-8 w-8 rounded-full bg-primary/10 text-primary font-bold text-xs flex items-center justify-center shrink-0",children:["#",a.email_number]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.title}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 mt-1",children:[e.jsxs(Be,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(ln,{className:"h-2.5 w-2.5"})," ",a.sent_count.toLocaleString()," sent"]}),e.jsxs(Be,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600",children:[e.jsx(xa,{className:"h-2.5 w-2.5"})," ",a.opened_count.toLocaleString()," (",i.toFixed(1),"%)"]}),e.jsxs(Be,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600",children:[e.jsx(Ch,{className:"h-2.5 w-2.5"})," ",a.clicked_count.toLocaleString()," (",l.toFixed(1),"%)"]}),a.failed_count>0&&e.jsxs(Be,{variant:"outline",className:"text-[10px] gap-1 border-destructive/30 text-destructive",children:[e.jsx(tc,{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 Ice({icon:s,color:t,label:n,value:r,sub:a}){return e.jsx(we,{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 dss(s){return ct({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 BSt={cold:{icon:$w,color:"text-blue-500",bg:"bg-blue-50 dark:bg-blue-950/30",label:"Cold — Curiosity"},warm:{icon:eN,color:"text-amber-500",bg:"bg-amber-50 dark:bg-amber-950/30",label:"Warm — Growth"},hot:{icon:Xd,color:"text-red-500",bg:"bg-red-50 dark:bg-red-950/30",label:"Hot — Private Invite"}};function uss({brokerageId:s}){var ge,ke,Te,Me;const{user:t}=vs(),n=Qt(),[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),[p,f]=j.useState("editor"),[x,y]=j.useState(null),[v,b]=j.useState(null),{data:N={}}=dss(s),[S,A]=j.useState({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""}),{data:T}=ct({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:Oe,error:Se}=await q.from("brokerages").select("name, city, state").eq("id",s).single();if(Se)throw Se;return Oe}}),{data:L}=ct({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:Oe,error:Se}=await q.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(Se)throw Se;return Oe}}),M={first_name:"Sarah",brokerage_name:((ge=L==null?void 0:L.merge_fields)==null?void 0:ge.brokerage_name)||(T==null?void 0:T.name)||"Your Brokerage",city:((ke=L==null?void 0:L.merge_fields)==null?void 0:ke.city)||(T==null?void 0:T.city)||"Your City",sender_name:((Te=L==null?void 0:L.merge_fields)==null?void 0:Te.sender_name)||(L==null?void 0:L.sender_name)||"Your Name"},I=Oe=>Oe.replace(/\{\{first_name\}\}/g,M.first_name).replace(/\{\{brokerage_name\}\}/g,M.brokerage_name).replace(/\{\{city\}\}/g,M.city).replace(/\{\{sender_name\}\}/g,M.sender_name),{data:R=[],isLoading:z}=ct({queryKey:["recruit-campaigns",s],queryFn:async()=>{const{data:Oe,error:Se}=await q.from("recruit_campaigns").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(Se)throw Se;return Oe}}),{data:$={}}=ct({queryKey:["recruit-campaign-emails",s],enabled:R.length>0,queryFn:async()=>{const Oe=R.map(Fe=>Fe.id),{data:Se,error:Qe}=await q.from("recruit_campaign_emails").select("*").in("campaign_id",Oe).order("email_number");if(Qe)throw Qe;const Ae={};return Se.forEach(Fe=>{Ae[Fe.campaign_id]||(Ae[Fe.campaign_id]=[]),Ae[Fe.campaign_id].push(Fe)}),Ae}}),H=Object.values($).flat().map(Oe=>Oe.id),{data:V=[]}=ct({queryKey:["recruit-subject-overrides",s],enabled:H.length>0,queryFn:async()=>{const{data:Oe,error:Se}=await q.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(Se)throw Se;return Oe}}),K={};V.forEach(Oe=>{K[Oe.campaign_email_id]=Oe.selected_subject_index});const Z=yt({mutationFn:async({campaignEmailId:Oe,selectedIndex:Se})=>{const{error:Qe}=await q.from("recruit_brokerage_subject_overrides").upsert({brokerage_id:s,campaign_email_id:Oe,selected_subject_index:Se,updated_at:new Date().toISOString()},{onConflict:"brokerage_id,campaign_email_id"});if(Qe)throw Qe},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-subject-overrides",s]}),re.success("Subject line updated for your brokerage")},onError:Oe=>re.error(Oe.message)}),Q=yt({mutationFn:async Oe=>{const{error:Se}=await q.from("recruit_campaign_emails").update({title:Oe.title,subject_line:Oe.subject_line,subject_line_options:Oe.subject_line_options,body_html:Oe.body_html,body_text:Oe.body_text,delay_days:Oe.delay_days,updated_at:new Date().toISOString()}).eq("id",Oe.id);if(Se)throw Se},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),re.success("Email template saved!"),l(null)},onError:Oe=>re.error(Oe.message)}),le=yt({mutationFn:async()=>{const Oe=S.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""),{data:Se,error:Qe}=await q.from("recruit_campaigns").insert({name:S.name,slug:Oe,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:R.length+1}).select().single();if(Qe)throw Qe;const Ae=[{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:Fe}=await q.from("recruit_campaign_emails").insert(Ae.map(Ne=>({campaign_id:Se.id,...Ne,body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",subject_line_options:[],is_active:!0})));if(Fe)throw Fe;return Se},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:Oe=>re.error(Oe.message)}),ue=yt({mutationFn:async Oe=>{const{error:Se}=await q.from("recruit_campaigns").update({name:Oe.name,description:Oe.description,theme:Oe.theme,goal:Oe.goal,primary_cta:Oe.primary_cta,warmth_level:Oe.warmth_level,sender_name:Oe.sender_name,sender_email:Oe.sender_email,reply_to_email:Oe.reply_to_email,updated_at:new Date().toISOString()}).eq("id",Oe.id);if(Se)throw Se},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),re.success("Campaign settings saved!"),y(null)},onError:Oe=>re.error(Oe.message)}),se=yt({mutationFn:async Oe=>{var $e,Ve;const{data:Se}=await q.from("recruit_campaign_emails").select("email_number, delay_days").eq("campaign_id",Oe).order("email_number",{ascending:!1}).limit(1),Qe=(($e=Se==null?void 0:Se[0])==null?void 0:$e.email_number)??0,Ae=((Ve=Se==null?void 0:Se[0])==null?void 0:Ve.delay_days)??0,Fe=Qe+1,{error:Ne}=await q.from("recruit_campaign_emails").insert({campaign_id:Oe,email_number:Fe,title:`Email ${Fe}`,subject_line:"Hey {{first_name}}",subject_line_options:[],body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",delay_days:Ae+7,is_active:!0});if(Ne)throw Ne},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),re.success("Email added to campaign!")},onError:Oe=>re.error(Oe.message)}),ne=yt({mutationFn:async Oe=>{const{error:Se}=await q.from("recruit_campaigns").delete().eq("id",Oe);if(Se)throw Se},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),re.success("Campaign deleted")},onError:Oe=>re.error(Oe.message)}),ie=yt({mutationFn:async Oe=>{const{error:Se}=await q.from("recruit_campaign_emails").delete().eq("id",Oe);if(Se)throw Se},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),re.success("Email removed from campaign")},onError:Oe=>re.error(Oe.message)}),ce=yt({mutationFn:async({emailId:Oe,delay_days:Se})=>{const{error:Qe}=await q.from("recruit_campaign_emails").update({delay_days:Se,updated_at:new Date().toISOString()}).eq("id",Oe);if(Qe)throw Qe},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),re.success("Send delay updated")},onError:Oe=>re.error(Oe.message)});if(z)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 je=R.filter(Oe=>!Oe.brokerage_id),be=R.filter(Oe=>Oe.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(U,{variant:"outline",size:"sm",onClick:()=>u(!0),className:"gap-1.5",children:[e.jsx(qc,{className:"h-4 w-4"})," Default Settings"]}),e.jsxs(U,{size:"sm",onClick:()=>m(!0),className:"gap-1.5",children:[e.jsx(an,{className:"h-4 w-4"})," New Campaign"]})]})]}),e.jsx(we,{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(cn,{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(qc,{className:"inline h-3.5 w-3.5"})," icon on any campaign to customize."]})]})]})})}),be.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(WX,{className:"h-4 w-4"})," Your Custom Campaigns"]}),e.jsx("div",{className:"space-y-3",children:be.map(Oe=>he(Oe,!0))})]}),je.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(cn,{className:"h-4 w-4"})," System Campaigns"]}),e.jsx("div",{className:"space-y-3",children:je.map(Oe=>he(Oe,!1))})]}),R.length===0&&e.jsx(we,{children:e.jsxs(Ie,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(ln,{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(U,{className:"mt-4",onClick:()=>m(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})}),e.jsx(WJn,{open:!!v,onClose:()=>b(null),campaignName:(v==null?void 0:v.name)||"",stat:v&&N[v.id]||null}),o&&e.jsx(lss,{email:o,mergeValues:M,selectedSubjectIndex:K[o.id],onClose:()=>c(null)}),e.jsx(zs,{open:!!i,onOpenChange:Oe=>!Oe&&l(null),children:e.jsxs(Ds,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(Vs,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(CM,{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(te,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Title"}),e.jsx(xe,{value:i.title,onChange:Oe=>l({...i,title:Oe.target.value}),className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Delay (days after previous)"}),e.jsx(xe,{type:"number",min:0,max:90,value:i.delay_days,onChange:Oe=>l({...i,delay_days:parseInt(Oe.target.value)||7}),className:"h-9"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Subject Line"}),e.jsx(xe,{value:i.subject_line,onChange:Oe=>l({...i,subject_line:Oe.target.value}),placeholder:"e.g. Hey {{first_name}}, quick question...",className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(te,{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(Fs,{value:((Me=i.subject_line_options)==null?void 0:Me.join(` `))||"",onChange:Oe=>l({...i,subject_line_options:Oe.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(te,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Body"}),e.jsx(oa,{value:p,onValueChange:Oe=>f(Oe),children:e.jsxs(la,{className:"h-7",children:[e.jsx(Kt,{value:"editor",className:"text-xs px-3 h-6",children:"Editor"}),e.jsx(Kt,{value:"preview",className:"text-xs px-3 h-6",children:"Preview"})]})})]}),p==="editor"?e.jsx(GJn,{content:i.body_html,onChange:Oe=>l({...i,body_html:Oe})}):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:[M.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:[M.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:I(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:I(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(U,{variant:"outline",size:"sm",onClick:()=>l(null),children:"Cancel"}),e.jsxs(U,{size:"sm",onClick:()=>Q.mutate(i),disabled:Q.isPending,className:"gap-1.5",children:[e.jsx(Ho,{className:"h-3.5 w-3.5"})," Save Changes"]})]})]})]})]})}),e.jsx(zs,{open:h,onOpenChange:m,children:e.jsxs(Ds,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(an,{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(te,{className:"text-xs font-medium",children:"Campaign Name *"}),e.jsx(xe,{value:S.name,onChange:Oe=>A({...S,name:Oe.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(te,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(Ns,{value:S.warmth_level,onValueChange:Oe=>A({...S,warmth_level:Oe}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"cold",children:"❄️ Cold — Curiosity"}),e.jsx(et,{value:"warm",children:"☀️ Warm — Growth"}),e.jsx(et,{value:"hot",children:"🔥 Hot — Private Invite"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs font-medium",children:"Primary CTA"}),e.jsx(xe,{value:S.primary_cta,onChange:Oe=>A({...S,primary_cta:Oe.target.value}),placeholder:"Learn more"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs font-medium",children:"Description"}),e.jsx(Fs,{value:S.description,onChange:Oe=>A({...S,description:Oe.target.value}),placeholder:"What is this campaign about?",rows:2})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs font-medium",children:"Goal"}),e.jsx(xe,{value:S.goal,onChange:Oe=>A({...S,goal:Oe.target.value}),placeholder:"e.g. Convert warm leads to meetings"})]}),e.jsxs(ub,{children:[e.jsx(hb,{asChild:!0,children:e.jsxs(U,{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(ln,{className:"h-3.5 w-3.5"})," Email Settings Override"]}),e.jsx(rl,{className:"h-3.5 w-3.5"})]})}),e.jsxs(mb,{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(te,{className:"text-xs",children:"Sender Name"}),e.jsx(xe,{value:S.sender_name,onChange:Oe=>A({...S,sender_name:Oe.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Sender Email"}),e.jsx(xe,{value:S.sender_email,onChange:Oe=>A({...S,sender_email:Oe.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(te,{className:"text-xs",children:"Reply-To Email"}),e.jsx(xe,{value:S.reply_to_email,onChange:Oe=>A({...S,reply_to_email:Oe.target.value}),placeholder:"e.g. jeremy@mybrokerage.com"})]})]})]}),e.jsxs(U,{className:"w-full",disabled:!S.name.trim()||le.isPending,onClick:()=>le.mutate(),children:[e.jsx(an,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})]})}),e.jsx(zs,{open:!!x,onOpenChange:Oe=>!Oe&&y(null),children:e.jsxs(Ds,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(qc,{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(te,{className:"text-xs font-medium",children:"Campaign Name"}),e.jsx(xe,{value:x.name,onChange:Oe=>y({...x,name:Oe.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(Ns,{value:x.warmth_level,onValueChange:Oe=>y({...x,warmth_level:Oe}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"cold",children:"❄️ Cold"}),e.jsx(et,{value:"warm",children:"☀️ Warm"}),e.jsx(et,{value:"hot",children:"🔥 Hot"})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs font-medium",children:"Goal"}),e.jsx(xe,{value:x.goal||"",onChange:Oe=>y({...x,goal:Oe.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(ln,{className:"h-4 w-4 text-primary"})," Email Sender Override"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Sender Name"}),e.jsx(xe,{value:x.sender_name||"",onChange:Oe=>y({...x,sender_name:Oe.target.value}),placeholder:"Uses brokerage default"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Sender Email"}),e.jsx(xe,{value:x.sender_email||"",onChange:Oe=>y({...x,sender_email:Oe.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(te,{className:"text-xs",children:"Reply-To Email"}),e.jsx(xe,{value:x.reply_to_email||"",onChange:Oe=>y({...x,reply_to_email:Oe.target.value}),placeholder:"Uses brokerage default"})]})]}),e.jsxs(U,{className:"w-full",onClick:()=>ue.mutate(x),disabled:ue.isPending,children:[e.jsx(Ho,{className:"h-4 w-4 mr-1"})," Save Campaign Settings"]})]})]})}),e.jsx(zs,{open:d,onOpenChange:u,children:e.jsxs(Ds,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Default Recruiting Email Settings"}),e.jsx(Pr,{children:"These defaults apply to campaigns without their own overrides."})]}),e.jsx(jrt,{brokerageId:s})]})})]});function he(Oe,Se){const Qe=BSt[Oe.warmth_level]||BSt.cold,Ae=Qe.icon,Fe=$[Oe.id]||[],Ne=r===Oe.id,$e=!!(Oe.sender_name||Oe.sender_email||Oe.reply_to_email),Ve=N[Oe.id];return e.jsxs(we,{className:"overflow-hidden transition-shadow hover:shadow-md",children:[e.jsx(Tt,{className:"cursor-pointer hover:bg-muted/40 transition-colors py-4",onClick:()=>a(Ne?null:Oe.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 ${Qe.bg} flex items-center justify-center`,children:e.jsx(Ae,{className:`h-5 w-5 ${Qe.color}`})}),e.jsxs("div",{children:[e.jsxs(It,{className:"text-base flex items-center gap-2",children:[Oe.name,e.jsx(Be,{variant:Oe.is_active?"default":"secondary",className:"text-[10px] px-1.5",children:Oe.is_active?"Active":"Draft"}),Se&&e.jsx(Be,{variant:"outline",className:"text-[10px] px-1.5",children:"Custom"}),$e&&e.jsxs(Be,{variant:"outline",className:"text-[10px] px-1.5 border-primary/30 text-primary",children:[e.jsx(ln,{className:"h-2.5 w-2.5 mr-0.5"})," Custom Sender"]})]}),e.jsx(Jn,{className:"text-xs mt-0.5",children:Oe.theme||Oe.description})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(U,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:qe=>{qe.stopPropagation(),y({...Oe})},children:e.jsx(qc,{className:"h-4 w-4 text-muted-foreground"})}),Se&&e.jsx(U,{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 Yi("Delete this campaign and all its emails? This cannot be undone.")&&ne.mutate(Oe.id)},children:e.jsx(In,{className:"h-4 w-4"})}),Ve&&Ve.sent>0&&e.jsxs("div",{className:"hidden md:flex items-center gap-1.5",children:[e.jsxs(Be,{variant:"outline",className:"text-[10px] gap-1 font-medium",title:"Total emails sent",children:[e.jsx(ln,{className:"h-2.5 w-2.5"})," ",Ve.sent.toLocaleString()]}),e.jsxs(Be,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600 font-medium",title:`${Ve.openRate.toFixed(1)}% open rate`,children:[e.jsx(xa,{className:"h-2.5 w-2.5"})," ",Ve.opened.toLocaleString()," (",Ve.openRate.toFixed(0),"%)"]}),e.jsxs(Be,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600 font-medium",title:`${Ve.clickRate.toFixed(1)}% click rate`,children:[e.jsx(Ch,{className:"h-2.5 w-2.5"})," ",Ve.clicked.toLocaleString()," (",Ve.clickRate.toFixed(1),"%)"]})]}),e.jsxs(U,{variant:"outline",size:"sm",className:"h-7 px-2 gap-1 text-xs",onClick:qe=>{qe.stopPropagation(),b(Oe)},title:"View detailed engagement stats",children:[e.jsx(Cl,{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(ln,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[Fe.length," emails"]})]}),e.jsx("div",{className:"h-7 w-7 rounded-md flex items-center justify-center",children:Ne?e.jsx(dv,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(rl,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),Ne&&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:Oe.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:Oe.primary_cta||"—"})]})]}),$e&&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(ln,{className:"h-3 w-3"})," Campaign Sender Override"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs text-muted-foreground",children:[Oe.sender_name&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Name:"})," ",Oe.sender_name]}),Oe.sender_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Email:"})," ",Oe.sender_email]}),Oe.reply_to_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Reply-To:"})," ",Oe.reply_to_email]})]})]}),e.jsx("div",{className:"relative",children:Fe.map((qe,Ze)=>{var Ue,Ye;return e.jsxs("div",{className:"relative flex gap-4 pb-4 last:pb-0",children:[ZeGe.stopPropagation(),onBlur:Ge=>{const He=parseInt(Ge.target.value)||0;He!==qe.delay_days&&ce.mutate({emailId:qe.id,delay_days:He})},onKeyDown:Ge=>{Ge.key==="Enter"&&Ge.target.blur()}}),"days"]})]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yr,{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: ",I(((Ue=qe.subject_line_options)==null?void 0:Ue.length)>0&&qe.subject_line_options[K[qe.id]??0]||qe.subject_line)]})]}),((Ye=qe.subject_line_options)==null?void 0:Ye.length)>1&&e.jsx("div",{className:"mt-2",children:e.jsxs(Ns,{value:String(K[qe.id]??0),onValueChange:Ge=>Z.mutate({campaignEmailId:qe.id,selectedIndex:parseInt(Ge)}),children:[e.jsx(ws,{className:"h-7 text-xs w-full max-w-sm",children:e.jsx(ks,{placeholder:"Choose subject line"})}),e.jsx(js,{children:qe.subject_line_options.map((Ge,He)=>e.jsxs(et,{value:String(He),className:"text-xs",children:[e.jsxs("span",{className:"font-medium mr-1.5",children:[He===0?"Primary":`Alt ${He}`,":"]}),I(Ge)]},He))})]})})]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:[e.jsx(U,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(qe),children:e.jsx(xa,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{l({...qe}),f("editor")},children:e.jsx(ri,{className:"h-4 w-4"})}),Se&&Fe.length>1&&e.jsx(U,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:async()=>{await Yi("Delete this email from the sequence?")&&ie.mutate(qe.id)},children:e.jsx(In,{className:"h-4 w-4"})})]})]})})]},qe.id)})}),Se&&e.jsxs(U,{variant:"outline",size:"sm",className:"w-full gap-1.5",onClick:()=>se.mutate(Oe.id),disabled:se.isPending,children:[e.jsx(an,{className:"h-3.5 w-3.5"})," Add Email to Sequence"]})]})]},Oe.id)}}const USt={active:{icon:lu,color:"bg-green-500/10 text-green-600",label:"Active"},paused:{icon:uv,color:"bg-amber-500/10 text-amber-600",label:"Paused"},completed:{icon:Yo,color:"bg-blue-500/10 text-blue-600",label:"Completed"},cancelled:{icon:ou,color:"bg-red-500/10 text-red-600",label:"Cancelled"}},qSt={sent:{icon:ln,color:"text-blue-500"},opened:{icon:xa,color:"text-amber-500"},clicked:{icon:Ch,color:"text-green-500"},failed:{icon:tc,color:"text-destructive"}};function hss({brokerageId:s}){var Me,Oe,Se,Qe,Ae;const{user:t}=vs(),n=Qt(),[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),[p,f]=j.useState(""),[x,y]=j.useState("all"),[v,b]=j.useState("all"),[N,S]=j.useState(!1),{data:A}=dre(),{data:T={}}=ct({queryKey:["recruit-campaign-emails-for-preview",s],queryFn:async()=>{const{data:Fe,error:Ne}=await q.from("recruit_campaign_emails").select("*").order("email_number");if(Ne)throw Ne;const $e={};return(Fe??[]).forEach(Ve=>{$e[Ve.campaign_id]||($e[Ve.campaign_id]=[]),$e[Ve.campaign_id].push(Ve)}),$e}}),{data:L}=ct({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:Fe,error:Ne}=await q.from("brokerages").select("name, city, state").eq("id",s).single();if(Ne)throw Ne;return Fe}}),{data:M}=ct({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:Fe,error:Ne}=await q.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(Ne)throw Ne;return Fe}}),{data:I=[]}=ct({queryKey:["recruit-subject-overrides",s],queryFn:async()=>{const{data:Fe,error:Ne}=await q.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(Ne)throw Ne;return Fe}}),R={};I.forEach(Fe=>{R[Fe.campaign_email_id]=Fe.selected_subject_index});const z={first_name:((Me=h==null?void 0:h.prospect)==null?void 0:Me.first_name)||"Sarah",brokerage_name:((Oe=M==null?void 0:M.merge_fields)==null?void 0:Oe.brokerage_name)||(L==null?void 0:L.name)||"Your Brokerage",city:((Se=M==null?void 0:M.merge_fields)==null?void 0:Se.city)||(L==null?void 0:L.city)||"Your City",sender_name:((Qe=M==null?void 0:M.merge_fields)==null?void 0:Qe.sender_name)||(M==null?void 0:M.sender_name)||"Your Name"},$=Fe=>{const Ne=T[Fe.campaign_id]||[],$e=Fe.current_email_number+1;return Ne.find(Ve=>Ve.email_number===$e)||null},{data:H=[],isLoading:V}=ct({queryKey:["recruit-campaign-assignments",s],queryFn:async()=>{let Ne=[],$e=0;for(;;){const{data:Ve,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($e,$e+1e3-1);if(qe)throw qe;if(Ne=Ne.concat(Ve??[]),!Ve||Ve.length<1e3)break;$e+=1e3}return Ne}}),{data:K=[]}=ct({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{const{data:Fe,error:Ne}=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(Ne)throw Ne;return Fe}}),{data:Z=[]}=ct({queryKey:["recruit-campaigns"],queryFn:async()=>{const{data:Fe,error:Ne}=await q.from("recruit_campaigns").select("id, name, warmth_level").eq("is_active",!0).order("sort_order");if(Ne)throw Ne;return Fe}}),{data:Q=[]}=ct({queryKey:["recruit-prospects-for-assign",s],queryFn:async()=>{let Ne=[],$e=0;for(;;){const{data:Ve,error:qe}=await q.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s).order("first_name").range($e,$e+1e3-1);if(qe)throw qe;if(Ne=Ne.concat(Ve??[]),!Ve||Ve.length<1e3)break;$e+=1e3}return Ne}}),le=new Set(H.map(Fe=>`${Fe.prospect_id}-${Fe.campaign_id}`)),ue=yt({mutationFn:async()=>{if(!i||o.size===0)throw new Error("Select a campaign and at least one prospect");const Fe=new Date,Ne=Array.from(o).filter(Ve=>!le.has(`${Ve}-${i}`)).map(Ve=>({prospect_id:Ve,campaign_id:i,brokerage_id:s,assigned_by:t.id,status:"active",current_email_number:0,next_send_at:Fe.toISOString(),started_at:Fe.toISOString()}));if(Ne.length===0)throw new Error("All selected prospects are already assigned to this campaign");const{error:$e}=await q.from("recruit_campaign_assignments").insert(Ne);if($e)throw $e},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),re.success(`Campaign assigned to ${o.size} prospect(s)!`),a(!1),l(""),c(new Set)},onError:Fe=>re.error(Fe.message)}),se=yt({mutationFn:async({id:Fe,newStatus:Ne})=>{const{error:$e}=await q.from("recruit_campaign_assignments").update({status:Ne,updated_at:new Date().toISOString()}).eq("id",Fe);if($e)throw $e},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),re.success("Assignment updated")}}),ne=yt({mutationFn:async()=>{const{data:Fe,error:Ne}=await q.functions.invoke("ses-recruit-drip",{body:{action:"process_drips"}});if(Ne)throw Ne;return Fe},onSuccess:Fe=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),n.invalidateQueries({queryKey:["recruit-campaign-sends",s]}),re.success(`Wave sent! ${Fe.sent} emails delivered, ${Fe.skipped} skipped, ${Fe.failed} failed`)},onError:Fe=>re.error(`Send failed: ${Fe.message}`)}),ie=H.filter(Fe=>Fe.status==="active").length;H.filter(Fe=>Fe.status==="completed").length;const ce=H.filter(Fe=>Fe.status==="active"&&Fe.next_send_at&&new Date(Fe.next_send_at)<=new Date).length,{data:je={}}=dss(s),be=H.reduce((Fe,Ne)=>Fe+Math.max(0,Ne.current_email_number||0),0),he=Object.values(je).reduce((Fe,Ne)=>Fe+Ne.opened,0),ge=Object.values(je).reduce((Fe,Ne)=>Fe+Ne.clicked,0);Object.values(je).reduce((Fe,Ne)=>Fe+Ne.failed,0);const ke=be>0?Math.round(he/be*100):0,Te=be>0?ge/be*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(U,{variant:"outline",onClick:()=>{ne.mutate()},disabled:ne.isPending,className:"border-amber-500/50 text-amber-600 hover:bg-amber-500/10",children:[e.jsx(Af,{className:"h-4 w-4 mr-1"}),ne.isPending?"Sending...":`Send Next Wave (${ce})`]}),e.jsxs(U,{onClick:()=>a(!0),children:[e.jsx($r,{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(we,{children:e.jsxs(Ie,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Bn,{className:"h-7 w-7 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:H.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Assigned"})]})]})}),e.jsx(we,{children:e.jsxs(Ie,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(lu,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:ie}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active"})]})]})}),e.jsx(we,{children:e.jsxs(Ie,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(ln,{className:"h-7 w-7 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:be.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Emails Sent"})]})]})}),e.jsx(we,{children:e.jsxs(Ie,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(xa,{className:"h-7 w-7 text-amber-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[ke,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Open Rate (",he.toLocaleString(),")"]})]})]})}),e.jsx(we,{children:e.jsxs(Ie,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Ch,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Te.toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Click Rate (",ge.toLocaleString(),")"]})]})]})})]}),e.jsxs(oa,{value:d,onValueChange:u,children:[e.jsxs(la,{children:[e.jsxs(Kt,{value:"assignments",children:["Active Drips (",ie,")"]}),e.jsxs(Kt,{value:"history",children:["Send History (",be.toLocaleString(),")"]})]}),e.jsx(Zt,{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"})}):H.length===0?e.jsx(we,{children:e.jsxs(Ie,{className:"py-12 text-center text-muted-foreground",children:[e.jsx($r,{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:H.map(Fe=>{var Ue,Ye,Ge,He;const Ne=USt[Fe.status]||USt.active,$e=Ne.icon,qe=(T[Fe.campaign_id]||[]).length||4,Ze=$(Fe);return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Be,{className:`text-xs ${Ne.color} border-0`,children:[e.jsx($e,{className:"h-3 w-3 mr-1"}),Ne.label]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(Ue=Fe.prospect)==null?void 0:Ue.first_name," ",(Ye=Fe.prospect)==null?void 0:Ye.last_name,e.jsx("span",{className:"text-muted-foreground font-normal ml-2",children:(Ge=Fe.prospect)==null?void 0:Ge.email})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(He=Fe.campaign)==null?void 0:He.name," · Email ",Fe.current_email_number,"/",qe,Fe.next_send_at&&Fe.status==="active"&&e.jsxs(e.Fragment,{children:[" ","· ",e.jsx(Yr,{className:"h-3 w-3 inline"})," Next: ",Gs(new Date(Fe.next_send_at),"MMM d, h:mm a"),new Date(Fe.next_send_at)<=new Date&&e.jsx(Be,{variant:"outline",className:"ml-1 text-[10px] px-1 py-0 border-amber-500 text-amber-600",children:"DUE"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[Ze&&e.jsx(U,{variant:"ghost",size:"sm",title:"Preview next email",onClick:()=>m(Fe),children:e.jsx(xa,{className:"h-3.5 w-3.5"})}),Fe.status==="active"&&e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>se.mutate({id:Fe.id,newStatus:"paused"}),children:e.jsx(uv,{className:"h-3.5 w-3.5"})}),Fe.status==="paused"&&e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>se.mutate({id:Fe.id,newStatus:"active"}),children:e.jsx(lu,{className:"h-3.5 w-3.5"})}),(Fe.status==="active"||Fe.status==="paused")&&e.jsx(U,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>se.mutate({id:Fe.id,newStatus:"cancelled"}),children:e.jsx(ou,{className:"h-3.5 w-3.5"})})]})]},Fe.id)})})}),e.jsxs(Zt,{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(Ns,{value:x,onValueChange:y,children:[e.jsx(ws,{className:"w-[220px] h-8 text-xs",children:e.jsx(ks,{placeholder:"All campaigns"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All campaigns"}),Z.map(Fe=>e.jsx(et,{value:Fe.id,children:Fe.name},Fe.id))]})]}),e.jsxs(Ns,{value:v,onValueChange:b,children:[e.jsx(ws,{className:"w-[160px] h-8 text-xs",children:e.jsx(ks,{placeholder:"All statuses"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All statuses"}),e.jsx(et,{value:"sent",children:"Sent (no engagement)"}),e.jsx(et,{value:"opened",children:"Opened"}),e.jsx(et,{value:"clicked",children:"Clicked"})]})]}),(x!=="all"||v!=="all")&&e.jsx(U,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>{y("all"),b("all")},children:"Clear"})]}),(()=>{var Ne;const Fe=K.filter($e=>{var Ve;return!(x!=="all"&&((Ve=$e.campaign_email)==null?void 0:Ve.campaign_id)!==x||v==="opened"&&!$e.opened_at||v==="clicked"&&!$e.clicked_at||v==="sent"&&($e.opened_at||$e.clicked_at))});return Fe.length===0?e.jsx(we,{children:e.jsxs(Ie,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(ln,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:K.length===0?"No emails sent yet":"No emails match these filters"}),e.jsx("p",{className:"text-sm",children:K.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 ",Fe.length," of ",K.length," recent sends",x!=="all"&&` · ${(Ne=Z.find($e=>$e.id===x))==null?void 0:Ne.name}`]}),e.jsx("div",{className:"space-y-1",children:Fe.map($e=>{var Ue,Ye,Ge;const Ve=qSt[$e.status]||qSt.sent,qe=Ve.icon,Ze=(Ue=Z.find(He=>{var tt;return He.id===((tt=$e.campaign_email)==null?void 0:tt.campaign_id)}))==null?void 0:Ue.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 ${Ve.color}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(Ye=$e.prospect)==null?void 0:Ye.first_name," ",(Ge=$e.prospect)==null?void 0:Ge.last_name,e.jsxs("span",{className:"text-muted-foreground font-normal ml-2",children:["Email #",$e.email_number]}),Ze&&e.jsx(Be,{variant:"outline",className:"ml-2 text-[10px] px-1.5 py-0 font-normal",children:Ze})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:$e.subject})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-shrink-0",children:[$e.opened_at&&e.jsxs("span",{className:"flex items-center gap-1 text-amber-500",children:[e.jsx(xa,{className:"h-3 w-3"})," ",Gs(new Date($e.opened_at),"MMM d")]}),$e.clicked_at&&e.jsxs("span",{className:"flex items-center gap-1 text-green-500",children:[e.jsx(Ch,{className:"h-3 w-3"})," ",Gs(new Date($e.clicked_at),"MMM d")]}),e.jsx("span",{children:Gs(new Date($e.sent_at),"MMM d, h:mm a")})]})]},$e.id)})})]})})()]})]}),e.jsx(zs,{open:r,onOpenChange:Fe=>{a(Fe),Fe||(f(""),c(new Set),l(""))},children:e.jsxs(Ds,{className:"max-w-lg max-h-[85vh] flex flex-col p-0",children:[e.jsxs(Vs,{className:"px-6 pt-6 pb-4",children:[e.jsx($s,{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(te,{className:"text-sm font-medium",children:"1. Select Campaign"}),e.jsxs(Ns,{value:i,onValueChange:l,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Choose a campaign..."})}),e.jsx(js,{children:Z.map(Fe=>e.jsx(et,{value:Fe.id,children:Fe.name},Fe.id))})]})]}),i&&(()=>{const Fe=p.toLowerCase(),Ne=Q.filter(qe=>`${qe.first_name} ${qe.last_name}`.toLowerCase().includes(Fe)||qe.email.toLowerCase().includes(Fe)),$e=Ne.filter(qe=>!le.has(`${qe.id}-${i}`)),Ve=$e.length>0&&$e.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(te,{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(Fr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name or email...",value:p,onChange:qe=>f(qe.target.value),className:"pl-9 h-9"})]}),e.jsxs(U,{variant:"outline",size:"sm",className:"h-9 whitespace-nowrap",onClick:()=>{if(Ve){const qe=new Set(o);$e.forEach(Ze=>qe.delete(Ze.id)),c(qe)}else{const qe=new Set(o);$e.forEach(Ze=>qe.add(Ze.id)),c(qe)}},children:[e.jsx(jF,{className:"h-3.5 w-3.5 mr-1"}),Ve?"Deselect All":`Select All (${$e.length})`]})]}),e.jsx("div",{className:"border rounded-lg max-h-60 overflow-y-auto divide-y",children:Ne.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:p?"No prospects match your search":"No prospects found for this brokerage"}):Ne.map(qe=>{const Ze=le.has(`${qe.id}-${i}`);return e.jsxs("label",{className:`flex items-center gap-3 p-2.5 hover:bg-muted/50 cursor-pointer ${Ze?"opacity-40":""}`,children:[e.jsx(xi,{checked:o.has(qe.id),disabled:Ze,onCheckedChange:Ue=>{const Ye=new Set(o);Ue?Ye.add(qe.id):Ye.delete(qe.id),c(Ye)}}),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})]}),Ze&&e.jsx(Be,{variant:"outline",className:"text-[10px] shrink-0",children:"Already assigned"})]},qe.id)})}),Ne.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Showing ",Ne.length," of ",Q.length," prospects",$e.length0&&e.jsx(we,{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:(Ae=Z.find(Fe=>Fe.id===i))==null?void 0:Ae.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(Mr,{className:"px-6 py-4 border-t",children:[e.jsx(U,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(U,{onClick:()=>{ue.mutate()},disabled:ue.isPending||!i||o.size===0,children:[e.jsx($r,{className:"h-4 w-4 mr-1"}),ue.isPending?"Assigning...":`Assign & Start (${o.size})`]})]})]})}),h&&(()=>{const Fe=$(h);return Fe?e.jsx(lss,{email:Fe,mergeValues:z,selectedSubjectIndex:R[Fe.id],onClose:()=>m(null)}):null})(),e.jsx(nPe,{open:N,onOpenChange:S,hasPending:A==null?void 0:A.hasPendingSes,pendingEmails:A==null?void 0:A.pendingEmails})]})}function mss({brokerageId:s}){const t=Qt(),[n,r]=j.useState([]),[a,i]=j.useState([]),[l,o]=j.useState(!1),c=j.useRef(!1),{data:d,isLoading:u}=ct({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=yt({mutationFn:async()=>{for(const b of a){const{error:N}=await q.from("recruit_pipeline_stages").delete().eq("id",b);if(N)throw N}const y=n.filter(b=>b.id&&!b.isNew),v=n.filter(b=>!b.id||b.isNew);for(const b of y){const{error:N}=await q.from("recruit_pipeline_stages").update({name:b.name,color:b.color,sort_order:b.sort_order}).eq("id",b.id);if(N)throw N}if(v.length>0){const{error:b}=await q.from("recruit_pipeline_stages").insert(v.map(N=>({brokerage_id:s,name:N.name,color:N.color,sort_order:N.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(N=>N.map((S,A)=>A===y?{...S,[v]:b}:S)),o(!0)},p=()=>{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)},f=y=>{const v=n[y];v.id&&!v.isNew&&i(b=>[...b,v.id]),r(b=>b.filter((N,S)=>S!==y)),o(!0)},x=(y,v)=>{const b=y+v;if(b<0||b>=n.length)return;const N=[...n];[N[y],N[b]]=[N[b],N[y]],N.forEach((S,A)=>S.sort_order=A+1),r(N),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(kf,{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(xe,{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(U,{variant:"ghost",size:"icon",onClick:()=>f(v),className:"text-destructive hover:text-destructive shrink-0 h-8 w-8",children:e.jsx(In,{className:"h-4 w-4"})})]},y.id||`new-${v}`))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(U,{variant:"outline",size:"sm",onClick:p,className:"gap-1",children:[e.jsx(an,{className:"h-4 w-4"})," Add Stage"]}),l&&e.jsxs(U,{size:"sm",onClick:()=>h.mutate(),disabled:h.isPending,className:"gap-1",children:[e.jsx(Ho,{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 KJn({brokerageId:s}){const{data:t=[],isLoading:n}=ct({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(DF,{className:"h-5 w-5 text-muted-foreground"}),"Unsubscribed Prospects"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Prospects who opted out of recruiting emails. They will not receive further outreach."})]}),e.jsxs(Be,{variant:"secondary",className:"text-base px-3 py-1",children:[t.length," total"]})]}),t.length===0?e.jsx(we,{children:e.jsxs(Ie,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(DF,{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(we,{className:"hover:shadow-sm transition-shadow",children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(It,{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(ln,{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(pa,{className:"h-3 w-3"}),r.unsubscribed_at&&Gs(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 YJn(){var o;const[s,t]=j.useState(""),[n,r]=j.useState("board"),{data:a=[],isLoading:i}=ct({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(qs,{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(qs,{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(Ns,{value:l,onValueChange:t,children:[e.jsxs(ws,{className:"w-[280px]",children:[e.jsx(_i,{className:"mr-2 h-4 w-4"}),e.jsx(ks,{placeholder:"Select brokerage"})]}),e.jsx(js,{children:a.map(c=>e.jsx(et,{value:c.id,children:c.name},c.id))})]})]}):e.jsx("div",{}),l&&e.jsx(ass,{brokerageId:l,trigger:e.jsxs(U,{size:"sm",className:"gap-1.5",children:[e.jsx(Wr,{className:"h-4 w-4"})," Record & Send Video"]})})]}),l?e.jsxs(oa,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(la,{className:"flex-wrap h-auto gap-1",children:[e.jsx(Kt,{value:"pipeline",children:"Pipeline"}),e.jsxs(Kt,{value:"contacts",children:[e.jsx(Bn,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(Kt,{value:"video-outreach",children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(Kt,{value:"follow-ups",children:"Follow-ups"}),e.jsx(Kt,{value:"referrals",children:"Referrals"}),e.jsx(Kt,{value:"interest",children:"Interest Form"}),e.jsx(Kt,{value:"landing-page",children:"Landing Page"}),e.jsx(Kt,{value:"goals",children:"Goals"}),e.jsx(Kt,{value:"metrics",children:"Metrics"}),e.jsx(Kt,{value:"templates",children:"Email Templates"}),e.jsxs(Kt,{value:"campaigns",children:[e.jsx(ln,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(Kt,{value:"drip-assignments",children:[e.jsx($r,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsx(Kt,{value:"activity",children:"Recruiter Activity"}),e.jsxs(Kt,{value:"email-settings",children:[e.jsx(qc,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(Kt,{value:"pipeline-stages",children:[e.jsx(LM,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]}),e.jsxs(Kt,{value:"unsubscribed",children:[e.jsx(DF,{className:"h-3.5 w-3.5 mr-1"}),"Unsubscribed"]})]}),e.jsxs(Zt,{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(U,{variant:n==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>r("board"),children:[e.jsx(Hg,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs(U,{variant:n==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>r("table"),children:[e.jsx(vq,{className:"h-3.5 w-3.5"})," Table"]})]})}),n==="board"?e.jsx(Xts,{brokerageId:l}):e.jsx(wTe,{brokerageId:l})]}),e.jsx(Zt,{value:"contacts",children:e.jsx(wTe,{brokerageId:l})}),e.jsx(Zt,{value:"video-outreach",children:e.jsx(iss,{brokerageId:l})}),e.jsx(Zt,{value:"follow-ups",children:e.jsx(nss,{brokerageId:l})}),e.jsx(Zt,{value:"referrals",children:e.jsx(tss,{brokerageId:l})}),e.jsx(Zt,{value:"interest",children:e.jsx(sss,{brokerageId:l})}),e.jsx(Zt,{value:"landing-page",children:e.jsx(rss,{brokerageId:l})}),e.jsx(Zt,{value:"goals",children:e.jsx(oss,{brokerageId:l})}),e.jsx(Zt,{value:"metrics",children:e.jsx(Qts,{brokerageId:l})}),e.jsx(Zt,{value:"templates",children:e.jsx(Jts,{brokerageId:l})}),e.jsx(Zt,{value:"campaigns",children:e.jsx(uss,{brokerageId:l})}),e.jsx(Zt,{value:"drip-assignments",children:e.jsx(hss,{brokerageId:l})}),e.jsx(Zt,{value:"activity",children:e.jsx(ess,{brokerageId:l})}),e.jsx(Zt,{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(jrt,{brokerageId:l})]})}),e.jsx(Zt,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(mss,{brokerageId:l})})}),e.jsx(Zt,{value:"unsubscribed",children:e.jsx(KJn,{brokerageId:l})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(_i,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found. Create a brokerage first."})]})]})})}function ZJn({brokerageId:s}){const[t,n]=j.useState(""),[r,a]=j.useState("all"),{data:i,isLoading:l}=ct({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:p}=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:f}=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 p||[]){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 f||[]){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:$r,color:"text-primary"},{label:"Video Emails",value:o.videos,icon:Wr,color:"text-blue-500"},{label:"Campaign Emails",value:o.campaigns,icon:ln,color:"text-violet-500"},{label:"Opened / Viewed",value:o.opened,icon:xa,color:"text-amber-500"},{label:"Clicked",value:o.clicked,icon:Ch,color:"text-emerald-500"}].map(d=>e.jsx(we,{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(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(It,{className:"text-lg",children:"Sent Emails"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oa,{value:r,onValueChange:d=>a(d),children:e.jsxs(la,{className:"h-8",children:[e.jsx(Kt,{value:"all",className:"text-xs h-7",children:"All"}),e.jsx(Kt,{value:"video",className:"text-xs h-7",children:"Video"}),e.jsx(Kt,{value:"campaign",className:"text-xs h-7",children:"Campaign"})]})}),e.jsxs("div",{className:"relative w-56",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{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(ln,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No emails sent yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Emails sent from Video Outreach or Drip Campaigns will appear here."})]}):e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/40 text-xs text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Type"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Recruit"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Subject"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Status"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Sent"}),e.jsx("th",{className:"text-right font-medium px-3 py-2",children:"Engagement"})]})}),e.jsx("tbody",{children:c.map(d=>e.jsxs("tr",{className:"border-t hover:bg-muted/30 transition-colors",children:[e.jsx("td",{className:"px-3 py-2",children:d.kind==="video"?e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(Wr,{className:"h-3 w-3"}),"Video"]}):e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(ln,{className:"h-3 w-3"}),"Campaign"]})}),e.jsxs("td",{className:"px-3 py-2",children:[e.jsx("div",{className:"font-medium",children:d.prospect_name}),d.prospect_email&&e.jsx("div",{className:"text-xs text-muted-foreground",children:d.prospect_email})]}),e.jsx("td",{className:"px-3 py-2 max-w-xs truncate",children:d.subject}),e.jsxs("td",{className:"px-3 py-2",children:[d.status==="failed"||d.status==="bounced"?e.jsxs(Be,{variant:"destructive",className:"gap-1",children:[e.jsx(Vo,{className:"h-3 w-3"}),d.status]}):d.clicked_at?e.jsxs(Be,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(Ch,{className:"h-3 w-3"}),"Clicked"]}):d.opened_at?e.jsxs(Be,{className:"bg-blue-500/15 text-blue-700 border-blue-200 gap-1",children:[e.jsx(xa,{className:"h-3 w-3"}),"Opened"]}):e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx($r,{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:[Gs(new Date(d.sent_at),"MMM d, yyyy"),e.jsx("div",{className:"text-[10px]",children:Gs(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(xa,{className:"h-3 w-3"}),d.view_count]}),d.kind==="video"&&d.share_token&&e.jsx(U,{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(Sr,{className:"h-3.5 w-3.5"})})]})})]},d.id))})]})})})]})]})}function XJn(){var l;const{managedBrokerages:s,selectedBrokerageId:t,setSelectedBrokerageId:n}=vs(),[r,a]=j.useState("board"),i=t||((l=s[0])==null?void 0:l.id)||"";return s.length===0?e.jsx(qs,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(_i,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages assigned to you. Contact an admin for access."})]})}):e.jsx(qs,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"space-y-6",children:[s.length>1&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage:"}),e.jsxs(Ns,{value:i,onValueChange:n,children:[e.jsxs(ws,{className:"w-[280px]",children:[e.jsx(_i,{className:"mr-2 h-4 w-4"}),e.jsx(ks,{placeholder:"Select brokerage"})]}),e.jsx(js,{children:s.map(o=>e.jsx(et,{value:o.id,children:o.name},o.id))})]})]}),i?e.jsxs(oa,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(la,{className:"flex-wrap h-auto gap-1",children:[e.jsx(Kt,{value:"pipeline",children:"Pipeline"}),e.jsxs(Kt,{value:"contacts",children:[e.jsx(Bn,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(Kt,{value:"video-outreach",children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(Kt,{value:"follow-ups",children:"Follow-ups"}),e.jsx(Kt,{value:"referrals",children:"Referrals"}),e.jsx(Kt,{value:"interest",children:"Interest Form"}),e.jsx(Kt,{value:"landing-page",children:"Landing Page"}),e.jsx(Kt,{value:"goals",children:"Goals"}),e.jsx(Kt,{value:"metrics",children:"Metrics"}),e.jsx(Kt,{value:"templates",children:"Email Templates"}),e.jsxs(Kt,{value:"campaigns",children:[e.jsx(ln,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(Kt,{value:"drip-assignments",children:[e.jsx($r,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsxs(Kt,{value:"sent-emails",children:[e.jsx(AM,{className:"h-3.5 w-3.5 mr-1"}),"Sent Emails"]}),e.jsx(Kt,{value:"activity",children:"Recruiter Activity"}),e.jsxs(Kt,{value:"email-settings",children:[e.jsx(qc,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(Kt,{value:"pipeline-stages",children:[e.jsx(LM,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]})]}),e.jsxs(Zt,{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(U,{variant:r==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>a("board"),children:[e.jsx(Hg,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs(U,{variant:r==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>a("table"),children:[e.jsx(vq,{className:"h-3.5 w-3.5"})," Table"]})]})}),r==="board"?e.jsx(Xts,{brokerageId:i}):e.jsx(wTe,{brokerageId:i})]}),e.jsx(Zt,{value:"contacts",children:e.jsx(wTe,{brokerageId:i})}),e.jsx(Zt,{value:"video-outreach",children:e.jsx(iss,{brokerageId:i})}),e.jsx(Zt,{value:"follow-ups",children:e.jsx(nss,{brokerageId:i})}),e.jsx(Zt,{value:"referrals",children:e.jsx(tss,{brokerageId:i})}),e.jsx(Zt,{value:"interest",children:e.jsx(sss,{brokerageId:i})}),e.jsx(Zt,{value:"landing-page",children:e.jsx(rss,{brokerageId:i})}),e.jsx(Zt,{value:"goals",children:e.jsx(oss,{brokerageId:i})}),e.jsx(Zt,{value:"metrics",children:e.jsx(Qts,{brokerageId:i})}),e.jsx(Zt,{value:"templates",children:e.jsx(Jts,{brokerageId:i})}),e.jsx(Zt,{value:"campaigns",children:e.jsx(uss,{brokerageId:i})}),e.jsx(Zt,{value:"drip-assignments",children:e.jsx(hss,{brokerageId:i})}),e.jsx(Zt,{value:"sent-emails",children:e.jsx(ZJn,{brokerageId:i})}),e.jsx(Zt,{value:"activity",children:e.jsx(ess,{brokerageId:i})}),e.jsx(Zt,{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(jrt,{brokerageId:i})]})}),e.jsx(Zt,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(mss,{brokerageId:i})})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(_i,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found."})]})]})})}function QJn(){const[s,t]=j.useState(""),{data:n,isLoading:r}=ct({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(p=>{const f=u.filter(v=>v.brokerage_id===p.id),x=h.filter(v=>v.brokerage_id===p.id),y=f.length>0?f.reduce((v,b)=>b.created_at>v?b.created_at:v,f[0].created_at):null;return{brokerage_id:p.id,brokerage_name:p.name,total_items:f.length,videos:f.filter(v=>v.content_type==="video").length,pdfs:f.filter(v=>v.content_type==="pdf").length,links:f.filter(v=>v.content_type==="link"||v.content_type==="canva_link").length,events:f.filter(v=>v.content_type==="event").length,graphics:f.filter(v=>v.content_type==="graphic").length,latest_item_date:y,categories:x.length}});return m.sort((p,f)=>f.total_items-p.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(qs,{title:"Brokerage Content Activity",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{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(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{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(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{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(we,{children:[e.jsx(Tt,{className:"pb-2",children:e.jsx(It,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search brokerages...",value:s,onChange:o=>t(o.target.value),className:"pl-9"})]}),e.jsx(we,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Brokerage"}),e.jsx(Lt,{className:"text-center",children:"Total"}),e.jsx(Lt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Wr,{className:"h-3 w-3"})," Videos"]})}),e.jsx(Lt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Ur,{className:"h-3 w-3"})," PDFs"]})}),e.jsx(Lt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(ad,{className:"h-3 w-3"})," Links"]})}),e.jsx(Lt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(nc,{className:"h-3 w-3"})," Events"]})}),e.jsx(Lt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(pc,{className:"h-3 w-3"})," Graphics"]})}),e.jsx(Lt,{className:"text-center",children:"Categories"}),e.jsx(Lt,{children:"Last Upload"})]})}),e.jsx(Xa,{children:r?e.jsx(gn,{children:e.jsx(gt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):a.length===0?e.jsx(gn,{children:e.jsx(gt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No brokerages found"})}):a.map(o=>e.jsxs(gn,{className:o.total_items===0?"opacity-50":"",children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_i,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:o.brokerage_name})]})}),e.jsx(gt,{className:"text-center",children:o.total_items>0?e.jsx(Be,{variant:"secondary",className:"font-bold",children:o.total_items}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(gt,{className:"text-center",children:o.videos||"–"}),e.jsx(gt,{className:"text-center",children:o.pdfs||"–"}),e.jsx(gt,{className:"text-center",children:o.links||"–"}),e.jsx(gt,{className:"text-center",children:o.events||"–"}),e.jsx(gt,{className:"text-center",children:o.graphics||"–"}),e.jsx(gt,{className:"text-center",children:o.categories||"–"}),e.jsx(gt,{children:o.latest_item_date?e.jsx("span",{className:"text-sm text-muted-foreground",children:Gs(new Date(o.latest_item_date),"MMM d, yyyy")}):e.jsx("span",{className:"text-muted-foreground",children:"–"})})]},o.brokerage_id))})]})})})]})})}const JJn=[{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:"📉"}],$St=[{value:"instagram-square",label:"Instagram Post",dimensions:"1080×1080",icon:e.jsx(gm,{className:"h-4 w-4"})},{value:"instagram-story",label:"Instagram Story",dimensions:"1080×1920",icon:e.jsx(gm,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook Post",dimensions:"1200×630",icon:e.jsx(zp,{className:"h-4 w-4"})}],eer=[{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:"📰"}],VSt=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),HSt={"luxury-dark":cet,"modern-clean":det,"bold-colorful":uet,editorial:het};function ter(){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,p]=j.useState("just-listed"),[f,x]=j.useState(["instagram-square"]),[y,v]=j.useState("luxury-dark"),[b,N]=j.useState(!1),[S,A]=j.useState(""),[T,L]=j.useState(""),[M,I]=j.useState(""),[R,z]=j.useState(!1),[$,H]=j.useState(!1),[V,K]=j.useState([]),[Z,Q]=j.useState("search"),le=j.useRef({});j.useEffect(()=>{(async()=>{const{data:{user:ke}}=await q.auth.getUser();if(!ke)return;const{data:Te}=await q.from("profiles").select("name, avatar_url, brokerages(name)").eq("id",ke.id).single();if(Te){A(Te.name||""),I(Te.avatar_url||"");const Me=Te.brokerages;L((Me==null?void 0:Me.name)||"")}})()},[]);const ue=async()=>{var ge;if(s.trim()){i(!0),o([]);try{const{data:ke,error:Te}=await q.functions.invoke("repliers-mls-search",{body:{searchType:n,query:s.trim()}});if(Te)throw Te;if(ke.error)throw new Error(ke.error);o(ke.listings||[]),((ge=ke.listings)==null?void 0:ge.length)===0&&re.info("No listings found. Try a different search.")}catch(ke){re.error(ke.message||"Search failed")}finally{i(!1)}}},se=ge=>{var ke;d(ge),h(0),Q("customize"),ge.soldDate||(ke=ge.status)!=null&&ke.toLowerCase().includes("sold")?p("just-sold"):p("just-listed")},ne=ge=>{x(ke=>ke.includes(ge)?ke.filter(Te=>Te!==ge):[...ke,ge])},ie=j.useCallback(async()=>{if(!(!c||f.length===0)){z(!0),K([]),Q("generate");try{await new Promise(ke=>setTimeout(ke,500));const ge=[];for(const ke of f){const Te=`${y}-${ke}`,Me=le.current[Te];if(!Me)continue;const Oe=nM[ke],Se=await eH(Me,{width:Oe.width,height:Oe.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});ge.push({format:ke,imageUrl:Se})}K(ge),re.success(`Generated ${ge.length} social post${ge.length>1?"s":""}!`)}catch(ge){re.error(ge.message||"Generation failed")}finally{z(!1)}}},[c,f,y,u,b,S,T,M,m]),ce=async()=>{if(!(!c||f.length===0)){z(!0),K([]),Q("generate");try{const ge={...c,photos:c.photos.length>0?[c.photos[u]]:[]},ke=[];for(const Te of f){const{data:Me,error:Oe}=await q.functions.invoke("generate-listing-social-post",{body:{listing:ge,postType:m,format:Te,branding:b?{enabled:!0,agentName:S,brokerage:T}:{enabled:!1}}});if(Oe)throw Oe;if(Me.error)throw new Error(Me.error);ke.push({format:Te,imageUrl:Me.imageUrl})}K(ke),re.success(`Generated ${ke.length} AI post${ke.length>1?"s":""}!`)}catch(ge){re.error(ge.message||"AI generation failed")}finally{z(!1)}}},je=()=>$?ce():ie(),be=(ge,ke)=>{var Me;const Te=document.createElement("a");Te.href=ge,Te.download=`${((Me=c==null?void 0:c.address)==null?void 0:Me.replace(/\s+/g,"-"))||"listing"}-${m}-${ke}.png`,document.body.appendChild(Te),Te.click(),document.body.removeChild(Te)},he=c?{listing:c,postType:m,format:"instagram-square",branding:b?{enabled:!0,agentName:S,brokerage:T,agentPhotoUrl:M||void 0}:{enabled:!1},selectedPhotoIndex:u}:null;return e.jsx(qs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Xh,{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:()=>Q("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${Z==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Fr,{className:"h-3.5 w-3.5"})," 1. Find Listing"]}),e.jsx(gi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>c&&Q("customize"),disabled:!c,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${Z==="customize"?"bg-primary text-primary-foreground":c?"bg-muted text-muted-foreground hover:text-foreground":"bg-muted text-muted-foreground/50 cursor-not-allowed"}`,children:[e.jsx(cn,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(gi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full ${Z==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(pc,{className:"h-3.5 w-3.5"})," 3. Generate"]})]}),Z==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(Fr,{className:"h-5 w-5 text-primary"})," Search MLS Listings ",e.jsx(x7t,{})]}),e.jsx(Jn,{children:"Find a listing by MLS number or property address using Repliers.io"})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx(oa,{value:n,onValueChange:ge=>r(ge),children:e.jsxs(la,{children:[e.jsxs(Kt,{value:"address",children:[e.jsx(ni,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Kt,{value:"mls",children:[e.jsx(Cf,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:s,onChange:ge=>t(ge.target.value),placeholder:n==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:ge=>ge.key==="Enter"&&ue()}),e.jsxs(U,{onClick:ue,disabled:a||!s.trim(),children:[a?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(Fr,{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((ge,ke)=>{var Te;return e.jsx(we,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group",onClick:()=>se(ge),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:(Te=ge.photos)!=null&&Te[0]?e.jsx("img",{src:ge.photos[0],alt:ge.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(ra,{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:VSt(ge.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:ge.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ge.city,", ",ge.state," ",ge.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[ge.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(C4,{className:"h-3 w-3"})," ",ge.bedrooms]}),ge.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(d0,{className:"h-3 w-3"})," ",ge.bathrooms]}),ge.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(PF,{className:"h-3 w-3"})," ",ge.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Be,{variant:"outline",className:"text-[10px]",children:ge.mlsNumber}),e.jsx(Be,{variant:"outline",className:"text-[10px]",children:ge.status})]})]})]})})},ge.mlsNumber||ke)})})]})]}),Z==="customize"&&c&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(we,{className:"lg:col-span-1",children:[e.jsx(Tt,{className:"pb-3",children:e.jsx(It,{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(U,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>h(ge=>Math.max(0,ge-1)),disabled:u===0,children:e.jsx(rd,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[u+1," of ",c.photos.length]}),e.jsx(U,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>h(ge=>Math.min(c.photos.length-1,ge+1)),disabled:u===c.photos.length-1,children:e.jsx(gi,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:VSt(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(U,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{Q("search"),d(null)},children:[e.jsx(Kg,{className:"h-3.5 w-3.5 mr-1.5"})," Choose Different Listing"]})]})]}),e.jsxs(we,{className:"lg:col-span-2",children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(cn,{className:"h-5 w-5 text-primary"})," Customize Your Post"]}),e.jsx(Jn,{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($c,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:$?"AI Custom Generation":"Template-Based (Free)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:$?"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(wn,{checked:$,onCheckedChange:H}),$&&e.jsx(Lg,{className:"h-4 w-4 text-purple-500"})]})]}),!$&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx($c,{className:"h-4 w-4"})," Template Style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:eer.map(ge=>e.jsxs("button",{onClick:()=>v(ge.value),className:`flex flex-col items-center gap-1 px-3 py-3 rounded-lg border-2 transition-all text-center ${y===ge.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:ge.preview}),e.jsx("span",{className:"text-sm font-medium",children:ge.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:ge.description})]},ge.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-sm font-medium",children:"Post Type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:JJn.map(ge=>e.jsxs("button",{onClick:()=>p(ge.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${m===ge.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:ge.icon})," ",ge.label]},ge.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-sm font-medium",children:"Output Formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:$St.map(ge=>e.jsxs("button",{onClick:()=>ne(ge.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${f.includes(ge.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[ge.icon,e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium",children:ge.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:ge.dimensions})]})]},ge.value))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(te,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(So,{className:"h-4 w-4"})," Agent Branding"]}),e.jsx(wn,{checked:b,onCheckedChange:N})]}),b&&e.jsxs("div",{className:"space-y-3 pl-6 border-l-2 border-primary/20",children:[M&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("img",{src:M,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(te,{className:"text-xs text-muted-foreground",children:"Agent Name"}),e.jsx(xe,{value:S,onChange:ge=>A(ge.target.value),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{className:"text-xs text-muted-foreground",children:"Brokerage (optional)"}),e.jsx(xe,{value:T,onChange:ge=>L(ge.target.value),placeholder:"XYZ Realty"})]})]})]})]}),!$&&he&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{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*(nM[f[0]||"instagram-square"].height/nM[f[0]||"instagram-square"].width)},children:(()=>{const ge=HSt[y],ke=f[0]||"instagram-square";return e.jsx(ge,{...he,format:ke})})()})})]}),e.jsx(U,{onClick:je,disabled:f.length===0||R,size:"lg",className:"w-full gap-2",children:R?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-5 w-5 animate-spin"})," Generating ",f.length," post",f.length>1?"s":"","..."]}):e.jsxs(e.Fragment,{children:[$?e.jsx(Lg,{className:"h-5 w-5"}):e.jsx(cn,{className:"h-5 w-5"}),"Generate ",f.length," Social Post",f.length>1?"s":"",$&&e.jsx(Be,{variant:"outline",className:"ml-2 text-[10px]",children:"Uses Credits"})]})})]})]})]}),Z==="generate"&&e.jsxs("div",{className:"space-y-4",children:[R&&e.jsx(we,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(Et,{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:$?"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(U,{variant:"outline",size:"sm",onClick:()=>Q("customize"),children:[e.jsx(Kg,{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((ge,ke)=>{const Te=$St.find(Me=>Me.value===ge.format);return e.jsxs(we,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:ge.imageUrl,alt:`${ge.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:[Te==null?void 0:Te.icon,e.jsx("span",{className:"text-sm font-medium",children:Te==null?void 0:Te.label})]}),e.jsx(Be,{variant:"outline",className:"text-[10px]",children:Te==null?void 0:Te.dimensions})]}),e.jsxs(U,{size:"sm",className:"w-full gap-1.5",onClick:()=>be(ge.imageUrl,ge.format),children:[e.jsx(pi,{className:"h-3.5 w-3.5"})," Download"]})]})]},ke)})})]})]}),Z==="generate"&&!$&&c&&he&&e.jsx("div",{style:{position:"absolute",left:"-9999px",top:0},"aria-hidden":!0,children:f.map(ge=>{const ke=HSt[y],Te=nM[ge];return e.jsx("div",{style:{width:Te.width,height:Te.height},children:e.jsx(ke,{ref:Me=>{le.current[`${y}-${ge}`]=Me},...he,format:ge})},`${y}-${ge}`)})})]})})}function ser(){return ct({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 ner(s){return ct({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 rer(){const s=Qt();return yt({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 pss(){const s=Qt();return yt({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 aer(){const s=Qt();return yt({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 ier(){const s=Qt();return yt({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 oer(){const s=Qt();return yt({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 ler(){const s=Qt();return yt({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 cer(){const s=Qt();return yt({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 der(){const s=Qt();return yt({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 uer(){const s=Qt();return yt({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 her(){return ct({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 mer(s){return ct({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 fss(s){return ct({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 per(){const s=Qt();return yt({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 fer(){const{user:s}=vs(),t=Wn(),{data:n,isLoading:r}=ser(),a=rer(),i=pss(),l=aer(),[o,c]=j.useState(!1),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,f]=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:p,created_by:s.id});re.success("Course created"),c(!1),u(""),m(""),f(!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 Yi("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(qs,{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(Kh,{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(U,{variant:"outline",onClick:()=>t("/admin/lms/stats"),children:[e.jsx(Cl,{className:"h-4 w-4 mr-2"}),"Analytics"]}),e.jsxs(U,{onClick:()=>c(!0),children:[e.jsx(an,{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(we,{className:"animate-pulse",children:e.jsxs(Tt,{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 T,L;const N=((L=(T=b.modules)==null?void 0:T[0])==null?void 0:L.count)??0,S=b.access||[],A=S.length===0?"No access set":S.some(M=>M.access_type==="all")?"All agents":`${S.length} rule(s)`;return e.jsxs(we,{className:"group hover:shadow-md transition-all hover:border-primary/50 cursor-pointer",onClick:()=>t(`/admin/lms/${b.id}`),children:[e.jsx(Tt,{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(It,{className:"text-base truncate",children:b.title}),b.description&&e.jsx(Jn,{className:"mt-1 line-clamp-2",children:b.description})]}),e.jsx(Be,{variant:b.is_published?"default":"secondary",className:"ml-2 shrink-0",children:b.is_published?"Published":"Draft"})]})}),e.jsxs(Ie,{className:"pt-0",children:[e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ig,{className:"h-3.5 w-3.5"}),N," module",N!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[b.is_sequential?e.jsx(sj,{className:"h-3.5 w-3.5"}):e.jsx(FF,{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(Bn,{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(U,{size:"sm",variant:"ghost",onClick:M=>{M.stopPropagation(),y(b)},children:[b.is_published?e.jsx(Vg,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(xa,{className:"h-3.5 w-3.5 mr-1"}),b.is_published?"Unpublish":"Publish"]}),e.jsx(U,{size:"sm",variant:"ghost",className:"text-destructive",onClick:M=>{M.stopPropagation(),v(b.id)},children:e.jsx(In,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"flex-1"}),e.jsx(Oa,{className:"h-4 w-4 text-muted-foreground"})]})]})]},b.id)})}):e.jsx(we,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(ig,{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(U,{onClick:()=>c(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Create Course"]})]})})]}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{children:"Course Title"}),e.jsx(xe,{value:d,onChange:b=>u(b.target.value),placeholder:"e.g. LevelUp Onboarding"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Description"}),e.jsx(Fs,{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(wn,{checked:p,onCheckedChange:f})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(U,{onClick:x,disabled:!d.trim()||a.isPending,children:a.isPending?"Creating...":"Create Course"})]})]})})]})}function ger(){const{courseId:s}=Di(),t=Wn(),{data:n,isLoading:r}=ner(s),a=pss(),i=ier(),l=oer(),o=ler(),c=cer(),d=der(),u=uer(),{data:h}=ct({queryKey:["all-brokerages"],queryFn:async()=>{const{data:Ye}=await q.from("brokerages").select("id, name").order("name");return Ye||[]}}),[m,p]=j.useState(null),[f,x]=j.useState(!1),[y,v]=j.useState({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),[b,N]=j.useState(null),[S,A]=j.useState({title:"",resource_type:"link",url:""}),[T,L]=j.useState(new Set),[M,I]=j.useState(null),[R,z]=j.useState(0),[$,H]=j.useState(!1),V=j.useRef(null),K=j.useRef(null),[Z,Q]=j.useState(!1),[le,ue]=j.useState(""),[se,ne]=j.useState(""),[ie,ce]=j.useState(""),[je,be]=j.useState(!1);if(r)return e.jsx(qs,{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(qs,{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(U,{variant:"outline",className:"mt-4",onClick:()=>t("/admin/lms"),children:[e.jsx(Aa,{className:"h-4 w-4 mr-2"})," Back to Courses"]})]})});const he=n.modules||[],ge=n.access||[],ke=ge.some(Ye=>Ye.access_type==="all"),Te=ge.filter(Ye=>Ye.access_type==="brokerage").map(Ye=>Ye.brokerage_id),Me=(h||[]).filter(Ye=>Ye.name.toLowerCase().includes(le.toLowerCase())),Oe=Ye=>{const Ge=new Set(T);Ge.has(Ye)?Ge.delete(Ye):Ge.add(Ye),L(Ge)},Se=async()=>{if(!M)return null;H(!0),z(0);try{const{data:Ye,error:Ge}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:M.name}});if(Ge)throw new Error(Ge.message);const{videoId:He,libraryId:tt}=Ye,{data:pt,error:ft}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:He,libraryId:tt}});if(ft)throw new Error(ft.message);const qt=new XMLHttpRequest;return await new Promise((Ut,Wt)=>{qt.upload.onprogress=us=>{us.lengthComputable&&z(Math.round(us.loaded/us.total*100))},qt.onload=()=>qt.status>=200&&qt.status<300?Ut():Wt(new Error(`Upload failed: ${qt.status}`)),qt.onerror=()=>Wt(new Error("Upload failed")),qt.open("PUT",pt.uploadUrl),qt.setRequestHeader("AccessKey",pt.apiKey),qt.send(M)}),`https://iframe.mediadelivery.net/embed/${tt}/${He}`}catch(Ye){return console.error("Bunny upload error:",Ye),re.error("Video upload failed"),null}finally{H(!1),z(0)}},Qe=async()=>{if(y.title.trim())try{let Ye=y.video_url.trim()||void 0;if(M){const Ge=await Se();if(!Ge)return;Ye=Ge}await i.mutateAsync({course_id:n.id,title:y.title.trim(),description:y.description.trim()||void 0,video_url:Ye,text_content:y.text_content.trim()||void 0,duration_minutes:y.duration_minutes?parseInt(y.duration_minutes):void 0,sort_order:he.length}),re.success("Module added"),x(!1),v({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),I(null)}catch{re.error("Failed to add module")}},Ae=async()=>{if(m)try{let Ye=y.video_url.trim()||null;if(M){const Ge=await Se();if(!Ge)return;Ye=Ge}await l.mutateAsync({id:m.id,title:y.title.trim(),description:y.description.trim()||null,video_url:Ye,text_content:y.text_content.trim()||null,duration_minutes:y.duration_minutes?parseInt(y.duration_minutes):null}),re.success("Module updated"),p(null),I(null)}catch{re.error("Failed to update")}},Fe=async Ye=>{if(await Yi("Delete this module?"))try{await o.mutateAsync(Ye),re.success("Module deleted")}catch{re.error("Failed to delete")}},Ne=async Ye=>{if(S.title.trim())try{await c.mutateAsync({module_id:Ye,title:S.title.trim(),resource_type:S.resource_type,url:S.url.trim()||void 0}),re.success("Resource added"),N(null),A({title:"",resource_type:"link",url:""})}catch{re.error("Failed to add resource")}},$e=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")}},Ve=async Ye=>{const Ge=ge.filter(ft=>ft.access_type==="brokerage").map(ft=>ft.brokerage_id),He=Ge.includes(Ye);let tt;He?tt=Ge.filter(ft=>ft!==Ye):tt=[...Ge,Ye];const pt=tt.map(ft=>({access_type:"brokerage",brokerage_id:ft}));try{await u.mutateAsync({courseId:n.id,accessRules:pt}),re.success(He?"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")}},Ze=async(Ye,Ge)=>{const He=Ge==="up"?Ye-1:Ye+1;if(!(He<0||He>=he.length))try{await Promise.all([l.mutateAsync({id:he[Ye].id,sort_order:He}),l.mutateAsync({id:he[He].id,sort_order:Ye})])}catch{re.error("Failed to reorder")}},Ue=async()=>{try{await a.mutateAsync({id:n.id,title:se,description:ie||null}),re.success("Course updated"),be(!1)}catch{re.error("Failed to update")}};return e.jsxs(qs,{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(U,{variant:"ghost",size:"icon",onClick:()=>t("/admin/lms"),children:e.jsx(Aa,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:n.title}),e.jsx(Be,{variant:n.is_published?"default":"secondary",children:n.is_published?"Published":"Draft"})]}),n.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:n.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[n.is_sequential?e.jsx(sj,{className:"h-3.5 w-3.5"}):e.jsx(FF,{className:"h-3.5 w-3.5"}),n.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{children:[he.length," module",he.length!==1?"s":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>{ne(n.title),ce(n.description||""),be(!0)},children:[e.jsx(ri,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs(U,{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(Vg,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(xa,{className:"h-3.5 w-3.5 mr-1"}),n.is_published?"Unpublish":"Publish"]})]})]}),e.jsxs(oa,{defaultValue:"modules",className:"w-full",children:[e.jsxs(la,{children:[e.jsx(Kt,{value:"modules",children:"Modules"}),e.jsx(Kt,{value:"access",children:"Access & Permissions"}),e.jsx(Kt,{value:"settings",children:"Settings"})]}),e.jsxs(Zt,{value:"modules",className:"mt-6 space-y-4",children:[he.map((Ye,Ge)=>e.jsxs(we,{className:"overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-4 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>Oe(Ye.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:He=>{He.stopPropagation(),Ze(Ge,"up")},disabled:Ge===0,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(dv,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:He=>{He.stopPropagation(),Ze(Ge,"down")},disabled:Ge===he.length-1,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(rl,{className:"h-3.5 w-3.5"})})]})}),e.jsx(Be,{variant:"outline",className:"shrink-0 font-mono text-xs",children:Ge+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:Ye.title}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-0.5",children:[Ye.video_url&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Wr,{className:"h-3 w-3"})," Video"]}),Ye.text_content&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Ur,{className:"h-3 w-3"})," Text"]}),Ye.duration_minutes&&e.jsxs("span",{children:[Ye.duration_minutes," min"]}),Ye.resources&&Ye.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(ad,{className:"h-3 w-3"})," ",Ye.resources.length," resource(s)"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(U,{size:"sm",variant:"ghost",onClick:He=>{var tt;He.stopPropagation(),p(Ye),v({title:Ye.title,description:Ye.description||"",video_url:Ye.video_url||"",text_content:Ye.text_content||"",duration_minutes:((tt=Ye.duration_minutes)==null?void 0:tt.toString())||""})},children:e.jsx(ri,{className:"h-3.5 w-3.5"})}),e.jsx(U,{size:"sm",variant:"ghost",className:"text-destructive",onClick:He=>{He.stopPropagation(),Fe(Ye.id)},children:e.jsx(In,{className:"h-3.5 w-3.5"})})]})]}),T.has(Ye.id)&&e.jsxs("div",{className:"border-t bg-muted/30 p-4 space-y-3",children:[Ye.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:Ye.description}),Ye.video_url&&e.jsxs("div",{className:"text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Video: "}),e.jsx("a",{href:Ye.video_url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline break-all",children:Ye.video_url})]}),Ye.text_content&&e.jsx("div",{className:"text-sm bg-background rounded-md p-3 border max-h-40 overflow-auto whitespace-pre-wrap",children:Ye.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(U,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>{N(Ye.id),A({title:"",resource_type:"link",url:""})},children:[e.jsx(an,{className:"h-3 w-3 mr-1"})," Add Resource"]})]}),Ye.resources&&Ye.resources.length>0?e.jsx("div",{className:"space-y-1",children:Ye.resources.map(He=>e.jsxs("div",{className:"flex items-center gap-2 text-sm bg-background rounded p-2 border",children:[e.jsx(Be,{variant:"outline",className:"text-[10px]",children:He.resource_type}),e.jsx("span",{className:"flex-1 truncate",children:He.title}),He.url&&e.jsx("a",{href:He.url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline text-xs",children:"Open"}),e.jsx(U,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-destructive",onClick:()=>d.mutateAsync(He.id),children:e.jsx(er,{className:"h-3 w-3"})})]},He.id))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No resources yet"})]})]})]},Ye.id)),e.jsxs(U,{variant:"outline",className:"w-full border-dashed",onClick:()=>{x(!0),v({title:"",description:"",video_url:"",text_content:"",duration_minutes:""})},children:[e.jsx(an,{className:"h-4 w-4 mr-2"})," Add Module"]})]}),e.jsx(Zt,{value:"access",className:"mt-6 space-y-4",children:e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Who can access this course?"})}),e.jsxs(Ie,{className:"space-y-5",children:[e.jsxs("div",{className:Mt("flex items-center gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all",ke?"border-primary bg-primary/5":"border-muted hover:border-muted-foreground/30"),onClick:$e,children:[e.jsx("div",{className:Mt("h-10 w-10 rounded-full flex items-center justify-center shrink-0",ke?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(fl,{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(wn,{checked:ke,onCheckedChange:$e})]}),!ke&&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:Te.length===0?"No brokerages selected — agents won't see this course":`${Te.length} brokerage${Te.length!==1?"s":""} selected`})]}),Te.length>0&&e.jsx(U,{size:"sm",variant:"ghost",className:"text-xs text-muted-foreground",onClick:qe,children:"Clear all"})]}),e.jsx(xe,{placeholder:"Search brokerages...",value:le,onChange:Ye=>ue(Ye.target.value),className:"h-9"}),e.jsx("div",{className:"border rounded-lg divide-y max-h-[360px] overflow-auto",children:Me.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No brokerages found"}):Me.map(Ye=>{const Ge=Te.includes(Ye.id);return e.jsxs("div",{className:Mt("flex items-center gap-3 px-3 py-2.5 cursor-pointer transition-colors",Ge?"bg-primary/5":"hover:bg-muted/50"),onClick:()=>Ve(Ye.id),children:[e.jsx("div",{className:Mt("h-5 w-5 rounded border-2 flex items-center justify-center shrink-0 transition-colors",Ge?"bg-primary border-primary":"border-muted-foreground/30"),children:Ge&&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(_i,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:Ye.name}),Ge&&e.jsx(Be,{variant:"secondary",className:"text-[10px] shrink-0",children:"Active"})]},Ye.id)})})]})]})]})}),e.jsxs(Zt,{value:"settings",className:"mt-6 space-y-4",children:[e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(er,{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(ly,{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:K,type:"file",accept:"image/*",className:"hidden",onChange:async Ye=>{var He;const Ge=(He=Ye.target.files)==null?void 0:He[0];if(!(!Ge||!n)){Q(!0);try{const tt=Ge.name.split(".").pop(),pt=`${n.id}/thumbnail.${tt}`,{error:ft}=await q.storage.from("lms-thumbnails").upload(pt,Ge,{upsert:!0});if(ft)throw ft;const{data:qt}=q.storage.from("lms-thumbnails").getPublicUrl(pt),Ut=`${qt.publicUrl}?t=${Date.now()}`;await a.mutateAsync({id:n.id,thumbnail_url:Ut}),re.success("Thumbnail uploaded")}catch{re.error("Failed to upload thumbnail")}finally{Q(!1),K.current&&(K.current.value="")}}}}),e.jsxs(U,{variant:"outline",size:"sm",disabled:Z,onClick:()=>{var Ye;return(Ye=K.current)==null?void 0:Ye.click()},children:[Z?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(qa,{className:"h-4 w-4 mr-2"}),Z?"Uploading...":"Upload Thumbnail"]})]})]})})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(wn,{checked:n.is_sequential,onCheckedChange:Ye=>a.mutateAsync({id:n.id,is_sequential:Ye}).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(wn,{checked:n.is_published,onCheckedChange:Ye=>a.mutateAsync({id:n.id,is_published:Ye}).then(()=>re.success("Updated"))})]})]})]})]})]})]}),e.jsx(zs,{open:f||!!m,onOpenChange:Ye=>{Ye||(x(!1),p(null))},children:e.jsxs(Ds,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{children:"Title"}),e.jsx(xe,{value:y.title,onChange:Ye=>v(Ge=>({...Ge,title:Ye.target.value})),placeholder:"Module title"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Description"}),e.jsx(Fs,{value:y.description,onChange:Ye=>v(Ge=>({...Ge,description:Ye.target.value})),placeholder:"Brief description",rows:2})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Video"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:Mt("border-2 border-dashed rounded-lg p-4 text-center cursor-pointer transition-colors hover:border-primary/50",M?"border-primary bg-primary/5":"border-muted-foreground/25"),onClick:()=>{var Ye;return(Ye=V.current)==null?void 0:Ye.click()},children:[e.jsx("input",{ref:V,type:"file",accept:"video/*",className:"hidden",onChange:Ye=>{var He;const Ge=(He=Ye.target.files)==null?void 0:He[0];Ge&&(I(Ge),v(tt=>({...tt,video_url:""})))}}),M?e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm",children:[e.jsx(Wr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-primary",children:M.name}),e.jsx(U,{type:"button",size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:Ye=>{Ye.stopPropagation(),I(null)},children:e.jsx(er,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"flex flex-col items-center gap-1 text-muted-foreground",children:[e.jsx(qa,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Click to upload a video file"})]})]}),$&&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(Et,{className:"h-3.5 w-3.5 animate-spin"}),e.jsxs("span",{children:["Uploading to Bunny.net... ",R,"%"]})]}),e.jsx(ro,{value:R,className:"h-1.5"})]}),!M&&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(xe,{value:y.video_url,onChange:Ye=>v(Ge=>({...Ge,video_url:Ye.target.value})),placeholder:"YouTube, Vimeo, or Bunny.net URL"})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Text Content"}),e.jsx(Fs,{value:y.text_content,onChange:Ye=>v(Ge=>({...Ge,text_content:Ye.target.value})),placeholder:"Additional text content, instructions, notes...",rows:4})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Duration (minutes)"}),e.jsx(xe,{type:"number",value:y.duration_minutes,onChange:Ye=>v(Ge=>({...Ge,duration_minutes:Ye.target.value})),placeholder:"e.g. 15"})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>{x(!1),p(null),I(null)},children:"Cancel"}),e.jsxs(U,{onClick:m?Ae:Qe,disabled:!y.title.trim()||$,children:[$?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-2"}),$?"Uploading...":m?"Save Changes":"Add Module"]})]})]})}),e.jsx(zs,{open:!!b,onOpenChange:Ye=>{Ye||N(null)},children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{children:"Title"}),e.jsx(xe,{value:S.title,onChange:Ye=>A(Ge=>({...Ge,title:Ye.target.value})),placeholder:"Resource title"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Type"}),e.jsxs(Ns,{value:S.resource_type,onValueChange:Ye=>A(Ge=>({...Ge,resource_type:Ye})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"link",children:"Link"}),e.jsx(et,{value:"pdf",children:"PDF"}),e.jsx(et,{value:"template",children:"Template"}),e.jsx(et,{value:"worksheet",children:"Worksheet"})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"URL"}),e.jsx(xe,{value:S.url,onChange:Ye=>A(Ge=>({...Ge,url:Ye.target.value})),placeholder:"https://..."})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>N(null),children:"Cancel"}),e.jsx(U,{onClick:()=>b&&Ne(b),disabled:!S.title.trim(),children:"Add Resource"})]})]})}),e.jsx(zs,{open:je,onOpenChange:be,children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{children:"Title"}),e.jsx(xe,{value:se,onChange:Ye=>ne(Ye.target.value)})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Description"}),e.jsx(Fs,{value:ie,onChange:Ye=>ce(Ye.target.value),rows:3})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>be(!1),children:"Cancel"}),e.jsx(U,{onClick:Ue,disabled:!se.trim(),children:"Save"})]})]})})]})}function xer(){return ct({queryKey:["lms-stats-overview"],queryFn:async()=>{const{data:s,error:t}=await q.rpc("get_lms_stats");if(t)throw t;return s}})}function yer(){return ct({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 ver(s){return ct({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 ber(){const s=Wn(),{data:t,isLoading:n}=xer(),{data:r,isLoading:a}=yer(),[i,l]=j.useState(null),{data:o,isLoading:c}=ver(i),[d,u]=j.useState(""),h=r==null?void 0:r.find(f=>f.course_id===i),m=o==null?void 0:o.filter(f=>{var x,y;return!d||((x=f.agent_name)==null?void 0:x.toLowerCase().includes(d.toLowerCase()))||((y=f.email)==null?void 0:y.toLowerCase().includes(d.toLowerCase()))}),p=[{label:"Total Courses",value:(t==null?void 0:t.total_courses)??0,icon:ig,color:"text-primary"},{label:"Published",value:(t==null?void 0:t.published_courses)??0,icon:zr,color:"text-emerald-500"},{label:"Enrolled Agents",value:(t==null?void 0:t.total_enrollments)??0,icon:Bn,color:"text-blue-500"},{label:"Modules Completed",value:(t==null?void 0:t.total_completions)??0,icon:Al,color:"text-amber-500"},{label:"Active (30d)",value:(t==null?void 0:t.active_learners)??0,icon:rc,color:"text-violet-500"},{label:"Total Modules",value:(t==null?void 0:t.total_modules)??0,icon:Cl,color:"text-rose-500"}];return e.jsx(qs,{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(U,{variant:"ghost",size:"icon",onClick:()=>s("/admin/lms"),children:e.jsx(Aa,{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(Kh,{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:p.map(f=>e.jsx(we,{className:Mt("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(f.icon,{className:Mt("h-4 w-4",f.color)}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:f.label})]}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:n?"—":f.value})]})},f.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(Cl,{className:"h-5 w-5 text-primary"}),"Course Breakdown"]}),a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(f=>e.jsx(we,{className:"animate-pulse",children:e.jsx(Ie,{className:"p-4",children:e.jsx("div",{className:"h-16 bg-muted rounded"})})},f))}):r!=null&&r.length?e.jsx("div",{className:"space-y-2",children:r.map(f=>{const x=i===f.course_id;return e.jsx(we,{className:Mt("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:f.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:f.course_title}),e.jsx(Be,{variant:f.is_published?"default":"secondary",className:"shrink-0 text-[10px] px-1.5 py-0",children:f.is_published?"Live":"Draft"})]})}),e.jsx(gi,{className:Mt("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:f.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:f.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:f.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:[f.avg_completion_pct,"%"]})]}),e.jsx(ro,{value:f.avg_completion_pct,className:"h-2"})]})]})},f.course_id)})}):e.jsx(we,{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(tN,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:d,onChange:f=>u(f.target.value),placeholder:"Search agents...",className:"pl-9"})]}),c?e.jsx("div",{className:"space-y-2",children:[1,2,3,4].map(f=>e.jsx(we,{className:"animate-pulse",children:e.jsx(Ie,{className:"p-4",children:e.jsx("div",{className:"h-12 bg-muted rounded"})})},f))}):m!=null&&m.length?e.jsx("div",{className:"space-y-2 max-h-[600px] overflow-y-auto pr-1",children:m.map((f,x)=>{const y=f.completion_pct>=100;return e.jsx(we,{className:Mt("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:Mt("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(Ea,{className:"h-9 w-9 shrink-0",children:[e.jsx(Ci,{src:f.avatar_url||void 0}),e.jsx(Ta,{className:"text-xs bg-primary/10 text-primary",children:(f.agent_name||f.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:f.agent_name||f.email}),y&&e.jsxs(Be,{variant:"default",className:"text-[10px] px-1.5 py-0 bg-emerald-500 hover:bg-emerald-600 shrink-0",children:[e.jsx(zr,{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:[f.modules_completed,"/",f.total_modules," modules"]}),f.last_activity&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yr,{className:"h-3 w-3"}),Gs(new Date(f.last_activity),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"text-right shrink-0 w-20",children:[e.jsxs("p",{className:Mt("text-sm font-bold",y?"text-emerald-600 dark:text-emerald-400":"text-foreground"),children:[f.completion_pct,"%"]}),e.jsx(ro,{value:f.completion_pct,className:"h-1.5 mt-1"})]})]})})},f.user_id)})}):e.jsx(we,{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(we,{className:"border-dashed",children:e.jsxs(Ie,{className:"py-16 text-center",children:[e.jsx(Bn,{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 _er(){const{user:s}=vs(),t=Wn(),{data:n,isLoading:r}=her();return e.jsx(qs,{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(Kh,{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(we,{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(wer,{course:a,userId:s==null?void 0:s.id,onClick:()=>t(`/levelup-u/${a.id}`)},a.id))}):e.jsx(we,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(ig,{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 wer({course:s,userId:t,onClick:n}){var o;const r=((o=s.modules)==null?void 0:o.length)??0,{data:a}=fss(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(we,{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(Kh,{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(ig,{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(sj,{className:"h-3.5 w-3.5"}):e.jsx(FF,{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(ro,{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(gi,{className:"h-3.5 w-3.5"})]})})]})]})}function jer(){const{courseId:s}=Di(),t=Wn(),{user:n}=vs(),{data:r,isLoading:a}=mer(s),{data:i}=fss(s),l=per(),[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(N=>!u.has(N.id));c((b==null?void 0:b.id)||d[0].id)}},[d,o,u]);const p=d.find(b=>b.id===o),f=d.findIndex(b=>b.id===o),x=(b,N)=>{if(!(r!=null&&r.is_sequential)||N===0)return!1;for(let S=0;S{if(!(!p||!n||!s))try{await l.mutateAsync({courseId:s,moduleId:p.id,userId:n.id}),re.success("Module completed! 🎉"),f{const N=b.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(N)return`https://www.youtube.com/embed/${N[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(qs,{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(qs,{title:r.title,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>t("/levelup-u"),children:e.jsx(Aa,{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(ro,{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(we,{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(Gi,{className:"max-h-[calc(100vh-280px)]",children:e.jsx("div",{className:"p-1",children:d.map((b,N)=>{const S=x(b,N),A=u.has(b.id),T=b.id===o;return e.jsxs("button",{disabled:S,onClick:()=>!S&&c(b.id),className:Mt("w-full flex items-center gap-3 p-3 rounded-lg text-left transition-all text-sm",T?"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(Ql,{className:"h-4 w-4 text-muted-foreground"}):A?e.jsx(zr,{className:"h-4 w-4 text-green-500"}):e.jsx(Nf,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:Mt("font-medium truncate",T&&"text-primary"),children:[N+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(Yr,{className:"h-3 w-3"})," ",b.duration_minutes," min"]})]})]},b.id)})})})]})}),e.jsx("div",{className:"space-y-4",children:p?e.jsxs(e.Fragment,{children:[p.video_url&&e.jsx(we,{className:"overflow-hidden",children:e.jsx("div",{className:"aspect-video bg-black",children:e.jsx("iframe",{src:v(p.video_url),className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}),e.jsx(we,{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:p.title}),p.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:p.description})]}),u.has(p.id)?e.jsxs(Be,{className:"bg-green-500/15 text-green-600 border-green-500/30 shrink-0",children:[e.jsx(zr,{className:"h-3.5 w-3.5 mr-1"})," Completed"]}):e.jsxs(U,{size:"sm",onClick:y,disabled:l.isPending,children:[e.jsx(zr,{className:"h-4 w-4 mr-1"}),"Mark Complete"]})]}),p.text_content&&e.jsx("div",{className:"prose prose-sm max-w-none text-foreground border-t pt-4 whitespace-pre-wrap",children:p.text_content}),p.resources&&p.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:p.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(Ur,{className:"h-4 w-4 text-red-500 shrink-0"}):b.resource_type==="template"?e.jsx(Kh,{className:"h-4 w-4 text-purple-500 shrink-0"}):e.jsx(ad,{className:"h-4 w-4 text-blue-500 shrink-0"}),e.jsx("span",{className:"flex-1 truncate",children:b.title}),e.jsx(Sr,{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(U,{variant:"outline",size:"sm",disabled:f===0,onClick:()=>f>0&&c(d[f-1].id),children:[e.jsx(Aa,{className:"h-3.5 w-3.5 mr-1"})," Previous"]}),fc(d[f+1].id),children:["Next ",e.jsx(gi,{className:"h-3.5 w-3.5 ml-1"})]}):m===100&&e.jsx(Be,{className:"bg-green-500/15 text-green-600 border-green-500/30 text-sm px-3 py-1.5",children:"🎉 Course Complete!"})]})]})})]}):e.jsx(we,{children:e.jsx(Ie,{className:"flex items-center justify-center py-16 text-muted-foreground",children:"Select a module to begin"})})})]})]})}):e.jsx(qs,{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(U,{variant:"outline",className:"mt-4",onClick:()=>t("/levelup-u"),children:[e.jsx(Aa,{className:"h-4 w-4 mr-2"})," Back"]})]})})}function Ner({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(kr.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(kr.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(kr.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(kr.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(kr.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(Oa,{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(kr.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 jj({children:s,className:t="",delay:n=0,direction:r="up"}){const a=j.useRef(null),i=cIs(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(kr.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 ker({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(jj,{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(jj,{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 Ser({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(jj,{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(Bn,{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(jj,{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(er,{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 Cer({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(jj,{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(jj,{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(tS,{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 Aer({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(jj,{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(jj,{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(te,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(xe,{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(te,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(xe,{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(te,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(xe,{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(te,{className:"text-gray-700 text-sm font-medium",children:"Phone"}),e.jsx(xe,{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(te,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(xe,{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(te,{className:"text-gray-700 text-sm font-medium",children:"License #"}),e.jsx(xe,{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(te,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(xe,{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(te,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(xe,{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(te,{className:"text-gray-700 text-sm font-medium",children:"Why are you interested?"}),e.jsx(Fs,{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(U,{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(Oa,{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(Im,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Your information is confidential and will not be shared."})]})]})})]})]})}function Eer({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,p=f=>{u(f),t(x=>({...x,why_interested:f})),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(jj,{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(Ql,{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(jj,{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(f=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-colors duration-500",style:{backgroundColor:f<=o?a:"#e5e7eb"}},f)),e.jsxs("span",{className:"text-xs text-gray-400 ml-2",children:[o,"/",h]})]}),e.jsxs(_G,{mode:"wait",children:[o===1&&e.jsxs(kr.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(f=>e.jsxs("button",{type:"button",onClick:()=>p(f.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:f.icon}),e.jsx("span",{className:"font-medium text-gray-700 group-hover:text-gray-900 flex-1",children:f.label}),e.jsx(Oa,{className:"h-4 w-4 text-gray-300 group-hover:text-gray-500 group-hover:translate-x-1 transition-all"})]},f.val))]},"step1"),o===2&&e.jsxs(kr.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(te,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(xe,{required:!0,value:s.first_name,onChange:f=>t(x=>({...x,first_name:f.target.value})),className:"h-11",placeholder:"John"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(xe,{value:s.last_name,onChange:f=>t(x=>({...x,last_name:f.target.value})),className:"h-11",placeholder:"Smith"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(xe,{type:"email",required:!0,value:s.email,onChange:f=>t(x=>({...x,email:f.target.value})),className:"h-11",placeholder:"john@email.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-gray-700 text-sm font-medium",children:"Phone (preferred)"}),e.jsx(xe,{value:s.phone,onChange:f=>t(x=>({...x,phone:f.target.value})),className:"h-11",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(U,{type:"button",variant:"ghost",onClick:()=>c(1),className:"h-11",children:[e.jsx(Aa,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsxs(U,{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(Oa,{className:"h-4 w-4 ml-1"})]})]})]},"step2"),o===3&&e.jsxs(kr.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(te,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(xe,{value:s.current_brokerage,onChange:f=>t(x=>({...x,current_brokerage:f.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(te,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(xe,{type:"number",min:"0",value:s.experience_years,onChange:f=>t(x=>({...x,experience_years:f.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(xe,{value:s.annual_production,onChange:f=>t(x=>({...x,annual_production:f.target.value})),className:"h-11",placeholder:"e.g. $5M"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-gray-700 text-sm font-medium",children:"Anything else?"}),e.jsx(Fs,{value:s.why_interested,onChange:f=>t(x=>({...x,why_interested:f.target.value})),rows:2,className:"resize-none",placeholder:"Optional message..."})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(U,{type:"button",variant:"ghost",onClick:()=>c(2),className:"h-11",children:[e.jsx(Aa,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsx(U,{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(Xr,{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(Im,{className:"h-3 w-3"})," Confidential"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(Ki,{className:"h-3 w-3"})," Text first"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(ba,{className:"h-3 w-3"})," No spam"]})]})]})})]})]})}function Ter({config:s,primaryColor:t,accentColor:n,brokerageId:r,brokerageName:a}){const{toast:i}=Ai(),[l,o]=j.useState("250000"),[c,d]=j.useState("12"),[u,h]=j.useState("70"),[m,p]=j.useState("150"),[f,x]=j.useState(""),[y,v]=j.useState(!1),[b,N]=j.useState(!1),S=s.commission_split_pct??80,A=s.cap_amount??16e3,T=s.post_cap_split_pct??100,L=s.monthly_fee??99,M=s.transaction_fee??0,I=j.useMemo(()=>{const $=parseFloat(l)||0,H=Math.max(0,parseInt(c,10)||0),V=parseFloat(u)||0,K=parseFloat(m)||0,Z=$*(V/100)-K*12-M*H,Q=1-S/100,le=Q>0?A/Q:$,ue=Math.min($,le),se=Math.max(0,$-le),ne=ue*Q+se*(1-T/100),ie=$-ne-L*12-M*H,ce=ie-Z;return{currentNet:Z,newNet:ie,diff:ce}},[l,c,u,m,S,A,T,L,M]),R=$=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format($),z=async $=>{if($.preventDefault(),!!f){N(!0);try{const{error:H}=await q.from("recruit_lead_magnet_downloads").insert({brokerage_id:r,email:f,source:"calculator"});if(H)throw H;const{error:V}=await q.functions.invoke("send-calculator-breakdown",{body:{brokerage_id:r,brokerage_name:a,email:f,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:T,monthly_fee:L,transaction_fee:M},result:I,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(H){i({title:"Error",description:H.message,variant:"destructive"})}finally{N(!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(jj,{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(Ql,{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(jj,{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(Qw,{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(te,{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(xe,{type:"number",value:l,onChange:$=>o($.target.value),className:"pl-7 h-11 text-base",placeholder:"250,000"})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-gray-600 text-sm",children:"Transactions per Year"}),e.jsx(xe,{type:"number",min:"0",value:c,onChange:$=>d($.target.value),className:"mt-1.5 h-11 text-base",placeholder:"12"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-gray-600 text-sm",children:"Your Current Commission Split (%)"}),e.jsx(xe,{type:"number",value:u,onChange:$=>h($.target.value),className:"mt-1.5 h-11 text-base",placeholder:"70"})]}),e.jsxs("div",{children:[e.jsx(te,{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(xe,{type:"number",value:m,onChange:$=>p($.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(rc,{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:R(I.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:R(I.newNet)})]})]}),e.jsxs(kr.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:I.diff>=0?"You could earn":"Difference"}),e.jsxs("p",{className:"text-4xl font-bold mb-1",children:[I.diff>=0?"+":"",R(I.diff)]}),e.jsx("p",{className:"text-white/70 text-xs",children:I.diff>=0?"more per year":"per year"})]},I.diff),s.show_email_capture&&!y&&e.jsxs("form",{onSubmit:z,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(xe,{type:"email",required:!0,value:f,onChange:$=>x($.target.value),placeholder:"you@email.com",className:"bg-white/95 border-0 text-gray-900 h-10 text-sm"}),e.jsx(U,{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(Xr,{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 Mer({config:s,primaryColor:t,accentColor:n,brokerageId:r}){const{toast:a}=Ai(),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(!1),[h,m]=j.useState(!1),p=async f=>{f.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(jj,{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(W2,{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(Ql,{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(Xr,{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:p,className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx(xe,{value:o,onChange:f=>c(f.target.value),placeholder:"First name (optional)",className:"h-11"}),e.jsx(xe,{type:"email",required:!0,value:i,onChange:f=>l(f.target.value),placeholder:"your@email.com",className:"h-11"})]}),e.jsxs(U,{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(W2,{className:"h-4 w-4 mr-2"}),h?"Sending...":s.button_text||"Email Me the PDF"]})]})]})]})})})})})}function Per(){const{slug:s}=Di(),{toast:t}=Ai(),[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 I=()=>{['[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(H=>document.querySelectorAll(H).forEach(V=>V.style.display="none"))};I();const R=[setTimeout(I,500),setTimeout(I,1500),setTimeout(I,3e3)],z=new MutationObserver(I);return z.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-landing-page"),R.forEach(clearTimeout),z.disconnect()}},[]);const{data:l,isLoading:o,error:c}=ct({queryKey:["recruit-form-brokerage",s],queryFn:async()=>{const{data:I,error:R}=await q.from("brokerages").select("id, name, recruit_form_enabled").eq("recruit_form_slug",s).single();if(R)throw R;return I},enabled:!!s}),{data:d}=ct({queryKey:["recruit-landing-public",l==null?void 0:l.id],queryFn:async()=>{const{data:I,error:R}=await q.from("recruit_landing_page_settings").select("*").eq("brokerage_id",l.id).single();if(R&&R.code!=="PGRST116")throw R;return I},enabled:!!(l!=null&&l.id)}),u=yt({mutationFn:async()=>{const I={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:R}=await q.from("recruit_interest_submissions").insert(I);if(R)throw R;q.functions.invoke("recruit-lead-notify",{body:{lead:I,brokerage_id:l.id}}).catch(z=>console.error("Lead notification error:",z))},onSuccess:()=>r(!0),onError:I=>t({title:"Error",description:I.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(_i,{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",p=(h==null?void 0:h.accent_color)||"#2a4c64",f=(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.",N=(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,T=(h==null?void 0:h.lead_magnet_config)||{},L=(h==null?void 0:h.form_style)||"classic",M=(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(kr.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}, ${p})`},children:e.jsx(Xr,{className:"h-10 w-10 text-white"})}),e.jsx("h2",{className:"text-3xl font-bold mb-3 tracking-tight",style:{color:p},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:p},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":p},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:p},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}, ${p})`},children:["Apply Now ",e.jsx(Oa,{className:"h-3.5 w-3.5"})]})]})}),e.jsx(Ner,{headline:v,subtext:b,primaryColor:m,accentColor:p,heroImageUrl:h==null?void 0:h.hero_image_url,logoUrl:h==null?void 0:h.logo_url,brokerageName:l.name}),e.jsx(ker,{benefits:f,accentColor:p,primaryColor:m}),e.jsx(Ser,{images:y,primaryColor:m,accentColor:p}),e.jsx(Cer,{testimonials:x,primaryColor:m,accentColor:p}),N&&e.jsx(Ter,{config:S,primaryColor:m,accentColor:p,brokerageId:l.id,brokerageName:l.name}),A&&e.jsx(Mer,{config:T,primaryColor:m,accentColor:p,brokerageId:l.id}),L==="multi_step"?e.jsx(Eer,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:m,accentColor:p,showConfidentialBadges:M}):e.jsx(Aer,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:m,accentColor:p}),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 Ler(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 Ier(){var m,p,f,x;const{shareToken:s}=Di(),t=j.useRef(!1),{data:n,isLoading:r,error:a}=ct({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:N}=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:N,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=((p=i.prospect)==null?void 0:p.first_name)||"there",h=(f=i.video)!=null&&f.playback_url?Ler(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(U,{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(pa,{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 Rer="relzejiswnotikjgvjhz",GSt=`https://${Rer}.supabase.co/functions/v1/recruit-unsubscribe`;function Der(){const[s]=fc(),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 p=()=>{['[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"))};p();const f=[setTimeout(p,500),setTimeout(p,1500),setTimeout(p,3e3)],x=new MutationObserver(p);return x.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-unsubscribe-page"),f.forEach(clearTimeout),x.disconnect()}},[]),j.useEffect(()=>{if(!t){h({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${GSt}?token=${encodeURIComponent(t)}`).then(async p=>{const f=await p.json();if(!p.ok)throw new Error(f.error||"Lookup failed");h(f),f.already_unsubscribed&&o(!0)}).catch(p=>h({error:p.message||"Could not load status"})).finally(()=>r(!1))},[t]);const m=async()=>{i(!0);try{const p=await fetch(GSt,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,reason:c.trim()||null})}),f=await p.json();if(!p.ok)throw new Error(f.error||"Failed");o(!0)}catch(p){h({...u,error:p.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(Et,{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(Vo,{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(zr,{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(cg,{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(cg,{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(te,{htmlFor:"reason",className:"text-xs text-slate-500",children:"Optional — what's the main reason? (helps us improve)"}),e.jsx(Fs,{id:"reason",value:c,onChange:p=>d(p.target.value),placeholder:"e.g. Not currently looking, too many emails, already moved…",rows:3,className:"resize-none"})]}),e.jsx(U,{onClick:m,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Et,{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 Oer="relzejiswnotikjgvjhz",WSt=`https://${Oer}.supabase.co/functions/v1/event-invite-unsubscribe`;function Fer(){const[s]=fc(),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(`${WSt}?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(WSt,{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(Et,{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(Vo,{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(zr,{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(cg,{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(EX,{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(U,{onClick:u,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Et,{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 zer(){const s=Wn(),t=Qt(),{isAdmin:n}=vs(),[r,a]=j.useState(!1),[i,l]=j.useState(null),[o,c]=j.useState(null),{data:d,isLoading:u}=ct({queryKey:["my-social-accounts"],queryFn:async()=>{const{data:{user:A},error:T}=await q.auth.getUser();if(T)throw T;if(!A)return[];const{data:L,error:M}=await q.from("social_accounts").select("*").eq("user_id",A.id).order("created_at",{ascending:!1});if(M)throw M;return L}}),h=yt({mutationFn:async A=>{const{data:{user:T},error:L}=await q.auth.getUser();if(L)throw L;if(!T)throw new Error("Not authenticated");const{error:M}=await q.from("social_accounts").delete().eq("id",A).eq("user_id",T.id);if(M)throw M},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")}}),m=async A=>{a(!0),sessionStorage.setItem("social-connect-return-to",window.location.pathname);try{const{data:T,error:L}=await q.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:A}});if(L)throw L;if(T!=null&&T.authUrl)window.location.href=T.authUrl;else throw new Error("Failed to get authorization URL")}catch(T){console.error("Meta OAuth error:",T),re.error("Failed to start connection. Please try again."),a(!1)}},p=async()=>{a(!0);try{const{data:A,error:T}=await q.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(T)throw T;if(A!=null&&A.authUrl)window.location.href=A.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(A){console.error("LinkedIn OAuth error:",A),re.error("Failed to start LinkedIn connection. Please try again."),a(!1)}},f=async()=>{a(!0);try{const{data:A,error:T}=await q.functions.invoke("google-business-oauth",{body:{action:"get_auth_url",returnPath:"/social-connections"}});if(T)throw T;if(A!=null&&A.authUrl)window.location.href=A.authUrl;else throw new Error("Failed to get Google authorization URL")}catch(A){console.error("Google OAuth error:",A),re.error("Failed to start Google connection. Please try again."),a(!1)}},x=(d==null?void 0:d.filter(A=>A.platform==="facebook"))||[],y=(d==null?void 0:d.filter(A=>A.platform==="instagram"))||[],v=(d==null?void 0:d.filter(A=>A.platform==="linkedin"))||[],b=(d==null?void 0:d.filter(A=>A.platform==="google_business"))||[],N=((d==null?void 0:d.length)||0)>0,S=async(A,T)=>{l(A),c(null);try{const{data:L,error:M}=await q.functions.invoke("meta-api-test",{body:{testType:"all",accountId:A}});if(M)throw M;c(L.results||[]),re.success(L.summary||"API tests completed")}catch(L){console.error("Meta API test error:",L),re.error("Failed to run API tests")}finally{l(null)}};return e.jsx(qs,{title:"Social Connections",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-pink-500 via-purple-500 to-blue-500 p-6 md:p-8 text-white",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmYiIGZpbGwtb3BhY2l0eT0iMC4xIj48cGF0aCBkPSJNMzYgMzRjMC0yIDItNCAyLTRzMiAyIDIgNC0yIDQtMiA0LTItMi0yLTR6Ii8+PC9nPjwvZz48L3N2Zz4=')] opacity-30"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs(Be,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(cn,{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(U,{variant:"ghost",onClick:()=>s("/social-studio"),className:"gap-2",children:[e.jsx(Aa,{className:"h-4 w-4"}),"Back to Social Studio"]}),N&&e.jsx(we,{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(Yo,{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(we,{children:[e.jsx(Tt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-blue-500/10 p-3",children:e.jsx(zp,{className:"h-6 w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(It,{className:"text-lg",children:"Facebook"}),e.jsx(Jn,{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(no,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):x.length>0?e.jsx("div",{className:"space-y-3",children:x.map(A=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Ea,{className:"h-10 w-10",children:[e.jsx(Ci,{src:A.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(zp,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:A.page_name||A.platform_username||"Facebook Page"}),e.jsx(Be,{variant:A.is_active?"default":"secondary",className:"text-xs",children:A.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(In,{className:"h-4 w-4"})})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Disconnect Facebook?"}),e.jsx(Ll,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>h.mutate(A.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},A.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Facebook pages connected yet"}),e.jsxs(U,{onClick:()=>m("facebook"),disabled:r,className:"w-full gap-2",variant:"outline",children:[r?e.jsx(no,{className:"h-4 w-4 animate-spin"}):e.jsx(an,{className:"h-4 w-4"}),x.length>0?"Connect Another Page":"Connect Facebook Page"]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{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(gm,{className:"h-6 w-6 text-pink-600"})}),e.jsxs("div",{children:[e.jsx(It,{className:"text-lg",children:"Instagram"}),e.jsx(Jn,{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(no,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):y.length>0?e.jsx("div",{className:"space-y-3",children:y.map(A=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Ea,{className:"h-10 w-10",children:[e.jsx(Ci,{src:A.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(gm,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:["@",A.platform_username||"Instagram Account"]}),e.jsx(Be,{variant:A.is_active?"default":"secondary",className:"text-xs",children:A.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(In,{className:"h-4 w-4"})})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Disconnect Instagram?"}),e.jsx(Ll,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>h.mutate(A.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},A.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Instagram accounts connected yet"}),e.jsxs(U,{onClick:()=>m("instagram"),disabled:r,className:"w-full gap-2",variant:"outline",children:[r?e.jsx(no,{className:"h-4 w-4 animate-spin"}):e.jsx(an,{className:"h-4 w-4"}),y.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(we,{children:[e.jsx(Tt,{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(Gg,{className:"h-6 w-6 text-blue-700"})}),e.jsxs("div",{children:[e.jsx(It,{className:"text-lg",children:"LinkedIn"}),e.jsx(Jn,{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(no,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):v.length>0?e.jsx("div",{className:"space-y-3",children:v.map(A=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Ea,{className:"h-10 w-10",children:[e.jsx(Ci,{src:A.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(Gg,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:A.platform_username||"LinkedIn Account"}),e.jsx(Be,{variant:A.is_active?"default":"secondary",className:"text-xs",children:A.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(In,{className:"h-4 w-4"})})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Disconnect LinkedIn?"}),e.jsx(Ll,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>h.mutate(A.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},A.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No LinkedIn account connected yet"}),e.jsxs(U,{onClick:p,disabled:r,className:"w-full gap-2",variant:v.length>0?"outline":"default",children:[r?e.jsx(no,{className:"h-4 w-4 animate-spin"}):e.jsx(an,{className:"h-4 w-4"}),v.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(we,{className:`relative overflow-hidden ${n?"":"opacity-75"}`,children:[!n&&e.jsx("div",{className:"absolute top-3 right-3 z-10",children:e.jsx(Be,{variant:"secondary",className:"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400",children:"Coming Soon"})}),n&&e.jsx("div",{className:"absolute top-3 right-3 z-10",children:e.jsx(Be,{variant:"secondary",className:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400",children:"Admin Testing"})}),e.jsx(Tt,{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(ni,{className:"h-6 w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(It,{className:"text-lg",children:"Google Business"}),e.jsx(Jn,{children:"Connect your Google Business Profile"})]})]})}),e.jsxs(Ie,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(no,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length>0?e.jsx("div",{className:"space-y-3",children:b.map(A=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Ea,{className:"h-10 w-10",children:[e.jsx(Ci,{src:A.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(ni,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:A.page_name||A.platform_username||"Google Business"}),e.jsx(Be,{variant:A.is_active?"default":"secondary",className:"text-xs",children:A.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Fl,{children:[e.jsx(Op,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(In,{className:"h-4 w-4"})})}),e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Disconnect Google Business?"}),e.jsx(Ll,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>h.mutate(A.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},A.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:n?"No Google Business account connected yet":"Google Business Profile integration is coming soon!"}),e.jsxs(U,{onClick:n?f:void 0,disabled:!n||r,className:"w-full gap-2",variant:b.length>0?"outline":"default",children:[r?e.jsx(no,{className:"h-4 w-4 animate-spin"}):e.jsx(an,{className:"h-4 w-4"}),b.length>0?"Reconnect Google Business":"Connect Google Business"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Post updates directly to your Google Business Profile"})]})]})]}),n&&(x.length>0||y.length>0)&&e.jsxs(we,{className:"border-amber-200 bg-amber-50 dark:bg-amber-950/20 dark:border-amber-900",children:[e.jsx(Tt,{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(SM,{className:"h-6 w-6 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(It,{className:"text-lg",children:"Meta API Testing (Admin Only)"}),e.jsx(Jn,{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:[x.map(A=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border bg-background p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(zp,{className:"h-5 w-5 text-blue-600"}),e.jsx("span",{className:"font-medium",children:A.page_name||"Facebook Page"})]}),e.jsx(U,{size:"sm",variant:"outline",onClick:()=>S(A.id),disabled:i===A.id,children:i===A.id?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(SM,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-fb-${A.id}`)),y.map(A=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border bg-background p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(gm,{className:"h-5 w-5 text-pink-600"}),e.jsxs("span",{className:"font-medium",children:["@",A.platform_username||"Instagram"]})]}),e.jsx(U,{size:"sm",variant:"outline",onClick:()=>S(A.id),disabled:i===A.id,children:i===A.id?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(SM,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-ig-${A.id}`))]}),o&&o.length>0&&e.jsxs("div",{className:"mt-4 rounded-lg border bg-background p-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:"Test Results"}),e.jsx("div",{className:"space-y-2",children:o.map((A,T)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[A.status==="success"?e.jsx(zr,{className:"h-4 w-4 text-green-600 mt-0.5 shrink-0"}):A.status==="pending"?e.jsx(Et,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}):e.jsx(ou,{className:"h-4 w-4 text-red-600 mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("span",{className:"font-mono text-xs bg-muted px-1 rounded",children:A.test}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:A.details})]})]},T))})]}),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(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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 Ber(){const[s]=fc(),t=Wn(),[n,r]=j.useState("loading"),a=j.useRef(!1),[i,l]=j.useState("Processing your connection..."),[o,c]=j.useState(!1),d=(()=>{const u=sessionStorage.getItem("social-connect-return-to");return u&&u.startsWith("/")&&!u.startsWith("/admin")?u:"/social-connections"})();return j.useEffect(()=>{if(a.current)return;a.current=!0,(async()=>{var x;const h=s.get("code"),m=s.get("error"),p=s.get("error_description"),f=s.get("state");if(m){r("error"),l(p||"Authorization was denied"),re.error("Connection failed: "+(p||m));return}if(!h){r("error"),l("No authorization code received"),re.error("No authorization code received");return}try{const{data:y,error:v}=await q.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:h,state:f,callbackPath:"/social-connections/callback"}});if(v)throw v;if(y!=null&&y.success)r("success"),l(`Successfully connected ${((x=y.accounts)==null?void 0:x.length)||0} account(s)!`),re.success("Social accounts connected successfully!");else throw new Error((y==null?void 0:y.error)||"Unknown error")}catch(y){console.error("OAuth callback error:",y),r("error");const v=y instanceof Error?y.message:"Failed to connect accounts";l(v),/page/i.test(v)&&/(no|didn't|did not|zero|empty|return)/i.test(v)&&c(!0),re.error("Failed to connect: "+(y instanceof Error?y.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(we,{className:"w-full max-w-md",children:[e.jsxs(Tt,{className:"text-center",children:[n==="loading"&&e.jsx(Et,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Yo,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(ou,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(It,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Jn,{children:i})]}),e.jsxs(Ie,{className:"flex flex-col items-center gap-4",children:[n==="error"&&o&&e.jsxs("div",{className:"w-full rounded-lg border bg-muted/40 p-4 text-left text-sm space-y-3",children:[e.jsxs("p",{className:"font-medium text-foreground",children:["Meta didn't return any Pages — this almost always means your personal Facebook profile doesn't have"," ",e.jsx("span",{className:"font-semibold",children:"Full control"})," of your business Page yet."]}),e.jsxs("ol",{className:"list-decimal list-inside space-y-2 text-muted-foreground",children:[e.jsxs("li",{children:["Open"," ",e.jsxs("a",{href:"https://business.facebook.com/latest/settings/people",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline inline-flex items-center gap-1",children:["Meta Business Suite → Settings → People",e.jsx(Sr,{className:"h-3 w-3"})]})]}),e.jsxs("li",{children:["Select yourself, then under ",e.jsx("span",{className:"font-medium text-foreground",children:"Pages"})," assign your business Page."]}),e.jsxs("li",{children:["Turn on ",e.jsx("span",{className:"font-medium text-foreground",children:"Full control"})," (an Editor or Moderator role is not enough — Meta hides those Pages from apps)."]}),e.jsxs("li",{children:["Make sure you're logged into Facebook with the same personal profile that manages the Page, then click ",e.jsx("span",{className:"font-medium text-foreground",children:"Try Again"})," below."]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"When you reconnect, Meta's dialog should list your Page by name. If the list is still empty, the Page access change hasn't taken effect yet — wait a minute and retry."})]}),n!=="loading"&&e.jsx(U,{onClick:()=>t(d),children:n==="success"?"View Connected Accounts":"Try Again"})]})]})})}function Uer(){const[s]=fc(),t=Wn();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(Et,{className:"h-8 w-8 animate-spin text-primary"})})}function qer(){const[s]=fc(),t=Wn(),[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:p}=await q.functions.invoke("linkedin-oauth",{body:{action:"exchange_code",code:o,state:c,callbackPath:"/social-connections/linkedin-callback"}});if(p)throw p;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(we,{className:"w-full max-w-md",children:[e.jsxs(Tt,{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(Et,{className:"h-8 w-8 animate-spin text-blue-600"}),n==="success"&&e.jsx(Yo,{className:"h-8 w-8 text-green-600"}),n==="error"&&e.jsx(ou,{className:"h-8 w-8 text-red-600"})]}),e.jsxs(It,{className:"flex items-center justify-center gap-2",children:[e.jsx(Gg,{className:"h-5 w-5 text-blue-600"}),n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Jn,{children:a})]}),e.jsx(Ie,{className:"flex justify-center",children:e.jsx(U,{onClick:()=>t("/mission-control/integrations"),disabled:n==="loading",children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function $er(){const s=Wn(),[t,n]=j.useState(null),{data:r,isLoading:a}=Uts(t||void 0,!0),{data:i,isLoading:l}=_rt(!0),{cartItems:o}=bMe(),c=o.reduce((u,h)=>u+h.quantity,0),d=u=>{s(`/marketplace/${u.id}`)};return a||l?e.jsx(qs,{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(qs,{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(U,{variant:"outline",onClick:()=>s("/marketplace/cart"),className:"relative",children:[e.jsx(sS,{className:"h-4 w-4 mr-2"}),"Cart",c>0&&e.jsx(Be,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:c})]})]}),i&&i.length>0&&e.jsxs("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[e.jsx(U,{variant:t===null?"default":"outline",size:"sm",onClick:()=>n(null),children:"All"}),i.map(u=>e.jsx(U,{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(we,{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(dh,{className:"h-12 w-12 text-muted-foreground"})}),u.category&&e.jsx(Be,{className:"absolute top-2 left-2",variant:"secondary",children:u.category.name})]}),e.jsxs(Ie,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1 line-clamp-1",children:u.name}),u.description&&e.jsx("p",{className:"text-sm text-muted-foreground mb-2 line-clamp-2",children:u.description}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"font-bold text-lg",children:["$",Number(u.base_price).toFixed(2)]}),u.variants&&u.variants.length>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[u.variants.length," options"]})]})]})]},u.id)})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(dh,{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 gss=j.forwardRef(({...s},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...s}));gss.displayName="Breadcrumb";const xss=j.forwardRef(({className:s,...t},n)=>e.jsx("ol",{ref:n,className:Mt("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",s),...t}));xss.displayName="BreadcrumbList";const Q4e=j.forwardRef(({className:s,...t},n)=>e.jsx("li",{ref:n,className:Mt("inline-flex items-center gap-1.5",s),...t}));Q4e.displayName="BreadcrumbItem";const AKe=j.forwardRef(({asChild:s,className:t,...n},r)=>{const a=s?lZe:"a";return e.jsx(a,{ref:r,className:Mt("transition-colors hover:text-foreground",t),...n})});AKe.displayName="BreadcrumbLink";const yss=j.forwardRef(({className:s,...t},n)=>e.jsx("span",{ref:n,role:"link","aria-disabled":"true","aria-current":"page",className:Mt("font-normal text-foreground",s),...t}));yss.displayName="BreadcrumbPage";const EKe=({children:s,className:t,...n})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:Mt("[&>svg]:size-3.5",t),...n,children:s??e.jsx(gi,{})});EKe.displayName="BreadcrumbSeparator";function Ver(){var H,V;const{productId:s}=Di(),t=Wn(),{data:n,isLoading:r}=PQn(s||""),{addToCart:a,cartItems:i}=bMe(),[l,o]=j.useState(null),[c,d]=j.useState(1),[u,h]=j.useState(0),[m,p]=j.useState(null),[f,x]=j.useState(!1),[y,v]=j.useState(!1),b=(H=n==null?void 0:n.variants)==null?void 0:H.find(K=>K.id===l),N=((V=n==null?void 0:n.variants)==null?void 0:V.filter(K=>K.is_active))||[],S=Number((n==null?void 0:n.base_price)||0),A=b?Number(b.price_adjustment):0,T=S+A,L=Number((n==null?void 0:n.shipping_fee)||0),M=i.reduce((K,Z)=>K+Z.quantity,0),I=async K=>{if(!K.target.files||K.target.files.length===0)return;x(!0);const Z=K.target.files[0],Q=Z.name.split(".").pop(),le=`artwork/${Date.now()}-${Math.random().toString(36).substring(7)}.${Q}`;try{const{error:ue}=await q.storage.from("marketplace").upload(le,Z);if(ue)throw ue;const{data:{publicUrl:se}}=q.storage.from("marketplace").getPublicUrl(le);p(se),re.success("Artwork uploaded successfully")}catch(ue){re.error("Failed to upload artwork: "+ue.message)}finally{x(!1)}},R=()=>{if(n){if(N.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)}},z=()=>{n!=null&&n.images&&h(K=>(K+1)%n.images.length)},$=()=>{n!=null&&n.images&&h(K=>(K-1+n.images.length)%n.images.length)};return r?e.jsx(qs,{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(qs,{title:n.name,children:[e.jsx(gss,{className:"mb-6",children:e.jsxs(xss,{children:[e.jsx(Q4e,{children:e.jsx(AKe,{asChild:!0,children:e.jsx(xr,{to:"/marketplace",children:"Marketplace"})})}),n.category&&e.jsxs(e.Fragment,{children:[e.jsx(EKe,{}),e.jsx(Q4e,{children:e.jsx(AKe,{asChild:!0,children:e.jsx(xr,{to:`/marketplace?category=${n.category.id}`,children:n.category.name})})})]}),e.jsx(EKe,{}),e.jsx(Q4e,{children:e.jsx(yss,{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(U,{variant:"ghost",size:"icon",className:"absolute left-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:$,children:e.jsx(rd,{className:"h-6 w-6"})}),e.jsx(U,{variant:"ghost",size:"icon",className:"absolute right-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:z,children:e.jsx(gi,{className:"h-6 w-6"})})]})]}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(dh,{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((K,Z)=>e.jsx("button",{onClick:()=>h(Z),className:`w-16 h-16 flex-shrink-0 rounded-md overflow-hidden border-2 ${Z===u?"border-primary":"border-transparent"}`,children:e.jsx("img",{src:K.image_url,alt:"",className:"w-full h-full object-cover"})},K.id))}),n.video&&e.jsx(we,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-2",children:"Product Video"}),e.jsx("div",{className:"aspect-video",children:e.jsx("iframe",{src:n.video.video_url,className:"w-full h-full rounded-lg",allowFullScreen:!0})})]})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[n.category&&e.jsx(Be,{variant:"secondary",className:"mb-2",children:n.category.name}),e.jsx("h1",{className:"text-3xl font-bold mb-2",children:n.name}),e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-3xl font-bold",children:["$",T.toFixed(2)]}),L>0&&e.jsxs("span",{className:"text-muted-foreground",children:["+ $",L.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})}),N.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(te,{children:"Select Option"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:N.map(K=>e.jsxs(U,{variant:l===K.id?"default":"outline",onClick:()=>o(K.id),children:[K.name,Number(K.price_adjustment)!==0&&e.jsxs("span",{className:"ml-1 opacity-70",children:["(",Number(K.price_adjustment)>0?"+":"","$",Number(K.price_adjustment).toFixed(2),")"]})]},K.id))})]}),n.allow_artwork_upload&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(te,{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(U,{variant:"ghost",size:"sm",className:"absolute -top-2 -right-2",onClick:()=>p(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:I,className:"hidden",id:"artwork-upload",disabled:f}),e.jsxs("label",{htmlFor:"artwork-upload",className:"flex flex-col items-center cursor-pointer",children:[e.jsx(qa,{className:"h-8 w-8 text-muted-foreground mb-2"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:f?"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(te,{children:"Quantity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(U,{variant:"outline",size:"icon",onClick:()=>d(K=>Math.max(1,K-1)),children:"-"}),e.jsx(xe,{type:"number",value:c,onChange:K=>d(Math.max(1,parseInt(K.target.value)||1)),className:"w-20 text-center",min:"1"}),e.jsx(U,{variant:"outline",size:"icon",onClick:()=>d(K=>K+1),children:"+"})]})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsx(U,{size:"lg",className:"flex-1",onClick:R,disabled:y,children:y?e.jsxs(e.Fragment,{children:[e.jsx(Xr,{className:"h-5 w-5 mr-2"}),"Added!"]}):e.jsxs(e.Fragment,{children:[e.jsx(sS,{className:"h-5 w-5 mr-2"}),"Add to Cart"]})}),e.jsxs(U,{variant:"outline",size:"lg",onClick:()=>t("/marketplace/cart"),className:"relative",children:[e.jsx(sS,{className:"h-5 w-5"}),M>0&&e.jsx(Be,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:M})]})]}),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(qs,{title:"Product Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(dh,{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(U,{onClick:()=>t("/marketplace"),children:"Back to Marketplace"})]})})}function Her(){const s=Wn(),{cartItems:t,removeFromCart:n,updateQuantity:r,getItemPrice:a,getSubtotal:i,getShippingTotal:l,getTotal:o,clearCart:c}=bMe(),[d,u]=j.useState(!1),[h,m]=j.useState(""),p=async()=>{if(t.length===0){re.error("Your cart is empty");return}u(!0);try{const{data:f,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(f!=null&&f.url)c(),window.open(f.url,"_blank");else throw new Error("No checkout URL received")}catch(f){re.error("Checkout failed: "+f.message)}finally{u(!1)}};return t.length===0?e.jsx(qs,{title:"Shopping Cart",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(D4,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Your cart is empty"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"Add some products to get started!"}),e.jsx(U,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(qs,{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(f=>{var x,y;return e.jsx(we,{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:f.product.images&&f.product.images.length>0?e.jsx("img",{src:((x=f.product.images.find(v=>v.is_primary))==null?void 0:x.image_url)||f.product.images[0].image_url,alt:f.product.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(D4,{className:"h-8 w-8 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:f.product.name}),f.variant&&e.jsx("p",{className:"text-sm text-muted-foreground",children:f.variant.name}),e.jsxs("p",{className:"font-medium mt-1",children:["$",a(f).toFixed(2),Number(f.product.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:["+ $",Number(f.product.shipping_fee).toFixed(2)," shipping"]})]}),f.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(U,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{var v;return n(f.product.id,(v=f.variant)==null?void 0:v.id)},children:e.jsx(In,{className:"h-4 w-4 text-destructive"})}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(U,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var v;return r(f.product.id,(v=f.variant)==null?void 0:v.id,f.quantity-1)},disabled:f.quantity<=1,children:e.jsx(Z2,{className:"h-3 w-3"})}),e.jsx(xe,{type:"number",value:f.quantity,onChange:v=>{var b;return r(f.product.id,(b=f.variant)==null?void 0:b.id,parseInt(v.target.value)||1)},className:"w-14 h-8 text-center text-sm",min:"1"}),e.jsx(U,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var v;return r(f.product.id,(v=f.variant)==null?void 0:v.id,f.quantity+1)},children:e.jsx(an,{className:"h-3 w-3"})})]})]})]})})},`${f.product.id}-${((y=f.variant)==null?void 0:y.id)||"base"}`)}),e.jsx(U,{variant:"ghost",className:"text-destructive",onClick:c,children:"Clear Cart"})]}),e.jsx("div",{children:e.jsxs(we,{className:"sticky top-4",children:[e.jsx(Tt,{children:e.jsx(It,{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((f,x)=>f+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(hc,{}),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(hc,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"orderNotes",children:"Order Notes (Optional)"}),e.jsx(Fs,{id:"orderNotes",placeholder:"Add any special instructions, design notes, or comments for your order...",value:h,onChange:f=>m(f.target.value),rows:3,className:"resize-none"})]}),e.jsx(U,{className:"w-full",size:"lg",onClick:p,disabled:d,children:d?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-5 w-5 mr-2 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:["Checkout",e.jsx(Oa,{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 Ger(){const s=Wn(),{data:t,isLoading:n}=$Qn();return n?e.jsx(qs,{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(qs,{title:"My Orders",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(dh,{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(U,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(qs,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:t.map(r=>{var a,i,l;return e.jsx(we,{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:Gs(new Date(r.created_at),"MMM d, yyyy")})]}),e.jsx(Be,{className:brt[r.status],children:o$[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(U,{variant:"outline",size:"sm",onClick:o=>{o.stopPropagation(),window.open(r.tracking_url,"_blank")},children:[e.jsx(Sr,{className:"h-4 w-4 mr-1"}),"Track"]}),e.jsx(gi,{className:"h-5 w-5 text-muted-foreground"})]})]})]})},r.id)})})})}const KSt=["order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed"];function Wer({currentStatus:s,statusHistory:t}){const n=KSt.indexOf(s);return e.jsx("div",{className:"space-y-3",children:KSt.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(zr,{className:"h-4 w-4"}):o?e.jsx(Yr,{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:o$[r]}),i&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Gs(new Date(i.created_at),"MMM d, yyyy h:mm a"),i.notes&&` — ${i.notes}`]})]})]},r)})})}function Ker(){var v;const{orderId:s}=Di(),t=Wn(),{data:n,isLoading:r,refetch:a}=VQn(s||""),i=WQn(),l=KQn(),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(""),[p,f]=j.useState(null),x=async b=>{f(b);try{await i.mutateAsync({orderId:s,itemId:b}),re.success("Proof approved!"),a()}catch{re.error("Failed to approve proof")}finally{f(null)}},y=async()=>{if(d){f(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{f(null)}}};return r?e.jsx(qs,{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(qs,{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(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsx(It,{children:"Order Status"}),e.jsx(Be,{className:brt[n.status],children:o$[n.status]})]}),e.jsx(Ie,{children:e.jsx(Wer,{currentStatus:n.status,statusHistory:n.status_history})})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{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(kM,{className:"h-4 w-4"}),"View Artwork",e.jsx(Sr,{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(kM,{className:"h-4 w-4"}),"View Proof",e.jsx(Sr,{className:"h-3 w-3"})]}),b.proof_status==="pending"&&e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(U,{size:"sm",onClick:()=>x(b.id),disabled:p===b.id,children:[p===b.id?e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(wx,{className:"h-4 w-4 mr-1"}),"Approve"]}),e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>{u(b.id),c(!0)},disabled:p===b.id,children:[e.jsx(uQ,{className:"h-4 w-4 mr-1"}),"Request Changes"]})]}),b.proof_status==="approved"&&e.jsxs(Be,{className:"bg-green-100 text-green-800",children:[e.jsx(zr,{className:"h-3 w-3 mr-1"}),"Proof Approved"]}),b.proof_status==="rejected"&&b.proof_notes&&e.jsxs("div",{className:"mt-2",children:[e.jsx(Be,{variant:"destructive",className:"mb-2",children:"Revision Requested"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:b.proof_notes})]})]})]},b.id))})]}),n.shipping_name&&e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(hQ,{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(U,{variant:"link",className:"p-0 h-auto mt-1",onClick:()=>window.open(n.tracking_url,"_blank"),children:["Track Package",e.jsx(Sr,{className:"h-3 w-3 ml-1"})]})]})]})]})]}),e.jsx("div",{children:e.jsxs(we,{className:"sticky top-4",children:[e.jsx(Tt,{children:e.jsx(It,{children:"Order Summary"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Placed on ",Gs(new Date(n.created_at),"MMMM d, yyyy")]}),e.jsx(hc,{}),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(hc,{}),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(hc,{}),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(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Request Changes"}),e.jsx(Pr,{children:"Please describe what changes you'd like made to the proof."})]}),e.jsx(Fs,{placeholder:"Describe the changes needed...",value:h,onChange:b=>m(b.target.value),rows:4}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(U,{onClick:y,disabled:!h.trim()||p!==null,children:[p?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Submit Request"]})]})]})})]}):e.jsx(qs,{title:"Order Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(dh,{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(U,{onClick:()=>t("/marketplace/orders"),children:"View All Orders"})]})})}function Yer(){const s=Wn(),[t]=fc();return t.get("session_id"),j.useEffect(()=>{localStorage.removeItem("marketplace-cart")},[]),e.jsx(qs,{title:"Order Confirmed",children:e.jsx("div",{className:"max-w-lg mx-auto text-center py-8",children:e.jsx(we,{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(zr,{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(dh,{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(U,{className:"flex-1",onClick:()=>s("/marketplace/orders"),children:["View My Orders",e.jsx(Oa,{className:"h-4 w-4 ml-2"})]}),e.jsx(U,{variant:"outline",className:"flex-1",onClick:()=>s("/marketplace"),children:"Continue Shopping"})]})]})})})})}function Zer(){const{user:s}=vs(),[t,n]=j.useState("store"),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(!1),[d,u]=j.useState(5),[h,m]=j.useState(""),[p,f]=j.useState(!1),[x,y]=j.useState(!1),[v,b]=j.useState(""),[N,S]=j.useState(null),[A,T]=j.useState(!1),{hasSubmittedReview:L,submitReview:M,markPostedToGoogle:I}=S8t(),{data:R}=$ts(),{data:z,isLoading:$}=qts(),{data:H,isLoading:V}=tJn(r),{data:K,isLoading:Z}=sJn(s==null?void 0:s.id),{data:Q=0}=rJn(s==null?void 0:s.id),le=aJn(),ue=new Set((K==null?void 0:K.map(he=>he.item_id))||[]),se=async()=>{if(i)try{const he=await le.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(he){re.error(he.message||"Failed to purchase item")}},ne=async()=>{if(!h.trim()){re.error("Please write a review");return}f(!0);const he=await M(d,h);f(!1),he.success?(re.success("Thank you for your review! You earned 25 points!"),b(h),y(!0),m(""),u(5)):re.error(he.error||"Failed to submit review")},ie=()=>{navigator.clipboard.writeText(v),re.success("Review copied to clipboard!")},ce=()=>{I(),window.open("https://g.page/r/CT8bqTBTm7nJEBM/review","_blank")},je=()=>{y(!1),c(!1),b("")};return $||V||Z?e.jsx(qs,{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(he=>e.jsx(xn,{className:"h-64"},he))})]})}):e.jsxs(qs,{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(we,{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(Ua,{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:Q.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(Al,{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(Xd,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{children:"Streak bonuses add extra points!"})]})]})]})})}),e.jsx(ub,{open:A,onOpenChange:T,children:e.jsxs(we,{className:"border-primary/20",children:[e.jsx(hb,{asChild:!0,children:e.jsx(Tt,{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(Al,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(It,{className:"text-base",children:"How to Earn Points"}),e.jsx(Jn,{children:"See all the ways you can earn spendable points"})]})]}),A?e.jsx(dv,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(rl,{className:"h-5 w-5 text-muted-foreground"})]})})}),e.jsx(mb,{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:[R==null?void 0:R.filter(he=>he.is_active).map(he=>{const ge=ke=>{switch(ke){case"event_attendance":return e.jsx(pa,{className:"h-5 w-5"});case"leave_review":return e.jsx(Ua,{className:"h-5 w-5"});case"add_listing":return e.jsx(ra,{className:"h-5 w-5"});case"first_contact":return e.jsx(Bn,{className:"h-5 w-5"});case"first_video":return e.jsx(Wr,{className:"h-5 w-5"});case"first_community_post":return e.jsx(Ki,{className:"h-5 w-5"});default:return e.jsx(Ro,{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:ge(he.action_key)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:he.action_name}),he.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:he.description})]}),e.jsxs(Be,{variant:"secondary",className:"font-bold shrink-0",children:["+",he.points]})]},he.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(Xd,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:"Streak Bonuses"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Attend consecutive weeks for bonus points!"})]}),e.jsx(Be,{variant:"outline",className:"font-bold shrink-0 border-orange-500/50 text-orange-600",children:"+Bonus"})]})]})})})]})}),!L&&e.jsx(we,{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(Ki,{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(U,{onClick:()=>c(!0),className:"bg-yellow-600 hover:bg-yellow-700",children:[e.jsx(Ua,{className:"h-4 w-4 mr-2"}),"Leave Review"]})]})})}),e.jsxs(oa,{value:t,onValueChange:n,children:[e.jsxs(la,{children:[e.jsxs(Kt,{value:"store",className:"flex items-center gap-2",children:[e.jsx(D4,{className:"h-4 w-4"}),"Store"]}),e.jsxs(Kt,{value:"my-rewards",className:"flex items-center gap-2",children:[e.jsx(dh,{className:"h-4 w-4"}),"My Rewards",K&&K.length>0&&e.jsx(Be,{variant:"secondary",className:"ml-1",children:K.length})]})]}),e.jsxs(Zt,{value:"store",className:"mt-6",children:[z&&z.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[e.jsx(U,{variant:r===null?"default":"outline",size:"sm",onClick:()=>a(null),children:"All"}),z.map(he=>e.jsxs(U,{variant:r===he.id?"default":"outline",size:"sm",onClick:()=>a(he.id),children:[he.icon&&`${he.icon} `,he.name]},he.id))]}),!H||H.length===0?e.jsx(we,{children:e.jsx(Ie,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Ro,{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:H.map(he=>{const ge=he.item_type==="reelflow_credits",ke=!ge&&ue.has(he.id),Te=!ge&&he.max_quantity!==null&&he.current_quantity===0,Me=Q>=he.points_cost;return e.jsxs(we,{className:`overflow-hidden transition-all cursor-pointer hover:shadow-lg ${ke?"ring-2 ring-green-500/50 bg-green-500/5":""}`,onClick:()=>S(he),children:[he.preview_image_url?e.jsxs("div",{className:"aspect-video relative overflow-hidden bg-muted",children:[e.jsx("img",{src:he.preview_image_url,alt:he.name,className:"w-full h-full object-cover"}),ke&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Be,{className:"bg-green-500 text-white",children:[e.jsx(zr,{className:"h-3 w-3 mr-1"}),"Owned"]})}),Te&&!ke&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(Be,{variant:"destructive",children:"Sold Out"})})]}):e.jsxs("div",{className:"aspect-video bg-muted flex items-center justify-center relative",children:[e.jsx(Ro,{className:"h-12 w-12 text-muted-foreground/50"}),ke&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Be,{className:"bg-green-500 text-white",children:[e.jsx(zr,{className:"h-3 w-3 mr-1"}),"Owned"]})})]}),e.jsxs(Tt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx(It,{className:"text-lg",children:he.name}),e.jsxs(Be,{variant:"secondary",className:"font-bold shrink-0",children:[e.jsx(Ua,{className:"h-3 w-3 mr-1"}),he.points_cost]})]}),he.category&&e.jsxs(Be,{variant:"outline",className:"w-fit",children:[he.category.icon&&`${he.category.icon} `,he.category.name]})]}),e.jsxs(Ie,{children:[e.jsx(Jn,{className:"mb-4 line-clamp-2",children:he.description||"No description available"}),he.max_quantity!==null&&!ke&&!ge&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:[he.current_quantity," of ",he.max_quantity," remaining"]}),ge&&e.jsxs("p",{className:"text-xs text-violet-600 font-medium mb-3",children:["🎬 Grants ",he.max_quantity," ReelFlow credits per purchase"]}),ke?e.jsx(U,{className:"w-full",onClick:Oe=>{Oe.stopPropagation(),he.file_url&&xze(he.file_url,he.name)},disabled:!he.file_url,children:he.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(pi,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Sr,{className:"h-4 w-4 mr-2"}),"Access"]})}):e.jsx(U,{className:"w-full",onClick:Oe=>{Oe.stopPropagation(),l(he)},disabled:Te||!Me,children:Te?"Sold Out":Me?e.jsxs(e.Fragment,{children:[e.jsx(D4,{className:"h-4 w-4 mr-2"}),"Purchase"]}):`Need ${he.points_cost-Q} more pts`})]})]},he.id)})})]}),e.jsx(Zt,{value:"my-rewards",className:"mt-6",children:!K||K.length===0?e.jsx(we,{children:e.jsx(Ie,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(dh,{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:K.map(he=>{var ge,ke,Te,Me,Oe,Se,Qe;return e.jsxs(we,{className:"overflow-hidden",children:[(ge=he.item)!=null&&ge.preview_image_url?e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted",children:e.jsx("img",{src:he.item.preview_image_url,alt:((ke=he.item)==null?void 0:ke.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(Ro,{className:"h-12 w-12 text-muted-foreground/50"})}),e.jsxs(Tt,{className:"pb-2",children:[e.jsx(It,{className:"text-lg",children:((Te=he.item)==null?void 0:Te.name)||"Unknown Item"}),e.jsxs(Jn,{className:"text-xs",children:["Purchased for ",he.points_spent," points • ",new Date(he.purchased_at).toLocaleDateString()]})]}),e.jsx(Ie,{children:((Me=he.item)==null?void 0:Me.item_type)==="reelflow_credits"?e.jsxs(U,{className:"w-full",variant:"outline",disabled:!0,children:[e.jsx(zr,{className:"h-4 w-4 mr-2 text-green-500"}),(Oe=he.item)==null?void 0:Oe.max_quantity," Credits Applied"]}):e.jsx(U,{className:"w-full",onClick:()=>{var Ae,Fe;(Ae=he.item)!=null&&Ae.file_url&&xze(he.item.file_url,(Fe=he.item)==null?void 0:Fe.name)},disabled:!((Se=he.item)!=null&&Se.file_url),children:((Qe=he.item)==null?void 0:Qe.item_type)==="file"?e.jsxs(e.Fragment,{children:[e.jsx(pi,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Sr,{className:"h-4 w-4 mr-2"}),"Access"]})})})]},he.id)})})})]})]}),e.jsx(Fl,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Confirm Purchase"}),e.jsxs(Ll,{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:[Q," points"]}),". After this purchase, you'll have"," ",e.jsxs("strong",{children:[Q-((i==null?void 0:i.points_cost)||0)," points"]})," remaining."]})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:se,disabled:le.isPending,children:le.isPending?"Purchasing...":"Confirm Purchase"})]})]})}),e.jsx(zs,{open:o,onOpenChange:he=>{!he&&x?je():c(he)},children:e.jsx(Ds,{children:x?e.jsxs(e.Fragment,{children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(zr,{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(U,{variant:"outline",className:"w-full",onClick:ie,children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Copy Review to Clipboard"]})]}),e.jsxs(Mr,{className:"flex-col sm:flex-row gap-2",children:[e.jsx(U,{variant:"outline",onClick:je,children:"Maybe Later"}),e.jsxs(U,{onClick:ce,className:"bg-blue-600 hover:bg-blue-700",children:[e.jsx(Sr,{className:"h-4 w-4 mr-2"}),"Leave Google Review"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Vs,{children:[e.jsx($s,{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(he=>e.jsx("button",{type:"button",onClick:()=>u(he),className:"focus:outline-none",children:e.jsx(Ua,{className:`h-8 w-8 transition-colors ${d>=he?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-yellow-400"}`})},he))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Your Review"}),e.jsx(Fs,{placeholder:"What do you love about LevelUp? How has it helped your business?",value:h,onChange:he=>m(he.target.value),rows:4})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(U,{onClick:ne,disabled:p,className:"bg-yellow-600 hover:bg-yellow-700",children:p?"Submitting...":"Submit & Earn 25 Points"})]})]})})}),e.jsx(zs,{open:!!N,onOpenChange:()=>S(null),children:e.jsxs(Ds,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[N==null?void 0:N.name,e.jsxs(Be,{variant:"secondary",className:"font-bold",children:[e.jsx(Ua,{className:"h-3 w-3 mr-1"}),N==null?void 0:N.points_cost]})]}),(N==null?void 0:N.category)&&e.jsxs(Be,{variant:"outline",className:"w-fit",children:[N.category.icon&&`${N.category.icon} `,N.category.name]})]}),(N==null?void 0:N.preview_image_url)&&e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted rounded-lg",children:e.jsx("img",{src:N.preview_image_url,alt:N.name,className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:(N==null?void 0:N.description)||"No description available"}),(N==null?void 0:N.item_type)==="reelflow_credits"&&e.jsxs("p",{className:"text-sm text-violet-600 font-medium",children:["🎬 Grants ",N==null?void 0:N.max_quantity," ReelFlow credits per purchase"]}),(N==null?void 0:N.item_type)!=="reelflow_credits"&&(N==null?void 0:N.max_quantity)!==null&&!ue.has((N==null?void 0:N.id)||"")&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[N==null?void 0:N.current_quantity," of ",N==null?void 0:N.max_quantity," remaining"]})]}),e.jsx(Mr,{children:N&&N.item_type!=="reelflow_credits"&&ue.has(N.id)?e.jsx(U,{className:"w-full",onClick:()=>{N.file_url&&xze(N.file_url,N.name)},disabled:!N.file_url,children:N.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(pi,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Sr,{className:"h-4 w-4 mr-2"}),"Access"]})}):N&&e.jsx(U,{className:"w-full",onClick:()=>{S(null),l(N)},disabled:N.item_type!=="reelflow_credits"&&N.max_quantity!==null&&N.current_quantity===0||Q{s&&Z()},[s==null?void 0:s.id]);const Z=async()=>{if(!s)return;o(!0),v(!1),x(!0);const{data:Oe}=await q.from("point_reward_settings").select("action_key, points").in("action_key",["referral_signup","referral_paid"]);Oe==null||Oe.forEach(Fe=>{Fe.action_key==="referral_signup"&&h(Fe.points),Fe.action_key==="referral_paid"&&p(Fe.points)});const{data:Se}=await q.from("profiles").select("name").eq("id",s.id).maybeSingle();Se!=null&&Se.name&&N(Se.name);let{data:Qe}=await q.from("agent_referral_codes").select("code").eq("user_id",s.id).maybeSingle();if(!Qe){const{data:Fe}=await q.rpc("generate_agent_referral_code",{_user_id:s.id}),Ne=Fe||`agent${s.id.slice(0,6)}`,{data:$e,error:Ve}=await q.from("agent_referral_codes").insert({user_id:s.id,code:Ne}).select("code").maybeSingle();!Ve&&$e&&(Qe=$e)}i((Qe==null?void 0:Qe.code)??null);const{data:Ae}=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(Ae&&Ae.length>0){const Fe=Ae.map(Ve=>Ve.referred_user_id),{data:Ne}=await q.from("profiles").select("id, name, email").in("id",Fe),$e=new Map((Ne==null?void 0:Ne.map(Ve=>[Ve.id,Ve]))??[]);d(Ae.map(Ve=>({...Ve,referred_profile:$e.get(Ve.referred_user_id)??null})))}else d([]);o(!1)},Q=j.useMemo(()=>a?`${Xer}/trial?ref=${a}`:"",[a]),le=c.length,ue=c.filter(Oe=>Oe.status==="qualified").length,se=c.filter(Oe=>Oe.signup_points_awarded).length*u+c.filter(Oe=>Oe.paid_points_awarded).length*m,ne=async()=>{Q&&(await navigator.clipboard.writeText(Q),re.success("Referral link copied!"))},ie=()=>{const Oe=encodeURIComponent("Join me on LevelUp"),Se=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: ${Q} Let me know if you have any questions!`);window.location.href=`mailto:?subject=${Oe}&body=${Se}`},ce=()=>{const Oe=encodeURIComponent(`Hey! I think you'd love LevelUp for your business — sign up with my link: ${Q}`);window.location.href=`sms:?&body=${Oe}`},je=async()=>{if(navigator.share&&Q)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:Q})}catch{}else ne()},be=Oe=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Oe.trim()),he=Oe=>{const Se=(Oe??T).trim().replace(/,$/,"");if(!Se)return;const Qe=Se.split(/[\s,;]+/).filter(Boolean),Ae=[...M];let Fe=0;for(const Ne of Qe){if(!be(Ne)){re.error(`Invalid email: ${Ne}`);continue}Ae.includes(Ne)||(Ae.push(Ne),Fe++)}I(Ae),Fe>0&&L("")},ge=Oe=>I(M.filter(Se=>Se!==Oe)),ke=()=>{H(`${b?b.split(" ")[0]+" invited you to":"Join me on"} LevelUp`),z("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)},Te=Oe=>{const Se=Oe.replace(/&/g,"&").replace(//g,">").replace(/\n/g,"
"),Qe=b||"A fellow agent",Ae="https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/levelup-logo-email.png",Fe=Q;return`
LevelUp
You're Invited

${Qe} thinks you'd love LevelUp 🎉

${Se}

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

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

`.trim()},Me=async()=>{if(M.length===0&&(T.trim()&&he(),M.length===0)){re.error("Add at least one recipient");return}if(!$.trim()){re.error("Subject is required");return}K(!0);const Oe=Te(R);let Se=0,Qe=0;for(const Ae of M)try{const{data:Fe,error:Ne}=await q.functions.invoke("gmail-send",{body:{to:Ae,subject:$,body:Oe,source:"referral_invite"}});if(Ne||Fe!=null&&Fe.error)throw new Error((Ne==null?void 0:Ne.message)||(Fe==null?void 0:Fe.error));Se++}catch(Fe){console.error("Gmail send failed for",Ae,Fe),Qe++}K(!1),Se>0?(re.success(`Invite sent to ${Se} ${Se===1?"person":"people"}`+(Qe>0?` (${Qe} failed)`:"")),I([]),L(""),A(!1)):re.error("Failed to send invites")};return!y&&!f?e.jsx(qs,{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(we,{className:"border-2 border-dashed",children:[e.jsxs(Tt,{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(Ql,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx(It,{children:"Refer & Earn is for active members"}),e.jsx(Jn,{children:"Activate your subscription to unlock your personal referral link and start earning points."})]}),e.jsx(Ie,{className:"flex justify-center",children:e.jsx(U,{onClick:()=>t("/subscription"),children:"View Subscription"})})]})]})}):e.jsxs(qs,{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(Ro,{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(we,{children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx(Bn,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:le}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Friends signed up"})]})]})}),e.jsx(we,{children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx(zr,{className:"h-5 w-5 text-emerald-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ue}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Activated paid plan"})]})]})}),e.jsx(we,{children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx(Al,{className:"h-5 w-5 text-amber-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:se.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Points earned"})]})]})})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(cn,{className:"h-5 w-5 text-primary"}),"Your referral link"]}),e.jsx(Jn,{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(xe,{readOnly:!0,value:l?"Loading…":Q,className:"font-mono text-sm",onFocus:Oe=>Oe.currentTarget.select()}),e.jsxs(U,{onClick:ne,disabled:!Q,children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"}),"Copy link"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[n&&e.jsxs(U,{size:"sm",onClick:ke,disabled:!Q,className:"bg-primary hover:bg-primary/90",children:[e.jsx($r,{className:"h-4 w-4 mr-2"})," Send via Gmail"]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:ie,disabled:!Q,children:[e.jsx(ln,{className:"h-4 w-4 mr-2"})," Email"]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:ce,disabled:!Q,children:[e.jsx(Ki,{className:"h-4 w-4 mr-2"})," Text"]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:je,disabled:!Q,children:[e.jsx(jd,{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(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"Your Referrals"}),e.jsx(Jn,{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(Bn,{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(Oe=>{var Ae,Fe;const Se=((Ae=Oe.referred_profile)==null?void 0:Ae.name)||((Fe=Oe.referred_profile)==null?void 0:Fe.email)||"New agent",Qe=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(Oe.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:Se}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Joined ",Qe]})]}),Oe.status==="qualified"?e.jsxs(Be,{className:"bg-emerald-100 text-emerald-700 border-emerald-200 hover:bg-emerald-100",children:[e.jsx(zr,{className:"h-3 w-3 mr-1"})," Paid · +",u+m," pts"]}):e.jsxs(Be,{variant:"secondary",children:[e.jsx(Yr,{className:"h-3 w-3 mr-1"})," Signed up · +",u," pts"]})]},Oe.id)})})})]}),e.jsx(we,{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(cn,{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(hc,{className:"opacity-0"})]}),e.jsx(zs,{open:S,onOpenChange:A,children:e.jsxs(Ds,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx($r,{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(te,{children:"Recipients"}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 p-2 border rounded-md min-h-[44px] bg-background",children:[M.map(Oe=>e.jsxs(Be,{variant:"secondary",className:"gap-1 pr-1",children:[Oe,e.jsx("button",{type:"button",onClick:()=>ge(Oe),className:"hover:bg-muted-foreground/20 rounded-full p-0.5","aria-label":`Remove ${Oe}`,children:e.jsx(er,{className:"h-3 w-3"})})]},Oe)),e.jsx("input",{type:"email",value:T,onChange:Oe=>L(Oe.target.value),onKeyDown:Oe=>{Oe.key==="Enter"||Oe.key===","||Oe.key===" "?(Oe.preventDefault(),he()):Oe.key==="Backspace"&&!T&&M.length>0&&I(M.slice(0,-1))},onBlur:()=>T.trim()&&he(),onPaste:Oe=>{const Se=Oe.clipboardData.getData("text");/[\s,;]/.test(Se)&&(Oe.preventDefault(),he(Se))},placeholder:M.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(te,{htmlFor:"email-subject",children:"Subject"}),e.jsx(xe,{id:"email-subject",value:$,onChange:Oe=>H(Oe.target.value),placeholder:"Subject line"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"personal-note",children:"Your personal note"}),e.jsx(Fs,{id:"personal-note",value:R,onChange:Oe=>z(Oe.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(te,{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: ",$||"(no subject)"]})]}),e.jsx("iframe",{title:"Email preview",srcDoc:Te(R),className:"w-full h-[420px] bg-white"})]})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>A(!1),disabled:V,children:"Cancel"}),e.jsxs(U,{onClick:Me,disabled:V,children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),V?"Sending…":`Send${M.length>0?` to ${M.length}`:""}`]})]})]})})]})}const vss=()=>{const{user:s}=vs(),t=Qt(),n=ct({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=ct({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=yt({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=yt({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=yt({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=yt({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=yt({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}},Jer=()=>{const s=Wn(),{presentations:t,isLoading:n,archivePresentation:r,saveAsTemplate:a}=vss(),i=o=>o.status==="draft"?e.jsx(Be,{variant:"outline",className:"text-xs",children:"Draft"}):o.view_count>1?e.jsx(Be,{className:"text-xs bg-emerald-100 text-emerald-700 border-emerald-200",children:"Revisited"}):o.view_count===1?e.jsx(Be,{className:"text-xs bg-blue-100 text-blue-700 border-blue-200",children:"Opened"}):e.jsx(Be,{variant:"secondary",className:"text-xs",children:"Not Opened"}),l=o=>{const c=`https://presentations.relevelup.com/${o}`;navigator.clipboard.writeText(c),re.success("Link copied!")};return e.jsx(qs,{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(U,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(an,{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(we,{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(hv,{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(U,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(an,{className:"h-4 w-4"}),"Create Your First Presentation"]})]})}):e.jsx("div",{className:"space-y-3",children:t.map(o=>e.jsx(we,{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(Ur,{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 ",Gs(new Date(o.created_at),"MMM d, yyyy")]}),o.view_count>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(xa,{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(U,{variant:"outline",size:"sm",onClick:()=>l(o.share_token),children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1"}),"Copy Link"]}),o.status==="published"&&e.jsx(U,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}?edit=true`),children:"Edit"}),e.jsx(U,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}`),children:o.status==="draft"?"Edit":"View"}),e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(ey,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",children:[o.status==="published"&&o.share_token&&e.jsxs(La,{onClick:()=>window.open(`https://presentations.relevelup.com/${o.share_token}`,"_blank"),children:[e.jsx(Sr,{className:"h-4 w-4 mr-2"}),"Preview Link"]}),e.jsxs(La,{onClick:()=>a.mutate(o),children:[e.jsx(Ur,{className:"h-4 w-4 mr-2"}),"Save as Template"]}),e.jsxs(La,{onClick:()=>r.mutate(o.id),className:"text-destructive",children:[e.jsx(n1,{className:"h-4 w-4 mr-2"}),"Archive"]})]})]})]})]})})]})})},o.id))})]})})},YSt={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."}]},etr=[{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 ttr(s){const t=YSt[s];if(t)return t;const n=s.toLowerCase();for(const[r,a]of Object.entries(YSt))if(n.includes(r.toLowerCase())||r.toLowerCase().includes(n))return a;return etr}function str({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}=nWt(),m=f3(),[p,f]=j.useState(""),[x,y]=j.useState(!1),[v,b]=j.useState(!0),[N,S]=j.useState(!1),[A,T]=j.useState(null),L=ttr(s),M=()=>{l("script"),c(0),u(0),f(""),y(!1),b(!0),S(!1),T(null)},I=V=>{!V&&(i==="uploading"||i==="processing")||(a(V),V||M())},R=V=>{T(V),f(L[V].text),y(!1)},z=()=>{l("record"),b(p.trim().length>0)},$=()=>{f(""),b(!1),l("record")},H=j.useCallback(async(V,K)=>{l("uploading");try{const Z=s||"Presentation Video",{videoId:Q,uploadUrl:le,libraryId:ue}=await cL(Z),{apiKey:se}=await dL(Q),ne=new XMLHttpRequest;ne.upload.onprogress=he=>{he.lengthComputable&&c(he.loaded/he.total*100)},await new Promise((he,ge)=>{ne.onload=()=>ne.status>=200&&ne.status<300?he():ge(new Error("Upload failed")),ne.onerror=()=>ge(new Error("Upload failed")),ne.open("PUT",le),ne.setRequestHeader("AccessKey",se),ne.send(V)}),l("processing");let ie=0;const ce=Date.now(),je=9e4;let be=null;for(;ie<4;){if(await new Promise(ge=>setTimeout(ge,3e3)),Date.now()-ce>je){const ge=V.size/1048576,ke=`https://iframe.mediadelivery.net/embed/${ue}/${Q}?responsive=true`;await m.mutateAsync({bunny_video_id:Q,playback_url:ke,file_size_mb:ge,title:Z,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(ke),re.success("Video saved — still encoding. It will be ready shortly."),l("done"),setTimeout(()=>a(!1),1500);return}const he=await fN(Q);if(ie=he.status,u(he.encodeProgress||0),ie===4)be={playbackUrl:he.directPlayUrl,thumbnailUrl:he.thumbnailUrl,previewUrl:he.previewUrl||null,duration:he.length||K,fileSizeMb:(he.storageSize||V.size)/(1024*1024)};else if(ie===5||ie===6)throw new Error("Video processing failed")}if(!be)throw new Error("No video data");await m.mutateAsync({bunny_video_id:Q,contact_id:t||void 0,playback_url:be.playbackUrl,thumbnail_url:be.thumbnailUrl,preview_url:be.previewUrl,duration_seconds:be.duration,file_size_mb:be.fileSizeMb,title:Z,status:"ready",touch_type:"presentation"}),n(be.playbackUrl),re.success("Video recorded, saved to library & attached!"),l("done"),setTimeout(()=>a(!1),1500)}catch(Z){console.error("Recording upload error:",Z),re.error("Failed to process video. Please try again."),l("record")}},[s,t,n,m]);return e.jsxs(zs,{open:r,onOpenChange:I,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Record a video",children:[e.jsx(Wr,{className:"h-3.5 w-3.5"}),"Record"]})}),e.jsxs(Ds,{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(Vs,{children:e.jsxs($s,{children:[i==="script"&&`Prepare your script for "${s}"`,i==="record"&&`Record video for "${s}"`,i==="uploading"&&"Uploading...",i==="processing"&&"Processing...",i==="done"&&"Done!"]})}),i==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose a starter script below, edit it to make it yours, or skip and speak freely."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Starter Scripts"}),e.jsx("div",{className:"grid gap-2",children:L.map((V,K)=>e.jsxs("button",{onClick:()=>R(K),className:Mt("text-left p-3 rounded-lg border transition-all hover:bg-accent/50",A===K?"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(Ur,{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})]},K))})]}),p&&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(U,{variant:"ghost",size:"sm",onClick:()=>y(!0),className:"h-7 text-xs gap-1",children:[e.jsx(ri,{className:"h-3 w-3"}),"Edit"]})]}),x?e.jsx(Fs,{value:p,onChange:V=>f(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:p})]}),!p&&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(Fs,{value:p,onChange:V=>{f(V.target.value),T(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(U,{variant:"ghost",size:"sm",onClick:$,className:"text-muted-foreground",children:"Skip — no teleprompter"}),e.jsx(U,{onClick:z,disabled:!1,children:p.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(tc,{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."}),p.trim()&&e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>b(!v),className:"h-7 text-xs gap-1",children:[v?e.jsx(Vg,{className:"h-3 w-3"}):e.jsx(xa,{className:"h-3 w-3"}),v?"Hide Script":"Show Script"]})]}),e.jsx(kE,{maxDurationSeconds:600,onRecordingComplete:H,onRecordingStateChange:S,onError:V=>re.error(V),teleprompterContent:p.trim()?e.jsx(Pnt,{text:p,isVisible:v,onToggleVisibility:()=>b(!v),isRecording:N,startCountdown:!1}):void 0}),e.jsx(U,{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(Et,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(ro,{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(Et,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(ro,{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(Yo,{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 ntr({sectionTitle:s,contactId:t,onVideoReady:n}){const[r,a]=j.useState(!1),[i,l]=j.useState(null),[o,c]=j.useState("idle"),[d,u]=j.useState(0),h=j.useRef(null),m=f3(),{data:p}=VLe(),f=(p==null?void 0:p.total_storage_mb)||0,y=((p==null?void 0:p.max_storage_mb)||1024)-f,v=()=>{l(null),c("idle"),u(0)},b=L=>{!L&&o!=="idle"&&o!=="done"||(a(L),L||v())},N=L=>{var R;const M=(R=L.target.files)==null?void 0:R[0];if(!M)return;if(!M.type.startsWith("video/")){re.error("Please select a video file");return}const I=M.size/(1024*1024);if(I>500){re.error("Video file must be less than 500MB");return}if(I>y){re.error(`Not enough storage. You have ${y.toFixed(1)} MB remaining.`);return}l(M)},S=j.useCallback(async()=>{if(i){c("creating"),u(0);try{const L=s||i.name,{data:M,error:I}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:L,isAgentVideo:!0}});if(I)throw new Error(I.message);const{videoId:R,libraryId:z}=M;c("uploading");const{data:$,error:H}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:R,isAgentVideo:!0}});if(H)throw new Error(H.message);await new Promise((Z,Q)=>{const le=new XMLHttpRequest;le.upload.addEventListener("progress",ue=>{ue.lengthComputable&&u(Math.round(ue.loaded/ue.total*100))}),le.addEventListener("load",()=>le.status>=200&&le.status<300?Z():Q(new Error(`Upload failed (${le.status})`))),le.addEventListener("error",()=>Q(new Error("Upload failed"))),le.open("PUT",$.uploadUrl),le.setRequestHeader("AccessKey",$.apiKey),le.send(i)}),c("processing");const V=i.size/(1024*1024),K=`https://iframe.mediadelivery.net/embed/${z}/${R}`;await m.mutateAsync({bunny_video_id:R,playback_url:K,file_size_mb:V,title:L,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(K),c("done"),re.success("Video uploaded & attached to section!"),setTimeout(()=>a(!1),1200)}catch(L){console.error("Upload error:",L),re.error(L instanceof Error?L.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""}},T=o!=="idle"&&o!=="done";return e.jsxs(zs,{open:r,onOpenChange:b,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Upload a video file",children:[e.jsx(qa,{className:"h-3.5 w-3.5"}),"Upload"]})}),e.jsxs(Ds,{className:"sm:max-w-md",children:[e.jsx(Vs,{children:e.jsxs($s,{children:['Upload Video for "',s,'"']})}),e.jsxs("div",{className:"space-y-4 py-2",children:[i?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(Wr,{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"]})]}),!T&&e.jsx(U,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(null),children:e.jsx(er,{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 L;return(L=h.current)==null?void 0:L.click()},children:[e.jsx(qa,{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:N,disabled:T}),T&&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(Et,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:A()})]}),e.jsx(ro,{value:o==="uploading"?d:o==="processing"?100:10})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>b(!1),disabled:T,children:"Cancel"}),e.jsx(U,{onClick:S,disabled:!i||T,children:T?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qa,{className:"h-4 w-4 mr-2"}),"Upload & Attach"]})})]})]})]})}const ZSt=[{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"}],XSt=()=>{const s=Wn(),{id:t}=Di(),{user:n}=vs(),{templates:r,templatesLoading:a,createPresentation:i,updatePresentation:l,publishPresentation:o}=vss(),{isGmailConnected:c,gmailEmail:d}=Ax(),[u,h]=j.useState(!1),[m,p]=j.useState("client"),[f,x]=j.useState(!1),[y,v]=j.useState(""),[b,N]=j.useState([]),[S,A]=j.useState(!1),[T,L]=j.useState(null),[M,I]=j.useState(!1),[R,z]=j.useState(""),[$,H]=j.useState(""),[V,K]=j.useState(""),[Z,Q]=j.useState("buyer"),[le,ue]=j.useState(""),[se,ne]=j.useState(null),[ie,ce]=j.useState(""),[je,be]=j.useState([]),[he,ge]=j.useState("schedule_call"),[ke,Te]=j.useState("Schedule a Call"),[Me,Oe]=j.useState(""),[Se,Qe]=j.useState(""),[Ae,Fe]=j.useState(null),[Ne,$e]=j.useState(t||null),[Ve,qe]=j.useState(null),[Ze,Ue]=j.useState(!1),Ye=async(vt,Ws)=>{if(!n)return;const on=5*1024*1024;if(vt.size>on){re.error("Image must be under 5MB");return}if(!vt.type.startsWith("image/")){re.error("Please upload an image file");return}Fe(Ws);try{const Ms=vt.name.split(".").pop()||"jpg",dn=`${n.id}/${Date.now()}.${Ms}`,{error:rn}=await q.storage.from("listing-photos").upload(dn,vt);if(rn)throw rn;const{data:{publicUrl:br}}=q.storage.from("listing-photos").getPublicUrl(dn);qt(Ws,{image_url:br}),re.success("Image uploaded")}catch{re.error("Failed to upload image")}finally{Fe(null)}};j.useEffect(()=>{t&&Ge(t)},[t]);const Ge=async vt=>{const{data:Ws,error:on}=await q.from("smart_presentations").select("*").eq("id",vt).single();if(on||!Ws)return;const Ms=Ws;if(x(!0),ce(Ms.title),z(Ms.client_name||""),ue(Ms.property_address||""),be(Ms.sections||[]),ge(Ms.cta_type||"schedule_call"),Te(Ms.cta_label||"Schedule a Call"),Oe(Ms.cta_url||""),Qe(Ms.heading||""),qe(Ms.share_token),Ue(Ms.status==="published"),$e(Ms.id),p("builder"),Ms.contact_id){const{data:dn}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("id",Ms.contact_id).maybeSingle();dn&&(L(dn),H(dn.email||""),K(dn.phone||""))}};j.useEffect(()=>{if(!n||y.length<1){N([]);return}const vt=setTimeout(async()=>{A(!0);const{data:Ws}=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);N(Ws||[]),A(!1)},300);return()=>clearTimeout(vt)},[y,n]);const He=vt=>{L(vt),z(`${vt.first_name} ${vt.last_name||""}`.trim()),H(vt.email||""),K(vt.phone||""),I(!1)},tt=async()=>{if(!R.trim()){re.error("Client name is required");return}const vt=R.trim().split(" "),Ws=vt[0],on=vt.slice(1).join(" ")||null,{data:Ms,error:dn}=await q.from("innercircle_contacts").insert({owner_user_id:n.id,first_name:Ws,last_name:on,email:$||null,phone:V||null,lead_source:"Smart Presentation"}).select().single();if(dn){re.error("Failed to create client");return}L(Ms),re.success("Client created & saved to Agent OS"),p("template")},pt=vt=>{ne(vt);const Ws=(vt.sections||[]).map(on=>({...on,is_visible:!0,video_url:"",text:""}));if(be(Ws),ce(vt.name+(R?` for ${R}`:"")),vt.cta_config){const on=vt.cta_config;ge(on.type||"schedule_call"),Te(on.label||"Schedule a Call")}p("builder")},ft=()=>{be([{title:"Welcome",description:"A personal welcome",type:"video",icon:"👋",is_visible:!0}]),ce(R?`Presentation for ${R}`:"New Presentation"),p("builder")},qt=(vt,Ws)=>{be(on=>on.map((Ms,dn)=>dn===vt?{...Ms,...Ws}:Ms))},Ut=vt=>{qt(vt,{is_visible:!je[vt].is_visible})},Wt=()=>{be(vt=>[...vt,{title:"New Section",description:"",type:"video",icon:"📝",is_visible:!0}])},us=vt=>{be(Ws=>Ws.filter((on,Ms)=>Ms!==vt))},zt=async()=>{if(!ie.trim()){re.error("Title is required");return}try{if(Ne){const vt=await l.mutateAsync({id:Ne,title:ie,sections:je,client_name:R,property_address:le||null,cta_type:he,cta_label:ke,cta_url:Me||null,heading:Se||null});re.success("Saved")}else{const vt=await i.mutateAsync({title:ie,contact_id:(T==null?void 0:T.id)||void 0,client_name:R,property_address:le||void 0,template_id:(se==null?void 0:se.id)||void 0,sections:je,cta_type:he,cta_label:ke,cta_url:Me||void 0,heading:Se||void 0});$e(vt.id),qe(vt.share_token),re.success("Presentation created!")}}catch(vt){console.error("Failed to save presentation:",vt);const Ws=(vt==null?void 0:vt.message)||(vt==null?void 0:vt.toString())||"Unknown error";re.error(`Failed to save: ${Ws}`)}},bt=async()=>{try{await zt();const vt=Ne;if(vt){const Ws=await o.mutateAsync(vt);qe(Ws.share_token),Ue(!0),p("share")}}catch(vt){console.error("Failed to publish presentation:",vt),re.error(`Failed to publish: ${(vt==null?void 0:vt.message)||"Unknown error"}`)}},As=Ve?`https://presentations.relevelup.com/${Ve}`:"";return e.jsx(qs,{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(U,{variant:"ghost",size:"icon",onClick:()=>s("/mission-control/presentations"),children:e.jsx(Aa,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-serif font-bold text-foreground",children:f?"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"]})]})]}),!f&&e.jsx("div",{className:"flex items-center gap-2",children:["client","template","builder","share"].map((vt,Ws)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:Mt("w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors",m===vt?"bg-primary text-primary-foreground":Ws<["client","template","builder","share"].indexOf(m)?"bg-emerald-100 text-emerald-700":"bg-muted text-muted-foreground"),children:Ws<["client","template","builder","share"].indexOf(m)?e.jsx(Xr,{className:"h-4 w-4"}):Ws+1}),e.jsx("span",{className:"text-sm font-medium capitalize hidden sm:inline",children:vt}),Ws<3&&e.jsx("div",{className:"w-8 h-px bg-border"})]},vt))}),m==="client"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("button",{onClick:()=>{L(null),z(""),H(""),K(""),I(!1),p("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($r,{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(Oa,{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(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(Fr,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search by name or email...",value:y,onChange:vt=>v(vt.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(vt=>e.jsxs("button",{onClick:()=>He(vt),className:Mt("w-full text-left p-3 rounded-lg border transition-colors",(T==null?void 0:T.id)===vt.id?"border-primary bg-primary/5":"border-border hover:border-primary/50"),children:[e.jsxs("p",{className:"font-medium text-sm",children:[vt.first_name," ",vt.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:vt.email||vt.phone||"No contact info"})]},vt.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"})]}),T&&e.jsxs(U,{onClick:()=>p("template"),className:"w-full gap-2",children:["Continue with ",T.first_name,e.jsx(Oa,{className:"h-4 w-4"})]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(zl,{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(te,{className:"text-xs",children:"Name *"}),e.jsx(xe,{value:R,onChange:vt=>{z(vt.target.value),I(!0),L(null)},placeholder:"Sarah & Mike Johnson"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Email"}),e.jsx(xe,{value:$,onChange:vt=>H(vt.target.value),placeholder:"Optional",type:"email"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Phone"}),e.jsx(xe,{value:V,onChange:vt=>K(vt.target.value),placeholder:"Optional"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Client Type"}),e.jsxs(Ns,{value:Z,onValueChange:Q,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"buyer",children:"Buyer"}),e.jsx(et,{value:"seller",children:"Seller"}),e.jsx(et,{value:"recruit",children:"Recruit"}),e.jsx(et,{value:"other",children:"Other"})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Property Address"}),e.jsx(xe,{value:le,onChange:vt=>ue(vt.target.value),placeholder:"Optional"})]})]}),M&&R&&e.jsxs(U,{onClick:tt,className:"w-full gap-2",children:["Create Client & Continue",e.jsx(Oa,{className:"h-4 w-4"})]})]})]})]})]}),m==="template"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs(oa,{defaultValue:"system",children:[e.jsxs(la,{children:[e.jsx(Kt,{value:"mine",children:"My Core Templates"}),e.jsx(Kt,{value:"system",children:"LevelUp Smart Templates"}),e.jsx(Kt,{value:"blank",children:"+ Start Blank"})]}),e.jsx(Zt,{value:"mine",className:"mt-4",children:a?e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[1,2].map(vt=>e.jsx(xn,{className:"h-32"},vt))}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(vt=>!vt.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(vt=>!vt.is_system).map(vt=>e.jsx(QSt,{template:vt,onSelect:pt},vt.id))})}),e.jsx(Zt,{value:"system",className:"mt-4",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(vt=>vt.is_system).map(vt=>e.jsx(QSt,{template:vt,onSelect:pt},vt.id))})}),e.jsx(Zt,{value:"blank",className:"mt-4",children:e.jsx(we,{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(U,{onClick:ft,children:"Start from Scratch"})]})})})]}),e.jsxs(U,{variant:"outline",onClick:()=>p("client"),className:"gap-2",children:[e.jsx(Aa,{className:"h-4 w-4"}),"Back"]})]}),m==="builder"&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(we,{children:e.jsxs(Ie,{className:"pt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Presentation Title"}),e.jsx(xe,{value:ie,onChange:vt=>ce(vt.target.value)})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Page Heading"}),e.jsx(xe,{value:Se,onChange:vt=>Qe(vt.target.value),placeholder:R?`Welcome, ${R}!`:"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(te,{children:"Client Name"}),e.jsx(xe,{value:R,onChange:vt=>z(vt.target.value)})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Property Address"}),e.jsx(xe,{value:le,onChange:vt=>ue(vt.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(U,{variant:"outline",size:"sm",onClick:Wt,children:"+ Add Section"})]}),e.jsx("div",{className:"space-y-3",children:je.map((vt,Ws)=>e.jsx(we,{className:Mt(!vt.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(kf,{className:"h-4 w-4 text-muted-foreground cursor-grab"}),e.jsx("span",{className:"text-lg",children:vt.icon})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(xe,{value:vt.title,onChange:on=>qt(Ws,{title:on.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(U,{variant:"ghost",size:"icon",onClick:()=>Ut(Ws),children:vt.is_visible?e.jsx(xa,{className:"h-4 w-4"}):e.jsx(Vg,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"icon",onClick:()=>us(Ws),className:"text-destructive hover:text-destructive",children:e.jsx(In,{className:"h-4 w-4"})})]})]}),e.jsx(xe,{value:vt.description||"",onChange:on=>qt(Ws,{description:on.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(te,{className:"text-xs",children:"Video URL"}),e.jsx(xe,{value:vt.video_url||"",onChange:on=>qt(Ws,{video_url:on.target.value}),placeholder:"Paste a YouTube or video URL...",className:"text-sm"})]}),e.jsx(str,{sectionTitle:vt.title,contactId:T==null?void 0:T.id,onVideoReady:on=>qt(Ws,{video_url:on})}),e.jsx(ntr,{sectionTitle:vt.title,contactId:T==null?void 0:T.id,onVideoReady:on=>qt(Ws,{video_url:on})}),e.jsx(T9,{userId:n==null?void 0:n.id,onSelect:on=>qt(Ws,{video_url:on})})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Image (optional — shown if no video is set)"}),vt.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:vt.image_url,alt:"",className:"w-full max-h-40 object-cover"}),e.jsx(U,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>qt(Ws,{image_url:""}),children:e.jsx(er,{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:[Ae===Ws?e.jsx(Et,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(ly,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Ae===Ws?"Uploading...":"Click to upload an image"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",disabled:Ae===Ws,onChange:on=>{var dn;const Ms=(dn=on.target.files)==null?void 0:dn[0];Ms&&Ye(Ms,Ws),on.target.value=""}})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Text (optional)"}),e.jsx(SN,{content:vt.text||"",onChange:on=>qt(Ws,{text:on}),placeholder:"Add supporting text...",minHeight:"80px",compact:!0})]})]})]})})},Ws))})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Call to Action"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"CTA Type"}),e.jsxs(Ns,{value:he,onValueChange:vt=>{ge(vt);const Ws=ZSt.find(on=>on.value===vt);Ws&&Te(Ws.label)},children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:ZSt.map(vt=>e.jsx(et,{value:vt.value,children:vt.label},vt.value))})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Button Label"}),e.jsx(xe,{value:ke,onChange:vt=>Te(vt.target.value)})]}),e.jsxs("div",{children:[e.jsxs(te,{children:["Link URL ",e.jsx("span",{className:"text-muted-foreground",children:"(optional — leave blank to show a lead capture form instead)"})]}),e.jsx(xe,{value:Me,onChange:vt=>Oe(vt.target.value),placeholder:"https://calendly.com/..."}),!Me&&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:[!f&&e.jsxs(U,{variant:"outline",onClick:()=>p("template"),className:"gap-2",children:[e.jsx(Aa,{className:"h-4 w-4"}),"Back"]}),e.jsxs("div",{className:"flex gap-3 ml-auto",children:[e.jsx(U,{variant:"outline",onClick:zt,disabled:i.isPending||l.isPending,children:"Save Draft"}),e.jsxs(U,{onClick:bt,disabled:o.isPending,className:"gap-2",children:[e.jsx($r,{className:"h-4 w-4"}),Ze?"Update & Reshare":"Publish & Share"]})]})]})]}),m==="share"&&Ve&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(we,{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(Xr,{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 ",R||"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(xe,{value:As,readOnly:!0,className:"text-center font-mono text-sm"}),e.jsx(U,{onClick:()=>{navigator.clipboard.writeText(As),re.success("Link copied!")},children:e.jsx(Pa,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-3 mt-6",children:[e.jsxs(U,{variant:"outline",className:"gap-2",onClick:()=>{const vt=`Hi ${R||""}! I put together something for you — check it out: ${As}`;navigator.clipboard.writeText(vt),re.success("Message copied!")},children:[e.jsx(Ki,{className:"h-4 w-4"}),"Copy Text Message"]}),e.jsxs(U,{variant:"outline",className:"gap-2",onClick:()=>{c?h(!0):window.open(`mailto:${$||""}?subject=${encodeURIComponent(ie)}&body=${encodeURIComponent(`Hi ${(T==null?void 0:T.first_name)||(R==null?void 0:R.split(" ")[0])||""}, I put together a personalized presentation for you: ${As} Looking forward to connecting!`)}`)},children:[e.jsx(ln,{className:"h-4 w-4"}),"Send Email"]})]}),c&&e.jsx(wS,{open:u,onOpenChange:h,contact:T?{id:T.id,first_name:T.first_name,last_name:T.last_name,email:$||T.email||""}:$?{id:"",first_name:(R==null?void 0:R.split(" ")[0])||"",last_name:(R==null?void 0:R.split(" ").slice(1).join(" "))||"",email:$}:void 0,defaultSubject:ie,defaultBody:`Hi ${(T==null?void 0:T.first_name)||(R==null?void 0:R.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(U,{variant:"outline",onClick:()=>p("builder"),children:[e.jsx(Aa,{className:"h-4 w-4 mr-2"}),"Edit Presentation"]}),e.jsx(U,{onClick:()=>s("/mission-control/presentations"),children:"Done"})]})]})]})})},QSt=({template:s,onSelect:t})=>e.jsx(we,{className:"hover:shadow-sm transition-shadow",children:e.jsxs(Ie,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-2xl",children:s.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold",children:s.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:s.description}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(Be,{variant:"outline",className:"text-xs capitalize",children:s.template_type}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(s.sections||[]).length," sections"]})]})]})]}),e.jsx(U,{className:"w-full mt-4",size:"sm",onClick:()=>t(s),children:"Use Template"})]})}),rtr=()=>{var x;const{shareToken:s}=Di(),[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 N;if(b!=null&&b.brokerage_id){const{data:A}=await q.from("brokerages").select("name").eq("id",b.brokerage_id).single();N=(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:N,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],p=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 N=y.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return N?`https://iframe.mediadelivery.net/embed/${N[1]}/${N[2]}?responsive=true`:y},f=!!((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&&p(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:p(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:Mt("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?"}),f?e.jsxs(U,{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(Sr,{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(xRt,{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"})]})},vze="__none__";function atr({value:s,onChange:t}){const{data:n=[],isLoading:r}=Fre(),a=Xtt(),[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),ka({title:"Open House Follow-Up added",description:"The 6-email sequence is now in your library and selected here."})}catch(h){ka({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(te,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(RM,{className:"h-4 w-4 text-emerald-600"}),"Auto follow-up campaign"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Everyone who signs in with an email is automatically enrolled."})]}),s&&e.jsx(Be,{variant:"outline",className:"text-[10px] border-emerald-300 bg-emerald-500/10 text-emerald-700",children:"On"})]}),e.jsxs(Ns,{value:s??vze,onValueChange:h=>t(h===vze?null:h),disabled:r,children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"No follow-up campaign"})}),e.jsxs(js,{children:[e.jsx(et,{value:vze,children:"No follow-up campaign"}),o.map(h=>e.jsxs(et,{value:h.id,children:[h.icon?`${h.icon} `:"",h.name,h.is_active?"":" (paused)"]},h.id))]})]}),c&&!d&&e.jsxs(U,{type:"button",variant:"outline",size:"sm",className:"w-full gap-1.5 text-xs",onClick:u,disabled:i,children:[i?e.jsx(Et,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(cn,{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 itr({openHouseId:s,enableSurvey:t,onToggleSurvey:n}){const{data:r,isLoading:a}=vEs(s),i=jEs(),l=NEs(),o=kEs(),c=SEs(),[d,u]=j.useState(""),[h,m]=j.useState("rating"),p=async v=>{n(v),v&&(!r||r.length===0)&&await c.mutateAsync(s)},f=async()=>{if(!d.trim())return;const v=(r==null?void 0:r.reduce((b,N)=>Math.max(b,N.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(te,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(iy,{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(wn,{checked:t,onCheckedChange:p})]}),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(Et,{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(kf,{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(wn,{checked:v.is_active,onCheckedChange:()=>x(v),className:"scale-75"}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>y(v),children:e.jsx(In,{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(te,{className:"text-xs text-muted-foreground",children:"Add Question"}),e.jsx(xe,{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"&&f()})]}),e.jsxs(Ns,{value:h,onValueChange:m,children:[e.jsx(ws,{className:"w-28 h-9 text-xs",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"rating",children:"Rating"}),e.jsx(et,{value:"open_text",children:"Text"})]})]}),e.jsx(U,{size:"sm",variant:"outline",onClick:f,disabled:!d.trim()||i.isPending,className:"h-9",children:e.jsx(an,{className:"h-3.5 w-3.5"})})]})]})})]})}function otr({openHouseId:s}){const{user:t}=vs(),{data:n=[],isLoading:r}=TEs(s),a=PEs(),i=OEs(),l=(m,p)=>{const f=m+p;if(f<0||f>=n.length)return;const x=n.map(y=>y.id);[x[m],x[f]]=[x[f],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(te,{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(Et,{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,p)=>e.jsx(ltr,{room:m,index:p,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(xe,{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(U,{onClick:h,disabled:!o.trim()||d,size:"sm",children:d?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(an,{className:"h-4 w-4 mr-1"})," Add"]})})]})]})}function ltr({room:s,index:t,total:n,userId:r,openHouseId:a,onMoveRoom:i}){const l=LEs(),o=IEs(),c=REs(),d=DEs(),u=FEs(),h=j.useRef(null),[m,p]=j.useState(!0),[f,x]=j.useState(s.name),[y,v]=j.useState(s.description||""),[b,N]=j.useState(!1),S=j.useMemo(()=>s.media.filter($=>$.kind==="video"&&$.agent_video_id).map($=>$.agent_video_id),[s.media]),{data:A={}}=ct({queryKey:["room-video-statuses",s.id,S.join(",")],enabled:S.length>0,queryFn:async()=>{const{data:$,error:H}=await q.from("agent_videos").select("id, status, bunny_video_id, thumbnail_url, preview_url").in("id",S);if(H)throw H;const V=$||[],K=V.filter(Q=>Q.status==="processing"&&Q.bunny_video_id);await Promise.all(K.map(async Q=>{try{const{data:le}=await q.functions.invoke("bunny-upload",{body:{action:"status",videoId:Q.bunny_video_id,isAgentVideo:!0}});le&&le.status===4&&(await q.from("agent_videos").update({status:"ready",playback_url:le.directPlayUrl,thumbnail_url:le.thumbnailUrl,preview_url:le.previewUrl,duration_seconds:le.length||void 0,updated_at:new Date().toISOString()}).eq("id",Q.id),Q.status="ready",Q.thumbnail_url=le.thumbnailUrl,Q.preview_url=le.previewUrl)}catch{}}));const Z={};return V.forEach(Q=>{Z[Q.id]={status:Q.status,thumbnail_url:Q.thumbnail_url,preview_url:Q.preview_url}}),Z},refetchInterval:$=>{const H=$.state.data;return H?Object.values(H).some(V=>V.status!=="ready"&&V.status!=="failed")?5e3:!1:5e3}}),T=()=>{f.trim()&&f!==s.name&&l.mutate({id:s.id,open_house_id:a,name:f.trim()})},L=()=>{y!==(s.description||"")&&l.mutate({id:s.id,open_house_id:a,description:y.trim()||null})},M=async()=>{await Yi(`Delete "${s.name}" and all its media?`)&&o.mutate({id:s.id,open_house_id:a})},I=$=>i(t,$),R=($,H)=>{const V=$+H;if(V<0||V>=s.media.length)return;const K=s.media.map(Z=>Z.id);[K[$],K[V]]=[K[V],K[$]],u.mutate({open_house_id:a,room_id:s.id,orderedIds:K})},z=async $=>{const H=Array.from($.target.files||[]);if(!(!H.length||!r)){N(!0);try{for(const V of H){const K=V.type.startsWith("video/"),Z=K?500*1024*1024:15*1024*1024;if(V.size>Z){ka({title:`${V.name} is too large`,description:K?"Videos must be under 500MB":"Photos must be under 15MB",variant:"destructive"});continue}if(K){try{const ne=`${s.name} – ${V.name.replace(/\.[^/.]+$/,"")}`,{data:ie,error:ce}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:ne,isAgentVideo:!0}});if(ce||!ie)throw new Error((ce==null?void 0:ce.message)||"Could not start upload");const{videoId:je,libraryId:be}=ie,{data:he,error:ge}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:je,isAgentVideo:!0}});if(ge||!he)throw new Error((ge==null?void 0:ge.message)||"Could not get upload URL");await new Promise((Se,Qe)=>{const Ae=new XMLHttpRequest;Ae.addEventListener("load",()=>{Ae.status>=200&&Ae.status<300?Se():Qe(new Error(`Upload failed (${Ae.status})`))}),Ae.addEventListener("error",()=>Qe(new Error("Upload failed"))),Ae.open("PUT",he.uploadUrl),Ae.setRequestHeader("AccessKey",he.apiKey),Ae.send(V)});const ke=`https://iframe.mediadelivery.net/embed/${be}/${je}`,Te=V.size/(1024*1024),{data:Me,error:Oe}=await q.from("agent_videos").insert({owner_user_id:r,bunny_video_id:je,playback_url:ke,file_size_mb:Te,title:ne,status:"processing",touch_type:"open_house_tour",category:"open_house",page_template:"default"}).select().single();if(Oe)throw Oe;await c.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:ke,sort_order:s.media.length,agent_video_id:Me.id}),ka({title:"Video uploaded",description:"Processing in the background — it’ll appear in your Video Library too."})}catch(ne){ka({title:"Video upload failed",description:(ne==null?void 0:ne.message)||"Try again",variant:"destructive"})}continue}const Q=V.name.split(".").pop()||"jpg",le=`${r}/${a}/rooms/${s.id}-${Date.now()}-${Math.random().toString(36).slice(2,7)}.${Q}`,{error:ue}=await q.storage.from("open-house-tour-media").upload(le,V,{upsert:!1,contentType:V.type});if(ue){ka({title:"Upload failed",description:ue.message,variant:"destructive"});continue}const{data:se}=q.storage.from("open-house-tour-media").getPublicUrl(le);await c.mutateAsync({open_house_id:a,room_id:s.id,kind:"photo",url:se.publicUrl,sort_order:s.media.length})}}finally{N(!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(kf,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>p($=>!$),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(U,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>I(-1),disabled:t===0,children:e.jsx(dv,{className:"h-4 w-4"})}),e.jsx(U,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>I(1),disabled:t===n-1,children:e.jsx(rl,{className:"h-4 w-4"})}),e.jsx(U,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive",onClick:M,children:e.jsx(In,{className:"h-4 w-4"})})]}),m&&e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsx(xe,{value:f,onChange:$=>x($.target.value),onBlur:T,placeholder:"Room name",className:"h-9"}),e.jsx(Fs,{value:y,onChange:$=>v($.target.value),onBlur:L,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(($,H)=>{const V=$.agent_video_id?A[$.agent_video_id]:void 0,K=V==null?void 0:V.status,Z=$.kind==="video"&&K&&K!=="ready"&&K!=="failed",Q=$.kind==="video"&&K==="failed",le=(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:[$.kind==="video"?e.jsxs(e.Fragment,{children:[le?e.jsx("img",{src:le,alt:"",className:"w-full h-full object-cover"}):/iframe\.mediadelivery\.net\/embed\//.test($.url)?e.jsx("div",{className:"w-full h-full bg-slate-800"}):e.jsx("video",{src:$.url,className:"w-full h-full object-cover"}),!Z&&!Q&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 pointer-events-none",children:e.jsx(Wr,{className:"h-6 w-6 text-white"})}),Z&&e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center bg-black/70 text-white gap-1 pointer-events-none",children:[e.jsx(Et,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wide",children:"Processing"})]}),Q&&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:$.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:H+1}),e.jsx("button",{type:"button","aria-label":"Remove media",onClick:()=>d.mutate({id:$.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(er,{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:H===0,onClick:()=>R(H,-1),className:"w-6 h-6 rounded-full bg-black/60 text-white flex items-center justify-center disabled:opacity-30",children:e.jsx(rd,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Move later",disabled:H===s.media.length-1,onClick:()=>R(H,1),className:"w-6 h-6 rounded-full bg-black/60 text-white flex items-center justify-center disabled:opacity-30",children:e.jsx(gi,{className:"h-3.5 w-3.5"})})]})]},$.id)})}),e.jsx("input",{ref:h,type:"file",accept:"image/*,video/*",multiple:!0,onChange:z,className:"hidden"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{variant:"outline",size:"sm",onClick:()=>{var $;return($=h.current)==null?void 0:$.click()},disabled:b,className:"flex-1",children:b?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(qa,{className:"h-4 w-4 mr-2"})," Upload"]})}),e.jsx(T9,{userId:r,triggerLabel:"From Video Library",triggerClassName:"gap-1.5 flex-1 justify-center",onSelect:()=>{},onSelectVideo:async $=>{try{await c.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:$.playback_url||"",sort_order:s.media.length,agent_video_id:$.id}),ka({title:"Video added to room"})}catch(H){ka({title:"Failed to add video",description:H==null?void 0:H.message,variant:"destructive"})}}})]})]})]})}function ctr({open:s,onOpenChange:t,openHouse:n}){const r=vRt(),{user:a}=vs(),i=j.useRef(null),l=j.useRef(null),o=j.useRef(null),c=n.kind==="virtual",[d,u]=j.useState(n.auto_forward_to_card??!1),[h,m]=j.useState(n.disclosure_pdf_url??""),[p,f]=j.useState(n.enable_survey??!1),[x,y]=j.useState(n.ask_visitor_intent??!0),[v,b]=j.useState(n.ask_visitor_address??!1),[N,S]=j.useState(n.photo_url??""),[A,T]=j.useState(!1),[L,M]=j.useState(!1),[I,R]=j.useState(!1),[z,$]=j.useState(n.hero_video_url??""),[H,V]=j.useState(!1),[K,Z]=j.useState(n.price!=null?String(n.price):""),[Q,le]=j.useState(n.beds!=null?String(n.beds):""),[ue,se]=j.useState(n.baths!=null?String(n.baths):""),[ne,ie]=j.useState(n.sqft!=null?String(n.sqft):""),[ce,je]=j.useState(n.enable_question??!0),[be,he]=j.useState(n.enable_showing??!0),[ge,ke]=j.useState(n.enable_disclosures??!0),[Te,Me]=j.useState(n.enable_offer??!0),[Oe,Se]=j.useState(n.brand_color_override??""),[Qe,Ae]=j.useState(n.property_description??""),[Fe,Ne]=j.useState(n.drip_campaign_id??null),$e=async Ge=>{var Ut;const He=(Ut=Ge.target.files)==null?void 0:Ut[0];if(!He||!a)return;if(He.size>200*1024*1024){ka({title:"Video must be under 200MB",variant:"destructive"});return}if(!He.type.startsWith("video/")){ka({title:"Please upload a video file",variant:"destructive"});return}V(!0);const tt=He.name.split(".").pop()||"mp4",pt=`${a.id}/${n.id}/hero-${Date.now()}.${tt}`,{error:ft}=await q.storage.from("open-house-tour-media").upload(pt,He,{upsert:!0,contentType:He.type});if(ft){ka({title:"Upload failed",description:ft.message,variant:"destructive"}),V(!1);return}const{data:qt}=q.storage.from("open-house-tour-media").getPublicUrl(pt);$(qt.publicUrl),V(!1),ka({title:"Video uploaded!"})},Ve=async Ge=>{var Ut;const He=(Ut=Ge.target.files)==null?void 0:Ut[0];if(!He||!a)return;if(He.size>10*1024*1024){ka({title:"Image must be under 10MB",variant:"destructive"});return}if(!He.type.startsWith("image/")){ka({title:"Please upload an image file",variant:"destructive"});return}M(!0);const tt=He.name.split(".").pop()||"jpg",pt=`${a.id}/${n.id}-${Date.now()}.${tt}`,{error:ft}=await q.storage.from("open-house-photos").upload(pt,He,{upsert:!0});if(ft){ka({title:"Upload failed",description:ft.message,variant:"destructive"}),M(!1);return}const{data:qt}=q.storage.from("open-house-photos").getPublicUrl(pt);S(qt.publicUrl),M(!1),ka({title:"Photo updated!"})},qe=()=>{S(""),l.current&&(l.current.value="")},Ze=async Ge=>{var qt;const He=(qt=Ge.target.files)==null?void 0:qt[0];if(!He||!a)return;if(He.size>20*1024*1024){ka({title:"File must be under 20MB",variant:"destructive"});return}if(He.type!=="application/pdf"){ka({title:"Only PDF files are accepted",variant:"destructive"});return}T(!0);const tt=`${a.id}/disclosures/${n.id}-${Date.now()}.pdf`,{error:pt}=await q.storage.from("open-house-photos").upload(tt,He,{upsert:!0});if(pt){ka({title:"Upload failed",description:pt.message,variant:"destructive"}),T(!1);return}const{data:ft}=q.storage.from("open-house-photos").getPublicUrl(tt);m(ft.publicUrl),T(!1),ka({title:"PDF uploaded!"})},Ue=()=>{m(""),i.current&&(i.current.value="")},Ye=async()=>{R(!0);try{const Ge={id:n.id,auto_forward_to_card:d,disclosure_pdf_url:h||null,enable_survey:p,ask_visitor_intent:x,ask_visitor_address:v,photo_url:N||null,drip_campaign_id:Fe};c&&(Ge.hero_video_url=z||null,Ge.price=K.trim()?Number(K):null,Ge.beds=Q.trim()?parseInt(Q,10):null,Ge.baths=ue.trim()?Number(ue):null,Ge.sqft=ne.trim()?parseInt(ne,10):null,Ge.enable_question=ce,Ge.enable_showing=be,Ge.enable_disclosures=ge,Ge.enable_offer=Te,Ge.brand_color_override=Oe.trim()||null,Ge.property_description=Qe.trim()||null),await r.mutateAsync(Ge),ka({title:"Settings saved!"}),t(!1)}catch{ka({title:"Failed to save",variant:"destructive"})}finally{R(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"sm:max-w-md max-h-[85vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{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:[c&&e.jsxs(e.Fragment,{children:[n.tour_mode==="single_video"?e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Wr,{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:$e,className:"hidden"}),z?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border bg-black",children:[e.jsx("video",{src:z,controls:!0,className:"w-full max-h-48"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsx(U,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var Ge;return(Ge=o.current)==null?void 0:Ge.click()},disabled:H,children:H?e.jsx(Et,{className:"h-3.5 w-3.5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(qa,{className:"h-3.5 w-3.5 mr-1"}),"Replace"]})}),e.jsx(U,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:()=>$(""),children:e.jsx(er,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var Ge;return(Ge=o.current)==null?void 0:Ge.click()},disabled:H,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:H?e.jsx(Et,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Wr,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload tour video (max 200MB)"})]})})]}):e.jsx(otr,{openHouseId:n.id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{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(te,{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(xe,{type:"number",value:K,onChange:Ge=>Z(Ge.target.value),placeholder:"650000",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-muted-foreground",children:"Sq Ft"}),e.jsx(xe,{type:"number",value:ne,onChange:Ge=>ie(Ge.target.value),placeholder:"2200",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-muted-foreground",children:"Beds"}),e.jsx(xe,{type:"number",value:Q,onChange:Ge=>le(Ge.target.value),placeholder:"3",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs text-muted-foreground",children:"Baths"}),e.jsx(xe,{type:"number",step:"0.5",value:ue,onChange:Ge=>se(Ge.target.value),placeholder:"2.5",className:"mt-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{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(Fs,{value:Qe,onChange:Ge=>Ae(Ge.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(te,{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(wn,{checked:ce,onCheckedChange:je})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Schedule a private showing"}),e.jsx(wn,{checked:be,onCheckedChange:he})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Request seller disclosures"}),e.jsx(wn,{checked:ge,onCheckedChange:ke})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Make an offer / express interest"}),e.jsx(wn,{checked:Te,onCheckedChange:Me})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{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:Oe||"#0f172a",onChange:Ge=>Se(Ge.target.value),className:"h-10 w-14 rounded-md border border-input cursor-pointer bg-transparent"}),e.jsx(xe,{value:Oe,onChange:Ge=>Se(Ge.target.value),placeholder:"#0f172a",className:"flex-1 font-mono text-sm"}),Oe&&e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>Se(""),children:"Reset"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:["#0f172a","#406E71","#2a4c64","#7c2d12","#1e3a8a","#581c87","#9f1239","#065f46"].map(Ge=>e.jsx("button",{type:"button",onClick:()=>Se(Ge),className:"w-6 h-6 rounded-full border border-border hover:scale-110 transition-transform",style:{backgroundColor:Ge},"aria-label":Ge},Ge))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{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:Ve,className:"hidden"}),N?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:N,alt:"Property",className:"w-full h-40 object-cover"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsxs(U,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var Ge;return(Ge=l.current)==null?void 0:Ge.click()},disabled:L,children:[L?e.jsx(Et,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(qa,{className:"h-3.5 w-3.5 mr-1"}),L?"":"Replace"]}),e.jsx(U,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:qe,children:e.jsx(er,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var Ge;return(Ge=l.current)==null?void 0:Ge.click()},disabled:L,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:L?e.jsx(Et,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(pc,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload property photo (max 10MB)"})]})})]}),e.jsx(atr,{value:Fe,onChange:Ne}),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(te,{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(wn,{checked:d,onCheckedChange:u})]})}),!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{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:Ze,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(Ur,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm truncate flex-1",children:"Disclosure PDF uploaded"}),e.jsx(U,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:Ue,children:e.jsx(er,{className:"h-4 w-4"})})]}):e.jsx("button",{type:"button",onClick:()=>{var Ge;return(Ge=i.current)==null?void 0:Ge.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(Et,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(qa,{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(te,{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(wn,{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(te,{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(wn,{checked:v,onCheckedChange:b})]})}),e.jsx(itr,{openHouseId:n.id,enableSurvey:p,onToggleSurvey:f}),e.jsx(U,{onClick:Ye,disabled:I,className:"w-full",children:I?"Saving...":"Save Settings"})]})]})})}const bss={5:"Excellent",4:"Good",3:"Neutral",2:"Bad",1:"Very Bad"};function dtr({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:bss[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 utr({openHouseId:s}){const{data:t,isLoading:n}=wEs(s),{data:r}=yRt(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(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(iy,{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(we,{children:[e.jsx(Tt,{className:"pb-3",children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(iy,{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(oa,{defaultValue:"summary",children:[e.jsxs(la,{className:"mb-4",children:[e.jsxs(Kt,{value:"summary",className:"text-xs gap-1",children:[e.jsx(Cl,{className:"h-3.5 w-3.5"})," Summary"]}),e.jsxs(Kt,{value:"individual",className:"text-xs gap-1",children:[e.jsx(So,{className:"h-3.5 w-3.5"})," Per Visitor"]})]}),e.jsxs(Zt,{value:"summary",className:"space-y-6",children:[o.map(h=>e.jsx(dtr,{question:h,responses:l},h.id)),c.map(h=>{const m=l.filter(p=>p.question_id===h.id&&p.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(p=>{const f=a[p.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:[f?`${f.first_name} ${f.last_name||""}`.trim():"Visitor",":"]}),e.jsx("p",{className:"mt-0.5",children:p.text_value})]},p.id)})})]},h.id)})]}),e.jsx(Zt,{value:"individual",className:"space-y-4",children:d.map(h=>{const m=a[h],p=l.filter(f=>f.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:p.map(f=>{const x=i.find(y=>y.id===f.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:f.rating_value!=null?bss[f.rating_value]||f.rating_value:f.text_value})]},f.id):null})})]},h)})})]})})]})}const htr={question:{label:"Question",icon:Ki,color:"text-sky-700 dark:text-sky-300",bg:"bg-sky-100 dark:bg-sky-950"},showing:{label:"Showing",icon:pa,color:"text-orange-700 dark:text-orange-300",bg:"bg-orange-100 dark:bg-orange-950"},disclosure:{label:"Disclosures",icon:Ur,color:"text-indigo-700 dark:text-indigo-300",bg:"bg-indigo-100 dark:bg-indigo-950"},offer:{label:"Hot Lead",icon:yu,color:"text-emerald-700 dark:text-emerald-300",bg:"bg-emerald-100 dark:bg-emerald-950"}},JSt={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 mtr({openHouseId:s}){const{data:t=[],isLoading:n}=zEs(s),r=BEs(),[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(AM,{className:"h-4 w-4"}),"Virtual Open House Leads",e.jsx(Be,{variant:"secondary",className:"ml-1",children:d.all}),d.new>0&&e.jsxs(Be,{className:"bg-emerald-600 hover:bg-emerald-600",children:[d.new," new"]})]}),e.jsx("div",{className:"flex items-center gap-1 flex-wrap",children:[["all","All",d.all],["new","New",d.new],["offer","Hot",d.offer],["showing","Showings",d.showing],["question","Questions",d.question],["disclosure","Docs",d.disclosure]].map(([h,m,p])=>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:p})]},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=htr[h.action_type],p=m.icon,f=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(p,{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:f.visitor_name||"Visitor"}),e.jsx(Be,{variant:"outline",className:`text-[10px] ${m.color}`,children:m.label}),h.status==="new"&&e.jsx("span",{className:"text-[10px] font-bold text-emerald-600 uppercase tracking-wide",children:"New"}),y&&e.jsxs("span",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wide flex items-center gap-1",children:[e.jsx(zr,{className:"h-3 w-3"}),"Contacted"]})]}),f.message&&e.jsxs("p",{className:"text-sm text-muted-foreground line-clamp-1 mt-0.5 italic",children:['"',f.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(Yr,{className:"h-3 w-3"}),Gs(new Date(h.created_at),"MMM d, h:mm a")]}),f.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(ln,{className:"h-3 w-3"}),f.email]}),f.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ba,{className:"h-3 w-3"}),f.phone]})]})]}),x?e.jsx(rl,{className:"h-4 w-4 mt-1 text-muted-foreground"}):e.jsx(gi,{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:[f.message&&e.jsxs("div",{className:"bg-muted/40 rounded-md p-3 text-sm border-l-2 border-foreground/30",children:['"',f.message,'"']}),Object.keys(JSt).some(b=>f[b]!=null&&f[b]!==""&&!(Array.isArray(f[b])&&f[b].length===0))&&e.jsx("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1.5 text-sm",children:Object.entries(JSt).map(([b,N])=>{const S=f[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:N}),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:[f.email&&e.jsx("a",{href:`mailto:${f.email}?subject=${encodeURIComponent("Re: your open house inquiry")}`,children:e.jsxs(U,{size:"sm",variant:"default",className:"gap-1.5",children:[e.jsx(ln,{className:"h-3.5 w-3.5"}),"Reply"]})}),f.phone&&e.jsx("a",{href:`tel:${String(f.phone).replace(/[^0-9+]/g,"")}`,children:e.jsxs(U,{size:"sm",variant:"outline",className:"gap-1.5",children:[e.jsx(ba,{className:"h-3.5 w-3.5"}),"Call"]})}),!y&&e.jsxs(U,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>u(h.id,"contacted"),children:[e.jsx(zr,{className:"h-3.5 w-3.5"}),"Mark contacted"]}),v?e.jsx(U,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>u(h.id,"new"),children:"Restore"}):e.jsxs(U,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>u(h.id,"archived"),children:[e.jsx(n1,{className:"h-3.5 w-3.5"}),"Archive"]})]})]})]},h.id)})})]})}const e5t=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}`},ptr=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"})},t5t=25;function ftr({open:s,onOpenChange:t,openHouse:n,variant:r="tour"}){var Ze;const a=r==="rsvp",{isGmailConnected:i,gmailEmail:l}=Ax(),{data:o}=dre(),c=!!(o!=null&&o.hasVerifiedSes),d=Sa(),{data:u=[]}=F_(),[h,m]=j.useState([]),[p,f]=j.useState(!1),[x,y]=j.useState("all"),[v,b]=j.useState([]),[N,S]=j.useState([]),[A,T]=j.useState(""),[L,M]=j.useState([]),[I,R]=j.useState(""),[z,$]=j.useState(""),[H,V]=j.useState(""),[K,Z]=j.useState("platform"),[Q,le]=j.useState(!1),[ue,se]=j.useState(0),[ne,ie]=j.useState(!1),ce=a?`https://guestbook.relevelup.com/rsvp/${n.slug}`:`https://guestbook.relevelup.com/${n.slug}`,je=ptr(n.event_date),be=n.start_time?`${e5t(n.start_time)}${n.end_time?` – ${e5t(n.end_time)}`:""}`:"",he=[je,be].filter(Boolean).join(" · ");j.useEffect(()=>{s&&($(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}${je?` on ${je}`:""}${be?` from ${be}`:""}. 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([]),M([]),T(""),y("all"),se(0),Z(c?"ses":i?"gmail":"platform"),h.length===0&&ge())},[s,n.id,i,c]);const ge=async()=>{if(d){f(!0);try{const Ue=[];let Ge=0;for(;;){const{data:He,error:tt}=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(Ge,Ge+1e3-1);if(tt)throw tt;const pt=He||[];if(Ue.push(...pt),pt.length<1e3)break;Ge+=1e3}m(Ue.map(He=>({id:He.id,first_name:He.first_name,last_name:He.last_name,email:He.email,tagIds:(He.tags||[]).map(tt=>tt.relationship_type_id)})))}catch{re.error("Failed to load contacts")}finally{f(!1)}}},ke=Ue=>`${Ue.first_name} ${Ue.last_name||""}`.trim(),Te=j.useMemo(()=>{const Ue=I.trim().toLowerCase();return Ue?h.filter(Ye=>`${ke(Ye)} ${Ye.email||""}`.toLowerCase().includes(Ue)):h},[h,I]),Me=j.useMemo(()=>{const Ue={};return h.forEach(Ye=>Ye.tagIds.forEach(Ge=>{Ue[Ge]=(Ue[Ge]||0)+1})),Ue},[h]),Oe=j.useMemo(()=>x==="all"?h:x==="tags"?v.length===0?[]:h.filter(Ue=>Ue.tagIds.some(Ye=>v.includes(Ye))):h.filter(Ue=>N.includes(Ue.id)),[x,h,v,N]),Se=j.useMemo(()=>{const Ue=new Set,Ye=[];return[...Oe.map(Ge=>({email:Ge.email,name:ke(Ge)})),...L].forEach(Ge=>{const He=Ge.email.toLowerCase();!Ge.email||Ue.has(He)||(Ue.add(He),Ye.push(Ge))}),Ye},[Oe,L]),Qe=()=>{const Ue=A.trim();if(Ue){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Ue)){re.error("Invalid email");return}M(Ye=>[...Ye,{email:Ue,name:Ue.split("@")[0]}]),T("")}},Ae=Ue=>Ue.replace(/&/g,"&").replace(//g,">"),Fe=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||"",Ne=Ue=>{const Ye=Ue?`Hi ${Ae(Ue)},`:"Hi there,",Ge=[n.city,n.state].filter(Boolean).join(", "),He=Ae(H).split(/\n\n+/).map(tt=>`

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

`).join("");return`
${Fe?``:""} ${a&&he?``:""}

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

${Ae(n.property_address)}

${Ge?`

${Ae(Ge)}${n.zip?" "+Ae(n.zip):""}

`:""}
 

When

${Ae(he)}

${Ye}

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

Or copy this link:
${ce}

`},$e=j.useMemo(()=>Ne("Alex"),[H,n.id,Fe,a,he]),Ve=async()=>{var Ue;if(Se.length===0){re.error("Add at least one recipient");return}le(!0),se(0);try{if(K==="gmail"&&i){let Ye=0;for(const Ge of Se){const{data:He,error:tt}=await q.functions.invoke("gmail-send",{body:{to:Ge.email,subject:z,body:Ne((Ue=Ge.name)==null?void 0:Ue.split(" ")[0])}});!tt&&(He!=null&&He.success)&&(Ye+=1),se(Ye)}if(Ye===0)throw new Error("Gmail send failed");re.success(`Sent to ${Ye} of ${Se.length} via Gmail`)}else{let Ye=0;for(let Ge=0;Ge{await navigator.clipboard.writeText(ce),ie(!0),setTimeout(()=>ie(!1),1500)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"sm:max-w-[900px] w-[calc(100vw-2rem)] max-h-[92vh] overflow-y-auto overflow-x-hidden",children:[e.jsxs(Vs,{className:"min-w-0",children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(ln,{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(Rc,{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(U,{variant:"ghost",size:"sm",onClick:qe,className:"shrink-0 h-7 gap-1",children:[ne?e.jsx(Xr,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(Pa,{className:"h-3.5 w-3.5"}),ne?"Copied":"Copy"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{className:"flex items-center gap-1.5",children:[e.jsx(ln,{className:"h-3.5 w-3.5"}),"Send from"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[c&&e.jsx(U,{type:"button",variant:K==="ses"?"default":"outline",size:"sm",onClick:()=>Z("ses"),className:"gap-1.5",children:"Mass Email (your address)"}),i&&e.jsx(U,{type:"button",variant:K==="gmail"?"default":"outline",size:"sm",onClick:()=>Z("gmail"),className:"gap-1.5",children:"Gmail"}),e.jsx(U,{type:"button",variant:K==="platform"?"default":"outline",size:"sm",onClick:()=>Z("platform"),className:"gap-1.5",children:"LevelUp"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:K==="ses"&&((Ze=o==null?void 0:o.verifiedEmails)!=null&&Ze[0])?e.jsxs(e.Fragment,{children:["Sending as ",e.jsx("span",{className:"font-medium",children:o.verifiedEmails[0]})," via your Mass Email setup"]}):K==="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(te,{className:"flex items-center gap-1.5",children:[e.jsx(Bn,{className:"h-3.5 w-3.5"}),"Who should receive this?"]}),e.jsxs(oa,{value:x,onValueChange:Ue=>y(Ue),children:[e.jsxs(la,{className:"grid w-full grid-cols-3",children:[e.jsx(Kt,{value:"all",children:"All contacts"}),e.jsx(Kt,{value:"tags",children:"By tag"}),e.jsx(Kt,{value:"select",children:"Pick people"})]}),e.jsx(Zt,{value:"all",className:"pt-3",children:e.jsx("div",{className:"rounded-lg border p-3 text-sm text-muted-foreground",children:p?"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(Zt,{value:"tags",className:"pt-3",children:e.jsx(Gi,{className:"h-[210px] rounded-lg border p-2",children:e.jsxs("div",{className:"space-y-1",children:[u.map(Ue=>{const Ye=v.includes(Ue.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(xi,{checked:Ye,onCheckedChange:()=>b(Ge=>Ye?Ge.filter(He=>He!==Ue.id):[...Ge,Ue.id])}),e.jsxs("span",{className:"flex items-center gap-1.5 text-sm flex-1 min-w-0 truncate",children:[e.jsx(Cf,{className:"h-3 w-3 text-muted-foreground shrink-0"}),Ue.name]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Me[Ue.id]||0})]},Ue.id)}),u.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-2",children:"No tags yet."})]})})}),e.jsxs(Zt,{value:"select",className:"pt-3 space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(xe,{value:I,onChange:Ue=>R(Ue.target.value),placeholder:"Search contacts...",className:"pl-8 h-9"})]}),e.jsx(Gi,{className:"h-[210px] rounded-lg border p-2",children:e.jsxs("div",{className:"space-y-1",children:[Te.slice(0,300).map(Ue=>{const Ye=N.includes(Ue.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(xi,{checked:Ye,onCheckedChange:()=>S(Ge=>Ye?Ge.filter(He=>He!==Ue.id):[...Ge,Ue.id])}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:ke(Ue)||"(no name)"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Ue.email})]})]},Ue.id)}),Te.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-2",children:p?"Loading…":"No contacts found."})]})})]})]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(xe,{value:A,onChange:Ue=>T(Ue.target.value),placeholder:"Also send to an email...",type:"email",onKeyDown:Ue=>{Ue.key==="Enter"&&(Ue.preventDefault(),Qe())}}),e.jsx(U,{type:"button",variant:"outline",size:"sm",onClick:Qe,children:"Add"})]}),L.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:L.map(Ue=>e.jsxs(Be,{variant:"secondary",className:"gap-1 pl-2 pr-1 py-0.5",children:[e.jsx("span",{className:"text-xs",children:Ue.email}),e.jsx("button",{onClick:()=>M(Ye=>Ye.filter(Ge=>Ge.email!==Ue.email)),className:"hover:bg-muted-foreground/20 rounded p-0.5",children:e.jsx(er,{className:"h-3 w-3"})})]},Ue.email))})]}),e.jsx(hc,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"vt-subject",children:"Subject"}),e.jsx(xe,{id:"vt-subject",value:z,onChange:Ue=>$(Ue.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{htmlFor:"vt-message",children:"Message"}),e.jsx(Fs,{id:"vt-message",value:H,onChange:Ue=>V(Ue.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(te,{className:"flex items-center gap-1.5",children:[e.jsx(xa,{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:`${$e}`,className:"w-full h-[420px] lg:h-[560px] border-0 bg-white",sandbox:""})})]})]}),e.jsxs("div",{className:Mt("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:Se.length.toLocaleString()})," recipient",Se.length===1?"":"s",Q&&ue>0&&e.jsxs("span",{children:[" · sent ",ue]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),disabled:Q,children:"Cancel"}),e.jsxs(U,{onClick:Ve,disabled:Q||Se.length===0||!z.trim(),className:"gap-2",children:[Q?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx($r,{className:"h-4 w-4"}),Q?"Sending...":`Send${Se.length?` to ${Se.length}`:""}`]})]})]})]})})}function gtr({openHouseId:s}){const{data:t=[],isLoading:n}=sTs(s),r=rTs(s),a=aTs(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(cv,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-semibold",children:"RSVPs"}),e.jsx(Be,{variant:"secondary",className:"text-[11px]",children:t.length})]}),t.length>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[i," checked in"]})]}),n?e.jsx("div",{className:"px-4 py-6 text-sm text-muted-foreground",children:"Loading RSVPs…"}):t.length===0?e.jsxs("div",{className:"px-4 py-6 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No RSVPs yet."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Send an invite to your database to start filling the list."})]}):e.jsx("ul",{className:"divide-y divide-border",children:t.map(l=>e.jsxs("li",{className:"flex items-center gap-3 px-4 py-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:[l.first_name,l.last_name].filter(Boolean).join(" ")}),l.checked_in_at&&e.jsxs(Be,{className:"text-[10px] gap-1",children:[e.jsx(Xr,{className:"h-3 w-3"}),"Checked in"]}),l.has_agent&&e.jsxs(Be,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(tN,{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(ln,{className:"h-3 w-3"}),l.email]}),l.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ba,{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(U,{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(U,{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(In,{className:"h-4 w-4"})})]},l.id))})]})}function xtr({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(an,{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(Sf,{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(Fr,{className:"pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 opacity-70"}),e.jsx(xe,{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:Mt("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 s5t={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 ytr({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(Bn,{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(U,{variant:"outline",size:"sm",className:"mt-4 gap-1.5",onClick:n,children:[e.jsx(jd,{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(Xd,{className:"h-3 w-3"}),r," hot"]})]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:t,className:"h-7 gap-1 text-xs",children:[e.jsx(pi,{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=s5t[a.visitor_intent||""]||s5t.browsing;return e.jsxs("tr",{className:Mt("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:Mt("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:Mt("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:Gs(new Date(a.created_at),"h:mm a")})]},a.id)})})]})})]})}const J4e="guestbook.relevelup.com";function vtr(){const{data:s,isLoading:t}=gEs(),n=xEs(),r=vRt(),a=yEs(),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,m]=j.useState("all"),[p,f]=j.useState(!1),{user:x}=vs(),y=Sa(),[v,b]=j.useState(null),[N,S]=j.useState(null),[A,T]=j.useState(!1),L=j.useRef(null),[M,I]=j.useState({property_address:"",city:"",state:"",zip:"",event_date:Gs(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"}),R=ne=>{var ce;const ie=(ce=ne.target.files)==null?void 0:ce[0];if(ie){if(ie.size>5*1024*1024){ka({title:"Photo must be under 5MB",variant:"destructive"});return}b(ie),S(URL.createObjectURL(ie))}},z=()=>{b(null),S(null),L.current&&(L.current.value="")},$=async()=>{if(!M.property_address){ka({title:M.event_type==="community"?"Event name is required":"Address is required",variant:"destructive"});return}let ne;if(v&&x){T(!0);const ce=v.name.split(".").pop(),je=`${y}/${Date.now()}.${ce}`,{error:be}=await q.storage.from("open-house-photos").upload(je,v,{upsert:!0});if(be){ka({title:"Photo upload failed",description:be.message,variant:"destructive"}),T(!1);return}const{data:he}=q.storage.from("open-house-photos").getPublicUrl(je);ne=he.publicUrl,T(!1)}const ie=M.kind==="virtual"?{...M,start_time:void 0,end_time:void 0,photo_url:ne}:{...M,photo_url:ne};await n.mutateAsync(ie),l(!1),I({property_address:"",city:"",state:"",zip:"",event_date:Gs(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"}),z()},H=ne=>{navigator.clipboard.writeText(`https://${J4e}/${ne}`),ka({title:"Link copied!"})},V=Gs(new Date,"yyyy-MM-dd"),K=j.useMemo(()=>{const ne=s??[],ie=d.trim().toLowerCase(),ce=Se=>!ie||[Se.property_address,Se.city,Se.state].filter(Boolean).join(" ").toLowerCase().includes(ie),je=ne.filter(ce),be=je.filter(Se=>Se.kind==="virtual"),he=je.filter(Se=>Se.kind!=="virtual"),ge=he.filter(Se=>Se.event_date===V),ke=he.filter(Se=>Se.event_date>V).sort((Se,Qe)=>Se.event_date.localeCompare(Qe.event_date)),Te=he.filter(Se=>Se.event_dateQe.event_date.localeCompare(Se.event_date)),Me=ne.reduce((Se,Qe)=>Se+(Qe.visitor_count||0),0),Oe=ne.reduce((Se,Qe)=>Se+(Qe.qr_scan_count||0),0);return{today:ge,upcoming:ke,past:Te,virtual:be,totalSignIns:Me,totalScans:Oe}},[s,d,V]),Z=K.today.length+K.upcoming.length,Q=Z>0?`${Z} upcoming · ${K.totalSignIns.toLocaleString()} total sign-ins`:`${K.totalSignIns.toLocaleString()} total sign-ins collected`,le=ne=>h==="all"||h===ne,ue=ne=>m(ie=>ie===ne?"all":ne),se=ne=>e.jsx(btr,{openHouse:ne,isExpanded:o===ne.id,onToggle:()=>c(o===ne.id?null:ne.id),onCopyLink:()=>H(ne.slug||""),onToggleActive:()=>r.mutate({id:ne.id,is_active:!ne.is_active}),onDelete:()=>a.mutate(ne.id),isToday:ne.kind!=="virtual"&&ne.event_date===V},ne.id);return e.jsxs(qs,{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(xtr,{summary:Q,search:d,onSearchChange:u,onCreate:()=>l(!0),stats:[{key:"today",label:"Live Today",value:K.today.length,onClick:()=>ue("today"),active:h==="today"},{key:"upcoming",label:"Upcoming",value:K.upcoming.length,onClick:()=>ue("upcoming"),active:h==="upcoming"},{key:"virtual",label:"Virtual Tours",value:K.virtual.length,onClick:()=>ue("virtual"),active:h==="virtual"},{key:"signins",label:"Total Sign-Ins",value:K.totalSignIns.toLocaleString()},{key:"scans",label:"Total QR Scans",value:K.totalScans.toLocaleString()}]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(zs,{open:i,onOpenChange:l,children:[e.jsx(al,{asChild:!0,children:e.jsx("span",{className:"sr-only",children:"Open create dialog"})}),e.jsxs(Ds,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(te,{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:()=>I(ne=>({...ne,kind:"physical"})),className:`p-3 rounded-lg border text-left transition-all ${M.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:()=>I(ne=>({...ne,kind:"virtual",event_type:"property"})),className:`p-3 rounded-lg border text-left transition-all ${M.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"})]})]})]}),M.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:()=>I(ne=>({...ne,event_type:"property"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${M.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:()=>I(ne=>({...ne,event_type:"community"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${M.event_type==="community"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"Community Event"})]})}),M.kind==="virtual"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{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:()=>I(ne=>({...ne,tour_mode:"rooms"})),className:`p-3 rounded-lg border text-left transition-all ${M.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:()=>I(ne=>({...ne,tour_mode:"single_video"})),className:`p-3 rounded-lg border text-left transition-all ${M.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(te,{children:M.event_type==="community"?"Event Name *":"Property Address *"}),e.jsx(xe,{value:M.property_address,onChange:ne=>I(ie=>({...ie,property_address:ne.target.value})),placeholder:M.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(te,{children:"City"}),e.jsx(xe,{value:M.city,onChange:ne=>I(ie=>({...ie,city:ne.target.value})),placeholder:"Austin"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"State"}),e.jsx(xe,{value:M.state,onChange:ne=>I(ie=>({...ie,state:ne.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(te,{children:"ZIP"}),e.jsx(xe,{value:M.zip,onChange:ne=>I(ie=>({...ie,zip:ne.target.value})),placeholder:"78701"})]})]}),M.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(te,{children:"Date"}),e.jsx(xe,{type:"date",value:M.event_date,onChange:ne=>I(ie=>({...ie,event_date:ne.target.value}))})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Start Time"}),e.jsx(xe,{type:"time",value:M.start_time,onChange:ne=>I(ie=>({...ie,start_time:ne.target.value}))})]}),e.jsxs("div",{children:[e.jsx(te,{children:"End Time"}),e.jsx(xe,{type:"time",value:M.end_time,onChange:ne=>I(ie=>({...ie,end_time:ne.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Welcome Message"}),e.jsx(Fs,{value:M.agent_greeting,onChange:ne=>I(ie=>({...ie,agent_greeting:ne.target.value})),placeholder:"Welcome! Please sign in below."})]}),e.jsxs("div",{children:[e.jsx(te,{children:M.event_type==="community"?"Event Photo":"Property Photo"}),e.jsx("input",{ref:L,type:"file",accept:"image/*",onChange:R,className:"hidden"}),N?e.jsxs("div",{className:"relative mt-1 rounded-xl overflow-hidden border border-border",children:[e.jsx("img",{src:N,alt:"Property preview",className:"w-full h-40 object-cover"}),e.jsx("button",{type:"button",onClick:z,className:"absolute top-2 right-2 bg-black/60 hover:bg-black/80 text-white rounded-full p-1 transition-colors",children:e.jsx(er,{className:"h-4 w-4"})})]}):e.jsxs("button",{type:"button",onClick:()=>{var ne;return(ne=L.current)==null?void 0:ne.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(ly,{className:"h-6 w-6"}),e.jsxs("span",{className:"text-sm",children:["Add a ",M.event_type==="community"?"cover":"property"," photo"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Max 5MB"})]})]}),e.jsx(U,{onClick:$,disabled:n.isPending||A,className:"w-full",children:A?"Uploading photo...":n.isPending?"Creating...":M.kind==="virtual"?"Create Virtual Open House":M.event_type==="community"?"Create Community Event":"Create Open House"})]})]})]})}),t?e.jsx("div",{className:"grid gap-4",children:[1,2].map(ne=>e.jsx(we,{className:"animate-pulse",children:e.jsxs(Tt,{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"})]})},ne))}):s!=null&&s.length?e.jsxs("div",{className:"space-y-8",children:[K.today.length>0&&le("today")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(bze,{title:"Happening Today",count:K.today.length,accent:!0}),e.jsx("div",{className:"space-y-4",children:K.today.map(se)})]}),K.upcoming.length>0&&le("upcoming")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(bze,{title:"Upcoming",count:K.upcoming.length}),e.jsx("div",{className:"space-y-4",children:K.upcoming.map(se)})]}),K.virtual.length>0&&le("virtual")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(bze,{title:"Virtual Tours",count:K.virtual.length}),e.jsx("div",{className:"space-y-4",children:K.virtual.map(se)})]}),K.past.length>0&&h==="all"&&e.jsxs("section",{className:"space-y-3",children:[e.jsxs("button",{onClick:()=>f(ne=>!ne),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(Y2,{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:K.past.length})]}),p?e.jsx(dv,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(rl,{className:"h-4 w-4 text-muted-foreground"})]}),p&&e.jsx("div",{className:"space-y-4",children:K.past.map(se)})]}),Z===0&&K.virtual.length===0&&K.past.length===0&&e.jsx(we,{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(we,{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(Sf,{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(U,{onClick:()=>l(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"Create Your First Open House"]})]})})]})]})}function bze({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 btr({openHouse:s,isExpanded:t,onToggle:n,onCopyLink:r,onToggleActive:a,onDelete:i,isToday:l}){const{data:o}=yRt(t?s.id:void 0),{data:c}=ct({queryKey:["agent-profile-flyer",s.agent_id],queryFn:async()=>{const{data:M,error:I}=await q.from("profiles").select("name, avatar_url, phone, title, brokerages:brokerage_id(name)").eq("id",s.agent_id).single();if(I)throw I;const R=M.brokerages;return{...M,brokerage_name:(R==null?void 0:R.name)||null}},enabled:!!s.agent_id}),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[p,f]=j.useState(!1),[x,y]=j.useState(!1),v=j.useRef(null),b=`https://${J4e}/${s.slug}`,N=M=>{if(!M)return"";const[I,R]=M.split(":"),z=parseInt(I),$=z>=12?"PM":"AM";return`${z>12?z-12:z||12}:${R} ${$}`},S=()=>{if(!(o!=null&&o.length))return;const M=["First Name","Last Name","Email","Phone","Address","Intent","Wants Market Updates","Message","Signed In"],I=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,'""'),Gs(new Date(V.created_at),"MM/dd/yyyy h:mm a")]),R=[M,...I].map(V=>V.map(K=>`"${K}"`).join(",")).join(` `),z=new Blob([R],{type:"text/csv"}),$=URL.createObjectURL(z),H=document.createElement("a");H.href=$,H.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-visitors.csv`,H.click(),URL.revokeObjectURL($)},A=j.useCallback(()=>{if(!v.current)return;const M=v.current.querySelector("svg");if(!M)return;const I=new XMLSerializer().serializeToString(M),R=document.createElement("canvas");R.width=1024,R.height=1024;const z=R.getContext("2d"),$=new Image;$.onload=()=>{z==null||z.drawImage($,0,0,1024,1024);const H=document.createElement("a");H.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-qr.png`,H.href=R.toDataURL("image/png"),H.click()},$.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(I)))},[s.property_address]),T=j.useCallback(()=>{var Fe;if(!v.current)return;const M=v.current.querySelector("svg");if(!M)return;const I=new XMLSerializer().serializeToString(M),R="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(I))),z=Gs(new Date(s.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy"),$=s.start_time?`${N(s.start_time)}${s.end_time?" – "+N(s.end_time):""}`:"",H=[s.city,s.state].filter(Boolean).join(", "),V=s.agent_greeting||"Welcome! Please sign in below.",K=!!s.photo_url,Z=!!c,Q=K||Z,le=K&&Z,ue=le?"0.35in 0.75in 0.3in":"0.55in 0.75in 0.45in",se=le?"28px":"34px",ne=le?"0.2in 0.75in":Q?"0.3in 0.75in":"0.4in 0.75in",ie=Q?"0.15in":"0.3in",ce=Q?"0.15in":"0.3in",je=le?"14px 36px":"22px 44px",be=le?"20px":"24px",he=Q?"0.2in":"0.35in",ge=le?"1.8in":"2.4in",ke=Q?"0.15in":"0.3in",Te=le?"140px":Q?"160px":"200px",Me=le?"16px":"24px",Oe=le?"10px 20px":"16px 28px",Se=le?"44px":"56px",Qe="0.15in",Ae=window.open("","_blank");Ae&&(Ae.document.write(` Open House – ${s.property_address}
${s.event_type==="community"?"Community Event":"Open House"}
${s.property_address}
${H?`
${H}${s.zip?" "+s.zip:""}
`:""}
Date
${z}
${$?`
Time
${$}
`:""}
${V}
${c?`
${c.avatar_url?`${c.name}`:`
${((Fe=c.name)==null?void 0:Fe.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
`),Ae.document.close(),setTimeout(()=>{Ae.focus(),Ae.print()},500))},[s,b,c]),L=async()=>{y(!0);try{const{error:M}=await q.functions.invoke("guestbook-email-link",{body:{openHouseId:s.id}});if(M)throw M;ka({title:"Email sent!",description:"Check your inbox for the guest book link."})}catch(M){ka({title:"Failed to send",description:M.message,variant:"destructive"})}finally{y(!1)}};return e.jsxs(we,{className:Mt("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:Mt("absolute inset-y-0 left-0 w-1",l?"bg-emerald-500":s.kind==="virtual"?"bg-purple-500/70":"bg-primary/40")}),e.jsx(Tt,{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(It,{className:"text-base leading-snug break-words",children:s.property_address}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1.5 flex-wrap",children:[l&&e.jsxs(Be,{className:"shrink-0 gap-1 border-none bg-emerald-500/15 text-[11px] text-emerald-700 dark:text-emerald-300",children:[e.jsx(mv,{className:"h-3 w-3"}),"Today"]}),e.jsx(Be,{variant:s.is_active?"default":"secondary",className:"shrink-0 text-[11px]",children:s.is_active?"Active":"Inactive"}),s.kind==="virtual"?e.jsxs(Be,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-purple-500/10 text-purple-700 dark:text-purple-300 border-purple-500/20",children:[e.jsx(xa,{className:"h-3 w-3"}),"Virtual"]}):e.jsxs(Be,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 border-emerald-500/20",children:[e.jsx(ni,{className:"h-3 w-3"}),"In-Person"]}),s.agent_name&&e.jsxs(Be,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-blue-500/10 text-blue-700 dark:text-blue-300 border-blue-500/20",children:[e.jsx(So,{className:"h-3 w-3"}),s.agent_name]}),s.event_type==="community"&&e.jsxs(Be,{variant:"outline",className:"shrink-0 gap-1 text-[11px]",children:[e.jsx(_i,{className:"h-3 w-3"}),"Community"]})]})]}),e.jsx(U,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0 -mr-2 -mt-1",children:t?e.jsx(dv,{className:"h-4 w-4"}):e.jsx(rl,{className:"h-4 w-4"})})]}),e.jsxs(Jn,{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(ni,{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(Yr,{className:"h-3 w-3"}),"Always on"]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pa,{className:"h-3 w-3"}),Gs(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(Yr,{className:"h-3 w-3"}),N(s.start_time),s.end_time?` – ${N(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(Bn,{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(Sf,{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(U,{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(mv,{className:"h-3.5 w-3.5"}),"Live"]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:r,className:"h-8 gap-1.5 text-xs",children:[e.jsx(Pa,{className:"h-3.5 w-3.5"}),"Copy Link"]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>u(!0),className:"h-8 gap-1.5 text-xs",children:[e.jsx(Sf,{className:"h-3.5 w-3.5"}),"QR Code"]}),s.kind==="virtual"?e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>f(!0),className:"h-8 gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10",children:[e.jsx(jd,{className:"h-3.5 w-3.5"}),"Email Tour"]}):e.jsxs(e.Fragment,{children:[e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>f(!0),className:"h-8 gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10",children:[e.jsx(ln,{className:"h-3.5 w-3.5"}),"Invite"]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>window.open(`${b}?kiosk=1`,"_blank"),className:"h-8 gap-1.5 text-xs",children:[e.jsx(bq,{className:"h-3.5 w-3.5"}),"Tablet Mode"]})]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>m(!0),className:"h-8 gap-1.5 text-xs",children:[e.jsx(qc,{className:"h-3.5 w-3.5"}),"Settings"]}),e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0","aria-label":"More actions",children:e.jsx(Z1,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",className:"w-52",children:[e.jsxs(La,{onClick:()=>window.open(b,"_blank"),children:[e.jsx(Sr,{className:"mr-2 h-4 w-4"}),"Preview sign-in page"]}),s.kind==="virtual"?e.jsxs(La,{onClick:()=>window.open(`/guestbook/${s.slug}?preview=1`,"_blank"),children:[e.jsx(xa,{className:"mr-2 h-4 w-4"}),"Preview tour"]}):e.jsxs(La,{onClick:()=>window.open(`https://${J4e}/rsvp/${s.slug}`,"_blank"),children:[e.jsx(cv,{className:"mr-2 h-4 w-4"}),"Preview RSVP page"]}),e.jsxs(La,{onClick:a,children:[s.is_active?e.jsx(Vg,{className:"mr-2 h-4 w-4"}):e.jsx(xa,{className:"mr-2 h-4 w-4"}),s.is_active?"Deactivate":"Activate"]}),e.jsx(l1,{}),e.jsxs(La,{onClick:i,className:"text-destructive focus:text-destructive",children:[e.jsx(In,{className:"mr-2 h-4 w-4"}),"Delete"]})]})]})]})]})}),t&&e.jsxs(Ie,{className:"pt-0",children:[e.jsx(hc,{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://",J4e,"/",s.slug]})]}),e.jsx(ytr,{visitors:o??[],onExport:S}),s.kind!=="virtual"&&e.jsx("div",{className:"mt-4",children:e.jsx(gtr,{openHouseId:s.id})}),s.kind==="virtual"&&e.jsx("div",{className:"mt-4",children:e.jsx(mtr,{openHouseId:s.id})}),s.enable_survey&&e.jsx("div",{className:"mt-4",children:e.jsx(utr,{openHouseId:s.id})})]}),e.jsx(zs,{open:d,onOpenChange:u,children:e.jsxs(Ds,{className:"sm:max-w-sm",children:[e.jsxs(Vs,{children:[e.jsx($s,{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(fS,{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(U,{variant:"outline",className:"flex-1",onClick:A,children:[e.jsx(pi,{className:"h-4 w-4 mr-2"}),"Download"]}),e.jsxs(U,{variant:"outline",className:"flex-1",onClick:T,children:[e.jsx(PA,{className:"h-4 w-4 mr-2"}),"Print Flyer"]})]}),e.jsxs(U,{variant:"default",className:"w-full",onClick:L,disabled:x,children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),x?"Sending...":"Email Link to Me"]})]})]})}),e.jsx(ctr,{open:h,onOpenChange:m,openHouse:s}),e.jsx(ftr,{open:p,onOpenChange:f,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 _tr=kN({full_name:sl().trim().min(2,"Please enter your name").max(120),email:sl().trim().email("Please enter a valid email").max(200),brokerage:sl().trim().min(2,"Please enter your brokerage").max(160)}),n5t=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():"",wtr=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 jtr(){var S;const{slug:s}=Di(),[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(""),[p,f]=j.useState(!1),[x,y]=j.useState(!1);j.useEffect(()=>{let A=!0;return(async()=>{n(!0);const{data:T,error:L}=await q.functions.invoke("resource-kit-public",{body:{slug:s}});A&&(L||!(T!=null&&T.kit)?c(!0):(a(T.kit),l(T.files??[])),n(!1))})(),()=>{A=!1}},[s]);const v=async A=>{A.preventDefault(),m("");const T=_tr.safeParse(d);if(!T.success){m(T.error.issues[0].message);return}f(!0);try{const{data:L,error:M}=await q.functions.invoke("resource-kit-unlock",{body:{slug:s,...T.data}});if(M)throw M;if(L!=null&&L.error)throw new Error("Something went wrong. Please try again.");l(L.files??[]),y(!0)}catch(L){m(L.message||"Something went wrong. Please try again.")}finally{f(!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=n5t(r.subheadline),N=(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:N}),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:N}),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(cn,{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,T)=>e.jsxs("li",{className:"flex items-start gap-3 text-slate-200",children:[e.jsx(zr,{className:"h-5 w-5 shrink-0 text-amber-400 mt-0.5"}),e.jsx("span",{className:"leading-relaxed",children:n5t(A)||A})]},T))}),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(Ur,{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:wtr(A.file_size)}),x&&A.file_url?e.jsx(U,{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(pi,{className:"h-3.5 w-3.5 mr-1"})," Download"]})}):e.jsx(Ql,{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(zr,{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(pi,{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(U,{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(te,{htmlFor:"full_name",className:"text-slate-200",children:"Agent name"}),e.jsx(xe,{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(te,{htmlFor:"email",className:"text-slate-200",children:"Email"}),e.jsx(xe,{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(te,{htmlFor:"brokerage",className:"text-slate-200",children:"Brokerage"}),e.jsx(xe,{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(U,{type:"submit",disabled:p,className:"w-full h-12 rounded-xl bg-amber-400 text-slate-900 font-bold hover:bg-amber-300",children:[p?"Unlocking…":r.cta_text,e.jsx(Oa,{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(cg,{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."]})]})]})})})]})]})]})}Snt.workerSrc=Cnt;const Ntr={signature:Pg,initials:wq,date_signed:nc,printed_name:So,text:_q},_ss={signature:"Signature",initials:"Initials",date_signed:"Date signed",printed_name:"Printed name",text:"Text"};function wss(){return new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"2-digit",day:"2-digit",year:"numeric"}).format(new Date)}function ktr(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 Str(){var K,Z,Q,le;const{token:s}=Di(),t=Wn(),[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),p=j.useRef([]),[f,x]=j.useState({}),[y,v]=j.useState({}),[b,N]=j.useState(null),[S,A]=j.useState(!1),[T,L]=j.useState(!1),[M,I]=j.useState(!1);j.useEffect(()=>{let ue=!1;return r(!0),i(null),o(null),d(null),h(null),x({}),A(!1),(async()=>{var ie;const{data:se,error:ne}=await q.functions.invoke("forms-sign-public",{body:{action:"load",token:s}});if(!ue){if(ne||se!=null&&se.error)i((se==null?void 0:se.error)||"This signing link could not be loaded.");else if(se.state==="already_signed")d("signed");else{o(se);const ce={};for(const je of se.fields||[])je.field_kind==="printed_name"&&(ce[je.id]={value:((ie=se.signer)==null?void 0:ie.full_name)||""}),je.field_kind==="date_signed"&&(ce[je.id]={value:wss()});x(ce)}r(!1)}})(),()=>{ue=!0}},[s]),j.useEffect(()=>{let ue=!1;const se=m.current;if(!(!(l!=null&&l.pdf_url)||!se))return(async()=>{try{const ie=await(await fetch(l.pdf_url)).arrayBuffer(),ce=await rTe({data:ie}).promise;if(ue)return;se.innerHTML="",p.current=[];const je=Math.min(se.clientWidth-16||700,820);for(let be=1;be<=ce.numPages;be++){const he=await ce.getPage(be);if(ue)return;const ge=he.getViewport({scale:1}),ke=je/ge.width,Te=he.getViewport({scale:ke*(window.devicePixelRatio||1)}),Me=document.createElement("div");Me.className="relative mx-auto shadow",Me.style.width=`${je}px`,Me.style.height=`${ge.height*ke}px`;const Oe=document.createElement("canvas");Oe.width=Math.floor(Te.width),Oe.height=Math.floor(Te.height),Oe.style.width="100%",Oe.style.height="100%",Oe.className="rounded-md border border-border bg-white",Me.appendChild(Oe),se.appendChild(Me),p.current[be-1]=Me;const Se=Oe.getContext("2d");Se&&await he.render({canvasContext:Se,viewport:Te}).promise}ue||x(be=>({...be}))}catch{ue||i("The document could not be displayed.")}})(),()=>{ue=!0}},[l==null?void 0:l.pdf_url]);const R=(l==null?void 0:l.fields)||[],z=R.filter(ue=>{var se,ne;return ue.is_required&&!((se=f[ue.id])!=null&&se.value)&&!((ne=f[ue.id])!=null&&ne.png)}),$=async()=>{if(!S){re.error("Please agree to sign electronically first.");return}if(z.length){re.error("Please complete every highlighted field.");return}L(!0);try{const{data:ue,error:se}=await q.functions.invoke("forms-sign-public",{body:{action:"submit",token:s,consent:!0,fields:R.filter(ne=>f[ne.id]).map(ne=>{var ie,ce;return{mapping_id:ne.id,value:(ie=f[ne.id])==null?void 0:ie.value,signature_png:(ce=f[ne.id])==null?void 0:ce.png}})}});if(se||ue!=null&&ue.error)throw new Error((ue==null?void 0:ue.error)||(se==null?void 0:se.message)||"Could not submit");ue!=null&&ue.next_token&&h({token:ue.next_token,title:ue.next_title??null}),d("signed"),window.scrollTo({top:0})}catch(ue){re.error((ue==null?void 0:ue.message)||"Could not finish signing")}finally{L(!1)}},H=async()=>{const ue=window.prompt("Optional: tell the sender why you are declining.")??"";I(!0),await q.functions.invoke("forms-sign-public",{body:{action:"decline",token:s,reason:ue}}),d("declined"),I(!1)},V=(ue,se)=>{x(ne=>({...ne,[ue.id]:se})),N(null)};return n?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-slate-100",children:e.jsx(Et,{className:"h-8 w-8 animate-spin text-[#406E71]"})}):a?e.jsx(Rce,{icon:e.jsx(ou,{className:"h-8 w-8 text-destructive"}),title:"Link unavailable",body:a}):c==="declined"?e.jsx(Rce,{icon:e.jsx(ou,{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(Rce,{icon:e.jsx(zr,{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(U,{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(Rce,{icon:e.jsx(zr,{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:(K=l==null?void 0:l.envelope)==null?void 0:K.title}),e.jsxs("p",{className:"text-xs opacity-80",children:["Signing as ",(Z=l==null?void 0:l.signer)==null?void 0:Z.full_name]})]})}),((Q=l==null?void 0:l.envelope)==null?void 0:Q.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"}),R.map(ue=>{const se=p.current[ue.page_index];if(!se)return null;const ne=f[ue.id],ie=!!(ne!=null&&ne.png||ne!=null&&ne.value),ce=Ntr[ue.field_kind];return e.jsx(r5t,{target:se,children:e.jsx("button",{onClick:()=>N(ue),className:`absolute flex items-center justify-center gap-1 rounded-sm border-2 transition-colors ${ie?"border-emerald-500 bg-emerald-500/10":"animate-pulse border-[#406E71] bg-[#406E71]/15 hover:bg-[#406E71]/25"}`,style:{left:`${ue.pos_x*100}%`,top:`${ue.pos_y*100}%`,width:`${ue.width*100}%`,height:`${ue.height*100}%`},children:ne!=null&&ne.png?e.jsx("img",{src:ne.png,alt:ue.label||"Signature",className:"max-h-full max-w-full object-contain"}):ne!=null&&ne.value?e.jsx("span",{className:"truncate px-1 text-[10px] font-medium text-emerald-800",children:ne.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"})," ",ue.label||_ss[ue.field_kind]]})})},ue.id)}),((l==null?void 0:l.data_overlays)||[]).map(ue=>{const se=p.current[ue.page_index];return!se||!ue.value?null:e.jsx(r5t,{target:se,children:e.jsx("div",{className:"pointer-events-none absolute flex items-center",style:{left:`${ue.pos_x*100}%`,top:`${ue.pos_y*100}%`,width:`${ue.width*100}%`,height:`${ue.height*100}%`},children:e.jsx("span",{className:"truncate px-0.5 text-[10px] text-slate-900",children:ue.value})})},ue.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(xi,{checked:S,onCheckedChange:ue=>A(!!ue),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(U,{className:"flex-1 bg-[#406E71] hover:bg-[#355c5f]",disabled:T||!S||z.length>0,onClick:$,children:[T?e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Pg,{className:"mr-2 h-4 w-4"}),z.length>0?`${z.length} field${z.length===1?"":"s"} left`:"Finish signing"]}),e.jsx(U,{variant:"ghost",size:"sm",disabled:M,onClick:H,className:"text-muted-foreground",children:"Decline"})]})]})}),e.jsx(Ctr,{field:b,signerName:((le=l==null?void 0:l.signer)==null?void 0:le.full_name)||"",current:b?f[b.id]:void 0,adopted:y,onAdopt:(ue,se)=>{v(ne=>({...ne,[ue]:se})),x(ne=>{var ce;const ie={...ne};for(const je of R)je.field_kind===ue&&!((ce=ie[je.id])!=null&&ce.png)&&(ie[je.id]={png:se});return ie})},onClose:()=>N(null),onApply:V})]})}function Rce({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 r5t({target:s,children:t}){return tv.createPortal(t,s)}function Ctr({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),[p,f]=j.useState("");j.useEffect(()=>{if(!s)return;f((n==null?void 0:n.value)||(s.field_kind==="printed_name"?t:s.field_kind==="date_signed"?wss():"")),u(s.field_kind==="initials"?t.split(" ").map(S=>S[0]).join(""):t);const N=h.current;if(N){const S=N.getContext("2d");S==null||S.clearRect(0,0,N.width,N.height)}},[s==null?void 0:s.id]);const x=N=>{const S=h.current;if(!S)return;m.current=!0,S.setPointerCapture(N.pointerId);const A=S.getContext("2d"),T=S.getBoundingClientRect();A.strokeStyle="#12233f",A.lineWidth=3,A.lineCap="round",A.beginPath(),A.moveTo((N.clientX-T.left)/T.width*S.width,(N.clientY-T.top)/T.height*S.height)},y=N=>{if(!m.current)return;const S=h.current;if(!S)return;const A=S.getContext("2d"),T=S.getBoundingClientRect();A.lineTo((N.clientX-T.left)/T.width*S.width,(N.clientY-T.top)/T.height*S.height),A.stroke()},v=()=>{m.current=!1},b=(N,S)=>{s&&(S&&o&&a(c,N),l(s,{png:N}))};return e.jsx(my,{open:!!s,onOpenChange:N=>!N&&i(),children:e.jsxs(g0,{side:"bottom",className:"mx-auto max-w-lg rounded-t-2xl",children:[e.jsx(vv,{className:"text-left",children:e.jsx(bv,{className:"text-base",children:(s==null?void 0:s.label)||(s?_ss[s.field_kind]:"")})}),s&&o&&e.jsxs(oa,{defaultValue:r[c]?"saved":"draw",className:"mt-3",children:[e.jsxs(la,{className:"grid w-full grid-cols-3",children:[e.jsx(Kt,{value:"draw",children:"Draw"}),e.jsx(Kt,{value:"type",children:"Type"}),e.jsx(Kt,{value:"saved",disabled:!r[c],children:"Saved"})]}),e.jsxs(Zt,{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(U,{variant:"outline",size:"sm",onClick:()=>{var S;const N=h.current;(S=N==null?void 0:N.getContext("2d"))==null||S.clearRect(0,0,N.width,N.height)},children:[e.jsx(LX,{className:"mr-1 h-3.5 w-3.5"})," Clear"]}),e.jsxs(U,{size:"sm",className:"flex-1 bg-[#406E71] hover:bg-[#355c5f]",onClick:()=>{const N=h.current;N&&b(N.toDataURL("image/png"),!0)},children:["Use this ",s.field_kind==="initials"?"initials":"signature"," everywhere"]})]})]}),e.jsxs(Zt,{value:"type",className:"space-y-3 pt-3",children:[e.jsx(xe,{value:d,onChange:N=>u(N.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(U,{size:"sm",className:"w-full bg-[#406E71] hover:bg-[#355c5f]",disabled:!d.trim(),onClick:()=>b(ktr(d.trim(),s.field_kind==="signature"),!0),children:"Use this everywhere"})]}),e.jsx(Zt,{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(U,{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(xe,{value:p,onChange:N=>f(N.target.value),autoFocus:!0}),e.jsx(U,{size:"sm",className:"w-full bg-[#406E71] hover:bg-[#355c5f]",disabled:!p.trim(),onClick:()=>l(s,{value:p.trim()}),children:"Apply"})]})]})})}const a5t="https://dashboard.relevelup.com/trial",Atr=["Full LevelUp Agent OS access","300+ marketing templates & AI tools","Cancel anytime — no risk"];function TKe({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(cn,{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:a5t,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(Oa,{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(cn,{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:Atr.map(n=>e.jsxs("li",{className:"flex items-start gap-2 text-sm text-slate-200",children:[e.jsx(Xr,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-400"}),e.jsx("span",{children:n})]},n))}),e.jsxs("a",{href:a5t,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(Oa,{className:"h-5 w-5"})]})]})]})}const i5t=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)))},Etr=s=>{const t=s.replace(/<[^>]*>/g," ").split(/\s+/).filter(Boolean).length;return Math.max(1,Math.round(t/220))};function Ttr(){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(xr,{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(xr,{to:`/blog/${c.slug}`,className:"group mt-12 grid gap-8 overflow-hidden rounded-3xl border border-white/10 bg-white/5 p-6 transition hover:border-amber-400/30 md:grid-cols-2 md:p-8",children:[c.cover_image_url&&e.jsx("div",{className:"overflow-hidden rounded-2xl",children:e.jsx("img",{src:c.cover_image_url,alt:c.title,className:"h-56 w-full object-cover transition duration-500 group-hover:scale-105 md:h-72"})}),e.jsxs("div",{className:"flex flex-col justify-center",children:[e.jsxs("div",{className:"flex items-center gap-3 text-xs text-slate-400",children:[c.category&&e.jsx(Be,{className:"border-amber-400/30 bg-amber-400/15 text-amber-200",children:c.category}),e.jsx("span",{children:i5t(c.published_at)}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Yr,{className:"h-3 w-3"})," ",Etr(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(Oa,{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(xr,{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:i5t(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(Oa,{className:"h-3.5 w-3.5 transition group-hover:translate-x-1"})]})]})]},u.id))})]}),e.jsx(TKe,{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(xr,{to:"/",className:"hover:text-slate-300",children:"Home"})]})]})]})}const Mtr=s=>(s||"LevelUp Member").split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase(),Ptr=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 Ltr({postId:s,allowComments:t}){const{user:n}=vs(),[r,a]=j.useState([]),[i,l]=j.useState(!0),[o,c]=j.useState(""),[d,u]=j.useState(null),[h,m]=j.useState(""),[p,f]=j.useState(!1),x=j.useCallback(async()=>{l(!0);const{data:A,error:T}=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(T){l(!1);return}const L=A||[],M=[...new Set(L.map(I=>I.user_id))];if(M.length){const{data:I}=await q.from("profiles").select("id, name, avatar_url").in("id",M),R=new Map((I||[]).map(z=>[z.id,z]));L.forEach(z=>{z.author=R.get(z.user_id)})}a(L),l(!1)},[s]);j.useEffect(()=>{x()},[x]);const y=async(A,T)=>{if(!n){re.error("Sign in to comment");return}if(!A.trim())return;f(!0);const{error:L}=await q.from("blog_comments").insert({post_id:s,user_id:n.id,parent_id:T,body:A.trim()});if(f(!1),L){re.error(L.message);return}c(""),m(""),u(null),re.success("Comment posted"),x()},v=async A=>{const{error:T}=await q.from("blog_comments").delete().eq("id",A);if(T){re.error(T.message);return}x()},b=r.filter(A=>!A.parent_id),N=A=>r.filter(T=>T.parent_id===A),S=({c:A,nested:T=!1})=>{var L,M,I;return e.jsxs("div",{className:`flex gap-3 ${T?"ml-10 mt-4":"mt-6"}`,children:[e.jsxs(Ea,{className:"h-9 w-9 shrink-0",children:[e.jsx(Ci,{src:((L=A.author)==null?void 0:L.avatar_url)||void 0}),e.jsx(Ta,{className:"bg-white/10 text-xs text-white",children:Mtr((M=A.author)==null?void 0:M.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:((I=A.author)==null?void 0:I.name)||"LevelUp Member"}),e.jsx("span",{className:"text-xs text-slate-500",children:Ptr(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:[!T&&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(MX,{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(In,{className:"h-3 w-3"})," Delete"]})]}),d===A.id&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Fs,{value:h,onChange:R=>m(R.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(U,{size:"sm",disabled:p,onClick:()=>y(h,A.id),children:[p&&e.jsx(Et,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"})," Post reply"]}),e.jsx(U,{size:"sm",variant:"ghost",className:"text-slate-400",onClick:()=>u(null),children:"Cancel"})]})]}),N(A.id).map(R=>e.jsx(S,{c:R,nested:!0},R.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(vu,{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(Fs,{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(U,{disabled:p||!o.trim(),onClick:()=>y(o,null),children:[p&&e.jsx(Et,{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(xr,{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(Et,{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 o5t=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)))},Itr=s=>Math.max(1,Math.round(s.replace(/<[^>]*>/g," ").split(/\s+/).filter(Boolean).length/220));function Rtr(){var h;const{slug:s=""}=Di(),[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:p}=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(p||[])}})()},[s]);const o=typeof window<"u"?`${window.location.origin}/blog/${s}`:"",c=async m=>{const p=encodeURIComponent((t==null?void 0:t.title)||"LevelUp"),f=encodeURIComponent(o),x={facebook:`https://www.facebook.com/sharer/sharer.php?u=${f}`,linkedin:`https://www.linkedin.com/sharing/share-offsite/?url=${f}`,twitter:`https://twitter.com/intent/tweet?url=${f}&text=${p}`,email:`mailto:?subject=${p}&body=${f}`};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(xr,{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(xr,{to:"/blog",className:"inline-flex items-center gap-2 text-sm font-medium text-slate-400 hover:text-white",children:[e.jsx(Aa,{className:"h-4 w-4"})," All articles"]}),e.jsxs("div",{className:"mt-8 grid gap-12 lg:grid-cols-[minmax(0,1fr)_300px]",children:[e.jsxs("article",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-slate-400",children:[t.category&&e.jsx(Be,{className:"border-amber-400/30 bg-amber-400/15 text-amber-200",children:t.category}),e.jsx("span",{children:o5t(t.published_at)}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Yr,{className:"h-3 w-3"})," ",Itr(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(Ea,{className:"h-11 w-11",children:[e.jsx(Ci,{src:t.author_avatar_url||void 0}),e.jsx(Ta,{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(ad,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>c("facebook"),title:"Share on Facebook",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white",children:e.jsx(zp,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>c("linkedin"),title:"Share on LinkedIn",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white",children:e.jsx(Gg,{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(mQ,{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(ln,{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(jd,{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(TKe,{className:"mt-14"}),e.jsx(Ltr,{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(TKe,{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(xr,{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:o5t(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(xr,{to:"/blog",className:"hover:text-slate-300",children:"Blog"})]})]})]})}const Dtr=/^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu\.be|youtube-nocookie\.com))(\/(?:[\w-]+\?v=|embed\/|v\/)?)([\w-]+)(\S+)?$/,Otr=/^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu\.be|youtube-nocookie\.com))(\/(?:[\w-]+\?v=|embed\/|v\/)?)([\w-]+)(\S+)?$/g,jss=s=>s.match(Dtr),Ftr=(s,t)=>t?"https://www.youtube-nocookie.com/embed/videoseries?list=":s?"https://www.youtube-nocookie.com/embed/":"https://www.youtube.com/embed/",ztr=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,Btr=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:p,modestBranding:f,nocookie:x,origin:y,playlist:v,progressBarColor:b,startAt:N,rel:S}=s;if(!jss(n))return null;if(n.includes("/embed/"))return n;const A=new URL(n),{id:T,isPlaylist:L}=(t=ztr(A))!==null&&t!==void 0?t:{};if(!T)return null;const M=new URL(`${Ftr(x,L)}${T}`);return A.searchParams.has("t")&&M.searchParams.set("start",A.searchParams.get("t").replaceAll("s","")),r===!1&&M.searchParams.set("fs","0"),a&&M.searchParams.set("autoplay","1"),i&&M.searchParams.set("cc_lang_pref",i),l&&M.searchParams.set("cc_load_policy","1"),o||M.searchParams.set("controls","0"),c&&M.searchParams.set("disablekb","1"),d&&M.searchParams.set("enablejsapi","1"),u&&M.searchParams.set("end",u.toString()),h&&M.searchParams.set("hl",h),m&&M.searchParams.set("iv_load_policy",m.toString()),p&&M.searchParams.set("loop","1"),f&&M.searchParams.set("modestbranding","1"),y&&M.searchParams.set("origin",y),v&&M.searchParams.set("playlist",v),N&&M.searchParams.set("start",N.toString()),b&&M.searchParams.set("color",b),S!==void 0&&M.searchParams.set("rel",S.toString()),M.toString()},Utr=fy.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})=>jss(s.src)?t.insertContent({type:this.name,attrs:s}):!1}},addPasteRules(){return this.options.addPasteHandler?[uHs({find:Otr,type:this.type,getAttributes:s=>({src:s.input})})]:[]},renderHTML({HTMLAttributes:s}){const t=Btr({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",Dm(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)]]}}),qtr=fy.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",Dm(s,{controls:"true",playsinline:"true",preload:"metadata",class:"w-full rounded-xl"})]}}),zx=({onClick:s,active:t,title:n,children:r,disabled:a})=>e.jsx(U,{type:"button",variant:t?"secondary":"ghost",size:"sm",className:"h-8 w-8 p-0",title:n,disabled:a,onClick:s,children:r});function $tr({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),p=j.useRef(null),f=j.useRef(null),x=wPe({extensions:[jPe.configure({heading:{levels:[2,3,4]}}),css,kPe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),jzt.configure({HTMLAttributes:{class:"rounded-xl w-full"}}),SPe.configure({types:["heading","paragraph"]}),Utr.configure({width:960,height:540,HTMLAttributes:{class:"w-full aspect-video rounded-xl"}}),qtr],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:N})=>t(N.getHTML())});j.useEffect(()=>{x&&s!==x.getHTML()&&x.commands.setContent(s||"",!1)},[s]);const y=j.useCallback(async(N,S)=>{var R;const{data:A}=await q.auth.getUser(),T=(R=A.user)==null?void 0:R.id;if(!T)return re.error("You must be signed in"),null;const L=N.name.split(".").pop()||(S==="image"?"jpg":"mp4"),M=`${T}/blog/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${L}`,{error:I}=await q.storage.from("email-assets").upload(M,N,{cacheControl:"31536000",upsert:!1});return I?(re.error(`Upload failed: ${I.message}`),null):q.storage.from("email-assets").getPublicUrl(M).data.publicUrl},[]),v=async(N,S)=>{if(!N||!x)return;m(!0);const A=await y(N,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(zx,{title:"Bold",active:b.isActive("bold"),onClick:()=>b.chain().focus().toggleBold().run(),children:e.jsx(wA,{className:"h-4 w-4"})}),e.jsx(zx,{title:"Italic",active:b.isActive("italic"),onClick:()=>b.chain().focus().toggleItalic().run(),children:e.jsx(kA,{className:"h-4 w-4"})}),e.jsx(zx,{title:"Underline",active:b.isActive("underline"),onClick:()=>b.chain().focus().toggleUnderline().run(),children:e.jsx(UF,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(zx,{title:"Heading",active:b.isActive("heading",{level:2}),onClick:()=>b.chain().focus().toggleHeading({level:2}).run(),children:e.jsx(AF,{className:"h-4 w-4"})}),e.jsx(zx,{title:"Subheading",active:b.isActive("heading",{level:3}),onClick:()=>b.chain().focus().toggleHeading({level:3}).run(),children:e.jsx(JU,{className:"h-4 w-4"})}),e.jsx(zx,{title:"Bullet list",active:b.isActive("bulletList"),onClick:()=>b.chain().focus().toggleBulletList().run(),children:e.jsx(m0,{className:"h-4 w-4"})}),e.jsx(zx,{title:"Numbered list",active:b.isActive("orderedList"),onClick:()=>b.chain().focus().toggleOrderedList().run(),children:e.jsx(sj,{className:"h-4 w-4"})}),e.jsx(zx,{title:"Quote",active:b.isActive("blockquote"),onClick:()=>b.chain().focus().toggleBlockquote().run(),children:e.jsx(tS,{className:"h-4 w-4"})}),e.jsx(zx,{title:"Code block",active:b.isActive("codeBlock"),onClick:()=>b.chain().focus().toggleCodeBlock().run(),children:e.jsx(jA,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(zx,{title:"Align left",active:b.isActive({textAlign:"left"}),onClick:()=>b.chain().focus().setTextAlign("left").run(),children:e.jsx(_M,{className:"h-4 w-4"})}),e.jsx(zx,{title:"Align center",active:b.isActive({textAlign:"center"}),onClick:()=>b.chain().focus().setTextAlign("center").run(),children:e.jsx(bM,{className:"h-4 w-4"})}),e.jsx(zx,{title:"Align right",active:b.isActive({textAlign:"right"}),onClick:()=>b.chain().focus().setTextAlign("right").run(),children:e.jsx(wM,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(zx,{title:"Link",active:b.isActive("link"),onClick:()=>{l(b.getAttributes("link").href||""),a(!0)},children:e.jsx(Rc,{className:"h-4 w-4"})}),e.jsx(zx,{title:"Insert image",disabled:h,onClick:()=>{var N;return(N=p.current)==null?void 0:N.click()},children:e.jsx(ly,{className:"h-4 w-4"})}),e.jsx(zx,{title:"Upload video",disabled:h,onClick:()=>{var N;return(N=f.current)==null?void 0:N.click()},children:e.jsx(Wr,{className:"h-4 w-4"})}),e.jsx(zx,{title:"Embed YouTube / Vimeo",onClick:()=>{u(""),c(!0)},children:e.jsx(Sq,{className:"h-4 w-4"})}),e.jsx(zx,{title:"Divider",onClick:()=>b.chain().focus().setHorizontalRule().run(),children:e.jsx(Z2,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(zx,{title:"Undo",onClick:()=>b.chain().focus().undo().run(),children:e.jsx(RA,{className:"h-4 w-4"})}),e.jsx(zx,{title:"Redo",onClick:()=>b.chain().focus().redo().run(),children:e.jsx(LA,{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(Et,{className:"h-3.5 w-3.5 animate-spin"})," Uploading…"]})]}),e.jsx(_Pe,{editor:x,"data-placeholder":n}),e.jsx("input",{ref:p,type:"file",accept:"image/*",className:"hidden",onChange:N=>{var S;v((S=N.target.files)==null?void 0:S[0],"image"),N.target.value=""}}),e.jsx("input",{ref:f,type:"file",accept:"video/*",className:"hidden",onChange:N=>{var S;v((S=N.target.files)==null?void 0:S[0],"video"),N.target.value=""}}),e.jsx(zs,{open:r,onOpenChange:a,children:e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Insert link"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"URL"}),e.jsx(xe,{value:i,onChange:N=>l(N.target.value),placeholder:"https://…"})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>{b.chain().focus().unsetLink().run(),a(!1)},children:"Remove link"}),e.jsx(U,{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(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Embed a video"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"YouTube or Vimeo URL"}),e.jsx(xe,{value:d,onChange:N=>u(N.target.value),placeholder:"https://youtube.com/watch?v=…"})]}),e.jsx(Mr,{children:e.jsx(U,{onClick:()=>{const N=d.trim();if(N){if(/vimeo\.com/i.test(N)){const S=N.split("/").filter(Boolean).pop();b.chain().focus().insertContent(`
`).run()}else b.commands.setYoutubeVideo({src:N});c(!1)}},children:"Embed"})})]})})]})}const Dce=s=>s.toLowerCase().trim().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,80),Vtr=()=>({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 Htr(){const{user:s}=vs(),[t,n]=j.useState([]),[r,a]=j.useState(!0),[i,l]=j.useState(null),[o,c]=j.useState(!1),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,f]=j.useState(!1),x=j.useRef(null),[y,v]=j.useState([]),b=async()=>{a(!0);const{data:z,error:$}=await q.from("blog_posts").select("*").order("created_at",{ascending:!1});$&&re.error($.message),n(z||[]),a(!1)},N=async()=>{const{data:z}=await q.from("blog_comments").select("id, body, created_at, is_hidden, user_id, post_id").order("created_at",{ascending:!1}).limit(200),$=z||[],H=[...new Set($.map(ue=>ue.user_id))],V=[...new Set($.map(ue=>ue.post_id))],[{data:K},{data:Z}]=await Promise.all([H.length?q.from("profiles").select("id, name, email").in("id",H):Promise.resolve({data:[]}),V.length?q.from("blog_posts").select("id, title, slug").in("id",V):Promise.resolve({data:[]})]),Q=new Map((K||[]).map(ue=>[ue.id,ue])),le=new Map((Z||[]).map(ue=>[ue.id,ue]));v($.map(ue=>({...ue,author:Q.get(ue.user_id),post:le.get(ue.post_id)})))};j.useEffect(()=>{b(),N()},[]);const S=j.useMemo(()=>t.filter(z=>z.title.toLowerCase().includes(d.toLowerCase())),[t,d]),A=async z=>{if(!z||!s)return;f(!0);const $=z.name.split(".").pop()||"jpg",H=`${s.id}/blog/cover-${Date.now()}.${$}`,{error:V}=await q.storage.from("email-assets").upload(H,z);if(f(!1),V){re.error(V.message);return}const K=q.storage.from("email-assets").getPublicUrl(H).data.publicUrl;l(Z=>({...Z||{},cover_image_url:K}))},T=async z=>{if(!i)return;const $=(i.title||"").trim();if(!$){re.error("Give the article a title");return}const H=Dce(i.slug||$),V=z===void 0?i.status||"draft":z?"published":"draft";c(!0);const K={title:$,slug:H,excerpt:i.excerpt||null,content:i.content||"",cover_image_url:i.cover_image_url||null,category:i.category||null,tags:i.tags||[],author_name:i.author_name||"Jeremy Collins",author_title:i.author_title||"Founder, LevelUp",author_avatar_url:i.author_avatar_url||null,status:V,featured:!!i.featured,allow_comments:i.allow_comments!==!1,seo_title:i.seo_title||null,seo_description:i.seo_description||null,published_at:V==="published"?i.published_at||new Date().toISOString():i.published_at||null};let Z;if(i.id)({error:Z}=await q.from("blog_posts").update(K).eq("id",i.id));else{K.created_by=(s==null?void 0:s.id)||null;const Q=await q.from("blog_posts").insert(K).select().single();Z=Q.error,Q.data&&l(Q.data)}if(c(!1),Z){re.error(Z.message);return}re.success(V==="published"?"Published":"Saved"),b()},L=async z=>{if(!confirm("Delete this article and its comments?"))return;const{error:$}=await q.from("blog_posts").delete().eq("id",z);if($){re.error($.message);return}re.success("Deleted"),(i==null?void 0:i.id)===z&&l(null),b()},M=async z=>{const $=z.status==="published"?"draft":"published",{error:H}=await q.from("blog_posts").update({status:$,published_at:$==="published"?z.published_at||new Date().toISOString():z.published_at}).eq("id",z.id);if(H){re.error(H.message);return}b()},I=async z=>{const{error:$}=await q.from("blog_comments").update({is_hidden:!z.is_hidden}).eq("id",z.id);if($){re.error($.message);return}N()},R=async z=>{const{error:$}=await q.from("blog_comments").delete().eq("id",z);if($){re.error($.message);return}N()};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(U,{variant:"ghost",onClick:()=>l(null),children:[e.jsx(Aa,{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(U,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`/blog/${i.slug}`,target:"_blank",rel:"noreferrer",children:[e.jsx(Sr,{className:"mr-2 h-4 w-4"})," View live"]})}),e.jsxs(U,{variant:"outline",disabled:o,onClick:()=>T(!1),children:[o&&e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"})," Save draft"]}),e.jsxs(U,{disabled:o,onClick:()=>T(!0),children:[o&&e.jsx(Et,{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(xe,{value:i.title||"",onChange:z=>l({...i,title:z.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(Fs,{value:i.excerpt||"",onChange:z=>l({...i,excerpt:z.target.value}),placeholder:"Short excerpt shown on the blog index and social previews…",rows:2}),e.jsx($tr,{content:i.content||"",onChange:z=>l($=>({...$||{},content:z}))})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(we,{children:e.jsxs(Ie,{className:"space-y-4 pt-6",children:[e.jsxs("div",{children:[e.jsx(te,{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(U,{variant:"outline",size:"sm",className:"w-full",onClick:()=>l({...i,cover_image_url:null}),children:"Remove"})]}):e.jsxs(U,{variant:"outline",className:"mt-2 w-full",disabled:p,onClick:()=>{var z;return(z=x.current)==null?void 0:z.click()},children:[p?e.jsx(Et,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(ly,{className:"mr-2 h-4 w-4"}),"Upload cover"]}),e.jsx("input",{ref:x,type:"file",accept:"image/*",className:"hidden",onChange:z=>{var $;A(($=z.target.files)==null?void 0:$[0]),z.target.value=""}})]}),e.jsxs("div",{children:[e.jsx(te,{children:"URL slug"}),e.jsx(xe,{className:"mt-1",value:i.slug||"",onChange:z=>l({...i,slug:z.target.value}),onBlur:z=>l({...i,slug:Dce(z.target.value||i.title||"")}),placeholder:Dce(i.title||"")||"my-article"}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["/blog/",i.slug||Dce(i.title||"")||"…"]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Category"}),e.jsx(xe,{className:"mt-1",value:i.category||"",onChange:z=>l({...i,category:z.target.value}),placeholder:"e.g. Lead Generation"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Tags"}),e.jsx("div",{className:"mt-1 flex gap-2",children:e.jsx(xe,{value:h,onChange:z=>m(z.target.value),placeholder:"Add a tag and press Enter",onKeyDown:z=>{z.key==="Enter"&&h.trim()&&(z.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((z,$)=>e.jsxs(Be,{variant:"secondary",className:"cursor-pointer",onClick:()=>l({...i,tags:(i.tags||[]).filter((H,V)=>V!==$)}),children:[z," ×"]},`${z}-${$}`))})]}),e.jsx(hc,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{htmlFor:"featured",children:"Featured article"}),e.jsx(wn,{id:"featured",checked:!!i.featured,onCheckedChange:z=>l({...i,featured:z})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{htmlFor:"comments",children:"Allow comments"}),e.jsx(wn,{id:"comments",checked:i.allow_comments!==!1,onCheckedChange:z=>l({...i,allow_comments:z})})]})]})}),e.jsx(we,{children:e.jsxs(Ie,{className:"space-y-4 pt-6",children:[e.jsx("div",{className:"text-sm font-semibold",children:"Author"}),e.jsx(xe,{value:i.author_name||"",placeholder:"Author name",onChange:z=>l({...i,author_name:z.target.value})}),e.jsx(xe,{value:i.author_title||"",placeholder:"Author title",onChange:z=>l({...i,author_title:z.target.value})}),e.jsx(xe,{value:i.author_avatar_url||"",placeholder:"Author photo URL (optional)",onChange:z=>l({...i,author_avatar_url:z.target.value})})]})}),e.jsx(we,{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(te,{className:"text-xs",children:"SEO title"}),e.jsx(xe,{className:"mt-1",maxLength:60,value:i.seo_title||"",onChange:z=>l({...i,seo_title:z.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Meta description"}),e.jsx(Fs,{className:"mt-1",maxLength:160,rows:3,value:i.seo_description||"",onChange:z=>l({...i,seo_description:z.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(U,{onClick:()=>l(Vtr()),children:[e.jsx(an,{className:"mr-2 h-4 w-4"})," New article"]})]}),e.jsxs(oa,{defaultValue:"articles",children:[e.jsxs(la,{children:[e.jsxs(Kt,{value:"articles",children:["Articles (",t.length,")"]}),e.jsxs(Kt,{value:"comments",children:["Comments (",y.length,")"]})]}),e.jsxs(Zt,{value:"articles",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{className:"pl-9",value:d,onChange:z=>u(z.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(Et,{className:"h-4 w-4 animate-spin"})," Loading…"]}):S.length===0?e.jsx(we,{children:e.jsx(Ie,{className:"py-12 text-center text-sm text-muted-foreground",children:"No articles yet. Write your first one."})}):S.map(z=>e.jsx(we,{className:"transition hover:border-primary/30",children:e.jsxs(Ie,{className:"flex flex-wrap items-center gap-4 py-4",children:[z.cover_image_url?e.jsx("img",{src:z.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(z),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate font-semibold",children:z.title}),z.featured&&e.jsx(Ua,{className:"h-3.5 w-3.5 fill-amber-400 text-amber-400"})]}),e.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Be,{variant:z.status==="published"?"default":"secondary",children:z.status}),z.category&&e.jsx("span",{children:z.category}),e.jsxs("span",{children:[z.view_count," views"]}),e.jsxs("span",{children:["/blog/",z.slug]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(U,{variant:"ghost",size:"sm",title:"Toggle publish",onClick:()=>M(z),children:z.status==="published"?e.jsx(Vg,{className:"h-4 w-4"}):e.jsx(xa,{className:"h-4 w-4"})}),z.status==="published"&&e.jsx(U,{variant:"ghost",size:"sm",asChild:!0,children:e.jsx("a",{href:`/blog/${z.slug}`,target:"_blank",rel:"noreferrer",children:e.jsx(Sr,{className:"h-4 w-4"})})}),e.jsx(U,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>L(z.id),children:e.jsx(In,{className:"h-4 w-4"})})]})]})},z.id))]}),e.jsx(Zt,{value:"comments",className:"mt-4 space-y-3",children:y.length===0?e.jsx(we,{children:e.jsx(Ie,{className:"py-12 text-center text-sm text-muted-foreground",children:"No comments yet."})}):y.map(z=>{var $,H,V;return e.jsx(we,{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:[(($=z.author)==null?void 0:$.name)||((H=z.author)==null?void 0:H.email)||"Member",e.jsxs("span",{className:"ml-2 font-normal text-muted-foreground",children:["on “",((V=z.post)==null?void 0:V.title)||"article","”"]})]}),e.jsx("p",{className:"mt-1 whitespace-pre-wrap text-sm text-muted-foreground",children:z.body})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[z.is_hidden&&e.jsx(Be,{variant:"secondary",children:"hidden"}),e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>I(z),children:z.is_hidden?e.jsx(xa,{className:"h-4 w-4"}):e.jsx(Vg,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>R(z.id),children:e.jsx(In,{className:"h-4 w-4"})})]})]})},z.id)})})]})]})}const Gtr=["What was it like working together?","What moment stood out the most?","Would you recommend me to a friend?"];function Wtr(s){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(String(r.result)),r.onerror=n,r.readAsDataURL(s)})}function Ktr(){var T,L,M,I,R,z,$;const{token:s}=Di(),[t,n]=j.useState(null),[r,a]=j.useState(!0),[i,l]=j.useState("none"),[o,c]=j.useState(""),[d,u]=j.useState(5),[h,m]=j.useState(""),[p,f]=j.useState(!1),[x,y]=j.useState(!1),[v,b]=j.useState(null);j.useEffect(()=>{(async()=>{const{data:H}=await q.rpc("get_review_request_by_token",{_token:s}),V=H;n(V),V!=null&&V.recipient_name&&c(V.recipient_name),a(!1)})()},[s]);const N=j.useCallback(()=>{q.functions.invoke("review-public",{body:{action:"clicked",token:s}}).catch(()=>{}),t!=null&&t.google_review_link&&window.open(t.google_review_link,"_blank","noopener")},[s,t]),S=j.useCallback(async H=>{f(!0),b(null);try{const V={action:"submit",token:s,reviewer_name:o,rating:d,review_text:h||void 0};H&&(V.video_base64=await Wtr(H),V.video_type=H.type||"video/webm");const{data:K,error:Z}=await q.functions.invoke("review-public",{body:V});if(Z||K!=null&&K.error)throw new Error((K==null?void 0:K.error)||(Z==null?void 0:Z.message)||"Something went wrong");y(!0)}catch(V){b(V.message)}finally{f(!1)}},[s,o,d,h]);if(r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f7f5f1]",children:e.jsx(Et,{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 text-center",children:"This review link is invalid or has expired."})});const A=((T=t.agent)==null?void 0:T.name)||"Your agent";return x?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f7f5f1] p-6",children:e.jsxs("div",{className:"text-center max-w-md",children:[e.jsx(zr,{className:"h-16 w-16 text-[#406E71] mx-auto mb-4"}),e.jsx("h1",{className:"text-3xl font-serif text-[#2a4c64] mb-2",children:"Thank you!"}),e.jsxs("p",{className:"text-slate-600",children:["Your review means the world to ",((M=(L=t.agent)==null?void 0:L.name)==null?void 0:M.split(" ")[0])||"us",". We appreciate you taking the time."]})]})}):e.jsx("div",{className:"min-h-screen bg-[#f7f5f1] py-10 px-4",children:e.jsxs("div",{className:"max-w-lg mx-auto",children:[e.jsxs("div",{className:"text-center mb-8",children:[((I=t.agent)==null?void 0:I.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:A,className:"w-20 h-20 rounded-full object-cover mx-auto mb-4 border-4 border-white shadow-lg"}),e.jsx("h1",{className:"text-3xl font-serif text-[#2a4c64]",children:A}),((R=t.agent)==null?void 0:R.title)&&e.jsx("p",{className:"text-slate-500 text-sm mt-1",children:t.agent.title}),e.jsx("p",{className:"text-slate-600 mt-4",children:"Thank you for your trust. How would you like to share your experience?"})]}),e.jsx("div",{className:"flex justify-center gap-1 mb-8",children:[1,2,3,4,5].map(H=>e.jsx("button",{onClick:()=>u(H),"aria-label":`${H} stars`,children:e.jsx(Ua,{className:Mt("h-8 w-8 transition-colors",H<=d?"fill-[#c9a24b] text-[#c9a24b]":"text-slate-300")})},H))}),i==="none"&&e.jsxs("div",{className:"grid gap-4",children:[t.google_review_link&&e.jsx("button",{onClick:N,className:"bg-white rounded-2xl p-6 shadow-sm border border-slate-200 hover:shadow-md hover:border-[#406E71] transition-all text-left group",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-[#406E71]/10 flex items-center justify-center group-hover:bg-[#406E71]/20 transition-colors",children:e.jsx(Ua,{className:"h-6 w-6 text-[#406E71]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-[#2a4c64]",children:"Leave a Google review"}),e.jsxs("p",{className:"text-sm text-slate-500",children:["Takes 30 seconds — helps others find ",($=(z=t.agent)==null?void 0:z.name)==null?void 0:$.split(" ")[0]]})]})]})}),e.jsx("button",{onClick:()=>l("video"),className:"bg-white rounded-2xl p-6 shadow-sm border border-slate-200 hover:shadow-md hover:border-[#406E71] transition-all text-left group",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-[#c9a24b]/10 flex items-center justify-center group-hover:bg-[#c9a24b]/20 transition-colors",children:e.jsx(Wr,{className:"h-6 w-6 text-[#c9a24b]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-[#2a4c64]",children:"Record a quick video"}),e.jsx("p",{className:"text-sm text-slate-500",children:"60 seconds, right from your phone"})]})]})}),e.jsx("button",{onClick:()=>l("write"),className:"bg-white rounded-2xl p-6 shadow-sm border border-slate-200 hover:shadow-md hover:border-[#406E71] transition-all text-left group",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-slate-100 flex items-center justify-center group-hover:bg-slate-200 transition-colors",children:e.jsx(Pg,{className:"h-6 w-6 text-slate-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-[#2a4c64]",children:"Write a note"}),e.jsx("p",{className:"text-sm text-slate-500",children:"A few kind words go a long way"})]})]})})]}),i!=="none"&&e.jsxs("div",{className:"bg-white rounded-2xl p-6 shadow-sm border border-slate-200 space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700",children:"Your name"}),e.jsx(xe,{value:o,onChange:H=>c(H.target.value),placeholder:"Jane Smith",className:"mt-1"})]}),i==="write"&&e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700",children:"Your review"}),e.jsx(Fs,{value:h,onChange:H=>m(H.target.value),rows:5,placeholder:"Share a few words about your experience...",className:"mt-1"})]}),i==="video"&&e.jsxs("div",{children:[e.jsxs("div",{className:"bg-[#2a4c64]/5 rounded-xl p-4 mb-4",children:[e.jsx("p",{className:"text-xs font-semibold text-[#2a4c64] uppercase tracking-wide mb-2",children:"Not sure what to say? Try these:"}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1",children:Gtr.map(H=>e.jsxs("li",{children:["• ",H]},H))})]}),e.jsx(kE,{maxDurationSeconds:60,onRecordingComplete:H=>S(H),onError:H=>b(H)})]}),v&&e.jsx("p",{className:"text-sm text-red-600",children:v}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(U,{variant:"ghost",onClick:()=>l("none"),disabled:p,children:"Back"}),i==="write"&&e.jsxs(U,{onClick:()=>S(),disabled:p||!o.trim()||!h.trim(),className:"bg-[#406E71] hover:bg-[#355e61] text-white flex-1",children:[p?e.jsx(Et,{className:"h-4 w-4 animate-spin mr-2"}):null,"Send review"]})]}),i==="video"&&p&&e.jsxs("p",{className:"text-sm text-slate-500 flex items-center gap-2",children:[e.jsx(Et,{className:"h-4 w-4 animate-spin"})," Uploading your video…"]})]})]})})}function Oce({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(Ua,{className:Mt(t,n<=s?"fill-[#c9a24b] text-[#c9a24b]":"text-slate-300")},n))})}function Ytr(){var d,u;const{slug:s}=Di(),[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(Et,{className:"h-8 w-8 animate-spin text-[#406E71]"})});if(!t)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f7f5f1] p-6",children:e.jsx("p",{className:"text-slate-600",children:"This reviews page isn't available."})});const l=t.reviews.filter(h=>h.source==="video"&&h.video_url),o=t.reviews.filter(h=>h.source==="google"),c=t.reviews.filter(h=>h.source==="video"&&!h.video_url);return e.jsxs("div",{className:"min-h-screen bg-[#f7f5f1]",children:[e.jsxs("header",{className:"bg-[#2a4c64] text-white py-16 px-6 text-center",children:[((d=t.agent)==null?void 0:d.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:i,className:"w-24 h-24 rounded-full object-cover mx-auto mb-5 border-4 border-[#c9a24b]/60 shadow-xl"}),e.jsx("h1",{className:"text-4xl font-serif",children:i}),((u=t.agent)==null?void 0:u.title)&&e.jsx("p",{className:"text-white/70 mt-1",children:t.agent.title}),e.jsxs("div",{className:"flex items-center justify-center gap-3 mt-5",children:[e.jsx(Oce,{rating:Math.round(t.stats.avg_rating),size:"h-6 w-6"}),e.jsx("span",{className:"text-2xl font-semibold",children:t.stats.avg_rating}),e.jsxs("span",{className:"text-white/60",children:["· ",t.stats.total_reviews," review",t.stats.total_reviews!==1?"s":""]})]}),t.settings.intro_text&&e.jsx("p",{className:"max-w-xl mx-auto mt-5 text-white/80 leading-relaxed",children:t.settings.intro_text})]}),e.jsxs("main",{className:"max-w-4xl mx-auto px-4 py-12 space-y-14",children:[l.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-2xl font-serif text-[#2a4c64] mb-6 flex items-center gap-2",children:[e.jsx(Wr,{className:"h-6 w-6 text-[#c9a24b]"})," Video testimonials"]}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-6",children:l.map(h=>e.jsxs("figure",{className:"bg-white rounded-2xl overflow-hidden shadow-sm border border-slate-200",children:[e.jsx("video",{src:h.video_url,controls:!0,playsInline:!0,preload:"metadata",className:"w-full aspect-video bg-black"}),e.jsxs("figcaption",{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-[#2a4c64]",children:h.reviewer_name}),h.rating&&e.jsx(Oce,{rating:h.rating})]}),h.review_text&&e.jsx("p",{className:"text-sm text-slate-600 mt-2",children:h.review_text})]})]},h.id))})]}),o.length>0&&e.jsxs("section",{children:[e.jsx("h2",{className:"text-2xl font-serif text-[#2a4c64] mb-6",children:"Google reviews"}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-6",children:o.map(h=>{var m,p;return e.jsxs("blockquote",{className:"bg-white rounded-2xl p-6 shadow-sm border border-slate-200 flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[h.rating&&e.jsx(Oce,{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(TC,{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(XX,{className:"h-3.5 w-3.5"})," Response from ",(p=(m=t.agent)==null?void 0:m.name)==null?void 0:p.split(" ")[0]]}),e.jsx("p",{className:"text-sm text-slate-600",children:h.reply_text})]})]},h.id)})})]}),c.length>0&&e.jsxs("section",{children:[e.jsx("h2",{className:"text-2xl font-serif text-[#2a4c64] mb-6",children:"Kind words"}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-6",children:c.map(h=>e.jsxs("blockquote",{className:"bg-white rounded-2xl p-6 shadow-sm border border-slate-200",children:[h.rating&&e.jsx(Oce,{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 l5t({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(Ua,{className:Mt(t,n<=s?"fill-[#c9a24b] text-[#c9a24b]":"text-slate-300")},n))})}function c5t(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")}function Ztr(){var Fe;const{user:s,isAdmin:t,rolesLoading:n}=vs(),[r,a]=j.useState([]),[i,l]=j.useState([]),[o,c]=j.useState(!0),[d,u]=j.useState({slug:"",intro_text:"",is_published:!1,show_google_reviews:!0,show_video_reviews:!0}),[h,m]=j.useState(!1),[p,f]=j.useState(!1),[x,y]=j.useState(""),[v,b]=j.useState("email"),[N,S]=j.useState(""),[A,T]=j.useState(!1),[L,M]=j.useState(null),[I,R]=j.useState(""),[z,$]=j.useState(!1),[H,V]=j.useState(!1),[K,Z]=j.useState(!1),[Q,le]=j.useState(null),ue=Q?Q.connected:null,[se,ne]=fc(),ie=j.useRef(!1),ce=j.useCallback(async()=>{const{data:Ne,error:$e}=await q.functions.invoke("google-business-oauth",{body:{action:"get_status"}});if($e||Ne!=null&&Ne.error){le({connected:!1,email:null,apiAccessPending:!1,hasRefreshToken:!1,connectedAt:null,locations:[]});return}le(Ne)},[]),je=j.useCallback(async()=>{if(!s)return;c(!0);const[{data:Ne},{data:$e},{data:Ve}]=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(a(Ne??[]),l($e??[]),ce(),Ve)u({id:Ve.id,slug:Ve.slug??"",intro_text:Ve.intro_text??"",is_published:Ve.is_published,show_google_reviews:Ve.show_google_reviews,show_video_reviews:Ve.show_video_reviews});else{const{data:qe}=await q.from("profiles").select("name").eq("id",s.id).single(),Ze=c5t((qe==null?void 0:qe.name)??"");u(Ue=>({...Ue,slug:Ue.slug||Ze}))}c(!1)},[s,ce]);j.useEffect(()=>{je()},[je]),j.useEffect(()=>{if(ie.current)return;const Ne=se.get("google"),$e=se.get("google_error");if(!Ne&&!$e)return;if(ie.current=!0,$e)re.error($e==="access_denied"?"Google connection was cancelled":$e==="invalid_state"?"That connection link expired — please try again":$e==="not_configured"?"Google Business credentials are not configured yet":`Google connection failed: ${$e}`);else{const qe=Number(se.get("locations")??0);re.success(se.get("google_pending")?"Google connected — review access is still pending Google approval":`Google Business Profile connected${qe?` (${qe} location${qe>1?"s":""})`:""}`)}const Ve=new URLSearchParams(se);["google","google_error","google_pending","locations"].forEach(qe=>Ve.delete(qe)),ne(Ve,{replace:!0}),ce()},[se,ne,ce]);const be=async()=>{Z(!0);const{data:Ne,error:$e}=await q.functions.invoke("google-business-oauth",{body:{action:"get_auth_url",returnPath:"/apps/reviews"}});if($e||Ne!=null&&Ne.error||!(Ne!=null&&Ne.authUrl))return Z(!1),re.error((Ne==null?void 0:Ne.error)||($e==null?void 0:$e.message)||"Could not start Google connection");window.location.href=Ne.authUrl},he=async()=>{const{error:Ne}=await q.functions.invoke("google-business-oauth",{body:{action:"disconnect"}});if(Ne)return re.error("Could not disconnect");re.success("Google Business Profile disconnected"),ce()},ge=j.useMemo(()=>{const Ne=r.filter(Ye=>Ye.status!=="hidden"),$e=Ne.filter(Ye=>Ye.rating),Ve=$e.length?$e.reduce((Ye,Ge)=>Ye+(Ge.rating??0),0)/$e.length:0,qe=i.filter(Ye=>["sent","reminded","clicked"].includes(Ye.status)).length,Ze=i.filter(Ye=>Ye.status==="completed").length,Ue=i.length?Math.round(Ze/i.length*100):0;return{avg:Math.round(Ve*10)/10,total:Ne.length,pending:qe,responseRate:Ue,newCount:r.filter(Ye=>Ye.status==="new").length}},[r,i]),ke=async(Ne,$e)=>{const{error:Ve}=await q.from("review_responses").update({status:$e}).eq("id",Ne);if(Ve)return re.error(Ve.message);a(qe=>qe.map(Ze=>Ze.id===Ne?{...Ze,status:$e}:Ze))},Te=async Ne=>{const{error:$e}=await q.from("review_responses").update({is_pinned:!Ne.is_pinned}).eq("id",Ne.id);if($e)return re.error($e.message);a(Ve=>Ve.map(qe=>qe.id===Ne.id?{...qe,is_pinned:!Ne.is_pinned}:qe))},Me=async()=>{if(!s)return;if(!d.slug)return re.error("Choose a slug for your page");m(!0);const Ne={user_id:s.id,slug:c5t(d.slug),intro_text:d.intro_text||null,is_published:d.is_published,show_google_reviews:d.show_google_reviews,show_video_reviews:d.show_video_reviews},{error:$e}=d.id?await q.from("agent_review_page_settings").update(Ne).eq("id",d.id):await q.from("agent_review_page_settings").insert(Ne);if(m(!1),$e)return re.error($e.message.includes("unique")?"That slug is taken — try another":$e.message);re.success(d.is_published?"Your reviews page is live":"Settings saved"),je()},Oe=async()=>{const $e=x.split(` `).map(Ue=>Ue.trim()).filter(Boolean).map(Ue=>{const[Ye,Ge,He]=Ue.split(",").map(tt=>tt.trim());return{name:Ye,email:Ge,phone:He}}).filter(Ue=>Ue.email||Ue.phone);if($e.length===0)return re.error("Add at least one recipient (Name, email, phone — one per line)");T(!0);const{data:Ve,error:qe}=await q.functions.invoke("review-request-send",{body:{recipients:$e,channel:v,message:N||void 0}});if(T(!1),qe||Ve!=null&&Ve.error)return re.error((Ve==null?void 0:Ve.error)||(qe==null?void 0:qe.message)||"Send failed");const Ze=(Ve.results??[]).filter(Ue=>Ue.ok).length;re.success(`${Ze} review request${Ze!==1?"s":""} sent`),f(!1),y(""),je()},Se=async()=>{if(!(!L||!I.trim())){if($(!0),L.source==="google"){const{data:Ne,error:$e}=await q.functions.invoke("google-reviews-sync",{body:{action:"reply",review_id:L.id,text:I.trim()}});if($e||Ne!=null&&Ne.error)return $(!1),re.error((Ne==null?void 0:Ne.error)||($e==null?void 0:$e.message)||"Reply failed")}else{const{error:Ne}=await q.from("review_responses").update({reply_text:I.trim(),replied_at:new Date().toISOString()}).eq("id",L.id);if(Ne)return $(!1),re.error(Ne.message)}$(!1),re.success("Reply posted"),M(null),R(""),je()}},Qe=async()=>{V(!0);const{data:Ne,error:$e}=await q.functions.invoke("google-reviews-sync",{body:{action:"sync_mine"}});if(V(!1),$e||Ne!=null&&Ne.error)return re.error((Ne==null?void 0:Ne.error)||($e==null?void 0:$e.message)||"Sync failed");if(Ne!=null&&Ne.needsReconnect)return re.error("Your Google connection expired — click Connect Google to reconnect");re.success(`Synced ${(Ne==null?void 0:Ne.synced)??0} reviews`),je()};if(n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsx(Et,{className:"h-8 w-8 animate-spin text-primary"})});if(!t)return e.jsx("div",{className:"min-h-screen flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center max-w-md",children:[e.jsx(cn,{className:"h-12 w-12 text-[#c9a24b] mx-auto mb-4"}),e.jsx("h1",{className:"text-2xl font-serif text-foreground mb-2",children:"Reviews is coming soon"}),e.jsx("p",{className:"text-muted-foreground",children:"We're putting the finishing touches on this app. Stay tuned."})]})});const Ae=d.slug?`${window.location.origin}/reviews/${d.slug}`:null;return e.jsx(qs,{title:"Reviews",children:e.jsxs("div",{className:"min-h-screen bg-background pb-20",children:[e.jsx("div",{className:"bg-[#2a4c64] text-white",children:e.jsxs("div",{className:"max-w-6xl mx-auto px-4 py-10",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-white/60 text-sm uppercase tracking-widest mb-1",children:"Reputation"}),e.jsx("h1",{className:"text-4xl font-serif",children:"Reviews"}),e.jsxs("div",{className:"flex items-center gap-3 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold tabular-nums",children:ge.avg||"—"}),e.jsxs("div",{children:[e.jsx(l5t,{rating:Math.round(ge.avg),size:"h-5 w-5"}),e.jsxs("p",{className:"text-white/60 text-sm mt-1",children:[ge.total," review",ge.total!==1?"s":""," collected"]})]})]})]}),e.jsxs("div",{className:"flex gap-3 items-center",children:[ue===!1?e.jsxs(U,{onClick:be,disabled:K,className:"bg-[#c9a24b] hover:bg-[#b8923f] text-[#2a4c64] font-semibold",children:[K?e.jsx(Et,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(fl,{className:"h-4 w-4 mr-2"}),"Connect Google"]}):e.jsxs(U,{onClick:Qe,variant:"outline",className:"border-white/30 text-white hover:bg-white/10",disabled:H,children:[H?e.jsx(Et,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(fl,{className:"h-4 w-4 mr-2"}),"Sync Google"]}),e.jsxs(U,{onClick:()=>f(!0),className:"bg-[#c9a24b] hover:bg-[#b8923f] text-[#2a4c64] font-semibold",children:[e.jsx($r,{className:"h-4 w-4 mr-2"})," Request a Review"]}),e.jsx(wN,{children:e.jsxs(Bg,{children:[e.jsx(Ug,{asChild:!0,children:e.jsx(xr,{to:"/social-connections","aria-label":"All social connections",className:"p-2.5 rounded-xl border border-white/20 text-white/70 hover:text-white hover:bg-white/10 transition-colors",children:e.jsx(R4,{className:"h-5 w-5"})})}),e.jsx(ng,{children:"All social connections"})]})})]})]}),Q&&e.jsx("div",{className:"mt-6 rounded-2xl border border-white/15 bg-white/5 backdrop-blur px-4 py-3 flex flex-wrap items-center gap-x-5 gap-y-2 text-sm",children:Q.connected?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-2 text-emerald-300",children:[e.jsx(zr,{className:"h-4 w-4"}),"Google connected",Q.email?` — ${Q.email}`:""]}),Q.apiAccessPending?e.jsxs("span",{className:"flex items-center gap-2 text-amber-300",children:[e.jsx(tc,{className:"h-4 w-4"})," Review access pending Google approval"]}):e.jsxs("span",{className:"flex items-center gap-2 text-white/70",children:[e.jsx(ni,{className:"h-4 w-4"}),Q.locations.length," location",Q.locations.length!==1?"s":"",(Fe=Q.locations[0])!=null&&Fe.last_synced_at?` · last synced ${new Date(Q.locations[0].last_synced_at).toLocaleString()}`:" · not synced yet"]}),!Q.hasRefreshToken&&e.jsxs("span",{className:"flex items-center gap-2 text-amber-300",children:[e.jsx(tc,{className:"h-4 w-4"})," Reconnect to enable automatic syncing"]}),e.jsxs("button",{onClick:he,className:"ml-auto flex items-center gap-1.5 text-white/60 hover:text-white transition-colors",children:[e.jsx(jq,{className:"h-4 w-4"})," Disconnect"]})]}):e.jsxs("span",{className:"flex items-center gap-2 text-white/70",children:[e.jsx(tc,{className:"h-4 w-4 text-[#c9a24b]"}),"Google Business Profile not connected — review requests and video reviews still work."]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mt-8",children:[{label:"Total reviews",value:ge.total,icon:Ua},{label:"Awaiting response",value:ge.newCount,icon:Ki},{label:"Pending requests",value:ge.pending,icon:Bn},{label:"Response rate",value:`${ge.responseRate}%`,icon:rc}].map(Ne=>e.jsxs("div",{className:"bg-white/10 backdrop-blur rounded-xl p-4 border border-white/10",children:[e.jsx(Ne.icon,{className:"h-5 w-5 text-[#c9a24b] mb-2"}),e.jsx("p",{className:"text-2xl font-bold",children:Ne.value}),e.jsx("p",{className:"text-white/60 text-xs mt-1",children:Ne.label})]},Ne.label))})]})}),e.jsx("div",{className:"max-w-6xl mx-auto px-4 mt-8",children:e.jsxs(oa,{defaultValue:"inbox",children:[e.jsxs(la,{children:[e.jsxs(Kt,{value:"inbox",children:["Inbox ",ge.newCount>0&&e.jsx(Be,{className:"ml-2 bg-[#c9a24b] text-[#2a4c64]",children:ge.newCount})]}),e.jsx(Kt,{value:"requests",children:"Requests"}),e.jsx(Kt,{value:"page",children:"Public Page"})]}),e.jsxs(Zt,{value:"inbox",className:"mt-6",children:[ue===!1&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-xl p-4 mb-6 text-sm text-amber-800 flex flex-wrap items-center gap-3",children:[e.jsx("span",{className:"flex-1 min-w-[240px]",children:"Connect your Google Business Profile to pull in Google reviews and reply from here. (Reading reviews requires Google's API approval — until then, requests and video reviews work fully.)"}),e.jsxs(U,{size:"sm",onClick:be,disabled:K,className:"bg-[#406E71] hover:bg-[#355e61] text-white",children:[K?e.jsx(Et,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(fl,{className:"h-4 w-4 mr-2"}),"Connect Google"]})]}),(Q==null?void 0:Q.connected)&&Q.apiAccessPending&&e.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-xl p-4 mb-6 text-sm text-amber-800",children:"Google is connected, but the Business Profile review APIs aren't approved for this app yet, so reviews can't be read or replied to. Requesting reviews and video testimonials work today."}),o?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Et,{className:"h-6 w-6 animate-spin text-primary"})}):r.length===0?e.jsxs("div",{className:"text-center py-16 text-muted-foreground",children:[e.jsx(Ua,{className:"h-10 w-10 mx-auto mb-3 text-[#c9a24b]"}),e.jsx("p",{children:"No reviews yet. Send your first request to get the stars rolling in."})]}):e.jsx("div",{className:"grid md:grid-cols-2 gap-5",children:r.map(Ne=>e.jsxs("div",{className:Mt("bg-card rounded-2xl border p-5 shadow-sm",Ne.status==="hidden"&&"opacity-50"),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-[#406E71]/10 flex items-center justify-center",children:Ne.source==="google"?e.jsx(TC,{className:"h-5 w-5 text-[#406E71]"}):e.jsx(Wr,{className:"h-5 w-5 text-[#c9a24b]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:Ne.reviewer_name||"Anonymous"}),Ne.rating&&e.jsx(l5t,{rating:Ne.rating})]})]}),e.jsx(Be,{variant:"outline",className:"capitalize",children:Ne.source})]}),Ne.video_url&&e.jsx("video",{src:Ne.video_url,controls:!0,playsInline:!0,preload:"metadata",className:"w-full rounded-xl mt-4 aspect-video bg-black"}),Ne.review_text&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-3 leading-relaxed",children:['"',Ne.review_text,'"']}),Ne.reply_text&&e.jsxs("p",{className:"text-sm mt-3 pl-3 border-l-2 border-[#c9a24b]/60 text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Your reply:"})," ",Ne.reply_text]}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[Ne.status!=="approved"&&Ne.status!=="featured"&&e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>ke(Ne.id,"approved"),children:[e.jsx(xa,{className:"h-3.5 w-3.5 mr-1"})," Approve"]}),Ne.status==="approved"&&e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>ke(Ne.id,"featured"),children:[e.jsx(cn,{className:"h-3.5 w-3.5 mr-1"})," Feature"]}),e.jsxs(U,{size:"sm",variant:"ghost",onClick:()=>Te(Ne),children:[e.jsx(MA,{className:Mt("h-3.5 w-3.5 mr-1",Ne.is_pinned&&"fill-current")})," ",Ne.is_pinned?"Unpin":"Pin"]}),!Ne.reply_text&&e.jsxs(U,{size:"sm",variant:"ghost",onClick:()=>{M(Ne),R("")},children:[e.jsx(uq,{className:"h-3.5 w-3.5 mr-1"})," Reply"]}),Ne.status!=="hidden"?e.jsxs(U,{size:"sm",variant:"ghost",className:"text-muted-foreground",onClick:()=>ke(Ne.id,"hidden"),children:[e.jsx(Vg,{className:"h-3.5 w-3.5 mr-1"})," Hide"]}):e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>ke(Ne.id,"new"),children:"Restore"})]})]},Ne.id))})]}),e.jsxs(Zt,{value:"requests",className:"mt-6",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Every request sends a branded email (and optional text) with a personal review link. A gentle reminder goes out automatically after 3 days."}),e.jsxs(U,{onClick:()=>f(!0),className:"bg-[#406E71] hover:bg-[#355e61] text-white shrink-0 ml-4",children:[e.jsx($r,{className:"h-4 w-4 mr-2"})," New request"]})]}),e.jsx("div",{className:"bg-card rounded-2xl border overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/50 text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left p-3 font-medium",children:"Recipient"}),e.jsx("th",{className:"text-left p-3 font-medium",children:"Channel"}),e.jsx("th",{className:"text-left p-3 font-medium",children:"Status"}),e.jsx("th",{className:"text-left p-3 font-medium",children:"Sent"})]})}),e.jsxs("tbody",{children:[i.map(Ne=>e.jsxs("tr",{className:"border-t",children:[e.jsxs("td",{className:"p-3",children:[e.jsx("p",{className:"font-medium text-foreground",children:Ne.recipient_name||"—"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Ne.recipient_email||Ne.recipient_phone})]}),e.jsx("td",{className:"p-3 capitalize",children:Ne.channel}),e.jsx("td",{className:"p-3",children:e.jsx(Be,{variant:Ne.status==="completed"?"default":"outline",className:Mt("capitalize",Ne.status==="completed"&&"bg-[#406E71]"),children:Ne.status})}),e.jsx("td",{className:"p-3 text-muted-foreground",children:Ne.sent_at?new Date(Ne.sent_at).toLocaleDateString():"—"})]},Ne.id)),i.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"p-8 text-center text-muted-foreground",children:"No requests sent yet."})})]})]})})]}),e.jsx(Zt,{value:"page",className:"mt-6",children:e.jsx("div",{className:"max-w-xl space-y-5",children:e.jsxs("div",{className:"bg-card rounded-2xl border p-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Page URL slug"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"/reviews/"}),e.jsx(xe,{value:d.slug,onChange:Ne=>u($e=>({...$e,slug:Ne.target.value})),placeholder:"jane-smith"})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Intro text"}),e.jsx(Fs,{value:d.intro_text,onChange:Ne=>u($e=>({...$e,intro_text:Ne.target.value})),rows:3,placeholder:"A short note shown at the top of your page...",className:"mt-1"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{children:"Show Google reviews"}),e.jsx(wn,{checked:d.show_google_reviews,onCheckedChange:Ne=>u($e=>({...$e,show_google_reviews:Ne}))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{children:"Show video testimonials"}),e.jsx(wn,{checked:d.show_video_reviews,onCheckedChange:Ne=>u($e=>({...$e,show_video_reviews:Ne}))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Publish page"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only approved & featured reviews appear publicly."})]}),e.jsx(wn,{checked:d.is_published,onCheckedChange:Ne=>u($e=>({...$e,is_published:Ne}))})]}),e.jsxs("div",{className:"flex gap-3 pt-2",children:[e.jsxs(U,{onClick:Me,disabled:h,className:"bg-[#406E71] hover:bg-[#355e61] text-white",children:[h&&e.jsx(Et,{className:"h-4 w-4 animate-spin mr-2"})," Save"]}),d.is_published&&Ae&&e.jsxs(e.Fragment,{children:[e.jsxs(U,{variant:"outline",onClick:()=>{navigator.clipboard.writeText(Ae),re.success("Link copied")},children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"})," Copy link"]}),e.jsx(U,{variant:"ghost",asChild:!0,children:e.jsxs("a",{href:Ae,target:"_blank",rel:"noreferrer",children:[e.jsx(Sr,{className:"h-4 w-4 mr-2"})," View page"]})})]})]})]})})})]})}),e.jsx(zs,{open:p,onOpenChange:f,children:e.jsxs(Ds,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Request reviews"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Recipients — one per line: Name, email, phone"}),e.jsx(Fs,{value:x,onChange:Ne=>y(Ne.target.value),rows:6,placeholder:`Jane Smith, jane@email.com, 555-123-4567 John Doe, john@email.com`,className:"mt-1 font-mono text-sm"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Send via"}),e.jsxs(Ns,{value:v,onValueChange:Ne=>b(Ne),children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"email",children:"Email"}),e.jsx(et,{value:"sms",children:"Text message"}),e.jsx(et,{value:"both",children:"Email + text"})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Personal note (optional)"}),e.jsx(Fs,{value:N,onChange:Ne=>S(Ne.target.value),rows:3,placeholder:"It was a pleasure working with you...",className:"mt-1"})]}),e.jsxs(U,{onClick:Oe,disabled:A,className:"w-full bg-[#406E71] hover:bg-[#355e61] text-white",children:[A?e.jsx(Et,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx($r,{className:"h-4 w-4 mr-2"}),"Send requests"]})]})]})}),e.jsx(zs,{open:!!L,onOpenChange:Ne=>!Ne&&M(null),children:e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsxs($s,{children:["Reply to ",L==null?void 0:L.reviewer_name]})}),(L==null?void 0:L.review_text)&&e.jsxs("p",{className:"text-sm text-muted-foreground italic",children:['"',L.review_text,'"']}),e.jsx(Fs,{value:I,onChange:Ne=>R(Ne.target.value),rows:4,placeholder:"Thank you so much, Jane..."}),e.jsxs(U,{onClick:Se,disabled:z||!I.trim(),className:"bg-[#406E71] hover:bg-[#355e61] text-white",children:[z&&e.jsx(Et,{className:"h-4 w-4 animate-spin mr-2"}),(L==null?void 0:L.source)==="google"?"Post reply to Google":"Save reply"]})]})})]})})}function Xtr(){const{slug:s}=Di();return s?e.jsx(LOt,{slug:s}):e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Portal Not Found"}),e.jsx("p",{className:"text-slate-500",children:"No portal slug was provided."})]})})}function Nss({photoUrl:s,videoUrl:t,onPhotoChange:n,onVideoChange:r,contactId:a}){const{user:i}=vs(),l=f3(),o=j.useRef(null),c=j.useRef(null),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[p,f]=j.useState(0),x=async v=>{if(i){u(!0);try{const b=v.name.split(".").pop()||"jpg",N=`${i.id}/card-${Date.now()}.${b}`,{error:S}=await q.storage.from("listing-photos").upload(N,v);if(S)throw S;const{data:{publicUrl:A}}=q.storage.from("listing-photos").getPublicUrl(N);n(A),re.success("Photo uploaded")}catch(b){re.error(b.message||"Failed to upload photo")}finally{u(!1)}}},y=async v=>{if(i){if(v.size>500*1024*1024){re.error("Video must be under 500MB");return}m(!0),f(0);try{const{videoId:b,libraryId:N}=await cL(`Card Video - ${Date.now()}`),{uploadUrl:S,apiKey:A}=await dL(b);await new Promise((M,I)=>{const R=new XMLHttpRequest;R.upload.addEventListener("progress",z=>{z.lengthComputable&&f(Math.round(z.loaded/z.total*100))}),R.addEventListener("load",()=>{R.status>=200&&R.status<300?M():I(new Error("Upload failed"))}),R.addEventListener("error",()=>I(new Error("Upload failed"))),R.open("PUT",S),R.setRequestHeader("AccessKey",A),R.send(v)});const T=`https://iframe.mediadelivery.net/embed/${N}/${b}`;r(T);const L=parseFloat((v.size/(1024*1024)).toFixed(2));await l.mutateAsync({bunny_video_id:b,playback_url:`https://iframe.mediadelivery.net/play/${N}/${b}`,file_size_mb:L,title:"Card Video",status:"processing",touch_type:"video",contact_id:a||void 0}),re.success("Video uploaded & added to your library")}catch(b){re.error(b.message||"Failed to upload video")}finally{m(!1),f(0)}}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx(te,{children:"Media (optional)"}),e.jsxs(oa,{defaultValue:"photo",className:"w-full",children:[e.jsxs(la,{className:"grid w-full grid-cols-2",children:[e.jsxs(Kt,{value:"photo",className:"gap-1.5 text-xs",children:[e.jsx(pc,{className:"h-3.5 w-3.5"}),"Photo"]}),e.jsxs(Kt,{value:"video",className:"gap-1.5 text-xs",children:[e.jsx(Wr,{className:"h-3.5 w-3.5"}),"Video"]})]}),e.jsxs(Zt,{value:"photo",className:"mt-3",children:[s?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:s,alt:"Card photo",className:"w-full h-40 object-cover"}),e.jsx(U,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>n(null),children:e.jsx(er,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var v;return(v=o.current)==null?void 0:v.click()},disabled:d,className:"w-full h-32 border-2 border-dashed border-border rounded-lg flex flex-col items-center justify-center gap-2 text-muted-foreground hover:border-primary/40 hover:bg-accent/50 transition-colors",children:d?e.jsx(Et,{className:"h-6 w-6 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(_x,{className:"h-6 w-6"}),e.jsx("span",{className:"text-xs",children:"Upload a photo"})]})}),e.jsx("input",{ref:o,type:"file",accept:"image/*",className:"hidden",onChange:v=>{var N;const b=(N=v.target.files)==null?void 0:N[0];b&&x(b),v.target.value=""}})]}),e.jsxs(Zt,{value:"video",className:"mt-3",children:[t?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("iframe",{src:`${t}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0}),e.jsx(U,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>r(null),children:e.jsx(er,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var v;return(v=c.current)==null?void 0:v.click()},disabled:h,className:"w-full h-32 border-2 border-dashed border-border rounded-lg flex flex-col items-center justify-center gap-2 text-muted-foreground hover:border-primary/40 hover:bg-accent/50 transition-colors",children:h?e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(Et,{className:"h-6 w-6 animate-spin"}),e.jsxs("span",{className:"text-xs",children:["Uploading... ",p,"%"]}),e.jsx("div",{className:"w-32 h-1.5 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary rounded-full transition-all",style:{width:`${p}%`}})})]}):e.jsxs(e.Fragment,{children:[e.jsx(qa,{className:"h-6 w-6"}),e.jsx("span",{className:"text-xs",children:"Upload a video (max 500MB)"})]})}),!t&&!h&&e.jsx("div",{className:"mt-2",children:e.jsx(frt,{contactId:a,onVideoReady:v=>r(v)})}),e.jsx("input",{ref:c,type:"file",accept:"video/*",className:"hidden",onChange:v=>{var N;const b=(N=v.target.files)==null?void 0:N[0];b&&y(b),v.target.value=""}}),e.jsx("p",{className:"text-[10px] text-muted-foreground/60 mt-1.5 text-center",children:"Videos are also saved to your Video Library"})]})]})]})}const Qtr=[{type:"home_anniversary",label:"Home Anniversary",emoji:"🏡",description:"Celebrate their homeownership milestone",gradient:"from-blue-500/20 to-slate-500/20 border-blue-200 dark:border-blue-800"},{type:"wedding_anniversary",label:"Wedding Anniversary",emoji:"💍",description:"Celebrate their special day together",gradient:"from-rose-500/20 to-fuchsia-500/20 border-rose-200 dark:border-rose-800"},{type:"birthday",label:"Birthday",emoji:"🎂",description:"Wish them a happy birthday",gradient:"from-pink-500/20 to-purple-500/20 border-pink-200 dark:border-pink-800"},{type:"just_sold",label:"Just Sold",emoji:"🎉",description:"Announce a successful closing",gradient:"from-emerald-500/20 to-teal-500/20 border-emerald-200 dark:border-emerald-800"},{type:"just_listed",label:"Just Listed",emoji:"🏠",description:"Share a new listing announcement",gradient:"from-amber-500/20 to-orange-500/20 border-amber-200 dark:border-amber-800"},{type:"thank_you",label:"Thank You",emoji:"💐",description:"Show your appreciation",gradient:"from-rose-500/20 to-pink-500/20 border-rose-200 dark:border-rose-800"},{type:"congratulations",label:"Congratulations",emoji:"🏆",description:"Celebrate their achievements",gradient:"from-yellow-500/20 to-amber-500/20 border-yellow-200 dark:border-yellow-800"},{type:"holiday",label:"Holiday",emoji:"🎄",description:"Send seasonal greetings",gradient:"from-red-500/20 to-green-500/20 border-red-200 dark:border-red-800"},{type:"thinking_of_you",label:"Thinking of You",emoji:"💭",description:"Stay top of mind with a personal touch",gradient:"from-violet-500/20 to-indigo-500/20 border-violet-200 dark:border-violet-800"}];function Jtr({onSelect:s}){return e.jsx("div",{className:"grid grid-cols-2 gap-2.5",children:Qtr.map((t,n)=>e.jsxs(kr.button,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:n*.04,duration:.25},onClick:()=>s(t.type),className:`group relative flex flex-col items-start gap-1 p-3.5 rounded-xl border bg-gradient-to-br ${t.gradient} hover:shadow-md hover:scale-[1.02] active:scale-[0.98] transition-all text-left`,children:[e.jsx("span",{className:"text-2xl",children:t.emoji}),e.jsx("span",{className:"text-sm font-semibold text-foreground",children:t.label}),e.jsx("span",{className:"text-[11px] text-muted-foreground leading-tight",children:t.description})]},t.type))})}const kW={home_anniversary:{title:["Happy Home","Anniversary"],icon:"🏡",emojis:["🏡","✨","🎉","❤️","🎊","🏠"],defaultMessage:"Wishing you many more wonderful years of memories in your beautiful home. Thank you for letting me be part of your journey."},wedding_anniversary:{title:["Happy","Anniversary"],icon:"💍",emojis:["💍","💐","❤️","🥂","💕","✨"],defaultMessage:"Wishing you both a wonderful anniversary filled with love, laughter, and cherished memories. Here's to many more years together!"},just_listed:{title:["Just","Listed!"],icon:"🏠",emojis:["🏠","📋","🔑","⭐","🎯","✨"],defaultMessage:"Exciting news — this beautiful property just hit the market! Contact me for a private showing."},just_sold:{title:["Just","Sold!"],icon:"🎉",emojis:["🎉","🏡","🔑","🥂","🎊","💰"],defaultMessage:"Another successful closing! Congratulations to the new homeowners. It was a pleasure making this happen."},congratulations:{title:["Congratulations!",""],icon:"🏆",emojis:["🎉","🥳","🏆","⭐","🎊","✨"],defaultMessage:"What an incredible milestone! I'm so happy for you. Wishing you all the best in this exciting new chapter."},birthday:{title:["Happy","Birthday!"],icon:"🎂",emojis:["🎂","🎈","🎁","🥳","🎉","🧁"],defaultMessage:"Wishing you the happiest of birthdays! May this year bring you joy, laughter, and everything you've been dreaming of."},holiday:{title:["Happy","Holidays!"],icon:"🎄",emojis:["🎄","❄️","🎁","⭐","🕯️","🎅"],defaultMessage:"Wishing you and your family a season filled with warmth, joy, and cherished moments. Happy Holidays!"},thank_you:{title:["Thank","You!"],icon:"💐",emojis:["💐","🙏","❤️","⭐","✨","🤝"],defaultMessage:"Thank you so much for your trust and confidence. It truly means the world to me. I'm always here for you!"},thinking_of_you:{title:["Thinking","Of You"],icon:"💭",emojis:["💭","❤️","🌸","☀️","🦋","💫"],defaultMessage:"Just wanted to reach out and let you know I'm thinking of you. I hope you're doing well — don't hesitate to reach out anytime!"}};function d5t({initialOpen:s,initialCardType:t,initialContactId:n,initialRecipientName:r,initialAddress:a,initialDate:i,onOpenChange:l}){const{user:o}=vs(),c=Qt(),[d,u]=j.useState(!1),[h,m]=j.useState("type"),[p,f]=j.useState(""),[x,y]=j.useState(null),[v,b]=j.useState(!1),[N,S]=j.useState("home_anniversary"),[A,T]=j.useState(""),[L,M]=j.useState(""),[I,R]=j.useState(""),[z,$]=j.useState(""),[H,V]=j.useState("elegant"),[K,Z]=j.useState(null),[Q,le]=j.useState(null),ue=j.useState(!1);!ue[0]&&s&&t&&(ue[1](!0),u(!0),S(t),n&&y(n),r&&T(r),a&&M(a),i&&R(i),m(r?"details":"contact"));const{data:se}=ct({queryKey:["contacts-for-card",o==null?void 0:o.id,p],queryFn:async()=>{let Oe=q.from("innercircle_contacts").select("id, first_name, last_name, address, city, state, home_anniversary, wedding_anniversary, email, phone").eq("owner_user_id",o.id).order("first_name").limit(20);p&&(Oe=Oe.or(`first_name.ilike.%${p}%,last_name.ilike.%${p}%`));const{data:Se,error:Qe}=await Oe;if(Qe)throw Qe;return Se},enabled:!!(o!=null&&o.id)&&d}),{data:ne}=ct({queryKey:["agent-profile-card",o==null?void 0:o.id],queryFn:async()=>{const{data:Oe,error:Se}=await q.from("profiles").select("name, email, phone, avatar_url, brokerage:brokerages(name)").eq("id",o.id).single();if(Se)throw Se;return Oe},enabled:!!(o!=null&&o.id)}),ie=Oe=>{y(Oe.id),T(`${Oe.first_name}${Oe.last_name?" "+Oe.last_name:""}`),M([Oe.address,Oe.city,Oe.state].filter(Boolean).join(", "));const Se=N==="wedding_anniversary"?Oe.wedding_anniversary:N==="home_anniversary"?Oe.home_anniversary:"";R(Se||""),m("details")},ce=Oe=>{S(Oe),m("contact")},je=async()=>{var Oe;if(!(!o||!ne)){b(!0);try{const Se={owner_user_id:o.id,contact_id:x,card_type:N,template:H,recipient_name:A,property_address:L||null,home_anniversary_date:I||null,custom_message:z||null,property_photo_url:K||null,video_url:Q||null,agent_name:ne.name||"Agent",agent_photo_url:ne.avatar_url,agent_phone:ne.phone,agent_email:ne.email,agent_brokerage:((Oe=ne.brokerage)==null?void 0:Oe.name)||null},{error:Qe}=await q.from("sendable_cards").insert(Se);if(Qe)throw Qe;re.success("Card created! Copy the link to share it."),c.invalidateQueries({queryKey:["sendable-cards"]}),be()}catch(Se){re.error(Se.message||"Failed to create card")}finally{b(!1)}}},be=()=>{u(!1),m("type"),S("home_anniversary"),f(""),y(null),T(""),M(""),R(""),$(""),V("elegant"),Z(null),le(null)},he={home_anniversary:"Home Anniversary",wedding_anniversary:"Wedding Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"},ge=kW[N],ke=N==="home_anniversary"||N==="wedding_anniversary",Te=N==="wedding_anniversary"?"Wedding Anniversary Date":"Home Anniversary Date",Me=["home_anniversary","just_listed","just_sold"].includes(N);return e.jsxs(zs,{open:d,onOpenChange:Oe=>{Oe?u(!0):(be(),l==null||l(!1))},children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{className:"gap-2",children:[e.jsx(an,{className:"h-4 w-4"}),"Create Card"]})}),e.jsxs(Ds,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:h==="type"?"What type of card?":h==="contact"?`${he[N]} — Choose a Contact`:`${he[N]} — Customize`})}),h==="type"&&e.jsx(Jtr,{onSelect:ce}),h==="contact"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(U,{variant:"ghost",size:"sm",className:"gap-1.5 -ml-2 text-muted-foreground",onClick:()=>m("type"),children:[e.jsx(Aa,{className:"h-3.5 w-3.5"})," Back to card types"]}),e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search contacts...",value:p,onChange:Oe=>f(Oe.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"space-y-1 max-h-64 overflow-y-auto",children:[se==null?void 0:se.map(Oe=>e.jsxs("button",{onClick:()=>ie(Oe),className:"w-full flex items-center gap-3 p-3 rounded-lg hover:bg-accent text-left transition-colors",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(So,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[Oe.first_name," ",Oe.last_name]}),Oe.address&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate flex items-center gap-1",children:[e.jsx(ra,{className:"h-3 w-3"}),Oe.address]})]}),(N==="home_anniversary"&&Oe.home_anniversary||N==="wedding_anniversary"&&Oe.wedding_anniversary)&&e.jsx("span",{className:"text-[10px] text-emerald-600 bg-emerald-500/10 px-2 py-0.5 rounded-full shrink-0",children:"Date set"})]},Oe.id)),(se==null?void 0:se.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No contacts found"})]}),e.jsx("div",{className:"border-t pt-3",children:e.jsx(U,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{m("details")},children:"Skip — enter details manually"})})]}),h==="details"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(U,{variant:"ghost",size:"sm",className:"gap-1.5 -ml-2 text-muted-foreground",onClick:()=>m("contact"),children:[e.jsx(Aa,{className:"h-3.5 w-3.5"})," Back"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Recipient Name"}),e.jsx(xe,{value:A,onChange:Oe=>T(Oe.target.value),placeholder:"John & Jane Smith"})]}),Me&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Property Address"}),e.jsx(xe,{value:L,onChange:Oe=>M(Oe.target.value),placeholder:"123 Main St, Austin, TX"})]}),ke&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:Te}),e.jsx(xe,{type:"date",value:I,onChange:Oe=>R(Oe.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Personal Message (optional)"}),e.jsx(Fs,{value:z,onChange:Oe=>$(Oe.target.value),placeholder:ge.defaultMessage,rows:3})]}),e.jsx(Nss,{photoUrl:K,videoUrl:Q,onPhotoChange:Z,onVideoChange:le,contactId:x}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Template Style"}),e.jsx("div",{className:"grid grid-cols-5 gap-2",children:[{key:"elegant",label:"Elegant",gradient:"bg-gradient-to-br from-slate-100 to-blue-100 dark:from-slate-800 dark:to-slate-700"},{key:"bold",label:"Bold",gradient:"bg-gradient-to-br from-violet-500 to-fuchsia-500"},{key:"warm",label:"Warm",gradient:"bg-gradient-to-br from-amber-200 to-orange-300"},{key:"glass",label:"Glass",gradient:"bg-gradient-to-br from-slate-900 via-blue-900/50 to-slate-900 border border-white/10"},{key:"cinematic",label:"Cinema",gradient:"bg-gradient-to-br from-slate-950 via-blue-950 to-slate-950"}].map(({key:Oe,label:Se,gradient:Qe})=>e.jsxs("button",{onClick:()=>V(Oe),className:`p-2 rounded-lg border-2 transition-all text-center ${H===Oe?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-10 rounded-md mb-1.5 ${Qe}`}),e.jsx("span",{className:"text-[10px] font-medium",children:Se})]},Oe))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(U,{variant:"outline",onClick:()=>m("contact"),className:"flex-1",children:"Back"}),e.jsx(U,{onClick:je,disabled:!A||v,className:"flex-1 gap-2",children:v?"Creating...":"Create Card"})]})]})]})]})}const esr={home_anniversary:"Home Anniversary",wedding_anniversary:"Wedding Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"};function tsr({card:s}){const{user:t}=vs(),{isGmailConnected:n,hasVerifiedSes:r,canSendEmail:a,sendMethod:i}=Ax(),l=Qt(),[o,c]=j.useState(!1);j.useState(!1);const[d,u]=j.useState("");j.useEffect(()=>{o&&s.contact_id&&!d&&q.from("innercircle_contacts").select("email").eq("id",s.contact_id).maybeSingle().then(({data:N})=>{N!=null&&N.email&&u(N.email)})},[o,s.contact_id]);const h={home_anniversary:`🏡 Happy Home Anniversary, ${s.recipient_name}!`,wedding_anniversary:`💍 Happy Anniversary, ${s.recipient_name}!`,just_listed:`🏠 Just Listed — Check This Out, ${s.recipient_name}!`,just_sold:`🎉 Just Sold! Congrats, ${s.recipient_name}!`,congratulations:`🏆 Congratulations, ${s.recipient_name}!`,birthday:`🎂 Happy Birthday, ${s.recipient_name}!`,holiday:`🎄 Happy Holidays, ${s.recipient_name}!`,thank_you:`💐 Thank You, ${s.recipient_name}!`,thinking_of_you:`💭 Thinking of You, ${s.recipient_name}!`},[m,p]=j.useState(h[s.card_type]||`A Special Card for ${s.recipient_name}!`),[f,x]=j.useState(""),y=`https://cardstudio.relevelup.com/c/${s.share_token}`,v=yt({mutationFn:async()=>{if(!d)throw new Error("Recipient email is required");const N=`
${f?`

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


`:""}

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

${s.property_address?`

${s.property_address}

`:""}
`,S=async()=>{const{data:M,error:I}=await q.functions.invoke("send-connect-invite",{body:{contactEmail:d,subject:m,htmlBody:N}});if(I)throw I;if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Failed to send");return"system"};if(!a)return await S();const{data:A,error:T}=await q.functions.invoke("gmail-send",{body:{to:d,subject:m,body:N,contactId:s.contact_id||void 0}});let L=A&&A.error?A:null;if(T){L={error:"send_failed",message:T.message};const M=T.context;if(M&&typeof M.json=="function")try{L=await M.clone().json()}catch{}}if(L){if(L.error==="insufficient_scope"||L.error==="no_integration")return await S(),re.warning("Sent using system email — reconnect Gmail in Integrations to send from your own inbox.",{duration:8e3}),"system";throw new Error(L.message||L.error||"Failed to send")}if(!(A!=null&&A.success))throw new Error("Failed to send");return"gmail"},onSuccess:async N=>{await q.from("sendable_cards").update({sent_at:new Date().toISOString(),sent_via:N==="gmail"?"gmail":"system"}).eq("id",s.id),l.invalidateQueries({queryKey:["sendable-cards"]}),re.success(`Card sent to ${d}!`),c(!1)},onError:N=>{re.error(N.message||"Failed to send email")}}),b=i==="mass_email"?"Mass Email":i==="gmail"?"Gmail":"Email";return e.jsxs(zs,{open:o,onOpenChange:c,children:[e.jsx(al,{asChild:!0,children:e.jsx(U,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx($r,{className:"h-3 w-3"})})}),e.jsxs(Ds,{className:"sm:max-w-md",children:[e.jsx(Vs,{children:e.jsxs($s,{children:["Send Card via ",b]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"gmail-to",children:"To"}),e.jsx(o7t,{value:d,onChange:u,userId:t==null?void 0:t.id,placeholder:"Search contacts or type an email..."}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Pick from your Agent OS contacts, or type any email address."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Subject"}),e.jsx(xe,{value:m,onChange:N=>p(N.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Personal Note (optional)"}),e.jsx(Fs,{value:f,onChange:N=>x(N.target.value),placeholder:"Add a warm personal note before the card link...",rows:3})]}),e.jsxs("div",{className:"rounded-lg bg-muted/50 p-3 text-xs text-muted-foreground",children:[i==="mass_email"?e.jsx(e.Fragment,{children:"Sending via your verified Mass Email sender (Gmail isn't connected)."}):e.jsx(e.Fragment,{children:"The email will include a beautiful button linking to your card at:"}),e.jsx("br",{}),e.jsx("span",{className:"font-mono text-foreground",children:y})]}),e.jsx(U,{onClick:()=>v.mutate(),disabled:!d||v.isPending,className:"w-full gap-2",children:v.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx($r,{className:"h-4 w-4"})," Send Card"]})})]})]})]})}function ssr({card:s}){const t=Qt(),[n,r]=j.useState(!1),[a,i]=j.useState(!1),[l,o]=j.useState(s.recipient_name),[c,d]=j.useState(s.property_address||""),[u,h]=j.useState(s.home_anniversary_date||""),[m,p]=j.useState(s.custom_message||""),[f,x]=j.useState(s.template),[y,v]=j.useState(s.property_photo_url),[b,N]=j.useState(s.video_url||null),S=T=>{T&&(o(s.recipient_name),d(s.property_address||""),h(s.home_anniversary_date||""),p(s.custom_message||""),x(s.template),v(s.property_photo_url),N(s.video_url||null)),r(T)},A=async()=>{if(!l.trim()){re.error("Recipient name is required");return}i(!0);try{const{error:T}=await q.from("sendable_cards").update({recipient_name:l.trim(),property_address:c.trim()||null,home_anniversary_date:u||null,custom_message:m.trim()||null,template:f,property_photo_url:y||null,video_url:b||null}).eq("id",s.id);if(T)throw T;t.invalidateQueries({queryKey:["sendable-cards"]}),re.success("Card updated"),r(!1)}catch(T){re.error(T.message||"Failed to update card")}finally{i(!1)}};return e.jsxs(zs,{open:n,onOpenChange:S,children:[e.jsx(al,{asChild:!0,children:e.jsx(U,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(ri,{className:"h-3 w-3"})})}),e.jsxs(Ds,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Edit Card"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Recipient Name"}),e.jsx(xe,{value:l,onChange:T=>o(T.target.value),placeholder:"John & Jane Smith"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Property Address"}),e.jsx(xe,{value:c,onChange:T=>d(T.target.value),placeholder:"123 Main St, Austin, TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Home Anniversary Date"}),e.jsx(xe,{type:"date",value:u,onChange:T=>h(T.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Personal Message (optional)"}),e.jsx(Fs,{value:m,onChange:T=>p(T.target.value),placeholder:"Wishing you many more happy years in your beautiful home!",rows:3})]}),e.jsx(Nss,{photoUrl:y,videoUrl:b,onPhotoChange:v,onVideoChange:N,contactId:s.contact_id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Template Style"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:["elegant","bold","warm"].map(T=>e.jsxs("button",{onClick:()=>x(T),className:`p-3 rounded-lg border-2 transition-all text-center ${f===T?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-12 rounded-md mb-2 ${T==="elegant"?"bg-gradient-to-br from-slate-100 to-slate-200 dark:from-slate-800 dark:to-slate-700":T==="bold"?"bg-gradient-to-br from-violet-500 to-fuchsia-500":"bg-gradient-to-br from-amber-200 to-orange-300"}`}),e.jsx("span",{className:"text-xs font-medium capitalize",children:T})]},T))})]}),e.jsx(U,{onClick:A,disabled:!l.trim()||a,className:"w-full gap-2",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 animate-spin"})," Saving..."]}):"Save Changes"})]})]})]})}function nsr(){const{user:s}=vs(),t=Qt(),[n,r]=j.useState(""),[a,i]=fc(),l=a.get("cardType"),o=a.get("contactId"),c=a.get("name"),d=a.get("address"),u=a.get("date"),h=!!l,{data:m,isLoading:p}=ct({queryKey:["sendable-cards",s==null?void 0:s.id],queryFn:async()=>{const{data:N,error:S}=await q.from("sendable_cards").select("*").eq("owner_user_id",s.id).order("created_at",{ascending:!1});if(S)throw S;return N},enabled:!!(s!=null&&s.id)}),f=yt({mutationFn:async N=>{const{error:S}=await q.from("sendable_cards").delete().eq("id",N);if(S)throw S},onSuccess:()=>{t.invalidateQueries({queryKey:["sendable-cards"]}),re.success("Card deleted")}}),x=N=>{const S=`https://cardstudio.relevelup.com/c/${N}`;navigator.clipboard.writeText(S),re.success("Share link copied!")},y=m==null?void 0:m.filter(N=>{var S;return!n||N.recipient_name.toLowerCase().includes(n.toLowerCase())||((S=N.property_address)==null?void 0:S.toLowerCase().includes(n.toLowerCase()))}),v={elegant:"Elegant",bold:"Bold",warm:"Warm"},b={home_anniversary:"Home Anniversary",wedding_anniversary:"Wedding Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"};return e.jsx(qs,{title:"Card Studio",children:e.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Card Studio"})}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Create & send beautiful branded cards to your clients"})]}),e.jsx(d5t,{initialOpen:h,initialCardType:l,initialContactId:o||void 0,initialRecipientName:c||void 0,initialAddress:d||void 0,initialDate:u||void 0,onOpenChange:()=>i({})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search cards...",value:n,onChange:N=>r(N.target.value),className:"pl-9"})]}),p?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3].map(N=>e.jsx(we,{className:"animate-pulse",children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("div",{className:"h-40 bg-muted rounded-lg mb-3"}),e.jsx("div",{className:"h-4 bg-muted rounded w-2/3 mb-2"}),e.jsx("div",{className:"h-3 bg-muted rounded w-1/2"})]})},N))}):y!=null&&y.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:y.map(N=>e.jsxs(we,{className:"group overflow-hidden hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:`aspect-[16/10] flex items-center justify-center relative overflow-hidden ${N.template==="elegant"?"bg-gradient-to-br from-slate-50 via-slate-100 to-slate-200 dark:from-slate-900 dark:via-slate-800 dark:to-slate-700":N.template==="bold"?"bg-gradient-to-br from-violet-600 via-fuchsia-500 to-pink-500":"bg-gradient-to-br from-amber-100 via-orange-200 to-rose-200 dark:from-amber-900 dark:via-orange-800 dark:to-rose-800"}`,children:[N.template==="elegant"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"absolute top-0 left-0 w-full h-full opacity-10",children:[e.jsx("div",{className:"absolute top-3 left-3 w-16 h-16 border-t-2 border-l-2 border-primary/40 rounded-tl-lg"}),e.jsx("div",{className:"absolute bottom-3 right-3 w-16 h-16 border-b-2 border-r-2 border-primary/40 rounded-br-lg"})]}),e.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-32 h-32 rounded-full border border-primary/10"})]}),N.template==="bold"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute -top-8 -right-8 w-32 h-32 rounded-full bg-white/10 blur-sm"}),e.jsx("div",{className:"absolute -bottom-6 -left-6 w-24 h-24 rounded-full bg-white/10 blur-sm"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_center,rgba(255,255,255,0.15)_0%,transparent_70%)]"})]}),N.template==="warm"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute -top-4 -left-4 w-28 h-28 rounded-full bg-orange-400/15 blur-md"}),e.jsx("div",{className:"absolute -bottom-6 -right-6 w-32 h-32 rounded-full bg-rose-400/15 blur-md"})]}),e.jsxs("div",{className:"text-center px-4 relative z-10",children:[e.jsx("div",{className:"text-3xl mb-1.5 opacity-80",children:N.card_type==="home_anniversary"?"🏡":N.card_type==="wedding_anniversary"?"💍":N.card_type==="birthday"?"🎂":N.card_type==="just_sold"?"🎉":N.card_type==="just_listed"?"🏠":N.card_type==="thank_you"?"💐":N.card_type==="congratulations"?"🏆":N.card_type==="holiday"?"🎄":N.card_type==="thinking_of_you"?"💭":"✉️"}),e.jsx("p",{className:`text-[10px] uppercase tracking-[0.2em] mb-1 ${N.template==="bold"?"text-white/70":"text-muted-foreground"}`,children:b[N.card_type]||N.card_type}),e.jsx("p",{className:`font-semibold text-base ${N.template==="bold"?"text-white":"text-foreground"}`,children:N.recipient_name}),N.property_address&&e.jsx("p",{className:`text-xs mt-1 ${N.template==="bold"?"text-white/60":"text-muted-foreground"}`,children:N.property_address})]}),e.jsx("div",{className:"absolute top-2 right-2 z-10",children:e.jsx(Be,{variant:N.template==="bold"?"outline":"secondary",className:`text-[10px] ${N.template==="bold"?"border-white/30 text-white/80":""}`,children:v[N.template]||N.template})})]}),e.jsxs(Ie,{className:"p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(xa,{className:"h-3 w-3"}),N.view_count," views"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Nd(new Date(N.created_at),{addSuffix:!0})})]}),N.sent_at&&e.jsxs("p",{className:"text-[10px] text-emerald-600 mb-2",children:["Sent ",Gs(new Date(N.sent_at),"MMM d, yyyy")," via ",N.sent_via]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(U,{variant:"outline",size:"sm",className:"flex-1 gap-1 text-xs",onClick:()=>x(N.share_token),children:[e.jsx(Pa,{className:"h-3 w-3"}),"Copy Link"]}),e.jsx(ssr,{card:N}),e.jsx(tsr,{card:N}),e.jsx(U,{variant:"outline",size:"sm",className:"gap-1 text-xs",onClick:()=>window.open(`https://cardstudio.relevelup.com/c/${N.share_token}`,"_blank"),children:e.jsx(Sr,{className:"h-3 w-3"})}),e.jsx(U,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive gap-1 text-xs",onClick:()=>f.mutate(N.id),children:e.jsx(In,{className:"h-3 w-3"})})]})]})]},N.id))}):e.jsx(we,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx("div",{className:"h-16 w-16 rounded-full bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(ln,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"No cards yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Create your first digital card to send to a client"}),e.jsx(d5t,{initialOpen:h,initialCardType:l,initialContactId:o||void 0,initialRecipientName:c||void 0,initialAddress:d||void 0,initialDate:u||void 0,onOpenChange:()=>i({})})]})})]})})}const Fce=[{id:"mls",label:"MLS Description",tag:"Standard",icon:ra,accent:"from-sky-500 to-cyan-500",desc:"Polished MLS-ready listing",category:"listing"},{id:"luxury",label:"Luxury MLS",tag:"Premium",icon:h0,accent:"from-amber-500 to-orange-500",desc:"Evocative, high-end voice",category:"listing"},{id:"short",label:"Short MLS",tag:"Concise",icon:Af,accent:"from-violet-500 to-fuchsia-500",desc:"Punchy 60–90 words",category:"listing"},{id:"openHouse",label:"Open House",tag:"Promo",icon:G2,accent:"from-emerald-500 to-teal-500",desc:"Friendly invite copy",category:"listing",extras:["openHouse"]},{id:"newConstruction",label:"New Construction",tag:"Build",icon:BX,accent:"from-rose-500 to-pink-500",desc:"Builder-focused angle",category:"listing",extras:["newConstruction"]},{id:"investment",label:"Investment",tag:"ROI",icon:rc,accent:"from-indigo-500 to-blue-500",desc:"Cap rate & income hooks",category:"listing",extras:["investment"]},{id:"facebookPost",label:"Facebook Post",tag:"Social",icon:zp,accent:"from-blue-600 to-blue-400",desc:"Engaging FB caption",category:"social"},{id:"instagramPost",label:"Instagram Post",tag:"Social",icon:gm,accent:"from-pink-500 via-fuchsia-500 to-orange-400",desc:"IG caption + hashtags",category:"social"},{id:"linkedinPost",label:"LinkedIn Post",tag:"Social",icon:Gg,accent:"from-sky-700 to-sky-500",desc:"Professional tone",category:"social"},{id:"justListed",label:"Just Listed",tag:"Announce",icon:Th,accent:"from-emerald-500 to-green-500",desc:"Hit the market announcement",category:"social"},{id:"comingSoon",label:"Coming Soon",tag:"Tease",icon:Yr,accent:"from-amber-500 to-yellow-500",desc:"Build pre-market buzz",category:"social",extras:["comingSoon"]},{id:"priceImprovement",label:"Price Improvement",tag:"Update",icon:nS,accent:"from-orange-500 to-red-500",desc:"New price announcement",category:"social",extras:["priceImprovement"]},{id:"openHousePost",label:"Open House Post",tag:"Event",icon:nc,accent:"from-teal-500 to-emerald-500",desc:"Social invite to OH",category:"social",extras:["openHouse"]},{id:"underContract",label:"Under Contract",tag:"Status",icon:RX,accent:"from-indigo-500 to-purple-500",desc:"Pending celebration",category:"social",extras:["underContract"]},{id:"justSold",label:"Just Sold",tag:"Celebrate",icon:Wg,accent:"from-fuchsia-500 to-pink-500",desc:"Sold success post",category:"social",extras:["sold"]},{id:"propertyTourScript",label:"Property Tour",tag:"Script",icon:Wr,accent:"from-red-500 to-rose-500",desc:"Full walkthrough script",category:"video",extras:["signoff"]},{id:"reelScript",label:"Reel Script",tag:"Short",icon:Gh,accent:"from-fuchsia-500 to-pink-500",desc:"30–60s reel structure",category:"video",extras:["vibe","signoff"]},{id:"shortFormHooks",label:"Short-Form Hooks",tag:"Hooks",icon:LF,accent:"from-violet-500 to-purple-500",desc:"5 scroll-stopping hooks",category:"video",extras:["vibe"]},{id:"luxuryWalkthrough",label:"Luxury Walkthrough",tag:"Premium",icon:h0,accent:"from-amber-500 to-yellow-500",desc:"Cinematic, refined tone",category:"video",extras:["signoff"]},{id:"droneScript",label:"Drone Script",tag:"Aerial",icon:rQ,accent:"from-sky-500 to-blue-500",desc:"Voiceover for aerial b-roll",category:"video",extras:["signoff"]},{id:"neighborhoodTour",label:"Neighborhood Tour",tag:"Local",icon:ni,accent:"from-emerald-500 to-teal-500",desc:"Area lifestyle script",category:"video",extras:["neighborhood","signoff"]},{id:"justListedEmail",label:"Just Listed Email",tag:"Announce",icon:ln,accent:"from-emerald-500 to-green-500",desc:"Email blast for new listing",category:"email",extras:["signoff"]},{id:"openHouseEmail",label:"Open House Invite",tag:"Invite",icon:GX,accent:"from-teal-500 to-cyan-500",desc:"Public OH invitation",category:"email",extras:["openHouse","signoff"]},{id:"brokerOpenEmail",label:"Broker Open Invite",tag:"Agents",icon:Bn,accent:"from-indigo-500 to-blue-500",desc:"Invite to fellow agents",category:"email",extras:["openHouse","brokerOpen","signoff"]},{id:"priceReductionEmail",label:"Price Reduction",tag:"Update",icon:nS,accent:"from-orange-500 to-red-500",desc:"Price drop notification",category:"email",extras:["priceImprovement","signoff"]},{id:"justSoldEmail",label:"Just Sold Email",tag:"Celebrate",icon:A4,accent:"from-fuchsia-500 to-pink-500",desc:"Sold announcement email",category:"email",extras:["sold","signoff"]},{id:"neighborhoodEmail",label:"Neighborhood Email",tag:"Nurture",icon:ni,accent:"from-sky-500 to-indigo-500",desc:"Area update / market touch",category:"email",extras:["neighborhood","signoff"]}];function rsr(){var Fa,Fo,Xo,Vi,Ja,Co,Go,hi,Qo,Ao,_a;const{user:s}=vs(),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState([]),[o,c]=j.useState(""),[d,u]=j.useState([]),[h,m]=j.useState(""),[p,f]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState(""),[N,S]=j.useState(""),[A,T]=j.useState(""),[L,M]=j.useState(""),[I,R]=j.useState(null),[z,$]=j.useState(""),[H,V]=j.useState(""),[K,Z]=j.useState(""),[Q,le]=j.useState(""),[ue,se]=j.useState(""),[ne,ie]=j.useState(""),[ce,je]=j.useState(""),[be,he]=j.useState(""),[ge,ke]=j.useState(""),[Te,Me]=j.useState(""),[Oe,Se]=j.useState(""),[Qe,Ae]=j.useState(""),[Fe,Ne]=j.useState(""),[$e,Ve]=j.useState(""),[qe,Ze]=j.useState(""),[Ue,Ye]=j.useState(""),[Ge,He]=j.useState(""),[tt,pt]=j.useState(""),[ft,qt]=j.useState(""),[Ut,Wt]=j.useState(""),[us,zt]=j.useState(""),[bt,As]=j.useState(""),[vt,Ws]=j.useState(""),[on,Ms]=j.useState(""),[dn,rn]=j.useState(""),[br,Gn]=j.useState("listing"),[On,Rr]=j.useState("mls"),[cr,Hs]=j.useState({}),[_r,nn]=j.useState({}),[Zn,es]=j.useState(!1),[ar,Hn]=j.useState(!1),kn=ir=>{Gn(ir);const li=Fce.find(Eo=>Eo.category===ir);li&&Rr(li.id)},{data:Un}=ct({queryKey:["listing-studio-listings",s==null?void 0:s.id],enabled:!!(s!=null&&s.id)&&Zn,queryFn:async()=>{const{data:ir,error:li}=await q.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, property_type, description").eq("agent_id",s.id).order("created_at",{ascending:!1}).limit(50);if(li)throw li;return ir||[]}}),sn=()=>{const ir=o.trim();ir&&(l(li=>[...li,ir]),c(""))},un=ir=>l(li=>li.filter((Eo,gl)=>gl!==ir)),Ar=ir=>{var li,Eo,gl,ds;R(ir.id),n(ir.property_address||""),T(ir.city||""),M(ir.state||""),b(((li=ir.price)==null?void 0:li.toString())||""),m(((Eo=ir.bedrooms)==null?void 0:Eo.toString())||""),f(((gl=ir.bathrooms)==null?void 0:gl.toString())||""),y(((ds=ir.square_footage)==null?void 0:ds.toString())||""),S(ir.property_type||""),a(ir.description||""),es(!1),re.success("Listing imported")},fs=async ir=>{if(!(!ir.target.files||!(s!=null&&s.id))){Hn(!0);try{const li=[];for(const Eo of Array.from(ir.target.files).slice(0,10)){const gl=`${s.id}/${Date.now()}-${Eo.name.replace(/[^\w.-]/g,"_")}`,{error:ds}=await q.storage.from("listing-photos").upload(gl,Eo,{upsert:!1});if(ds){console.error(ds);continue}const{data:Gr}=q.storage.from("listing-photos").getPublicUrl(gl);li.push(Gr.publicUrl)}u(Eo=>[...Eo,...li]),li.length&&re.success(`${li.length} photo(s) uploaded`)}catch(li){re.error(li.message||"Photo upload failed")}finally{Hn(!1)}}},ot=Fce.find(ir=>ir.id===On),mt=async ir=>{var Eo,gl,ds;const li=Fce.find(Gr=>Gr.id===ir);if(!t.trim()&&!r.trim()&&i.length===0){re.error("Add a property address, MLS remarks, or features first");return}if((Eo=li.extras)!=null&&Eo.includes("openHouse")&&(!z||!H||!K)){re.error("Add the open house date, start and end time");return}if((gl=li.extras)!=null&&gl.includes("priceImprovement")&&(!Q||!ue)){re.error("Add previous and new price");return}if((ds=li.extras)!=null&&ds.includes("sold")&&!ne){re.error("Add the sold price");return}Rr(ir),nn(Gr=>({...Gr,[ir]:!0}));try{const{data:Gr,error:ji}=await q.functions.invoke("listing-studio-generate",{body:{copyType:ir,propertyAddress:t,mlsRemarks:r,features:i,photoUrls:d,listingId:I,bedrooms:h?Number(h):null,bathrooms:p?Number(p):null,squareFootage:x?Number(x):null,price:v?Number(v):null,propertyType:N||null,city:A||null,state:L||null,openHouseDate:z||null,openHouseStart:H||null,openHouseEnd:K||null,previousPrice:Q?Number(Q):null,newPrice:ue?Number(ue):null,soldPrice:ne?Number(ne):null,soldDate:ce||null,comingSoonDate:be||null,builderName:ge||null,yearBuilt:Te?Number(Te):null,warrantyInfo:Oe||null,monthlyRent:Qe?Number(Qe):null,capRate:Fe||null,occupancy:$e||null,daysOnMarket:qe?Number(qe):null,offerCount:Ue?Number(Ue):null,originalListPrice:Ge?Number(Ge):null,soldDaysOnMarket:tt?Number(tt):null,commissionOffered:ft||null,refreshments:Ut||null,vibe:us||null,neighborhoodHighlights:bt||null,agentName:vt||null,agentBrokerage:on||null,agentContact:dn||null}});if(ji)throw ji;if(Gr!=null&&Gr.error)throw new Error(Gr.error);Hs(ya=>({...ya,[ir]:Gr.content}))}catch(Gr){re.error(Gr.message||"Generation failed")}finally{nn(Gr=>({...Gr,[ir]:!1}))}},Nt=ir=>{navigator.clipboard.writeText(ir),re.success("Copied to clipboard")},Pt=ot.icon,ts=cr[On]?cr[On].trim().split(/\s+/).length:0,ls=ir=>e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:Fce.filter(li=>li.category===ir).map(li=>{const Eo=li.icon,gl=On===li.id,ds=!!cr[li.id];return e.jsxs("button",{onClick:()=>Rr(li.id),className:Mt("relative text-left p-4 rounded-2xl border transition-all overflow-hidden group",gl?"border-primary shadow-lg shadow-primary/10 bg-card":"border-border/60 hover:border-border bg-card/50 hover:bg-card"),children:[gl&&e.jsx("div",{className:Mt("absolute inset-0 opacity-[0.07] bg-gradient-to-br",li.accent)}),e.jsxs("div",{className:"relative space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:Mt("h-9 w-9 rounded-xl grid place-items-center text-white bg-gradient-to-br shadow-sm",li.accent),children:e.jsx(Eo,{className:"h-4 w-4"})}),ds&&e.jsx("div",{className:"h-5 w-5 rounded-full bg-emerald-500/15 text-emerald-600 grid place-items-center",children:e.jsx(Xr,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-sm",children:li.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:li.desc})]})]})]},li.id)})}),Is=(Fa=ot.extras)==null?void 0:Fa.includes("openHouse"),ps=(Fo=ot.extras)==null?void 0:Fo.includes("priceImprovement"),Ht=(Xo=ot.extras)==null?void 0:Xo.includes("sold"),Xs=(Vi=ot.extras)==null?void 0:Vi.includes("comingSoon"),Rs=(Ja=ot.extras)==null?void 0:Ja.includes("newConstruction"),zn=(Co=ot.extras)==null?void 0:Co.includes("investment"),Qr=(Go=ot.extras)==null?void 0:Go.includes("underContract"),ma=(hi=ot.extras)==null?void 0:hi.includes("brokerOpen"),qr=(Qo=ot.extras)==null?void 0:Qo.includes("vibe"),Zr=(Ao=ot.extras)==null?void 0:Ao.includes("neighborhood"),Jr=(_a=ot.extras)==null?void 0:_a.includes("signoff"),ha=Is||ps||Ht||Xs||Rs||zn||Qr||ma||qr||Zr||Jr;return e.jsx(qs,{title:"Listing Studio",children:e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-3xl border bg-gradient-to-br from-fuchsia-500/10 via-violet-500/5 to-sky-500/10 dark:from-fuchsia-500/20 dark:via-violet-500/10 dark:to-sky-500/20",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_top_right,_hsl(var(--primary)/0.15),_transparent_60%)]"}),e.jsx("div",{className:"absolute -top-24 -right-24 h-72 w-72 rounded-full bg-fuchsia-500/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-24 -left-24 h-72 w-72 rounded-full bg-sky-500/20 blur-3xl"}),e.jsxs("div",{className:"relative px-6 py-8 sm:px-10 sm:py-12 flex flex-col md:flex-row md:items-center gap-6",children:[e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-background/60 backdrop-blur-sm border text-xs font-medium",children:[e.jsx(cn,{className:"h-3.5 w-3.5 text-fuchsia-500"}),"AI-powered listing & social copy"]}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-bold tracking-tight bg-gradient-to-br from-foreground to-foreground/60 bg-clip-text",children:"Listing Studio"}),e.jsx("p",{className:"text-muted-foreground max-w-xl",children:"Drop in a property, generate magnetic MLS copy, luxury narratives, open-house promos, and ready-to-post social content — all in seconds."})]}),e.jsxs(zs,{open:Zn,onOpenChange:es,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{size:"lg",variant:"secondary",className:"shadow-lg shadow-fuchsia-500/10",children:[e.jsx(Ur,{className:"h-4 w-4 mr-2"}),"Import from Listings"]})}),e.jsxs(Ds,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Import from Listing Exchange"})}),e.jsxs("div",{className:"space-y-2 mt-2",children:[!(Un!=null&&Un.length)&&e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No listings found yet."}),Un==null?void 0:Un.map(ir=>e.jsxs("button",{onClick:()=>Ar(ir),className:"w-full text-left p-4 border rounded-xl hover:border-primary hover:bg-accent/50 transition-all",children:[e.jsx("div",{className:"font-medium",children:ir.property_address||"Untitled listing"}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[[ir.city,ir.state].filter(Boolean).join(", "),ir.price?` · $${Number(ir.price).toLocaleString()}`:"",ir.bedrooms?` · ${ir.bedrooms}bd`:"",ir.bathrooms?` · ${ir.bathrooms}ba`:""]})]},ir.id))]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-6",children:[e.jsx(we,{className:"lg:col-span-2 border-border/60 shadow-sm",children:e.jsxs(Ie,{className:"p-6 space-y-5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-primary/10 grid place-items-center",children:e.jsx(ra,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:"Property Details"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Fill in what you have — AI handles the rest"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsx(xe,{value:t,onChange:ir=>n(ir.target.value),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"City"}),e.jsx(xe,{value:A,onChange:ir=>T(ir.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"State"}),e.jsx(xe,{value:L,onChange:ir=>M(ir.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Price"}),e.jsx(xe,{type:"number",value:v,onChange:ir=>b(ir.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsx(xe,{value:N,onChange:ir=>S(ir.target.value),placeholder:"Single Family"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Beds"}),e.jsx(xe,{type:"number",value:h,onChange:ir=>m(ir.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Baths"}),e.jsx(xe,{type:"number",step:"0.5",value:p,onChange:ir=>f(ir.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sqft"}),e.jsx(xe,{type:"number",value:x,onChange:ir=>y(ir.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"MLS Remarks / Notes"}),e.jsx(Fs,{value:r,onChange:ir=>a(ir.target.value),placeholder:"Paste existing MLS remarks or rough notes...",rows:4,className:"resize-none"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Features"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:o,onChange:ir=>c(ir.target.value),onKeyDown:ir=>ir.key==="Enter"&&(ir.preventDefault(),sn()),placeholder:"e.g. Quartz countertops"}),e.jsx(U,{type:"button",size:"icon",variant:"secondary",onClick:sn,children:e.jsx(an,{className:"h-4 w-4"})})]}),i.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-2 animate-fade-in",children:i.map((ir,li)=>e.jsxs(Be,{variant:"secondary",className:"pl-3 pr-1 py-1 gap-1",children:[ir,e.jsx("button",{onClick:()=>un(li),className:"ml-0.5 p-0.5 hover:bg-background/60 rounded-full",children:e.jsx(er,{className:"h-3 w-3"})})]},li))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Photos (optional)"}),e.jsxs("label",{className:"flex items-center justify-center gap-2 p-4 border-2 border-dashed rounded-xl cursor-pointer hover:border-primary hover:bg-accent/30 transition-colors text-sm text-muted-foreground",children:[e.jsx(ly,{className:"h-4 w-4"}),ar?"Uploading…":"Click to upload photos",e.jsx("input",{type:"file",accept:"image/*",multiple:!0,onChange:fs,disabled:ar,className:"hidden"})]}),d.length>0&&e.jsx("div",{className:"grid grid-cols-4 gap-2 mt-2",children:d.map((ir,li)=>e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden group",children:[e.jsx("img",{src:ir,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>u(Eo=>Eo.filter((gl,ds)=>ds!==li)),className:"absolute top-1 right-1 bg-background/90 backdrop-blur rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(er,{className:"h-3 w-3"})})]},li))})]}),ha&&e.jsxs("div",{className:"space-y-4 p-4 rounded-xl border border-dashed border-primary/40 bg-primary/5 animate-fade-in",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cn,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"text-sm font-semibold",children:["Extra info for ",ot.label]})]}),Is&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Date"}),e.jsx(xe,{type:"date",value:z,onChange:ir=>$(ir.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Start"}),e.jsx(xe,{type:"time",value:H,onChange:ir=>V(ir.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"End"}),e.jsx(xe,{type:"time",value:K,onChange:ir=>Z(ir.target.value)})]})]})]}),ps&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Previous Price"}),e.jsx(xe,{type:"number",value:Q,onChange:ir=>le(ir.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"New Price"}),e.jsx(xe,{type:"number",value:ue,onChange:ir=>se(ir.target.value),placeholder:"$"})]})]}),Ht&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Price"}),e.jsx(xe,{type:"number",value:ne,onChange:ir=>ie(ir.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Date"}),e.jsx(xe,{type:"date",value:ce,onChange:ir=>je(ir.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Original List Price (optional)"}),e.jsx(xe,{type:"number",value:Ge,onChange:ir=>He(ir.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(xe,{type:"number",value:tt,onChange:ir=>pt(ir.target.value)})]})]})]}),Xs&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Expected Live Date (optional)"}),e.jsx(xe,{type:"date",value:be,onChange:ir=>he(ir.target.value)})]}),Rs&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Builder Name"}),e.jsx(xe,{value:ge,onChange:ir=>ke(ir.target.value),placeholder:"ABC Homes"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Year Built"}),e.jsx(xe,{type:"number",value:Te,onChange:ir=>Me(ir.target.value),placeholder:"2026"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Warranty / Energy / Smart-home (optional)"}),e.jsx(xe,{value:Oe,onChange:ir=>Se(ir.target.value),placeholder:"10-yr structural, ENERGY STAR, smart-home pkg"})]})]}),zn&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Monthly Rent (optional)"}),e.jsx(xe,{type:"number",value:Qe,onChange:ir=>Ae(ir.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Cap Rate (optional)"}),e.jsx(xe,{value:Fe,onChange:ir=>Ne(ir.target.value),placeholder:"6.5%"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Occupancy"}),e.jsxs("select",{value:$e,onChange:ir=>Ve(ir.target.value),className:"w-full h-10 rounded-md border border-input bg-background px-3 text-sm",children:[e.jsx("option",{value:"",children:"Select…"}),e.jsx("option",{value:"Vacant",children:"Vacant"}),e.jsx("option",{value:"Tenant-occupied",children:"Tenant-occupied"}),e.jsx("option",{value:"Owner-occupied",children:"Owner-occupied"}),e.jsx("option",{value:"Short-term rental",children:"Short-term rental"})]})]})]}),Qr&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(xe,{type:"number",value:qe,onChange:ir=>Ze(ir.target.value),placeholder:"e.g. 3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"# of Offers (optional)"}),e.jsx(xe,{type:"number",value:Ue,onChange:ir=>Ye(ir.target.value),placeholder:"e.g. 5"})]})]}),ma&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Commission / Co-op Offered (optional)"}),e.jsx(xe,{value:ft,onChange:ir=>qt(ir.target.value),placeholder:"2.5% buyer agent commission"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Refreshments / Perks (optional)"}),e.jsx(xe,{value:Ut,onChange:ir=>Wt(ir.target.value),placeholder:"Lunch + raffle for $100 gift card"})]})]}),qr&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Vibe / Tone"}),e.jsxs("select",{value:us,onChange:ir=>zt(ir.target.value),className:"w-full h-10 rounded-md border border-input bg-background px-3 text-sm",children:[e.jsx("option",{value:"",children:"Default"}),e.jsx("option",{value:"Energetic",children:"Energetic & fun"}),e.jsx("option",{value:"Luxury",children:"Luxury & cinematic"}),e.jsx("option",{value:"Cozy",children:"Warm & cozy"}),e.jsx("option",{value:"Humorous",children:"Humorous"}),e.jsx("option",{value:"Educational",children:"Educational"}),e.jsx("option",{value:"Bold",children:"Bold & confident"})]})]}),Zr&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Nearby Highlights (optional)"}),e.jsx(Fs,{value:bt,onChange:ir=>As(ir.target.value),rows:3,placeholder:"Top schools, parks, coffee shops, restaurants, commute, walkability…"})]}),Jr&&e.jsxs("div",{className:"space-y-3 pt-2 border-t border-border/40",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Sign-off (optional)"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium text-muted-foreground",children:"Agent Name"}),e.jsx(xe,{value:vt,onChange:ir=>Ws(ir.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage"}),e.jsx(xe,{value:on,onChange:ir=>Ms(ir.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs font-medium text-muted-foreground",children:"Phone / Email"}),e.jsx(xe,{value:dn,onChange:ir=>rn(ir.target.value),placeholder:"555-123-4567 or you@brand.com"})]})]})]})]})}),e.jsxs("div",{className:"lg:col-span-3 space-y-6",children:[e.jsx("div",{className:"flex gap-2 p-1 rounded-xl bg-muted/60 border border-border/40 overflow-x-auto",children:[{key:"listing",label:"Listing Copy",icon:Ur},{key:"social",label:"Social Media",icon:gm},{key:"video",label:"Video Scripts",icon:Wr},{key:"email",label:"Email Marketing",icon:ln}].map(ir=>{const li=ir.icon,Eo=br===ir.key;return e.jsxs("button",{onClick:()=>kn(ir.key),className:Mt("flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all",Eo?"bg-card shadow-sm text-foreground border border-border/60":"text-muted-foreground hover:text-foreground hover:bg-background/50"),children:[e.jsx(li,{className:"h-4 w-4"}),ir.label]},ir.key)})}),ls(br),e.jsxs(we,{className:"border-border/60 shadow-sm overflow-hidden",children:[e.jsx("div",{className:Mt("h-1 bg-gradient-to-r",ot.accent)}),e.jsxs(Ie,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Mt("h-10 w-10 rounded-xl grid place-items-center text-white bg-gradient-to-br",ot.accent),children:e.jsx(Pt,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold flex items-center gap-2",children:[ot.label,e.jsx(Be,{variant:"outline",className:"text-[10px] font-normal",children:ot.tag})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:cr[On]?`${ts} words`:"Ready to generate"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[cr[On]&&e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>Nt(cr[On]),children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"})," Copy"]}),e.jsx(U,{onClick:()=>mt(On),disabled:_r[On],className:Mt("shadow-lg shadow-primary/10 bg-gradient-to-r text-white border-0 hover:opacity-90",ot.accent),size:"sm",children:_r[On]?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"})," Generating"]}):cr[On]?e.jsxs(e.Fragment,{children:[e.jsx(no,{className:"h-4 w-4 mr-2"})," Regenerate"]}):e.jsxs(e.Fragment,{children:[e.jsx(Lg,{className:"h-4 w-4 mr-2"})," Generate"]})})]})]}),cr[On]?e.jsx(Fs,{value:cr[On],onChange:ir=>Hs(li=>({...li,[On]:ir.target.value})),rows:16,className:"resize-none font-serif text-[15px] leading-relaxed bg-muted/30 border-border/60 animate-fade-in"}):e.jsxs("div",{className:"border border-dashed rounded-xl p-12 text-center bg-muted/20",children:[e.jsx("div",{className:Mt("mx-auto h-14 w-14 rounded-2xl grid place-items-center text-white bg-gradient-to-br mb-4",ot.accent),children:e.jsx(Lg,{className:"h-6 w-6"})}),e.jsxs("div",{className:"font-medium mb-1",children:["Generate a ",ot.label.toLowerCase()]}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-sm mx-auto",children:"Fill in property details on the left, then click Generate. Your copy appears here — fully editable."})]})]})]})]})]})]})})}function GY({delay:s,x:t,y:n,size:r}){return e.jsx(kr.div,{className:"absolute rounded-full bg-slate-300/30 dark:bg-slate-500/20",style:{left:t,top:n,width:r,height:r},animate:{y:[0,-20,0],opacity:[.3,.7,.3],scale:[1,1.2,1]},transition:{duration:4,delay:s,repeat:1/0,ease:"easeInOut"}})}function asr(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:m}=s,p=kW[t];return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 via-blue-50/30 to-white dark:from-slate-950 dark:to-slate-900 flex items-center justify-center p-4 overflow-hidden relative",children:[e.jsxs("div",{className:"absolute inset-0 overflow-hidden",children:[e.jsx(kr.div,{className:"absolute -top-20 -right-20 w-72 h-72 rounded-full bg-gradient-to-br from-blue-100/40 to-slate-100/20 blur-3xl",animate:{scale:[1,1.1,1],rotate:[0,5,0]},transition:{duration:8,repeat:1/0,ease:"easeInOut"}}),e.jsx(kr.div,{className:"absolute -bottom-20 -left-20 w-64 h-64 rounded-full bg-gradient-to-tr from-slate-200/30 to-blue-100/20 blur-3xl",animate:{scale:[1,1.15,1],rotate:[0,-5,0]},transition:{duration:10,repeat:1/0,ease:"easeInOut"}}),e.jsx(GY,{delay:0,x:"15%",y:"20%",size:8}),e.jsx(GY,{delay:1,x:"80%",y:"30%",size:6}),e.jsx(GY,{delay:2,x:"60%",y:"70%",size:10}),e.jsx(GY,{delay:.5,x:"25%",y:"80%",size:7}),e.jsx(GY,{delay:1.5,x:"70%",y:"15%",size:5})]}),e.jsxs(kr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.8,ease:"easeOut"},children:[e.jsxs(kr.div,{className:"bg-white/80 dark:bg-slate-900/80 backdrop-blur-xl rounded-3xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.1)] overflow-hidden border border-slate-200/60 dark:border-slate-700/50",initial:{scale:.95},animate:{scale:1},transition:{duration:.6,delay:.2},children:[e.jsx("div",{className:"relative h-2 bg-gradient-to-r from-slate-200 via-blue-300 to-slate-200 dark:from-slate-700 dark:via-blue-500 dark:to-slate-700 overflow-hidden",children:e.jsx(kr.div,{className:"absolute inset-0 bg-gradient-to-r from-transparent via-white/60 to-transparent",animate:{x:["-100%","200%"]},transition:{duration:3,repeat:1/0,repeatDelay:2,ease:"easeInOut"}})}),e.jsxs("div",{className:"px-8 py-10 text-center",children:[e.jsxs(kr.div,{className:"mx-auto mb-6 h-20 w-20 rounded-2xl bg-gradient-to-br from-slate-100 to-blue-50 dark:from-slate-800 dark:to-slate-700 flex items-center justify-center shadow-lg relative",initial:{scale:0,rotate:-10},animate:{scale:1,rotate:0},transition:{duration:.5,delay:.4,type:"spring",stiffness:200},children:[e.jsx(kr.div,{className:"absolute inset-0 rounded-2xl border-2 border-slate-200/50 dark:border-slate-600/50",animate:{scale:[1,1.15,1],opacity:[.5,0,.5]},transition:{duration:2.5,repeat:1/0,ease:"easeInOut"}}),e.jsx("span",{className:"text-4xl",children:p.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsx(kr.div,{className:"inline-block mb-4",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.4,delay:.6},children:e.jsxs("span",{className:"text-sm font-semibold tracking-[0.25em] uppercase text-blue-400 dark:text-blue-300",children:[a," ",a===1?"Year":"Years"]})}),e.jsx(kr.h1,{className:"text-4xl font-light text-slate-800 dark:text-slate-100 mb-1 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.5,delay:.7},children:p.title[0]}),p.title[1]&&e.jsx(kr.h2,{className:"text-4xl font-bold text-slate-800 dark:text-slate-100 mb-8 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.5,delay:.85},children:p.title[1]}),e.jsxs(kr.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.5,delay:1},children:[e.jsx("p",{className:"text-xl font-medium text-slate-700 dark:text-slate-200 mb-1",children:n}),r&&e.jsx("p",{className:"text-sm text-slate-400 dark:text-slate-500 mb-6",children:r})]}),e.jsx(kr.div,{className:"h-px bg-gradient-to-r from-transparent via-slate-300 dark:via-slate-600 to-transparent mx-auto mb-6",initial:{width:0},animate:{width:"80%"},transition:{duration:.8,delay:1.1},style:{margin:"0 auto 1.5rem"}}),h&&e.jsx(kr.div,{className:"mb-6 rounded-xl overflow-hidden shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.15,duration:.5},children:e.jsx("img",{src:h,alt:"Property",className:"w-full h-48 object-cover"})}),m&&e.jsx(kr.div,{className:"mb-6 rounded-xl overflow-hidden shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("iframe",{src:`${m}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(kr.p,{className:"text-sm text-slate-500 dark:text-slate-400 leading-relaxed max-w-xs mx-auto mb-8 italic",initial:{opacity:0},animate:{opacity:1},transition:{duration:.6,delay:1.3},children:i||p.defaultMessage}),e.jsxs(kr.div,{className:"border-t border-slate-100 dark:border-slate-800 pt-6",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.5,delay:1.5},children:[e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[o?e.jsx(kr.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-slate-200 dark:ring-slate-700 shadow-md",whileHover:{scale:1.1}}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-gradient-to-br from-slate-200 to-blue-100 dark:from-slate-700 dark:to-slate-600 flex items-center justify-center shadow-md",children:e.jsx("span",{className:"text-sm font-semibold text-slate-600 dark:text-slate-300",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-700 dark:text-slate-200",children:l}),u&&e.jsx("p",{className:"text-xs text-slate-400 dark:text-slate-500",children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-3 mt-4",children:[c&&e.jsxs(kr.a,{href:`tel:${c}`,className:"flex items-center gap-1.5 px-4 py-2 rounded-full bg-slate-100 dark:bg-slate-800 text-xs font-medium text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors shadow-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(ba,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(kr.a,{href:`mailto:${d}`,className:"flex items-center gap-1.5 px-4 py-2 rounded-full bg-slate-100 dark:bg-slate-800 text-xs font-medium text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors shadow-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(ln,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(kr.p,{className:"text-center text-[10px] text-slate-400 dark:text-slate-600 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function _ze({delay:s,x:t,y:n,color:r,size:a}){return e.jsx(kr.div,{className:`absolute rounded-full blur-2xl ${r}`,style:{left:t,top:n,width:a,height:a},animate:{scale:[1,1.4,1],opacity:[.2,.5,.2]},transition:{duration:5,delay:s,repeat:1/0,ease:"easeInOut"}})}function WY({delay:s,x:t,y:n}){return e.jsx(kr.div,{className:"absolute text-white/30 text-lg",style:{left:t,top:n},animate:{opacity:[0,1,0],scale:[.5,1,.5],rotate:[0,180,360]},transition:{duration:3,delay:s,repeat:1/0,ease:"easeInOut"},children:"✦"})}const u5t={home_anniversary:{bg:"from-violet-950 via-purple-900 to-fuchsia-950",orbs:["bg-violet-500/30","bg-fuchsia-500/25","bg-purple-400/20"]},birthday:{bg:"from-pink-950 via-rose-900 to-fuchsia-950",orbs:["bg-pink-500/30","bg-rose-500/25","bg-fuchsia-400/20"]},just_sold:{bg:"from-emerald-950 via-teal-900 to-cyan-950",orbs:["bg-emerald-500/30","bg-teal-500/25","bg-cyan-400/20"]},just_listed:{bg:"from-amber-950 via-orange-900 to-yellow-950",orbs:["bg-amber-500/30","bg-orange-500/25","bg-yellow-400/20"]},thank_you:{bg:"from-rose-950 via-pink-900 to-red-950",orbs:["bg-rose-500/30","bg-pink-500/25","bg-red-400/20"]},congratulations:{bg:"from-yellow-950 via-amber-900 to-orange-950",orbs:["bg-yellow-500/30","bg-amber-500/25","bg-orange-400/20"]},holiday:{bg:"from-red-950 via-rose-900 to-emerald-950",orbs:["bg-red-500/30","bg-green-500/25","bg-rose-400/20"]},thinking_of_you:{bg:"from-indigo-950 via-violet-900 to-purple-950",orbs:["bg-indigo-500/30","bg-violet-500/25","bg-purple-400/20"]}};function isr(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:m}=s,p=kW[t],f=u5t[t]||u5t.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-br ${f.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[e.jsx(_ze,{delay:0,x:"10%",y:"10%",color:f.orbs[0],size:200}),e.jsx(_ze,{delay:1,x:"70%",y:"60%",color:f.orbs[1],size:180}),e.jsx(_ze,{delay:2,x:"50%",y:"20%",color:f.orbs[2],size:150}),e.jsx(WY,{delay:0,x:"20%",y:"25%"}),e.jsx(WY,{delay:.8,x:"75%",y:"15%"}),e.jsx(WY,{delay:1.6,x:"85%",y:"65%"}),e.jsx(WY,{delay:2.4,x:"10%",y:"75%"}),e.jsx(WY,{delay:.4,x:"45%",y:"85%"}),e.jsxs(kr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:40},animate:{opacity:1,y:0},transition:{duration:.7,ease:"easeOut"},children:[e.jsxs(kr.div,{className:"relative rounded-3xl overflow-hidden",initial:{scale:.9},animate:{scale:1},transition:{duration:.5,delay:.2,type:"spring",stiffness:150},children:[e.jsx(kr.div,{className:"absolute -inset-[1px] rounded-3xl bg-gradient-to-r from-violet-500 via-fuchsia-500 to-violet-500 opacity-50",animate:{backgroundPosition:["0% 50%","100% 50%","0% 50%"]},transition:{duration:4,repeat:1/0,ease:"linear"},style:{backgroundSize:"200% 200%"}}),e.jsxs("div",{className:"relative bg-white/5 backdrop-blur-xl border border-white/10 rounded-3xl px-8 py-10 text-center m-[1px]",children:[e.jsxs(kr.div,{className:"mx-auto mb-6 h-20 w-20 rounded-2xl bg-gradient-to-br from-violet-500 to-fuchsia-500 flex items-center justify-center shadow-2xl shadow-violet-500/40 relative",initial:{scale:0,rotate:-20},animate:{scale:1,rotate:0},transition:{duration:.6,delay:.4,type:"spring",stiffness:200},children:[e.jsx(kr.div,{className:"absolute inset-0 rounded-2xl bg-gradient-to-br from-violet-500 to-fuchsia-500",animate:{scale:[1,1.3,1],opacity:[.6,0,.6]},transition:{duration:2,repeat:1/0,ease:"easeInOut"}}),e.jsx("span",{className:"text-4xl relative z-10",children:p.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(kr.div,{className:"inline-flex items-center gap-2 mb-5 px-5 py-2 rounded-full bg-white/10 border border-white/15 backdrop-blur-sm",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.4,delay:.6},children:[e.jsx(kr.span,{className:"text-3xl font-black text-white",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.8},children:a}),e.jsx("span",{className:"text-xs font-semibold text-violet-200 uppercase tracking-widest",children:a===1?"Year":"Years"})]}),e.jsx(kr.h1,{className:"text-5xl font-black text-transparent bg-clip-text bg-gradient-to-r from-violet-200 via-white to-fuchsia-200 mb-2 leading-tight",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.7},children:p.title[0]}),p.title[1]&&e.jsx(kr.h2,{className:"text-5xl font-black text-transparent bg-clip-text bg-gradient-to-r from-fuchsia-300 via-violet-200 to-purple-300 mb-2 leading-tight",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.85},children:p.title[1]}),e.jsx(kr.div,{className:"text-3xl mb-4",initial:{opacity:0,scale:0},animate:{opacity:1,scale:1},transition:{duration:.4,delay:1,type:"spring",stiffness:300},children:p.emojis.slice(0,3).join("")}),e.jsxs(kr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[e.jsx("p",{className:"text-xl font-semibold text-white/90 mb-1",children:n}),r&&e.jsxs("p",{className:"text-sm text-violet-300/70 mb-6 flex items-center justify-center gap-1.5",children:[e.jsx(ra,{className:"h-3.5 w-3.5"}),r]})]}),h&&e.jsx(kr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10 shadow-lg",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("img",{src:h,alt:"Property",className:"w-full h-48 object-cover"})}),m&&e.jsx(kr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10 shadow-lg",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.25,duration:.5},children:e.jsx("iframe",{src:`${m}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(kr.div,{className:"bg-white/5 rounded-2xl p-5 border border-white/10 mb-8 backdrop-blur-sm",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsx("p",{className:"text-sm text-violet-100/80 leading-relaxed",children:i||p.defaultMessage})}),e.jsxs(kr.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[o?e.jsx(kr.img,{src:o,alt:l,className:"h-12 w-12 rounded-xl object-cover ring-2 ring-violet-500/40 shadow-lg",whileHover:{scale:1.1}}):e.jsx("div",{className:"h-12 w-12 rounded-xl bg-gradient-to-br from-violet-500 to-fuchsia-500 flex items-center justify-center shadow-lg",children:e.jsx("span",{className:"text-sm font-bold text-white",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-bold text-white",children:l}),u&&e.jsx("p",{className:"text-xs text-violet-300/60",children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-5",children:[c&&e.jsxs(kr.a,{href:`tel:${c}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r from-violet-500/30 to-fuchsia-500/30 text-xs font-semibold text-white hover:from-violet-500/50 hover:to-fuchsia-500/50 transition-all border border-white/15 shadow-lg",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(ba,{className:"h-3.5 w-3.5"})," Call Me"]}),d&&e.jsxs(kr.a,{href:`mailto:${d}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r from-violet-500/30 to-fuchsia-500/30 text-xs font-semibold text-white hover:from-violet-500/50 hover:to-fuchsia-500/50 transition-all border border-white/15 shadow-lg",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(ln,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(kr.p,{className:"text-center text-[10px] text-violet-400/40 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function osr({emoji:s,delay:t,x:n,duration:r}){return e.jsx(kr.div,{className:"absolute text-2xl pointer-events-none",style:{left:n,bottom:-20},animate:{y:[0,-600],opacity:[0,1,1,0],x:[0,15,-10,5],rotate:[0,20,-15,10]},transition:{duration:r,delay:t,repeat:1/0,ease:"easeOut"},children:s})}const h5t={home_anniversary:{bg:"from-amber-50 via-orange-50 to-rose-50",header:"from-amber-400 via-orange-400 to-rose-400",accent:"text-amber-900",text:"text-amber-800"},birthday:{bg:"from-pink-50 via-rose-50 to-fuchsia-50",header:"from-pink-400 via-rose-400 to-fuchsia-400",accent:"text-pink-900",text:"text-pink-800"},just_sold:{bg:"from-emerald-50 via-teal-50 to-cyan-50",header:"from-emerald-400 via-teal-400 to-cyan-400",accent:"text-emerald-900",text:"text-emerald-800"},just_listed:{bg:"from-sky-50 via-blue-50 to-indigo-50",header:"from-sky-400 via-blue-400 to-indigo-400",accent:"text-blue-900",text:"text-blue-800"},thank_you:{bg:"from-rose-50 via-pink-50 to-red-50",header:"from-rose-400 via-pink-400 to-red-400",accent:"text-rose-900",text:"text-rose-800"},congratulations:{bg:"from-yellow-50 via-amber-50 to-orange-50",header:"from-yellow-400 via-amber-400 to-orange-400",accent:"text-amber-900",text:"text-amber-800"},holiday:{bg:"from-red-50 via-green-50 to-emerald-50",header:"from-red-500 via-green-500 to-emerald-500",accent:"text-green-900",text:"text-green-800"},thinking_of_you:{bg:"from-violet-50 via-purple-50 to-indigo-50",header:"from-violet-400 via-purple-400 to-indigo-400",accent:"text-violet-900",text:"text-violet-800"}};function lsr(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:m}=s,p=kW[t],f=h5t[t]||h5t.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${f.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[p.emojis.map((x,y)=>e.jsx(osr,{emoji:x,delay:y*1.2,x:`${15+y*14}%`,duration:5+y%3},y)),e.jsx(kr.div,{className:"absolute top-1/4 left-1/2 -translate-x-1/2 w-96 h-96 bg-gradient-to-r from-amber-200/30 to-rose-200/30 rounded-full blur-[100px]",animate:{scale:[1,1.2,1],opacity:[.3,.5,.3]},transition:{duration:6,repeat:1/0,ease:"easeInOut"}}),e.jsxs(kr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.7},children:[e.jsxs(kr.div,{className:"bg-white rounded-3xl shadow-[0_20px_60px_-15px_rgba(251,146,60,0.2)] overflow-hidden border border-amber-100",initial:{scale:.9},animate:{scale:1},transition:{duration:.5,delay:.2,type:"spring",stiffness:150},children:[e.jsxs(kr.div,{className:`h-28 bg-gradient-to-r ${f.header} relative overflow-hidden`,children:[e.jsx(kr.div,{className:"absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent",animate:{x:["-100%","200%"]},transition:{duration:3,repeat:1/0,repeatDelay:2,ease:"easeInOut"}}),e.jsx(kr.div,{className:"absolute top-3 left-10 text-5xl",animate:{rotate:[0,10,-5,0],y:[0,-3,0]},transition:{duration:3,repeat:1/0,ease:"easeInOut"},children:p.emojis[0]}),e.jsx(kr.div,{className:"absolute top-2 right-14 text-3xl",animate:{scale:[1,1.3,1],rotate:[0,15,0]},transition:{duration:2,repeat:1/0,ease:"easeInOut",delay:.5},children:p.emojis[1]}),e.jsx(kr.div,{className:"absolute bottom-2 left-1/2 -translate-x-1/2 text-3xl",animate:{y:[0,-5,0],scale:[1,1.1,1]},transition:{duration:2.5,repeat:1/0,ease:"easeInOut",delay:1},children:p.emojis[2]})]}),e.jsxs("div",{className:"px-8 py-8 text-center -mt-10 relative",children:[e.jsx(kr.div,{className:"mx-auto mb-4 h-20 w-20 rounded-full bg-white shadow-xl flex items-center justify-center border-4 border-white relative",initial:{scale:0},animate:{scale:1},transition:{delay:.4,type:"spring",stiffness:300},children:e.jsx(kr.div,{animate:{scale:[1,1.2,1]},transition:{duration:1.5,repeat:1/0,ease:"easeInOut"},children:e.jsx("span",{className:"text-3xl",children:p.icon})})}),t==="home_anniversary"&&a!==null&&a>0&&e.jsx(kr.div,{className:"mb-3",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{delay:.6},children:e.jsxs("span",{className:`inline-flex items-baseline gap-1.5 ${f.accent}`,children:[e.jsx(kr.span,{className:"text-5xl font-black",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.8},children:a}),e.jsx("span",{className:"text-sm font-semibold",children:a===1?"year":"wonderful years"})]})}),e.jsxs(kr.h1,{className:`text-3xl font-bold ${f.accent} mb-1`,initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.9},children:[p.title.join(" ")," ",p.emojis[4]]}),e.jsxs(kr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[e.jsx("p",{className:`text-lg font-semibold ${f.text} mb-1`,children:n}),r&&e.jsxs("p",{className:`text-sm ${f.text} opacity-70 flex items-center justify-center gap-1 mb-5`,children:[e.jsx(ni,{className:"h-3 w-3"}),r]})]}),h&&e.jsx(kr.div,{className:"mb-5 rounded-2xl overflow-hidden border border-amber-200 shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("img",{src:h,alt:"Property",className:"w-full h-48 object-cover"})}),m&&e.jsx(kr.div,{className:"mb-5 rounded-2xl overflow-hidden border border-amber-200 shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.25,duration:.5},children:e.jsx("iframe",{src:`${m}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(kr.div,{className:"bg-gradient-to-br from-amber-50 to-orange-50 rounded-2xl p-5 mb-6 border border-amber-100 shadow-inner",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsxs("p",{className:`text-sm ${f.text} leading-relaxed italic`,children:['"',i||p.defaultMessage,'"']})}),e.jsxs(kr.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[e.jsxs("div",{className:"flex items-center gap-3 justify-center",children:[o?e.jsx(kr.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-amber-200 shadow-md",whileHover:{scale:1.1}}):e.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${f.header} flex items-center justify-center shadow-md`,children:e.jsx("span",{className:"text-sm font-bold text-white",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:`text-sm font-bold ${f.accent}`,children:l}),u&&e.jsx("p",{className:`text-xs ${f.text} opacity-60`,children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[c&&e.jsxs(kr.a,{href:`tel:${c}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${f.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(ba,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(kr.a,{href:`mailto:${d}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${f.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(ln,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(kr.p,{className:"text-center text-[10px] text-amber-400 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function zce({delay:s,x:t,y:n,size:r,color:a}){return e.jsx(kr.div,{className:`absolute rounded-full ${a} blur-3xl`,style:{left:t,top:n,width:r,height:r},animate:{scale:[1,1.3,1],opacity:[.4,.7,.4],x:[0,20,-10,0],y:[0,-15,10,0]},transition:{duration:8,delay:s,repeat:1/0,ease:"easeInOut"}})}function wze({delay:s,x:t,y:n,size:r}){return e.jsx(kr.div,{className:"absolute rounded-full border border-white/10",style:{left:t,top:n,width:r,height:r},animate:{scale:[1,1.2,1],opacity:[.1,.3,.1],rotate:[0,180,360]},transition:{duration:12,delay:s,repeat:1/0,ease:"linear"}})}const m5t={home_anniversary:{mesh:["bg-sky-400/40","bg-indigo-500/30","bg-violet-400/25"],accent:"text-sky-200",glow:"shadow-sky-500/20"},birthday:{mesh:["bg-pink-400/40","bg-fuchsia-500/30","bg-purple-400/25"],accent:"text-pink-200",glow:"shadow-pink-500/20"},just_sold:{mesh:["bg-emerald-400/40","bg-teal-500/30","bg-cyan-400/25"],accent:"text-emerald-200",glow:"shadow-emerald-500/20"},just_listed:{mesh:["bg-amber-400/40","bg-orange-500/30","bg-yellow-400/25"],accent:"text-amber-200",glow:"shadow-amber-500/20"},thank_you:{mesh:["bg-rose-400/40","bg-pink-500/30","bg-red-400/25"],accent:"text-rose-200",glow:"shadow-rose-500/20"},congratulations:{mesh:["bg-yellow-400/40","bg-amber-500/30","bg-orange-400/25"],accent:"text-yellow-200",glow:"shadow-yellow-500/20"},holiday:{mesh:["bg-red-400/40","bg-emerald-500/30","bg-green-400/25"],accent:"text-red-200",glow:"shadow-red-500/20"},thinking_of_you:{mesh:["bg-violet-400/40","bg-indigo-500/30","bg-blue-400/25"],accent:"text-violet-200",glow:"shadow-violet-500/20"}};function csr(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:m}=s,p=kW[t],f=m5t[t]||m5t.home_anniversary;return e.jsxs("div",{className:"min-h-screen bg-slate-950 flex items-center justify-center p-4 overflow-hidden relative",children:[e.jsx(zce,{delay:0,x:"5%",y:"10%",size:300,color:f.mesh[0]}),e.jsx(zce,{delay:2,x:"60%",y:"50%",size:250,color:f.mesh[1]}),e.jsx(zce,{delay:4,x:"30%",y:"70%",size:200,color:f.mesh[2]}),e.jsx(zce,{delay:1,x:"80%",y:"15%",size:180,color:f.mesh[0]}),e.jsx(wze,{delay:0,x:"15%",y:"20%",size:100}),e.jsx(wze,{delay:3,x:"70%",y:"60%",size:140}),e.jsx(wze,{delay:6,x:"40%",y:"10%",size:80}),e.jsx("div",{className:"absolute inset-0 opacity-[0.03]",style:{backgroundImage:`url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E")`}}),e.jsxs(kr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:40},animate:{opacity:1,y:0},transition:{duration:.8,ease:[.16,1,.3,1]},children:[e.jsxs(kr.div,{className:`relative rounded-[28px] overflow-hidden backdrop-blur-2xl bg-white/[0.06] border border-white/[0.12] shadow-2xl ${f.glow}`,initial:{scale:.92},animate:{scale:1},transition:{duration:.6,delay:.2,type:"spring",stiffness:120},children:[e.jsx("div",{className:"relative h-[2px] bg-gradient-to-r from-transparent via-white/20 to-transparent overflow-hidden",children:e.jsx(kr.div,{className:"absolute inset-0 bg-gradient-to-r from-transparent via-white/60 to-transparent",animate:{x:["-100%","200%"]},transition:{duration:4,repeat:1/0,repeatDelay:3,ease:"easeInOut"}})}),e.jsxs("div",{className:"px-8 py-10 text-center",children:[e.jsxs(kr.div,{className:"mx-auto mb-6 h-24 w-24 rounded-3xl bg-white/[0.08] backdrop-blur-xl border border-white/[0.15] flex items-center justify-center relative",initial:{scale:0,rotate:-15},animate:{scale:1,rotate:0},transition:{duration:.6,delay:.4,type:"spring",stiffness:180},children:[e.jsx(kr.div,{className:"absolute -inset-1 rounded-3xl border border-white/[0.08]",animate:{scale:[1,1.1,1],opacity:[.3,0,.3]},transition:{duration:3,repeat:1/0,ease:"easeInOut"}}),e.jsx(kr.span,{className:"text-5xl",animate:{scale:[1,1.08,1]},transition:{duration:2,repeat:1/0,ease:"easeInOut"},children:p.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(kr.div,{className:"inline-flex items-center gap-2 mb-5 px-5 py-2 rounded-full bg-white/[0.06] border border-white/[0.1] backdrop-blur-sm",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.4,delay:.6},children:[e.jsx(kr.span,{className:"text-3xl font-black text-white",initial:{opacity:0},animate:{opacity:1},transition:{delay:.8},children:a}),e.jsx("span",{className:`text-[10px] font-bold uppercase tracking-[0.2em] ${f.accent}`,children:a===1?"Year":"Years"})]}),e.jsx(kr.h1,{className:"text-4xl font-extralight text-white/90 mb-1 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.6,delay:.7},children:p.title[0]}),p.title[1]&&e.jsx(kr.h2,{className:"text-4xl font-bold text-white mb-6 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.6,delay:.85},children:p.title[1]}),e.jsxs(kr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1},children:[e.jsx("p",{className:"text-xl font-medium text-white/80 mb-1",children:n}),r&&e.jsxs("p",{className:"text-sm text-white/30 mb-6 flex items-center justify-center gap-1.5",children:[e.jsx(ni,{className:"h-3 w-3"})," ",r]})]}),e.jsx(kr.div,{className:"h-px bg-gradient-to-r from-transparent via-white/15 to-transparent mx-auto mb-6",initial:{width:0},animate:{width:"70%"},transition:{duration:1,delay:1.1},style:{margin:"0 auto 1.5rem"}}),h&&e.jsx(kr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.15,duration:.5},children:e.jsx("img",{src:h,alt:"Property",className:"w-full h-48 object-cover"})}),m&&e.jsx(kr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("iframe",{src:`${m}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(kr.div,{className:"bg-white/[0.04] rounded-2xl p-5 border border-white/[0.08] mb-8 backdrop-blur-sm",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsxs("p",{className:"text-sm text-white/60 leading-relaxed italic",children:['"',i||p.defaultMessage,'"']})}),e.jsxs(kr.div,{className:"border-t border-white/[0.06] pt-6",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[o?e.jsx(kr.img,{src:o,alt:l,className:"h-12 w-12 rounded-2xl object-cover ring-1 ring-white/10",whileHover:{scale:1.08}}):e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-white/[0.08] border border-white/[0.1] flex items-center justify-center",children:e.jsx("span",{className:"text-sm font-semibold text-white/60",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-white/80",children:l}),u&&e.jsx("p",{className:"text-xs text-white/30",children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[c&&e.jsxs(kr.a,{href:`tel:${c}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/70 hover:bg-white/[0.12] transition-colors backdrop-blur-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(ba,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(kr.a,{href:`mailto:${d}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/70 hover:bg-white/[0.12] transition-colors backdrop-blur-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(ln,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(kr.p,{className:"text-center text-[10px] text-white/20 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function jze({delay:s,x:t,angle:n,color:r}){return e.jsx(kr.div,{className:`absolute h-[400px] w-[1px] ${r} origin-top`,style:{left:t,top:"-10%",transform:`rotate(${n}deg)`},animate:{opacity:[0,.4,0],scaleY:[.5,1,.5]},transition:{duration:6,delay:s,repeat:1/0,ease:"easeInOut"}})}function Bce({delay:s,x:t}){return e.jsx(kr.div,{className:"absolute w-1 h-1 rounded-full bg-amber-400/60",style:{left:t,bottom:"20%"},animate:{y:[0,-200,-400],x:[0,15,-10],opacity:[0,.8,0],scale:[0,1.5,0]},transition:{duration:4,delay:s,repeat:1/0,ease:"easeOut"}})}const p5t={home_anniversary:{gradient:"from-slate-950 via-blue-950 to-slate-950",accent:"from-blue-400 to-cyan-300",stripe:"bg-blue-400/20"},birthday:{gradient:"from-slate-950 via-rose-950 to-slate-950",accent:"from-rose-400 to-pink-300",stripe:"bg-rose-400/20"},just_sold:{gradient:"from-slate-950 via-emerald-950 to-slate-950",accent:"from-emerald-400 to-green-300",stripe:"bg-emerald-400/20"},just_listed:{gradient:"from-slate-950 via-amber-950 to-slate-950",accent:"from-amber-400 to-yellow-300",stripe:"bg-amber-400/20"},thank_you:{gradient:"from-slate-950 via-pink-950 to-slate-950",accent:"from-pink-400 to-rose-300",stripe:"bg-pink-400/20"},congratulations:{gradient:"from-slate-950 via-yellow-950 to-slate-950",accent:"from-yellow-400 to-amber-300",stripe:"bg-yellow-400/20"},holiday:{gradient:"from-slate-950 via-red-950 to-slate-950",accent:"from-red-400 to-green-400",stripe:"bg-red-400/20"},thinking_of_you:{gradient:"from-slate-950 via-purple-950 to-slate-950",accent:"from-purple-400 to-violet-300",stripe:"bg-purple-400/20"}};function dsr(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:m}=s,p=kW[t],f=p5t[t]||p5t.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${f.gradient} flex items-center justify-center p-4 overflow-hidden relative`,children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,rgba(255,255,255,0.04)_0%,transparent_60%)]"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_bottom,rgba(0,0,0,0.6)_0%,transparent_60%)]"}),e.jsx(jze,{delay:0,x:"20%",angle:15,color:f.stripe}),e.jsx(jze,{delay:2,x:"75%",angle:-12,color:f.stripe}),e.jsx(jze,{delay:4,x:"50%",angle:5,color:f.stripe}),e.jsx(Bce,{delay:0,x:"30%"}),e.jsx(Bce,{delay:1.5,x:"60%"}),e.jsx(Bce,{delay:3,x:"45%"}),e.jsx(Bce,{delay:.7,x:"75%"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.015] mix-blend-overlay",style:{backgroundImage:`url("data:image/svg+xml,%3Csvg viewBox='0 0 512 512' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.7' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")`}}),e.jsxs(kr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0},animate:{opacity:1},transition:{duration:1.2},children:[e.jsx(kr.div,{className:"relative overflow-hidden",initial:{y:50},animate:{y:0},transition:{duration:.8,delay:.3,ease:[.16,1,.3,1]},children:e.jsxs("div",{className:"px-8 py-12 text-center",children:[e.jsx(kr.div,{className:"mx-auto mb-8 relative",initial:{scale:0},animate:{scale:1},transition:{duration:.8,delay:.5,type:"spring",stiffness:100},children:e.jsx(kr.div,{className:`h-20 w-20 mx-auto rounded-2xl bg-gradient-to-br ${f.accent} flex items-center justify-center shadow-2xl`,animate:{boxShadow:["0 0 40px rgba(255,255,255,0.05)","0 0 80px rgba(255,255,255,0.1)","0 0 40px rgba(255,255,255,0.05)"]},transition:{duration:3,repeat:1/0,ease:"easeInOut"},children:e.jsx("span",{className:"text-4xl",children:p.icon})})}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(kr.div,{className:"mb-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:.7},children:[e.jsx(kr.span,{className:`text-6xl font-black bg-gradient-to-r ${f.accent} bg-clip-text text-transparent`,initial:{scale:.5,opacity:0},animate:{scale:1,opacity:1},transition:{delay:.9,type:"spring"},children:a}),e.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.4em] text-white/30 mt-1",children:a===1?"Year":"Years"})]}),e.jsx("div",{className:"overflow-hidden mb-2",children:e.jsx(kr.h1,{className:"text-5xl font-thin text-white/90 tracking-wide",initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.8,ease:[.16,1,.3,1]},children:p.title[0]})}),p.title[1]&&e.jsx("div",{className:"overflow-hidden mb-8",children:e.jsx(kr.h2,{className:`text-5xl font-black bg-gradient-to-r ${f.accent} bg-clip-text text-transparent`,initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.95,ease:[.16,1,.3,1]},children:p.title[1]})}),e.jsxs(kr.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.1,duration:.6},children:[e.jsx("p",{className:"text-lg font-light text-white/70 tracking-wide",children:n}),r&&e.jsxs("p",{className:"text-xs text-white/25 mt-1 flex items-center justify-center gap-1",children:[e.jsx(ni,{className:"h-3 w-3"})," ",r]})]}),e.jsxs(kr.div,{className:"flex items-center justify-center gap-3 my-8",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.2},children:[e.jsx(kr.div,{className:"h-px flex-1 max-w-[60px] bg-gradient-to-r from-transparent to-white/15",initial:{scaleX:0},animate:{scaleX:1},transition:{delay:1.3,duration:.8},style:{transformOrigin:"right"}}),e.jsx(kr.span,{className:"text-white/10 text-xs",animate:{rotate:[0,360]},transition:{duration:20,repeat:1/0,ease:"linear"},children:"✦"}),e.jsx(kr.div,{className:"h-px flex-1 max-w-[60px] bg-gradient-to-l from-transparent to-white/15",initial:{scaleX:0},animate:{scaleX:1},transition:{delay:1.3,duration:.8},style:{transformOrigin:"left"}})]}),h&&e.jsxs(kr.div,{className:"mb-8 rounded-2xl overflow-hidden ring-1 ring-white/5",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.3,duration:.6},children:[e.jsx("img",{src:h,alt:"Property",className:"w-full h-48 object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-950/30 to-transparent pointer-events-none"})]}),m&&e.jsx(kr.div,{className:"mb-8 rounded-2xl overflow-hidden ring-1 ring-white/5",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.35,duration:.6},children:e.jsx("iframe",{src:`${m}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(kr.p,{className:"text-sm text-white/40 leading-relaxed max-w-xs mx-auto mb-10 font-light",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.4,duration:.8},children:i||p.defaultMessage}),e.jsxs(kr.div,{className:"pt-6 border-t border-white/[0.04]",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{delay:1.6,duration:.6},children:[e.jsxs("div",{className:"flex items-center justify-center gap-3 mb-4",children:[o?e.jsx(kr.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white/10 shadow-xl",whileHover:{scale:1.1}}):e.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${f.accent} flex items-center justify-center shadow-xl`,children:e.jsx("span",{className:"text-sm font-bold text-slate-900",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-medium text-white/70",children:l}),u&&e.jsx("p",{className:"text-[11px] text-white/25",children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[c&&e.jsxs(kr.a,{href:`tel:${c}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${f.accent} text-xs font-semibold text-slate-900 shadow-lg`,whileHover:{scale:1.05,boxShadow:"0 10px 40px rgba(255,255,255,0.15)"},whileTap:{scale:.95},children:[e.jsx(ba,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(kr.a,{href:`mailto:${d}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/60 hover:bg-white/[0.12] transition-colors",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(ln,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})}),e.jsx(kr.p,{className:"text-center text-[10px] text-white/10 mt-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:2.2},children:"Powered by LevelUp"})]})]})}function kss(){const{shareToken:s}=Di(),{data:t,isLoading:n,error:r}=ct({queryKey:["public-sendable-card",s],queryFn:async()=>{const{data:l,error:o}=await q.from("sendable_cards").select("*").eq("share_token",s).single();if(o)throw o;return l},enabled:!!s});if(j.useEffect(()=>{if(!t)return;const l=(t.recipient_name||"").trim().split(/\s+/)[0],c={home_anniversary:"Happy Home Anniversary",birthday:"Happy Birthday",wedding_anniversary:"Happy Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",holiday:"Happy Holidays",thank_you:"Thank You",thinking_of_you:"Thinking of You"}[t.card_type]||"A card for you";document.title=l?`${c}, ${l}!`:`${c}!`},[t]),j.useEffect(()=>{s&&q.rpc("log_sendable_card_view",{p_share_token:s}).then(({error:l})=>{l&&console.error("Error tracking view:",l)})},[s]),n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"animate-pulse space-y-4 text-center",children:[e.jsx("div",{className:"h-8 w-48 bg-muted rounded mx-auto"}),e.jsx("div",{className:"h-4 w-32 bg-muted rounded mx-auto"})]})});if(r||!t)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Card not found"}),e.jsx("p",{className:"text-muted-foreground",children:"This card may have been removed or the link is invalid."})]})});const a=t.home_anniversary_date?Math.floor((Date.now()-Su(t.home_anniversary_date).getTime())/(365.25*24*60*60*1e3)):null,i={cardType:t.card_type||"home_anniversary",recipientName:t.recipient_name,propertyAddress:t.property_address,anniversaryYears:a,customMessage:t.custom_message,agentName:t.agent_name,agentPhotoUrl:t.agent_photo_url,agentPhone:t.agent_phone,agentEmail:t.agent_email,agentBrokerage:t.agent_brokerage,propertyPhotoUrl:t.property_photo_url,videoUrl:t.video_url||null};switch(t.template){case"bold":return e.jsx(isr,{...i});case"warm":return e.jsx(lsr,{...i});case"glass":return e.jsx(csr,{...i});case"cinematic":return e.jsx(dsr,{...i});case"elegant":default:return e.jsx(asr,{...i})}}function usr(){const s=Sa();return ct({queryKey:["drip-settings",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("drip_settings").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function hsr(){const s=Sa(),t=Qt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r}=await q.from("drip_settings").select("id").eq("user_id",s).maybeSingle();if(r){const{data:a,error:i}=await q.from("drip_settings").update(n).eq("user_id",s).select().single();if(i)throw i;return a}else{const{data:a,error:i}=await q.from("drip_settings").insert({user_id:s,is_globally_enabled:n.is_globally_enabled??!1,append_signature:n.append_signature??!0}).select().single();if(i)throw i;return a}},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-settings"]})}})}function msr(){const s=Wn(),{isGmailConnected:t,gmailEmail:n}=Ax(),{data:r,isLoading:a}=usr(),i=hsr(),[l,o]=j.useState(!1),[c,d]=j.useState(!0),[u,h]=j.useState(!1);j.useEffect(()=>{r&&(o(r.is_globally_enabled),d(r.append_signature))},[r]);const m=async f=>{if(f&&!t){re.error("Connect your Gmail account first before enabling Smart Drips");return}o(f);try{await i.mutateAsync({is_globally_enabled:f}),re.success(f?"Smart Drips enabled globally":"Smart Drips paused globally")}catch{o(!f),re.error("Failed to update settings")}},p=async f=>{d(f);try{await i.mutateAsync({append_signature:f}),re.success(f?"Signature will be appended to drip emails":"Signature disabled for drip emails")}catch{d(!f),re.error("Failed to update settings")}};return e.jsxs(zs,{open:u,onOpenChange:h,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(qc,{className:"h-3.5 w-3.5"}),"Settings"]})}),e.jsxs(Ds,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(qc,{className:"h-5 w-5 text-primary"}),"Smart Drip Settings"]}),e.jsx(Pr,{children:"Configure how your automated drip emails are sent."})]}),e.jsxs("div",{className:"space-y-5 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Email Connection"}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`p-2 rounded-full ${t?"bg-emerald-500/10":"bg-destructive/10"}`,children:e.jsx(ln,{className:`h-4 w-4 ${t?"text-emerald-600":"text-destructive"}`})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:t?"Gmail Connected":"Gmail Not Connected"}),n&&e.jsx("p",{className:"text-xs text-muted-foreground",children:n})]})]}),t?e.jsxs(Be,{variant:"outline",className:"gap-1 text-emerald-600 border-emerald-200 bg-emerald-500/10 text-[10px]",children:[e.jsx(zr,{className:"h-3 w-3"}),"Active"]}):e.jsxs(U,{variant:"outline",size:"sm",className:"text-xs gap-1",onClick:()=>{h(!1),s("/mission-control/integrations")},children:[e.jsx(Sr,{className:"h-3 w-3"}),"Connect"]})]}),!t&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Smart Drips sends emails from your Gmail account. Connect Gmail to get started."})]}),e.jsx(hc,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`p-2 rounded-full ${l?"bg-emerald-500/10":"bg-muted"}`,children:e.jsx(aQ,{className:`h-4 w-4 ${l?"text-emerald-600":"text-muted-foreground"}`})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Enable Smart Drips"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l?"Active drips will send when deals move stages":"All drips are paused — nothing will send"})]})]}),e.jsx(wn,{checked:l,onCheckedChange:m,disabled:a||i.isPending})]}),e.jsx(hc,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`p-2 rounded-full ${c?"bg-primary/10":"bg-muted"}`,children:e.jsx(C2,{className:`h-4 w-4 ${c?"text-primary":"text-muted-foreground"}`})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Append Email Signature"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:c?"Your signature from Profile settings will be added":"Drip emails will send without a signature"})]})]}),e.jsx(wn,{checked:c,onCheckedChange:p,disabled:a||i.isPending})]}),c&&e.jsxs(U,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>{h(!1),s("/profile")},children:[e.jsx(C2,{className:"h-3 w-3 mr-1"}),"Edit your email signature in Profile settings"]})]})]})]})}function psr(){const s=Sa();return ct({queryKey:["drip-templates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_templates").select("*").or(`owner_user_id.eq.${s},is_starter.eq.true`).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function fsr(){const s=Sa();return ct({queryKey:["drip-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 gsr(){const s=Sa(),t=Qt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("drip_templates").insert({owner_user_id:s,stage_id:n.stage_id,title:n.title||"",subject:n.subject||"",body:n.body||"",video_url:n.video_url||null,channel:n.channel||"email",delay_type:n.delay_type||"instant",delay_minutes:n.delay_minutes||0,is_enabled:!1,deal_type:n.deal_type||null,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-templates"]})}})}function xsr(){const s=Qt();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("drip_templates").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function ysr(){const s=Qt();return yt({mutationFn:async t=>{const{error:n}=await q.from("drip_templates").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function vsr(){const s=Sa(),t=Qt();return yt({mutationFn:async({templateId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await q.from("drip_templates").select("*").eq("id",n).single();if(i)throw i;const{data:l,error:o}=await q.from("drip_templates").insert({owner_user_id:s,stage_id:r,title:a.title,subject:a.subject,body:a.body,video_url:a.video_url,channel:a.channel,delay_type:a.delay_type,delay_minutes:a.delay_minutes,is_enabled:!1,is_starter:!1,deal_type:a.deal_type}).select().single();if(o)throw o;return l},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-templates"]})}})}const bsr=[{key:"{{client_first_name}}",label:"Client First Name"},{key:"{{client_last_name}}",label:"Client Last Name"},{key:"{{property_address}}",label:"Property Address"},{key:"{{agent_name}}",label:"Your Name"},{key:"{{agent_phone}}",label:"Your Phone"},{key:"{{close_date}}",label:"Target Close Date"},{key:"{{stage_name}}",label:"Current Stage"},{key:"{{portal_link}}",label:"Portal Link"},{key:"{{review_link}}",label:"Review Link"}],Nze=1e3;function Sss({open:s,onOpenChange:t,campaignId:n,campaignName:r,birthdayFocused:a,onSuccess:i}){const l=Sa(),o=Qtt(),[c,d]=j.useState(""),[u,h]=j.useState(!!a),[m,p]=j.useState(new Set),{data:f,isLoading:x}=ct({queryKey:["campaign-contact-picker",l],queryFn:async()=>{const M=[];for(let I=0;;I+=Nze){const{data:R,error:z}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, birthday").eq("owner_user_id",l).order("first_name").range(I,I+Nze-1);if(z)throw z;if(M.push(...R||[]),!R||R.length{const{data:M,error:I}=await q.from("drip_campaign_enrollments").select("contact_id, status").eq("campaign_id",n);if(I)throw I;return new Set((M||[]).filter(R=>R.status==="active"||R.status==="paused").map(R=>R.contact_id))},enabled:s&&!!n}),v=j.useMemo(()=>{const M=c.trim().toLowerCase();return(f||[]).filter(I=>u&&!I.birthday?!1:M?`${I.first_name||""} ${I.last_name||""}`.toLowerCase().includes(M)||(I.email||"").toLowerCase().includes(M):!0)},[f,c,u]),b=v.filter(M=>!(y!=null&&y.has(M.id))).map(M=>M.id),N=b.length>0&&b.every(M=>m.has(M)),S=M=>{p(I=>{const R=new Set(I);return R.has(M)?R.delete(M):R.add(M),R})},A=()=>{p(M=>{if(N){const I=new Set(M);return b.forEach(R=>I.delete(R)),I}return new Set([...M,...b])})},T=async()=>{if(!(!n||m.size===0))try{const M=await o.mutateAsync({campaignId:n,contactIds:Array.from(m)}),I=[`${M.enrolled} enrolled`];M.skipped>0&&I.push(`${M.skipped} already in`),M.errors>0&&I.push(`${M.errors} errors`),re.success(I.join(" · ")),p(new Set),t(!1),i==null||i()}catch(M){re.error(M.message||"Failed to add contacts")}},L=(f||[]).filter(M=>M.birthday).length;return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-lg max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[e.jsxs(Vs,{className:"p-5 pb-3 border-b shrink-0 text-left",children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4 text-primary"}),"Add contacts — ",r||"Campaign"]}),e.jsxs(Pr,{className:"text-xs",children:["Pick the people you want in this campaign. Contacts already enrolled are greyed out.",a&&" Birthday emails send automatically on each person's birthday once they're in."]})]}),e.jsxs("div",{className:"px-5 pt-3 space-y-2 shrink-0",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(xe,{placeholder:"Search contacts by name or email...",value:c,onChange:M=>d(M.target.value),className:"pl-9 h-9"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground cursor-pointer",children:[e.jsx(xi,{checked:u,onCheckedChange:M=>h(!!M)}),e.jsx(lg,{className:"h-3.5 w-3.5 text-primary"}),"Only contacts with a birthday on file (",L,")"]}),e.jsx(U,{variant:"ghost",size:"sm",className:"text-xs h-7",onClick:A,disabled:b.length===0,children:N?"Clear all":`Select all ${b.length}`})]})]}),e.jsx("div",{className:"flex-1 min-h-0 px-5 py-3",children:e.jsx(Gi,{className:"h-[320px] -mx-1 px-1",children:x?e.jsx("div",{className:"text-center py-10 text-sm text-muted-foreground",children:"Loading contacts..."}):v.length===0?e.jsx("div",{className:"text-center py-10 text-sm text-muted-foreground",children:u?"No contacts have a birthday saved yet. Add birthdays on a contact record first.":"No contacts match your search."}):e.jsx("div",{className:"space-y-1",children:v.map(M=>{const I=y==null?void 0:y.has(M.id);return e.jsxs("label",{className:`flex items-center gap-3 p-2.5 rounded-lg border transition-colors ${I?"opacity-50 border-transparent":m.has(M.id)?"border-primary bg-primary/5 cursor-pointer":"border-border hover:bg-muted/40 cursor-pointer"}`,children:[e.jsx(xi,{checked:I?!0:m.has(M.id),disabled:I,onCheckedChange:()=>S(M.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:[M.first_name,M.last_name].filter(Boolean).join(" ")||"Unnamed contact"}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground",children:[M.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(ln,{className:"h-2.5 w-2.5"}),M.email]}),M.birthday&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(lg,{className:"h-2.5 w-2.5"}),M.birthday]})]})]}),I&&e.jsx(Be,{variant:"outline",className:"text-[9px]",children:"In campaign"})]},M.id)})})})}),e.jsxs(Mr,{className:"p-4 border-t shrink-0 gap-2 sm:gap-2",children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{onClick:T,disabled:m.size===0||o.isPending,children:[o.isPending&&e.jsx(Et,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Add ",m.size||""," contact",m.size===1?"":"s"]})]})]})})}function _sr({open:s,onOpenChange:t,campaignId:n,campaignName:r}){const{data:a,isLoading:i}=yIn(n||void 0),l=bIn(),o=Qtt(),[c,d]=j.useState(!1),u=async(p,f)=>{try{await l.mutateAsync({id:p,status:f}),re.success(`Enrollment ${f}`)}catch{re.error("Failed to update")}},h=async p=>{if(n)try{const f=await o.mutateAsync({campaignId:n,contactIds:[p]});f.enrolled>0?re.success("Contact re-enrolled — first email queued"):f.skipped>0?re.message("Already active in this campaign"):re.error("Could not re-enroll")}catch{re.error("Failed to re-enroll")}},m=p=>{const f={active:"bg-emerald-500/10 text-emerald-600 border-emerald-200",paused:"bg-amber-500/10 text-amber-600 border-amber-200",completed:"bg-blue-500/10 text-blue-600 border-blue-200",exited:"bg-muted text-muted-foreground"};return e.jsx(Be,{variant:"outline",className:`text-[10px] capitalize ${f[p]||""}`,children:p})};return e.jsxs(zs,{open:s,onOpenChange:t,children:[e.jsxs(Ds,{className:"max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[e.jsxs("div",{className:"p-5 border-b shrink-0",children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4 text-primary"}),"Enrollments — ",r||"Campaign"]}),e.jsx(Pr,{className:"text-xs mt-1",children:"Manage every contact currently in this campaign. Pause to take over, or exit to remove."}),e.jsx("div",{className:"mt-3",children:e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>d(!0),children:[e.jsx(zl,{className:"h-3.5 w-3.5 mr-1.5"})," Add contacts"]})})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsx("div",{className:"p-5",children:i?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(p=>e.jsx(xn,{className:"h-14"},p))}):!a||a.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Bn,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No contacts enrolled yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Add the contacts you want in this campaign — they'll start receiving it automatically."}),e.jsxs(U,{size:"sm",onClick:()=>d(!0),children:[e.jsx(zl,{className:"h-3.5 w-3.5 mr-1.5"})," Add contacts"]})]}):e.jsx("div",{className:"space-y-2",children:a.map(p=>{var f,x,y,v;return e.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg bg-card",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(f=p.contact)==null?void 0:f.first_name," ",(x=p.contact)==null?void 0:x.last_name]}),m(p.status)]}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-0.5",children:[((y=p.contact)==null?void 0:y.email)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ln,{className:"h-2.5 w-2.5"})," ",p.contact.email]}),e.jsxs("span",{children:["Step ",p.current_step]}),p.next_send_at&&p.status==="active"&&e.jsxs("span",{children:["Next: ",Gs(new Date(p.next_send_at),"MMM d, h:mma")]}),p.exit_reason&&e.jsxs("span",{children:["Exit: ",p.exit_reason]})]})]}),p.status==="active"&&e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>u(p.id,"paused"),title:"Pause",children:e.jsx(uv,{className:"h-3.5 w-3.5"})}),p.status==="paused"&&e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>u(p.id,"active"),title:"Resume",children:e.jsx(lu,{className:"h-3.5 w-3.5"})}),(p.status==="active"||p.status==="paused")&&e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>u(p.id,"exited"),title:"Exit",children:e.jsx(er,{className:"h-3.5 w-3.5 text-destructive"})}),(p.status==="exited"||p.status==="completed")&&((v=p.contact)==null?void 0:v.id)&&e.jsxs(U,{size:"sm",variant:"outline",className:"h-7 text-[11px] gap-1",onClick:()=>h(p.contact.id),disabled:o.isPending,children:[e.jsx(Kg,{className:"h-3 w-3"}),"Re-enroll"]})]},p.id)})})})})]}),e.jsx(Sss,{open:c,onOpenChange:d,campaignId:n,campaignName:r,birthdayFocused:/birthday/i.test(r||"")})]})}function wsr(){var A,T,L;const{data:s,isLoading:t}=Fre(),{hasLeadSite:n}=$p(),r=Xtt(),a=pIn(),i=tWt(),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,p]=j.useState(null),[f,x]=j.useState(null),y=(s||[]).filter(M=>!M.is_starter),v=(s||[]).filter(M=>M.is_starter).filter(M=>!M.requires_lead_site||n),b=async M=>{try{await r.mutateAsync(M),re.success("Campaign added to your library — customize and activate it!"),o(null)}catch(I){re.error(I.message||"Failed to copy campaign")}},N=async M=>{try{await i.mutateAsync({id:M.id,is_active:!M.is_active}),re.success(M.is_active?"Campaign paused":"Campaign activated")}catch{re.error("Failed to update")}},S=async M=>{if(await Yi("Delete this campaign? Active enrollments will be removed."))try{await a.mutateAsync(M),re.success("Campaign deleted")}catch{re.error("Failed to delete")}};return t?e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3,4,5,6].map(M=>e.jsx(xn,{className:"h-44 rounded-xl"},M))}):e.jsxs("div",{className:"space-y-8",children:[e.jsx("div",{className:"rounded-xl border bg-gradient-to-br from-primary/5 via-background to-background p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(Jk,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"How Smart Drips work"}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3 mt-2",children:[e.jsxs("div",{className:"flex gap-2 text-xs",children:[e.jsx(Gu,{className:"h-3.5 w-3.5 text-amber-500 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:"Stage Drips (automatic)"}),e.jsx("p",{className:"text-muted-foreground",children:"Trigger when a contact moves to a deal stage (Listing, Under Contract, etc)."})]})]}),e.jsxs("div",{className:"flex gap-2 text-xs",children:[e.jsx($r,{className:"h-3.5 w-3.5 text-primary shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:"Campaigns (manual / bulk)"}),e.jsxs("p",{className:"text-muted-foreground",children:["Click ",e.jsx("strong",{children:"Add contacts"})," on any campaign card, pick the people you want, and they start receiving it. (You can also select contacts in your Contacts list and choose “Enroll in Campaign”.)"]})]})]})]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-2.5 italic",children:["Tip: A campaign must be ",e.jsx("strong",{children:"Active"})," before its emails will send to enrolled contacts."]})]})]})}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4 text-primary"}),"My Campaigns"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Custom drip campaigns you've created or copied"})]}),e.jsxs(U,{size:"sm",onClick:()=>{h(null),d(!0)},children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1.5"})," New Campaign"]})]}),y.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl bg-muted/20",children:[e.jsx(cn,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold mb-1",children:"No custom campaigns yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Build one from scratch or clone a starter from the library below."}),e.jsxs(U,{size:"sm",onClick:()=>{h(null),d(!0)},children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1.5"})," Create your first campaign"]})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:y.map(M=>e.jsx(jsr,{campaign:M,onPreview:()=>o(M.id),onToggleActive:()=>N(M),onDelete:()=>S(M.id),onEdit:()=>{h(M.id),d(!0)},onViewEnrollments:()=>p(M.id),onAddContacts:()=>x(M.id)},M.id))})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(cn,{className:"h-4 w-4 text-amber-500"}),"Starter Library"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Premium, ready-to-go campaigns crafted for real estate. One-click copy."})]}),e.jsxs(Be,{variant:"outline",className:"text-[10px]",children:[v.length," templates"]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:v.map(M=>e.jsx(Nsr,{campaign:M,onPreview:()=>o(M.id)},M.id))})]}),e.jsx(Sss,{open:!!f,onOpenChange:M=>!M&&x(null),campaignId:f,campaignName:(A=y.find(M=>M.id===f))==null?void 0:A.name,birthdayFocused:/birthday/i.test(((T=y.find(M=>M.id===f))==null?void 0:T.name)||"")}),e.jsx(ksr,{campaignId:l,open:!!l,onOpenChange:M=>!M&&o(null),onClone:b,isCloning:r.isPending,onEdit:M=>{o(null),h(M),d(!0)}}),e.jsx(aWt,{open:c,onOpenChange:d,campaignId:u}),e.jsx(_sr,{open:!!m,onOpenChange:M=>!M&&p(null),campaignId:m,campaignName:(L=y.find(M=>M.id===m))==null?void 0:L.name})]})}function jsr({campaign:s,onPreview:t,onToggleActive:n,onDelete:r,onEdit:a,onViewEnrollments:i,onAddContacts:l}){const c=vIn(s.id).data??0,d=!s.is_active&&c>0;return e.jsxs("div",{className:"group rounded-xl border bg-card overflow-hidden hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:`h-20 bg-gradient-to-br ${s.cover_color} relative flex items-center justify-center`,children:[e.jsx("span",{className:"text-4xl drop-shadow-sm",children:s.icon}),s.is_active&&e.jsx(Be,{className:"absolute top-2 right-2 bg-emerald-500 hover:bg-emerald-500 text-white text-[10px]",children:"Active"})]}),e.jsxs("div",{className:"p-3.5",children:[e.jsx("h3",{className:"font-semibold text-sm truncate",children:s.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1 min-h-[2rem]",children:s.description||"No description"}),e.jsx(Be,{variant:"outline",className:"text-[9px] mt-2",children:$Le[s.category]}),d&&e.jsxs("button",{onClick:n,className:"mt-2 w-full flex items-start gap-1.5 p-2 rounded-md bg-amber-500/10 border border-amber-500/30 text-left hover:bg-amber-500/15 transition-colors",children:[e.jsx(tc,{className:"h-3 w-3 text-amber-600 dark:text-amber-400 shrink-0 mt-0.5"}),e.jsxs("span",{className:"text-[10px] leading-tight text-amber-700 dark:text-amber-300",children:[e.jsxs("strong",{children:[c," contact",c===1?"":"s"," enrolled"]})," but not sending — tap to activate"]})]}),e.jsxs(U,{size:"sm",className:"w-full h-8 text-xs mt-3",onClick:l,children:[e.jsx(zl,{className:"h-3.5 w-3.5 mr-1.5"})," Add contacts"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-1.5 mt-1.5",children:[e.jsxs(U,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:a,children:[e.jsx(ri,{className:"h-3 w-3 mr-1"})," Edit"]}),e.jsx(U,{size:"sm",variant:s.is_active?"secondary":"default",className:"h-7 text-xs",onClick:n,children:s.is_active?"Pause":"Activate"})]}),e.jsxs("div",{className:"flex items-center justify-between mt-2 text-[10px]",children:[e.jsx("button",{onClick:i,className:"text-primary hover:underline",children:"View enrollments"}),e.jsx("button",{onClick:t,className:"text-muted-foreground hover:underline",children:"Preview"}),e.jsx("button",{onClick:r,className:"text-muted-foreground hover:text-destructive",children:"Delete"})]})]})]})}function Nsr({campaign:s,onPreview:t}){return e.jsxs("button",{onClick:t,className:"group rounded-xl border bg-card overflow-hidden hover:shadow-xl hover:scale-[1.02] transition-all text-left",children:[e.jsxs("div",{className:`h-24 bg-gradient-to-br ${s.cover_color} relative flex items-center justify-center`,children:[e.jsx("span",{className:"text-5xl drop-shadow-sm",children:s.icon}),e.jsxs(Be,{className:"absolute top-2 right-2 bg-white/90 text-foreground hover:bg-white text-[10px]",children:[e.jsx(cn,{className:"h-2.5 w-2.5 mr-0.5"})," Starter"]})]}),e.jsxs("div",{className:"p-3.5",children:[e.jsx("h3",{className:"font-semibold text-sm",children:s.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1 min-h-[2rem]",children:s.description}),e.jsx(Be,{variant:"outline",className:"text-[9px] mt-2",children:$Le[s.category]})]})]})}function ksr({campaignId:s,open:t,onOpenChange:n,onClone:r,isCloning:a,onEdit:i}){const{data:l}=Fre(),{data:o}=sWt(s||void 0),[c,d]=j.useState(new Set),u=l==null?void 0:l.find(p=>p.id===s);if(!u)return null;const h=p=>{d(f=>{const x=new Set(f);return x.has(p)?x.delete(p):x.add(p),x})},m=(p,f)=>{if(p.delay_type==="calendar_anchor"){const y=p.anchor_field==="birthday"?"birthday":"home anniversary",v=p.anchor_offset_days||0;return v===0?`On their ${y}`:v<0?`${Math.abs(v)} days before ${y}`:`${v} days after ${y}`}if(f===0&&p.delay_days===0&&p.delay_hours===0)return"Sends immediately";const x=[];return p.delay_days&&x.push(`${p.delay_days}d`),p.delay_hours&&x.push(`${p.delay_hours}h`),f===0?`After ${x.join(" ")}`:`+${x.join(" ")}`};return e.jsx(zs,{open:t,onOpenChange:n,children:e.jsxs(Ds,{className:"max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[e.jsx("div",{className:`bg-gradient-to-br ${u.cover_color} p-6 text-white shrink-0`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("span",{className:"text-5xl drop-shadow-sm",children:u.icon}),e.jsxs("div",{className:"flex-1",children:[e.jsx($s,{className:"text-xl font-bold text-white",children:u.name}),e.jsx(Pr,{className:"text-white/90 mt-1",children:u.description}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx(Be,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:$Le[u.category]}),e.jsxs(Be,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:[(o==null?void 0:o.length)||0," step",(o==null?void 0:o.length)!==1?"s":""]})]})]})]})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsxs("div",{className:"p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"The sequence"}),u.is_starter?e.jsx("span",{className:"text-[10px] text-muted-foreground italic",children:"Copy to your library to edit"}):e.jsx("span",{className:"text-[10px] text-muted-foreground italic",children:"Tap a step to expand · Edit to customize"})]}),o==null?void 0:o.map((p,f)=>{const x=c.has(p.id);return e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"shrink-0 flex flex-col items-center",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xs font-semibold",children:f+1}),fh(p.id),className:"flex-1 pb-4 text-left",children:e.jsxs("div",{className:"border rounded-lg p-3 bg-muted/20 hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5 text-xs text-muted-foreground",children:[p.delay_type==="calendar_anchor"?e.jsx(pa,{className:"h-3 w-3"}):e.jsx(Yr,{className:"h-3 w-3"}),e.jsx("span",{children:m(p,f)}),e.jsx("span",{children:"·"}),e.jsx(ln,{className:"h-3 w-3"}),e.jsx("span",{className:"capitalize",children:p.channel})]}),e.jsx("p",{className:"font-medium text-sm",children:p.subject}),(()=>{const y=p.body||"",v=/<\/?[a-z][\s\S]*>/i.test(y),b=v?y.replace(//gi,"").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\s+/g," ").trim():y;return x?v?e.jsx("div",{className:"text-xs text-foreground mt-2 prose prose-sm max-w-none [&_a]:text-primary",dangerouslySetInnerHTML:{__html:y}}):e.jsx("p",{className:"text-xs text-muted-foreground mt-2 whitespace-pre-line",children:y}):e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:b})})(),p.body&&p.body.length>160&&e.jsx("span",{className:"text-[10px] text-primary mt-1.5 inline-block",children:x?"Show less":"Show full email"})]})})]},p.id)})]})}),e.jsxs(Mr,{className:"border-t p-4 shrink-0",children:[e.jsx(U,{variant:"outline",onClick:()=>n(!1),children:"Close"}),!u.is_starter&&i&&e.jsxs(U,{variant:"secondary",onClick:()=>i(u.id),children:[e.jsx(ri,{className:"h-3.5 w-3.5 mr-1.5"})," Edit Campaign"]}),u.is_starter&&e.jsxs(U,{onClick:()=>r(u.id),disabled:a,children:[a?e.jsx(Et,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1.5"}),"Copy to my campaigns"]})]})]})})}const e3e=[{value:"birthday",label:"Birthday",description:"Celebrate your contact's birthday",column:"birthday",emoji:"🎂"},{value:"home_anniversary",label:"Home Anniversary",description:"The date they closed on their home",column:"home_anniversary",emoji:"🏡"},{value:"spouse_birthday",label:"Spouse's Birthday",description:"Remember their partner's day too",column:"spouse_birthday",emoji:"💐"},{value:"wedding_anniversary",label:"Wedding Anniversary",description:"A thoughtful touch couples remember",column:"wedding_anniversary",emoji:"💍"}];function Ssr(){const s=Sa();return ct({queryKey:["drip-auto-rules",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_auto_enroll_rules").select("*, campaign:drip_campaigns(id, name, category, cover_color)").eq("owner_user_id",s).order("created_at",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function Csr(){const s=Sa(),t=Qt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r={owner_user_id:s,campaign_id:n.campaign_id,trigger_type:n.trigger_type,lead_days:n.lead_days??14,filter_tags:n.filter_tags??[],filter_relationship_types:n.filter_relationship_types??[],require_email:n.require_email??!0,is_active:n.is_active??!0};n.id&&(r.id=n.id);const{data:a,error:i}=await q.from("drip_auto_enroll_rules").upsert(r).select().single();if(i)throw i;return a},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-auto-rules"]})}})}function Asr(){const s=Qt();return yt({mutationFn:async({id:t,is_active:n})=>{const{error:r}=await q.from("drip_auto_enroll_rules").update({is_active:n}).eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["drip-auto-rules"]})})}function Esr(){const s=Qt();return yt({mutationFn:async t=>{const{error:n}=await q.from("drip_auto_enroll_rules").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["drip-auto-rules"]})})}function Tsr(s=25){const t=Sa();return ct({queryKey:["drip-auto-log",t,s],queryFn:async()=>{if(!t)return[];const{data:n,error:r}=await q.from("drip_auto_enroll_log").select("*, contact:innercircle_contacts(id, first_name, last_name, email)").eq("owner_user_id",t).order("created_at",{ascending:!1}).limit(s);if(r)throw r;return n||[]},enabled:!!t})}function Msr(){const s=Sa();return ct({queryKey:["life-event-coverage",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("innercircle_contacts").select("birthday, home_anniversary, spouse_birthday, wedding_anniversary, email").eq("owner_user_id",s).limit(1e4);if(n)throw n;const r=t||[],a=(l,o)=>{if(!l)return!1;const[,c,d]=String(l).split("-").map(Number),u=new Date;let h=new Date(u.getFullYear(),c-1,d);return h{const o=r.filter(c=>!!c[l.column]);i[l.value]={total:o.length,upcoming30:o.filter(c=>a(c[l.column],30)).length}}),{totalContacts:r.length,counts:i}},enabled:!!s})}function Psr(){const s=Qt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.functions.invoke("process-life-event-drips",{body:t?{rule_id:t}:{}});if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-auto-rules"]}),s.invalidateQueries({queryKey:["drip-auto-log"]}),s.invalidateQueries({queryKey:["drip-campaign-enrollments"]})}})}const Lsr={birthday:lg,home_anniversary:Xk,spouse_birthday:Ro,wedding_anniversary:ko};function Isr(){var S;const{data:s,isLoading:t}=Ssr(),{data:n}=Fre(),{data:r}=Msr(),{data:a}=Tsr(10),i=Csr(),l=Asr(),o=Esr(),c=Psr(),d=Xtt(),[u,h]=j.useState(null),m=j.useMemo(()=>(n||[]).filter(A=>!A.is_starter),[n]),p={birthday:"Birthday",home_anniversary:"Home Anniversary",spouse_birthday:"Spouse Birthday",wedding_anniversary:"Wedding Anniversary"},f=j.useMemo(()=>{if(!(u!=null&&u.trigger_type))return null;const A=p[u.trigger_type];return!A||m.some(L=>String(L.name||"").toLowerCase().includes(A.toLowerCase()))?null:(n||[]).find(L=>L.is_starter&&String(L.name||"").toLowerCase()===A.toLowerCase())??null},[n,m,u==null?void 0:u.trigger_type]),x=async()=>{if(f)try{const A=await d.mutateAsync(f.id);h(T=>({...T,campaign_id:A.id})),re.success(`“${f.name}” template added to your campaigns`)}catch(A){re.error((A==null?void 0:A.message)||"Could not copy the template")}},y=A=>(s||[]).find(T=>T.trigger_type===A),v=async()=>{if(!(u!=null&&u.campaign_id)||!(u!=null&&u.trigger_type)){re.error("Pick a campaign first");return}try{await i.mutateAsync(u),re.success("Autopilot rule saved"),h(null)}catch(A){re.error((A==null?void 0:A.message)||"Could not save rule")}},b=async()=>{try{const A=await c.mutateAsync(void 0);re.success(A!=null&&A.enrolled?`Enrolled ${A.enrolled} contact${A.enrolled===1?"":"s"} with upcoming life events`:"All caught up — nobody new to enroll right now")}catch(A){re.error((A==null?void 0:A.message)||"Autopilot run failed")}},N=(s||[]).filter(A=>A.is_active).length;return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"rounded-2xl border bg-gradient-to-br from-primary/10 via-card to-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:"flex items-start gap-3",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-primary/15 flex items-center justify-center shrink-0",children:e.jsx(cn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-bold leading-tight",children:"Life Event Autopilot"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-xl",children:"Every morning we scan your database for upcoming birthdays and anniversaries and quietly enroll those contacts in the campaign you choose. You never miss a moment again."})]})]}),e.jsxs(U,{variant:"outline",onClick:b,disabled:c.isPending||N===0,className:"gap-2 shrink-0",children:[c.isPending?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(no,{className:"h-4 w-4"}),"Run now"]})]}),r&&e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2 mt-4",children:e3e.map(A=>{const T=r.counts[A.value];return e.jsxs("div",{className:"rounded-xl bg-background/70 border px-3 py-2",children:[e.jsxs("p",{className:"text-[11px] text-muted-foreground truncate",children:[A.emoji," ",A.label]}),e.jsx("p",{className:"text-lg font-bold leading-tight",children:(T==null?void 0:T.total)??0}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[(T==null?void 0:T.upcoming30)??0," in next 30 days"]})]},A.value)})})]}),t?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(Et,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:e3e.map(A=>{var I;const T=y(A.value),L=Lsr[A.value]||lg,M=r==null?void 0:r.counts[A.value];return e.jsxs("div",{className:Mt("rounded-xl border bg-card p-4 transition-colors",(T==null?void 0:T.is_active)&&"border-primary/40 bg-primary/[0.03]"),children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Mt("h-10 w-10 rounded-lg flex items-center justify-center shrink-0",T!=null&&T.is_active?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(L,{className:"h-5 w-5"})}),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-semibold text-sm",children:A.label}),(T==null?void 0:T.is_active)&&e.jsx(Be,{className:"text-[10px] bg-primary/10 text-primary hover:bg-primary/10",children:"On"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:T?`${((I=T.campaign)==null?void 0:I.name)??"Campaign"} · starts ${T.lead_days} days before`:A.description}),T&&T.total_enrolled>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1",children:[T.total_enrolled," contact",T.total_enrolled===1?"":"s"," enrolled so far"]}),!T&&((M==null?void 0:M.total)??0)===0&&e.jsx("p",{className:"text-[11px] text-amber-600 dark:text-amber-400 mt-1",children:"No contacts have this date on file yet."})]}),T?e.jsx(wn,{checked:T.is_active,onCheckedChange:R=>l.mutate({id:T.id,is_active:R})}):null]}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(U,{size:"sm",variant:T?"outline":"default",className:"flex-1 gap-1.5",onClick:()=>h(T??{trigger_type:A.value,lead_days:A.value==="birthday"?7:14,require_email:!0,is_active:!0,filter_tags:[],filter_relationship_types:[]}),children:[T?e.jsx(Af,{className:"h-3.5 w-3.5"}):e.jsx(an,{className:"h-3.5 w-3.5"}),T?"Edit rule":"Turn on autopilot"]}),T&&e.jsx(U,{size:"sm",variant:"ghost",className:"text-muted-foreground hover:text-destructive",onClick:()=>o.mutate(T.id),children:e.jsx(In,{className:"h-3.5 w-3.5"})})]})]},A.value)})}),((a==null?void 0:a.length)??0)>0&&e.jsxs("div",{className:"rounded-xl border bg-card",children:[e.jsxs("div",{className:"px-4 py-3 border-b",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Recently auto-enrolled"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Proof your autopilot is running while you sleep."})]}),e.jsx("div",{className:"divide-y",children:(a||[]).map(A=>{var T,L;return e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5",children:[e.jsx(Xr,{className:"h-4 w-4 text-emerald-500 shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[(T=A.contact)==null?void 0:T.first_name," ",(L=A.contact)==null?void 0:L.last_name]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[String(A.trigger_type).replace(/_/g," ")," · ",A.note]})]}),e.jsx("span",{className:"text-[11px] text-muted-foreground shrink-0",children:new Date(A.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})})]},A.id)})})]}),e.jsx(zs,{open:!!u,onOpenChange:A=>!A&&h(null),children:e.jsxs(Ds,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{children:[(S=e3e.find(A=>A.value===(u==null?void 0:u.trigger_type)))==null?void 0:S.label," autopilot"]}),e.jsx(Pr,{children:"Choose the campaign to run and how far ahead it should start."})]}),e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Campaign to enroll into"}),e.jsxs(Ns,{value:(u==null?void 0:u.campaign_id)??"",onValueChange:A=>h(T=>({...T,campaign_id:A})),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select one of your campaigns"})}),e.jsx(js,{children:m.map(A=>e.jsx(et,{value:A.id,children:A.name},A.id))})]}),f&&e.jsx("div",{className:"rounded-lg border border-primary/25 bg-primary/5 p-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(cn,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium leading-tight",children:["Use the LevelUp “",f.name,"” template"]}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:"Beautifully designed, personalized emails written for this moment. We'll copy it into your campaigns so you can edit anything you like."}),e.jsxs(U,{size:"sm",variant:"outline",className:"mt-2 gap-1.5",disabled:d.isPending,onClick:x,children:[d.isPending?e.jsx(Et,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(an,{className:"h-3.5 w-3.5"}),"Use this template"]})]})]})}),m.length===0&&!f&&e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:"You need one of your own campaigns first — clone a starter from the Campaigns tab."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{children:"Start this many days before the event"}),e.jsxs("span",{className:"text-sm font-semibold tabular-nums",children:[(u==null?void 0:u.lead_days)??14,"d"]})]}),e.jsx(rg,{min:0,max:45,step:1,value:[(u==null?void 0:u.lead_days)??14],onValueChange:([A])=>h(T=>({...T,lead_days:A}))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Gives your campaign time to warm up before the big day."})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-sm",children:"Only contacts with an email"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Skip records that can't be reached."})]}),e.jsx(wn,{checked:(u==null?void 0:u.require_email)??!0,onCheckedChange:A=>h(T=>({...T,require_email:A}))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-sm",children:"Autopilot active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Runs every morning automatically."})]}),e.jsx(wn,{checked:(u==null?void 0:u.is_active)??!0,onCheckedChange:A=>h(T=>({...T,is_active:A}))})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"ghost",onClick:()=>h(null),children:"Cancel"}),e.jsxs(U,{onClick:v,disabled:i.isPending||!(u!=null&&u.campaign_id),children:[i.isPending&&e.jsx(Et,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save rule"]})]})]})})]})}function Rsr(){const s=Sa(),t=Wn(),{isGmailConnected:n,gmailEmail:r,isLoading:a}=Ax(),{data:i,isLoading:l}=psr(),{data:o,isLoading:c}=fsr(),d=gsr(),u=xsr(),h=ysr(),m=vsr(),[p,f]=j.useState(null),[x,y]=j.useState(null),v=(i==null?void 0:i.filter(I=>!I.is_starter&&I.owner_user_id===s))||[],b=(i==null?void 0:i.filter(I=>I.is_starter))||[],N=I=>v.filter(R=>R.stage_id===I),S=async I=>{try{await u.mutateAsync({id:I.id,is_enabled:!I.is_enabled}),re.success(I.is_enabled?"Drip disabled":"Drip enabled")}catch{re.error("Failed to update")}},A=async I=>{try{const R=o==null?void 0:o.find(z=>z.id===I);await d.mutateAsync({stage_id:I,title:`${(R==null?void 0:R.name)||"Stage"} follow-up`,subject:"",body:"",channel:"email",delay_type:"instant",delay_minutes:0}),f(I),re.success("Drip template created")}catch{re.error("Failed to create template")}},T=async I=>{try{await h.mutateAsync(I),re.success("Template deleted")}catch{re.error("Failed to delete")}},L=async I=>{if(!o||o.length===0){re.error("No pipeline stages found");return}const R=o[0].id;try{await m.mutateAsync({templateId:I,stageId:R}),re.success("Template copied to your drips!")}catch{re.error("Failed to copy template")}},M=l||c;return e.jsx(qs,{children:e.jsxs("div",{className:"container max-w-4xl mx-auto py-6 px-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Af,{className:"h-5 w-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"Smart Drips"}),e.jsx(Be,{variant:"outline",className:"text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 border-amber-500 text-amber-600 bg-amber-500/10",children:"Beta"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Automatically send personalized emails when deals move through your pipeline."})]}),e.jsx(msr,{})]}),e.jsxs("div",{className:"bg-primary/5 border border-primary/15 rounded-xl p-4 mb-4 flex items-start gap-3",children:[e.jsx(Jk,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("p",{className:"font-medium text-foreground mb-1",children:"How it works"}),e.jsxs("p",{children:["When a deal moves to a new stage in your pipeline, Smart Drips automatically sends your pre-written email to the client. Nothing sends until you create a template ",e.jsx("strong",{children:"and"})," toggle it on."]})]})]}),!a&&(n?e.jsxs("div",{className:"bg-emerald-500/5 border border-emerald-500/20 rounded-xl p-4 mb-6 flex items-start gap-3",children:[e.jsx(ln,{className:"h-4 w-4 text-emerald-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm flex-1",children:[e.jsxs("p",{className:"font-medium text-foreground mb-0.5",children:["Sending from your Gmail",r?` (${r})`:""]}),e.jsx("p",{className:"text-muted-foreground",children:"Drips will send directly from your connected Gmail for the most personal feel and best deliverability."})]})]}):e.jsxs("div",{className:"bg-amber-500/5 border border-amber-500/20 rounded-xl p-4 mb-6 flex items-start gap-3",children:[e.jsx(Jk,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm flex-1",children:[e.jsx("p",{className:"font-medium text-foreground mb-0.5",children:"Drips will send from our shared sender"}),e.jsxs("p",{className:"text-muted-foreground mb-2",children:["You haven't connected Gmail, so drips will send from ",e.jsx("strong",{children:"send.relevelup.com"})," with your name on the From line and your email as Reply-To. Connect Gmail to send directly from your own inbox for better deliverability and a more personal touch."]}),e.jsxs(U,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>t("/mission-control/integrations"),children:[e.jsx(ln,{className:"h-3 w-3 mr-1.5"}),"Connect Gmail"]})]})]})),e.jsxs(oa,{defaultValue:"my-drips",children:[e.jsxs(la,{className:"grid grid-cols-4 w-full max-w-2xl mb-6",children:[e.jsx(Kt,{value:"my-drips",children:"Stage Drips"}),e.jsxs(Kt,{value:"campaigns",children:["Campaigns",e.jsx(Be,{variant:"outline",className:"ml-1.5 text-[9px] bg-amber-500/10 text-amber-600 border-amber-200 px-1 py-0",children:"New"})]}),e.jsxs(Kt,{value:"autopilot",children:["Life Events",e.jsx(Be,{variant:"outline",className:"ml-1.5 text-[9px] bg-primary/10 text-primary border-primary/20 px-1 py-0",children:"Auto"})]}),e.jsxs(Kt,{value:"starters",children:["Stage Starters",b.length>0&&e.jsx(Be,{variant:"secondary",className:"ml-1.5 text-[10px] px-1.5 py-0",children:b.length})]})]}),e.jsx(Zt,{value:"campaigns",children:e.jsx(wsr,{})}),e.jsx(Zt,{value:"autopilot",children:e.jsx(Isr,{})}),e.jsx(Zt,{value:"my-drips",children:M?e.jsx("div",{className:"space-y-3",children:[1,2,3,4].map(I=>e.jsx(xn,{className:"h-16 w-full rounded-xl"},I))}):!o||o.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(Af,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"No Pipeline Stages"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create pipeline stages first to set up drip automations."})]}):e.jsxs("div",{className:"space-y-2",children:[o.filter(I=>!I.is_won_stage&&!I.is_lost_stage).map(I=>{const R=N(I.id),z=p===I.id,$=R.some(H=>H.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden",children:[e.jsxs("button",{onClick:()=>f(z?null:I.id),className:"w-full flex items-center gap-3 p-4 hover:bg-muted/30 transition-colors text-left",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:I.color||"#94A3B8"}}),e.jsx("span",{className:"font-medium text-sm flex-1",children:I.name}),R.length>0&&e.jsxs(Be,{variant:"outline",className:`text-[10px] ${$?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[R.length," drip",R.length!==1?"s":"",$&&" · Active"]}),z?e.jsx(rl,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(gi,{className:"h-4 w-4 text-muted-foreground"})]}),z&&e.jsx("div",{className:"border-t bg-muted/10 p-4 space-y-3",children:R.length===0?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No drip set for this stage"}),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>A(I.id),disabled:d.isPending,children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1.5"}),"Create Drip"]})]}):e.jsxs(e.Fragment,{children:[R.map(H=>e.jsx(f5t,{template:H,isEditing:x===H.id,onToggleEdit:()=>y(x===H.id?null:H.id),onToggleEnabled:()=>S(H),onUpdate:V=>u.mutateAsync({id:H.id,...V}),onDelete:()=>T(H.id),userId:s||""},H.id)),e.jsxs(U,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>A(I.id),children:[e.jsx(an,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},I.id)}),o.filter(I=>I.is_won_stage||I.is_lost_stage).length>0&&e.jsxs("div",{className:"pt-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground font-medium mb-2 px-1",children:"Closing Stages"}),o.filter(I=>I.is_won_stage||I.is_lost_stage).map(I=>{const R=N(I.id),z=p===I.id,$=R.some(H=>H.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden mb-2",children:[e.jsxs("button",{onClick:()=>f(z?null:I.id),className:"w-full flex items-center gap-3 p-4 hover:bg-muted/30 transition-colors text-left",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:I.color||"#94A3B8"}}),e.jsx("span",{className:"font-medium text-sm flex-1",children:I.name}),R.length>0&&e.jsxs(Be,{variant:"outline",className:`text-[10px] ${$?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[R.length," drip",R.length!==1?"s":"",$&&" · Active"]}),z?e.jsx(rl,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(gi,{className:"h-4 w-4 text-muted-foreground"})]}),z&&e.jsx("div",{className:"border-t bg-muted/10 p-4 space-y-3",children:R.length===0?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No drip set for this stage"}),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>A(I.id),disabled:d.isPending,children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1.5"})," Create Drip"]})]}):e.jsxs(e.Fragment,{children:[R.map(H=>e.jsx(f5t,{template:H,isEditing:x===H.id,onToggleEdit:()=>y(x===H.id?null:H.id),onToggleEnabled:()=>S(H),onUpdate:V=>u.mutateAsync({id:H.id,...V}),onDelete:()=>T(H.id),userId:s||""},H.id)),e.jsxs(U,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>A(I.id),children:[e.jsx(an,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},I.id)})]})]})}),e.jsx(Zt,{value:"starters",children:b.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(cn,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"No Starter Templates Yet"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:"Admin-created starter templates will appear here. You'll be able to copy them into your own drips."})]}):e.jsx("div",{className:"space-y-3",children:b.map(I=>e.jsx(Dsr,{template:I,onCopy:()=>L(I.id),isCopying:m.isPending},I.id))})})]})]})})}function f5t({template:s,isEditing:t,onToggleEdit:n,onToggleEnabled:r,onUpdate:a,onDelete:i,userId:l}){const[o,c]=j.useState(s.title),[d,u]=j.useState(s.subject),[h,m]=j.useState(s.body),[p,f]=j.useState(s.video_url||""),[x,y]=j.useState(s.channel),[v,b]=j.useState(s.delay_type),[N,S]=j.useState(s.delay_minutes),[A,T]=j.useState(!1),L=async()=>{T(!0);try{await a({title:o,subject:d,body:h,video_url:p||null,channel:x,delay_type:v,delay_minutes:N}),re.success("Drip saved"),n()}catch{re.error("Failed to save")}finally{T(!1)}},M=I=>{m(R=>R+I)};return e.jsxs("div",{className:"border rounded-lg bg-background overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",role:"button",onClick:n,children:[e.jsx("p",{className:"text-sm font-medium truncate",children:s.title||"Untitled drip"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[s.channel==="sms"?e.jsx(Ki,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(ln,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:s.delay_type==="instant"?"Sends instantly":`Sends after ${s.delay_minutes>=60?`${Math.round(s.delay_minutes/60)}h`:`${s.delay_minutes}m`}`}),s.video_url&&e.jsx(Wr,{className:"h-3 w-3 text-primary"})]})]}),e.jsx(wn,{checked:s.is_enabled,onCheckedChange:r})]}),t&&e.jsxs("div",{className:"border-t p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs font-medium",children:"Title (internal)"}),e.jsx(xe,{value:o,onChange:I=>c(I.target.value),className:"mt-1 h-8 text-sm",placeholder:"e.g. Buyer intro video"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(te,{className:"text-xs font-medium",children:"Channel"}),e.jsx("div",{className:"flex gap-1 mt-1",children:["email","sms"].map(I=>e.jsxs("button",{onClick:()=>y(I),className:`flex-1 flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${x===I?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[I==="sms"?e.jsx(Ki,{className:"h-3 w-3"}):e.jsx(ln,{className:"h-3 w-3"}),I==="sms"?"SMS":"Email"]},I))})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx(te,{className:"text-xs font-medium",children:"Timing"}),e.jsxs("div",{className:"flex gap-1 mt-1",children:[e.jsx("button",{onClick:()=>b("instant"),className:`flex-1 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${v==="instant"?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:"Instant"}),e.jsxs("button",{onClick:()=>b("scheduled"),className:`flex-1 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${v==="scheduled"?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[e.jsx(Yr,{className:"h-3 w-3 mr-1 inline"}),"Delay"]})]})]})]}),v==="scheduled"&&e.jsxs("div",{children:[e.jsx(te,{className:"text-xs font-medium",children:"Delay"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(xe,{type:"number",min:1,value:N>=60?Math.round(N/60):N,onChange:I=>{const R=parseInt(I.target.value)||0;S(N>=60?R*60:R)},className:"h-8 w-20 text-sm"}),e.jsx("div",{className:"flex gap-1",children:[{label:"Minutes",mins:N<60?N:30},{label:"Hours",mins:N>=60?N:60},{label:"Days",mins:N>=1440?N:1440}].map(I=>e.jsx("button",{className:`px-2 py-1 rounded text-xs border transition-colors ${I.label==="Minutes"&&N<60||I.label==="Hours"&&N>=60&&N<1440||I.label==="Days"&&N>=1440?"bg-primary/10 text-primary border-primary/30":"text-muted-foreground border-input"}`,onClick:()=>{I.label==="Minutes"?S(30):I.label==="Hours"?S(60):S(1440)},children:I.label},I.label))})]})]}),x==="email"&&e.jsxs("div",{children:[e.jsx(te,{className:"text-xs font-medium",children:"Subject Line"}),e.jsx(xe,{value:d,onChange:I=>u(I.target.value),className:"mt-1 h-8 text-sm",placeholder:"e.g. Next steps for your home purchase"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(te,{className:"text-xs font-medium",children:x==="sms"?"Message":"Email Body"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Insert:"}),e.jsxs("select",{className:"text-[10px] border rounded px-1 py-0.5 bg-background text-muted-foreground",value:"",onChange:I=>{I.target.value&&M(I.target.value),I.target.value=""},children:[e.jsx("option",{value:"",children:"Merge variable..."}),bsr.map(I=>e.jsx("option",{value:I.key,children:I.label},I.key))]})]})]}),e.jsx("textarea",{value:h,onChange:I=>m(I.target.value),placeholder:x==="sms"?"Hey {{client_first_name}}, great talking with you today! Here's a quick video about what's next...":`Hi {{client_first_name}}, It was great meeting with you! Here's a video about what to expect next...`,className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[100px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs font-medium",children:"Attached Video"}),p?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(Wr,{className:"h-3 w-3 inline mr-1 text-primary"}),p.length>50?p.slice(0,50)+"...":p]}),e.jsx(U,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:()=>f(""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(frt,{onVideoReady:I=>f(I)}),e.jsx(T9,{userId:l,onSelect:I=>f(I),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1"}),e.jsxs(U,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1",onClick:()=>{const I=prompt("Paste a YouTube or Loom URL:");I&&f(I)},children:[e.jsx(Rc,{className:"h-3 w-3"})," Paste URL"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(U,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive",onClick:i,children:[e.jsx(In,{className:"h-3 w-3 mr-1"})," Delete"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{variant:"outline",size:"sm",className:"text-xs",onClick:n,children:"Cancel"}),e.jsx(U,{size:"sm",className:"text-xs",onClick:L,disabled:A,children:A?"Saving...":"Save Drip"})]})]})]})]})}function Dsr({template:s,onCopy:t,isCopying:n}){const[r,a]=j.useState(!1),i=s.body.replace(/<[^>]+>/g,""),l=s.deal_type==="buyer"?"Buyer":s.deal_type==="seller"?"Seller":null,o=s.delay_type==="instant"?"Sends instantly":s.delay_minutes>=1440?`Sends after ${Math.round(s.delay_minutes/1440)} day${Math.round(s.delay_minutes/1440)!==1?"s":""}`:s.delay_minutes>=60?`Sends after ${Math.round(s.delay_minutes/60)} hour${Math.round(s.delay_minutes/60)!==1?"s":""}`:`Sends after ${s.delay_minutes} min`;return e.jsxs("div",{className:"border rounded-xl overflow-hidden transition-all hover:shadow-sm",children:[e.jsxs("button",{onClick:()=>a(!r),className:"w-full flex items-start gap-3 p-4 text-left hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"font-medium text-sm",children:s.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:s.subject}),!r&&e.jsx("p",{className:"text-xs text-muted-foreground/70 line-clamp-1 mt-1",children:i})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 pt-0.5",children:[l&&e.jsx(Be,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:l}),e.jsxs(Be,{variant:"outline",className:"text-[10px] gap-1",children:[s.channel==="sms"?e.jsx(Ki,{className:"h-3 w-3"}):e.jsx(ln,{className:"h-3 w-3"}),s.channel==="sms"?"SMS":"Email"]}),e.jsxs(Be,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(Yr,{className:"h-3 w-3"}),s.delay_type==="instant"?"Instant":o.replace("Sends ","")]}),r?e.jsx(rl,{className:"h-4 w-4 text-muted-foreground ml-1"}):e.jsx(gi,{className:"h-4 w-4 text-muted-foreground ml-1"})]})]}),r&&e.jsxs("div",{className:"border-t bg-muted/10 p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase font-semibold text-muted-foreground tracking-wider mb-1",children:"Subject Line"}),e.jsx("p",{className:"text-sm font-medium",children:s.subject})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase font-semibold text-muted-foreground tracking-wider mb-1",children:"Email Body"}),e.jsx("div",{className:"text-sm text-foreground/80 bg-background rounded-lg border p-4 prose prose-sm max-w-none [&_ul]:list-disc [&_ul]:pl-5 [&_ol]:list-decimal [&_ol]:pl-5 [&_li]:my-0.5 [&_p]:my-2 [&_a]:text-primary [&_a]:underline",dangerouslySetInnerHTML:{__html:s.body}})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Yr,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:o})]}),e.jsxs(U,{onClick:c=>{c.stopPropagation(),t()},size:"sm",className:"w-full gap-1.5",disabled:n,children:[e.jsx(Pa,{className:"h-3.5 w-3.5"}),"Use This Template"]})]})]})}const Css=()=>{const s=Od();return j.useEffect(()=>{console.error("404 Error: User attempted to access non-existent route:",s.pathname)},[s.pathname]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-gray-100",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"mb-4 text-4xl font-bold",children:"404"}),e.jsx("p",{className:"mb-4 text-xl text-gray-600",children:"Oops! Page not found"}),e.jsx("a",{href:"/",className:"text-blue-500 underline hover:text-blue-700",children:"Return to Home"})]})})};function Osr(){return j.useEffect(()=>(document.body.classList.add("cardstudio-page"),()=>{document.body.classList.remove("cardstudio-page")}),[]),e.jsxs(tee,{children:[e.jsx(ns,{path:"/c/:shareToken",element:e.jsx(kss,{})}),e.jsx(ns,{path:"*",element:e.jsx(Css,{})})]})}const kze={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"},Fsr=["America/New_York","America/Chicago","America/Denver","America/Phoenix","America/Los_Angeles","America/Anchorage","Pacific/Honolulu","Europe/London","Europe/Paris","Asia/Dubai","Asia/Singapore","Asia/Tokyo","Australia/Sydney"];function zsr(s,t,n){const[r,a,i]=s.split("-").map(Number),[l,o]=t.split(":").map(Number),c=Date.UTC(r,a-1,i,l,o),d=new Intl.DateTimeFormat("en-US",{timeZone:n,hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}),u=Object.fromEntries(d.formatToParts(new Date(c)).filter(m=>m.type!=="literal").map(m=>[m.type,m.value])),h=Date.UTC(Number(u.year),Number(u.month)-1,Number(u.day),Number(u.hour)%24,Number(u.minute));return c+(c-h)}function Sze(s){var t;try{return((t=new Intl.DateTimeFormat("en-US",{timeZone:s,timeZoneName:"short"}).formatToParts(new Date).find(r=>r.type==="timeZoneName"))==null?void 0:t.value)||s}catch{return s}}function Ass({slugOverride:s}){const t=Di(),n=s||t.slug,[r,a]=j.useState("types"),[i,l]=j.useState(null),[o,c]=j.useState(null),[d,u]=j.useState(null),[h,m]=j.useState(new Date),[p,f]=j.useState({name:"",email:"",phone:"",message:""}),[x,y]=j.useState(!1),[v,b]=j.useState(null),[N,S]=j.useState(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"America/New_York"}catch{return"America/New_York"}}),{data:A,isLoading:T}=ct({queryKey:["public-booking-settings",n],queryFn:async()=>{const{data:se,error:ne}=await q.from("agent_booking_settings").select("*").eq("slug",n).eq("is_active",!0).single();if(ne)throw ne;return se},enabled:!!n}),{data:L}=ct({queryKey:["public-booking-profile",A==null?void 0:A.user_id],queryFn:async()=>{const{data:se,error:ne}=await q.from("profiles").select("name, avatar_url, email, phone, title, bio").eq("id",A.user_id).single();if(ne)throw ne;return se},enabled:!!(A!=null&&A.user_id)}),{data:M=[]}=ct({queryKey:["public-booking-types",A==null?void 0:A.user_id],queryFn:async()=>{const{data:se,error:ne}=await q.from("agent_booking_types").select("id, name, description, duration_minutes, color, icon, qualification_enabled").eq("user_id",A.user_id).eq("is_active",!0).eq("is_coaching_only",!1).order("sort_order");if(ne)throw ne;return se},enabled:!!(A!=null&&A.user_id)}),I=Gs(h,"yyyy-MM"),{data:R={},isFetching:z}=ct({queryKey:["public-availability-map",n,i==null?void 0:i.id,I],enabled:!!n&&!!i,staleTime:6e4,queryFn:async()=>{const se=new Date(h.getFullYear(),h.getMonth(),1),ne=vf(new Date),ie=F4(ne,se)?ne:se,ce=new Date(h.getFullYear(),h.getMonth()+1,0),je=Math.max(1,Math.round((ce.getTime()-ie.getTime())/864e5)+1),{data:be,error:he}=await q.functions.invoke("agent-booking",{body:{action:"availability",slug:n,booking_type_id:i.id,start:Gs(ie,"yyyy-MM-dd"),days:Math.min(je,90)}});if(he)throw he;if(be!=null&&be.error)throw new Error(be.error);return(be==null?void 0:be.availability)||{}}}),$=se=>{const ne=vf(new Date),ie=jh(ne,(A==null?void 0:A.max_advance_days)||30);return rS(se,ne)||F4(se,ie)?!1:(R[Gs(se,"yyyy-MM-dd")]||[]).length>0},H=j.useMemo(()=>o?R[Gs(o,"yyyy-MM-dd")]||[]:[],[o,R]),V=j.useMemo(()=>{const se=h.getFullYear(),ne=h.getMonth(),ie=new Date(se,ne,1),ce=new Date(se,ne+1,0),je=ie.getDay(),be=[];for(let he=0;he{var se,ne;if(!(!i||!o||!d||!p.name||!A)){y(!0);try{const ie=Gs(o,"yyyy-MM-dd"),{data:ce,error:je}=await q.functions.invoke("agent-booking",{body:{action:"create",slug:n,booking_type_id:i.id,date:ie,time:d,guest_name:p.name,guest_email:p.email||null,guest_phone:p.phone||null,guest_message:p.message||null,guest_timezone:N}});if(je){let ge=je.message;try{const ke=await((ne=(se=je.context)==null?void 0:se.json)==null?void 0:ne.call(se));ke!=null&&ke.error&&(ge=ke.error)}catch{}throw new Error(ge)}if(ce!=null&&ce.error)throw new Error(ce.error);const be=(ce==null?void 0:ce.end_time)||d,he=ce!=null&&ce.manage_token?`${window.location.origin}/booking/manage/${ce.manage_token}`:null;b(he),q.functions.invoke("booking-notify",{body:{agentUserId:A.user_id,guestName:p.name,guestEmail:p.email||null,guestPhone:p.phone||null,guestMessage:p.message||null,bookingTypeName:i.name,bookingDate:ie,startTime:d,endTime:be,durationMinutes:i.duration_minutes,meetingLink:A.meeting_link||null,manageUrl:he}}).catch(ge=>console.error("Booking notify error:",ge)),a("confirmed")}catch(ie){re.error("Failed to book: "+ie.message)}finally{y(!1)}}},Z=se=>{const[ne,ie]=se.split(":").map(Number),ce=ne>=12?"PM":"AM";return`${ne%12||12}:${ie.toString().padStart(2,"0")} ${ce}`},Q=(A==null?void 0:A.timezone)||"America/New_York",le=N!==Q,ue=(se,ne)=>{if(!le)return Z(ne);try{return new Intl.DateTimeFormat("en-US",{timeZone:N,hour:"numeric",minute:"2-digit"}).format(new Date(zsr(se,ne,Q)))}catch{return Z(ne)}};return T?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] flex items-center justify-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[#406E71] border-t-transparent"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Loading booking page..."})]})}):A?e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8]",children:[e.jsx("div",{className:"h-1.5 bg-gradient-to-r from-[#406E71] via-[#5a9a9d] to-[#2a4c64]"}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 py-6 sm:py-10",children:[e.jsxs("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden mb-6",children:[e.jsx("div",{className:"relative bg-gradient-to-r from-[#406E71] to-[#2a4c64] px-6 pt-6 pb-12",children:e.jsxs("div",{className:"absolute inset-0 opacity-10",children:[e.jsx("div",{className:"absolute top-2 right-8 w-20 h-20 rounded-full border-2 border-white/30"}),e.jsx("div",{className:"absolute bottom-4 left-12 w-10 h-10 rounded-full border border-white/20"})]})}),e.jsx("div",{className:"relative -mt-10 px-6",children:e.jsxs("div",{className:"flex items-end gap-4",children:[L!=null&&L.avatar_url?e.jsx("img",{src:L.avatar_url,alt:(L==null?void 0:L.name)||"Agent",className:"w-20 h-20 sm:w-24 sm:h-24 rounded-2xl object-cover border-4 border-white shadow-md"}):e.jsx("div",{className:"w-20 h-20 sm:w-24 sm:h-24 rounded-2xl bg-gradient-to-br from-[#406E71] to-[#2a4c64] border-4 border-white shadow-md flex items-center justify-center",children:e.jsx(So,{className:"h-10 w-10 text-white"})}),e.jsxs("div",{className:"pb-1.5",children:[e.jsx("h1",{className:"text-xl sm:text-2xl font-bold text-slate-800 leading-tight",children:(L==null?void 0:L.name)||"Agent"}),(L==null?void 0:L.title)&&e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:L.title})]})]})}),e.jsxs("div",{className:"px-6 py-4 flex flex-wrap gap-2",children:[(L==null?void 0:L.phone)&&e.jsxs("a",{href:`tel:${L.phone}`,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-[#406E71]/8 hover:bg-[#406E71]/15 text-[#406E71] text-xs font-medium transition-colors",children:[e.jsx(ba,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:L.phone}),e.jsx("span",{className:"sm:hidden",children:"Call"})]}),(L==null?void 0:L.email)&&e.jsxs("a",{href:`mailto:${L.email}`,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-[#2a4c64]/8 hover:bg-[#2a4c64]/15 text-[#2a4c64] text-xs font-medium transition-colors",children:[e.jsx(ln,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:L.email}),e.jsx("span",{className:"sm:hidden",children:"Email"})]})]})]}),e.jsx("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden",children:e.jsxs("div",{className:"p-5 sm:p-6",children:[r==="types"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-slate-800",children:"Select a meeting type"}),e.jsx("p",{className:"text-xs text-slate-400 mt-0.5",children:"Choose the type of meeting you'd like to schedule"})]}),e.jsx("div",{className:"space-y-2.5",children:M.map(se=>e.jsx("button",{onClick:()=>{l(se),a("date")},className:"w-full text-left group",children:e.jsx("div",{className:"relative rounded-xl border border-slate-150 p-4 transition-all duration-200 hover:shadow-md hover:border-[#406E71]/30 hover:-translate-y-0.5 active:translate-y-0",style:{borderLeftWidth:"3px",borderLeftColor:se.color},children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("span",{className:"text-2xl shrink-0 mt-0.5",children:kze[se.icon]||"📅"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-semibold text-sm text-slate-800 group-hover:text-[#406E71] transition-colors",children:se.name}),se.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-0.5 line-clamp-2",children:se.description})]})]}),e.jsxs("div",{className:"shrink-0 flex items-center gap-1 px-2.5 py-1 rounded-full bg-slate-100 text-slate-600 text-xs font-medium",children:[e.jsx(Yr,{className:"h-3 w-3"}),se.duration_minutes,"m"]})]})})},se.id))})]}),r==="date"&&i&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("button",{onClick:()=>{a("types"),c(null),u(null)},className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800 transition-colors",children:[e.jsx(Aa,{className:"h-3.5 w-3.5"})," Back to meeting types"]}),e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl border",style:{borderColor:i.color+"40",backgroundColor:i.color+"08"},children:[e.jsx("span",{className:"text-xl",children:kze[i.icon]||"📅"}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("p",{className:"font-semibold text-sm text-slate-800",children:i.name})}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-slate-500 font-medium",children:[e.jsx(Yr,{className:"h-3 w-3"}),i.duration_minutes," min"]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:Gs(h,"MMMM yyyy")}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{className:"h-8 w-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100 hover:text-slate-800 transition-colors",onClick:()=>m(new Date(h.getFullYear(),h.getMonth()-1)),children:e.jsx(rd,{className:"h-4 w-4"})}),e.jsx("button",{className:"h-8 w-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100 hover:text-slate-800 transition-colors",onClick:()=>m(new Date(h.getFullYear(),h.getMonth()+1)),children:e.jsx(gi,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-7 gap-0.5 text-center",children:[["Su","Mo","Tu","We","Th","Fr","Sa"].map(se=>e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-slate-400 font-semibold py-2",children:se},se)),V.map((se,ne)=>{if(!se)return e.jsx("div",{},`pad-${ne}`);const ie=$(se),ce=o&&Hh(se,o),je=Hh(se,new Date);return e.jsx("button",{disabled:!ie,onClick:()=>{c(se),u(null)},className:`h-10 w-10 mx-auto rounded-xl text-sm font-medium transition-all duration-150 ${ce?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-105":ie?"hover:bg-[#406E71]/10 text-slate-700 hover:text-[#406E71]":"text-slate-200 cursor-not-allowed"} ${je&&!ce?"ring-1 ring-[#406E71]/40":""}`,children:se.getDate()},se.toISOString())})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nc,{className:"h-4 w-4 text-[#406E71]"}),e.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:Gs(o,"EEEE, MMMM d")})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-xl bg-slate-50 border border-slate-100 px-3 py-2",children:[e.jsx("span",{className:"text-[11px] text-slate-500",children:"Times shown in your timezone"}),e.jsx("select",{value:N,onChange:se=>S(se.target.value),className:"text-[11px] font-medium text-slate-700 bg-transparent focus:outline-none cursor-pointer",children:Array.from(new Set([N,Q,...Fsr])).map(se=>e.jsxs("option",{value:se,children:[se.replace(/_/g," ")," (",Sze(se),")"]},se))})]}),z&&H.length===0?e.jsxs("div",{className:"text-center py-8 space-y-2",children:[e.jsx(Et,{className:"h-6 w-6 text-slate-300 mx-auto animate-spin"}),e.jsx("p",{className:"text-sm text-slate-400",children:"Checking live availability…"})]}):H.length===0?e.jsxs("div",{className:"text-center py-8 space-y-2",children:[e.jsx(Yr,{className:"h-8 w-8 text-slate-300 mx-auto"}),e.jsx("p",{className:"text-sm text-slate-400",children:"No available times on this day"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Try selecting a different date"})]}):e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2 max-h-52 overflow-y-auto pr-1 custom-scrollbar",children:H.map(se=>{const ne=d===se;return e.jsx("button",{onClick:()=>u(se),className:`px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-150 ${ne?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-[1.02]":"bg-slate-50 text-slate-700 hover:bg-[#406E71]/10 hover:text-[#406E71] border border-slate-150"}`,children:ue(Gs(o,"yyyy-MM-dd"),se)},se)})}),d&&e.jsx(U,{className:"w-full h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold shadow-md shadow-[#406E71]/20 transition-all hover:shadow-lg",onClick:()=>a("form"),children:"Continue to Details"})]})]}),r==="form"&&i&&o&&d&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("button",{onClick:()=>a("date"),className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800 transition-colors",children:[e.jsx(Aa,{className:"h-3.5 w-3.5"})," Back"]}),e.jsxs("div",{className:"rounded-xl bg-gradient-to-r from-[#406E71]/5 to-[#2a4c64]/5 border border-[#406E71]/15 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-lg",children:kze[i.icon]||"📅"}),e.jsx("p",{className:"font-semibold text-sm text-slate-800",children:i.name})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs text-slate-600",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(nc,{className:"h-3.5 w-3.5 text-[#406E71]"}),Gs(o,"EEE, MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yr,{className:"h-3.5 w-3.5 text-[#406E71]"}),ue(Gs(o,"yyyy-MM-dd"),d)," (",Sze(N),") · ",i.duration_minutes," min"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs font-semibold text-slate-700",children:"Full Name *"}),e.jsx(xe,{value:p.name,onChange:se=>f({...p,name:se.target.value}),placeholder:"Jane Smith",className:"h-11 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs font-semibold text-slate-700",children:"Email"}),e.jsxs("div",{className:"relative",children:[e.jsx(ln,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(xe,{type:"email",value:p.email,onChange:se=>f({...p,email:se.target.value}),placeholder:"jane@email.com",className:"h-11 pl-9 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs font-semibold text-slate-700",children:"Phone"}),e.jsxs("div",{className:"relative",children:[e.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(xe,{type:"tel",value:p.phone,onChange:se=>f({...p,phone:se.target.value}),placeholder:"(555) 123-4567",className:"h-11 pl-9 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs font-semibold text-slate-700",children:"Message (optional)"}),e.jsx(Fs,{value:p.message,onChange:se=>f({...p,message:se.target.value}),placeholder:"Anything you'd like the agent to know ahead of time?",rows:3,className:"rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20 resize-none"})]})]}),e.jsx(U,{className:"w-full h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold shadow-md shadow-[#406E71]/20 transition-all hover:shadow-lg disabled:opacity-60",onClick:K,disabled:!p.name||x,children:x?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent"}),"Booking..."]}):"Confirm Booking"})]}),r==="confirmed"&&e.jsxs("div",{className:"text-center space-y-5 py-6",children:[e.jsxs("div",{className:"relative mx-auto w-20 h-20",children:[e.jsx("div",{className:"absolute inset-0 rounded-full bg-emerald-100 animate-ping opacity-30"}),e.jsx("div",{className:"relative w-20 h-20 rounded-full bg-gradient-to-br from-emerald-400 to-emerald-600 flex items-center justify-center shadow-lg shadow-emerald-200",children:e.jsx(zr,{className:"h-10 w-10 text-white"})})]}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-slate-800",children:"You're booked!"}),e.jsxs("p",{className:"text-slate-500 mt-1.5",children:[i==null?void 0:i.name," with ",(L==null?void 0:L.name)||"your agent"]})]}),e.jsx("div",{className:"inline-flex items-center gap-3 px-5 py-3 rounded-xl bg-slate-50 border border-slate-100",children:e.jsxs("div",{className:"text-left text-sm",children:[e.jsx("p",{className:"font-semibold text-slate-800",children:o&&Gs(o,"EEEE, MMMM d, yyyy")}),e.jsxs("p",{className:"text-slate-500",children:[o&&d?`${ue(Gs(o,"yyyy-MM-dd"),d)} (${Sze(N)})`:""," · ",i==null?void 0:i.duration_minutes," min"]})]})}),e.jsx("p",{className:"text-sm text-slate-400 max-w-xs mx-auto",children:"A confirmation with meeting details will be sent to you shortly."}),v&&e.jsx("div",{className:"pt-1",children:e.jsx("a",{href:v,className:"inline-flex items-center gap-1.5 text-xs font-semibold text-[#406E71] underline underline-offset-4",children:"Reschedule or cancel this meeting"})}),((L==null?void 0:L.phone)||(L==null?void 0:L.email))&&e.jsxs("div",{className:"flex flex-col items-center gap-2 pt-2",children:[e.jsx("p",{className:"text-xs text-slate-400 uppercase tracking-wider font-semibold",children:"Contact"}),e.jsxs("div",{className:"flex gap-3",children:[(L==null?void 0:L.phone)&&e.jsxs("a",{href:`tel:${L.phone}`,className:"inline-flex items-center gap-1.5 px-4 py-2 rounded-full bg-[#406E71]/10 text-[#406E71] text-xs font-medium hover:bg-[#406E71]/20 transition-colors",children:[e.jsx(ba,{className:"h-3.5 w-3.5"})," Call"]}),(L==null?void 0:L.email)&&e.jsxs("a",{href:`mailto:${L.email}`,className:"inline-flex items-center gap-1.5 px-4 py-2 rounded-full bg-[#2a4c64]/10 text-[#2a4c64] text-xs font-medium hover:bg-[#2a4c64]/20 transition-colors",children:[e.jsx(ln,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]})}),e.jsx("p",{className:"text-center text-[10px] text-slate-300 mt-6 font-medium tracking-wide uppercase",children:"Powered by LevelUp"})]})]}):e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] flex items-center justify-center p-4",children:e.jsxs("div",{className:"max-w-sm w-full text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-16 h-16 rounded-2xl bg-slate-100 flex items-center justify-center",children:e.jsx(nc,{className:"h-8 w-8 text-slate-400"})}),e.jsx("h2",{className:"text-lg font-semibold text-slate-700",children:"Page Not Available"}),e.jsx("p",{className:"text-sm text-slate-500",children:"This booking page doesn't exist or is currently inactive."})]})})}function Bsr(){const t=Od().pathname.slice(1).split("/")[0];return j.useEffect(()=>{document.body.classList.add("booking-page");const n=()=>{['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};n();const r=[setTimeout(n,500),setTimeout(n,1500),setTimeout(n,3e3),setTimeout(n,5e3)];return()=>{document.body.classList.remove("booking-page"),r.forEach(clearTimeout)}},[]),t?e.jsx(Ass,{slugOverride:t}):e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-950 dark:to-slate-900 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"LevelUp Scheduler"}),e.jsx("p",{className:"text-muted-foreground",children:"Visit a specific agent's booking URL to schedule a meeting."})]})})}function Usr(){const t=Od().pathname.slice(1);return j.useEffect(()=>{document.body.classList.add("connect-page");const n=()=>{['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};n();const r=[setTimeout(n,500),setTimeout(n,1500),setTimeout(n,3e3),setTimeout(n,5e3)];return()=>{document.body.classList.remove("connect-page"),r.forEach(clearTimeout)}},[]),!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Connect"}),e.jsx("p",{className:"text-slate-500",children:"Stay connected with your real estate professional."}),e.jsx("p",{className:"text-slate-400 text-sm mt-2",children:"Visit a specific agent link to get started."})]})}):e.jsx(d7t,{slugOverride:t})}function qsr(s){try{const t=document.createElement("canvas"),n=t.width=Math.min(s.naturalWidth,64),r=t.height=Math.min(s.naturalHeight,64),a=t.getContext("2d");if(!a)return!0;a.drawImage(s,0,0,n,r);const i=a.getImageData(0,0,n,r).data,l=[[0,0],[n-1,0],[0,r-1],[n-1,r-1],[Math.floor(n/2),0],[Math.floor(n/2),r-1],[0,Math.floor(r/2)],[n-1,Math.floor(r/2)]];for(const[o,c]of l)if(i[(c*n+o)*4+3]<250)return!0;return!1}catch{return!0}}const $sr={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function Vsr({page:s,fields:t,answers:n,setAnswers:r,onSubmit:a,isSubmitting:i,renderField:l}){const o=s.accent_color||"#E8B84A",c=s.primary_color||"#0F1B3D",d=$sr[s.heading_font||"playfair"],u=s.eyebrow||null,h=s.headline_accent||null,m=Array.isArray(s.trust_pills)?s.trust_pills:[],p=t,f=p.length>5;return e.jsxs("section",{className:"relative w-full min-h-screen md:min-h-[760px] overflow-hidden",style:{backgroundColor:c},children:[s.hero_image_url?e.jsx("img",{src:s.hero_image_url,alt:"",className:"absolute inset-0 w-full h-full object-cover",loading:"eager"}):e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(135deg, ${c}, #000)`}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/85 via-black/55 to-black/25"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-black/20"}),e.jsx("div",{className:"relative z-10 mx-auto w-full max-w-7xl px-6 md:px-10 py-16 md:py-24 min-h-screen md:min-h-[760px] flex items-center",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-10 lg:gap-12 w-full items-center",children:[e.jsxs("div",{className:"lg:col-span-3 text-white",children:[s.logo_url&&e.jsx(Hsr,{src:s.logo_url}),u&&e.jsx("p",{className:"text-xs md:text-sm font-semibold tracking-[0.22em] text-white/80 mb-4 uppercase",children:u}),e.jsxs("h1",{className:"font-bold leading-[1.04] mb-5 text-4xl sm:text-5xl md:text-6xl lg:text-[68px]",style:{fontFamily:d,letterSpacing:"-0.015em"},children:[s.hero_headline,h&&e.jsxs(e.Fragment,{children:[" ",e.jsx("span",{style:{color:o,fontStyle:"italic"},children:h})]})]}),s.hero_subtext&&e.jsx("p",{className:"text-base md:text-lg text-white/85 leading-relaxed max-w-xl",children:s.hero_subtext}),s.agent_name&&e.jsxs("div",{className:"mt-8 flex items-center gap-3",children:[s.agent_photo_url&&e.jsx("img",{src:s.agent_photo_url,alt:s.agent_name,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white/30"}),e.jsxs("div",{className:"text-white/90",children:[e.jsx("p",{className:"font-semibold text-sm",children:s.agent_name}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs text-white/70 mt-0.5",children:[s.agent_phone&&e.jsxs("a",{href:`tel:${s.agent_phone}`,className:"flex items-center gap-1 hover:text-white",children:[e.jsx(ba,{className:"h-3 w-3"})," ",s.agent_phone]}),s.agent_email&&e.jsxs("a",{href:`mailto:${s.agent_email}`,className:"flex items-center gap-1 hover:text-white",children:[e.jsx(ln,{className:"h-3 w-3"})," ",s.agent_email]})]})]})]})]}),e.jsx("div",{className:"lg:col-span-2",children:e.jsxs("div",{className:"rounded-2xl border border-white/15 bg-white/10 backdrop-blur-xl shadow-2xl p-5 md:p-6",children:[e.jsxs("form",{className:"space-y-3",onSubmit:a,children:[e.jsx("div",{className:f?"space-y-3 max-h-[52vh] overflow-y-auto pr-1 -mr-1":"space-y-3",children:p.map(x=>e.jsxs("div",{children:[e.jsxs(te,{className:"block text-[11px] font-semibold tracking-wider uppercase text-white/85 mb-1.5",children:[x.label,x.is_required&&e.jsx("span",{className:"ml-1",style:{color:o},children:"*"})]}),e.jsx("div",{className:"[&_input]:bg-white/95 [&_input]:border-0 [&_input]:text-neutral-900 [&_input]:placeholder:text-neutral-400 [&_textarea]:bg-white/95 [&_textarea]:border-0 [&_textarea]:text-neutral-900 [&_textarea]:placeholder:text-neutral-400 [&_button[role=combobox]]:bg-white/95 [&_button[role=combobox]]:border-0 [&_button[role=combobox]]:text-neutral-900 [&_span]:text-white/90 [&_button[role=checkbox]]:border-white/60 [&_button[role=checkbox]]:bg-white/20 [&_button[role=checkbox][data-state=checked]]:bg-white [&_button[role=checkbox][data-state=checked]]:text-neutral-900",children:l(x,n,r,c)})]},x.id))}),e.jsx("button",{type:"submit",disabled:i,className:"w-full px-6 py-3.5 rounded-lg font-bold text-neutral-900 text-base md:text-lg shadow-lg hover:brightness-110 active:brightness-95 transition-all disabled:opacity-60 mt-2",style:{backgroundColor:o},children:i?"Submitting...":s.cta_text||"Get Started"})]}),m.length>0&&e.jsx("div",{className:"flex flex-wrap gap-x-5 gap-y-2 mt-4",children:m.map((x,y)=>e.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] md:text-xs text-white/80 font-medium",children:[e.jsx("span",{className:"h-1 w-1 rounded-full",style:{backgroundColor:o}}),x]},y))})]})})]})})]})}function Hsr({src:s}){const[t,n]=j.useState(null),r=e.jsx("img",{src:s,alt:"Logo",crossOrigin:"anonymous",className:"h-10 md:h-12 w-auto object-contain",onLoad:a=>n(qsr(a.currentTarget)),onError:()=>n(!0)});return t===!1?e.jsx("span",{className:"inline-flex items-center rounded-md bg-white/90 backdrop-blur px-3 py-2 mb-6 shadow-sm",children:r}):e.jsx("div",{className:"mb-6 inline-block drop-shadow-md",children:r})}function Gsr(s){const t=Math.max(0,Math.floor(s/1e3));return{d:Math.floor(t/86400),h:Math.floor(t%86400/3600),m:Math.floor(t%3600/60),s:t%60}}function Wsr(s,t,n){const r=new Date(t),a=new Date(r.getTime()+60*60*1e3),i=o=>o.toISOString().replace(/[-:]|\.\d{3}/g,""),l=new URL("https://www.google.com/calendar/render");return l.searchParams.set("action","TEMPLATE"),l.searchParams.set("text",s),l.searchParams.set("dates",`${i(r)}/${i(a)}`),n&&l.searchParams.set("location",n),l.toString()}function Ksr(s,t,n){const r=new Date(t),a=new Date(r.getTime()+60*60*1e3),i=o=>o.toISOString().replace(/[-:]|\.\d{3}/g,""),l=["BEGIN:VCALENDAR","VERSION:2.0","BEGIN:VEVENT",`UID:${Date.now()}@levelup`,`DTSTAMP:${i(new Date)}`,`DTSTART:${i(r)}`,`DTEND:${i(a)}`,`SUMMARY:${s}`,n?`LOCATION:${n}`:"","END:VEVENT","END:VCALENDAR"].filter(Boolean).join(`\r `);return`data:text/calendar;charset=utf-8,${encodeURIComponent(l)}`}function Ysr({startsAt:s,locationName:t,address:n,title:r,accent:a}){const[i,l]=j.useState(Date.now());j.useEffect(()=>{const p=setInterval(()=>l(Date.now()),1e3);return()=>clearInterval(p)},[]);const o=new Date(s).getTime();if(!Number.isFinite(o))return null;const c=Gsr(o-i),d=o-i<=0,u=new Date(s).toLocaleString("en-US",{weekday:"long",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"}),h=[t,n].filter(Boolean).join(" · "),m=n?`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(n)}`:null;return e.jsx("section",{className:"max-w-5xl mx-auto px-4 py-10",children:e.jsx("div",{className:"rounded-2xl border bg-white/80 backdrop-blur p-6 md:p-8 shadow-sm",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider font-medium",style:{color:a},children:d?"Just happened":"Event starts in"}),d?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Missed this one? Submit the form and we'll let you know about the next one."}):e.jsx("div",{className:"flex items-baseline gap-3",children:[{v:c.d,l:"days"},{v:c.h,l:"hrs"},{v:c.m,l:"min"},{v:c.s,l:"sec"}].map(p=>e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-3xl md:text-4xl font-bold tabular-nums",style:{color:a},children:String(p.v).padStart(2,"0")}),e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:p.l})]},p.l))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 pt-2 text-sm text-neutral-700",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Yr,{className:"h-3.5 w-3.5"})," ",u]}),h&&e.jsxs("a",{href:m||"#",target:m?"_blank":void 0,rel:"noreferrer",className:"inline-flex items-center gap-1.5 hover:underline",children:[e.jsx(ni,{className:"h-3.5 w-3.5"})," ",h]})]})]}),!d&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("a",{href:Wsr(r,s,h||null),target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-2 text-sm font-medium rounded-lg border px-3 py-2 hover:bg-neutral-50",children:[e.jsx(pa,{className:"h-4 w-4"})," Add to Google"]}),e.jsxs("a",{href:Ksr(r,s,h||null),download:`${r.replace(/\W+/g,"-").toLowerCase()}.ics`,className:"inline-flex items-center gap-2 text-sm font-medium rounded-lg border px-3 py-2 hover:bg-neutral-50",children:[e.jsx(pa,{className:"h-4 w-4"})," Apple / Outlook"]})]})]})})})}function Zsr(){try{const s="_lp_sid";let t=sessionStorage.getItem(s);return t||(t=crypto.randomUUID?crypto.randomUUID():`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,sessionStorage.setItem(s,t)),t}catch{return`s_${Date.now()}`}}function Ess({slugOverride:s}){var z;const{slug:t}=Di(),n=s||t,[r,a]=j.useState(!1),[i,l]=j.useState({}),[o,c]=j.useState(0),[d,u]=j.useState(!1),[h,m]=j.useState(""),[p]=j.useState(()=>Date.now()),f=j.useState(()=>Zsr())[0],{data:x,isLoading:y}=ct({queryKey:["public-landing-page",n],queryFn:async()=>{const{data:$,error:H}=await q.from("landing_pages").select("*").eq("slug",n).eq("is_published",!0).single();if(H)throw H;return $},enabled:!!n}),{data:v=[]}=ct({queryKey:["public-landing-page-fields",x==null?void 0:x.id],queryFn:async()=>{const{data:$,error:H}=await q.from("landing_page_fields").select("*").eq("page_id",x.id).order("sort_order");if(H)throw H;return $},enabled:!!(x!=null&&x.id)});j.useEffect(()=>{x!=null&&x.id&&q.from("landing_pages").update({view_count:(x.view_count||0)+1}).eq("id",x.id).then(()=>{})},[x==null?void 0:x.id]),j.useEffect(()=>{if(!(x!=null&&x.id))return;const $=new URLSearchParams(window.location.search);q.functions.invoke("landing-page-track",{body:{page_id:x.id,event_type:"view",session_id:f,utm_source:$.get("utm_source"),utm_medium:$.get("utm_medium"),utm_campaign:$.get("utm_campaign"),referrer:document.referrer||null,device:window.matchMedia("(max-width: 768px)").matches?"mobile":"desktop"}}).catch(()=>{})},[x==null?void 0:x.id,f]);const b=yt({mutationFn:async()=>{const $=v.find(ne=>ne.field_type==="text"&&ne.label.toLowerCase().includes("name")),H=v.find(ne=>ne.field_type==="email"),V=v.find(ne=>ne.field_type==="phone"),K=$?String(i[$.label]||""):null,Z=H?String(i[H.label]||""):null,Q=V?String(i[V.label]||""):null,le=new URLSearchParams(window.location.search),{data:ue,error:se}=await q.functions.invoke("landing-page-submit",{body:{page_id:x.id,answers:JSON.parse(JSON.stringify(i)),contact_name:K,contact_email:Z,contact_phone:Q,session_id:f,honeypot:h,rendered_at:p,utm_source:le.get("utm_source"),utm_medium:le.get("utm_medium"),utm_campaign:le.get("utm_campaign"),referrer:document.referrer||null}});if(se)throw se;return ue},onSuccess:$=>{a(!0),$!=null&&$.redirect_url&&setTimeout(()=>{window.location.href=$.redirect_url},1500)}}),N=$=>{$.preventDefault(),!(v.filter(V=>V.is_required&&!i[V.label]).length>0)&&b.mutate()};if(y)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-gray-400 border-t-transparent"})});if(!x)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-700",children:"Page Not Found"}),e.jsx("p",{className:"text-gray-500 mt-2",children:"This page doesn't exist or is no longer available."})]})});const S=x.primary_color||"#406E71",A=x.accent_color||"#2a4c64",T=x,L=x.page_type==="lead_magnet",M=x.page_type==="just_listed"||x.page_type==="just_sold",I=Array.isArray(T.property_photos)?T.property_photos:[],R=T.lead_magnet_file_url||T.lead_magnet_external_url;if(r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:`linear-gradient(135deg, ${S}, ${A})`},children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl p-8 max-w-md mx-4 text-center",children:[e.jsx(zr,{className:"h-16 w-16 mx-auto mb-4",style:{color:S}}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:L?"Your download is ready!":"Submitted!"}),e.jsx("p",{className:"text-gray-600",children:x.success_message}),L&&R&&e.jsxs("a",{href:R,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 mt-6 px-6 py-3 rounded-lg text-white font-semibold transition-transform hover:scale-105",style:{backgroundColor:S},children:[e.jsx(pi,{className:"h-5 w-5"}),"Download ",T.lead_magnet_file_name||"Your File"]}),x.agent_name&&e.jsxs("div",{className:"mt-6 pt-4 border-t",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Contact"}),e.jsx("p",{className:"font-semibold",children:x.agent_name}),x.agent_phone&&e.jsxs("a",{href:`tel:${x.agent_phone}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:S},children:[e.jsx(ba,{className:"h-3 w-3"})," ",x.agent_phone]}),x.agent_email&&e.jsxs("a",{href:`mailto:${x.agent_email}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:S},children:[e.jsx(ln,{className:"h-3 w-3"})," ",x.agent_email]})]})]})});if(M){const $=H=>{const V=parseFloat(H.replace(/[^0-9.]/g,""));return isNaN(V)?H:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(V)};return e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[d&&I.length>0&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center",onClick:()=>u(!1),children:[e.jsx("button",{onClick:()=>u(!1),className:"absolute top-4 right-4 text-white/80 hover:text-white z-10",children:e.jsx(er,{className:"h-8 w-8"})}),e.jsx("button",{onClick:H=>{H.stopPropagation(),c(V=>V===0?I.length-1:V-1)},className:"absolute left-4 top-1/2 -translate-y-1/2 bg-white/10 hover:bg-white/20 text-white rounded-full p-3 transition-colors z-10",children:e.jsx(rd,{className:"h-6 w-6"})}),e.jsx("img",{src:I[o],alt:`Property photo ${o+1}`,className:"max-h-[90vh] max-w-[90vw] object-contain rounded-lg",onClick:H=>H.stopPropagation()}),e.jsx("button",{onClick:H=>{H.stopPropagation(),c(V=>V===I.length-1?0:V+1)},className:"absolute right-4 top-1/2 -translate-y-1/2 bg-white/10 hover:bg-white/20 text-white rounded-full p-3 transition-colors z-10",children:e.jsx(gi,{className:"h-6 w-6"})}),e.jsxs("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 text-white/70 text-sm",children:[o+1," / ",I.length]})]}),I.length>0&&e.jsxs("div",{className:"relative max-w-6xl mx-auto px-4 pt-6",children:[e.jsx("div",{className:"absolute top-10 left-8 z-10 px-4 py-1.5 rounded-full text-white font-bold text-sm uppercase tracking-wider shadow-lg",style:{backgroundColor:T.property_status==="just_sold"?"#e74c3c":S},children:T.property_status==="just_sold"?"🎉 Just Sold":"🏡 Just Listed"}),I.length===1?e.jsxs("div",{className:"rounded-2xl overflow-hidden cursor-pointer group",onClick:()=>{c(0),u(!0)},children:[e.jsx("img",{src:I[0],alt:"Property",className:"w-full h-[50vh] object-cover group-hover:scale-105 transition-transform duration-500"}),e.jsxs("div",{className:"absolute bottom-4 right-4 bg-black/60 text-white px-3 py-1.5 rounded-lg text-sm flex items-center gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(OM,{className:"h-4 w-4"})," View"]})]}):I.length===2?e.jsx("div",{className:"grid grid-cols-2 gap-2 rounded-2xl overflow-hidden",children:I.slice(0,2).map((H,V)=>e.jsx("div",{className:"cursor-pointer group relative",onClick:()=>{c(V),u(!0)},children:e.jsx("img",{src:H,alt:`Property ${V+1}`,className:"w-full h-[45vh] object-cover group-hover:scale-105 transition-transform duration-500"})},V))}):e.jsxs("div",{className:"grid grid-cols-4 gap-2 rounded-2xl overflow-hidden",style:{height:"55vh"},children:[e.jsx("div",{className:"col-span-2 row-span-2 cursor-pointer group relative",onClick:()=>{c(0),u(!0)},children:e.jsx("img",{src:I[0],alt:"Property main",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})}),I.slice(1,5).map((H,V)=>e.jsxs("div",{className:"cursor-pointer group relative",onClick:()=>{c(V+1),u(!0)},children:[e.jsx("img",{src:H,alt:`Property ${V+2}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}),V===3&&I.length>5&&e.jsxs("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center text-white font-bold text-lg",children:["+",I.length-5," more"]})]},V))]}),I.length>2&&e.jsxs("button",{onClick:()=>{c(0),u(!0)},className:"absolute bottom-4 right-8 bg-white shadow-lg hover:shadow-xl text-gray-800 px-4 py-2 rounded-lg text-sm font-medium flex items-center gap-2 transition-shadow",children:[e.jsx(OM,{className:"h-4 w-4"})," View all ",I.length," photos"]})]}),I.length===0&&e.jsx("div",{className:"relative py-16 px-4",style:{background:x.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${x.hero_image_url}) center/cover`:`linear-gradient(135deg, ${S}, ${A})`},children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[x.logo_url&&e.jsx("img",{src:x.logo_url,alt:"Logo",className:"h-12 w-auto mx-auto mb-6"}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:x.hero_headline}),x.hero_subtext&&e.jsx("p",{className:"mt-3 text-lg opacity-90",children:x.hero_subtext})]})}),e.jsx("div",{className:"max-w-4xl mx-auto px-4 py-8",children:e.jsxs("div",{className:"grid md:grid-cols-5 gap-6",children:[e.jsx("div",{className:"md:col-span-3 space-y-6",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 md:p-8",children:[T.property_price&&e.jsx("p",{className:"text-3xl md:text-4xl font-bold mb-2",style:{color:S},children:$(T.property_price)}),T.property_address&&e.jsxs("p",{className:"text-gray-600 flex items-center gap-1.5 mb-5 text-lg",children:[e.jsx(ni,{className:"h-5 w-5 shrink-0"})," ",T.property_address]}),e.jsxs("div",{className:"flex gap-6 mb-5 py-4 border-y border-gray-100",children:[T.property_beds&&e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[e.jsx(Xw,{className:"h-5 w-5",style:{color:S}})," ",T.property_beds]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bedrooms"})]}),T.property_baths&&e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[e.jsx(d0,{className:"h-5 w-5",style:{color:S}})," ",T.property_baths]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bathrooms"})]}),T.property_sqft&&e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[e.jsx(I4,{className:"h-5 w-5",style:{color:S}})," ",Number(T.property_sqft).toLocaleString()]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Sq Ft"})]})]}),T.property_description&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-gray-800 mb-2",children:"About This Property"}),e.jsx("p",{className:"text-gray-600 leading-relaxed whitespace-pre-line",children:T.property_description})]})]})}),e.jsx("div",{className:"md:col-span-2",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 sticky top-6",children:[e.jsx("h2",{className:"text-lg font-bold mb-1",style:{color:S},children:T.property_status==="just_sold"?"Want results like this?":"Interested in this property?"}),e.jsx("p",{className:"text-gray-500 text-sm mb-4",children:"Fill out the form and I'll be in touch!"}),x.agent_name&&e.jsxs("div",{className:"flex items-center gap-3 mb-5 pb-4 border-b",children:[x.agent_photo_url&&e.jsx("img",{src:x.agent_photo_url,alt:x.agent_name,className:"h-12 w-12 rounded-full object-cover"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:x.agent_name}),e.jsxs("div",{className:"flex flex-col gap-0.5 text-xs text-gray-500",children:[x.agent_phone&&e.jsxs("a",{href:`tel:${x.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(ba,{className:"h-3 w-3"})," ",x.agent_phone]}),x.agent_email&&e.jsxs("a",{href:`mailto:${x.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(ln,{className:"h-3 w-3"})," ",x.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:N,className:"space-y-3",children:[v.map(H=>e.jsxs("div",{children:[e.jsxs(te,{className:"text-xs font-medium",children:[H.label,H.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),Cze(H,i,l)]},H.id)),e.jsx(U,{type:"submit",className:"w-full text-white",style:{backgroundColor:S},disabled:b.isPending,children:b.isPending?"Submitting...":"Submit"}),b.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})})]})}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}return x.theme_style!=="classic"&&!L?e.jsxs("div",{className:"min-h-screen bg-neutral-50",children:[e.jsx("input",{type:"text",name:"company_website",tabIndex:-1,autoComplete:"off","aria-hidden":"true",value:h,onChange:$=>m($.target.value),style:{position:"absolute",left:"-10000px",top:"auto",width:"1px",height:"1px",overflow:"hidden"}}),e.jsx(Vsr,{page:x,fields:v,answers:i,setAnswers:l,onSubmit:N,isSubmitting:b.isPending,renderField:Cze}),x.page_type==="event_registration"&&((z=x.settings)==null?void 0:z.event_starts_at)&&e.jsx(Ysr,{startsAt:x.settings.event_starts_at,locationName:x.settings.event_location_name,address:x.settings.event_address,title:x.hero_headline||x.title,accent:x.accent_color||x.primary_color||"#406E71"}),b.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center py-4",children:"Something went wrong. Please try again."}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]}):e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[e.jsx("div",{className:"relative py-16 px-4",style:{background:x.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${x.hero_image_url}) center/cover`:`linear-gradient(135deg, ${S}, ${A})`},children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[x.logo_url&&e.jsx("img",{src:x.logo_url,alt:"Logo",className:"h-12 w-auto mx-auto mb-6"}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:x.hero_headline}),x.hero_subtext&&e.jsx("p",{className:"mt-3 text-lg opacity-90",children:x.hero_subtext}),L&&T.lead_magnet_file_name&&e.jsxs("div",{className:"mt-6 inline-flex items-center gap-2 bg-white/20 backdrop-blur px-4 py-2 rounded-full text-sm",children:[e.jsx(pi,{className:"h-4 w-4"}),"Free Download: ",T.lead_magnet_file_name]})]})}),e.jsx("div",{className:"max-w-2xl mx-auto px-4 -mt-8",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 md:p-8",children:[L&&e.jsx("p",{className:"text-sm text-gray-500 mb-4 text-center",children:"Fill out the form below to get your free download!"}),x.agent_name&&e.jsxs("div",{className:"flex items-center gap-3 mb-6 pb-4 border-b",children:[x.agent_photo_url&&e.jsx("img",{src:x.agent_photo_url,alt:x.agent_name,className:"h-12 w-12 rounded-full object-cover"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:x.agent_name}),e.jsxs("div",{className:"flex items-center gap-3 text-sm text-gray-500",children:[x.agent_phone&&e.jsxs("a",{href:`tel:${x.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(ba,{className:"h-3 w-3"})," ",x.agent_phone]}),x.agent_email&&e.jsxs("a",{href:`mailto:${x.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(ln,{className:"h-3 w-3"})," ",x.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:N,className:"space-y-4",children:[v.map($=>e.jsxs("div",{children:[e.jsxs(te,{className:"text-sm font-medium",children:[$.label,$.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),Cze($,i,l)]},$.id)),e.jsx(U,{type:"submit",className:"w-full text-white",style:{backgroundColor:S},disabled:b.isPending,children:b.isPending?"Submitting...":L?"Get My Free Download":"Submit"}),b.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}function Cze(s,t,n,r){const a=t[s.label]||"",i=Array.isArray(s.options)?s.options:[];switch(s.field_type){case"text":case"email":case"phone":return e.jsx(xe,{type:s.field_type==="email"?"email":s.field_type==="phone"?"tel":"text",value:String(a),onChange:l=>n(o=>({...o,[s.label]:l.target.value})),placeholder:s.placeholder||"",className:"mt-1"});case"textarea":return e.jsx(Fs,{value:String(a),onChange:l=>n(o=>({...o,[s.label]:l.target.value})),placeholder:s.placeholder||"",rows:3,className:"mt-1"});case"select":return e.jsxs(Ns,{value:String(a),onValueChange:l=>n(o=>({...o,[s.label]:l})),children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{placeholder:"Select..."})}),e.jsx(js,{children:i.map(l=>e.jsx(et,{value:l,children:l},l))})]});case"multiselect":return e.jsx("div",{className:"mt-1 space-y-2",children:i.map(l=>{const o=Array.isArray(a)?a:[];return e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(xi,{checked:o.includes(l),onCheckedChange:c=>{const d=c?[...o,l]:o.filter(u=>u!==l);n(u=>({...u,[s.label]:d}))}}),e.jsx("span",{className:"text-sm",children:l})]},l)})});case"toggle":return e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[e.jsx(wn,{checked:!!a,onCheckedChange:l=>n(o=>({...o,[s.label]:l?"Yes":"No"}))}),e.jsx("span",{className:"text-sm text-gray-600",children:a?"Yes":"No"})]});default:return e.jsx(xe,{value:String(a),onChange:l=>n(o=>({...o,[s.label]:l.target.value})),className:"mt-1"})}}function Xsr(){const t=Od().pathname.slice(1).split("/")[0];return j.useEffect(()=>{document.body.classList.add("landing-page-public");const n=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};n();const r=[setTimeout(n,500),setTimeout(n,1500),setTimeout(n,3e3),setTimeout(n,5e3)];return()=>{document.body.classList.remove("landing-page-public"),r.forEach(clearTimeout)}},[]),t?e.jsx(Ess,{slugOverride:t}):e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"LevelUp Pages"}),e.jsx("p",{className:"text-gray-500",children:"Visit a specific page URL to view content."})]})})}const Qsr=[{type:"hero",enabled:!0},{type:"featured_listings",enabled:!0},{type:"new_listings",enabled:!1},{type:"open_houses",enabled:!1},{type:"my_listings",enabled:!1},{type:"city_pages",enabled:!1},{type:"featured_areas",enabled:!0},{type:"about",enabled:!0},{type:"testimonials",enabled:!0},{type:"cta_banner",enabled:!0}],yxr={hero:"Hero Section",featured_listings:"Featured Listings",featured_areas:"Featured Areas",about:"About Me",testimonials:"Testimonials",cta_banner:"Call To Action",new_listings:"New Listings Carousel",open_houses:"Open Houses Carousel",my_listings:"My Listings Carousel",city_pages:"City Pages Grid",property_types:"Property Types Gallery",advantages:"Advantages / Why Choose Us",rate_my_agent:"RateMyAgent Reviews",lifestyle_gallery:"Lifestyle Gallery",market_pulse:"Market Pulse",concierge_services:"Concierge Services",credentials:"Credentials & Clientele",land_use_guide:"Land Use Guide",land_valuation_cta:"Land Valuation CTA",acreage_showcase:"Acreage Showcase",featured_video:"Featured Video",schedule_cta:"Schedule a Consultation"},vxr={hero:"Full-screen background image with headline, subtitle, and search bar",featured_listings:"Grid of highlighted properties from the MLS",featured_areas:"Spotlight regions or neighborhoods that link to property search",about:"Agent photo, bio, and credentials section",testimonials:"Client reviews carousel with quotes",cta_banner:"Call-to-action block to drive contact and search engagement",new_listings:"Horizontal carousel of newest listings, filterable by city",open_houses:"Horizontal carousel of open house listings, filterable by city",my_listings:"Showcase the agent's own active listings in a carousel",city_pages:"Grid of your city landing pages with photos and links",property_types:"Visual gallery of property categories (Ranch, Farm, Land, etc.)",advantages:"Feature cards highlighting your expertise and unique value",rate_my_agent:"Verified client reviews carousel powered by RateMyAgent",lifestyle_gallery:"Cinematic photo grid showcasing luxury living — pools, views, interiors",market_pulse:"Sleek market stats dashboard with avg price, days on market, inventory",concierge_services:"White-glove services showcase — staging, design, moving coordination",credentials:"Affiliation logos and specialty positioning (e.g. luxury and sports & entertainment divisions)",land_use_guide:"Interactive land use cards — Agriculture, Hunting, Equestrian, Recreational",land_valuation_cta:`"What's Your Land Worth?" — bold call-to-action for landowners`,acreage_showcase:"Large visual cards emphasizing lot size with aerial imagery",featured_video:"Embedded YouTube or Bunny video section for cinematic storytelling",schedule_cta:"Prominent booking section that sends visitors to your online scheduling calendar"},g5t={basic:["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","rate_my_agent","featured_video","schedule_cta","cta_banner"],luxury:["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","rate_my_agent","cta_banner","lifestyle_gallery","market_pulse","concierge_services","credentials","featured_video","schedule_cta"],"land-ranch":["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","rate_my_agent","cta_banner","property_types","advantages","land_use_guide","land_valuation_cta","acreage_showcase","featured_video","schedule_cta"]};function bxr(s){return g5t[s]||g5t.basic}function Jsr(s){const t=s.theme_config||{};return{themeTier:s.theme_tier||"basic",brandColor:s.brand_color||"#0f172a",accentColor:s.accent_color||"#3b82f6",fontFamily:s.font_family||"Inter",heroImageUrl:s.hero_image_url||null,homepageModules:Array.isArray(s.homepage_modules)&&s.homepage_modules.length?s.homepage_modules.map(n=>typeof n=="string"?{type:n,enabled:!0}:{enabled:!0,...n}):Qsr,testimonials:Array.isArray(s.testimonials)?s.testimonials:[],featuredListingIds:s.featured_listing_ids||[],searchCities:Array.isArray(t.searchCities)?t.searchCities:[],searchZipCodes:Array.isArray(t.searchZipCodes)?t.searchZipCodes:[],searchCounties:Array.isArray(t.searchCounties)?t.searchCounties:[],searchSubdivisions:Array.isArray(t.searchSubdivisions)?t.searchSubdivisions:[],referralMode:t.referralMode===!0,referralPrimaryLabel:t.referralPrimaryLabel||void 0,referralPrimaryUrl:t.referralPrimaryUrl||void 0,referralSecondaryLabel:t.referralSecondaryLabel||void 0,referralSecondaryUrl:t.referralSecondaryUrl||void 0,divisionLogos:Array.isArray(t.divisionLogos)?t.divisionLogos:[],focusPages:Array.isArray(t.focusPages)?t.focusPages:[]}}const enr=new Set(["localhost","tile-portal.lovable.app","id-preview--b4ed24ae-0b44-4f4d-8676-c620f649ed8a.lovable.app","dashboard.relevelup.com","guestbook.relevelup.com","pages.relevelup.com","listings.relevelup.com"]);function tnr(s){const t=s.toLowerCase().replace(/:\d+$/,"");return!!(enr.has(t)||t.endsWith(".lovable.app")||t.endsWith(".lovableproject.com")||t.endsWith(".lovable.dev"))}function Tss(){return new URLSearchParams(window.location.search).get("previewSlug")}function snr(){const s=Tss();if(s)return s;const n=window.location.hostname.match(/^([^.]+)\.thelocalmove\.com$/i);return n?n[1]:null}function nnr(){const s=snr(),t=!!Tss(),n=window.location.hostname,r=s?null:yEt(n),a=!s&&!tnr(n)&&n.includes(".")&&!xEt(n),i=s||r||(a?n:null),{data:l,isLoading:o,error:c}=ct({queryKey:["lead-site",i,a,t],queryFn:async()=>{var N;if(!i)return null;const u=q.from("lead_sites").select("*"),h=t?u:u.eq("is_active",!0);let m;if(s)m=await h.eq("subdomain_slug",s).maybeSingle();else if(r)m=await h.ilike("custom_domain",r).maybeSingle();else if(a)m=await h.ilike("custom_domain",n).maybeSingle();else return null;const{data:p,error:f}=m;if(f)throw f;if(!p)return null;const{data:x}=await q.from("profiles").select("id, name, avatar_url, email, phone, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url").eq("id",p.agent_id).single();let y=null;if(p.show_team_logo)if(p.team_logo_url)y=p.team_logo_url;else{const{data:S}=await q.from("team_members").select("team_id, teams(avatar_url, name)").eq("user_id",p.agent_id).limit(1).maybeSingle();S&&((N=S.teams)!=null&&N.avatar_url)&&(y=S.teams.avatar_url)}const v={id:p.id,agentId:p.agent_id,subdomainSlug:p.subdomain_slug,customDomain:p.custom_domain||null,mlsProviderId:p.mls_provider_id,siteTitle:p.site_title,siteTagline:p.site_tagline,leadRegistrationMode:p.lead_registration_mode||"disabled",registrationTriggerCount:p.registration_trigger_count??1,themeConfig:p.theme_config||{},themeTier:p.theme_tier||"basic",planTier:p.plan_tier||"paid",brandColor:p.brand_color||void 0,accentColor:p.accent_color||void 0,mlsServiceCities:Array.isArray(p.mls_service_cities)?p.mls_service_cities:[],isActive:p.is_active,brokerageLegalName:p.brokerage_legal_name||null,brokerageLicenseNumber:p.brokerage_license_number||null,agentLicenseNumber:p.agent_license_number||null,licenseState:p.license_state||null,mlsDisclaimerText:p.mls_disclaimer_text||null,mlsLogoUrl:p.mls_logo_url||null,equalHousingEnabled:p.equal_housing_enabled??!0,faviconUrl:p.favicon_url||null,ogImageUrl:p.og_image_url||null,showTeamLogo:p.show_team_logo??!1,teamLogoUrl:y,noMlsMode:p.no_mls_mode===!0,bookingUrl:p.booking_url||null,pageSubtitles:p.page_subtitles||{},agent:x?{id:x.id,full_name:x.name||"",avatar_url:x.avatar_url,email:x.email,phone:x.phone,title:x.title,bio:x.bio,areas_served:x.areas_served||null,years_experience:x.years_experience??null,instagram_url:x.instagram_url||null,facebook_url:x.facebook_url||null,linkedin_url:x.linkedin_url||null}:void 0,testimonials:Array.isArray(p.testimonials)?p.testimonials.filter(S=>S&&typeof S=="object"&&S.text).map(S=>({name:String(S.name||"Client"),text:String(S.text),rating:typeof S.rating=="number"?S.rating:5,location:S.location?String(S.location):void 0})):[],seoMetaTitle:p.seo_meta_title||null,seoMetaDescription:p.seo_meta_description||null},b=Jsr(p);return{siteConfig:v,themeConfig:b}},enabled:!!i,staleTime:5*60*1e3,gcTime:30*60*1e3,refetchOnWindowFocus:!1}),d=r||(a?n:null);return{siteConfig:(l==null?void 0:l.siteConfig)??null,themeConfig:(l==null?void 0:l.themeConfig)??null,isLoading:o,error:c,slug:s??(l==null?void 0:l.siteConfig.subdomainSlug)??null,customDomain:d}}async function rnr(s,t){try{await q.functions.invoke("lead-site-notify",{body:{lead:t,lead_site_id:s}})}catch(n){console.warn("Lead notification failed:",n)}}const Mss=j.createContext(null);function YIe(){const s=j.useContext(Mss);if(!s)throw new Error("useLeadSiteAuth must be used within LeadSiteAuthProvider");return s}function anr({siteConfig:s,children:t}){const[n,r]=j.useState(null),[a,i]=j.useState(null),[l,o]=j.useState(!0);j.useEffect(()=>{let h=!0,m=0;const p=async y=>{const v=++m,{data:b}=await q.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",y.id).eq("lead_site_id",s.id).maybeSingle();!h||v!==m||(i(b?{...b,email:y.email||""}:null),o(!1))},{data:{subscription:f}}=q.auth.onAuthStateChange((y,v)=>{const b=(v==null?void 0:v.user)??null;r(b),b?window.setTimeout(()=>void p(b),0):(m+=1,i(null),o(!1))}),x=window.setTimeout(()=>{h&&(console.warn("Lead site auth initialization timed out."),o(!1))},8e3);return()=>{h=!1,window.clearTimeout(x),f.unsubscribe()}},[s.id]);const c=j.useCallback(async h=>{const m=h.email.toLowerCase().trim(),p=h.phone.replace(/\D/g,""),{data:f,error:x}=await q.auth.signUp({email:m,password:p,options:{data:{full_name:h.name,consumer_site_id:s.id},emailRedirectTo:window.location.origin}});if(x){if(x.message.includes("already registered")){await d(m,p);return}throw x}if(f.user){const{error:y}=await q.from("lead_site_consumer_profiles").insert({user_id:f.user.id,lead_site_id:s.id,name:h.name.trim(),phone:h.phone.trim()});y&&console.warn("Consumer profile insert error:",y);const{error:v}=await q.from("lead_site_leads").insert({lead_site_id:s.id,name:h.name.trim(),email:m,phone:h.phone.trim(),message:"Created account on website",source_page:window.location.pathname,lead_type:"website_registration",metadata:{registered:!0,has_account:!0}});v&&console.error("Lead insert error (CRM sync may not trigger):",v),rnr(s.id,{name:h.name.trim(),email:m,phone:h.phone.trim(),lead_type:"website_registration",message:"Created account on website",source_page:window.location.pathname})}},[s.id]),d=j.useCallback(async(h,m)=>{const p=m.replace(/\D/g,""),{error:f}=await q.auth.signInWithPassword({email:h.toLowerCase().trim(),password:p});if(f)throw f},[]),u=j.useCallback(async()=>{await q.auth.signOut(),r(null),i(null)},[]);return e.jsx(Mss.Provider,{value:{user:n,profile:a,isLoading:l,signUp:c,signIn:d,signOut:u},children:t})}const inr=new Set(["7605cc2e-ce21-4f4f-8bb1-4c0f217b1109"]),onr=new Set(["tomlois"]);function Nrt(s,t){var n;return s?(t==null?void 0:t.referralMode)===!0||((n=s.themeConfig)==null?void 0:n.referralMode)===!0||s.noMlsMode===!0||inr.has(s.id||"")||onr.has((s.subdomainSlug||"").toLowerCase())||!s.mlsProviderId:!1}function _xr(s){return`Contact ${s.split(" ")[0]||"Me"}`}const SW="#c9a96e",lnr="Schedule a Free Consultation",cnr={sm:"px-5 py-2.5 text-[11px]",md:"px-7 py-3.5 text-xs",lg:"px-9 py-4 text-xs"};function VA({bookingUrl:s,label:t=lnr,className:n="",variant:r="solid",color:a=SW,size:i="md",onDark:l=!0,source:o}){if(!s)return null;const c=`inline-flex items-center justify-center gap-2.5 font-semibold tracking-[0.18em] uppercase rounded-full transition-all duration-300 ${cnr[i]}`,d=r==="solid"?{backgroundColor:a,color:"#0d0b0a",boxShadow:`0 10px 30px -12px ${a}`}:{borderColor:a,color:a,borderWidth:1};return e.jsxs("a",{href:s,target:"_blank",rel:"noopener noreferrer","data-schedule-source":o,className:`${c} ${r==="solid"?"hover:brightness-110":`border hover:bg-[${a}]/10`} ${r==="outline"&&!l?"bg-white/0":""} ${n}`,style:d,children:[e.jsx(cv,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:t})]})}function wxr({bookingUrl:s,agentName:t,accentColor:n=SW,config:r={},luxury:a=!0}){const i=r.bookingUrl||s;if(!i)return null;const l=r.eyebrow||"No Cost. No Obligation.",o=r.sectionTitle||"Schedule a Free Consultation",c=r.subtitle||`Pick a time that works for you and ${t.split(" ")[0]} will personally call you for a free 30-minute real estate consultation.`,d=r.buttonLabel||"Book My Free Consultation",u=[{icon:Yr,title:r.point1Title||"30 Minutes",text:r.point1Text||"A focused conversation about your goals, timeline, and options."},{icon:sQ,title:r.point2Title||"A Personal Call",text:r.point2Text||`${t.split(" ")[0]} calls you at the time you choose — no phone tag.`},{icon:zr,title:r.point3Title||"Real Answers",text:r.point3Text||"Pricing, strategy, and next steps for buying or selling — free of charge."}],h=a?"bg-[#12100e]":"bg-gray-950";return e.jsxs("section",{className:`relative py-24 ${h} overflow-hidden`,children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.07] pointer-events-none",style:{background:`radial-gradient(circle at 50% 0%, ${n}, transparent 60%)`}}),e.jsx("div",{className:"relative max-w-5xl mx-auto px-6 text-center",children:e.jsxs(kr.div,{initial:{opacity:0,y:24},whileInView:{opacity:1,y:0},viewport:{once:!0},transition:{duration:.7},children:[e.jsxs("div",{className:"flex items-center justify-center gap-4 mb-5",children:[e.jsx("div",{className:"h-px w-12 bg-white/10"}),e.jsx("span",{className:"text-[11px] tracking-[0.4em] uppercase",style:{color:n},children:l}),e.jsx("div",{className:"h-px w-12 bg-white/10"})]}),e.jsx("h2",{className:"text-3xl md:text-5xl text-white tracking-tight",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:o}),e.jsx("p",{className:"text-white/50 mt-5 text-lg max-w-2xl mx-auto leading-relaxed",style:{fontFamily:"'Playfair Display', Georgia, serif",fontStyle:"italic"},children:c}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mt-14 text-left",children:u.map((m,p)=>e.jsxs("div",{className:"border border-white/10 bg-white/[0.03] p-6",children:[e.jsx(m.icon,{className:"h-5 w-5 mb-4",style:{color:n}}),e.jsx("p",{className:"text-white text-sm tracking-[0.15em] uppercase mb-2",children:m.title}),e.jsx("p",{className:"text-white/45 text-sm leading-relaxed",children:m.text})]},p))}),e.jsxs("div",{className:"mt-12 flex flex-col items-center gap-4",children:[e.jsx(VA,{bookingUrl:i,label:d,size:"lg",color:n,source:"home_section"}),e.jsx("p",{className:"text-white/30 text-xs tracking-[0.2em] uppercase",children:"Opens in a new tab · Free 30-minute consultation"})]})]})})]})}function jxr({bookingUrl:s,accentColor:t=SW,headline:n="Prefer to talk it through?",subtext:r="Book a free 30-minute consultation at a time that works for you.",dark:a=!0,className:i="",source:l}){return s?e.jsxs("div",{className:`flex flex-col sm:flex-row sm:items-center sm:justify-between gap-5 p-6 md:p-8 border ${a?"border-white/10 bg-white/[0.03]":"border-gray-200 bg-gray-50 rounded-2xl"} ${i}`,children:[e.jsxs("div",{children:[e.jsx("p",{className:`text-lg ${a?"text-white":"text-gray-900"}`,style:{fontFamily:"'Playfair Display', Georgia, serif"},children:n}),e.jsx("p",{className:`text-sm mt-1 ${a?"text-white/45":"text-gray-600"}`,children:r})]}),e.jsx(VA,{bookingUrl:s,label:"Schedule Now",color:t,size:"sm",className:"flex-shrink-0",source:l})]}):null}function dnr({bookingUrl:s,accentColor:t=SW}){const[n,r]=j.useState(!1),[a,i]=j.useState(!1);if(j.useEffect(()=>{sessionStorage.getItem("schedule-cta-dismissed")==="1"&&i(!0);const o=()=>r(window.scrollY>260);return o(),window.addEventListener("scroll",o,{passive:!0}),()=>window.removeEventListener("scroll",o)},[]),!s||a)return null;const l=()=>{sessionStorage.setItem("schedule-cta-dismissed","1"),i(!0)};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`md:hidden fixed inset-x-0 bottom-0 z-[60] transition-transform duration-300 ${n?"translate-y-0":"translate-y-full"}`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:e.jsxs("div",{className:"bg-[#0d0b0a]/95 backdrop-blur-lg border-t border-white/10 px-4 py-3 flex items-center gap-3",children:[e.jsxs("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:"flex-1 inline-flex items-center justify-center gap-2 rounded-full py-3 text-[11px] font-semibold tracking-[0.18em] uppercase",style:{backgroundColor:t,color:"#0d0b0a"},children:[e.jsx(cv,{className:"h-4 w-4"}),"Schedule Free Consultation"]}),e.jsx("button",{onClick:l,"aria-label":"Dismiss",className:"p-2 text-white/40 hover:text-white",children:e.jsx(er,{className:"h-4 w-4"})})]})}),e.jsx("div",{className:`hidden md:flex fixed bottom-6 right-6 z-[60] items-center gap-2 transition-all duration-300 ${n?"opacity-100 translate-y-0":"opacity-0 translate-y-4 pointer-events-none"}`,children:e.jsx(VA,{bookingUrl:s,label:"Schedule a Free Consultation",size:"sm",color:t,source:"sticky"})})]})}function unr({bookingUrl:s,agentName:t}){return j.useEffect(()=>{if(s){const n=setTimeout(()=>window.location.replace(s),400);return()=>clearTimeout(n)}},[s]),e.jsx("div",{className:"min-h-[70vh] flex items-center justify-center bg-[#0d0b0a] px-6 text-center",children:e.jsxs("div",{children:[e.jsx(cv,{className:"h-8 w-8 mx-auto mb-6",style:{color:SW}}),e.jsx("h1",{className:"text-3xl md:text-4xl text-white tracking-tight",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:"Free 30-Minute Real Estate Consultation"}),e.jsx("p",{className:"text-white/45 mt-4",style:{fontFamily:"'Playfair Display', Georgia, serif",fontStyle:"italic"},children:s?`Taking you to ${t}'s booking calendar…`:"Online booking is not available yet — please use the contact page."}),s&&e.jsx("div",{className:"mt-8",children:e.jsx(VA,{bookingUrl:s,label:"Open Booking Calendar",size:"lg",source:"schedule_page"})})]})})}function krt({open:s,mode:t,siteConfig:n,onComplete:r,onSkip:a,theme:i="default",accentColor:l}){var H;const{signUp:o,signIn:c}=YIe(),[d,u]=j.useState(!1),[h,m]=j.useState(""),[p,f]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState(!1),[N,S]=j.useState(""),A=t==="required",T=i==="luxury",L=l||(T?"#c9a96e":"#2563eb"),M=((H=n.agent)==null?void 0:H.full_name)||"the agent",I={borderColor:`${L}66`,"--tw-ring-color":`${L}66`},R=async V=>{var Z;if(V.preventDefault(),S(""),!p.trim()||!x.trim()){S("Email and phone number are required.");return}if(!d&&!h.trim()){S("Name is required.");return}if(x.replace(/\D/g,"").length<7){S("Please enter a valid phone number.");return}b(!0);try{d?await c(p,x):await o({name:h,email:p,phone:x}),r()}catch(Q){(Z=Q==null?void 0:Q.message)!=null&&Z.includes("Invalid login")?S("Invalid email or phone number. Please try again."):S((Q==null?void 0:Q.message)||"Something went wrong. Please try again.")}finally{b(!1)}},z=T?"w-full px-3 py-2.5 border rounded-lg text-sm focus:outline-none focus:ring-2":"w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",$=T?I:void 0;return e.jsx(zs,{open:s,onOpenChange:A?void 0:V=>{V||a()},children:e.jsxs(Ds,{className:`sm:max-w-md ${T?"border-white/10 bg-[#f7f1e7] text-[#201915]":""}`,onPointerDownOutside:A?V=>V.preventDefault():void 0,onEscapeKeyDown:A?V=>V.preventDefault():void 0,children:[e.jsxs(Vs,{children:[e.jsx($s,{className:"text-xl",style:T?{fontFamily:"'Playfair Display', Georgia, serif"}:void 0,children:d?"Welcome Back":A?"Create a Free Account to Continue":"Save Your Search & Get Updates"}),e.jsx(Pr,{className:T?"text-[#5f5145]":void 0,children:d?"Sign in with your email and phone number.":`Create a free account to save favorites, get alerts, and connect with ${M}.`})]}),e.jsxs("form",{onSubmit:R,className:"space-y-3 mt-2",children:[!d&&e.jsx("input",{type:"text",required:!0,placeholder:"Your name",value:h,onChange:V=>m(V.target.value),className:z,style:$}),e.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:p,onChange:V=>f(V.target.value),className:z,style:$}),e.jsxs("div",{children:[e.jsx("input",{type:"tel",required:!0,placeholder:"Phone number",value:x,onChange:V=>y(V.target.value),className:z,style:$}),e.jsx("p",{className:`text-xs mt-1 ${T?"text-[#8a7869]":"text-gray-400"}`,children:d?"Your phone number is your password":"Your phone number will be used as your password"})]}),N&&e.jsx("p",{className:"text-red-600 text-sm",children:N}),e.jsx("button",{type:"submit",disabled:v,className:`w-full py-2.5 font-medium rounded-lg disabled:opacity-50 transition-colors ${T?"text-black hover:opacity-90 tracking-wider uppercase text-sm":"bg-blue-600 text-white hover:bg-blue-700"}`,style:T?{backgroundColor:L}:void 0,children:v?d?"Signing in...":"Creating account...":d?"Sign In":"Create Account"}),e.jsx("button",{type:"button",onClick:()=>{u(!d),S("")},className:"w-full text-center text-sm hover:opacity-80 transition-opacity",style:{color:L},children:d?"Don't have an account? Sign up":"Already have an account? Sign in"}),!A&&!d&&e.jsx("button",{type:"button",onClick:a,className:`w-full py-2 text-sm transition-colors ${T?"text-[#7a6758] hover:text-[#201915]":"text-gray-500 hover:text-gray-700"}`,children:"Skip for now"})]}),e.jsx("p",{className:`text-xs text-center mt-1 ${T?"text-[#8a7869]":"text-gray-400"}`,children:"By registering you agree to receive property updates. You can unsubscribe anytime."})]})})}function Srt({siteConfig:s,pagePath:t}){const n=s.agent;if(!n)return null;const r=s.customDomain?`https://${s.customDomain}`:`https://${s.subdomainSlug}.thelocalmove.com`,i=(n.areas_served||"").split(/,|;|\|/).map(N=>N.trim()).filter(Boolean),l=i[0]||"",[o,c]=l.split(/,\s*/),d=(n.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],u=[...new Set(d.map(N=>N.toUpperCase()))],h=s.testimonials||[],m=h.length?{"@type":"AggregateRating",ratingValue:(h.reduce((N,S)=>N+(S.rating||5),0)/h.length).toFixed(1),reviewCount:h.length,bestRating:5,worstRating:1}:void 0,p=[n.facebook_url,n.instagram_url,n.linkedin_url].filter(Boolean),f={"@context":"https://schema.org","@type":["RealEstateAgent","LocalBusiness"],"@id":`${r}/#agent`,name:n.full_name,url:r,image:n.avatar_url||s.ogImageUrl||void 0,logo:s.ogImageUrl||n.avatar_url||void 0,email:n.email,telephone:n.phone||void 0,jobTitle:n.title||"Real Estate Agent",description:n.bio||`${n.full_name} is a trusted local real estate professional${l?` serving ${l}`:""}.`,priceRange:"$$",...p.length&&{sameAs:p},...s.brokerageLegalName&&{worksFor:{"@type":"RealEstateAgent",name:s.brokerageLegalName,...s.brokerageLicenseNumber&&{identifier:s.brokerageLicenseNumber}}},...s.agentLicenseNumber&&{identifier:s.agentLicenseNumber},...o&&{address:{"@type":"PostalAddress",addressLocality:o,...c&&{addressRegion:c},addressCountry:"US"}},...i.length&&{areaServed:i.map(N=>{const[S,A]=N.split(/,\s*/);return{"@type":"City",name:S,...A&&{containedInPlace:{"@type":"State",name:A}}}})},...m&&{aggregateRating:m},...h.length&&{review:h.slice(0,10).map(N=>({"@type":"Review",author:{"@type":"Person",name:N.name},reviewBody:N.text,reviewRating:{"@type":"Rating",ratingValue:N.rating||5,bestRating:5,worstRating:1},...N.location&&{locationCreated:{"@type":"Place",name:N.location}}}))}},x={"@context":"https://schema.org","@type":"Person","@id":`${r}/#person`,name:n.full_name,jobTitle:n.title||"Real Estate Agent",description:n.bio||void 0,image:n.avatar_url||void 0,url:r,email:n.email,telephone:n.phone||void 0,...p.length&&{sameAs:p},...n.years_experience&&{knowsAbout:["Residential Real Estate","Home Buying","Home Selling",l?`${l} Real Estate`:"Local Real Estate"].filter(Boolean)},...u.length&&{hasCredential:u.map(N=>({"@type":"EducationalOccupationalCredential",credentialCategory:"designation",name:N}))},...s.brokerageLegalName&&{worksFor:{"@type":"Organization",name:s.brokerageLegalName}}},y={"@context":"https://schema.org","@type":"WebSite","@id":`${r}/#website`,name:s.siteTitle||`${n.full_name} Real Estate`,url:r,publisher:{"@id":`${r}/#agent`},potentialAction:{"@type":"SearchAction",target:{"@type":"EntryPoint",urlTemplate:`${r}/search?q={search_term_string}`},"query-input":"required name=search_term_string"}},v=[{name:"Search Homes",description:`Browse all current MLS listings${l?` in ${l}`:""}.`,path:"/search"},{name:"Featured Areas",description:"Explore featured neighborhoods, cities, and communities.",path:"/areas"},{name:"Sold Properties",description:"See recently sold homes and local market activity.",path:"/sold"},{name:"Home Valuation",description:"Get a free, no-obligation estimate of what your home is worth.",path:"/sell"},{name:"About",description:`Learn more about ${n.full_name}${s.brokerageLegalName?` and ${s.brokerageLegalName}`:""}.`,path:"/about"},{name:"Contact",description:`Get in touch with ${n.full_name} for buying, selling, or relocation help.`,path:"/contact"}],b={"@context":"https://schema.org","@type":"ItemList","@id":`${r}/#nav`,name:"Main Navigation",itemListElement:v.map((N,S)=>({"@type":"SiteNavigationElement",position:S+1,name:N.name,description:N.description,url:`${r}${N.path}`}))};return e.jsxs(dl,{children:[e.jsx("script",{type:"application/ld+json",children:JSON.stringify(f)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(x)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(y)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(b)})]})}function Nxr({items:s,siteConfig:t}){const n=t.customDomain?`https://${t.customDomain}`:`https://${t.subdomainSlug}.thelocalmove.com`,r={"@context":"https://schema.org","@type":"BreadcrumbList",itemListElement:s.map((a,i)=>({"@type":"ListItem",position:i+1,name:a.name,item:`${n}${a.path}`}))};return e.jsx(dl,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(r)})})}function kxr({listing:s,siteConfig:t}){var a;const n=t.customDomain?`https://${t.customDomain}`:`https://${t.subdomainSlug}.thelocalmove.com`,r={"@context":"https://schema.org","@type":"SingleFamilyResidence",name:`${s.address}, ${s.city}, ${s.state} ${s.zip}`,url:`${n}/listing/${s.mlsNumber}`,image:((a=s.photos)==null?void 0:a[0])||void 0,numberOfRooms:s.bedrooms,numberOfBathroomsTotal:s.bathrooms,floorSize:s.sqft?{"@type":"QuantitativeValue",value:s.sqft,unitCode:"FTK"}:void 0,address:{"@type":"PostalAddress",streetAddress:s.address,addressLocality:s.city,addressRegion:s.state,postalCode:s.zip},...s.latitude&&s.longitude&&{geo:{"@type":"GeoCoordinates",latitude:s.latitude,longitude:s.longitude}},offers:{"@type":"Offer",price:s.price,priceCurrency:"USD",availability:s.status==="Active"?"https://schema.org/InStock":"https://schema.org/SoldOut"},...s.yearBuilt&&{yearBuilt:s.yearBuilt}};return e.jsx(dl,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(r)})})}function hnr({faqs:s}){if(!s.length)return null;const t={"@context":"https://schema.org","@type":"FAQPage",mainEntity:s.map(n=>({"@type":"Question",name:n.question,acceptedAnswer:{"@type":"Answer",text:n.answer}}))};return e.jsx(dl,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(t)})})}function Sxr({title:s,description:t,publishedAt:n,imageUrl:r,slug:a,siteConfig:i}){const l=i.customDomain?`https://${i.customDomain}`:`https://${i.subdomainSlug}.thelocalmove.com`,o=i.agent,c={"@context":"https://schema.org","@type":"Article",headline:s,description:t,url:`${l}/blog/${a}`,datePublished:n,...r&&{image:r},author:o?{"@type":"Person",name:o.full_name,url:l}:void 0,publisher:{"@type":"Organization",name:i.siteTitle||(o==null?void 0:o.full_name)||"Agent",url:l}};return e.jsx(dl,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(c)})})}function Cxr({videoId:s,title:t,description:n,thumbnailUrl:r,uploadDate:a,durationSeconds:i}){const l=i&&i>0?i:null,o=l?`PT${Math.floor(l/3600)?`${Math.floor(l/3600)}H`:""}${Math.floor(l%3600/60)}M${l%60}S`:void 0,c={"@context":"https://schema.org","@type":"VideoObject",name:t,description:n,thumbnailUrl:r||`https://i.ytimg.com/vi/${s}/maxresdefault.jpg`,...a&&{uploadDate:a},...o&&{duration:o},embedUrl:`https://www.youtube.com/embed/${s}`,contentUrl:`https://www.youtube.com/watch?v=${s}`};return e.jsx(dl,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(c)})})}function Crt({siteConfig:s}){var p;const t=s.agent;if(!t)return null;const n=t.full_name,r=s.brokerageLegalName||"their brokerage",a=t.areas_served||"the local market",i=((p=a.split(/,|;|\|/)[0])==null?void 0:p.trim())||"the local area",l=t.years_experience,o=t.phone||"",c=t.email,d=s.agentLicenseNumber,u=(t.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],h=[...new Set(u.map(f=>f.toUpperCase()))],m=[{question:`Who is ${n}?`,answer:`${n} is a ${t.title||"REALTOR®"} with ${r}${l?`, with ${l}+ years of local real estate experience`:""} serving ${a}. ${t.bio?t.bio.slice(0,280):""}`.trim()},{question:`What areas does ${n} serve?`,answer:`${n} serves ${a} and surrounding communities. Whether you're buying, selling, relocating, or downsizing, ${n.split(" ")[0]} provides expert local guidance.`},{question:`How can I contact ${n}?`,answer:`You can reach ${n} by ${o?`phone at ${o}, `:""}email at ${c}, or by booking a consultation directly through this website.`},...h.length?[{question:`What real estate designations does ${n} hold?`,answer:`${n} holds the following professional designations: ${h.join(", ")}. These designations represent advanced training in specialized areas of real estate.`}]:[],...d?[{question:`Is ${n} a licensed real estate agent?`,answer:`Yes, ${n} is a fully licensed real estate professional (License #${d}) with ${r}.`}]:[],{question:`How do I search for homes for sale in ${i}?`,answer:`Use the property search on this site to view all current MLS listings in ${i}. You can filter by price, bedrooms, neighborhood, school district, and more. Save searches to receive instant email alerts when new homes match your criteria.`},{question:`What is the home buying process like in ${i}?`,answer:`${n} guides buyers through every step: getting pre-approved, searching MLS listings, touring homes, writing competitive offers, navigating inspections and appraisals, and closing on schedule. Contact ${n.split(" ")[0]} for a free buyer consultation.`},{question:`How do I find out what my home is worth in ${i}?`,answer:`Request a free, no-obligation home valuation from ${n}. ${n.split(" ")[0]} provides a comparative market analysis (CMA) using recent sold comps and current market conditions in ${i}.`}];return e.jsx(hnr,{faqs:m})}const x5t="ls_visitor_geo",mnr=1e3*60*60,Aze="lu_lc_attrib_v1",pnr=1e3*60*60*24*90;function fnr(s){return s==="/"?"home":s==="/search"?"search":s==="/sell"?"sell":s==="/blog"?"blog":s.startsWith("/listing/")?"listing":s.startsWith("/homes-for-sale-in-")?"city":s.startsWith("/homes-in-")?"subdivision":s==="/dashboard"?"dashboard":"other"}function gnr(s,t){switch(t){case"home":return"Home";case"search":return"Search";case"sell":return"Sell Your Home";case"blog":return"Blog";case"listing":return`Listing ${s.split("/listing/")[1]||""}`;case"city":return s.replace("/homes-for-sale-in-","").split("-").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ");case"subdivision":return s.replace("/homes-in-","").split("-").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ");case"dashboard":return"My Dashboard";default:return s}}async function xnr(){try{const s=localStorage.getItem(x5t);if(s){const t=JSON.parse(s);if(Date.now()-t.ts{i.current||(i.current=!0,xnr().then(l=>{a.current=l}))},[]),j.useEffect(()=>{if(!(s!=null&&s.id))return;const l=n.pathname;if(l===r.current)return;r.current=l;const o=fnr(l),c=gnr(l,o),d=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,u=a.current;(async()=>{const m=new URLSearchParams(n.search),p=m.get("luc");if(p&&/^[0-9a-f-]{36}$/i.test(p)){try{localStorage.setItem(Aze,JSON.stringify({contact_id:p,ts:Date.now()}))}catch{}return p}const f=m.get("lc");if(f&&/^[0-9a-f-]{36}$/i.test(f)){const{data:x}=await q.from("listing_email_recipients").select("contact_id").eq("id",f).maybeSingle(),y=x==null?void 0:x.contact_id;if(y){try{localStorage.setItem(Aze,JSON.stringify({contact_id:y,ts:Date.now()}))}catch{}return y}}try{const x=localStorage.getItem(Aze);if(x){const y=JSON.parse(x);if(y!=null&&y.contact_id&&Date.now()-(y.ts||0){q.from("lead_site_page_views").insert({lead_site_id:s.id,page_type:o,page_path:l,page_title:c,visitor_fingerprint:d,auth_user_id:t||null,contact_id:m,visitor_city:(u==null?void 0:u.city)||null,visitor_region:(u==null?void 0:u.region)||null,visitor_country:(u==null?void 0:u.country)||null,visitor_lat:(u==null?void 0:u.lat)||null,visitor_lng:(u==null?void 0:u.lng)||null}).then(({error:p})=>{p&&console.error("[PageTracking] insert failed:",p.message)})})},[n.pathname,n.search,s==null?void 0:s.id,t])}const ynr=3e4;function Ert(s,t){const n=Od(),r=j.useRef(null),a=j.useRef(null),i=j.useRef(0),l=n.pathname,o=vnr(l),c=bnr(l,o),d=o==="listing"&&l.split("/listing/")[1]||null;j.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;o==="listing"&&(i.current+=1);const u=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,h=async()=>{const{data:m,error:p}=await q.from("lead_site_active_visitors").upsert({lead_site_id:s.id,auth_user_id:t,visitor_fingerprint:u,current_page_path:l,current_page_title:c,current_mls_number:d,last_seen_at:new Date().toISOString(),listing_views_count:i.current},{onConflict:"lead_site_id,coalesce(auth_user_id::text,visitor_fingerprint,'')"}).select("id, notified_agent").single();!p&&m&&(r.current=m.id,i.current>=2&&!m.notified_agent&&q.functions.invoke("lead-site-presence-notify",{body:{visitor_id:m.id,lead_site_id:s.id}}).catch(()=>{}))};return h(),a.current&&clearInterval(a.current),a.current=setInterval(h,ynr),()=>{a.current&&clearInterval(a.current)}},[s==null?void 0:s.id,t,l]),j.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;const u=()=>{r.current&&q.from("lead_site_active_visitors").delete().eq("id",r.current).then(()=>{})};return window.addEventListener("beforeunload",u),()=>window.removeEventListener("beforeunload",u)},[s==null?void 0:s.id,t])}function vnr(s){return s==="/"?"home":s==="/search"?"search":s.startsWith("/listing/")?"listing":s.startsWith("/homes-for-sale-in-")?"city":s.startsWith("/homes-in-")?"subdivision":"other"}function bnr(s,t){switch(t){case"home":return"Home";case"search":return"Search";case"listing":return`Listing ${s.split("/listing/")[1]||""}`;case"city":return s.replace("/homes-for-sale-in-","").split("-").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ");case"subdivision":return s.replace("/homes-in-","").split("-").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ");default:return s}}const Bi=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},_nr=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=wnr},wnr=Number.MAX_SAFE_INTEGER||9007199254740991;let wo=function(s){return s.NETWORK_ERROR="networkError",s.MEDIA_ERROR="mediaError",s.KEY_SYSTEM_ERROR="keySystemError",s.MUX_ERROR="muxError",s.OTHER_ERROR="otherError",s}({}),yr=function(s){return s.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",s.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",s.KEY_SYSTEM_NO_SESSION="keySystemNoSession",s.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",s.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",s.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",s.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",s.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",s.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",s.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",s.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",s.MANIFEST_LOAD_ERROR="manifestLoadError",s.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",s.MANIFEST_PARSING_ERROR="manifestParsingError",s.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",s.LEVEL_EMPTY_ERROR="levelEmptyError",s.LEVEL_LOAD_ERROR="levelLoadError",s.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",s.LEVEL_PARSING_ERROR="levelParsingError",s.LEVEL_SWITCH_ERROR="levelSwitchError",s.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",s.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",s.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",s.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",s.FRAG_LOAD_ERROR="fragLoadError",s.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",s.FRAG_DECRYPT_ERROR="fragDecryptError",s.FRAG_PARSING_ERROR="fragParsingError",s.FRAG_GAP="fragGap",s.REMUX_ALLOC_ERROR="remuxAllocError",s.KEY_LOAD_ERROR="keyLoadError",s.KEY_LOAD_TIMEOUT="keyLoadTimeOut",s.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",s.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",s.BUFFER_APPEND_ERROR="bufferAppendError",s.BUFFER_APPENDING_ERROR="bufferAppendingError",s.BUFFER_STALLED_ERROR="bufferStalledError",s.BUFFER_FULL_ERROR="bufferFullError",s.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",s.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",s.ASSET_LIST_LOAD_ERROR="assetListLoadError",s.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",s.ASSET_LIST_PARSING_ERROR="assetListParsingError",s.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",s.INTERNAL_EXCEPTION="internalException",s.INTERNAL_ABORTED="aborted",s.ATTACH_MEDIA_ERROR="attachMediaError",s.UNKNOWN="unknown",s}({}),Ot=function(s){return s.MEDIA_ATTACHING="hlsMediaAttaching",s.MEDIA_ATTACHED="hlsMediaAttached",s.MEDIA_DETACHING="hlsMediaDetaching",s.MEDIA_DETACHED="hlsMediaDetached",s.MEDIA_ENDED="hlsMediaEnded",s.STALL_RESOLVED="hlsStallResolved",s.BUFFER_RESET="hlsBufferReset",s.BUFFER_CODECS="hlsBufferCodecs",s.BUFFER_CREATED="hlsBufferCreated",s.BUFFER_APPENDING="hlsBufferAppending",s.BUFFER_APPENDED="hlsBufferAppended",s.BUFFER_EOS="hlsBufferEos",s.BUFFERED_TO_END="hlsBufferedToEnd",s.BUFFER_FLUSHING="hlsBufferFlushing",s.BUFFER_FLUSHED="hlsBufferFlushed",s.MANIFEST_LOADING="hlsManifestLoading",s.MANIFEST_LOADED="hlsManifestLoaded",s.MANIFEST_PARSED="hlsManifestParsed",s.LEVEL_SWITCHING="hlsLevelSwitching",s.LEVEL_SWITCHED="hlsLevelSwitched",s.LEVEL_LOADING="hlsLevelLoading",s.LEVEL_LOADED="hlsLevelLoaded",s.LEVEL_UPDATED="hlsLevelUpdated",s.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",s.LEVELS_UPDATED="hlsLevelsUpdated",s.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",s.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",s.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",s.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",s.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",s.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",s.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",s.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",s.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",s.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",s.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",s.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",s.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",s.CUES_PARSED="hlsCuesParsed",s.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",s.INIT_PTS_FOUND="hlsInitPtsFound",s.FRAG_LOADING="hlsFragLoading",s.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",s.FRAG_LOADED="hlsFragLoaded",s.FRAG_DECRYPTED="hlsFragDecrypted",s.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",s.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",s.FRAG_PARSING_METADATA="hlsFragParsingMetadata",s.FRAG_PARSED="hlsFragParsed",s.FRAG_BUFFERED="hlsFragBuffered",s.FRAG_CHANGED="hlsFragChanged",s.FPS_DROP="hlsFpsDrop",s.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",s.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",s.ERROR="hlsError",s.DESTROYING="hlsDestroying",s.KEY_LOADING="hlsKeyLoading",s.KEY_LOADED="hlsKeyLoaded",s.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",s.BACK_BUFFER_REACHED="hlsBackBufferReached",s.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",s.ASSET_LIST_LOADING="hlsAssetListLoading",s.ASSET_LIST_LOADED="hlsAssetListLoaded",s.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",s.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",s.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",s.INTERSTITIAL_STARTED="hlsInterstitialStarted",s.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",s.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",s.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",s.INTERSTITIAL_ENDED="hlsInterstitialEnded",s.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",s.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",s.EVENT_CUE_ENTER="hlsEventCueEnter",s}({});var hd={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},io={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class NB{constructor(t,n=0,r=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=n,this.totalWeight_=r}sample(t,n){const r=Math.pow(this.alpha_,t);this.estimate_=n*(1-r)+r*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class jnr{constructor(t,n,r,a=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new NB(t),this.fast_=new NB(n),this.defaultTTFB_=a,this.ttfb_=new NB(t)}update(t,n){const{slow_:r,fast_:a,ttfb_:i}=this;r.halfLife!==t&&(this.slow_=new NB(t,r.getEstimate(),r.getTotalWeight())),a.halfLife!==n&&(this.fast_=new NB(n,a.getEstimate(),a.getTotalWeight())),i.halfLife!==t&&(this.ttfb_=new NB(t,i.getEstimate(),i.getTotalWeight()))}sample(t,n){t=Math.max(t,this.minDelayMs_);const r=8*n,a=t/1e3,i=r/a;this.fast_.sample(a,i),this.slow_.sample(a,i)}sampleTTFB(t){const n=t/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(n,2)/2);this.ttfb_.sample(r,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function Nnr(s,t,n){return(t=Snr(t))in s?Object.defineProperty(s,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):s[t]=n,s}function Yh(){return Yh=Object.assign?Object.assign.bind():function(s){for(var t=1;t`):QT}function v5t(s,t,n){return t[s]?t[s].bind(t):Anr(s,n)}const PKe=MKe();function Enr(s,t,n){const r=MKe();if(typeof console=="object"&&s===!0||typeof s=="object"){const a=["debug","log","info","warn","error"];a.forEach(i=>{r[i]=v5t(i,s,n)});try{r.log(`Debug logs enabled for "${t}" in hls.js version 1.6.16`)}catch{return MKe()}a.forEach(i=>{PKe[i]=v5t(i,s)})}else Yh(PKe,r);return r}const Ah=PKe;function SP(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Tnr(s){return typeof self<"u"&&s===self.ManagedMediaSource}function Pss(s,t){const n=Object.keys(s),r=Object.keys(t),a=n.length,i=r.length;return!a||!i||a===i&&!n.some(l=>r.indexOf(l)===-1)}function uj(s,t=!1){if(typeof TextDecoder<"u"){const d=new TextDecoder("utf-8").decode(s);if(t){const u=d.indexOf("\0");return u!==-1?d.substring(0,u):d}return d.replace(/\0/g,"")}const n=s.length;let r,a,i,l="",o=0;for(;o>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:l+=String.fromCharCode(r);break;case 12:case 13:a=s[o++],l+=String.fromCharCode((r&31)<<6|a&63);break;case 14:a=s[o++],i=s[o++],l+=String.fromCharCode((r&15)<<12|(a&63)<<6|(i&63)<<0);break}}return l}function Zy(s){let t="";for(let n=0;n1||a===1&&(n=this.levelkeys[r[0]])!=null&&n.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){if(!Bi(t)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=t}get ref(){return Fg(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const n=this.levelkeys;if(n){var r;const a=n[t];a&&!((r=this._decryptdata)!=null&&r.keyId)&&(this._decryptdata=a.getDecryptData(this.sn,n))}}abortRequests(){var t,n;(t=this.loader)==null||t.abort(),(n=this.keyLoader)==null||n.abort()}setElementaryStreamInfo(t,n,r,a,i,l=!1){const{elementaryStreams:o}=this,c=o[t];if(!c){o[t]={startPTS:n,endPTS:r,startDTS:a,endDTS:i,partial:l};return}c.startPTS=Math.min(c.startPTS,n),c.endPTS=Math.max(c.endPTS,r),c.startDTS=Math.min(c.startDTS,a),c.endDTS=Math.max(c.endDTS,i)}}class Lnr extends Iss{constructor(t,n,r,a,i){super(r),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=n,this.index=a;const l=t.enumeratedString("BYTERANGE");l&&this.setByteRange(l,i),i&&(this.fragOffset=i.fragOffset+i.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}}function Rss(s,t){const n=Object.getPrototypeOf(s);if(n){const r=Object.getOwnPropertyDescriptor(n,t);return r||Rss(n,t)}}function Inr(s,t){const n=Rss(s,t);n&&(n.enumerable=!0,Object.defineProperty(s,t,n))}const _5t=Math.pow(2,32)-1,Rnr=[].push,Dss={video:1,audio:2,id3:3,text:4};function Zx(s){return String.fromCharCode.apply(null,s)}function Oss(s,t){const n=s[t]<<8|s[t+1];return n<0?65536+n:n}function Zl(s,t){const n=Fss(s,t);return n<0?4294967296+n:n}function w5t(s,t){let n=Zl(s,t);return n*=Math.pow(2,32),n+=Zl(s,t+4),n}function Fss(s,t){return s[t]<<24|s[t+1]<<16|s[t+2]<<8|s[t+3]}function Dnr(s){const t=s.byteLength;for(let n=0;n8&&s[n+4]===109&&s[n+5]===111&&s[n+6]===111&&s[n+7]===102)return!0;n=r>1?n+r:t}return!1}function sd(s,t){const n=[];if(!t.length)return n;const r=s.byteLength;for(let a=0;a1?a+i:r;if(l===t[0])if(t.length===1)n.push(s.subarray(a+8,o));else{const c=sd(s.subarray(a+8,o),t.slice(1));c.length&&Rnr.apply(n,c)}a=o}return n}function Onr(s){const t=[],n=s[0];let r=8;const a=Zl(s,r);r+=4;let i=0,l=0;n===0?(i=Zl(s,r),l=Zl(s,r+4),r+=8):(i=w5t(s,r),l=w5t(s,r+8),r+=16),r+=2;let o=s.length+l;const c=Oss(s,r);r+=2;for(let d=0;d>>31===1)return Ah.warn("SIDX has hierarchical references (not supported)"),null;const f=Zl(s,u);u+=4,t.push({referenceSize:m,subsegmentDuration:f,info:{duration:f/a,start:o,end:o+m-1}}),o+=m,u+=4,r=u}return{earliestPresentationTime:i,timescale:a,version:n,referencesCount:c,references:t}}function zss(s){const t=[],n=sd(s,["moov","trak"]);for(let a=0;a{const i=Zl(a,4),l=t[i];l&&(l.default={duration:Zl(a,12),flags:Zl(a,20)})}),t}function Fnr(s){const t=s.subarray(8),n=t.subarray(86),r=Zx(t.subarray(4,8));let a=r,i;const l=r==="enca"||r==="encv";if(l){const d=sd(t,[r])[0].subarray(r==="enca"?28:78);sd(d,["sinf"]).forEach(h=>{const m=sd(h,["schm"])[0];if(m){const p=Zx(m.subarray(4,8));if(p==="cbcs"||p==="cenc"){const f=sd(h,["frma"])[0];f&&(a=Zx(f))}}})}const o=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":{const c=sd(n,["avcC"])[0];c&&c.length>3&&(a+="."+qce(c[1])+qce(c[2])+qce(c[3]),i=Uce(o==="avc1"?"dva1":"dvav",n));break}case"mp4a":{const c=sd(t,[r])[0],d=sd(c.subarray(28),["esds"])[0];if(d&&d.length>7){let u=4;if(d[u++]!==3)break;u=Mze(d,u),u+=2;const h=d[u++];if(h&128&&(u+=2),h&64&&(u+=d[u++]),d[u++]!==4)break;u=Mze(d,u);const m=d[u++];if(m===64)a+="."+qce(m);else break;if(u+=12,d[u++]!==5)break;u=Mze(d,u);const p=d[u++];let f=(p&248)>>3;f===31&&(f+=1+((p&7)<<3)+((d[u]&224)>>5)),a+="."+f}break}case"hvc1":case"hev1":{const c=sd(n,["hvcC"])[0];if(c&&c.length>12){const d=c[1],u=["","A","B","C"][d>>6],h=d&31,m=Zl(c,2),p=(d&32)>>5?"H":"L",f=c[12],x=c.subarray(6,12);a+="."+u+h,a+="."+znr(m).toString(16).toUpperCase(),a+="."+p+f;let y="";for(let v=x.length;v--;){const b=x[v];(b||y)&&(y="."+b.toString(16).toUpperCase()+y)}a+=y}i=Uce(o=="hev1"?"dvhe":"dvh1",n);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{a=Uce(a,n)||a;break}case"vp09":{const c=sd(n,["vpcC"])[0];if(c&&c.length>6){const d=c[4],u=c[5],h=c[6]>>4&15;a+="."+M5(d)+"."+M5(u)+"."+M5(h)}break}case"av01":{const c=sd(n,["av1C"])[0];if(c&&c.length>2){const d=c[1]>>>5,u=c[1]&31,h=c[2]>>>7?"H":"M",m=(c[2]&64)>>6,p=(c[2]&32)>>5,f=d===2&&m?p?12:10:m?10:8,x=(c[2]&16)>>4,y=(c[2]&8)>>3,v=(c[2]&4)>>2,b=c[2]&3;a+="."+d+"."+M5(u)+h+"."+M5(f)+"."+x+"."+y+v+b+"."+M5(1)+"."+M5(1)+"."+M5(1)+"."+0,i=Uce("dav1",n)}break}}return{codec:a,encrypted:l,supplemental:i}}function Uce(s,t){const n=sd(t,["dvvC"]),r=n.length?n[0]:sd(t,["dvcC"])[0];if(r){const a=r[2]>>1&127,i=r[2]<<5&32|r[3]>>3&31;return s+"."+M5(a)+"."+M5(i)}}function znr(s){let t=0;for(let n=0;n<32;n++)t|=(s>>n&1)<<31-n;return t>>>0}function Mze(s,t){const n=t+5;for(;s[t++]&128&&t{const i=r.subarray(8,24);i.some(l=>l!==0)||(Ah.log(`[eme] Patching keyId in 'enc${a?"a":"v"}>sinf>>tenc' box: ${Zy(i)} -> ${Zy(n)}`),r.set(n,8))})}function Unr(s){const t=[];return Bss(s,n=>t.push(n.subarray(8,24))),t}function Bss(s,t){sd(s,["moov","trak"]).forEach(r=>{const a=sd(r,["mdia","minf","stbl","stsd"])[0];if(!a)return;const i=a.subarray(8);let l=sd(i,["enca"]);const o=l.length>0;o||(l=sd(i,["encv"])),l.forEach(c=>{const d=o?c.subarray(28):c.subarray(78);sd(d,["sinf"]).forEach(h=>{const m=Uss(h);m&&t(m,o)})})})}function Uss(s){const t=sd(s,["schm"])[0];if(t){const n=Zx(t.subarray(4,8));if(n==="cbcs"||n==="cenc"){const r=sd(s,["schi","tenc"])[0];if(r)return r}}}function qnr(s,t,n){const r={},a=sd(s,["moof","traf"]);for(let i=0;ir[i].duration)){let i=1/0,l=0;const o=sd(s,["sidx"]);for(let c=0;ch+m.info.duration||0,0);l=Math.max(l,u+d.earliestPresentationTime/d.timescale)}}l&&Bi(l)&&Object.keys(r).forEach(c=>{r[c].duration||(r[c].duration=l*r[c].timescale-r[c].start)})}return r}function $nr(s){const t={valid:null,remainder:null},n=sd(s,["moof"]);if(n.length<2)return t.remainder=s,t;const r=n[n.length-1];return t.valid=s.slice(0,r.byteOffset-8),t.remainder=s.slice(r.byteOffset-8),t}function _N(s,t){const n=new Uint8Array(s.length+t.length);return n.set(s),n.set(t,s.length),n}function j5t(s,t){const n=[],r=t.samples,a=t.timescale,i=t.id;let l=!1;return sd(r,["moof"]).map(c=>{const d=c.byteOffset-8;sd(c,["traf"]).map(h=>{const m=sd(h,["tfdt"]).map(p=>{const f=p[0];let x=Zl(p,4);return f===1&&(x*=Math.pow(2,32),x+=Zl(p,8)),x/a})[0];return m!==void 0&&(s=m),sd(h,["tfhd"]).map(p=>{const f=Zl(p,4),x=Zl(p,0)&16777215,y=(x&1)!==0,v=(x&2)!==0,b=(x&8)!==0;let N=0;const S=(x&16)!==0;let A=0;const T=(x&32)!==0;let L=8;f===i&&(y&&(L+=8),v&&(L+=4),b&&(N=Zl(p,L),L+=4),S&&(A=Zl(p,L),L+=4),T&&(L+=4),t.type==="video"&&(l=ZIe(t.codec)),sd(h,["trun"]).map(M=>{const I=M[0],R=Zl(M,0)&16777215,z=(R&1)!==0;let $=0;const H=(R&4)!==0,V=(R&256)!==0;let K=0;const Z=(R&512)!==0;let Q=0;const le=(R&1024)!==0,ue=(R&2048)!==0;let se=0;const ne=Zl(M,4);let ie=8;z&&($=Zl(M,ie),ie+=4),H&&(ie+=4);let ce=$+d;for(let je=0;je>1&63;return n===39||n===40}else return(t&31)===6}function Prt(s,t,n,r){const a=qss(s);let i=0;i+=t;let l=0,o=0,c=0;for(;i=a.length)break;c=a[i++],l+=c}while(c===255);o=0;do{if(i>=a.length)break;c=a[i++],o+=c}while(c===255);const d=a.length-i;let u=i;if(od){Ah.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(l===4){if(a[u++]===181){const m=Oss(a,u);if(u+=2,m===49){const p=Zl(a,u);if(u+=4,p===1195456820){const f=a[u++];if(f===3){const x=a[u++],y=31&x,v=64&x,b=v?2+y*3:0,N=new Uint8Array(b);if(v){N[0]=x;for(let S=1;S16){const h=[];for(let f=0;f<16;f++){const x=a[u++].toString(16);h.push(x.length==1?"0"+x:x),(f===3||f===5||f===7||f===9)&&h.push("-")}const m=o-16,p=new Uint8Array(m);for(let f=0;f>24&255,i[1]=r>>16&255,i[2]=r>>8&255,i[3]=r&255,i.set(s,4),a=0,r=8;a0?(i=new Uint8Array(4),t.length>0&&new DataView(i.buffer).setUint32(0,t.length,!1)):i=new Uint8Array;const l=new Uint8Array(4);return n.byteLength>0&&new DataView(l.buffer).setUint32(0,n.byteLength,!1),Gnr([112,115,115,104],new Uint8Array([r,0,0,0]),s,i,a,l,n)}function Knr(s){const t=[];if(s instanceof ArrayBuffer){const n=s.byteLength;let r=0;for(;r+32>>24;if(i!==0&&i!==1)return{offset:n,size:t};const l=s.buffer,o=Zy(new Uint8Array(l,n+12,16));let c=null,d=null,u=0;if(i===0)u=28;else{const m=s.getUint32(28);if(!m||r<32+m*16)return{offset:n,size:t};c=[];for(let p=0;p/\(Windows.+Firefox\//i.test(navigator.userAgent),GH={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Lrt(s,t){const n=GH[t];return!!n&&!!n[s.slice(0,4)]}function Hte(s,t,n=!0){return!s.split(",").some(r=>!Irt(r,t,n))}function Irt(s,t,n=!0){var r;const a=SP(n);return(r=a==null?void 0:a.isTypeSupported(Gte(s,t)))!=null?r:!1}function Gte(s,t){return`${t}/mp4;codecs=${s}`}function N5t(s){if(s){const t=s.substring(0,4);return GH.video[t]}return 2}function jTe(s){const t=$ss();return s.split(",").reduce((n,r)=>{const i=t&&ZIe(r)?9:GH.video[r];return i?(i*2+n)/(n?3:2):(GH.audio[r]+n)/(n?2:1)},0)}const Pze={};function Znr(s,t=!0){if(Pze[s])return Pze[s];const n={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let a=0;aZnr(n.toLowerCase(),t))}function Qnr(s,t){const n=[];if(s){const r=s.split(",");for(let a=0;a4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(s)!==-1)&&(k5t(s,"audio")||k5t(s,"video")))return s;if(t){const n=t.split(",");if(n.length>1){if(s){for(let r=n.length;r--;)if(n[r].substring(0,4)===s.substring(0,4))return n[r]}return n[0]}}return t||s}function k5t(s,t){return Lrt(s,t)&&Irt(s,t)}function Jnr(s){const t=s.split(",");for(let n=0;n2&&r[0]==="avc1"&&(t[n]=`avc1.${parseInt(r[1]).toString(16)}${("000"+parseInt(r[2]).toString(16)).slice(-4)}`)}return t.join(",")}function err(s){if(s.startsWith("av01.")){const t=s.split("."),n=["0","111","01","01","01","0"];for(let r=t.length;r>4&&r<10;r++)t[r]=n[r-4];return t.join(".")}return s}function S5t(s){const t=SP(s)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function LKe(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const trr={supported:!0,powerEfficient:!0,smooth:!0},srr={supported:!1,smooth:!1,powerEfficient:!1},Vss={supported:!0,configurations:[],decodingInfoResults:[trr]};function Hss(s,t){return{supported:!1,configurations:t,decodingInfoResults:[srr],error:s}}function nrr(s,t,n,r,a,i){const l=s.videoCodec,o=s.audioCodec?s.audioGroups:null,c=i==null?void 0:i.audioCodec,d=i==null?void 0:i.channels,u=d?parseInt(d):c?1/0:2;let h=null;if(o!=null&&o.length)try{o.length===1&&o[0]?h=t.groups[o[0]].channels:h=o.reduce((m,p)=>{if(p){const f=t.groups[p];if(!f)throw new Error(`Audio track group ${p} not found`);Object.keys(f.channels).forEach(x=>{m[x]=(m[x]||0)+f.channels[x]})}return m},{2:0})}catch{return!0}return l!==void 0&&(l.split(",").some(m=>ZIe(m))||s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(r,30)||s.videoRange!=="SDR"&&s.videoRange!==n||s.bitrate>Math.max(a,8e6))||!!h&&Bi(u)&&Object.keys(h).some(m=>parseInt(m)>u)}function Gss(s,t,n,r={}){const a=s.videoCodec;if(!a&&!s.audioCodec||!n)return Promise.resolve(Vss);const i=[],l=rrr(s),o=l.length,c=arr(s,t,o>0),d=c.length;for(let u=o||1*d||1;u--;){const h={type:"media-source"};if(o&&(h.video=l[u%o]),d){h.audio=c[u%d];const m=h.audio.bitrate;h.video&&m&&(h.video.bitrate-=m)}i.push(h)}if(a){const u=navigator.userAgent;if(a.split(",").some(h=>ZIe(h))&&$ss())return Promise.resolve(Hss(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),i))}return Promise.all(i.map(u=>{const h=orr(u);return r[h]||(r[h]=n.decodingInfo(u))})).then(u=>({supported:!u.some(h=>!h.supported),configurations:i,decodingInfoResults:u})).catch(u=>({supported:!1,configurations:i,decodingInfoResults:[],error:u}))}function rrr(s){var t;const n=(t=s.videoCodec)==null?void 0:t.split(","),r=Wss(s),a=s.width||640,i=s.height||480,l=s.frameRate||30,o=s.videoRange.toLowerCase();return n?n.map(c=>{const d={contentType:Gte(err(c),"video"),width:a,height:i,bitrate:r,framerate:l};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function arr(s,t,n){var r;const a=(r=s.audioCodec)==null?void 0:r.split(","),i=Wss(s);return a&&s.audioGroups?s.audioGroups.reduce((l,o)=>{var c;const d=o?(c=t.groups[o])==null?void 0:c.tracks:null;return d?d.reduce((u,h)=>{if(h.groupId===o){const m=parseFloat(h.channels||"");a.forEach(p=>{const f={contentType:Gte(p,"audio"),bitrate:n?irr(p,i):i};m&&(f.channels=""+m),u.push(f)})}return u},l):l},[]):[]}function irr(s,t){if(t<=1)return 1;let n=128e3;return s==="ec-3"?n=768e3:s==="ac-3"&&(n=64e4),Math.min(t/2,n)}function Wss(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function orr(s){let t="";const{audio:n,video:r}=s;if(r){const a=LKe(r.contentType);t+=`${a}_r${r.height}x${r.width}f${Math.ceil(r.framerate)}${r.transferFunction||"sd"}_${Math.ceil(r.bitrate/1e5)}`}if(n){const a=LKe(n.contentType);t+=`${r?"_":""}${a}_c${n.channels}`}return t}const IKe=["NONE","TYPE-0","TYPE-1",null];function lrr(s){return IKe.indexOf(s)>-1}const kTe=["SDR","PQ","HLG"];function crr(s){return!!s&&kTe.indexOf(s)>-1}var s3e={No:"",Yes:"YES",v2:"v2"};function C5t(s){const{canSkipUntil:t,canSkipDateRanges:n,age:r}=s,a=r!!r).map(r=>r.substring(0,4)).join(","),"supplemental"in t){var n;this.supplemental=t.supplemental;const r=(n=t.supplemental)==null?void 0:n.videoCodec;r&&r!==t.videoCodec&&(this.codecSet+=`,${r.substring(0,4)}`)}this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return E5t(this._audioGroups,t)}hasSubtitleGroup(t){return E5t(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,n){if(n){if(t==="audio"){let r=this._audioGroups;r||(r=this._audioGroups=[]),r.indexOf(n)===-1&&r.push(n)}else if(t==="text"){let r=this._subtitleGroups;r||(r=this._subtitleGroups=[]),r.indexOf(n)===-1&&r.push(n)}}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return(t=this.audioGroups)==null?void 0:t[0]}get textGroupId(){var t;return(t=this.subtitleGroups)==null?void 0:t[0]}addFallback(){}}function E5t(s,t){return!t||!s?!1:s.indexOf(t)!==-1}function drr(){if(typeof matchMedia=="function"){const s=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(s.media!==t.media)return s.matches===!0}return!1}function urr(s,t){let n=!1,r=[];if(s&&(n=s!=="SDR",r=[s]),t){r=t.allowedVideoRanges||kTe.slice(0);const a=r.join("")!=="SDR"&&!t.videoCodec;n=t.preferHDR!==void 0?t.preferHDR:a&&drr(),n||(r=["SDR"])}return{preferHDR:n,allowedVideoRanges:r}}const hrr=s=>{const t=new WeakSet;return(n,r)=>{if(s&&(r=s(n,r)),typeof r=="object"&&r!==null){if(t.has(r))return;t.add(r)}return r}},fm=(s,t)=>JSON.stringify(s,hrr(t));function mrr(s,t,n,r,a){const i=Object.keys(s),l=r==null?void 0:r.channels,o=r==null?void 0:r.audioCodec,c=a==null?void 0:a.videoCodec,d=l&&parseInt(l)===2;let u=!1,h=!1,m=1/0,p=1/0,f=1/0,x=1/0,y=0,v=[];const{preferHDR:b,allowedVideoRanges:N}=urr(t,a);for(let M=i.length;M--;){const I=s[i[M]];u||(u=I.channels[2]>0),m=Math.min(m,I.minHeight),p=Math.min(p,I.minFramerate),f=Math.min(f,I.minBitrate),N.filter(z=>I.videoRanges[z]>0).length>0&&(h=!0)}m=Bi(m)?m:0,p=Bi(p)?p:0;const S=Math.max(1080,m),A=Math.max(30,p);f=Bi(f)?f:n,n=Math.max(f,n),h||(t=void 0);const T=i.length>1;return{codecSet:i.reduce((M,I)=>{const R=s[I];if(I===M)return M;if(v=h?N.filter(z=>R.videoRanges[z]>0):[],T){if(R.minBitrate>n)return f5(I,`min bitrate of ${R.minBitrate} > current estimate of ${n}`),M;if(!R.hasDefaultAudio)return f5(I,"no renditions with default or auto-select sound found"),M;if(o&&I.indexOf(o.substring(0,4))%5!==0)return f5(I,`audio codec preference "${o}" not found`),M;if(l&&!d){if(!R.channels[l])return f5(I,`no renditions with ${l} channel sound found (channels options: ${Object.keys(R.channels)})`),M}else if((!o||d)&&u&&R.channels[2]===0)return f5(I,"no renditions with stereo sound found"),M;if(R.minHeight>S)return f5(I,`min resolution of ${R.minHeight} > maximum of ${S}`),M;if(R.minFramerate>A)return f5(I,`min framerate of ${R.minFramerate} > maximum of ${A}`),M;if(!v.some(z=>R.videoRanges[z]>0))return f5(I,`no variants with VIDEO-RANGE of ${fm(v)} found`),M;if(c&&I.indexOf(c.substring(0,4))%5!==0)return f5(I,`video codec preference "${c}" not found`),M;if(R.maxScore=jTe(M)||R.fragmentError>s[M].fragmentError)?M:(x=R.minIndex,y=R.maxScore,I)},void 0),videoRanges:v,preferHDR:b,minFramerate:p,minBitrate:f,minIndex:x}}function f5(s,t){Ah.log(`[abr] start candidates with "${s}" ignored because ${t}`)}function Kss(s){return s.reduce((t,n)=>{let r=t.groups[n.groupId];r||(r=t.groups[n.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(n);const a=n.channels||"2";return r.channels[a]=(r.channels[a]||0)+1,r.hasDefault=r.hasDefault||n.default,r.hasAutoSelect=r.hasAutoSelect||n.autoselect,r.hasDefault&&(t.hasDefaultAudio=!0),r.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function prr(s,t,n,r){return s.slice(n,r+1).reduce((a,i,l)=>{if(!i.codecSet)return a;const o=i.audioGroups;let c=a[i.codecSet];c||(a[i.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:l,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,i.bitrate);const d=Math.min(i.height,i.width);return c.minHeight=Math.min(c.minHeight,d),c.minFramerate=Math.min(c.minFramerate,i.frameRate),c.minIndex=Math.min(c.minIndex,l),c.maxScore=Math.max(c.maxScore,i.score),c.fragmentError+=i.fragmentError,c.videoRanges[i.videoRange]=(c.videoRanges[i.videoRange]||0)+1,o&&o.forEach(u=>{if(!u)return;const h=t.groups[u];h&&(c.hasDefaultAudio=c.hasDefaultAudio||t.hasDefaultAudio?h.hasDefault:h.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(h.channels).forEach(m=>{c.channels[m]=(c.channels[m]||0)+h.channels[m]}))}),a},{})}function T5t(s){if(!s)return s;const{lang:t,assocLang:n,characteristics:r,channels:a,audioCodec:i}=s;return{lang:t,assocLang:n,characteristics:r,channels:a,audioCodec:i}}function w4(s,t,n){if("attrs"in s){const r=t.indexOf(s);if(r!==-1)return r}for(let r=0;rr.indexOf(a)===-1)}function CD(s,t){const{audioCodec:n,channels:r}=s;return(n===void 0||(t.audioCodec||"").substring(0,4)===n.substring(0,4))&&(r===void 0||r===(t.channels||"2"))}function xrr(s,t,n,r,a){const i=t[r],o=t.reduce((m,p,f)=>{const x=p.uri;return(m[x]||(m[x]=[])).push(f),m},{})[i.uri];o.length>1&&(r=Math.max.apply(Math,o));const c=i.videoRange,d=i.frameRate,u=i.codecSet.substring(0,4),h=M5t(t,r,m=>{if(m.videoRange!==c||m.frameRate!==d||m.codecSet.substring(0,4)!==u)return!1;const p=m.audioGroups,f=n.filter(x=>!p||p.indexOf(x.groupId)!==-1);return w4(s,f,a)>-1});return h>-1?h:M5t(t,r,m=>{const p=m.audioGroups,f=n.filter(x=>!p||p.indexOf(x.groupId)!==-1);return w4(s,f,a)>-1})}function M5t(s,t,n){for(let r=t;r>-1;r--)if(n(s[r]))return r;for(let r=t+1;r{var r;const{fragCurrent:a,partCurrent:i,hls:l}=this,{autoLevelEnabled:o,media:c}=l;if(!a||!c)return;const d=performance.now(),u=i?i.stats:a.stats,h=i?i.duration:a.duration,m=d-u.loading.start,p=l.minAutoLevel,f=a.level,x=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||f<=p){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const y=x>-1&&x!==f,v=!!n||y;if(!v&&(c.paused||!c.playbackRate||!c.readyState))return;const b=l.mainForwardBufferInfo;if(!v&&b===null)return;const N=this.bwEstimator.getEstimateTTFB(),S=Math.abs(c.playbackRate);if(m<=Math.max(N,1e3*(h/(S*2))))return;const A=b?b.len/S:0,T=u.loading.first?u.loading.first-u.loading.start:-1,L=u.loaded&&T>-1,M=this.getBwEstimate(),I=l.levels,R=I[f],z=Math.max(u.loaded,Math.round(h*(a.bitrate||R.averageBitrate)/8));let $=L?m-T:m;$<1&&L&&($=Math.min(m,u.loaded*8/M));const H=L?u.loaded*1e3/$:0,V=N/1e3,K=H?(z-u.loaded)/H:z*8/M+V;if(K<=A)return;const Z=H?H*8:M,Q=((r=(n==null?void 0:n.details)||this.hls.latestLevelDetails)==null?void 0:r.live)===!0,le=this.hls.config.abrBandWidthUpFactor;let ue=Number.POSITIVE_INFINITY,se;for(se=f-1;se>p;se--){const je=I[se].maxBitrate,be=!I[se].details||Q;if(ue=this.getTimeToLoadFrag(V,Z,h*je,be),ue=K||ue>h*10)return;L?this.bwEstimator.sample(m-Math.min(N,T),u.loaded):this.bwEstimator.sampleTTFB(m);const ne=I[se].maxBitrate;this.getBwEstimate()*le>ne&&this.resetEstimator(ne);const ie=this.findBestLevel(ne,p,se,0,A,1,1);ie>-1&&(se=ie),this.warn(`Fragment ${a.sn}${i?" part "+i.index:""} of level ${f} is loading too slowly; Fragment duration: ${a.duration.toFixed(3)} Time to underbuffer: ${A.toFixed(3)} s Estimated load time for current fragment: ${K.toFixed(3)} s Estimated load time for down switch fragment: ${ue.toFixed(3)} s TTFB estimate: ${T|0} ms Current BW estimate: ${Bi(M)?M|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${se} @ ${ne|0} bps`),l.nextLoadLevel=l.nextAutoLevel=se,this.clearTimer();const ce=()=>{if(this.clearTimer(),this.fragCurrent===a&&this.hls.loadLevel===se&&se>0){const je=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${se>0?"and switching down":""} Fragment duration: ${a.duration.toFixed(3)} s Time to underbuffer: ${je.toFixed(3)} s`),a.abortRequests(),this.fragCurrent=this.partCurrent=null,se>p){let be=this.findBestLevel(this.hls.levels[p].bitrate,p,se,0,je,1,1);be===-1&&(be=p),this.hls.nextLoadLevel=this.hls.nextAutoLevel=be,this.resetEstimator(this.hls.levels[be].bitrate)}}};y||K>ue*2?ce():this.timer=self.setInterval(ce,ue*1e3),l.trigger(Ot.FRAG_LOAD_EMERGENCY_ABORTED,{frag:a,part:i,stats:u})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(this.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new jnr(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ot.FRAG_LOADING,this.onFragLoading,this),t.on(Ot.FRAG_LOADED,this.onFragLoaded,this),t.on(Ot.FRAG_BUFFERED,this.onFragBuffered,this),t.on(Ot.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Ot.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Ot.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Ot.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(Ot.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ot.FRAG_LOADING,this.onFragLoading,this),t.off(Ot.FRAG_LOADED,this.onFragLoaded,this),t.off(Ot.FRAG_BUFFERED,this.onFragBuffered,this),t.off(Ot.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Ot.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Ot.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Ot.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(Ot.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,n){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,n){const r=n.frag;if(!this.ignoreFragment(r)){if(!r.bitrateTest){var a;this.fragCurrent=r,this.partCurrent=(a=n.part)!=null?a:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,n){this.clearTimer()}onError(t,n){if(!n.fatal)switch(n.details){case yr.BUFFER_ADD_CODEC_ERROR:case yr.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case yr.FRAG_LOAD_TIMEOUT:{const r=n.frag,{fragCurrent:a,partCurrent:i}=this;if(r&&a&&r.sn===a.sn&&r.level===a.level){const l=performance.now(),o=i?i.stats:r.stats,c=l-o.loading.start,d=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&d>-1){const h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(h,d),o.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(t,n,r,a){const i=t+r/n,l=a?t+this.lastLevelLoadSec:0;return i+l}onLevelLoaded(t,n){const r=this.hls.config,{loading:a}=n.stats,i=a.end-a.first;Bi(i)&&(this.lastLevelLoadSec=i/1e3),n.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(n.levelInfo)}onFragLoaded(t,{frag:n,part:r}){const a=r?r.stats:n.stats;if(n.type===io.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(n)){if(this.clearTimer(),n.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const i=r?r.duration:n.duration,l=this.hls.levels[n.level],o=(l.loaded?l.loaded.bytes:0)+a.loaded,c=(l.loaded?l.loaded.duration:0)+i;l.loaded={bytes:o,duration:c},l.realBitrate=Math.round(8*o/c)}if(n.bitrateTest){const i={stats:a,frag:n,part:r,id:n.type};this.onFragBuffered(Ot.FRAG_BUFFERED,i),n.bitrateTest=!1}else this.lastLoadedFragLevel=n.level}}onFragBuffered(t,n){const{frag:r,part:a}=n,i=a!=null&&a.stats.loaded?a.stats:r.stats;if(i.aborted||this.ignoreFragment(r))return;const l=i.parsing.end-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(l,i.loaded),i.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=l/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==io.MAIN||t.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:n}=this.hls,r=this.getBwEstimate(),a=this.hls.config.maxStarvationDelay,i=this.findBestLevel(r,n,t,0,a,1,1);if(i>-1)return i;const l=this.hls.firstLevel,o=Math.min(Math.max(l,n),t);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,r=this.bwEstimator.canEstimate(),a=this.lastLoadedFragLevel>-1;if(t!==-1&&(!r||!a||this.nextAutoLevelKey===this.getAutoLevelKey()))return t;const i=r&&a?this.getNextABRAutoLevel():this.firstAutoLevel;if(t!==-1){const l=this.hls.levels;if(l.length>Math.max(t,i)&&l[t].loadError<=l[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:n,hls:r}=this;if(r.levels.length<=1)return r.loadLevel;const{maxAutoLevel:a,config:i,minAutoLevel:l}=r,o=n?n.duration:t?t.duration:0,c=this.getBwEstimate(),d=this.getStarvationDelay();let u=i.abrBandWidthFactor,h=i.abrBandWidthUpFactor;if(d){const y=this.findBestLevel(c,l,a,d,0,u,h);if(y>=0)return this.rebufferNotice=-1,y}let m=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay;if(!d){const y=this.bitrateTestDelay;y&&(m=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-y,this.info(`bitrate test took ${Math.round(1e3*y)}ms, set first fragment max fetchDuration to ${Math.round(1e3*m)} ms`),u=h=1)}const p=this.findBestLevel(c,l,a,d,m,u,h);if(this.rebufferNotice!==p&&(this.rebufferNotice=p,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${p}`)),p>-1)return p;const f=r.levels[l],x=r.loadLevelObj;return x&&(f==null?void 0:f.bitrate)=n;Z--){var K;const Q=f[Z],le=Z>h;if(!Q)continue;if(v.useMediaCapabilities&&!Q.supportedResult&&!Q.supportedPromise){const be=navigator.mediaCapabilities;typeof(be==null?void 0:be.decodingInfo)=="function"&&nrr(Q,R,T,L,t,M)?(Q.supportedPromise=Gss(Q,R,be,this.supportedCache),Q.supportedPromise.then(he=>{if(!this.hls)return;Q.supportedResult=he;const ge=this.hls.levels,ke=ge.indexOf(Q);he.error?this.warn(`MediaCapabilities decodingInfo error: "${he.error}" for level ${ke} ${fm(he)}`):he.supported?he.decodingInfoResults.some(Te=>Te.smooth===!1||Te.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${ke} not smooth or powerEfficient: ${fm(he)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ke} ${fm(he)}`),ke>-1&&ge.length>1&&(this.log(`Removing unsupported level ${ke}`),this.hls.removeLevel(ke),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(he=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${he}`)})):Q.supportedResult=Vss}if((A&&Q.codecSet!==A||T&&Q.videoRange!==T||le&&L>Q.frameRate||!le&&L>0&&Lbe.smooth===!1))&&(!S||Z!==z)){V.push(Z);continue}const ue=Q.details,se=(p?ue==null?void 0:ue.partTarget:ue==null?void 0:ue.averagetargetduration)||$;let ne;le?ne=o*t:ne=l*t;const ie=$&&a>=$*2&&i===0?Q.averageBitrate:Q.maxBitrate,ce=this.getTimeToLoadFrag(H,ne,ie*se,ue===void 0);if(ne>=ie&&(Z===u||Q.loadError===0&&Q.fragmentError===0)&&(ce<=H||!Bi(ce)||N&&!this.bitrateTestDelay||ce${Z} adjustedbw(${Math.round(ne)})-bitrate=${Math.round(ne-ie)} ttfb:${H.toFixed(1)} avgDuration:${se.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${ce.toFixed(1)} firstSelection:${S} codecSet:${Q.codecSet} videoRange:${Q.videoRange} hls.loadLevel:${y}`)),S&&(this.firstSelection=Z),Z}}return-1}set nextAutoLevel(t){const n=this.deriveNextAutoLevel(t);this._nextAutoLevel!==n&&(this.nextAutoLevelKey="",this._nextAutoLevel=n)}deriveNextAutoLevel(t){const{maxAutoLevel:n,minAutoLevel:r}=this.hls;return Math.min(Math.max(t,r),n)}}const Yss={search:function(s,t){let n=0,r=s.length-1,a=null,i=null;for(;n<=r;){a=(n+r)/2|0,i=s[a];const l=t(i);if(l>0)n=a+1;else if(l<0)r=a-1;else return i}return null}};function vrr(s,t,n){if(t===null||!Array.isArray(s)||!s.length||!Bi(t))return null;const r=s[0].programDateTime;if(t<(r||0))return null;const a=s[s.length-1].endProgramDateTime;if(t>=(a||0))return null;for(let i=0;i0&&o<15e-7&&(n+=15e-7),i&&s.level!==i.level&&i.end<=s.end&&(i=t[2+s.sn-t[0].sn]||null)}else n===0&&t[0].start===0&&(i=t[0]);if(i&&((!s||s.level===i.level)&&P5t(n,r,i)===0||brr(i,s,Math.min(a,r))))return i;const l=Yss.search(t,P5t.bind(null,n,r));return l&&(l!==s||!i)?l:i}function brr(s,t,n){if(t&&t.start===0&&t.level0){const r=t.tagList.reduce((a,i)=>(i[0]==="INF"&&(a+=parseFloat(i[1])),a),n);return s.start<=r}return!1}function P5t(s=0,t=0,n){if(n.start<=s&&n.start+n.duration>s)return 0;const r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0));return n.start+n.duration-r<=s?1:n.start-r>s&&n.start?-1:0}function _rr(s,t,n){const r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0))*1e3;return(n.endProgramDateTime||0)-r>s}function Zss(s,t,n){if(s&&s.startCC<=t&&s.endCC>=t){let r=s.fragments;const{fragmentHint:a}=s;a&&(r=r.concat(a));let i;return Yss.search(r,l=>l.cct?-1:(i=l,l.end<=n?1:l.start>n?-1:0)),i||null}return null}function CTe(s){switch(s.details){case yr.FRAG_LOAD_TIMEOUT:case yr.KEY_LOAD_TIMEOUT:case yr.LEVEL_LOAD_TIMEOUT:case yr.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Xss(s){return s.details.startsWith("key")}function Qss(s){return Xss(s)&&!!s.frag&&!s.frag.decryptdata}function L5t(s,t){const n=CTe(t);return s.default[`${n?"timeout":"error"}Retry`]}function Rrt(s,t){const n=s.backoff==="linear"?1:Math.pow(2,t);return Math.min(n*s.retryDelayMs,s.maxRetryDelayMs)}function I5t(s){return _h(_h({},s),{errorRetry:null,timeoutRetry:null})}function ATe(s,t,n,r){if(!s)return!1;const a=r==null?void 0:r.code,i=t499)}function RKe(s){return s===0&&navigator.onLine===!1}var Yy={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},vw={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class jrr extends PN{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(Ot.ERROR,this.onError,this),t.on(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ot.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(Ot.ERROR,this.onError,this),t.off(Ot.ERROR,this.onErrorOut,this),t.off(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ot.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(t==null?void 0:t.type)===io.MAIN?t.level:this.getVariantIndex()}getVariantIndex(){var t;const n=this.hls,r=n.currentLevel;return(t=n.loadLevelObj)!=null&&t.details||r===-1?n.loadLevel:r}variantHasKey(t,n){if(t){var r;if((r=t.details)!=null&&r.hasKey(n))return!0;const a=t.audioGroups;if(a)return this.hls.allAudioTracks.filter(l=>a.indexOf(l.groupId)>=0).some(l=>{var o;return(o=l.details)==null?void 0:o.hasKey(n)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,n){var r;if(n.fatal)return;const a=this.hls,i=n.context;switch(n.details){case yr.FRAG_LOAD_ERROR:case yr.FRAG_LOAD_TIMEOUT:case yr.KEY_LOAD_ERROR:case yr.KEY_LOAD_TIMEOUT:n.errorAction=this.getFragRetryOrSwitchAction(n);return;case yr.FRAG_PARSING_ERROR:if((r=n.frag)!=null&&r.gap){n.errorAction=l$();return}case yr.FRAG_GAP:case yr.FRAG_DECRYPT_ERROR:{n.errorAction=this.getFragRetryOrSwitchAction(n),n.errorAction.action=Yy.SendAlternateToPenaltyBox;return}case yr.LEVEL_EMPTY_ERROR:case yr.LEVEL_PARSING_ERROR:{var l;const c=n.parent===io.MAIN?n.level:a.loadLevel;n.details===yr.LEVEL_EMPTY_ERROR&&((l=n.context)!=null&&(l=l.levelDetails)!=null&&l.live)?n.errorAction=this.getPlaylistRetryOrSwitchAction(n,c):(n.levelRetry=!1,n.errorAction=this.getLevelSwitchAction(n,c))}return;case yr.LEVEL_LOAD_ERROR:case yr.LEVEL_LOAD_TIMEOUT:typeof(i==null?void 0:i.level)=="number"&&(n.errorAction=this.getPlaylistRetryOrSwitchAction(n,i.level));return;case yr.AUDIO_TRACK_LOAD_ERROR:case yr.AUDIO_TRACK_LOAD_TIMEOUT:case yr.SUBTITLE_LOAD_ERROR:case yr.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const c=a.loadLevelObj;if(c&&(i.type===hd.AUDIO_TRACK&&c.hasAudioGroup(i.groupId)||i.type===hd.SUBTITLE_TRACK&&c.hasSubtitleGroup(i.groupId))){n.errorAction=this.getPlaylistRetryOrSwitchAction(n,a.loadLevel),n.errorAction.action=Yy.SendAlternateToPenaltyBox,n.errorAction.flags=vw.MoveAllAlternatesMatchingHost;return}}return;case yr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:n.errorAction={action:Yy.SendAlternateToPenaltyBox,flags:vw.MoveAllAlternatesMatchingHDCP};return;case yr.KEY_SYSTEM_SESSION_UPDATE_FAILED:case yr.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case yr.KEY_SYSTEM_NO_SESSION:n.errorAction={action:Yy.SendAlternateToPenaltyBox,flags:vw.MoveAllAlternatesMatchingKey};return;case yr.BUFFER_ADD_CODEC_ERROR:case yr.REMUX_ALLOC_ERROR:case yr.BUFFER_APPEND_ERROR:if(!n.errorAction){var o;n.errorAction=this.getLevelSwitchAction(n,(o=n.level)!=null?o:a.loadLevel)}return;case yr.INTERNAL_EXCEPTION:case yr.BUFFER_APPENDING_ERROR:case yr.BUFFER_FULL_ERROR:case yr.LEVEL_SWITCH_ERROR:case yr.BUFFER_STALLED_ERROR:case yr.BUFFER_SEEK_OVER_HOLE:case yr.BUFFER_NUDGE_ON_STALL:n.errorAction=l$();return}n.type===wo.KEY_SYSTEM_ERROR&&(n.levelRetry=!1,n.errorAction=l$())}getPlaylistRetryOrSwitchAction(t,n){const r=this.hls,a=L5t(r.config.playlistLoadPolicy,t),i=this.playlistError++;if(ATe(a,i,CTe(t),t.response))return{action:Yy.RetryRequest,flags:vw.None,retryConfig:a,retryCount:i};const o=this.getLevelSwitchAction(t,n);return a&&(o.retryConfig=a,o.retryCount=i),o}getFragRetryOrSwitchAction(t){const n=this.hls,r=this.getVariantLevelIndex(t.frag),a=n.levels[r],{fragLoadPolicy:i,keyLoadPolicy:l}=n.config,o=L5t(Xss(t)?l:i,t),c=n.levels.reduce((u,h)=>u+h.fragmentError,0);if(a&&(t.details!==yr.FRAG_GAP&&a.fragmentError++,!Qss(t)&&ATe(o,c,CTe(t),t.response)))return{action:Yy.RetryRequest,flags:vw.None,retryConfig:o,retryCount:c};const d=this.getLevelSwitchAction(t,r);return o&&(d.retryConfig=o,d.retryCount=c),d}getLevelSwitchAction(t,n){const r=this.hls;n==null&&(n=r.loadLevel);const a=this.hls.levels[n];if(a){var i,l;const d=t.details;a.loadError++,d===yr.BUFFER_APPEND_ERROR&&a.fragmentError++;let u=-1;const{levels:h,loadLevel:m,minAutoLevel:p,maxAutoLevel:f}=r;!r.autoLevelEnabled&&!r.config.preserveManualLevelOnError&&(r.loadLevel=-1);const x=(i=t.frag)==null?void 0:i.type,v=(x===io.AUDIO&&d===yr.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&(d===yr.BUFFER_ADD_CODEC_ERROR||d===yr.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:T})=>a.audioCodec!==T),N=t.sourceBufferName==="video"&&(d===yr.BUFFER_ADD_CODEC_ERROR||d===yr.BUFFER_APPEND_ERROR)&&h.some(({codecSet:T,audioCodec:L})=>a.codecSet!==T&&a.audioCodec===L),{type:S,groupId:A}=(l=t.context)!=null?l:{};for(let T=h.length;T--;){const L=(T+m)%h.length;if(L!==m&&L>=p&&L<=f&&h[L].loadError===0){var o,c;const M=h[L];if(d===yr.FRAG_GAP&&x===io.MAIN&&t.frag){const I=h[L].details;if(I){const R=i9(t.frag,I.fragments,t.frag.start);if(R!=null&&R.gap)continue}}else{if(S===hd.AUDIO_TRACK&&M.hasAudioGroup(A)||S===hd.SUBTITLE_TRACK&&M.hasSubtitleGroup(A))continue;if(x===io.AUDIO&&(o=a.audioGroups)!=null&&o.some(I=>M.hasAudioGroup(I))||x===io.SUBTITLE&&(c=a.subtitleGroups)!=null&&c.some(I=>M.hasSubtitleGroup(I))||v&&a.audioCodec===M.audioCodec||N&&a.codecSet===M.codecSet||!v&&a.codecSet!==M.codecSet)continue}u=L;break}}if(u>-1&&r.loadLevel!==u)return t.levelRetry=!0,this.playlistError=0,{action:Yy.SendAlternateToPenaltyBox,flags:vw.None,nextAutoLevel:u}}return{action:Yy.SendAlternateToPenaltyBox,flags:vw.MoveAllAlternatesMatchingHost}}onErrorOut(t,n){var r;switch((r=n.errorAction)==null?void 0:r.action){case Yy.DoNothing:break;case Yy.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(n),!n.errorAction.resolved&&n.details!==yr.FRAG_GAP?n.fatal=!0:/MediaSource readyState: ended/.test(n.error.message)&&(this.warn(`MediaSource ended after "${n.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(n.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(t){const n=this.hls,r=t.errorAction;if(!r)return;const{flags:a}=r,i=r.nextAutoLevel;switch(a){case vw.None:this.switchLevel(t,i);break;case vw.MoveAllAlternatesMatchingHDCP:{const c=this.getVariantLevelIndex(t.frag),d=n.levels[c],u=d==null?void 0:d.attrs["HDCP-LEVEL"];if(r.hdcpLevel=u,u==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(u){n.maxHdcpLevel=IKe[IKe.indexOf(u)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${n.maxHdcpLevel}" or lower`);break}}case vw.MoveAllAlternatesMatchingKey:{const c=t.decryptdata;if(c){const d=this.hls.levels,u=d.length;for(let m=u;m--;)if(this.variantHasKey(d[m],c)){var l,o;this.log(`Banned key found in level ${m} (${d[m].bitrate}bps) or audio group "${(l=d[m].audioGroups)==null?void 0:l.join(",")}" (${(o=t.frag)==null?void 0:o.type} fragment) ${Zy(c.keyId||[])}`),d[m].fragmentError++,d[m].loadError++,this.log(`Removing level ${m} with key error (${t.error})`),this.hls.removeLevel(m)}const h=t.frag;if(this.hls.levels.length{const c=this.fragments[o];if(!c||l>=c.body.sn)return;if(!c.buffered&&(!c.loaded||i)){c.body.type===r&&this.removeFragment(c.body);return}const d=c.range[t];if(d){if(d.time.length===0){this.removeFragment(c.body);return}d.time.some(u=>{const h=!this.isTimeBuffered(u.startPTS,u.endPTS,n);return h&&this.removeFragment(c.body),h})}})}detectPartialFragments(t){const n=this.timeRanges;if(!n||t.frag.sn==="initSegment")return;const r=t.frag,a=kB(r),i=this.fragments[a];if(!i||i.buffered&&r.gap)return;const l=!r.relurl;Object.keys(n).forEach(o=>{const c=r.elementaryStreams[o];if(!c)return;const d=n[o],u=l||c.partial===!0;i.range[o]=this.getBufferedTimes(r,t.part,u,d)}),i.loaded=null,Object.keys(i.range).length?(this.bufferedEnd(i,r),$ce(i)||this.removeParts(r.sn-1,r.type)):this.removeFragment(i.body)}bufferedEnd(t,n){t.buffered=!0,(t.body.endList=n.endList||t.body.endList)&&(this.endListFragments[t.body.type]=t)}removeParts(t,n){const r=this.activePartLists[n];r&&(this.activePartLists[n]=R5t(r,a=>a.fragment.sn>=t))}fragBuffered(t,n){const r=kB(t);let a=this.fragments[r];!a&&n&&(a=this.fragments[r]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),a&&(a.loaded=null,this.bufferedEnd(a,t))}getBufferedTimes(t,n,r,a){const i={time:[],partial:r},l=t.start,o=t.end,c=t.minEndPTS||o,d=t.maxStartPTS||l;for(let u=0;u=h&&c<=m){i.time.push({startPTS:Math.max(l,a.start(u)),endPTS:Math.min(o,a.end(u))});break}else if(lh){const p=Math.max(l,a.start(u)),f=Math.min(o,a.end(u));f>p&&(i.partial=!0,i.time.push({startPTS:p,endPTS:f}))}else if(o<=h)break}return i}getPartialFragment(t){let n=null,r,a,i,l=0;const{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(d=>{const u=c[d];u&&$ce(u)&&(a=u.body.start-o,i=u.body.end+o,t>=a&&t<=i&&(r=Math.min(t-a,i-t),l<=r&&(n=u.body,l=r)))}),n}isEndListAppended(t){const n=this.endListFragments[t];return n!==void 0&&(n.buffered||$ce(n))}getState(t){const n=kB(t),r=this.fragments[n];return r?r.buffered?$ce(r)?e0.PARTIAL:e0.OK:e0.APPENDING:e0.NOT_LOADED}isTimeBuffered(t,n,r){let a,i;for(let l=0;l=a&&n<=i)return!0;if(n<=a)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,n){if(n.frag.sn==="initSegment"||n.frag.bitrateTest)return;const r=n.frag,a=n.part?null:n,i=kB(r);this.fragments[i]={body:r,appendedPTS:null,loaded:a,buffered:!1,range:Object.create(null)}}onBufferAppended(t,n){const{frag:r,part:a,timeRanges:i,type:l}=n;if(r.sn==="initSegment")return;const o=r.type;if(a){let d=this.activePartLists[o];d||(this.activePartLists[o]=d=[]),d.push(a)}this.timeRanges=i;const c=i[l];this.detectEvictedFragments(l,c,o,a)}onFragBuffered(t,n){this.detectPartialFragments(n)}hasFragment(t){const n=kB(t);return!!this.fragments[n]}hasFragments(t){const{fragments:n}=this,r=Object.keys(n);if(!t)return r.length>0;for(let a=r.length;a--;){const i=n[r[a]];if((i==null?void 0:i.body.type)===t)return!0}return!1}hasParts(t){var n;return!!((n=this.activePartLists[t])!=null&&n.length)}removeFragmentsInRange(t,n,r,a,i){a&&!this.hasGaps||Object.keys(this.fragments).forEach(l=>{const o=this.fragments[l];if(!o)return;const c=o.body;c.type!==r||a&&!c.gap||c.startt&&(o.buffered||i)&&this.removeFragment(c)})}removeFragment(t){const n=kB(t);t.clearElementaryStreamInfo();const r=this.activePartLists[t.type];if(r){const a=t.sn;this.activePartLists[t.type]=R5t(r,i=>i.fragment.sn!==a)}delete this.fragments[n],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const n=(t=this.hls)==null||(t=t.latestLevelDetails)==null?void 0:t.partList;n&&n.forEach(r=>r.clearElementaryStreamInfo())}}function $ce(s){var t,n,r;return s.buffered&&!!(s.body.gap||(t=s.range.video)!=null&&t.partial||(n=s.range.audio)!=null&&n.partial||(r=s.range.audiovideo)!=null&&r.partial)}function kB(s){return`${s.type}_${s.level}_${s.sn}`}function R5t(s,t){return s.filter(n=>{const r=t(n);return r||n.clearElementaryStreamInfo(),r})}var CP={cbc:0,ctr:1};class krr{constructor(t,n,r){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=n,this.aesMode=r}decrypt(t,n){switch(this.aesMode){case CP.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},n,t);case CP.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},n,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function Srr(s){const t=s.byteLength,n=t&&new DataView(s.buffer).getUint8(t-1);return n?s.slice(0,t-n):s}class Crr{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const n=new DataView(t),r=new Uint32Array(4);for(let a=0;a<4;a++)r[a]=n.getUint32(a*4);return r}initTable(){const t=this.sBox,n=this.invSBox,r=this.subMix,a=r[0],i=r[1],l=r[2],o=r[3],c=this.invSubMix,d=c[0],u=c[1],h=c[2],m=c[3],p=new Uint32Array(256);let f=0,x=0,y=0;for(y=0;y<256;y++)y<128?p[y]=y<<1:p[y]=y<<1^283;for(y=0;y<256;y++){let v=x^x<<1^x<<2^x<<3^x<<4;v=v>>>8^v&255^99,t[f]=v,n[v]=f;const b=p[f],N=p[b],S=p[N];let A=p[v]*257^v*16843008;a[f]=A<<24|A>>>8,i[f]=A<<16|A>>>16,l[f]=A<<8|A>>>24,o[f]=A,A=S*16843009^N*65537^b*257^f*16843008,d[v]=A<<24|A>>>8,u[v]=A<<16|A>>>16,h[v]=A<<8|A>>>24,m[v]=A,f?(f=b^p[p[p[S^b]]],x^=p[p[x]]):f=x=1}}expandKey(t){const n=this.uint8ArrayToUint32Array_(t);let r=!0,a=0;for(;a{const o=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(o,n,r,a);const c=this.flush();c?i(c.buffer):l(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),n,r,a)}softwareDecrypt(t,n,r,a){const{currentIV:i,currentResult:l,remainderData:o}=this;if(a!==CP.cbc||n.byteLength!==16)return Ah.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(t=_N(o,t),this.remainderData=null);const c=this.getValidChunk(t);if(!c.length)return null;i&&(r=i);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new Crr),d.expandKey(n);const u=l;return this.currentResult=d.decrypt(c.buffer,0,r),this.currentIV=c.slice(-16).buffer,u||null}webCryptoDecrypt(t,n,r,a){if(this.key!==n||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,n,r,a));this.key=n,this.fastAesKey=new Arr(this.subtle,n,a)}return this.fastAesKey.expandKey().then(i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new krr(this.subtle,new Uint8Array(r),a).decrypt(t.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(Ah.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(t,n,r,a)))}onWebCryptoError(t,n,r,a){const i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,n,r,a);const l=this.flush();if(l)return l.buffer}throw new Error("WebCrypto"+(i?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let n=t;const r=t.length-t.length%Trr;return r!==t.length&&(n=t.slice(0,r),this.remainderData=t.slice(r)),n}logOnce(t){this.logEnabled&&(Ah.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const D5t=Math.pow(2,17);class Mrr{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,n){const r=t.url;if(!r)return Promise.reject(new kC({type:wo.NETWORK_ERROR,details:yr.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error(`Fragment does not have a ${r?"part list":"url"}`),networkDetails:null}));this.abort();const a=this.config,i=a.fLoader,l=a.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),t.gap)if(t.tagList.some(f=>f[0]==="GAP")){c(F5t(t));return}else t.gap=!1;const d=this.loader=i?new i(a):new l(a),u=O5t(t);t.loader=d;const h=I5t(a.fragLoadPolicy.default),m={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:D5t};t.stats=d.stats;const p={onSuccess:(f,x,y,v)=>{this.resetLoader(t,d);let b=f.data;y.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(b.slice(0,16)),b=b.slice(16)),o({frag:t,part:null,payload:b,networkDetails:v})},onError:(f,x,y,v)=>{this.resetLoader(t,d),c(new kC({type:wo.NETWORK_ERROR,details:yr.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:_h({url:r,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:y,stats:v}))},onAbort:(f,x,y)=>{this.resetLoader(t,d),c(new kC({type:wo.NETWORK_ERROR,details:yr.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:y,stats:f}))},onTimeout:(f,x,y)=>{this.resetLoader(t,d),c(new kC({type:wo.NETWORK_ERROR,details:yr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:y,stats:f}))}};n&&(p.onProgress=(f,x,y,v)=>n({frag:t,part:null,payload:y,networkDetails:v})),d.load(u,m,p)})}loadPart(t,n,r){this.abort();const a=this.config,i=a.fLoader,l=a.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),t.gap||n.gap){c(F5t(t,n));return}const d=this.loader=i?new i(a):new l(a),u=O5t(t,n);t.loader=d;const h=I5t(a.fragLoadPolicy.default),m={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:D5t};n.stats=d.stats,d.load(u,m,{onSuccess:(p,f,x,y)=>{this.resetLoader(t,d),this.updateStatsFromPart(t,n);const v={frag:t,part:n,payload:p.data,networkDetails:y};r(v),o(v)},onError:(p,f,x,y)=>{this.resetLoader(t,d),c(new kC({type:wo.NETWORK_ERROR,details:yr.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:n,response:_h({url:u.url,data:void 0},p),error:new Error(`HTTP Error ${p.code} ${p.text}`),networkDetails:x,stats:y}))},onAbort:(p,f,x)=>{t.stats.aborted=n.stats.aborted,this.resetLoader(t,d),c(new kC({type:wo.NETWORK_ERROR,details:yr.INTERNAL_ABORTED,fatal:!1,frag:t,part:n,error:new Error("Aborted"),networkDetails:x,stats:p}))},onTimeout:(p,f,x)=>{this.resetLoader(t,d),c(new kC({type:wo.NETWORK_ERROR,details:yr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:n,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:x,stats:p}))}})})}updateStatsFromPart(t,n){const r=t.stats,a=n.stats,i=a.total;if(r.loaded+=a.loaded,i){const c=Math.round(t.duration/n.duration),d=Math.min(Math.round(r.loaded/i),c),h=(c-d)*Math.round(r.loaded/d);r.total=r.loaded+h}else r.total=Math.max(r.loaded,r.total);const l=r.loading,o=a.loading;l.start?l.first+=o.first-o.start:(l.start=o.start,l.first=o.first),l.end=o.end}resetLoader(t,n){t.loader=null,this.loader===n&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),n.destroy()}}function O5t(s,t=null){const n=t||s,r={frag:s,part:t,responseType:"arraybuffer",url:n.url,headers:{},rangeStart:0,rangeEnd:0},a=n.byteRangeStartOffset,i=n.byteRangeEndOffset;if(Bi(a)&&Bi(i)){var l;let o=a,c=i;if(s.sn==="initSegment"&&Prr((l=s.decryptdata)==null?void 0:l.method)){const d=i-a;d%16&&(c=i+(16-d%16)),a!==0&&(r.resetIV=!0,o=a-16)}r.rangeStart=o,r.rangeEnd=c}return r}function F5t(s,t){const n=new Error(`GAP ${s.gap?"tag":"attribute"} found`),r={type:wo.MEDIA_ERROR,details:yr.FRAG_GAP,fatal:!1,frag:s,error:n,networkDetails:null};return t&&(r.part=t),(t||s).stats.aborted=!0,new kC(r)}function Prr(s){return s==="AES-128"||s==="AES-256"}class kC extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class Jss extends PN{constructor(t,n){super(t,n),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Ort{constructor(t,n,r,a=0,i=-1,l=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=Vce(),this.buffering={audio:Vce(),video:Vce(),audiovideo:Vce()},this.level=t,this.sn=n,this.id=r,this.size=a,this.part=i,this.partial=l}}function Vce(){return{start:0,executeStart:0,executeEnd:0,end:0}}const z5t={length:0,start:()=>0,end:()=>0};class uc{static isBuffered(t,n){if(t){const r=uc.getBuffered(t);for(let a=r.length;a--;)if(n>=r.start(a)&&n<=r.end(a))return!0}return!1}static bufferedRanges(t){if(t){const n=uc.getBuffered(t);return uc.timeRangesToArray(n)}return[]}static timeRangesToArray(t){const n=[];for(let r=0;r1&&t.sort((u,h)=>u.start-h.start||h.end-u.end);let a=-1,i=[];if(r)for(let u=0;u=t[u].start&&n<=t[u].end&&(a=u);const h=i.length;if(h){const m=i[h-1].end;t[u].start-mm&&(i[h-1].end=t[u].end):i.push(t[u])}else i.push(t[u])}else i=t;let l=0,o,c=n,d=n;for(let u=0;u=h&&n<=m&&(a=u),n+r>=h&&n{const a=r.substring(2,r.length-1),i=n==null?void 0:n[a];return i===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${a}"`)),r):i})}return t}function U5t(s,t,n){let r=s.variableList;r||(s.variableList=r={});let a,i;if("QUERYPARAM"in t){a=t.QUERYPARAM;try{const l=new self.URL(n).searchParams;if(l.has(a))i=l.get(a);else throw new Error(`"${a}" does not match any query parameter in URI: "${n}"`)}catch(l){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${l.message}`))}}else a=t.NAME,i=t.VALUE;a in r?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${a}"`)):r[a]=i||""}function Lrr(s,t,n){const r=t.IMPORT;if(n&&r in n){let a=s.variableList;a||(s.variableList=a={}),a[r]=n[r]}else s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}const Irr=/^(\d+)x(\d+)$/,q5t=/(.+?)=(".*?"|.*?)(?:,|$)/g;class uf{constructor(t,n){typeof t=="string"&&(t=uf.parseAttrList(t,n)),Yh(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>t.substring(0,2)==="X-")}decimalInteger(t){const n=parseInt(this[t],10);return n>Number.MAX_SAFE_INTEGER?1/0:n}hexadecimalInteger(t){if(this[t]){let n=(this[t]||"0x").slice(2);n=(n.length&1?"0":"")+n;const r=new Uint8Array(n.length/2);for(let a=0;aNumber.MAX_SAFE_INTEGER?1/0:n}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,n){const r=this[t];return r?parseFloat(r):n}enumeratedString(t){return this[t]}enumeratedStringList(t,n){const r=this[t];return(r?r.split(/[ ,]+/):[]).reduce((a,i)=>(a[i.toLowerCase()]=!0,a),n)}bool(t){return this[t]==="YES"}decimalResolution(t){const n=Irr.exec(this[t]);if(n!==null)return{width:parseInt(n[1],10),height:parseInt(n[2],10)}}static parseAttrList(t,n){let r;const a={},i='"';for(q5t.lastIndex=0;(r=q5t.exec(t))!==null;){const l=r[1].trim();let o=r[2];const c=o.indexOf(i)===0&&o.lastIndexOf(i)===o.length-1;let d=!1;if(c)o=o.slice(1,-1);else switch(l){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(n&&(c||d))o=DKe(n,o);else if(!d&&!c)switch(l){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Ah.warn(`${t}: attribute ${l} is missing quotes`)}a[l]=o}return a}}const Rrr="com.apple.hls.interstitial";function Drr(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function Orr(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class tns{constructor(t,n,r=0){var a;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(n==null?void 0:n.tagAnchor)||null,this.tagOrder=(a=n==null?void 0:n.tagOrder)!=null?a:r,n){const i=n.attr;for(const l in i)if(Object.prototype.hasOwnProperty.call(t,l)&&t[l]!==i[l]){Ah.warn(`DATERANGE tag attribute: "${l}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=l;break}t=Yh(new uf({}),i,t)}if(this.attr=t,n?(this._startDate=n._startDate,this._cue=n._cue,this._endDate=n._endDate,this._dateAtEnd=n._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const i=(n==null?void 0:n.endDate)||new Date(this.attr["END-DATE"]);Bi(i.getTime())&&(this._endDate=i)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return t===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return t===null||t.programDateTime===null?(Ah.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const n=this.duration;return n!==null?this._dateAtEnd=new Date(this._startDate.getTime()+n*1e3):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(Bi(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===Rrr}get isValid(){return!!this.id&&!this._badValueForSameId&&Bi(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const Frr=10;class zrr{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t){this.advanced=!0,this.updated=!0;return}const n=this.lastPartSn-t.lastPartSn,r=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!r||!!n||!this.live,this.advanced=this.endSN>t.endSN||n>0||n===0&&r>0,this.updated||this.advanced?this.misses=Math.floor(t.misses*.6):this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(n=>{let r=n.decryptdata;return r||(n.setKeyFormat(t.keyFormat),r=n.decryptdata),!!r&&t.matches(r)})}get hasProgramDateTime(){return this.fragments.length?Bi(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Frr}get drift(){const t=this.driftEndTime-this.driftStartTime;return t>0?(this.driftEnd-this.driftStart)*1e3/t:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const n=this.lastPartIndex;if(n!==-1){for(let r=t.length;r--;)if(t[r].index>n)return t[r].index;return n}}return 0}get lastPartSn(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}}function ETe(s,t){return s.length===t.length?!s.some((n,r)=>n!==t[r]):!1}function $5t(s,t){return!s&&!t?!0:!s||!t?!1:ETe(s,t)}function c$(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function Frt(s){switch(s){case"AES-128":case"AES-256":return CP.cbc;case"AES-256-CTR":return CP.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function zrt(s){return Uint8Array.from(atob(s),t=>t.charCodeAt(0))}function OKe(s){return Uint8Array.from(unescape(encodeURIComponent(s)),t=>t.charCodeAt(0))}function Brr(s){const t=OKe(s).subarray(0,16),n=new Uint8Array(16);return n.set(t,16-t.length),n}function sns(s){const t=function(r,a,i){const l=r[a];r[a]=r[i],r[i]=l};t(s,0,3),t(s,1,2),t(s,4,5),t(s,6,7)}function nns(s){const t=s.split(":");let n=null;if(t[0]==="data"&&t.length===2){const r=t[1].split(";"),a=r[r.length-1].split(",");if(a.length===2){const i=a[0]==="base64",l=a[1];i?(r.splice(-1,1),n=zrt(l)):n=Brr(l)}}return n}const TTe=typeof self<"u"?self:void 0;var xf={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Jy={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function n3e(s){switch(s){case Jy.FAIRPLAY:return xf.FAIRPLAY;case Jy.PLAYREADY:return xf.PLAYREADY;case Jy.WIDEVINE:return xf.WIDEVINE;case Jy.CLEARKEY:return xf.CLEARKEY}}function Lze(s){switch(s){case xf.FAIRPLAY:return Jy.FAIRPLAY;case xf.PLAYREADY:return Jy.PLAYREADY;case xf.WIDEVINE:return Jy.WIDEVINE;case xf.CLEARKEY:return Jy.CLEARKEY}}function cX(s){const{drmSystems:t,widevineLicenseUrl:n}=s,r=t?[xf.FAIRPLAY,xf.WIDEVINE,xf.PLAYREADY,xf.CLEARKEY].filter(a=>!!t[a]):[];return!r[xf.WIDEVINE]&&n&&r.push(xf.WIDEVINE),r}const rns=function(s){return TTe!=null&&(s=TTe.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function Urr(s,t,n,r){let a;switch(s){case xf.FAIRPLAY:a=["cenc","sinf"];break;case xf.WIDEVINE:case xf.PLAYREADY:a=["cenc"];break;case xf.CLEARKEY:a=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return qrr(a,t,n,r)}function qrr(s,t,n,r){return[{initDataTypes:s,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:t.map(i=>({contentType:`audio/mp4; codecs=${i}`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null})),videoCapabilities:n.map(i=>({contentType:`video/mp4; codecs=${i}`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}))}]}function $rr(s){var t;return!!s&&(s.sessionType==="persistent-license"||!!((t=s.sessionTypes)!=null&&t.some(n=>n==="persistent-license")))}function ans(s){const t=new Uint16Array(s.buffer,s.byteOffset,s.byteLength/2),n=String.fromCharCode.apply(null,Array.from(t)),r=n.substring(n.indexOf("<"),n.length),l=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(l){const o=l.childNodes[0]?l.childNodes[0].nodeValue:l.getAttribute("VALUE");if(o){const c=zrt(o).subarray(0,16);return sns(c),c}}return null}let SB={};class tP{static clearKeyUriToKeyIdMap(){SB={}}static setKeyIdForUri(t,n){SB[t]=n}static addKeyIdForUri(t){const n=Object.keys(SB).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,n),SB[t]=r,r}constructor(t,n,r,a=[1],i=null,l){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=n,this.keyFormat=r,this.keyFormatVersions=a,this.iv=i,this.encrypted=t?t!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!c$(t),l!=null&&l.startsWith("0x")&&(this.keyId=new Uint8Array(Lss(l)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&ETe(t.keyFormatVersions,this.keyFormatVersions)&&$5t(t.iv,this.iv)&&$5t(t.keyId,this.keyId)}isSupported(){if(this.method){if(c$(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Jy.FAIRPLAY:case Jy.WIDEVINE:case Jy.PLAYREADY:case Jy.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(t,n){if(!this.encrypted||!this.uri)return null;if(c$(this.method)){let i=this.iv;return i||(typeof t!="number"&&(Ah.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),i=Hrr(t)),new tP(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){const i=SB[this.uri];if(i&&!ETe(this.keyId,i)&&tP.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const r=nns(this.uri);if(r)switch(this.keyFormat){case Jy.WIDEVINE:if(this.pssh=r,!this.keyId){const i=Knr(r.buffer);if(i.length){var a;const l=i[0];this.keyId=(a=l.kids)!=null&&a.length?l.kids[0]:null}}this.keyId||(this.keyId=V5t(n));break;case Jy.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Wnr(i,null,r),this.keyId=ans(r);break}default:{let i=r.subarray(0,16);if(i.length!==16){const l=new Uint8Array(16);l.set(i,16-i.length),i=l}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i;i=Vrr(n),i||(i=V5t(n),i||(i=SB[this.uri])),i&&(this.keyId=i,tP.setKeyIdForUri(this.uri,i))}return this}}function Vrr(s){const t=s==null?void 0:s[Jy.WIDEVINE];return t?t.keyId:null}function V5t(s){const t=s==null?void 0:s[Jy.PLAYREADY];if(t){const n=nns(t.uri);if(n)return ans(n)}return null}function Hrr(s){const t=new Uint8Array(16);for(let n=12;n<16;n++)t[n]=s>>8*(15-n)&255;return t}const H5t=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,G5t=/#EXT-X-MEDIA:(.*)/g,Grr=/^#EXT(?:INF|-X-TARGETDURATION):/m,Ize=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Wrr=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class j4{static findGroup(t,n){for(let r=0;r0&&i.length({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:l.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(G5t.lastIndex=0;(a=G5t.exec(t))!==null;){const d=new uf(a[1],r),u=d.TYPE;if(u){const h=o[u],m=i[u]||[];i[u]=m;const p=d.LANGUAGE,f=d["ASSOC-LANGUAGE"],x=d.CHANNELS,y=d.CHARACTERISTICS,v=d["INSTREAM-ID"],b={attrs:d,bitrate:0,id:c++,groupId:d["GROUP-ID"]||"",name:d.NAME||p||"",type:u,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:p,url:d.URI?j4.resolve(d.URI,n):""};if(f&&(b.assocLang=f),x&&(b.channels=x),y&&(b.characteristics=y),v&&(b.instreamId=v),h!=null&&h.length){const N=j4.findGroup(h,b.groupId)||h[0];Z5t(b,N,"audioCodec"),Z5t(b,N,"textCodec")}m.push(b)}}return i}static parseLevelPlaylist(t,n,r,a,i,l){var o;const c={url:n},d=new zrr(n),u=d.fragments,h=[];let m=null,p=0,f=0,x=0,y=0,v=0,b=null,N=new Tze(a,c),S,A,T,L=-1,M=!1,I=null,R;if(Ize.lastIndex=0,d.m3u8=t,d.hasVariableRefs=B5t(t),((o=Ize.exec(t))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(S=Ize.exec(t))!==null;){M&&(M=!1,N=new Tze(a,c),N.playlistOffset=x,N.setStart(x),N.sn=p,N.cc=y,v&&(N.bitrate=v),N.level=r,m&&(N.initSegment=m,m.rawProgramDateTime&&(N.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),I&&(N.setByteRange(I),I=null)));const V=S[1];if(V){N.duration=parseFloat(V);const K=(" "+S[2]).slice(1);N.title=K||null,N.tagList.push(K?["INF",V,K]:["INF",V])}else if(S[3]){if(Bi(N.duration)){N.playlistOffset=x,N.setStart(x),T&&Q5t(N,T,d),N.sn=p,N.level=r,N.cc=y,u.push(N);const K=(" "+S[3]).slice(1);N.relurl=DKe(d,K),FKe(N,b,h),b=N,x+=N.duration,p++,f=0,M=!0}}else{if(S=S[0].match(Wrr),!S){Ah.warn("No matches on slow regex match for level playlist!");continue}for(A=1;A0&&J5t(d,K,S),p=d.startSN=parseInt(Z);break;case"SKIP":{d.skippedSegments&&cC(d,K,S);const le=new uf(Z,d),ue=le.decimalInteger("SKIPPED-SEGMENTS");if(Bi(ue)){d.skippedSegments+=ue;for(let ne=ue;ne--;)u.push(null);p+=ue}const se=le.enumeratedString("RECENTLY-REMOVED-DATERANGES");se&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(se.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&cC(d,K,S),d.targetduration=Math.max(parseInt(Z),1);break;case"VERSION":d.version!==null&&cC(d,K,S),d.version=parseInt(Z);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||cC(d,K,S),d.live=!1;break;case"#":(Z||Q)&&N.tagList.push(Q?[Z,Q]:[Z]);break;case"DISCONTINUITY":y++,N.tagList.push(["DIS"]);break;case"GAP":N.gap=!0,N.tagList.push([K]);break;case"BITRATE":N.tagList.push([K,Z]),v=parseInt(Z)*1e3,Bi(v)?N.bitrate=v:v=0;break;case"DATERANGE":{const le=new uf(Z,d),ue=new tns(le,d.dateRanges[le.ID],d.dateRangeTagCount);d.dateRangeTagCount++,ue.isValid||d.skippedSegments?d.dateRanges[ue.id]=ue:Ah.warn(`Ignoring invalid DATERANGE tag: "${Z}"`),N.tagList.push(["EXT-X-DATERANGE",Z]);break}case"DEFINE":{{const le=new uf(Z,d);"IMPORT"in le?Lrr(d,le,l):U5t(d,le,n)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?cC(d,K,S):u.length>0&&J5t(d,K,S),d.startCC=y=parseInt(Z);break;case"KEY":{const le=W5t(Z,n,d);if(le.isSupported()){if(le.method==="NONE"){T=void 0;break}T||(T={});const ue=T[le.keyFormat];ue!=null&&ue.matches(le)||(ue&&(T=Yh({},T)),T[le.keyFormat]=le)}else Ah.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${Z}"`);break}case"START":d.startTimeOffset=K5t(Z);break;case"MAP":{const le=new uf(Z,d);if(N.duration){const ue=new Tze(a,c);X5t(ue,le,r,T),m=ue,N.initSegment=m,m.rawProgramDateTime&&!N.rawProgramDateTime&&(N.rawProgramDateTime=m.rawProgramDateTime)}else{const ue=N.byteRangeEndOffset;if(ue){const se=N.byteRangeStartOffset;I=`${ue-se}@${se}`}else I=null;X5t(N,le,r,T),m=N,M=!0}m.cc=y;break}case"SERVER-CONTROL":{R&&cC(d,K,S),R=new uf(Z),d.canBlockReload=R.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=R.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&R.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=R.optionalFloat("PART-HOLD-BACK",0),d.holdBack=R.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&cC(d,K,S);const le=new uf(Z);d.partTarget=le.decimalFloatingPoint("PART-TARGET");break}case"PART":{let le=d.partList;le||(le=d.partList=[]);const ue=f>0?le[le.length-1]:void 0,se=f++,ne=new uf(Z,d),ie=new Lnr(ne,N,c,se,ue);le.push(ie),N.duration+=ie.duration;break}case"PRELOAD-HINT":{const le=new uf(Z,d);d.preloadHint=le;break}case"RENDITION-REPORT":{const le=new uf(Z,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(le);break}default:Ah.warn(`line parsed but not handled: ${S}`);break}}}b&&!b.relurl?(u.pop(),x-=b.duration,d.partList&&(d.fragmentHint=b)):d.partList&&(FKe(N,b,h),N.cc=y,d.fragmentHint=N,T&&Q5t(N,T,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const z=u.length,$=u[0],H=u[z-1];if(x+=d.skippedSegments*d.targetduration,x>0&&z&&H){d.averagetargetduration=x/z;const V=H.sn;d.endSN=V!=="initSegment"?V:0,d.live||(H.endList=!0),L>0&&(Yrr(u,L),$&&h.unshift($))}return d.fragmentHint&&(x+=d.fragmentHint.duration),d.totalduration=x,h.length&&d.dateRangeTagCount&&$&&ins(h,d),d.endCC=y,d}}function ins(s,t){let n=s.length;if(!n)if(t.hasProgramDateTime){const o=t.fragments[t.fragments.length-1];s.push(o),n++}else return;const r=s[n-1],a=t.live?1/0:t.totalduration,i=Object.keys(t.dateRanges);for(let o=i.length;o--;){const c=t.dateRanges[i[o]],d=c.startDate.getTime();c.tagAnchor=r.ref;for(let u=n;u--;){var l;if(((l=s[u])==null?void 0:l.sn)=o||r===0){var l;const c=(((l=n[r+1])==null?void 0:l.start)||a)-i.start;if(t<=o+c*1e3){const d=n[r].sn-s.startSN;if(d<0)return-1;const u=s.fragments;if(u.length>n.length){const m=(n[r+1]||u[u.length-1]).sn-s.startSN;for(let p=m;p>d;p--){const f=u[p].programDateTime;if(t>=f&&tr);["video","audio","text"].forEach(r=>{const a=n.filter(i=>Lrt(i,r));a.length&&(t[`${r}Codec`]=a.map(i=>i.split("/")[0]).join(","),n=n.filter(i=>a.indexOf(i)===-1))}),t.unknownCodecs=n}function Z5t(s,t,n){const r=t[n];r&&(s[n]=r)}function Yrr(s,t){let n=s[t];for(let r=t;r--;){const a=s[r];if(!a)return;a.programDateTime=n.programDateTime-a.duration*1e3,n=a}}function FKe(s,t,n){s.rawProgramDateTime?n.push(s):t!=null&&t.programDateTime&&(s.programDateTime=t.endProgramDateTime)}function X5t(s,t,n,r){s.relurl=t.URI,t.BYTERANGE&&s.setByteRange(t.BYTERANGE),s.level=n,s.sn="initSegment",r&&(s.levelkeys=r),s.initSegment=null}function Q5t(s,t,n){s.levelkeys=t;const{encryptedFragments:r}=n;(!r.length||r[r.length-1].levelkeys!==t)&&Object.keys(t).some(a=>t[a].isCommonEncryption)&&r.push(s)}function cC(s,t,n){s.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${n[0]})`)}function J5t(s,t,n){s.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${n[0]})`)}function Rze(s,t){const n=t.startPTS;if(Bi(n)){let r=0,a;t.sn>s.sn?(r=n-s.start,a=s):(r=s.start-n,a=t),a.duration!==r&&a.setDuration(r)}else t.sn>s.sn?s.cc===t.cc&&s.minEndPTS?t.setStart(s.start+(s.minEndPTS-s.start)):t.setStart(s.start+s.duration):t.setStart(Math.max(s.start-t.duration,0))}function ons(s,t,n,r,a,i,l){r-n<=0&&(l.warn("Fragment should have a positive duration",t),r=n+t.duration,i=a+t.duration);let c=n,d=r;const u=t.startPTS,h=t.endPTS;if(Bi(u)){const v=Math.abs(u-n);s&&v>s.totalduration?l.warn(`media timestamps and playlist times differ by ${v}s for level ${t.level} ${s.url}`):Bi(t.deltaPTS)?t.deltaPTS=Math.max(v,t.deltaPTS):t.deltaPTS=v,c=Math.max(n,u),n=Math.min(n,u),a=t.startDTS!==void 0?Math.min(a,t.startDTS):a,d=Math.min(r,h),r=Math.max(r,h),i=t.endDTS!==void 0?Math.max(i,t.endDTS):i}const m=n-t.start;t.start!==0&&t.setStart(n),t.setDuration(r-t.start),t.startPTS=n,t.maxStartPTS=c,t.startDTS=a,t.endPTS=r,t.minEndPTS=d,t.endDTS=i;const p=t.sn;if(!s||ps.endSN)return 0;let f;const x=p-s.startSN,y=s.fragments;for(y[x]=t,f=x;f>0;f--)Rze(y[f],y[f-1]);for(f=x;f=0;u--){const h=a[u].initSegment;if(h){r=h;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let i;Jrr(s,t,(u,h,m,p)=>{if((!t.startCC||t.skippedSegments)&&h.cc!==u.cc){const f=u.cc-h.cc;for(let x=m;x{var h;u&&(!u.initSegment||u.initSegment.relurl===((h=r)==null?void 0:h.relurl))&&(u.initSegment=r)}),t.skippedSegments){if(t.deltaUpdateFailed=l.some(u=>!u),t.deltaUpdateFailed){n.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let u=t.skippedSegments;u--;)l.shift();t.startSN=l[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=Xrr(s.dateRanges,t,n));const u=s.fragments.filter(h=>h.rawProgramDateTime);if(s.hasProgramDateTime&&!t.hasProgramDateTime)for(let h=1;h{h.elementaryStreams=u.elementaryStreams,h.stats=u.stats}),i?ons(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,n):lns(s,t),l.length&&(t.totalduration=t.edge-l[0].start),t.driftStartTime=s.driftStartTime,t.driftStart=s.driftStart;const d=t.advancedDateTime;if(t.advanced&&d){const u=t.edge;t.driftStart||(t.driftStartTime=d,t.driftStart=u),t.driftEndTime=d,t.driftEnd=u}else t.driftEndTime=s.driftEndTime,t.driftEnd=s.driftEnd,t.advancedDateTime=s.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=s.requestScheduled)}function Xrr(s,t,n){const{dateRanges:r,recentlyRemovedDateranges:a}=t,i=Yh({},s);a&&a.forEach(c=>{delete i[c]});const o=Object.keys(i).length;return o?(Object.keys(r).forEach(c=>{const d=i[c],u=new tns(r[c].attr,d);u.isValid?(i[c]=u,d||(u.tagOrder+=o)):n.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${fm(r[c].attr)}"`)}),i):r}function Qrr(s,t,n){if(s&&t){let r=0;for(let a=0,i=s.length;a<=i;a++){const l=s[a],o=t[a+r];l&&o&&l.index===o.index&&l.fragment.sn===o.fragment.sn?n(l,o):r--}}}function Jrr(s,t,n){const r=t.skippedSegments,a=Math.max(s.startSN,t.startSN)-t.startSN,i=(s.fragmentHint?1:0)+(r?t.endSN:Math.min(s.endSN,t.endSN))-t.startSN,l=t.startSN-s.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,c=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let d=a;d<=i;d++){const u=c[l+d];let h=o[d];if(r&&!h&&u&&(h=t.fragments[d]=u),u&&h){n(u,h,d,o);const m=u.relurl,p=h.relurl;if(m&&ear(m,p)){t.playlistParsingError=e4t(`media sequence mismatch ${h.sn}:`,s,t,u,h);return}else if(u.cc!==h.cc){t.playlistParsingError=e4t(`discontinuity sequence mismatch (${u.cc}!=${h.cc})`,s,t,u,h);return}}}}function e4t(s,t,n,r,a){return new Error(`${s} ${a.url} Playlist starting @${t.startSN} ${t.m3u8} Playlist starting @${n.startSN} ${n.m3u8}`)}function lns(s,t,n=!0){const r=t.startSN+t.skippedSegments-s.startSN,a=s.fragments,i=r>=0;let l=0;if(i&&rt){const i=r[r.length-1].duration*1e3;i{var r;(r=t.details)==null||r.fragments.forEach(a=>{a.level=n,a.initSegment&&(a.initSegment.level=n)})})}function ear(s,t){return s!==t&&t?s4t(s)!==s4t(t):!1}function s4t(s){return s.replace(/\?[^?]*$/,"")}function kJ(s,t){for(let r=0,a=s.length;rs.startCC)}function n4t(s,t){const n=s.start+t;s.startPTS=n,s.setStart(n),s.endPTS=n+s.duration}function mns(s,t){const n=t.fragments;for(let r=0,a=n.length;r{const{config:l,fragCurrent:o,media:c,mediaBuffer:d,state:u}=this,h=c?c.currentTime:0,m=uc.bufferInfo(d||c,h,l.maxBufferHole),p=!m.len;if(this.log(`Media seeking to ${Bi(h)?h.toFixed(3):h}, state: ${u}, ${p?"out of":"in"} buffer`),this.state===aa.ENDED)this.resetLoadingState();else if(o){const f=l.maxFragLookUpTolerance,x=o.start-f,y=o.start+o.duration+f;if(p||ym.end){const v=h>y;(hf&&(this.lastCurrentTime=h),!this.loadingParts){const x=Math.max(m.end,h),y=this.shouldLoadParts(this.getLevelDetails(),x);y&&(this.log(`LL-Part loading ON after seeking to ${h.toFixed(2)} with buffer @${x.toFixed(2)}`),this.loadingParts=y)}}this.hls.hasEnoughToStart||(this.log(`Setting ${p?"startPosition":"nextLoadPosition"} to ${h} for seek without enough to start`),this.nextLoadPosition=h,p&&(this.startPosition=h)),p&&this.state===aa.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=i,this.hls=t,this.fragmentLoader=new Mrr(t.config),this.keyLoader=r,this.fragmentTracker=n,this.config=t.config,this.decrypter=new Drt(t.config)}registerListeners(){const{hls:t}=this;t.on(Ot.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Ot.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ot.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Ot.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Ot.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Ot.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ot.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Ot.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===aa.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;t!=null&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=aa.STOPPED}get startPositionValue(){const{nextLoadPosition:t,startPosition:n}=this;return n===-1&&t?t:n}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,n){if(n.live||!this.media)return!1;const r=t.end||0,a=this.config.timelineOffset||0;if(r<=a)return!1;const i=t.buffered;this.config.maxBufferHole&&i&&i.length>1&&(t=uc.bufferedInfo(i,t.start,0));const l=t.nextStart;if(l&&l>a&&l{const l=i.frag;if(this.fragContextChanged(l)){this.warn(`${l.type} sn: ${l.sn}${i.part?" part: "+i.part.index:""} of ${this.fragInfo(l,!1,i.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(l);return}l.stats.chunkCount++,this._handleFragmentLoadProgress(i)};this._doFragLoad(t,n,r,a).then(i=>{if(!i)return;const l=this.state,o=i.frag;if(this.fragContextChanged(o)){(l===aa.FRAG_LOADING||!this.fragCurrent&&l===aa.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=aa.IDLE);return}"payload"in i&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(Ot.FRAG_LOADED,i)),this._handleFragmentLoadComplete(i)}).catch(i=>{this.state===aa.STOPPED||this.state===aa.ERROR||(this.warn(`Frag error: ${(i==null?void 0:i.message)||i}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var n;const{fragmentTracker:r}=this;if(r.getState(t)===e0.APPENDING){const i=t.type,l=this.getFwdBufferInfo(this.mediaBuffer,i),o=Math.max(t.duration,l?l.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?t.sn-c.sn:0)===1||this.reduceMaxBufferLength(o,t.duration))&&r.removeFragment(t)}else((n=this.mediaBuffer)==null?void 0:n.buffered.length)===0?r.removeAllFragments():r.hasParts(t.type)&&(r.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),r.getState(t)===e0.PARTIAL&&r.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const n=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:n,part:null,stats:n.stats,id:n.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const n=t.details;return(n==null?void 0:n.live)&&n.type!=="EVENT"&&(this.levelLastLoaded!==t||n.expired)}flushMainBuffer(t,n,r=null){if(!(t-n))return;const a={startOffset:t,endOffset:n,type:r};this.hls.trigger(Ot.BUFFER_FLUSHING,a)}_loadInitSegment(t,n){this._doFragLoad(t,n).then(r=>{const a=r==null?void 0:r.frag;if(!a||this.fragContextChanged(a)||!this.levels)throw new Error("init load aborted");return r}).then(r=>{const{hls:a}=this,{frag:i,payload:l}=r,o=i.decryptdata;if(l&&l.byteLength>0&&o!=null&&o.key&&o.iv&&c$(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(l),o.key.buffer,o.iv.buffer,Frt(o.method)).catch(d=>{throw a.trigger(Ot.ERROR,{type:wo.MEDIA_ERROR,details:yr.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:i}),d}).then(d=>{const u=self.performance.now();return a.trigger(Ot.FRAG_DECRYPTED,{frag:i,payload:d,stats:{tstart:c,tdecrypt:u}}),r.payload=d,this.completeInitSegmentLoad(r)})}return this.completeInitSegmentLoad(r)}).catch(r=>{this.state===aa.STOPPED||this.state===aa.ERROR||(this.warn(r),this.resetFragmentLoading(t))})}completeInitSegmentLoad(t){const{levels:n}=this;if(!n)throw new Error("init load aborted, missing levels");const r=t.frag.stats;this.state!==aa.STOPPED&&(this.state=aa.IDLE),t.frag.data=new Uint8Array(t.payload),r.parsing.start=r.buffering.start=self.performance.now(),r.parsing.end=r.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(t,n){var r,a;const i=t.tracks;if(i&&!n.encrypted&&((r=i.audio)!=null&&r.encrypted||(a=i.video)!=null&&a.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const l=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(n)} (media ${l?"attached mediaKeys: "+l.mediaKeys:"detached"})`);return this.warn(o.message),!l||l.mediaKeys?!1:(this.hls.trigger(Ot.ERROR,{type:wo.KEY_SYSTEM_ERROR,details:yr.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:n}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:n}=this;return!t||!n||t.sn!==n.sn||t.level!==n.level}fragBufferedComplete(t,n){const r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${n?" part: "+n.index:""} of ${this.fragInfo(t,!1,n)} > buffer:${r?nar.toString(uc.getBuffered(r)):"(detached)"})`),Fg(t)){var a;if(t.type!==io.SUBTITLE){const l=t.elementaryStreams;if(!Object.keys(l).some(o=>!!l[o])){this.state=aa.IDLE;return}}const i=(a=this.levels)==null?void 0:a[t.level];i!=null&&i.fragmentError&&(this.log(`Resetting level fragment error count of ${i.fragmentError} on frag buffered`),i.fragmentError=0)}this.state=aa.IDLE}_handleFragmentLoadComplete(t){const{transmuxer:n}=this;if(!n)return;const{frag:r,part:a,partsLoaded:i}=t,l=!i||i.length===0||i.some(c=>!c),o=new Ort(r.level,r.sn,r.stats.chunkCount+1,0,a?a.index:-1,!l);n.flush(o)}_handleFragmentLoadProgress(t){}_doFragLoad(t,n,r=null,a){var i;this.fragCurrent=t;const l=n.details;if(!this.levels||!l)throw new Error(`frag load aborted, missing level${l?"":" detail"}s`);let o=null;if(t.encrypted&&!((i=t.decryptdata)!=null&&i.key)){if(this.log(`Loading key for ${t.sn} of [${l.startSN}-${l.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=aa.KEY_LOADING,this.fragCurrent=t,o=this.keyLoader.load(t).then(m=>{if(!this.fragContextChanged(m.frag))return this.hls.trigger(Ot.KEY_LOADED,m),this.state===aa.KEY_LOADING&&(this.state=aa.IDLE),m}),this.hls.trigger(Ot.KEY_LOADING,{frag:t}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else t.encrypted||(o=this.keyLoader.loadClear(t,l.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));const c=this.fragPrevious;if(Fg(t)&&(!c||t.sn!==c.sn)){const m=this.shouldLoadParts(n.details,t.end);m!==this.loadingParts&&(this.log(`LL-Part loading ${m?"ON":"OFF"} loading sn ${c==null?void 0:c.sn}->${t.sn}`),this.loadingParts=m)}if(r=Math.max(t.start,r||0),this.loadingParts&&Fg(t)){const m=l.partList;if(m&&a){r>l.fragmentEnd&&l.fragmentHint&&(t=l.fragmentHint);const p=this.getNextPart(m,t,r);if(p>-1){const f=m[p];t=this.fragCurrent=f.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${f.index} (${p}/${m.length-1}) of ${this.fragInfo(t,!1,f)}) cc: ${t.cc} [${l.startSN}-${l.endSN}], target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=f.start+f.duration,this.state=aa.FRAG_LOADING;let x;return o?x=o.then(y=>!y||this.fragContextChanged(y.frag)?null:this.doFragPartsLoad(t,f,n,a)).catch(y=>this.handleFragLoadError(y)):x=this.doFragPartsLoad(t,f,n,a).catch(y=>this.handleFragLoadError(y)),this.hls.trigger(Ot.FRAG_LOADING,{frag:t,part:f,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):x}else if(!t.url||this.loadedEndOfParts(m,r))return Promise.resolve(null)}}if(Fg(t)&&this.loadingParts){var d;this.log(`LL-Part loading OFF after next part miss @${r.toFixed(2)} Check buffer at sn: ${t.sn} loaded parts: ${(d=l.partList)==null?void 0:d.filter(m=>m.loaded).map(m=>`[${m.start}-${m.end}]`)}`),this.loadingParts=!1}else if(!t.url)return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)}) cc: ${t.cc} ${"["+l.startSN+"-"+l.endSN+"]"}, target: ${parseFloat(r.toFixed(3))}`),Bi(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=aa.FRAG_LOADING;const u=this.config.progressive&&t.type!==io.SUBTITLE;let h;return u&&o?h=o.then(m=>!m||this.fragContextChanged(m.frag)?null:this.fragmentLoader.load(t,a)).catch(m=>this.handleFragLoadError(m)):h=Promise.all([this.fragmentLoader.load(t,u?a:void 0),o]).then(([m])=>(!u&&a&&a(m),m)).catch(m=>this.handleFragLoadError(m)),this.hls.trigger(Ot.FRAG_LOADING,{frag:t,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(t,n,r,a){return new Promise((i,l)=>{var o;const c=[],d=(o=r.details)==null?void 0:o.partList,u=h=>{this.fragmentLoader.loadPart(t,h,a).then(m=>{c[h.index]=m;const p=m.part;this.hls.trigger(Ot.FRAG_LOADED,m);const f=t4t(r.details,t.sn,h.index+1)||uns(d,t.sn,h.index+1);if(f)u(f);else return i({frag:t,part:p,partsLoaded:c})}).catch(l)};u(n)})}handleFragLoadError(t){if("data"in t){const n=t.data;n.frag&&n.details===yr.INTERNAL_ABORTED?this.handleFragLoadAborted(n.frag,n.part):n.frag&&n.type===wo.KEY_SYSTEM_ERROR?(n.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(n.frag)):this.hls.trigger(Ot.ERROR,n)}else this.hls.trigger(Ot.ERROR,{type:wo.OTHER_ERROR,details:yr.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const n=this.getCurrentContext(t);if(!n||this.state!==aa.PARSING){!this.fragCurrent&&this.state!==aa.STOPPED&&this.state!==aa.ERROR&&(this.state=aa.IDLE);return}const{frag:r,part:a,level:i}=n,l=self.performance.now();r.stats.parsing.end=l,a&&(a.stats.parsing.end=l);const o=this.getLevelDetails(),d=o&&r.sn>o.endSN||this.shouldLoadParts(o,r.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${r.end.toFixed(2)}`),this.loadingParts=d),this.updateLevelTiming(r,a,i,t.partial)}shouldLoadParts(t,n){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList){var r;const i=t.partList[0];if(i.fragment.type===io.SUBTITLE)return!1;const l=i.end+(((r=t.fragmentHint)==null?void 0:r.duration)||0);if(n>=l){var a;if((this.hls.hasEnoughToStart?((a=this.media)==null?void 0:a.currentTime)||this.lastCurrentTime:this.getLoadPosition())>i.start-i.fragment.duration)return!0}}}return!1}getCurrentContext(t){const{levels:n,fragCurrent:r}=this,{level:a,sn:i,part:l}=t;if(!(n!=null&&n[a]))return this.warn(`Levels object was unset while buffering fragment ${i} of ${this.playlistLabel()} ${a}. The current chunk will not be buffered.`),null;const o=n[a],c=o.details,d=l>-1?t4t(c,i,l):null,u=d?d.fragment:dns(c,i,r);return u?(r&&r!==u&&(u.stats=r.stats),{frag:u,part:d,level:o}):null}bufferFragmentData(t,n,r,a,i){if(this.state!==aa.PARSING)return;const{data1:l,data2:o}=t;let c=l;if(o&&(c=_N(l,o)),!c.length)return;const d=this.initPTS[n.cc],u=d?-d.baseTime/d.timescale:void 0,h={type:t.type,frag:n,part:r,chunkMeta:a,offset:u,parent:n.type,data:c};if(this.hls.trigger(Ot.BUFFER_APPENDING,h),t.dropped&&t.independent&&!r){if(i)return;this.flushBufferGap(n)}}flushBufferGap(t){const n=this.media;if(!n)return;if(!uc.isBuffered(n,n.currentTime)){this.flushMainBuffer(0,t.start);return}const r=n.currentTime,a=uc.bufferInfo(n,r,0),i=t.duration,l=Math.min(this.config.maxFragLookUpTolerance*2,i*.25),o=Math.max(Math.min(t.start-l,a.end-l),r+l);t.start-o>l&&this.flushMainBuffer(o,t.start)}getFwdBufferInfo(t,n){var r;const a=this.getLoadPosition();if(!Bi(a))return null;const l=this.lastCurrentTime>a||(r=this.media)!=null&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,a,n,l)}getFwdBufferInfoAtPos(t,n,r,a){const i=uc.bufferInfo(t,n,a);if(i.len===0&&i.nextStart!==void 0){const l=this.fragmentTracker.getBufferedFrag(n,r);if(l&&(i.nextStart<=l.end||l.gap)){const o=Math.max(Math.min(i.nextStart,l.end)-n,a);return uc.bufferInfo(t,n,o)}}return i}getMaxBufferLength(t){const{config:n}=this;let r;return t?r=Math.max(8*n.maxBufferSize/t,n.maxBufferLength):r=n.maxBufferLength,Math.min(r,n.maxMaxBufferLength)}exceedsMaxBuffer(t,n,r){const a=t.nextStart;if(a&&r.start>a){const i=t.buffered;if(i){let l=t.len;const o=t.bufferedIndex;for(let c=i.length-1;c>o;c--)i[c].start=n}}return!1}reduceMaxBufferLength(t,n){const r=this.config,a=Math.max(Math.min(t-n,r.maxBufferLength),n),i=Math.max(t-n*3,r.maxMaxBufferLength/2,a);return i>=a?(r.maxMaxBufferLength=i,this.warn(`Reduce max buffer length to ${i}s`),!0):!1}getAppendedFrag(t,n=io.MAIN){const r=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,n):null;return r&&"fragment"in r?r.fragment:r}getNextFragment(t,n){const r=n.fragments,a=r.length;if(!a)return null;const{config:i}=this,l=n.fragmentStart,o=i.lowLatencyMode&&!!n.partList;let c=null;if(n.live){const h=i.initialLiveManifestSize;if(a=l?(y=p,v=p===m?"config":"next load start"):f!==null?(y=f,v="live edge"):(y=t,v="buffer pos"),y=i){const c=l.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${a}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,l}get primaryPrefetch(){if(r4t(this.config)){var t;if((t=this.hls.interstitialsManager)==null||(t=t.playingItem)==null?void 0:t.event)return!0}return!1}filterReplacedPrimary(t,n){if(!t)return t;if(r4t(this.config)&&t.type!==io.SUBTITLE){const r=this.hls.interstitialsManager,a=r==null?void 0:r.bufferingItem;if(a){const l=a.event;if(l){if(l.appendInPlace||Math.abs(t.start-a.start)>1||a.start===0)return null}else if(t.end<=a.start&&(n==null?void 0:n.live)===!1||t.start>a.end&&a.nextEvent&&(a.nextEvent.appendInPlace||t.start-a.end>1))return null}const i=r==null?void 0:r.playerQueue;if(i)for(let l=i.length;l--;){const o=i[l].interstitial;if(o.appendInPlace&&t.start>=o.startTime&&t.end<=o.resumeTime)return null}}return t}mapToInitFragWhenRequired(t){return t!=null&&t.initSegment&&!t.initSegment.data&&!this.bitrateTest?t.initSegment:t}getNextPart(t,n,r){let a=-1,i=!1,l=!0;for(let o=0,c=t.length;o-1&&rr.start)return!0}return!1}getInitialLiveFragment(t){const n=t.fragments,r=this.fragPrevious;let a=null;if(r){if(t.hasProgramDateTime&&(a=vrr(n,r.endProgramDateTime,this.config.maxFragLookUpTolerance),a&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${r.programDateTime}`)),!a){const i=r.sn+1;if(i>=t.startSN&&i<=t.endSN){const l=n[i-t.startSN];r.cc===l.cc&&(a=l,this.log(`Live playlist, switching playlist, load frag with next SN: ${a.sn}`))}a||(a=Zss(t,r.cc,r.end),a&&this.log(`Live playlist, switching playlist, load frag with same CC: ${a.sn}`))}}else{const i=this.hls.liveSyncPosition;i!==null&&(a=this.getFragmentAtPosition(i,this.bitrateTest?t.fragmentEnd:t.edge,t))}return a}getFragmentAtPosition(t,n,r){const{config:a}=this;let{fragPrevious:i}=this,{fragments:l,endSN:o}=r;const{fragmentHint:c}=r,{maxFragLookUpTolerance:d}=a,u=r.partList,h=!!(this.loadingParts&&u!=null&&u.length&&c);h&&!this.bitrateTest&&u[u.length-1].fragment.sn===c.sn&&(l=l.concat(c),o=c.sn);let m;if(tn-d||(p=this.media)!=null&&p.paused||!this.startFragRequested?0:d;m=i9(i,l,t,x)}else m=l[l.length-1];if(m){const f=m.sn-r.startSN,x=this.fragmentTracker.getState(m);if((x===e0.OK||x===e0.PARTIAL&&m.gap)&&(i=m),i&&m.sn===i.sn&&(!h||u[0].fragment.sn>m.sn||!r.live)&&m.level===i.level){const v=l[f+1];m.sn${t.startSN} fragments: ${a}`),c}return i}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,t.partTarget*3)}setStartPosition(t,n){let r=this.startPosition;r=0&&(r=this.nextLoadPosition),r}handleFragLoadAborted(t,n){this.transmuxer&&t.type===this.playlistType&&Fg(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${n?" part "+n.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){(!this.fragCurrent||!this.fragContextChanged(t)&&this.state!==aa.FRAG_LOADING_WAITING_RETRY)&&(this.state=aa.IDLE)}onFragmentOrKeyLoadError(t,n){var r;if(n.chunkMeta&&!n.frag){const v=this.getCurrentContext(n.chunkMeta);v&&(n.frag=v.frag)}const a=n.frag;if(!a||a.type!==t||!this.levels)return;if(this.fragContextChanged(a)){var i;this.warn(`Frag load error must match current frag to retry ${a.url} > ${(i=this.fragCurrent)==null?void 0:i.url}`);return}const l=n.details===yr.FRAG_GAP;l&&this.fragmentTracker.fragBuffered(a,!0);const o=n.errorAction;if(!o){this.state=aa.ERROR;return}const{action:c,flags:d,retryCount:u=0,retryConfig:h}=o,m=!!h,p=m&&c===Yy.RetryRequest,f=m&&!o.resolved&&d===vw.MoveAllAlternatesMatchingHost,x=(r=this.hls.latestLevelDetails)==null?void 0:r.live;if(!p&&f&&Fg(a)&&!a.endList&&x&&!Qss(n))this.resetFragmentErrors(t),this.treatAsGap(a),o.resolved=!0;else if((p||f)&&u=n||r&&!RKe(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=aa.IDLE)}reduceLengthAndFlushBuffer(t){if(this.state===aa.PARSING||this.state===aa.PARSED){const n=t.frag,r=t.parent,a=this.getFwdBufferInfo(this.mediaBuffer,r),i=a&&a.len>.5;i&&this.reduceMaxBufferLength(a.len,(n==null?void 0:n.duration)||10);const l=!i;return l&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${r} buffer`),n&&(this.fragmentTracker.removeFragment(n),this.nextLoadPosition=n.start),this.resetLoadingState(),l}return!1}resetFragmentErrors(t){t===io.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==aa.STOPPED&&(this.state=aa.IDLE)}afterBufferFlushed(t,n,r){if(!t)return;const a=uc.getBuffered(t);this.fragmentTracker.detectEvictedFragments(n,a,r),this.state===aa.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==aa.STOPPED&&(this.state=aa.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.levelLastLoaded,n=t?t.details:null;n!=null&&n.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(n,n.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${t.level===-1?"":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,n,r,a){const i=r.details;if(!i){this.warn("level.details undefined");return}if(!Object.keys(t.elementaryStreams).reduce((c,d)=>{const u=t.elementaryStreams[d];if(u){const h=u.endPTS-u.startPTS;if(h<=0)return this.warn(`Could not parse fragment ${t.sn} ${d} duration reliably (${h})`),c||!1;const m=a?0:ons(i,t,u.startPTS,u.endPTS,u.startDTS,u.endDTS,this);return this.hls.trigger(Ot.LEVEL_PTS_UPDATED,{details:i,level:r,drift:m,type:d,frag:t,start:u.startPTS,end:u.endPTS}),!0}return c},!1)){var o;const c=((o=this.transmuxer)==null?void 0:o.error)===null;if((r.fragmentError===0||c&&(r.fragmentError<2||t.endList))&&this.treatAsGap(t,r),c){const d=new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(d.message),this.hls.trigger(Ot.ERROR,{type:wo.MEDIA_ERROR,details:yr.FRAG_PARSING_ERROR,fatal:!1,error:d,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${r.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=aa.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${n?" part: "+n.index:""} of ${this.fragInfo(t,!1,n)})`),this.hls.trigger(Ot.FRAG_PARSED,{frag:t,part:n})}playlistLabel(){return this.playlistType===io.MAIN?"level":"track"}fragInfo(t,n=!0,r){var a,i;return`${this.playlistLabel()} ${t.level} (${r?"part":"frag"}:[${((a=n&&!r?t.startPTS:(r||t).start)!=null?a:NaN).toFixed(3)}-${((i=n&&!r?t.endPTS:(r||t).end)!=null?i:NaN).toFixed(3)}]${r&&t.type==="main"?"INDEPENDENT="+(r.independent?"YES":"NO"):""}`}treatAsGap(t,n){n&&n.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)}resetTransmuxer(){var t;(t=this.transmuxer)==null||t.reset()}recoverWorkerError(t){t.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const n=this._state;n!==t&&(this._state=t,this.log(`${n}->${t}`))}get state(){return this._state}}function r4t(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class fns{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:n}=this;let r;if(t.length)t.length===1?r=t[0]:r=rar(t,n);else return new Uint8Array(0);return this.reset(),r}reset(){this.chunks.length=0,this.dataLength=0}}function rar(s,t){const n=new Uint8Array(t);let r=0;for(let a=0;a0)return s.subarray(n,n+r)}function uar(s,t,n,r){const a=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],i=t[n+2],l=i>>2&15;if(l>12){const p=new Error(`invalid ADTS sampling index:${l}`);s.emit(Ot.ERROR,Ot.ERROR,{type:wo.MEDIA_ERROR,details:yr.FRAG_PARSING_ERROR,fatal:!0,error:p,reason:p.message});return}const o=(i>>6&3)+1,c=t[n+3]>>6&3|(i&1)<<2,d="mp4a.40."+o,u=a[l];let h=l;(o===5||o===29)&&(h-=3);const m=[o<<3|(h&14)>>1,(h&1)<<7|c<<3];return Ah.log(`manifest codec:${r}, parsed codec:${d}, channels:${c}, rate:${u} (ADTS object type:${o} sampling index:${l})`),{config:m,samplerate:u,channelCount:c,codec:d,parsedCodec:d,manifestCodec:r}}function xns(s,t){return s[t]===255&&(s[t+1]&246)===240}function yns(s,t){return s[t+1]&1?7:9}function $rt(s,t){return(s[t+3]&3)<<11|s[t+4]<<3|(s[t+5]&224)>>>5}function har(s,t){return t+5=s.length)return!1;const r=$rt(s,t);if(r<=n)return!1;const a=t+r;return a===s.length||PTe(s,a)}return!1}function vns(s,t,n,r,a){if(!s.samplerate){const i=uar(t,n,r,a);if(!i)return;Yh(s,i)}}function bns(s){return 1024*9e4/s}function far(s,t){const n=yns(s,t);if(t+n<=s.length){const r=$rt(s,t)-n;if(r>0)return{headerLength:n,frameLength:r}}}function _ns(s,t,n,r,a){const i=bns(s.samplerate),l=r+a*i,o=far(t,n);let c;if(o){const{frameLength:h,headerLength:m}=o,p=m+h,f=Math.max(0,n+p-t.length);f?(c=new Uint8Array(p-m),c.set(t.subarray(n+m,t.length),0)):c=t.subarray(n+m,n+p);const x={unit:c,pts:l};return f||s.samples.push(x),{sample:x,length:p,missing:f}}const d=t.length-n;return c=new Uint8Array(d),c.set(t.subarray(n,t.length),0),{sample:{unit:c,pts:l},length:d,missing:-1}}function gar(s,t){return qrt(s,t)&&XIe(s,t+6)+10<=s.length-t}function xar(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function Oze(s,t=0,n=1/0){return yar(s,t,n,Uint8Array)}function yar(s,t,n,r){const a=bar(s);let i=1;"BYTES_PER_ELEMENT"in r&&(i=r.BYTES_PER_ELEMENT);const l=_ar(s)?s.byteOffset:0,o=(l+s.byteLength)/i,c=(l+t)/i,d=Math.floor(Math.max(0,Math.min(c,o))),u=Math.floor(Math.min(d+Math.max(n,0),o));return new r(a,d,u-d)}function bar(s){return s instanceof ArrayBuffer?s:s.buffer}function _ar(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function war(s){const t={key:s.type,description:"",data:"",mimeType:null,pictureType:null},n=3;if(s.size<2)return;if(s.data[0]!==n){console.log("Ignore frame with unrecognized character encoding");return}const r=s.data.subarray(1).indexOf(0);if(r===-1)return;const a=uj(Oze(s.data,1,r)),i=s.data[2+r],l=s.data.subarray(3+r).indexOf(0);if(l===-1)return;const o=uj(Oze(s.data,3+r,l));let c;return a==="-->"?c=uj(Oze(s.data,4+r+l)):c=xar(s.data.subarray(4+r+l)),t.mimeType=a,t.pictureType=i,t.description=o,t.data=c,t}function jar(s){if(s.size<2)return;const t=uj(s.data,!0),n=new Uint8Array(s.data.subarray(t.length+1));return{key:s.type,info:t,data:n.buffer}}function Nar(s){if(s.size<2)return;if(s.type==="TXXX"){let n=1;const r=uj(s.data.subarray(n),!0);n+=r.length+1;const a=uj(s.data.subarray(n));return{key:s.type,info:r,data:a}}const t=uj(s.data.subarray(1));return{key:s.type,info:"",data:t}}function kar(s){if(s.type==="WXXX"){if(s.size<2)return;let n=1;const r=uj(s.data.subarray(n),!0);n+=r.length+1;const a=uj(s.data.subarray(n));return{key:s.type,info:r,data:a}}const t=uj(s.data);return{key:s.type,info:"",data:t}}function Sar(s){return s.type==="PRIV"?jar(s):s.type[0]==="W"?kar(s):s.type==="APIC"?war(s):Nar(s)}function Car(s){const t=String.fromCharCode(s[0],s[1],s[2],s[3]),n=XIe(s,4),r=10;return{type:t,size:n,data:s.subarray(r,r+n)}}const Hce=10,Aar=10;function wns(s){let t=0;const n=[];for(;qrt(s,t);){const r=XIe(s,t+6);s[t+5]>>6&1&&(t+=Hce),t+=Hce;const a=t+r;for(;t+Aar0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Dw.audioId3,duration:Number.POSITIVE_INFINITY});a{if(Bi(s))return s*90;const r=n?n.baseTime*9e4/n.timescale:0;return t*9e4+r};let Gce=null;const Mar=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],Par=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Lar=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Iar=[0,1,1,4];function Nns(s,t,n,r,a){if(n+24>t.length)return;const i=kns(t,n);if(i&&n+i.frameLength<=t.length){const l=i.samplesPerFrame*9e4/i.sampleRate,o=r+a*l,c={unit:t.subarray(n,n+i.frameLength),pts:o,dts:o};return s.config=[],s.channelCount=i.channelCount,s.samplerate=i.sampleRate,s.samples.push(c),{sample:c,length:i.frameLength,missing:0}}}function kns(s,t){const n=s[t+1]>>3&3,r=s[t+1]>>1&3,a=s[t+2]>>4&15,i=s[t+2]>>2&3;if(n!==1&&a!==0&&a!==15&&i!==3){const l=s[t+2]>>1&1,o=s[t+3]>>6,c=n===3?3-r:r===3?3:4,d=Mar[c*14+a-1]*1e3,h=Par[(n===3?0:n===2?1:2)*3+i],m=o===3?1:2,p=Lar[n][r],f=Iar[r],x=p*8*f,y=Math.floor(p*d/h+l)*f;if(Gce===null){const N=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Gce=N?parseInt(N[1]):0}return!!Gce&&Gce<=87&&r===2&&d>=224e3&&o===0&&(s[t+3]=s[t+3]|128),{sampleRate:h,channelCount:m,frameLength:y,samplesPerFrame:x}}}function Grt(s,t){return s[t]===255&&(s[t+1]&224)===224&&(s[t+1]&6)!==0}function Sns(s,t){return t+1{let n=0,r=5;t+=r;const a=new Uint32Array(1),i=new Uint32Array(1),l=new Uint8Array(1);for(;r>0;){l[0]=s[t];const o=Math.min(r,8),c=8-o;i[0]=4278190080>>>24+c<>c,n=n?n<t.length||t[n]!==11||t[n+1]!==119)return-1;const i=t[n+4]>>6;if(i>=3)return-1;const o=[48e3,44100,32e3][i],c=t[n+4]&63,u=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][c*3+i]*2;if(n+u>t.length)return-1;const h=t[n+6]>>5;let m=0;h===2?m+=2:(h&1&&h!==1&&(m+=2),h&4&&(m+=2));const p=(t[n+6]<<8|t[n+7])>>12-m&1,x=[2,1,2,3,3,4,4,5][h]+p,y=t[n+5]>>3,v=t[n+5]&7,b=new Uint8Array([i<<6|y<<1|v>>2,(v&3)<<6|h<<3|p<<2|c>>4,c<<4&224]),N=1536/o*9e4,S=r+a*N,A=t.subarray(n,n+u);return s.config=b,s.channelCount=x,s.samplerate=o,s.samples.push({unit:A,pts:S}),u}class Far extends Hrt{resetInitSegment(t,n,r,a){super.resetInitSegment(t,n,r,a),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:n,duration:a,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const n=Yte(t,0);let r=(n==null?void 0:n.length)||0;if(n&&t[r]===11&&t[r+1]===119&&Vrt(n)!==void 0&&Ans(t,r)<=16)return!1;for(let a=t.length;r{const l=Hnr(i);if(zar.test(l.schemeIdUri)){const o=i4t(l,n);let c=l.eventDuration===4294967295?Number.POSITIVE_INFINITY:l.eventDuration/l.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const d=l.payload;r.samples.push({data:d,len:d.byteLength,dts:o,pts:o,type:Dw.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&l.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=i4t(l,n);r.samples.push({data:l.payload,len:l.payload.byteLength,dts:o,pts:o,type:Dw.misbklv,duration:Number.POSITIVE_INFINITY})}})}return r}demuxSampleAes(t,n,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function i4t(s,t){return Bi(s.presentationTime)?s.presentationTime/s.timeScale:t+s.presentationTimeDelta/s.timeScale}class Uar{constructor(t,n,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new Drt(n,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,CP.cbc)}decryptAacSample(t,n,r){const a=t[n].unit;if(a.length<=16)return;const i=a.subarray(16,a.length-a.length%16),l=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(l).then(o=>{const c=new Uint8Array(o);a.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(t,n+1,r)}).catch(r)}decryptAacSamples(t,n,r){for(;;n++){if(n>=t.length){r();return}if(!(t[n].unit.length<32)&&(this.decryptAacSample(t,n,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const n=Math.floor((t.length-48)/160)*16+16,r=new Int8Array(n);let a=0;for(let i=32;i{i.data=this.getAvcDecryptedUnit(l,c),this.decrypter.isSync()||this.decryptAvcSamples(t,n,r+1,a)}).catch(a)}decryptAvcSamples(t,n,r,a){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;n++,r=0){if(n>=t.length){a();return}const i=t[n].units;for(;!(r>=i.length);r++){const l=i[r];if(!(l.data.length<=48||l.type!==1&&l.type!==5)&&(this.decryptAvcSample(t,n,r,a,l),!this.decrypter.isSync()))return}}}}class Tns{constructor(){this.VideoSample=null}createVideoSample(t,n,r){return{key:t,frame:!1,pts:n,dts:r,units:[],length:0}}getLastNalUnit(t){var n;let r=this.VideoSample,a;if((!r||r.units.length===0)&&(r=t[t.length-1]),(n=r)!=null&&n.units){const i=r.units;a=i[i.length-1]}return a}pushAccessUnit(t,n){if(t.units.length&&t.frame){if(t.pts===void 0){const r=n.samples,a=r.length;if(a){const i=r[a-1];t.pts=i.pts,t.dts=i.dts}else{n.dropped++;return}}n.samples.push(t)}}parseNALu(t,n,r){const a=n.byteLength;let i=t.naluState||0;const l=i,o=[];let c=0,d,u,h,m=-1,p=0;for(i===-1&&(m=0,p=this.getNALuType(n,0),i=0,c=1);c=0){const f={data:n.subarray(m,u),type:p};o.push(f)}else{const f=this.getLastNalUnit(t.samples);f&&(l&&c<=4-l&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-l)),u>0&&(f.data=_N(f.data,n.subarray(0,u)),f.state=0))}c=0&&i>=0){const f={data:n.subarray(m,a),type:p,state:i};o.push(f)}if(o.length===0){const f=this.getLastNalUnit(t.samples);f&&(f.data=_N(f.data,n))}return t.naluState=i,o}}class SJ{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,n=this.bytesAvailable,r=t.byteLength-n,a=new Uint8Array(4),i=Math.min(4,n);if(i===0)throw new Error("no bytes available");a.set(t.subarray(r,r+i)),this.word=new DataView(a.buffer).getUint32(0),this.bitsAvailable=i*8,this.bytesAvailable-=i}skipBits(t){let n;t=Math.min(t,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,n=t>>3,t-=n<<3,this.bytesAvailable-=n,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let n=Math.min(this.bitsAvailable,t);const r=this.word>>>32-n;if(t>32&&Ah.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=n,this.bitsAvailable>0)this.word<<=n;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return n=t-n,n>0&&this.bitsAvailable?r<>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class qar extends Tns{parsePES(t,n,r,a){const i=this.parseNALu(t,r.data,a);let l=this.VideoSample,o,c=!1;r.data=null,l&&i.length&&!t.audFound&&(this.pushAccessUnit(l,t),l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),i.forEach(d=>{var u,h;switch(d.type){case 1:{let x=!1;o=!0;const y=d.data;if(c&&y.length>4){const v=this.readSliceType(y);(v===2||v===4||v===7||v===9)&&(x=!0)}if(x){var m;(m=l)!=null&&m.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),l.frame=!0,l.key=x;break}case 5:o=!0,(u=l)!=null&&u.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),l.key=!0,l.frame=!0;break;case 6:{o=!0,Prt(d.data,1,r.pts,n.samples);break}case 7:{var p,f;o=!0,c=!0;const x=d.data,y=this.readSPS(x);if(!t.sps||t.width!==y.width||t.height!==y.height||((p=t.pixelRatio)==null?void 0:p[0])!==y.pixelRatio[0]||((f=t.pixelRatio)==null?void 0:f[1])!==y.pixelRatio[1]){t.width=y.width,t.height=y.height,t.pixelRatio=y.pixelRatio,t.sps=[x];const v=x.subarray(1,4);let b="avc1.";for(let N=0;N<3;N++){let S=v[N].toString(16);S.length<2&&(S="0"+S),b+=S}t.codec=b}break}case 8:o=!0,t.pps=[d.data];break;case 9:o=!0,t.audFound=!0,(h=l)!=null&&h.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;case 12:o=!0;break;default:o=!1;break}l&&o&&l.units.push(d)}),a&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}getNALuType(t,n){return t[n]&31}readSliceType(t){const n=new SJ(t);return n.readUByte(),n.readUEG(),n.readUEG()}skipScalingList(t,n){let r=8,a=8,i;for(let l=0;l{var u,h;switch(d.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:l||(l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),l.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,c){var m;(m=l)!=null&&m.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),l.key=!0,l.frame=!0;break;case 19:case 20:o=!0,(u=l)!=null&&u.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),l.key=!0,l.frame=!0;break;case 39:o=!0,Prt(d.data,2,r.pts,n.samples);break;case 32:o=!0,t.vps||(typeof t.params!="object"&&(t.params={}),t.params=Yh(t.params,this.readVPS(d.data)),this.initVPS=d.data),t.vps=[d.data];break;case 33:if(o=!0,c=!0,t.vps!==void 0&&t.vps[0]!==this.initVPS&&t.sps!==void 0&&!this.matchSPS(t.sps[0],d.data)&&(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const p=this.readSPS(d.data);t.width=p.width,t.height=p.height,t.pixelRatio=p.pixelRatio,t.codec=p.codecString,t.sps=[],typeof t.params!="object"&&(t.params={});for(const f in p.params)t.params[f]=p.params[f]}this.pushParameterSet(t.sps,d.data,t.vps),l||(l=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),l.key=!0;break;case 34:if(o=!0,typeof t.params=="object"){if(!t.pps){t.pps=[];const p=this.readPPS(d.data);for(const f in p)t.params[f]=p[f]}this.pushParameterSet(t.pps,d.data,t.vps)}break;case 35:o=!0,t.audFound=!0,(h=l)!=null&&h.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;default:o=!1;break}l&&o&&l.units.push(d)}),a&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}pushParameterSet(t,n,r){(r&&r[0]===this.initVPS||!r&&!t.length)&&t.push(n)}getNALuType(t,n){return(t[n]&126)>>>1}ebsp2rbsp(t){const n=new Uint8Array(t.byteLength);let r=0;for(let a=0;a=2&&t[a]===3&&t[a-1]===0&&t[a-2]===0||(n[r]=t[a],r++);return new Uint8Array(n.buffer,0,r)}pushAccessUnit(t,n){super.pushAccessUnit(t,n),this.initVPS&&(this.initVPS=null)}readVPS(t){const n=new SJ(t);n.readUByte(),n.readUByte(),n.readBits(4),n.skipBits(2),n.readBits(6);const r=n.readBits(3),a=n.readBoolean();return{numTemporalLayers:r+1,temporalIdNested:a}}readSPS(t){const n=new SJ(this.ebsp2rbsp(t));n.readUByte(),n.readUByte(),n.readBits(4);const r=n.readBits(3);n.readBoolean();const a=n.readBits(2),i=n.readBoolean(),l=n.readBits(5),o=n.readUByte(),c=n.readUByte(),d=n.readUByte(),u=n.readUByte(),h=n.readUByte(),m=n.readUByte(),p=n.readUByte(),f=n.readUByte(),x=n.readUByte(),y=n.readUByte(),v=n.readUByte(),b=[],N=[];for(let Ne=0;Ne0)for(let Ne=r;Ne<8;Ne++)n.readBits(2);for(let Ne=0;Ne1&&n.readEG();for(let Ue=0;Ue0&&Ye<16?(ie=Ge[Ye-1],ce=He[Ye-1]):Ye===255&&(ie=n.readBits(16),ce=n.readBits(16))}if(n.readBoolean()&&n.readBoolean(),n.readBoolean()&&(n.readBits(3),n.readBoolean(),n.readBoolean()&&(n.readUByte(),n.readUByte(),n.readUByte())),n.readBoolean()&&(n.readUEG(),n.readUEG()),n.readBoolean(),n.readBoolean(),n.readBoolean(),ge=n.readBoolean(),ge&&(n.skipUEG(),n.skipUEG(),n.skipUEG(),n.skipUEG()),n.readBoolean()&&(be=n.readBits(32),he=n.readBits(32),n.readBoolean()&&n.readUEG(),n.readBoolean())){const He=n.readBoolean(),tt=n.readBoolean();let pt=!1;(He||tt)&&(pt=n.readBoolean(),pt&&(n.readUByte(),n.readBits(5),n.readBoolean(),n.readBits(5)),n.readBits(4),n.readBits(4),pt&&n.readBits(4),n.readBits(5),n.readBits(5),n.readBits(5));for(let ft=0;ft<=r;ft++){je=n.readBoolean();const qt=je||n.readBoolean();let Ut=!1;qt?n.readEG():Ut=n.readBoolean();const Wt=Ut?1:n.readUEG()+1;if(He)for(let us=0;us>Ne&1)<<31-Ne)>>>0;let Ae=Qe.toString(16);return l===1&&Ae==="2"&&(Ae="6"),{codecString:`hvc1.${Oe}${l}.${Ae}.${i?"H":"L"}${v}.B0`,params:{general_tier_flag:i,general_profile_idc:l,general_profile_space:a,general_profile_compatibility_flags:[o,c,d,u],general_constraint_indicator_flags:[h,m,p,f,x,y],general_level_idc:v,bit_depth:$+8,bit_depth_luma_minus8:$,bit_depth_chroma_minus8:H,min_spatial_segmentation_idc:ne,chroma_format_idc:S,frame_rate:{fixed:je,fps:he/be}},width:Te,height:Me,pixelRatio:[ie,ce]}}readPPS(t){const n=new SJ(this.ebsp2rbsp(t));n.readUByte(),n.readUByte(),n.skipUEG(),n.skipUEG(),n.skipBits(2),n.skipBits(3),n.skipBits(2),n.skipUEG(),n.skipUEG(),n.skipEG(),n.skipBits(2),n.readBoolean()&&n.skipUEG(),n.skipEG(),n.skipEG(),n.skipBits(4);const a=n.readBoolean(),i=n.readBoolean();let l=1;return i&&a?l=0:i?l=3:a&&(l=2),{parallelismType:l}}matchSPS(t,n){return String.fromCharCode.apply(null,t).substr(3)===String.fromCharCode.apply(null,n).substr(3)}}const F0=188;class JT{constructor(t,n,r,a){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=n,this.typeSupported=r,this.logger=a,this.videoParser=null}static probe(t,n){const r=JT.syncOffset(t);return r>0&&n.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),r!==-1}static syncOffset(t){const n=t.length;let r=Math.min(F0*5,n-F0)+1,a=0;for(;a1&&(l===0&&o>2||c+F0>r))return l}else{if(o)return-1;break}a++}return-1}static createTrack(t,n){return{container:t==="video"||t==="audio"?"video/mp2t":void 0,type:t,id:Dss[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:t==="audio"?n:void 0}}resetInitSegment(t,n,r,a){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=JT.createTrack("video"),this._videoTrack.duration=a,this._audioTrack=JT.createTrack("audio",a),this._id3Track=JT.createTrack("id3"),this._txtTrack=JT.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=n,this.videoCodec=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:n,_id3Track:r}=this;t&&(t.pesData=null),n&&(n.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,n,r=!1,a=!1){r||(this.sampleAes=null);let i;const l=this._videoTrack,o=this._audioTrack,c=this._id3Track,d=this._txtTrack;let u=l.pid,h=l.pesData,m=o.pid,p=c.pid,f=o.pesData,x=c.pesData,y=null,v=this.pmtParsed,b=this._pmtId,N=t.length;if(this.remainderData&&(t=_N(this.remainderData,t),N=t.length,this.remainderData=null),N>4;let z;if(R>1){if(z=L+5+t[L+4],z===L+F0)continue}else z=L+4;switch(I){case u:M&&(h&&(i=CB(h,this.logger))&&(this.readyVideoParser(l.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(l,d,i,!1)),h={data:[],size:0}),h&&(h.data.push(t.subarray(z,L+F0)),h.size+=L+F0-z);break;case m:if(M){if(f&&(i=CB(f,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,i);break;case"mp3":this.parseMPEGPES(o,i);break;case"ac3":this.parseAC3PES(o,i);break}f={data:[],size:0}}f&&(f.data.push(t.subarray(z,L+F0)),f.size+=L+F0-z);break;case p:M&&(x&&(i=CB(x,this.logger))&&this.parseID3PES(c,i),x={data:[],size:0}),x&&(x.data.push(t.subarray(z,L+F0)),x.size+=L+F0-z);break;case 0:M&&(z+=t[z]+1),b=this._pmtId=Var(t,z);break;case b:{M&&(z+=t[z]+1);const $=Har(t,z,this.typeSupported,r,this.observer,this.logger);u=$.videoPid,u>0&&(l.pid=u,l.segmentCodec=$.segmentVideoCodec),m=$.audioPid,m>0&&(o.pid=m,o.segmentCodec=$.segmentAudioCodec),p=$.id3Pid,p>0&&(c.pid=p),y!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${L} after unknown PID '${y}'. Backtracking to sync byte @${S} to parse all TS packets.`),y=null,L=S-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=I;break}}else A++;A>0&&UKe(this.observer,new Error(`Found ${A} TS packet/s that do not start with 0x47`),void 0,this.logger),l.pesData=h,o.pesData=f,c.pesData=x;const T={audioTrack:o,videoTrack:l,id3Track:c,textTrack:d};return a&&this.extractRemainingSamples(T),T}flush(){const{remainderData:t}=this;this.remainderData=null;let n;return t?n=this.demux(t,-1,!1,!0):n={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(n),this.sampleAes?this.decrypt(n,this.sampleAes):n}extractRemainingSamples(t){const{audioTrack:n,videoTrack:r,id3Track:a,textTrack:i}=t,l=r.pesData,o=n.pesData,c=a.pesData;let d;if(l&&(d=CB(l,this.logger))?(this.readyVideoParser(r.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(r,i,d,!0),r.pesData=null)):r.pesData=l,o&&(d=CB(o,this.logger))){switch(n.segmentCodec){case"aac":this.parseAACPES(n,d);break;case"mp3":this.parseMPEGPES(n,d);break;case"ac3":this.parseAC3PES(n,d);break}n.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),n.pesData=o;c&&(d=CB(c,this.logger))?(this.parseID3PES(a,d),a.pesData=null):a.pesData=c}demuxSampleAes(t,n,r){const a=this.demux(t,r,!0,!this.config.progressive),i=this.sampleAes=new Uar(this.observer,this.config,n);return this.decrypt(a,i)}readyVideoParser(t){this.videoParser===null&&(t==="avc"?this.videoParser=new qar:t==="hevc"&&(this.videoParser=new $ar))}decrypt(t,n){return new Promise(r=>{const{audioTrack:a,videoTrack:i}=t;a.samples&&a.segmentCodec==="aac"?n.decryptAacSamples(a.samples,0,()=>{i.samples?n.decryptAvcSamples(i.samples,0,0,()=>{r(t)}):r(t)}):i.samples&&n.decryptAvcSamples(i.samples,0,0,()=>{r(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(t,n){let r=0;const a=this.aacOverFlow;let i=n.data;if(a){this.aacOverFlow=null;const h=a.missing,m=a.sample.unit.byteLength;if(h===-1)i=_N(a.sample.unit,i);else{const p=m-h;a.sample.unit.set(i.subarray(0,h),p),t.samples.push(a.sample),r=a.missing}}let l,o;for(l=r,o=i.length;l0;)o+=c}}parseID3PES(t,n){if(n.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const r=Yh({},n,{type:this._videoTrack?Dw.emsg:Dw.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(r)}}function BKe(s,t){return((s[t+1]&31)<<8)+s[t+2]}function Var(s,t){return(s[t+10]&31)<<8|s[t+11]}function Har(s,t,n,r,a,i){const l={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(s[t+1]&15)<<8|s[t+2],c=t+3+o-4,d=(s[t+10]&15)<<8|s[t+11];for(t+=12+d;t0){let m=t+5,p=h;for(;p>2;){switch(s[m]){case 106:n.ac3!==!0?i.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=u,l.segmentAudioCodec="ac3");break}const x=s[m+1]+2;m+=x,p-=x}}break;case 194:case 135:return UKe(a,new Error("Unsupported EC-3 in M2TS found"),void 0,i),l;case 36:l.videoPid===-1&&(l.videoPid=u,l.segmentVideoCodec="hevc",i.log("HEVC in M2TS found"));break}t+=h+5}return l}function UKe(s,t,n,r){r.warn(`parsing error: ${t.message}`),s.emit(Ot.ERROR,Ot.ERROR,{type:wo.MEDIA_ERROR,details:yr.FRAG_PARSING_ERROR,fatal:!1,levelRetry:n,error:t,reason:t.message})}function Fze(s,t){t.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function CB(s,t){let n=0,r,a,i,l,o;const c=s.data;if(!s||s.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=_N(c[0],c[1]),c.splice(1,1);if(r=c[0],(r[0]<<16)+(r[1]<<8)+r[2]===1){if(a=(r[4]<<8)+r[5],a&&a>s.size-6)return null;const u=r[7];u&192&&(l=(r[9]&14)*536870912+(r[10]&255)*4194304+(r[11]&254)*16384+(r[12]&255)*128+(r[13]&254)/2,u&64?(o=(r[14]&14)*536870912+(r[15]&255)*4194304+(r[16]&254)*16384+(r[17]&255)*128+(r[18]&254)/2,l-o>60*9e4&&(t.warn(`${Math.round((l-o)/9e4)}s delta between PTS and DTS, align them`),l=o)):o=l),i=r[8];let h=i+9;if(s.size<=h)return null;s.size-=h;const m=new Uint8Array(s.size);for(let p=0,f=c.length;px){h-=x;continue}else r=r.subarray(h),x-=h,h=0;m.set(r,n),n+=x}return a&&(a-=i+3),{data:m,pts:l,dts:o,len:a}}return null}class Gar{static getSilentFrame(t,n){switch(t){case"mp4a.40.2":if(n===1)return new Uint8Array([0,200,0,128,35,128]);if(n===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(n===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(n===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(n===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(n===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(n===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(n===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(n===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const fT=Math.pow(2,32)-1;class fr{static init(){fr.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let t;for(t in fr.types)fr.types.hasOwnProperty(t)&&(fr.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const n=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);fr.HDLR_TYPES={video:n,audio:r};const a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),i=new Uint8Array([0,0,0,0,0,0,0,0]);fr.STTS=fr.STSC=fr.STCO=i,fr.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),fr.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),fr.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),fr.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const l=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);fr.FTYP=fr.box(fr.types.ftyp,l,c,l,o),fr.DINF=fr.box(fr.types.dinf,fr.box(fr.types.dref,a))}static box(t,...n){let r=8,a=n.length;const i=a;for(;a--;)r+=n[a].byteLength;const l=new Uint8Array(r);for(l[0]=r>>24&255,l[1]=r>>16&255,l[2]=r>>8&255,l[3]=r&255,l.set(t,4),a=0,r=8;a>24&255,t>>16&255,t>>8&255,t&255,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255,85,196,0,0]))}static mdia(t){return fr.box(fr.types.mdia,fr.mdhd(t.timescale||0,t.duration||0),fr.hdlr(t.type),fr.minf(t))}static mfhd(t){return fr.box(fr.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type==="audio"?fr.box(fr.types.minf,fr.box(fr.types.smhd,fr.SMHD),fr.DINF,fr.stbl(t)):fr.box(fr.types.minf,fr.box(fr.types.vmhd,fr.VMHD),fr.DINF,fr.stbl(t))}static moof(t,n,r){return fr.box(fr.types.moof,fr.mfhd(t),fr.traf(r,n))}static moov(t){let n=t.length;const r=[];for(;n--;)r[n]=fr.trak(t[n]);return fr.box.apply(null,[fr.types.moov,fr.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r).concat(fr.mvex(t)))}static mvex(t){let n=t.length;const r=[];for(;n--;)r[n]=fr.trex(t[n]);return fr.box.apply(null,[fr.types.mvex,...r])}static mvhd(t,n){n*=t;const r=Math.floor(n/(fT+1)),a=Math.floor(n%(fT+1)),i=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return fr.box(fr.types.mvhd,i)}static sdtp(t){const n=t.samples||[],r=new Uint8Array(4+n.length);let a,i;for(a=0;a>>8&255),n.push(l&255),n=n.concat(Array.prototype.slice.call(i));for(a=0;a>>8&255),r.push(l&255),r=r.concat(Array.prototype.slice.call(i));const o=fr.box(fr.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n).concat([t.pps.length]).concat(r))),c=t.width,d=t.height,u=t.pixelRatio[0],h=t.pixelRatio[1];return fr.box(fr.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,c&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,fr.box(fr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),fr.box(fr.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,h>>24,h>>16&255,h>>8&255,h&255])))}static esds(t){const n=t.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...n,6,1,2])}static audioStsd(t){const n=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,n>>8&255,n&255,0,0])}static mp4a(t){return fr.box(fr.types.mp4a,fr.audioStsd(t),fr.box(fr.types.esds,fr.esds(t)))}static mp3(t){return fr.box(fr.types[".mp3"],fr.audioStsd(t))}static ac3(t){return fr.box(fr.types["ac-3"],fr.audioStsd(t),fr.box(fr.types.dac3,t.config))}static stsd(t){const{segmentCodec:n}=t;if(t.type==="audio"){if(n==="aac")return fr.box(fr.types.stsd,fr.STSD,fr.mp4a(t));if(n==="ac3"&&t.config)return fr.box(fr.types.stsd,fr.STSD,fr.ac3(t));if(n==="mp3"&&t.codec==="mp3")return fr.box(fr.types.stsd,fr.STSD,fr.mp3(t))}else if(t.pps&&t.sps){if(n==="avc")return fr.box(fr.types.stsd,fr.STSD,fr.avc1(t));if(n==="hevc"&&t.vps)return fr.box(fr.types.stsd,fr.STSD,fr.hvc1(t))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${t.type} segment codec (${n}/${t.codec})`)}static tkhd(t){const n=t.id,r=(t.duration||0)*(t.timescale||0),a=t.width||0,i=t.height||0,l=Math.floor(r/(fT+1)),o=Math.floor(r%(fT+1));return fr.box(fr.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,n>>24&255,n>>16&255,n>>8&255,n&255,0,0,0,0,l>>24,l>>16&255,l>>8&255,l&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,a>>8&255,a&255,0,0,i>>8&255,i&255,0,0]))}static traf(t,n){const r=fr.sdtp(t),a=t.id,i=Math.floor(n/(fT+1)),l=Math.floor(n%(fT+1));return fr.box(fr.types.traf,fr.box(fr.types.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255])),fr.box(fr.types.tfdt,new Uint8Array([1,0,0,0,i>>24,i>>16&255,i>>8&255,i&255,l>>24,l>>16&255,l>>8&255,l&255])),fr.trun(t,r.length+16+20+8+16+8+8),r)}static trak(t){return t.duration=t.duration||4294967295,fr.box(fr.types.trak,fr.tkhd(t),fr.mdia(t))}static trex(t){const n=t.id;return fr.box(fr.types.trex,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,n){const r=t.samples||[],a=r.length,i=12+16*a,l=new Uint8Array(i);let o,c,d,u,h,m;for(n+=8+i,l.set([t.type==="video"?1:0,0,15,1,a>>>24&255,a>>>16&255,a>>>8&255,a&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255],0),o=0;o>>24&255,d>>>16&255,d>>>8&255,d&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,m>>>24&255,m>>>16&255,m>>>8&255,m&255],12+16*o);return fr.box(fr.types.trun,l)}static initSegment(t){fr.types||fr.init();const n=fr.moov(t);return _N(fr.FTYP,n)}static hvc1(t){const n=t.params,r=[t.vps,t.sps,t.pps],a=4,i=new Uint8Array([1,n.general_profile_space<<6|(n.general_tier_flag?32:0)|n.general_profile_idc,n.general_profile_compatibility_flags[0],n.general_profile_compatibility_flags[1],n.general_profile_compatibility_flags[2],n.general_profile_compatibility_flags[3],n.general_constraint_indicator_flags[0],n.general_constraint_indicator_flags[1],n.general_constraint_indicator_flags[2],n.general_constraint_indicator_flags[3],n.general_constraint_indicator_flags[4],n.general_constraint_indicator_flags[5],n.general_level_idc,240|n.min_spatial_segmentation_idc>>8,255&n.min_spatial_segmentation_idc,252|n.parallelismType,252|n.chroma_format_idc,248|n.bit_depth_luma_minus8,248|n.bit_depth_chroma_minus8,0,parseInt(n.frame_rate.fps),a-1|n.temporal_id_nested<<2|n.num_temporal_layers<<3|(n.frame_rate.fixed?64:0),r.length]);let l=i.length;for(let f=0;f>8,r[f][x].length&255]),l),l+=2,o.set(r[f][x],l),l+=r[f][x].length}const d=fr.box(fr.types.hvcC,o),u=t.width,h=t.height,m=t.pixelRatio[0],p=t.pixelRatio[1];return fr.box(fr.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,u>>8&255,u&255,h>>8&255,h&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),d,fr.box(fr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),fr.box(fr.types.pasp,new Uint8Array([m>>24,m>>16&255,m>>8&255,m&255,p>>24,p>>16&255,p>>8&255,p&255])))}}fr.types=void 0;fr.HDLR_TYPES=void 0;fr.STTS=void 0;fr.STSC=void 0;fr.STCO=void 0;fr.STSZ=void 0;fr.VMHD=void 0;fr.SMHD=void 0;fr.STSD=void 0;fr.FTYP=void 0;fr.DINF=void 0;const Mns=9e4;function Wrt(s,t,n=1,r=!1){const a=s*t*n;return r?Math.round(a):a}function War(s,t,n=1,r=!1){return Wrt(s,t,1/n,r)}function KY(s,t=!1){return Wrt(s,1e3,1/Mns,t)}function Kar(s,t=1){return Wrt(s,Mns,1/t)}function o4t(s){const{baseTime:t,timescale:n,trackId:r}=s;return`${t/n} (${t}/${n}) trackId: ${r}`}const Yar=10*1e3,Zar=1024,Xar=1152,Qar=1536;let AB=null,zze=null;function l4t(s,t,n,r){return{duration:t,size:n,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:s?2:1,isNonSync:s?0:1}}}class r3e extends PN{constructor(t,n,r,a){if(super("mp4-remuxer",a),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=n,this.typeSupported=r,this.ISGenerated=!1,AB===null){const l=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);AB=l?parseInt(l[1]):0}if(zze===null){const i=navigator.userAgent.match(/Safari\/(\d+)/i);zze=i?parseInt(i[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const n=this._initPTS;(!n||!t||t.trackId!==n.trackId||t.baseTime!==n.baseTime||t.timescale!==n.timescale)&&this.log(`Reset initPTS: ${n&&o4t(n)} > ${t&&o4t(t)}`),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let n=!1;const r=t[0].pts,a=t.reduce((i,l)=>{let o=l.pts,c=o-i;return c<-4294967296&&(n=!0,o=Tw(o,r),c=o-i),c>0?i:o},r);return n&&this.debug("PTS rollover detected"),a}remux(t,n,r,a,i,l,o,c){let d,u,h,m,p,f,x=i,y=i;const v=t.pid>-1,b=n.pid>-1,N=n.samples.length,S=t.samples.length>0,A=o&&N>0||N>1;if((!v||S)&&(!b||A)||this.ISGenerated||o){if(this.ISGenerated){var L,M,I,R;const V=this.videoTrackConfig;(V&&(n.width!==V.width||n.height!==V.height||((L=n.pixelRatio)==null?void 0:L[0])!==((M=V.pixelRatio)==null?void 0:M[0])||((I=n.pixelRatio)==null?void 0:I[1])!==((R=V.pixelRatio)==null?void 0:R[1]))||!V&&A||this.nextAudioTs===null&&S)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(t,n,i,l));const z=this.isVideoContiguous;let $=-1,H;if(A&&($=Jar(n.samples),!z&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,$>0){this.warn(`Dropped ${$} out of ${N} video samples due to a missing keyframe`);const V=this.getVideoStartPts(n.samples);n.samples=n.samples.slice($),n.dropped+=$,y+=(n.samples[0].pts-V)/n.inputTimeScale,H=y}else $===-1&&(this.warn(`No keyframe found out of ${N} video samples`),f=!1);if(this.ISGenerated){if(S&&A){const V=this.getVideoStartPts(n.samples),Z=(Tw(t.samples[0].pts,V)-V)/n.inputTimeScale;x+=Math.max(0,Z),y+=Math.max(0,-Z)}if(S){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(t,n,i,l)),u=this.remuxAudio(t,x,this.isAudioContiguous,l,b||A||c===io.AUDIO?y:void 0),A){const V=u?u.endPTS-u.startPTS:0;n.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(t,n,i,l)),d=this.remuxVideo(n,y,z,V)}}else A&&(d=this.remuxVideo(n,y,z,0));d&&(d.firstKeyFrame=$,d.independent=$!==-1,d.firstKeyFramePTS=H)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(p=Pns(r,i,this._initPTS,this._initDTS)),a.samples.length&&(m=Lns(a,i,this._initPTS))),{audio:u,video:d,initSegment:h,independent:f,text:m,id3:p}}computeInitPts(t,n,r,a){const i=Math.round(r*n);let l=Tw(t,i);if(l0?ne-1:ne].dts&&(b=!0)}b&&l.sort(function(ne,ie){const ce=ne.dts-ie.dts,je=ne.pts-ie.pts;return ce||je}),f=l[0].dts,x=l[l.length-1].dts;const S=x-f,A=S?Math.round(S/(c-1)):p||t.inputTimeScale/30;if(r){const ne=f-N,ie=ne>A,ce=ne<-1;if((ie||ce)&&(ie?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${KY(ne,!0)} ms (${ne}dts) hole between fragments detected at ${n.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${KY(-ne,!0)} ms (${ne}dts) overlapping between fragments detected at ${n.toFixed(3)}`),!ce||N>=l[0].pts||AB)){f=N;const je=l[0].pts-ne;if(ie)l[0].dts=f,l[0].pts=je;else{let be=!0;for(let he=0;heje&&be);he++){const ge=l[he].pts;if(l[he].dts-=ne,l[he].pts-=ne,he0?ie.dts-l[ne-1].dts:A;if(be=ne>0?ie.pts-l[ne-1].pts:A,ge.stretchShortVideoTrack&&this.nextAudioTs!==null){const Te=Math.floor(ge.maxBufferHole*i),Me=(a?y+a*i:this.nextAudioTs+u)-ie.pts;Me>Te?(p=Me-ke,p<0?p=ke:$=!0,this.log(`It is approximately ${Me/90} ms to the next segment; using duration ${p/90} ms for the last video frame.`)):p=ke}else p=ke}const he=Math.round(ie.pts-ie.dts);H=Math.min(H,p),K=Math.max(K,p),V=Math.min(V,be),Z=Math.max(Z,be),o.push(l4t(ie.key,p,je,he))}if(o.length){if(AB){if(AB<70){const ne=o[0].flags;ne.dependsOn=2,ne.isNonSync=0}}else if(zze&&Z-V0&&(a&&Math.abs(N-(v+b))<9e3||Math.abs(Tw(x[0].pts,N)-(v+b))<20*u),x.forEach(function(Z){Z.pts=Tw(Z.pts,N)}),!r||v<0){const Z=x.length;if(x=x.filter(Q=>Q.pts>=0),Z!==x.length&&this.warn(`Removed ${x.length-Z} of ${Z} samples (initPTS ${b} / ${l})`),!x.length)return;i===0?v=0:a&&!f?v=Math.max(0,N-b):v=x[0].pts-b}if(t.segmentCodec==="aac"){const Z=this.config.maxAudioFramesDrift;for(let Q=0,le=v+b;Q=Z*u&&ie0){L+=y;try{T=new Uint8Array(L)}catch(ie){this.observer.emit(Ot.ERROR,Ot.ERROR,{type:wo.MUX_ERROR,details:yr.REMUX_ALLOC_ERROR,fatal:!1,error:ie,bytes:L,reason:`fail allocating audio mdat ${L}`});return}m||(new DataView(T.buffer).setUint32(0,L),T.set(fr.types.mdat,4))}else return;T.set(ue,y);const ne=ue.byteLength;y+=ne,p.push(l4t(!0,d,ne,0)),A=se}const I=p.length;if(!I)return;const R=p[p.length-1];v=A-b,this.nextAudioTs=v+c*R.duration;const z=m?new Uint8Array(0):fr.moof(t.sequenceNumber++,S/c,Yh({},t,{samples:p}));t.samples=[];const $=(S-b)/l,H=this.nextAudioTs/l,K={data1:z,data2:T,startPTS:$,endPTS:H,startDTS:$,endDTS:H,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,K}}function Tw(s,t){let n;if(t===null)return s;for(t4294967296;)s+=n;return s}function Jar(s){for(let t=0;tl.pts-o.pts);const i=s.samples;return s.samples=[],{samples:i}}class eir extends PN{constructor(t,n,r,a){super("passthrough-remuxer",a),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(t){this.lastEndTime=null;const n=this.initPTS;n&&t&&n.baseTime===t.baseTime&&n.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,n,r,a){this.audioCodec=n,this.videoCodec=r,this.generateInitSegment(t,a),this.emitInitSegment=!0}generateInitSegment(t,n){let{audioCodec:r,videoCodec:a}=this;if(!(t!=null&&t.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:i,video:l}=this.initData=zss(t);if(n)Bnr(t,n);else{const c=i||l;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}i&&(r=c4t(i,dm.AUDIO,this)),l&&(a=c4t(l,dm.VIDEO,this));const o={};i&&l?o.audiovideo={container:"video/mp4",codec:r+","+a,supplemental:l.supplemental,encrypted:l.encrypted,initSegment:t,id:"main"}:i?o.audio={container:"audio/mp4",codec:r,encrypted:i.encrypted,initSegment:t,id:"audio"}:l?o.video={container:"video/mp4",codec:a,supplemental:l.supplemental,encrypted:l.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(t,n,r,a,i,l){var o,c;let{initPTS:d,lastEndTime:u}=this;const h={audio:void 0,video:void 0,text:a,id3:r,initSegment:void 0};Bi(u)||(u=this.lastEndTime=i||0);const m=n.samples;if(!m.length)return h;const p={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if((o=f)!=null&&o.length||(this.generateInitSegment(m),f=this.initData),!((c=f)!=null&&c.length))return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(p.tracks=this.initTracks,this.emitInitSegment=!1);const x=qnr(m,f,this),y=f.audio?x[f.audio.id]:null,v=f.video?x[f.video.id]:null,b=Wce(v,1/0),N=Wce(y,1/0),S=Wce(v,0,!0),A=Wce(y,0,!0);let T=i,L=0;const M=y&&(!v||!d&&N0?this.lastEndTime=z:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const $=!!f.audio,H=!!f.video;let V="";$&&(V+="audio"),H&&(V+="video");const K=(f.audio?f.audio.encrypted:!1)||(f.video?f.video.encrypted:!1),Z={data1:m,startPTS:R,startDTS:R,endPTS:z,endDTS:z,type:V,hasAudio:$,hasVideo:H,nb:1,dropped:0,encrypted:K};h.audio=$&&!H?Z:void 0,h.video=H?Z:void 0;const Q=v==null?void 0:v.sampleCount;if(Q){const le=v.keyFrameIndex,ue=le!==-1;Z.nb=Q,Z.dropped=le===0||this.isVideoContiguous?0:ue?le:Q,Z.independent=ue,Z.firstKeyFrame=le,ue&&v.keyFrameStart&&(Z.firstKeyFramePTS=(v.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(h.independent=ue),this.isVideoContiguous||(this.isVideoContiguous=ue),Z.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${le}/${Q} dropped: ${Z.dropped} start: ${Z.firstKeyFramePTS||"NA"}`)}return h.initSegment=p,h.id3=Pns(r,i,d,d),a.samples.length&&(h.text=Lns(a,i,d)),h}}function Wce(s,t,n=!1){return(s==null?void 0:s.start)!==void 0?(s.start+(n?s.duration:0))/s.timescale:t}function tir(s,t,n,r){if(s===null)return!0;const a=Math.max(r,1),i=t-s.baseTime/s.timescale;return Math.abs(i-n)>a}function c4t(s,t,n){const r=s.codec;return r&&r.length>4?r:t===dm.AUDIO?r==="ec-3"||r==="ac-3"||r==="alac"?r:r==="fLaC"||r==="Opus"?NTe(r,!1):(n.warn(`Unhandled audio codec "${r}" in mp4 MAP`),r||"mp4a"):(n.warn(`Unhandled video codec "${r}" in mp4 MAP`),r||"avc1")}let SC;try{SC=self.performance.now.bind(self.performance)}catch{SC=Date.now}const a3e=[{demux:Bar,remux:eir},{demux:JT,remux:r3e},{demux:Dar,remux:r3e},{demux:Far,remux:r3e}];a3e.splice(2,0,{demux:Oar,remux:r3e});class d4t{constructor(t,n,r,a,i,l){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=n,this.config=r,this.id=i,this.logger=l}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,n,r,a){const i=r.transmuxing;i.executeStart=SC();let l=new Uint8Array(t);const{currentTransmuxState:o,transmuxConfig:c}=this;a&&(this.currentTransmuxState=a);const{contiguous:d,discontinuity:u,trackSwitch:h,accurateTimeOffset:m,timeOffset:p,initSegmentChange:f}=a||o,{audioCodec:x,videoCodec:y,defaultInitPts:v,duration:b,initSegmentData:N}=c,S=sir(l,n);if(S&&c$(S.method)){const M=this.getDecrypter(),I=Frt(S.method);if(M.isSync()){let R=M.softwareDecrypt(l,S.key.buffer,S.iv.buffer,I);if(r.part>-1){const $=M.flush();R=$&&$.buffer}if(!R)return i.executeEnd=SC(),Bze(r);l=new Uint8Array(R)}else return this.asyncResult=!0,this.decryptionPromise=M.webCryptoDecrypt(l,S.key.buffer,S.iv.buffer,I).then(R=>{const z=this.push(R,null,r);return this.decryptionPromise=null,z}),this.decryptionPromise}const A=this.needsProbing(u,h);if(A){const M=this.configureTransmuxer(l);if(M)return this.logger.warn(`[transmuxer] ${M.message}`),this.observer.emit(Ot.ERROR,Ot.ERROR,{type:wo.MEDIA_ERROR,details:yr.FRAG_PARSING_ERROR,fatal:!1,error:M,reason:M.message}),i.executeEnd=SC(),Bze(r)}(u||h||f||A)&&this.resetInitSegment(N,x,y,b,n),(u||f||A)&&this.resetInitialTimestamp(v),d||this.resetContiguity();const T=this.transmux(l,S,p,m,r);this.asyncResult=Zte(T);const L=this.currentTransmuxState;return L.contiguous=!0,L.discontinuity=!1,L.trackSwitch=!1,i.executeEnd=SC(),T}flush(t){const n=t.transmuxing;n.executeStart=SC();const{decrypter:r,currentTransmuxState:a,decryptionPromise:i}=this;if(i)return this.asyncResult=!0,i.then(()=>this.flush(t));const l=[],{timeOffset:o}=a;if(r){const h=r.flush();h&&l.push(this.push(h.buffer,null,t))}const{demuxer:c,remuxer:d}=this;if(!c||!d){n.executeEnd=SC();const h=[Bze(t)];return this.asyncResult?Promise.resolve(h):h}const u=c.flush(o);return Zte(u)?(this.asyncResult=!0,u.then(h=>(this.flushRemux(l,h,t),l))):(this.flushRemux(l,u,t),this.asyncResult?Promise.resolve(l):l)}flushRemux(t,n,r){const{audioTrack:a,videoTrack:i,id3Track:l,textTrack:o}=n,{accurateTimeOffset:c,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${r.sn}${r.part>-1?" part: "+r.part:""} of ${this.id===io.MAIN?"level":"track"} ${r.level}`);const u=this.remuxer.remux(a,i,l,o,d,c,!0,this.id);t.push({remuxResult:u,chunkMeta:r}),r.transmuxing.executeEnd=SC()}resetInitialTimestamp(t){const{demuxer:n,remuxer:r}=this;!n||!r||(n.resetTimeStamp(t),r.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:n}=this;!t||!n||(t.resetContiguity(),n.resetNextTimestamp())}resetInitSegment(t,n,r,a,i){const{demuxer:l,remuxer:o}=this;!l||!o||(l.resetInitSegment(t,n,r,a),o.resetInitSegment(t,n,r,i))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,n,r,a,i){let l;return n&&n.method==="SAMPLE-AES"?l=this.transmuxSampleAes(t,n,r,a,i):l=this.transmuxUnencrypted(t,r,a,i),l}transmuxUnencrypted(t,n,r,a){const{audioTrack:i,videoTrack:l,id3Track:o,textTrack:c}=this.demuxer.demux(t,n,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(i,l,o,c,n,r,!1,this.id),chunkMeta:a}}transmuxSampleAes(t,n,r,a,i){return this.demuxer.demuxSampleAes(t,n,r).then(l=>({remuxResult:this.remuxer.remux(l.audioTrack,l.videoTrack,l.id3Track,l.textTrack,r,a,!1,this.id),chunkMeta:i}))}configureTransmuxer(t){const{config:n,observer:r,typeSupported:a}=this;let i;for(let h=0,m=a3e.length;h0&&(t==null?void 0:t.key)!=null&&t.iv!==null&&t.method!=null&&(n=t),n}const Bze=s=>({remuxResult:{},chunkMeta:s});function Zte(s){return"then"in s&&s.then instanceof Function}class nir{constructor(t,n,r,a,i){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=n,this.initSegmentData=r,this.duration=a,this.defaultInitPts=i||null}}class rir{constructor(t,n,r,a,i,l){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=n,this.accurateTimeOffset=r,this.trackSwitch=a,this.timeOffset=i,this.initSegmentChange=l}}let u4t=0;class Ins{constructor(t,n,r,a){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=u4t++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=c=>{const d=c.data,u=this.hls;if(!(!u||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.event){case"init":{var h;const m=(h=this.workerContext)==null?void 0:h.objectURL;m&&self.URL.revokeObjectURL(m);break}case"transmuxComplete":{this.handleTransmuxComplete(d.data);break}case"flush":{this.onFlush(d.data);break}case"workerLog":{u.logger[d.data.logType]&&u.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,u.trigger(d.event,d.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const d=new Error(`${c.message} (${c.filename}:${c.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(Ot.ERROR,{type:wo.OTHER_ERROR,details:yr.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})};const i=t.config;this.hls=t,this.id=n,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=r,this.onFlush=a;const l=(c,d)=>{d=d||{},d.frag=this.frag||void 0,c===Ot.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(c,d)};this.observer=new Urt,this.observer.on(Ot.FRAG_DECRYPTED,l),this.observer.on(Ot.ERROR,l);const o=S5t(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(i.workerPath||oar()){try{i.workerPath?(c.log(`loading Web Worker ${i.workerPath} for "${n}"`),this.workerContext=car(i.workerPath)):(c.log(`injecting Web Worker for "${n}"`),this.workerContext=lar());const{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:n,config:fm(i)})}catch(u){c.warn(`Error setting up "${n}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new d4t(this.observer,o,i,"",n,t.logger)}return}}this.transmuxer=new d4t(this.observer,o,i,"",n,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=u4t++;const n=this.hls.config,r=S5t(n.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:r,id:this.id,config:fm(n)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),dar(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const n=this.transmuxer;n&&(n.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,n,r,a,i,l,o,c,d,u){var h,m;d.transmuxing.start=self.performance.now();const{instanceNo:p,transmuxer:f}=this,x=l?l.start:i.start,y=i.decryptdata,v=this.frag,b=!(v&&i.cc===v.cc),N=!(v&&d.level===v.level),S=v?d.sn-v.sn:-1,A=this.part?d.part-this.part.index:-1,T=S===0&&d.id>1&&d.id===(v==null?void 0:v.stats.chunkCount),L=!N&&(S===1||S===0&&(A===1||T&&A<=0)),M=self.performance.now();(N||S||i.stats.parsing.start===0)&&(i.stats.parsing.start=M),l&&(A||!L)&&(l.stats.parsing.start=M);const I=!(v&&((h=i.initSegment)==null?void 0:h.url)===((m=v.initSegment)==null?void 0:m.url)),R=new rir(b,L,c,N,x,I);if(!L||b||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===io.MAIN?"level":"track"}: ${d.level} id: ${d.id} discontinuity: ${b} trackSwitch: ${N} contiguous: ${L} accurateTimeOffset: ${c} timeOffset: ${x} initSegmentChange: ${I}`);const z=new nir(r,a,n,o,u);this.configureTransmuxer(z)}if(this.frag=i,this.part=l,this.workerContext)this.workerContext.worker.postMessage({instanceNo:p,cmd:"demux",data:t,decryptdata:y,chunkMeta:d,state:R},t instanceof ArrayBuffer?[t]:[]);else if(f){const z=f.push(t,y,d,R);Zte(z)?z.then($=>{this.handleTransmuxComplete($)}).catch($=>{this.transmuxerError($,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(z)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:n,transmuxer:r}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:n,cmd:"flush",chunkMeta:t});else if(r){const a=r.flush(t);Zte(a)?a.then(i=>{this.handleFlushResult(i,t)}).catch(i=>{this.transmuxerError(i,t,"transmuxer-interface flush error")}):this.handleFlushResult(a,t)}}transmuxerError(t,n,r){this.hls&&(this.error=t,this.hls.trigger(Ot.ERROR,{type:wo.MEDIA_ERROR,details:yr.FRAG_PARSING_ERROR,chunkMeta:n,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:r}))}handleFlushResult(t,n){t.forEach(r=>{this.handleTransmuxComplete(r)}),this.onFlush(n)}configureTransmuxer(t){const{instanceNo:n,transmuxer:r}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:n,cmd:"configure",config:t}):r&&r.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}const h4t=100;class air extends Brt{constructor(t,n,r){super(t,n,r,"audio-stream-controller",io.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(Ot.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Ot.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(Ot.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Ot.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(Ot.BUFFER_RESET,this.onBufferReset,this),t.on(Ot.BUFFER_CREATED,this.onBufferCreated,this),t.on(Ot.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Ot.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Ot.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(Ot.FRAG_LOADING,this.onFragLoading,this),t.on(Ot.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(Ot.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Ot.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(Ot.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Ot.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(Ot.BUFFER_RESET,this.onBufferReset,this),t.off(Ot.BUFFER_CREATED,this.onBufferCreated,this),t.off(Ot.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Ot.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Ot.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(Ot.FRAG_LOADING,this.onFragLoading,this),t.off(Ot.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:n,id:r,initPTS:a,timescale:i,trackId:l}){if(r===io.MAIN){const o=n.cc,c=this.fragCurrent;if(this.initPTS[o]={baseTime:a,timescale:i,trackId:l},this.log(`InitPTS for cc: ${o} found from main: ${a/i} (${a}/${i}) trackId: ${l}`),this.mainAnchor=n,this.state===aa.WAITING_INIT_PTS){const d=this.waitingData;(!d&&!this.loadingParts||d&&d.frag.cc!==o)&&this.syncWithAnchor(n,d==null?void 0:d.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==o?(c.abortRequests(),this.syncWithAnchor(n,c)):this.state===aa.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,n){var r;const a=((r=this.mainFragLoading)==null?void 0:r.frag)||null;if(n&&(a==null?void 0:a.cc)===n.cc)return;const i=(a||t).cc,l=this.getLevelDetails(),o=this.getLoadPosition(),c=Zss(l,i,o);c&&(this.log(`Syncing with main frag at ${c.start} cc ${c.cc}`),this.startFragRequested=!1,this.nextLoadPosition=c.start,this.resetLoadingState(),this.state===aa.IDLE&&this.doTickIdle())}startLoad(t,n){if(!this.levels){this.startPosition=t,this.state=aa.STOPPED;return}const r=this.lastCurrentTime;this.stopLoad(),this.setInterval(h4t),r>0&&t===-1?(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),t=r,this.state=aa.IDLE):this.state=aa.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,this.tick()}doTick(){switch(this.state){case aa.IDLE:this.doTickIdle();break;case aa.WAITING_TRACK:{const{levels:t,trackId:n}=this,r=t==null?void 0:t[n],a=r==null?void 0:r.details;if(a&&!this.waitForLive(r)){if(this.waitForCdnTuneIn(a))break;this.state=aa.WAITING_INIT_PTS}break}case aa.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case aa.WAITING_INIT_PTS:{const t=this.waitingData;if(t){const{frag:n,part:r,cache:a,complete:i}=t,l=this.mainAnchor;if(this.initPTS[n.cc]!==void 0){this.waitingData=null,this.state=aa.FRAG_LOADING;const o=a.flush().buffer,c={frag:n,part:r,payload:o,networkDetails:null};this._handleFragmentLoadProgress(c),i&&super._handleFragmentLoadComplete(c)}else l&&l.cc!==t.frag.cc&&this.syncWithAnchor(l,t.frag)}else this.state=aa.IDLE}}this.onTickEnd()}resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:t}=this;t!=null&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){var t;const{hls:n,levels:r,media:a,trackId:i}=this,l=n.config;if(!this.buffering||!a&&!this.primaryPrefetch&&(this.startFragRequested||!l.startFragPrefetch)||!(r!=null&&r[i]))return;const o=r[i],c=o.details;if(!c||this.waitForLive(o)||this.waitForCdnTuneIn(c)){this.state=aa.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,dm.AUDIO,io.AUDIO));const u=this.getFwdBufferInfo(d,io.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,c)){n.trigger(Ot.BUFFER_EOS,{type:"audio"}),this.state=aa.ENDED;return}const h=u.len,m=n.maxBufferLength,p=c.fragments,f=p[0].start,x=this.getLoadPosition(),y=this.flushing?x:u.end;if(this.switchingTrack&&a){const N=x;c.PTSKnown&&Nf||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),a.currentTime=f+.05)}if(h>=m&&!this.switchingTrack&&yb.end){const S=this.fragmentTracker.getFragAtPos(y,io.MAIN);S&&S.end>b.end&&(b=S,this.mainFragLoading={frag:S,targetBufferTime:null})}if(v.start>b.end)return}this.loadFragment(v,o,y)}onMediaDetaching(t,n){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,n)}onAudioTracksUpdated(t,{audioTracks:n}){this.resetTransmuxer(),this.levels=n.map(r=>new Wte(r))}onAudioTrackSwitching(t,n){const r=!!n.url;this.trackId=n.id;const{fragCurrent:a}=this;a&&(a.abortRequests(),this.removeUnbufferedFrags(a.start)),this.resetLoadingState(),r?(this.switchingTrack=n,this.flushAudioIfNeeded(n),this.state!==aa.STOPPED&&(this.setInterval(h4t),this.state=aa.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=n,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,n){this.mainDetails=n.details;const r=this.cachedTrackLoadedData;r&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(Ot.AUDIO_TRACK_LOADED,r))}onAudioTrackLoaded(t,n){var r;const{levels:a}=this,{details:i,id:l,groupId:o,track:c}=n;if(!a){this.warn(`Audio tracks reset while loading track ${l} "${c.name}" of "${o}"`);return}const d=this.mainDetails;if(!d||i.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=n,this.state!==aa.STOPPED&&(this.state=aa.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${l} "${c.name}" of "${o}" loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:""},duration:${i.totalduration}`);const u=a[l];let h=0;if(i.live||(r=u.details)!=null&&r.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;if(u.details){var m;h=this.alignPlaylists(i,u.details,(m=this.levelLastLoaded)==null?void 0:m.details)}i.alignedSliding||(pns(i,d),i.alignedSliding||MTe(i,d),h=i.fragmentStart)}u.details=i,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(d,h),this.hls.trigger(Ot.AUDIO_TRACK_UPDATED,{details:i,id:l,groupId:n.groupId}),this.state===aa.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=aa.IDLE),this.tick()}_handleFragmentLoadProgress(t){var n;const r=t.frag,{part:a,payload:i}=t,{config:l,trackId:o,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);return}const d=c[o];if(!d){this.warn("Audio track is undefined on fragment load progress");return}const u=d.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(r.start);return}const h=l.defaultAudioCodec||d.audioCodec||"mp4a.40.2";let m=this.transmuxer;m||(m=this.transmuxer=new Ins(this.hls,io.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const p=this.initPTS[r.cc],f=(n=r.initSegment)==null?void 0:n.data;if(p!==void 0){const y=a?a.index:-1,v=y!==-1,b=new Ort(r.level,r.sn,r.stats.chunkCount,i.byteLength,y,v);m.push(i,f,h,"",r,a,u.totalduration,!1,b,p)}else{this.log(`Unknown video PTS for cc ${r.cc}, waiting for video PTS before demuxing audio frag ${r.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);const{cache:x}=this.waitingData=this.waitingData||{frag:r,part:a,cache:new fns,complete:!1};x.push(new Uint8Array(i)),this.state!==aa.STOPPED&&(this.state=aa.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(t){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,n){this.bufferFlushed=this.flushing=!1;const r=n.tracks.audio;r&&(this.mediaBuffer=r.buffer||null)}onFragLoading(t,n){!this.audioOnly&&n.frag.type===io.MAIN&&Fg(n.frag)&&(this.mainFragLoading=n,this.state===aa.IDLE&&this.tick())}onFragBuffered(t,n){const{frag:r,part:a}=n;if(r.type!==io.AUDIO){!this.audioOnly&&r.type===io.MAIN&&!r.elementaryStreams.video&&!r.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(r)){this.warn(`Fragment ${r.sn}${a?" p: "+a.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Fg(r)){this.fragPrevious=r;const i=this.switchingTrack;i&&(this.bufferedTrack=i,this.switchingTrack=null,this.hls.trigger(Ot.AUDIO_TRACK_SWITCHED,_h({},i)))}this.fragBufferedComplete(r,a),this.media&&this.tick()}onError(t,n){var r;if(n.fatal){this.state=aa.ERROR;return}switch(n.details){case yr.FRAG_GAP:case yr.FRAG_PARSING_ERROR:case yr.FRAG_DECRYPT_ERROR:case yr.FRAG_LOAD_ERROR:case yr.FRAG_LOAD_TIMEOUT:case yr.KEY_LOAD_ERROR:case yr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(io.AUDIO,n);break;case yr.AUDIO_TRACK_LOAD_ERROR:case yr.AUDIO_TRACK_LOAD_TIMEOUT:case yr.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===aa.WAITING_TRACK&&((r=n.context)==null?void 0:r.type)===hd.AUDIO_TRACK&&(this.state=aa.IDLE);break;case yr.BUFFER_ADD_CODEC_ERROR:case yr.BUFFER_APPEND_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)||this.resetLoadingState();break;case yr.BUFFER_FULL_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case yr.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onBufferFlushing(t,{type:n}){n!==dm.VIDEO&&(this.flushing=!0)}onBufferFlushed(t,{type:n}){if(n!==dm.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===aa.ENDED&&(this.state=aa.IDLE);const r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,n,io.AUDIO),this.tick())}}_handleTransmuxComplete(t){var n;const r="audio",{hls:a}=this,{remuxResult:i,chunkMeta:l}=t,o=this.getCurrentContext(l);if(!o){this.resetWhenMissingContext(l);return}const{frag:c,part:d,level:u}=o,{details:h}=u,{audio:m,text:p,id3:f,initSegment:x}=i;if(this.fragContextChanged(c)||!h){this.fragmentTracker.removeFragment(c);return}if(this.state=aa.PARSING,this.switchingTrack&&m&&this.completeAudioSwitch(this.switchingTrack),x!=null&&x.tracks){const y=c.initSegment||c;if(this.unhandledEncryptionError(x,c))return;this._bufferInitSegment(u,x.tracks,y,l),a.trigger(Ot.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:r,tracks:x.tracks})}if(m){const{startPTS:y,endPTS:v,startDTS:b,endDTS:N}=m;d&&(d.elementaryStreams[dm.AUDIO]={startPTS:y,endPTS:v,startDTS:b,endDTS:N}),c.setElementaryStreamInfo(dm.AUDIO,y,v,b,N),this.bufferFragmentData(m,c,d,l)}if(f!=null&&(n=f.samples)!=null&&n.length){const y=Yh({id:r,frag:c,details:h},f);a.trigger(Ot.FRAG_PARSING_METADATA,y)}if(p){const y=Yh({id:r,frag:c,details:h},p);a.trigger(Ot.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(t,n,r,a){if(this.state!==aa.PARSING||(n.video&&delete n.video,n.audiovideo&&delete n.audiovideo,!n.audio))return;const i=n.audio;i.id=io.AUDIO;const l=t.audioCodec;this.log(`Init audio buffer, container:${i.container}, codecs[level/parsed]=[${l}/${i.codec}]`),l&&l.split(",").length===1&&(i.levelCodec=l),this.hls.trigger(Ot.BUFFER_CODECS,n);const o=i.initSegment;if(o!=null&&o.byteLength){const c={type:"audio",frag:r,part:null,chunkMeta:a,parent:r.type,data:o};this.hls.trigger(Ot.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(t,n,r){const a=this.fragmentTracker.getState(t);if(this.switchingTrack||a===e0.NOT_LOADED||a===e0.PARTIAL){var i;if(!Fg(t))this._loadInitSegment(t,n);else if((i=n.details)!=null&&i.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=aa.WAITING_INIT_PTS;const l=this.mainDetails;l&&l.fragmentStart!==n.details.fragmentStart&&MTe(n.details,l)}else super.loadFragment(t,n,r)}else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack){const{name:n,lang:r,assocLang:a,characteristics:i,audioCodec:l,channels:o}=this.bufferedTrack;u7({name:n,lang:r,assocLang:a,characteristics:i,audioCodec:l,channels:o},t,CD)||(STe(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:n}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,n.trigger(Ot.AUDIO_TRACK_SWITCHED,_h({},t))}}class Krt extends PN{constructor(t,n){super(n,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,n,r){const a=n==null?void 0:n.renditionReports;if(a){let i=-1;for(let l=0;l=0&&u>n.partTarget&&(c+=1)}const d=r&&C5t(r);return new A5t(o,c>=0?c:void 0,d)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,n){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,n){if(n)try{return n.addDirectives(t)}catch(r){this.warn(`Could not construct new URL with HLS Delivery Directives: ${r}`)}return t}playlistLoaded(t,n,r){const{details:a,stats:i}=n,l=self.performance.now(),o=i.loading.first?Math.max(0,l-i.loading.first):0;a.advancedDateTime=Date.now()-o;const c=this.hls.config.timelineOffset;if(c!==a.appliedTimelineOffset){const u=Math.max(c||0,0);a.appliedTimelineOffset=u,a.fragments.forEach(h=>{h.setStart(h.playlistOffset+u)})}if(a.live||r!=null&&r.live){const u="levelInfo"in n?n.levelInfo:n.track;if(a.reloaded(r),r&&a.fragments.length>0){Zrr(r,a,this);const b=a.playlistParsingError;if(b){this.warn(b);const N=this.hls;if(!N.config.ignorePlaylistParsingErrors){var d;const{networkDetails:S}=n;N.trigger(Ot.ERROR,{type:wo.NETWORK_ERROR,details:yr.LEVEL_PARSING_ERROR,fatal:!1,url:a.url,error:b,reason:b.message,level:n.level||void 0,parent:(d=a.fragments[0])==null?void 0:d.type,networkDetails:S,stats:i});return}a.playlistParsingError=null}}a.requestScheduled===-1&&(a.requestScheduled=i.loading.start);const h=this.hls.mainForwardBufferInfo,m=h?h.end-h.len:0,p=(a.edge-m)*1e3,f=cns(a,p);if(a.requestScheduled+f0){if(I>a.targetduration*3)this.log(`Playlist last advanced ${M.toFixed(2)}s ago. Omitting segment and part directives.`),y=void 0,v=void 0;else if(r!=null&&r.tuneInGoal&&I-a.partTarget>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${R} with playlist age: ${a.age}`),R=0;else{const z=Math.floor(R/a.targetduration);if(y+=z,v!==void 0){const $=Math.round(R%a.targetduration/a.partTarget);v+=$}this.log(`CDN Tune-in age: ${a.ageHeader}s last advanced ${M.toFixed(2)}s goal: ${R} skip sn ${z} to part ${v}`)}a.tuneInGoal=R}if(x=this.getDeliveryDirectives(a,n.deliveryDirectives,y,v),b||!L){a.requestScheduled=l,this.loadingPlaylist(u,x);return}}else(a.canBlockReload||a.canSkipUntil)&&(x=this.getDeliveryDirectives(a,n.deliveryDirectives,y,v));x&&y!==void 0&&a.canBlockReload&&(a.requestScheduled=i.loading.first+Math.max(f-o*2,f/2)),this.scheduleLoading(u,x,a)}else this.clearTimer()}scheduleLoading(t,n,r){const a=r||t.details;if(!a){this.loadingPlaylist(t,n);return}const i=self.performance.now(),l=a.requestScheduled;if(i>=l){this.loadingPlaylist(t,n);return}const o=l-i;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,n),o)}getDeliveryDirectives(t,n,r,a){let i=C5t(t);return n!=null&&n.skip&&t.deltaUpdateFailed&&(r=n.msn,a=n.part,i=s3e.No),new A5t(r,a,i)}checkRetry(t){const n=t.details,r=CTe(t),a=t.errorAction,{action:i,retryCount:l=0,retryConfig:o}=a||{},c=!!a&&!!o&&(i===Yy.RetryRequest||!a.resolved&&i===Yy.SendAlternateToPenaltyBox);if(c){var d;if(l>=o.maxNumRetry)return!1;if(r&&(d=t.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${l+1}/${o.maxNumRetry} after "${n}" without delivery-directives`),this.loadPlaylist();else{const u=Rrt(o,l);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${l+1}/${o.maxNumRetry} after "${n}" in ${u}ms`)}t.levelRetry=!0,a.resolved=!0}return c}}function Rns(s,t){if(s.length!==t.length)return!1;for(let n=0;ns[a]!==t[a])}function qKe(s,t){return t.label.toLowerCase()===s.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(s.lang||"").toLowerCase())}class iir extends Krt{constructor(t){super(t,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ot.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Ot.LEVEL_LOADING,this.onLevelLoading,this),t.on(Ot.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Ot.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(Ot.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ot.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Ot.LEVEL_LOADING,this.onLevelLoading,this),t.off(Ot.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Ot.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(Ot.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,n){this.tracks=n.audioTracks||[]}onAudioTrackLoaded(t,n){const{id:r,groupId:a,details:i}=n,l=this.tracksInGroup[r];if(!l||l.groupId!==a){this.warn(`Audio track with id:${r} and group:${a} not found in active group ${l==null?void 0:l.groupId}`);return}const o=l.details;l.details=n.details,this.log(`Audio track ${r} "${l.name}" lang:${l.lang} group:${a} loaded [${i.startSN}-${i.endSN}]`),r===this.trackId&&this.playlistLoaded(r,n,o)}onLevelLoading(t,n){this.switchLevel(n.level)}onLevelSwitching(t,n){this.switchLevel(n.level)}switchLevel(t){const n=this.hls.levels[t];if(!n)return;const r=n.audioGroups||null,a=this.groupIds;let i=this.currentTrack;if(!r||(a==null?void 0:a.length)!==(r==null?void 0:r.length)||r!=null&&r.some(o=>(a==null?void 0:a.indexOf(o))===-1)){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(m=>!r||r.indexOf(m.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(m=>m.default)&&(this.selectDefaultTrack=!1),o.forEach((m,p)=>{m.id=p});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!i&&c){const m=w4(c,o,CD);if(m>-1)i=o[m];else{const p=w4(c,this.tracks);i=this.tracks[p]}}let d=this.findTrackId(i);d===-1&&i&&(d=this.findTrackId(null));const u={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${r==null?void 0:r.join(",")}`),this.hls.trigger(Ot.AUDIO_TRACKS_UPDATED,u);const h=this.trackId;if(d!==-1&&h===-1)this.setAudioTrack(d);else if(o.length&&h===-1){var l;const m=new Error(`No audio track selected for current audio group-ID(s): ${(l=this.groupIds)==null?void 0:l.join(",")} track count: ${o.length}`);this.warn(m.message),this.hls.trigger(Ot.ERROR,{type:wo.MEDIA_ERROR,details:yr.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:m})}}}onError(t,n){n.fatal||!n.context||n.context.type===hd.AUDIO_TRACK&&n.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(n.context.groupId)!==-1)&&this.checkRetry(n)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){const n=this.hls;if(n.config.audioPreference=t,t){const r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){const a=this.currentTrack;if(a&&u7(t,a,CD))return a;const i=w4(t,this.tracksInGroup,CD);if(i>-1){const l=this.tracksInGroup[i];return this.setAudioTrack(i),l}else if(a){let l=n.loadLevel;l===-1&&(l=n.firstAutoLevel);const o=xrr(t,n.levels,r,l,CD);if(o===-1)return null;n.nextLoadLevel=o}if(t.channels||t.audioCodec){const l=w4(t,r);if(l>-1)return r[l]}}}return null}setAudioTrack(t){const n=this.tracksInGroup;if(t<0||t>=n.length){this.warn(`Invalid audio track id: ${t}`);return}this.selectDefaultTrack=!1;const r=this.currentTrack,a=n[t],i=a.details&&!a.details.live;if(t===this.trackId&&a===r&&i||(this.log(`Switching to audio-track ${t} "${a.name}" lang:${a.lang} group:${a.groupId} channels:${a.channels}`),this.trackId=t,this.currentTrack=a,this.hls.trigger(Ot.AUDIO_TRACK_SWITCHING,_h({},a)),i))return;const l=this.switchParams(a.url,r==null?void 0:r.details,a.details);this.loadPlaylist(l)}findTrackId(t){const n=this.tracksInGroup;for(let r=0;r{const r={label:"async-blocker",execute:n,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(r,t)})}prependBlocker(t){return new Promise(n=>{if(this.queues){const r={label:"async-blocker-prepend",execute:n,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(r)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var n;const r=(n=t[0])==null?void 0:n.label;(r==="async-blocker"||r==="async-blocker-prepend")&&(t[0].execute(),t.splice(0,1))})}unblockAudio(t){if(this.queues===null)return;this.queues.audio[0]===t&&this.shiftAndExecuteNext("audio")}executeNext(t){if(this.queues===null||this.tracks===null)return;const n=this.queues[t];if(n.length){const a=n[0];try{a.execute()}catch(i){var r;if(a.onError(i),this.queues===null||this.tracks===null)return;const l=(r=this.tracks[t])==null?void 0:r.buffer;l!=null&&l.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues!==null&&(this.queues[t].shift(),this.executeNext(t))}current(t){var n;return((n=this.queues)==null?void 0:n[t][0])||null}toString(){const{queues:t,tracks:n}=this;return t===null||n===null?"":` ${this.list("video")} ${this.list("audio")} ${this.list("audiovideo")}}`}list(t){var n,r;return(n=this.queues)!=null&&n[t]||(r=this.tracks)!=null&&r[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var n;const r=(n=this.tracks)==null?void 0:n[t],a=r==null?void 0:r.buffer;return a?`SourceBuffer${a.updating?" updating":""}${r.ended?" ended":""}${r.ending?" ending":""}`:"none"}listOps(t){var n;return((n=this.queues)==null?void 0:n[t].map(r=>r.label).join(", "))||""}}const m4t=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Dns="HlsJsTrackRemovedError";class lir extends Error{constructor(t){super(t),this.name=Dns}}class cir extends PN{constructor(t,n){super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=r=>{var a;this.hls&&((a=this.mediaSource)==null?void 0:a.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=r=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=r=>{const{media:a,mediaSource:i}=this;r&&this.log("Media source opened"),!(!a||!i)&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),a.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(Ot.MEDIA_ATTACHED,{media:a,mediaSource:i}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:r,_objectUrl:a}=this;r!==a&&this.error(`Media element src was set while attaching MediaSource (${a} > ${r})`)},this.hls=t,this.fragmentTracker=n,this.appendSource=Tnr(SP(t.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:t}=this;t.on(Ot.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Ot.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ot.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Ot.BUFFER_RESET,this.onBufferReset,this),t.on(Ot.BUFFER_APPENDING,this.onBufferAppending,this),t.on(Ot.BUFFER_CODECS,this.onBufferCodecs,this),t.on(Ot.BUFFER_EOS,this.onBufferEos,this),t.on(Ot.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Ot.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Ot.FRAG_PARSED,this.onFragParsed,this),t.on(Ot.FRAG_CHANGED,this.onFragChanged,this),t.on(Ot.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Ot.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Ot.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ot.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Ot.BUFFER_RESET,this.onBufferReset,this),t.off(Ot.BUFFER_APPENDING,this.onBufferAppending,this),t.off(Ot.BUFFER_CODECS,this.onBufferCodecs,this),t.off(Ot.BUFFER_EOS,this.onBufferEos,this),t.off(Ot.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Ot.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Ot.FRAG_PARSED,this.onFragParsed,this),t.off(Ot.FRAG_CHANGED,this.onFragChanged,this),t.off(Ot.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:n}=this;if(!t)return null;const r={};if(this.operationQueue){const i=this.isUpdating();i||this.operationQueue.removeBlockers();const l=this.isQueued();(i||l)&&this.warn(`Transfering MediaSource with${l?" operations in queue":""}${i?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const a=this.transferData;return!this.sourceBufferCount&&a&&a.mediaSource===n?Yh(r,a.tracks):this.sourceBuffers.forEach(i=>{const[l]=i;l&&(r[l]=Yh({},this.tracks[l]),this.removeBuffer(l)),i[0]=i[1]=null}),{media:t,mediaSource:n,tracks:r}}initTracks(){const t={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=t,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,n){var r;let a=2;(n.audio&&!n.video||!n.altAudio)&&(a=1),this.bufferCodecEventsTotal=a,this.log(`${a} bufferCodec event(s) expected.`),(r=this.transferData)!=null&&r.mediaSource&&this.sourceBufferCount&&a&&this.bufferCreated()}onMediaAttaching(t,n){const r=this.media=n.media;this.transferData=this.overrides=void 0;const a=SP(this.appendSource);if(a){const i=!!n.mediaSource;(i||n.overrides)&&(this.transferData=n,this.overrides=n.overrides);const l=this.mediaSource=n.mediaSource||new a;if(this.assignMediaSource(l),i)this._objectUrl=r.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(l);if(this.appendSource)try{r.removeAttribute("src");const c=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||c&&l instanceof c,p4t(r),dir(r,o),r.load()}catch{r.src=o}else r.src=o}r.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var n,r;this.log(`${((n=this.transferData)==null?void 0:n.mediaSource)===t?"transferred":"created"} media source: ${(r=t.constructor)==null?void 0:r.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,n=this.transferData;if(!n||!t)return;const r=this.tracks,a=n.tracks,i=a?Object.keys(a):null,l=i?i.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(a&&i&&l){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal}) required tracks: ${fm(r,(c,d)=>c==="initSegment"?void 0:d)}; transfer tracks: ${fm(a,(c,d)=>c==="initSegment"?void 0:d)}}`),!Pss(a,r)){n.mediaSource=null,n.tracks=void 0;const c=t.currentTime,d=this.details,u=Math.max(c,(d==null?void 0:d.fragments[0].start)||0);if(u-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(a)}"->"${Object.keys(r)}") start time: ${u} currentTime: ${c}`),this.onMediaDetaching(Ot.MEDIA_DETACHING,{}),this.onMediaAttaching(Ot.MEDIA_ATTACHING,n),t.currentTime=u;return}this.transferData=void 0,i.forEach(c=>{const d=c,u=a[d];if(u){const h=u.buffer;if(h){const m=this.fragmentTracker,p=u.id;if(m.hasFragments(p)||m.hasParts(p)){const y=uc.getBuffered(h);m.detectEvictedFragments(d,y,p,null,!0)}const f=Uze(d),x=[d,h];this.sourceBuffers[f]=x,h.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,u)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var t;const n=(t=this.mediaSource)==null?void 0:t.readyState;return n==="open"||n==="ended"}onMediaDetaching(t,n){const r=!!n.transferMedia;this.transferData=this.overrides=void 0;const{media:a,mediaSource:i,_objectUrl:l}=this;if(i){if(this.log(`media source ${r?"transferring":"detaching"}`),r)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=i.readyState==="open";try{const c=i.sourceBuffers;for(let d=c.length;d--;)o&&c[d].abort(),i.removeSourceBuffer(c[d]);o&&i.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}i.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("sourceended",this._onMediaSourceEnded),i.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(i.removeEventListener("startstreaming",this._onStartStreaming),i.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}a&&(a.removeEventListener("emptied",this._onMediaEmptied),r||(l&&self.URL.revokeObjectURL(l),this.mediaSrc===l?(a.removeAttribute("src"),this.appendSource&&p4t(a),a.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(Ot.MEDIA_DETACHED,n)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var n;const r=(n=this.tracks[t])==null?void 0:n.buffer;if(this.removeBuffer(t),r)try{var a;(a=this.mediaSource)!=null&&a.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(i){this.warn(`onBufferReset ${t}`,i)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[Uze(t)]=[null,null];const n=this.tracks[t];n&&(n.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new oir(this.tracks)}onBufferCodecs(t,n){var r;const a=this.tracks,i=Object.keys(n);this.log(`BUFFER_CODECS: "${i}" (current SB count ${this.sourceBufferCount})`);const l="audiovideo"in n&&(a.audio||a.video)||a.audiovideo&&("audio"in n||"video"in n),o=!l&&this.sourceBufferCount&&this.media&&i.some(c=>!a[c]);if(l||o){this.warn(`Unsupported transition between "${Object.keys(a)}" and "${i}" SourceBuffers`);return}i.forEach(c=>{var d,u;const h=n[c],{id:m,codec:p,levelCodec:f,container:x,metadata:y,supplemental:v}=h;let b=a[c];const N=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[c],S=N!=null&&N.buffer?N:b,A=(S==null?void 0:S.pendingCodec)||(S==null?void 0:S.codec),T=S==null?void 0:S.levelCodec;b||(b=a[c]={buffer:void 0,listeners:[],codec:p,supplemental:v,container:x,levelCodec:f,metadata:y,id:m});const L=t3e(A,T),M=L==null?void 0:L.replace(m4t,"$1");let I=t3e(p,f);const R=(u=I)==null?void 0:u.replace(m4t,"$1");I&&L&&M!==R&&(c.slice(0,5)==="audio"&&(I=NTe(I,this.appendSource)),this.log(`switching codec ${A} to ${I}`),I!==(b.pendingCodec||b.codec)&&(b.pendingCodec=I),b.container=x,this.appendChangeType(c,x,I))}),(this.tracksReady||this.sourceBufferCount)&&(n.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!n.video&&((r=n.audio)==null?void 0:r.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,n)=>{const r=this.tracks[n];return t[n]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},t},{})}appendChangeType(t,n,r){const a=`${n};codecs=${r}`,i={label:`change-type=${a}`,execute:()=>{const l=this.tracks[t];if(l){const o=l.buffer;o!=null&&o.changeType&&(this.log(`changing ${t} sourceBuffer type to ${a}`),o.changeType(a),l.codec=r,l.container=n)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:l=>{this.warn(`Failed to change ${t} SourceBuffer type`,l)}};this.append(i,t,this.isPending(this.tracks[t]))}blockAudio(t){var n;const r=t.start,a=r+t.duration*.05;if(((n=this.fragmentTracker.getAppendedFrag(r,io.MAIN))==null?void 0:n.gap)===!0)return;const l={label:"block-audio",execute:()=>{var o;const c=this.tracks.video;(this.lastVideoAppendEnd>a||c!=null&&c.buffer&&uc.isBuffered(c.buffer,a)||((o=this.fragmentTracker.getAppendedFrag(a,io.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:l,frag:t},this.append(l,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:n}=this;t&&n&&(this.blockedAudioAppend=null,n.unblockAudio(t.op))}onBufferAppending(t,n){const{tracks:r}=this,{data:a,type:i,parent:l,frag:o,part:c,chunkMeta:d,offset:u}=n,h=d.buffering[i],{sn:m,cc:p}=o,f=self.performance.now();h.start=f;const x=o.stats.buffering,y=c?c.stats.buffering:null;x.start===0&&(x.start=f),y&&y.start===0&&(y.start=f);const v=r.audio;let b=!1;i==="audio"&&(v==null?void 0:v.container)==="audio/mpeg"&&(b=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const N=r.video,S=N==null?void 0:N.buffer;if(S&&m!=="initSegment"){const L=c||o,M=this.blockedAudioAppend;if(i==="audio"&&l!=="main"&&!this.blockedAudioAppend&&!(N.ending||N.ended)){const R=L.start+L.duration*.05,z=S.buffered,$=this.currentOp("video");!z.length&&!$?this.blockAudio(L):!$&&!uc.isBuffered(S,R)&&this.lastVideoAppendEndR||I{var L;h.executeStart=self.performance.now();const M=(L=this.tracks[i])==null?void 0:L.buffer;M&&(b?this.updateTimestampOffset(M,A,.1,i,m,p):u!==void 0&&Bi(u)&&this.updateTimestampOffset(M,u,1e-6,i,m,p)),this.appendExecutor(a,i)},onStart:()=>{},onComplete:()=>{const L=self.performance.now();h.executeEnd=h.end=L,x.first===0&&(x.first=L),y&&y.first===0&&(y.first=L);const M={};this.sourceBuffers.forEach(([I,R])=>{I&&(M[I]=uc.getBuffered(R))}),this.appendErrors[i]=0,i==="audio"||i==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(Ot.BUFFER_APPENDED,{type:i,frag:o,part:c,chunkMeta:d,parent:o.type,timeRanges:M})},onError:L=>{var M;const I={type:wo.MEDIA_ERROR,parent:o.type,details:yr.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:o,part:c,chunkMeta:d,error:L,err:L,fatal:!1},R=(M=this.media)==null?void 0:M.error;if(L.code===DOMException.QUOTA_EXCEEDED_ERR||L.name=="QuotaExceededError"||"quota"in L)I.details=yr.BUFFER_FULL_ERROR;else if(L.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!R)I.errorAction=l$(!0);else if(L.name===Dns&&this.sourceBufferCount===0)I.errorAction=l$(!0);else{const z=++this.appendErrors[i];this.warn(`Failed ${z}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer (${R||"no media error"})`),(z>=this.hls.config.appendErrorMaxRetry||R)&&(I.fatal=!0)}this.hls.trigger(Ot.ERROR,I)}};this.log(`queuing "${i}" append sn: ${m}${c?" p: "+c.index:""} of ${o.type===io.MAIN?"level":"track"} ${o.level} cc: ${p}`),this.append(T,i,this.isPending(this.tracks[i]))}getFlushOp(t,n,r){return this.log(`queuing "${t}" remove ${n}-${r}`),{label:"remove",execute:()=>{this.removeExecutor(t,n,r)},onStart:()=>{},onComplete:()=>{this.hls.trigger(Ot.BUFFER_FLUSHED,{type:t})},onError:a=>{this.warn(`Failed to remove ${n}-${r} from "${t}" SourceBuffer`,a)}}}onBufferFlushing(t,n){const{type:r,startOffset:a,endOffset:i}=n;r?this.append(this.getFlushOp(r,a,i),r):this.sourceBuffers.forEach(([l])=>{l&&this.append(this.getFlushOp(l,a,i),l)})}onFragParsed(t,n){const{frag:r,part:a}=n,i=[],l=a?a.elementaryStreams:r.elementaryStreams;l[dm.AUDIOVIDEO]?i.push("audiovideo"):(l[dm.AUDIO]&&i.push("audio"),l[dm.VIDEO]&&i.push("video"));const o=()=>{const c=self.performance.now();r.stats.buffering.end=c,a&&(a.stats.buffering.end=c);const d=a?a.stats:r.stats;this.hls.trigger(Ot.FRAG_BUFFERED,{frag:r,part:a,stats:d,id:r.type})};i.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${r.type} level: ${r.level} sn: ${r.sn}`),this.blockBuffers(o,i).catch(c=>{this.warn(`Fragment buffered callback ${c}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,n){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){const n=this.tracks[t];if(n)return!n.ended||n.ending}return!1})}onBufferEos(t,n){var r;this.sourceBuffers.forEach(([l])=>{if(l){const o=this.tracks[l];(!n.type||n.type===l)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${l} buffer reached EOS`)))}});const a=((r=this.overrides)==null?void 0:r.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([l])=>{var o;return l&&!((o=this.tracks[l])!=null&&o.ended)})?a?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:l}=this;if(!l||l.readyState!=="open"){l&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${l.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),l.endOfStream(),this.hls.trigger(Ot.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(Ot.BUFFERED_TO_END,void 0)):n.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(t!==null){const n=this.tracks[t];n&&(n.ending=!1)}})}onLevelUpdated(t,{details:n}){n.fragments.length&&(this.details=n,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)})}onError(t,n){if(n.details===yr.BUFFER_APPEND_ERROR&&n.frag){var r;const a=(r=n.errorAction)==null?void 0:r.nextAutoLevel;Bi(a)&&a!==n.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:n,media:r}=this;if(!r||n===null||!this.sourceBufferCount)return;const a=t.config,i=r.currentTime,l=n.levelTargetDuration,o=n.live&&a.liveBackBufferLength!==null?a.liveBackBufferLength:a.backBufferLength;if(Bi(o)&&o>=0){const d=Math.max(o,l),u=Math.floor(i/l)*l-d;this.flushBackBuffer(i,l,u)}const c=a.frontBufferFlushThreshold;if(Bi(c)&&c>0){const d=Math.max(a.maxBufferLength,c),u=Math.max(d,l),h=Math.floor(i/l)*l+u;this.flushFrontBuffer(i,l,h)}}flushBackBuffer(t,n,r){this.sourceBuffers.forEach(([a,i])=>{if(i){const o=uc.getBuffered(i);if(o.length>0&&r>o.start(0)){var l;this.hls.trigger(Ot.BACK_BUFFER_REACHED,{bufferEnd:r});const c=this.tracks[a];if((l=this.details)!=null&&l.live)this.hls.trigger(Ot.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(c!=null&&c.ended){this.log(`Cannot flush ${a} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(Ot.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:a})}}})}flushFrontBuffer(t,n,r){this.sourceBuffers.forEach(([a,i])=>{if(i){const l=uc.getBuffered(i),o=l.length;if(o<2)return;const c=l.start(o-1),d=l.end(o-1);if(r>c||t>=c&&t<=d)return;this.hls.trigger(Ot.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:a})}})}getDurationAndRange(){var t;const{details:n,mediaSource:r}=this;if(!n||!this.media||(r==null?void 0:r.readyState)!=="open")return null;const a=n.edge;if(n.live&&this.hls.config.liveDurationInfinity){if(n.fragments.length&&r.setLiveSeekableRange){const d=Math.max(0,n.fragmentStart),u=Math.max(d,a);return{duration:1/0,start:d,end:u}}return{duration:1/0}}const i=(t=this.overrides)==null?void 0:t.duration;if(i)return Bi(i)?{duration:i}:null;const l=this.media.duration,o=Bi(r.duration)?r.duration:0;return a>o&&a>l||!Bi(l)?{duration:a}:null}updateMediaSource({duration:t,start:n,end:r}){const a=this.mediaSource;!this.media||!a||a.readyState!=="open"||(a.duration!==t&&(Bi(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),a.duration=t),n!==void 0&&r!==void 0&&(this.log(`MediaSource duration is set to ${a.duration}. Setting seekable range to ${n}-${r}.`),a.setLiveSeekableRange(n,r)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:n,tracks:r}=this;if(this.log(`checkPendingTracks (pending: ${n} codec events expected: ${t}) ${fm(r)}`),this.tracksReady){var a;const i=(a=this.transferData)==null?void 0:a.tracks;i&&Object.keys(i).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([n,r])=>{if(n){const a=this.tracks[n];t[n]={buffer:r,container:a.container,codec:a.codec,supplemental:a.supplemental,levelCodec:a.levelCodec,id:a.id,metadata:a.metadata}}}),this.hls.trigger(Ot.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([n])=>{this.executeNext(n)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(Ot.ERROR,{type:wo.MEDIA_ERROR,details:yr.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:n,mediaSource:r}=this;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(const i in t){const l=i,o=t[l];if(this.isPending(o)){const c=this.getTrackCodec(o,l),d=`${o.container};codecs=${c}`;o.codec=c,this.log(`creating sourceBuffer(${d})${this.currentOp(l)?" Queued":""} ${fm(o)}`);try{const u=r.addSourceBuffer(d),h=Uze(l),m=[l,u];n[h]=m,o.buffer=u}catch(u){var a;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(l),(a=this.operationQueue)==null||a.removeBlockers(),delete this.tracks[l],this.hls.trigger(Ot.ERROR,{type:wo.MEDIA_ERROR,details:yr.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:l,mimeType:d,parent:o.id});return}this.trackSourceBuffer(l,o)}}this.bufferCreated()}getTrackCodec(t,n){const r=t.supplemental;let a=t.codec;r&&(n==="video"||n==="audiovideo")&&Hte(r,"video")&&(a=Qnr(a,r));const i=t3e(a,t.levelCodec);return i?n.slice(0,5)==="audio"?NTe(i,this.appendSource):i:""}trackSourceBuffer(t,n){const r=n.buffer;if(!r)return;const a=this.getTrackCodec(n,t);this.tracks[t]={buffer:r,codec:a,container:n.container,levelCodec:n.levelCodec,supplemental:n.supplemental,metadata:n.metadata,id:n.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(i,l)=>{const o=l.removedRanges;o!=null&&o.length&&this.hls.trigger(Ot.BUFFER_FLUSHED,{type:i})})}get mediaSrc(){var t,n;const r=((t=this.media)==null||(n=t.querySelector)==null?void 0:n.call(t,"source"))||this.media;return r==null?void 0:r.src}onSBUpdateStart(t){const n=this.currentOp(t);n&&n.onStart()}onSBUpdateEnd(t){var n;if(((n=this.mediaSource)==null?void 0:n.readyState)==="closed"){this.resetBuffer(t);return}const r=this.currentOp(t);r&&(r.onComplete(),this.shiftAndExecuteNext(t))}onSBUpdateError(t,n){var r;const a=new Error(`${t} SourceBuffer error. MediaSource readyState: ${(r=this.mediaSource)==null?void 0:r.readyState}`);this.error(`${a}`,n),this.hls.trigger(Ot.ERROR,{type:wo.MEDIA_ERROR,details:yr.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:a,fatal:!1});const i=this.currentOp(t);i&&i.onError(a)}updateTimestampOffset(t,n,r,a,i,l){const o=n-t.timestampOffset;Math.abs(o)>=r&&(this.log(`Updating ${a} SourceBuffer timestampOffset to ${n} (sn: ${i} cc: ${l})`),t.timestampOffset=n)}removeExecutor(t,n,r){const{media:a,mediaSource:i}=this,l=this.tracks[t],o=l==null?void 0:l.buffer;if(!a||!i||!o){this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(t);return}const c=Bi(a.duration)?a.duration:1/0,d=Bi(i.duration)?i.duration:1/0,u=Math.max(0,n),h=Math.min(r,c,d);h>u&&(!l.ending||l.ended)?(l.ended=!1,this.log(`Removing [${u},${h}] from the ${t} SourceBuffer`),o.remove(u,h)):this.shiftAndExecuteNext(t)}appendExecutor(t,n){const r=this.tracks[n],a=r==null?void 0:r.buffer;if(!a)throw new lir(`Attempting to append to the ${n} SourceBuffer, but it does not exist`);r.ending=!1,r.ended=!1,a.appendBuffer(t)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(n=>{this.warn(`SourceBuffer blocked callback ${n}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(n){this.warn(`Callback run without blocking ${this.operationQueue} ${n}`)}}isUpdating(){return this.sourceBuffers.some(([t,n])=>t&&n.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}blockBuffers(t,n=this.sourceBufferTypes){if(!n.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:r}=this,a=n.map(l=>this.appendBlocker(l));return n.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(a).then(l=>{r===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(n=>{var r;const a=(r=this.tracks[n])==null?void 0:r.buffer;!a||a.updating||this.shiftAndExecuteNext(n)})}append(t,n,r){this.operationQueue&&this.operationQueue.append(t,n,r)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,n)=>t+(this.isPending(this.tracks[n])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[n])=>t+(n?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,n,r){const a=this.tracks[t];if(!a)return;const i=a.buffer;if(!i)return;const l=r.bind(this,t);a.listeners.push({event:n,listener:l}),i.addEventListener(n,l)}removeBufferListeners(t){const n=this.tracks[t];if(!n)return;const r=n.buffer;r&&(n.listeners.forEach(a=>{r.removeEventListener(a.event,a.listener)}),n.listeners.length=0)}}function p4t(s){const t=s.querySelectorAll("source");[].slice.call(t).forEach(n=>{s.removeChild(n)})}function dir(s,t){const n=self.document.createElement("source");n.type="video/mp4",n.src=t,s.appendChild(n)}function Uze(s){return s==="audio"?1:0}class Yrt{constructor(t){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(Ot.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(Ot.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Ot.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Ot.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Ot.BUFFER_CODECS,this.onBufferCodecs,this),t.on(Ot.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(Ot.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(Ot.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Ot.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Ot.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Ot.BUFFER_CODECS,this.onBufferCodecs,this),t.off(Ot.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,n){const r=this.hls.levels[n.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}onMediaAttaching(t,n){this.media=n.media instanceof HTMLVideoElement?n.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,n){const r=this.hls;this.restrictedLevels=[],this.firstLevel=n.firstLevel,r.config.capLevelToPlayerSize&&n.video&&this.startCapping()}onLevelsUpdated(t,n){this.timer&&Bi(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,n){this.hls.config.capLevelToPlayerSize&&n.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const t=this.hls.levels;if(t.length){const n=this.hls,r=this.getMaxLevel(t.length-1);r!==this.autoLevelCapping&&n.logger.log(`Setting autoLevelCapping to ${r}: ${t[r].height}p@${t[r].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),n.autoLevelCapping=r,n.autoLevelEnabled&&n.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=n.autoLevelCapping}}}getMaxLevel(t){const n=this.hls.levels;if(!n.length)return-1;const r=n.filter((a,i)=>this.isLevelAllowed(a)&&i<=t);return this.clientRect=null,Yrt.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,n={width:0,height:0};if(t){const r=t.getBoundingClientRect();n.width=r.width,n.height=r.height,!n.width&&!n.height&&(n.width=r.right-r.left||t.width||0,n.height=r.bottom-r.top||t.height||0)}return this.clientRect=n,n}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch{}return Math.min(t,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(t){return!this.restrictedLevels.some(r=>t.bitrate===r.bitrate&&t.width===r.width&&t.height===r.height)}static getMaxLevelByMediaSize(t,n,r){if(!(t!=null&&t.length))return-1;const a=(o,c)=>c?o.width!==c.width||o.height!==c.height:!0;let i=t.length-1;const l=Math.max(n,r);for(let o=0;o=l||c.height>=l)&&a(c,t[o+1])){i=o;break}}return i}}const uir={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Xb=uir,hir={HLS:"h"},mir=hir;class r3{constructor(t,n){Array.isArray(t)&&(t=t.map(r=>r instanceof r3?r:new r3(r))),this.value=t,this.params=n}}const pir="Dict";function fir(s){return Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":typeof s=="object"?JSON.stringify(s):String(s)}function gir(s,t,n,r){return new Error(`failed to ${s} "${fir(t)}" as ${n}`,{cause:r})}function a3(s,t,n){return gir("serialize",s,t,n)}class Ons{constructor(t){this.description=t}}const f4t="Bare Item",xir="Boolean";function yir(s){if(typeof s!="boolean")throw a3(s,xir);return s?"?1":"?0"}function vir(s){return btoa(String.fromCharCode(...s))}const bir="Byte Sequence";function _ir(s){if(ArrayBuffer.isView(s)===!1)throw a3(s,bir);return`:${vir(s)}:`}const wir="Integer";function jir(s){return s<-999999999999999||99999999999999912)throw a3(s,kir);const n=t.toString();return n.includes(".")?n:`${n}.0`}const Cir="String",Air=/[\x00-\x1f\x7f]+/;function Eir(s){if(Air.test(s))throw a3(s,Cir);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Tir(s){return s.description||s.toString().slice(7,-1)}const Mir="Token";function g4t(s){const t=Tir(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw a3(t,Mir);return t}function $Ke(s){switch(typeof s){case"number":if(!Bi(s))throw a3(s,f4t);return Number.isInteger(s)?Fns(s):Sir(s);case"string":return Eir(s);case"symbol":return g4t(s);case"boolean":return yir(s);case"object":if(s instanceof Date)return Nir(s);if(s instanceof Uint8Array)return _ir(s);if(s instanceof Ons)return g4t(s);default:throw a3(s,f4t)}}const Pir="Key";function VKe(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw a3(s,Pir);return s}function Zrt(s){return s==null?"":Object.entries(s).map(([t,n])=>n===!0?`;${VKe(t)}`:`;${VKe(t)}=${$Ke(n)}`).join("")}function Bns(s){return s instanceof r3?`${$Ke(s.value)}${Zrt(s.params)}`:$Ke(s)}function Lir(s){return`(${s.value.map(Bns).join(" ")})${Zrt(s.params)}`}function Iir(s,t={whitespace:!0}){if(typeof s!="object"||s==null)throw a3(s,pir);const n=s instanceof Map?s.entries():Object.entries(s),r=t!=null&&t.whitespace?" ":"";return Array.from(n).map(([a,i])=>{i instanceof r3||(i=new r3(i));let l=VKe(a);return i.value===!0?l+=Zrt(i.params):(l+="=",Array.isArray(i.value)?l+=Lir(i):l+=Bns(i)),l}).join(`,${r}`)}function Uns(s,t){return Iir(s,t)}const g5="CMCD-Object",Wf="CMCD-Request",aI="CMCD-Session",gT="CMCD-Status",Rir={br:g5,ab:g5,d:g5,ot:g5,tb:g5,tpb:g5,lb:g5,tab:g5,lab:g5,url:g5,pb:Wf,bl:Wf,tbl:Wf,dl:Wf,ltc:Wf,mtp:Wf,nor:Wf,nrr:Wf,rc:Wf,sn:Wf,sta:Wf,su:Wf,ttfb:Wf,ttfbb:Wf,ttlb:Wf,cmsdd:Wf,cmsds:Wf,smrt:Wf,df:Wf,cs:Wf,ts:Wf,cid:aI,pr:aI,sf:aI,sid:aI,st:aI,v:aI,msd:aI,bs:gT,bsd:gT,cdn:gT,rtp:gT,bg:gT,pt:gT,ec:gT,e:gT},Dir={REQUEST:Wf};function Oir(s){return Object.keys(s).reduce((t,n)=>{var r;return(r=s[n])===null||r===void 0||r.forEach(a=>t[a]=n),t},{})}function Fir(s,t){const n={};if(!s)return n;const r=Object.keys(s),a=t?Oir(t):{};return r.reduce((i,l)=>{var o;const c=Rir[l]||a[l]||Dir.REQUEST,d=(o=i[c])!==null&&o!==void 0?o:i[c]={};return d[l]=s[l],i},n)}function zir(s){return["ot","sf","st","e","sta"].includes(s)}function Bir(s){return typeof s=="number"?Bi(s):s!=null&&s!==""&&s!==!1}const qns="event";function Uir(s,t){const n=new URL(s),r=new URL(t);if(n.origin!==r.origin)return s;const a=n.pathname.split("/").slice(1),i=r.pathname.split("/").slice(1,-1);for(;a[0]===i[0];)a.shift(),i.shift();for(;i.length;)i.shift(),a.unshift("..");return a.join("/")+n.search+n.hash}const i3e=s=>Math.round(s),HKe=(s,t)=>Array.isArray(s)?s.map(n=>HKe(n,t)):s instanceof r3&&typeof s.value=="string"?new r3(HKe(s.value,t),s.params):(t.baseUrl&&(s=Uir(s,t.baseUrl)),t.version===1?encodeURIComponent(s):s),Kce=s=>i3e(s/100)*100,qir=(s,t)=>{let n=s;return t.version>=2&&(s instanceof r3&&typeof s.value=="string"?n=new r3([s]):typeof s=="string"&&(n=[s])),HKe(n,t)},$ir={br:i3e,d:i3e,bl:Kce,dl:Kce,mtp:Kce,nor:qir,rtp:Kce,tb:i3e},$ns="request",Vns="response",Xrt=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],Vir=["e"],Hir=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function QIe(s){return Hir.test(s)}function Gir(s){return Xrt.includes(s)||Vir.includes(s)||QIe(s)}const Hns=["d","dl","nor","ot","rtp","su"];function Wir(s){return Xrt.includes(s)||Hns.includes(s)||QIe(s)}const Kir=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function Yir(s){return Xrt.includes(s)||Hns.includes(s)||Kir.includes(s)||QIe(s)}const Zir=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function Xir(s){return Zir.includes(s)||QIe(s)}const Qir={[Vns]:Yir,[qns]:Gir,[$ns]:Wir};function Gns(s,t={}){const n={};if(s==null||typeof s!="object")return n;const r=t.version||s.v||1,a=t.reportingMode||$ns,i=r===1?Xir:Qir[a];let l=Object.keys(s).filter(i);const o=t.filter;typeof o=="function"&&(l=l.filter(o));const c=a===Vns||a===qns;c&&!l.includes("ts")&&l.push("ts"),r>1&&!l.includes("v")&&l.push("v");const d=Yh({},$ir,t.formatters),u={version:r,reportingMode:a,baseUrl:t.baseUrl};return l.sort().forEach(h=>{let m=s[h];const p=d[h];if(typeof p=="function"&&(m=p(m,u)),h==="v"){if(r===1)return;m=r}h=="pr"&&m===1||(c&&h==="ts"&&!Bi(m)&&(m=Date.now()),Bir(m)&&(zir(h)&&typeof m=="string"&&(m=new Ons(m)),n[h]=m))}),n}function Jir(s,t={}){const n={};if(!s)return n;const r=Gns(s,t),a=Fir(r,t==null?void 0:t.customHeaderMap);return Object.entries(a).reduce((i,[l,o])=>{const c=Uns(o,{whitespace:!1});return c&&(i[l]=c),i},n)}function eor(s,t,n){return Yh(s,Jir(t,n))}const tor="CMCD";function sor(s,t={}){return s?Uns(Gns(s,t),{whitespace:!1}):""}function nor(s,t={}){if(!s)return"";const n=sor(s,t);return encodeURIComponent(n)}function ror(s,t={}){if(!s)return"";const n=nor(s,t);return`${tor}=${n}`}const x4t=/CMCD=[^&#]+/;function aor(s,t,n){const r=ror(t,n);if(!r)return s;if(x4t.test(s))return s.replace(x4t,r);const a=s.includes("?")?"&":"?";return`${s}${a}${r}`}class ior{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=a=>{try{this.apply(a,{ot:Xb.MANIFEST,su:!this.initialized})}catch(i){this.hls.logger.warn("Could not generate manifest CMCD data.",i)}},this.applyFragmentData=a=>{try{const{frag:i,part:l}=a,o=this.hls.levels[i.level],c=this.getObjectType(i),d={d:(l||i).duration*1e3,ot:c};(c===Xb.VIDEO||c===Xb.AUDIO||c==Xb.MUXED)&&(d.br=o.bitrate/1e3,d.tb=this.getTopBandwidth(c)/1e3,d.bl=this.getBufferLength(c));const u=l?this.getNextPart(l):this.getNextFrag(i);u!=null&&u.url&&u.url!==i.url&&(d.nor=u.url),this.apply(a,d)}catch(i){this.hls.logger.warn("Could not generate segment CMCD data.",i)}},this.hls=t;const n=this.config=t.config,{cmcd:r}=n;r!=null&&(n.pLoader=this.createPlaylistLoader(),n.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||t.sessionId,this.cid=r.contentId,this.useHeaders=r.useHeaders===!0,this.includeKeys=r.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(Ot.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Ot.MEDIA_DETACHED,this.onMediaDetached,this),t.on(Ot.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(Ot.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Ot.MEDIA_DETACHED,this.onMediaDetached,this),t.off(Ot.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(t,n){this.media=n.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(t,n){var r,a;this.audioBuffer=(r=n.tracks.audio)==null?void 0:r.buffer,this.videoBuffer=(a=n.tracks.video)==null?void 0:a.buffer}createData(){var t;return{v:1,sf:mir.HLS,sid:this.sid,cid:this.cid,pr:(t=this.media)==null?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,n={}){Yh(n,this.createData());const r=n.ot===Xb.INIT||n.ot===Xb.VIDEO||n.ot===Xb.MUXED;this.starved&&r&&(n.bs=!0,n.su=!0,this.starved=!1),n.su==null&&(n.su=this.buffering);const{includeKeys:a}=this;a&&(n=Object.keys(n).reduce((l,o)=>(a.includes(o)&&(l[o]=n[o]),l),{}));const i={baseUrl:t.url};this.useHeaders?(t.headers||(t.headers={}),eor(t.headers,n,i)):t.url=aor(t.url,n,i)}getNextFrag(t){var n;const r=(n=this.hls.levels[t.level])==null?void 0:n.details;if(r){const a=t.sn-r.startSN;return r.fragments[a+1]}}getNextPart(t){var n;const{index:r,fragment:a}=t,i=(n=this.hls.levels[a.level])==null||(n=n.details)==null?void 0:n.partList;if(i){const{sn:l}=a;for(let o=i.length-1;o>=0;o--){const c=i[o];if(c.index===r&&c.fragment.sn===l)return i[o+1]}}}getObjectType(t){const{type:n}=t;if(n==="subtitle")return Xb.TIMED_TEXT;if(t.sn==="initSegment")return Xb.INIT;if(n==="audio")return Xb.AUDIO;if(n==="main")return this.hls.audioTracks.length?Xb.VIDEO:Xb.MUXED}getTopBandwidth(t){let n=0,r;const a=this.hls;if(t===Xb.AUDIO)r=a.audioTracks;else{const i=a.maxAutoLevel,l=i>-1?i+1:a.levels.length;r=a.levels.slice(0,l)}return r.forEach(i=>{i.bitrate>n&&(n=i.bitrate)}),n>0?n:NaN}getBufferLength(t){const n=this.media,r=t===Xb.AUDIO?this.audioBuffer:this.videoBuffer;return!r||!n?NaN:uc.bufferInfo(r,n.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:t}=this.config,n=this.applyPlaylistData,r=t||this.config.loader;return class{constructor(i){this.loader=void 0,this.loader=new r(i)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(i,l,o){n(i),this.loader.load(i,l,o)}}}createFragmentLoader(){const{fLoader:t}=this.config,n=this.applyFragmentData,r=t||this.config.loader;return class{constructor(i){this.loader=void 0,this.loader=new r(i)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(i,l,o){n(i),this.loader.load(i,l,o)}}}}const oor=3e5;class lor extends PN{constructor(t){super("content-steering",t.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ot.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Ot.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Ot.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ot.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Ot.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Ot.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,n)=>(t.indexOf(n.pathwayId)===-1&&t.push(n.pathwayId),t),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=this.timeToLoad*1e3-(performance.now()-this.updated);if(t>0){this.scheduleRefresh(this.uri,t);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const n=this.levels;n&&(this.levels=n.filter(r=>r!==t))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,n){const{contentSteering:r}=n;r!==null&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}onManifestParsed(t,n){this.audioTracks=n.audioTracks,this.subtitleTracks=n.subtitleTracks}onError(t,n){const{errorAction:r}=n;if((r==null?void 0:r.action)===Yy.SendAlternateToPenaltyBox&&r.flags===vw.MoveAllAlternatesMatchingHost){const a=this.levels;let i=this._pathwayPriority,l=this.pathwayId;if(n.context){const{groupId:o,pathwayId:c,type:d}=n.context;o&&a?l=this.getPathwayForGroupId(o,d,l):c&&(l=c)}l in this.penalizedPathways||(this.penalizedPathways[l]=performance.now()),!i&&a&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),r.resolved=this.pathwayId!==l),n.details===yr.BUFFER_APPEND_ERROR&&!n.fatal?r.resolved=!0:r.resolved||this.warn(`Could not resolve ${n.details} ("${n.error.message}") with content-steering for Pathway: ${l} levels: ${a&&a.length} priorities: ${fm(i)} penalized: ${fm(this.penalizedPathways)}`)}}filterParsedLevels(t){this.levels=t;let n=this.getLevelsForPathway(this.pathwayId);if(n.length===0){const r=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${r}"`),n=this.getLevelsForPathway(r),this.pathwayId=r}return n.length!==t.length&&this.log(`Found ${n.length}/${t.length} levels in Pathway "${this.pathwayId}"`),n}getLevelsForPathway(t){return this.levels===null?[]:this.levels.filter(n=>t===n.pathwayId)}updatePathwayPriority(t){this._pathwayPriority=t;let n;const r=this.penalizedPathways,a=performance.now();Object.keys(r).forEach(i=>{a-r[i]>oor&&delete r[i]});for(let i=0;i0){this.log(`Setting Pathway to "${l}"`),this.pathwayId=l,hns(n),this.hls.trigger(Ot.LEVELS_UPDATED,{levels:n});const d=this.hls.levels[o];c&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(t,n,r){const a=this.getLevelsForPathway(r).concat(this.levels||[]);for(let i=0;i{const{ID:l,"BASE-ID":o,"URI-REPLACEMENT":c}=i;if(n.some(u=>u.pathwayId===l))return;const d=this.getLevelsForPathway(o).map(u=>{const h=new uf(u.attrs);h["PATHWAY-ID"]=l;const m=h.AUDIO&&`${h.AUDIO}_clone_${l}`,p=h.SUBTITLES&&`${h.SUBTITLES}_clone_${l}`;m&&(r[h.AUDIO]=m,h.AUDIO=m),p&&(a[h.SUBTITLES]=p,h.SUBTITLES=p);const f=Wns(u.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),x=new Wte({attrs:h,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:f,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let y=1;y{this.log(`Loaded steering manifest: "${a}"`);const f=u.data;if((f==null?void 0:f.VERSION)!==1){this.log(`Steering VERSION ${f.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=f.TTL;const{"RELOAD-URI":x,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":v}=f;if(x)try{this.uri=new self.URL(x,a).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${x}`);return}this.scheduleRefresh(this.uri||m.url),y&&this.clonePathways(y);const b={steeringManifest:f,url:a.toString()};this.hls.trigger(Ot.STEERING_MANIFEST_LOADED,b),v&&this.updatePathwayPriority(v)},onError:(u,h,m,p)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${h.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let f=this.timeToLoad*1e3;if(u.code===429){const x=this.loader;if(typeof(x==null?void 0:x.getResponseHeader)=="function"){const y=x.getResponseHeader("Retry-After");y&&(f=parseFloat(y)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,f)},onTimeout:(u,h,m)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${a}`),this.loader.load(i,c,d)}scheduleRefresh(t,n=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var r;const a=(r=this.hls)==null?void 0:r.media;if(a&&!a.ended){this.loadSteeringManifest(t);return}this.scheduleRefresh(t,this.timeToLoad*1e3)},n)}}function y4t(s,t,n,r){s&&Object.keys(t).forEach(a=>{const i=s.filter(l=>l.groupId===a).map(l=>{const o=Yh({},l);return o.details=void 0,o.attrs=new uf(o.attrs),o.url=o.attrs.URI=Wns(l.url,l.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",n),o.groupId=o.attrs["GROUP-ID"]=t[a],o.attrs["PATHWAY-ID"]=r,o});s.push(...i)})}function Wns(s,t,n,r){const{HOST:a,PARAMS:i,[n]:l}=r;let o;t&&(o=l==null?void 0:l[t],o&&(s=o));const c=new self.URL(s);return a&&!o&&(c.host=a),i&&Object.keys(i).sort().forEach(d=>{d&&c.searchParams.set(d,i[d])}),c.href}class d$ extends PN{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=d$.CDMCleanupPromise?[d$.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=n=>{const{initDataType:r,initData:a}=n,i=`"${n.type}" event: init data type: "${r}"`;if(this.debug(i),a!==null){if(!this.keyFormatPromise){let l=Object.keys(this.keySystemAccessPromises);l.length||(l=cX(this.config));const o=l.map(Lze).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(l=>{const o=n3e(l);if(r!=="sinf"||o!==xf.FAIRPLAY){this.log(`Ignoring "${n.type}" event with init data type: "${r}" for selected key-system ${o}`);return}let c;try{const p=Zx(new Uint8Array(a)),f=zrt(JSON.parse(p).sinf),x=Uss(f);if(!x)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(x.subarray(8,24))}catch(p){this.warn(`${i} Failed to parse sinf: ${p}`);return}const d=Zy(c),{keyIdToKeySessionPromise:u,mediaKeySessions:h}=this;let m=u[d];for(let p=0;pthis.generateRequestWithPreferredKeySession(f,r,a,"encrypted-event-key-match")),m.catch(v=>this.handleError(v));break}}m||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${h.length}.`))}).catch(l=>this.handleError(l))}},this.onWaitingForKey=n=>{this.log(`"${n.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(Ot.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Ot.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(Ot.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Ot.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(Ot.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(Ot.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Ot.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(Ot.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Ot.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(Ot.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:n,widevineLicenseUrl:r}=this.config,a=n==null?void 0:n[t];if(a)return a.licenseUrl;if(t===xf.WIDEVINE&&r)return r}getLicenseServerUrlOrThrow(t){const n=this.getLicenseServerUrl(t);if(n===void 0)throw new Error(`no license server URL configured for key-system "${t}"`);return n}getServerCertificateUrl(t){const{drmSystems:n}=this.config,r=n==null?void 0:n[t];if(r)return r.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const n=this.hls.levels,r=(l,o,c)=>!!l&&c.indexOf(l)===o,a=n.map(l=>l.audioCodec).filter(r),i=n.map(l=>l.videoCodec).filter(r);return a.length+i.length===0&&i.push("avc1.42e01e"),new Promise((l,o)=>{const c=d=>{const u=d.shift();this.getMediaKeysPromise(u,a,i).then(h=>l({keySystem:u,mediaKeys:h})).catch(h=>{d.length?c(d):h instanceof pw?o(h):o(new pw({type:wo.KEY_SYSTEM_ERROR,details:yr.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.message))})};c(t)})}requestMediaKeySystemAccess(t,n){const{requestMediaKeySystemAccessFunc:r}=this.config;if(typeof r!="function"){let a=`Configured requestMediaKeySystemAccess is not a function ${r}`;return rns===null&&self.location.protocol==="http:"&&(a=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(a))}return r(t,n)}getMediaKeysPromise(t,n,r){var a;const i=Urr(t,n,r,this.config.drmSystemOptions||{});let l=this.keySystemAccessPromises[t],o=(a=l)==null?void 0:a.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${t}" key-system access with config: ${fm(i)}`),o=this.requestMediaKeySystemAccess(t,i);const c=l=this.keySystemAccessPromises[t]={keySystemAccess:o};return o.catch(d=>{this.log(`Failed to obtain access to key-system "${t}": ${d}`)}),o.then(d=>{this.log(`Access for key-system "${d.keySystem}" obtained`);const u=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const h=c.mediaKeys=d.createMediaKeys().then(m=>(this.log(`Media-keys created for "${t}"`),c.hasMediaKeys=!0,u.then(p=>p?this.setMediaKeysServerCertificate(m,t,p):m)));return h.catch(m=>{this.error(`Failed to create media-keys for "${t}"}: ${m}`)}),h})}return o.then(()=>l.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:n,mediaKeys:r}){this.log(`Creating key-system session "${n}" keyId: ${Zy(t.keyId||[])} keyUri: ${t.uri}`);const a=r.createSession(),i={decryptdata:t,keySystem:n,mediaKeys:r,mediaKeysSession:a,keyStatus:"status-pending"};return this.mediaKeySessions.push(i),i}renewKeySession(t){const n=t.decryptdata;if(n.pssh){const r=this.createMediaKeySessionContext(t),a=Yce(n),i="cenc";this.keyIdToKeySessionPromise[a]=this.generateRequestWithPreferredKeySession(r,i,n.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}updateKeySession(t,n){const r=t.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyId ${Zy(t.decryptdata.keyId||[])} } (data length: ${n.byteLength})`),r.update(n)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>Lze(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:n,mediaKeys:r})=>this.attemptSetMediaKeys(n,r))}selectKeySystem(t){return new Promise((n,r)=>{this.getKeySystemSelectionPromise(t).then(({keySystem:a})=>{const i=Lze(a);i?n(i):r(new Error(`Unable to find format for key-system "${a}"`))}).catch(r)})}selectKeySystemFormat(t){const n=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${n.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(n)),this.keyFormatPromise}getKeyFormatPromise(t){const n=cX(this.config),r=t.map(n3e).filter(a=>!!a&&n.indexOf(a)!==-1);return this.selectKeySystem(r)}getKeyStatus(t){const{mediaKeySessions:n}=this;for(let r=0;r(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${i}`),this.attemptSetMediaKeys(c,d).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:d,decryptdata:n}))))).then(c=>{const d="cenc",u=n.pssh?n.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,d,u,"playlist-key")});return o.catch(c=>this.handleError(c,t.frag)),this.keyIdToKeySessionPromise[r]=o,o}return l.catch(o=>{if(o instanceof pw){const c=_h({},o.data);this.getKeyStatus(n)==="internal-error"&&(c.decryptdata=n);const d=new pw(c,o.message);this.handleError(d,t.frag)}}),l}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,n){if(this.hls)if(t instanceof pw){n&&(t.data.frag=n);const r=t.data.decryptdata;this.error(`${t.message}${r?` (${Zy(r.keyId||[])})`:""}`),this.hls.trigger(Ot.ERROR,t.data)}else this.error(t.message),this.hls.trigger(Ot.ERROR,{type:wo.KEY_SYSTEM_ERROR,details:yr.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const n=Yce(t),r=this.keyIdToKeySessionPromise[n];if(!r){const a=n3e(t.keyFormat),i=a?[a]:cX(this.config);return this.attemptKeySystemAccess(i)}return r}getKeySystemSelectionPromise(t){if(t.length||(t=cX(this.config)),t.length===0)throw new pw({type:wo.KEY_SYSTEM_ERROR,details:yr.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${fm({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,n){if(this.mediaResolved=void 0,this.mediaKeys===n)return Promise.resolve();const r=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const a=Promise.all(r).then(()=>this.media?this.media.setMediaKeys(n):new Promise((i,l)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return l(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=n,this.media.setMediaKeys(n).then(i).catch(l)}}));return this.mediaKeys=n,this.setMediaKeysQueue.push(a),a.then(()=>{this.log(`Media-keys set for "${t}"`),r.push(a),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(i=>r.indexOf(i)===-1)})}generateRequestWithPreferredKeySession(t,n,r,a){var i;const l=(i=this.config.drmSystems)==null||(i=i[t.keySystem])==null?void 0:i.generateRequest;if(l)try{const f=l.call(this.hls,n,r,t);if(!f)throw new Error("Invalid response from configured generateRequest filter");n=f.initDataType,r=f.initData?f.initData:null,t.decryptdata.pssh=r?new Uint8Array(r):null}catch(f){if(this.warn(f.message),this.hls&&this.hls.config.debug)throw f}if(r===null)return this.log(`Skipping key-session request for "${a}" (no initData)`),Promise.resolve(t);const o=Yce(t.decryptdata),c=t.decryptdata.uri;this.log(`Generating key-session request for "${a}" keyId: ${o} URI: ${c} (init data type: ${n} length: ${r.byteLength})`);const d=new Urt,u=t._onmessage=f=>{const x=t.mediaKeysSession;if(!x){d.emit("error",new Error("invalid state"));return}const{messageType:y,message:v}=f;this.log(`"${y}" message event for session "${x.sessionId}" message size: ${v.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(t,v).catch(b=>{d.eventNames().length?d.emit("error",b):this.handleError(b)}):y==="license-release"?t.keySystem===xf.FAIRPLAY&&this.updateKeySession(t,OKe("acknowledged")).then(()=>this.removeSession(t)).catch(b=>this.handleError(b)):this.warn(`unhandled media key message type "${y}"`)},h=(f,x)=>{x.keyStatus=f;let y;f.startsWith("usable")?d.emit("resolved"):f==="internal-error"||f==="output-restricted"||f==="output-downscaled"?y=v4t(f,x.decryptdata):f==="expired"?y=new Error(`key expired (keyId: ${o})`):f==="released"?y=new Error("key released"):f==="status-pending"||this.warn(`unhandled key status change "${f}" (keyId: ${o})`),y&&(d.eventNames().length?d.emit("error",y):this.handleError(y))},m=t._onkeystatuseschange=f=>{if(!t.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const y=this.getKeyStatuses(t);if(!Object.keys(y).some(S=>y[S]!=="status-pending"))return;if(y[o]==="expired"){this.log(`Expired key ${fm(y)} in key-session "${t.mediaKeysSession.sessionId}"`),this.renewKeySession(t);return}let b=y[o];if(b)h(b,t);else{var N;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(N=t.keyStatusTimeouts)[o]||(N[o]=self.setTimeout(()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;const A=this.getKeyStatus(t.decryptdata);if(A&&A!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${t.mediaKeysSession.sessionId}". Using session key-status ${A} from other session.`),h(A,t);this.log(`key status for ${o} in key-session "${t.mediaKeysSession.sessionId}" timed out after 1000ms`),b="internal-error",h(b,t)},1e3)),this.log(`No status for keyId ${o} (${fm(y)}).`)}};ob(t.mediaKeysSession,"message",u),ob(t.mediaKeysSession,"keystatuseschange",m);const p=new Promise((f,x)=>{d.on("error",x),d.on("resolved",f)});return t.mediaKeysSession.generateRequest(n,r).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(f=>{throw new pw({type:wo.KEY_SYSTEM_ERROR,details:yr.KEY_SYSTEM_NO_SESSION,error:f,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>p).catch(f=>(d.removeAllListeners(),this.removeSession(t).then(()=>{throw f}))).then(()=>(d.removeAllListeners(),t))}getKeyStatuses(t){const n={};return t.mediaKeysSession.keyStatuses.forEach((r,a)=>{if(typeof a=="string"&&typeof r=="object"){const o=a;a=r,r=o}const i="buffer"in a?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);if(t.keySystem===xf.PLAYREADY&&i.length===16){const o=Zy(i);n[o]=r,sns(i)}const l=Zy(i);r==="internal-error"&&(this.bannedKeyIds[l]=r),this.log(`key status change "${r}" for keyStatuses keyId: ${l} key-session "${t.mediaKeysSession.sessionId}"`),n[l]=r}),n}fetchServerCertificate(t){const n=this.config,r=n.loader,a=new r(n),i=this.getServerCertificateUrl(t);return i?(this.log(`Fetching server certificate for "${t}"`),new Promise((l,o)=>{const c={responseType:"arraybuffer",url:i},d=n.certLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(m,p,f,x)=>{l(m.data)},onError:(m,p,f,x)=>{o(new pw({type:wo.KEY_SYSTEM_ERROR,details:yr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:_h({url:c.url,data:void 0},m)},`"${t}" certificate request failed (${i}). Status: ${m.code} (${m.text})`))},onTimeout:(m,p,f)=>{o(new pw({type:wo.KEY_SYSTEM_ERROR,details:yr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:c.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(m,p,f)=>{o(new Error("aborted"))}};a.load(c,u,h)})):Promise.resolve()}setMediaKeysServerCertificate(t,n,r){return new Promise((a,i)=>{t.setServerCertificate(r).then(l=>{this.log(`setServerCertificate ${l?"success":"not supported by CDM"} (${r.byteLength}) on "${n}"`),a(t)}).catch(l=>{i(new pw({type:wo.KEY_SYSTEM_ERROR,details:yr.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:l,fatal:!0},l.message))})})}renewLicense(t,n){return this.requestLicense(t,new Uint8Array(n)).then(r=>this.updateKeySession(t,new Uint8Array(r)).catch(a=>{throw new pw({type:wo.KEY_SYSTEM_ERROR,details:yr.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t.decryptdata,error:a,fatal:!1},a.message)}))}unpackPlayReadyKeyMessage(t,n){const r=String.fromCharCode.apply(null,new Uint16Array(n.buffer));if(!r.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),n;const a=new DOMParser().parseFromString(r,"application/xml"),i=a.querySelectorAll("HttpHeader");if(i.length>0){let u;for(let h=0,m=i.length;h in key message");return OKe(atob(d))}setupLicenseXHR(t,n,r,a){const i=this.config.licenseXhrSetup;return i?Promise.resolve().then(()=>{if(!r.decryptdata)throw new Error("Key removed");return i.call(this.hls,t,n,r,a)}).catch(l=>{if(!r.decryptdata)throw l;return t.open("POST",n,!0),i.call(this.hls,t,n,r,a)}).then(l=>(t.readyState||t.open("POST",n,!0),{xhr:t,licenseChallenge:l||a})):(t.open("POST",n,!0),Promise.resolve({xhr:t,licenseChallenge:a}))}requestLicense(t,n){const r=this.config.keyLoadPolicy.default;return new Promise((a,i)=>{const l=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${l}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return i(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let c=o.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const d=this.config.licenseResponseCallback;if(d)try{c=d.call(this.hls,o,l,t)}catch(u){this.error(u)}a(c)}else{const c=r.errorRetry,d=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||o.status>=400&&o.status<500)i(new pw({type:wo.KEY_SYSTEM_ERROR,details:yr.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t.decryptdata,fatal:!0,networkDetails:o,response:{url:l,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${l}). Status: ${o.status} (${o.statusText})`));else{const u=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(t,n).then(a,i)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=o,this.setupLicenseXHR(o,l,t,n).then(({xhr:c,licenseChallenge:d})=>{t.keySystem==xf.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(c,d)),c.send(d)}).catch(i)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,n){if(!this.config.emeEnabled)return;const r=n.media;this.media=r,ob(r,"encrypted",this.onMediaEncrypted),ob(r,"waitingforkey",this.onWaitingForKey);const a=this.mediaResolved;a?a():this.mediaKeys=r.mediaKeys}onMediaDetached(){const t=this.media;t&&(w_(t,"encrypted",this.onMediaEncrypted),w_(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const n=this.mediaResolved;if(n&&n(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const r=this.media,a=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,tP.clearKeyUriToKeyIdMap();const i=a.length;d$.CDMCleanupPromise=Promise.all(a.map(l=>this.removeSession(l)).concat((r==null||(t=r.setMediaKeys(null))==null?void 0:t.catch(l=>{this.log(`Could not clear media keys: ${l}`),this.hls&&this.hls.trigger(Ot.ERROR,{type:wo.OTHER_ERROR,details:yr.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${l}`)})}))||Promise.resolve())).catch(l=>{this.log(`Could not close sessions and clear media keys: ${l}`),this.hls&&this.hls.trigger(Ot.ERROR,{type:wo.OTHER_ERROR,details:yr.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${l}`)})}).then(()=>{i&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(t,{sessionKeys:n}){if(!(!n||!this.config.emeEnabled)&&!this.keyFormatPromise){const r=n.reduce((a,i)=>(a.indexOf(i.keyFormat)===-1&&a.push(i.keyFormat),a),[]);this.log(`Selecting key-system from session-keys ${r.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(r)}}removeSession(t){const{mediaKeysSession:n,licenseXhr:r,decryptdata:a}=t;if(n){this.log(`Remove licenses and keys and close session "${n.sessionId}" keyId: ${Zy((a==null?void 0:a.keyId)||[])}`),t._onmessage&&(n.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(n.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),r&&r.readyState!==XMLHttpRequest.DONE&&r.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(t);i>-1&&this.mediaKeySessions.splice(i,1);const{keyStatusTimeouts:l}=t;l&&Object.keys(l).forEach(d=>self.clearTimeout(l[d]));const{drmSystemOptions:o}=this.config;return($rr(o)?new Promise((d,u)=>{self.setTimeout(()=>u(new Error("MediaKeySession.remove() timeout")),8e3),n.remove().then(d).catch(u)}):Promise.resolve()).catch(d=>{this.log(`Could not remove session: ${d}`),this.hls&&this.hls.trigger(Ot.ERROR,{type:wo.OTHER_ERROR,details:yr.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${d}`)})}).then(()=>n.close()).catch(d=>{this.log(`Could not close session: ${d}`),this.hls&&this.hls.trigger(Ot.ERROR,{type:wo.OTHER_ERROR,details:yr.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}d$.CDMCleanupPromise=void 0;function Yce(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return Zy(s.keyId)}function cor(s,t){if(s.keyId&&t.mediaKeysSession.keyStatuses.has(s.keyId))return t.mediaKeysSession.keyStatuses.get(s.keyId);if(s.matches(t.decryptdata))return t.keyStatus}class pw extends Error{constructor(t,n){super(n),this.data=void 0,t.error||(t.error=new Error(n)),this.data=t,t.err=t.error}}function v4t(s,t){const n=s==="output-restricted",r=n?yr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:yr.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new pw({type:wo.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},n?"HDCP level output restricted":`key status changed to "${s}"`)}class dor{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(Ot.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(Ot.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(Ot.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(Ot.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,n){const r=this.hls.config;if(r.capLevelOnFPSDrop){const a=n.media instanceof self.HTMLVideoElement?n.media:null;this.media=a,a&&typeof a.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,n,r){const a=performance.now();if(n){if(this.lastTime){const i=a-this.lastTime,l=r-this.lastDroppedFrames,o=n-this.lastDecodedFrames,c=1e3*l/i,d=this.hls;if(d.trigger(Ot.FPS_DROP,{currentDropped:l,currentDecoded:o,totalDroppedFrames:r}),c>0&&l>d.config.fpsDroppedMonitoringThreshold*o){let u=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=u)&&(u=u-1,d.trigger(Ot.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:d.currentLevel}),d.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=a,this.lastDroppedFrames=r,this.lastDecodedFrames=n}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const n=t.getVideoPlaybackQuality();this.checkFPS(t,n.totalVideoFrames,n.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}}function Kns(s,t){let n;try{n=new Event("addtrack")}catch{n=document.createEvent("Event"),n.initEvent("addtrack",!1,!1)}n.track=s,t.dispatchEvent(n)}function Yns(s,t){const n=s.mode;if(n==="disabled"&&(s.mode="hidden"),s.cues&&!s.cues.getCueById(t.id))try{if(s.addCue(t),!s.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(r){Ah.debug(`[texttrack-utils]: ${r}`);try{const a=new self.TextTrackCue(t.startTime,t.endTime,t.text);a.id=t.id,s.addCue(a)}catch(a){Ah.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${a}`)}}n==="disabled"&&(s.mode=n)}function DU(s,t){const n=s.mode;if(n==="disabled"&&(s.mode="hidden"),s.cues)for(let r=s.cues.length;r--;)t&&s.cues[r].removeEventListener("enter",t),s.removeCue(s.cues[r]);n==="disabled"&&(s.mode=n)}function GKe(s,t,n,r){const a=s.mode;if(a==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const i=hor(s.cues,t,n);for(let l=0;ls[n].endTime)return-1;let r=0,a=n,i;for(;r<=a;)if(i=Math.floor((a+r)/2),ts[i].startTime&&r-1)for(let i=a,l=s.length;i=t&&o.endTime<=n)r.push(o);else if(o.startTime>n)return r}return r}function o3e(s){const t=[];for(let n=0;nthis.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let n=null;const r=o3e(this.media.textTracks);for(let i=0;i-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(Ot.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Ot.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ot.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Ot.LEVEL_LOADING,this.onLevelLoading,this),t.on(Ot.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Ot.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(Ot.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Ot.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Ot.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ot.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Ot.LEVEL_LOADING,this.onLevelLoading,this),t.off(Ot.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Ot.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(Ot.ERROR,this.onError,this)}onMediaAttached(t,n){this.media=n.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(t,n){const r=this.media;if(!r)return;const a=!!n.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||r.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,a)return;o3e(r.textTracks).forEach(l=>{DU(l)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,n){this.tracks=n.subtitleTracks}onSubtitleTrackLoaded(t,n){const{id:r,groupId:a,details:i}=n,l=this.tracksInGroup[r];if(!l||l.groupId!==a){this.warn(`Subtitle track with id:${r} and group:${a} not found in active group ${l==null?void 0:l.groupId}`);return}const o=l.details;l.details=n.details,this.log(`Subtitle track ${r} "${l.name}" lang:${l.lang} group:${a} loaded [${i.startSN}-${i.endSN}]`),r===this.trackId&&this.playlistLoaded(r,n,o)}onLevelLoading(t,n){this.switchLevel(n.level)}onLevelSwitching(t,n){this.switchLevel(n.level)}switchLevel(t){const n=this.hls.levels[t];if(!n)return;const r=n.subtitleGroups||null,a=this.groupIds;let i=this.currentTrack;if(!r||(a==null?void 0:a.length)!==(r==null?void 0:r.length)||r!=null&&r.some(l=>(a==null?void 0:a.indexOf(l))===-1)){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const l=this.tracks.filter(u=>!r||r.indexOf(u.groupId)!==-1);if(l.length)this.selectDefaultTrack&&!l.some(u=>u.default)&&(this.selectDefaultTrack=!1),l.forEach((u,h)=>{u.id=h});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=l;const o=this.hls.config.subtitlePreference;if(!i&&o){this.selectDefaultTrack=!1;const u=w4(o,l);if(u>-1)i=l[u];else{const h=w4(o,this.tracks);i=this.tracks[h]}}let c=this.findTrackId(i);c===-1&&i&&(c=this.findTrackId(null));const d={subtitleTracks:l};this.log(`Updating subtitle tracks, ${l.length} track(s) found in "${r==null?void 0:r.join(",")}" group-id`),this.hls.trigger(Ot.SUBTITLE_TRACKS_UPDATED,d),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(t){const n=this.tracksInGroup,r=this.selectDefaultTrack;for(let a=0;a-1){const i=this.tracksInGroup[a];return this.setSubtitleTrack(a),i}else{if(r)return null;{const i=w4(t,n);if(i>-1)return n[i]}}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,n){super.loadingPlaylist(t,n);const r=t.id,a=t.groupId,i=this.getUrlWithDirectives(t.url,n),l=t.details,o=l==null?void 0:l.age;this.log(`Loading subtitle ${r} "${t.name}" lang:${t.lang} group:${a}${(n==null?void 0:n.msn)!==void 0?" at sn "+n.msn+" part "+n.part:""}${o&&l.live?" age "+o.toFixed(1)+(l.type&&" "+l.type||""):""} ${i}`),this.hls.trigger(Ot.SUBTITLE_TRACK_LOADING,{url:i,id:r,groupId:a,deliveryDirectives:n||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const n=o3e(t.textTracks),r=this.currentTrack;let a;if(r&&(a=n.filter(i=>qKe(r,i))[0],a||this.warn(`Unable to find subtitle TextTrack with name "${r.name}" and language "${r.lang}"`)),[].slice.call(n).forEach(i=>{i.mode!=="disabled"&&i!==a&&(i.mode="disabled")}),a){const i=this.subtitleDisplay?"showing":"hidden";a.mode!==i&&(a.mode=i)}}setSubtitleTrack(t){const n=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=t;return}if(t<-1||t>=n.length||!Bi(t)){this.warn(`Invalid subtitle track id: ${t}`);return}this.selectDefaultTrack=!1;const r=this.currentTrack,a=n[t]||null;if(this.trackId=t,this.currentTrack=a,this.toggleTrackModes(),!a){this.hls.trigger(Ot.SUBTITLE_TRACK_SWITCH,{id:t});return}const i=!!a.details&&!a.details.live;if(t===this.trackId&&a===r&&i)return;this.log(`Switching to subtitle-track ${t}`+(a?` "${a.name}" lang:${a.lang} group:${a.groupId}`:""));const{id:l,groupId:o="",name:c,type:d,url:u}=a;this.hls.trigger(Ot.SUBTITLE_TRACK_SWITCH,{id:l,groupId:o,name:c,type:d,url:u});const h=this.switchParams(a.url,r==null?void 0:r.details,a.details);this.loadPlaylist(h)}}function por(){try{return crypto.randomUUID()}catch{try{const t=URL.createObjectURL(new Blob),n=t.toString();return URL.revokeObjectURL(t),n.slice(n.lastIndexOf("/")+1)}catch{let n=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,a=>{const i=(n+Math.random()*16)%16|0;return n=Math.floor(n/16),(a=="x"?i:i&3|8).toString(16)})}}}function CJ(s){let t=5381,n=s.length;for(;n;)t=t*33^s.charCodeAt(--n);return(t>>>0).toString()}const u$=.025;let LTe=function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s}({});function gor(s,t,n){return`${s.identifier}-${n+1}-${CJ(t)}`}class xor{constructor(t,n){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=n,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,(t=this.assetListLoader)==null||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){var n;if(t>0&&t>=this.assetList.length)return!0;const r=this.playoutLimit;return t<=0||isNaN(r)?!1:r===0?!0:(((n=this.assetList[t])==null?void 0:n.startOffset)||0)>r}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const n=this.dateRange.tagAnchor;if(n)return qze(t,n)}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const n=this.dateRange.startTime,r=qze(n,t);return n-r<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,n=Bi(t)?t:this.duration;return this.cumulativeDuration+n}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const n=this.resumeAnchor;if(n)return qze(t,n)}return t}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)0||this.assetListResponse!==null}toString(){return yor(this)}}function qze(s,t){return s-t.start":s.cue.post?"":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function JB(s){const t=s.timelineStart,n=s.duration||0;return`["${s.identifier}" ${t.toFixed(2)}-${(t+n).toFixed(2)}]`}class vor{constructor(t,n,r,a){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(Ot.PLAYOUT_LIMIT_REACHED,{})};const i=this.hls=new t(n);this.interstitial=r,this.assetItem=a;const l=()=>{this.hasDetails=!0};i.once(Ot.LEVEL_LOADED,l),i.once(Ot.AUDIO_TRACK_LOADED,l),i.once(Ot.SUBTITLE_TRACK_LOADED,l),i.on(Ot.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&i.on(Ot.BUFFER_APPENDED,()=>{const u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,i.trigger(Ot.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const t=this.hls;if(t)if(t.url)t.levels.length&&!t.started&&t.startLoad(-1,!0);else{let n=this.assetItem.uri;try{n=Zns(n,t.config.primarySessionId||"").href}catch{}t.loadSource(n)}}bufferedInPlaceToEnd(t){var n;if(!this.appendInPlace)return!1;if((n=this.hls)!=null&&n.bufferedToEnd)return!0;if(!t)return!1;const r=Math.min(this._bufferedEosTime||1/0,this.duration),a=this.timelineOffset,i=uc.bufferInfo(t,a,0);return this.getAssetTime(i.end)>=r-.02}reachedPlayout(t){const r=this.interstitial.playoutLimit;return this.startOffset+t>=r}get destroyed(){var t;return!((t=this.hls)!=null&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return((t=this.hls)==null?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const n=uc.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(n.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){const t=this.assetItem.duration;if(!t)return 0;const n=this.interstitial.playoutLimit;if(n){const r=n-this.startOffset;if(r>0&&r1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}}getAssetTime(t){const n=this.timelineOffset,r=this.duration;return Math.min(Math.max(0,t-n),r)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var t;(t=this.hls)!=null&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){var n;this.loadSource(),(n=this.hls)==null||n.attachMedia(t)}detachMedia(){var t;this.removeMediaListeners(),this.mediaAttached=null,(t=this.hls)==null||t.detachMedia()}resumeBuffering(){var t;(t=this.hls)==null||t.resumeBuffering()}pauseBuffering(){var t;(t=this.hls)==null||t.pauseBuffering()}transferMedia(){var t;return this.bufferSnapShot(),((t=this.hls)==null?void 0:t.transferMedia())||null}resetDetails(){const t=this.hls;if(t&&this.hasDetails){t.stopLoad();const n=r=>delete r.details;t.levels.forEach(n),t.allAudioTracks.forEach(n),t.allSubtitleTracks.forEach(n),this.hasDetails=!1}}on(t,n,r){var a;(a=this.hls)==null||a.on(t,n)}once(t,n,r){var a;(a=this.hls)==null||a.once(t,n)}off(t,n,r){var a;(a=this.hls)==null||a.off(t,n)}toString(){var t;return`HlsAssetPlayer: ${JB(this.assetItem)} ${(t=this.hls)==null?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const b4t=.033;class bor extends PN{constructor(t,n){super("interstitials-sched",n),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,n){return this.events?this.events.reduce((r,a)=>t<=a.startOffset&&n>a.startOffset?(delete a.error,r+1):r,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,n){if(t.event)return this.findEventIndex(t.event.identifier);let r=-1;t.nextEvent?r=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(r=this.findEventIndex(t.previousEvent.identifier)+1);const a=this.items;if(a)for(a[r]||(n===void 0&&(n=t.start),r=this.findItemIndexAtTime(n));r>=0&&(i=a[r])!=null&&i.event;){var i;r--}return r}findItemIndexAtTime(t,n){const r=this.items;if(r)for(let a=0;ai.start&&t1)for(let i=0;io&&(n!o.includes(d.identifier)):[];l.length&&l.sort((d,u)=>{const h=d.cue.pre,m=d.cue.post,p=u.cue.pre,f=u.cue.post;if(h&&!p)return-1;if(p&&!h||m&&!f)return 1;if(f&&!m)return-1;if(!h&&!p&&!m&&!f){const x=d.startTime,y=u.startTime;if(x!==y)return x-y}return d.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=l,c.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(t,c)}updateSchedule(t,n=[],r=!1){const a=this.events||[];if(a.length||n.length||this.length<2){const i=this.items,l=this.parseSchedule(a,t);(r||n.length||(i==null?void 0:i.length)!==l.length||l.some((c,d)=>Math.abs(c.playout.start-i[d].playout.start)>.005||Math.abs(c.playout.end-i[d].playout.end)>.005))&&(this.items=l,this.onScheduleUpdate(n,i))}}parseDateRanges(t,n,r){const a=[],i=Object.keys(t);for(let l=0;l!c.error&&!(c.cue.once&&c.hasPlayed)),t.length){this.resolveOffsets(t,n);let c=0,d=0;if(t.forEach((u,h)=>{const m=u.cue.pre,p=u.cue.post,f=t[h-1]||null,x=u.appendInPlace,y=p?i:u.startOffset,v=u.duration,b=u.timelineOccupancy===LTe.Range?v:0,N=u.resumptionOffset,S=(f==null?void 0:f.startTime)===y,A=y+u.cumulativeDuration;let T=x?A+v:y+N;if(m||!p&&y<=0){const M=d;d+=b,u.timelineStart=A;const I=l;l+=v,r.push({event:u,start:A,end:T,playout:{start:I,end:l},integrated:{start:M,end:d}})}else if(y<=i){if(!S){const R=y-c;if(R>b4t){const z=c,$=d;d+=R;const H=l;l+=R;const V={previousEvent:t[h-1]||null,nextEvent:u,start:z,end:z+R,playout:{start:H,end:l},integrated:{start:$,end:d}};r.push(V)}else R>0&&f&&(f.cumulativeDuration+=R,r[r.length-1].end=y)}p&&(T=A),u.timelineStart=A;const M=d;d+=b;const I=l;l+=v,r.push({event:u,start:A,end:T,playout:{start:I,end:l},integrated:{start:M,end:d}})}else return;const L=u.resumeTime;p||L>i?c=i:c=L}),c{const d=o.cue.pre,u=o.cue.post,h=d?0:u?a:o.startTime;this.updateAssetDurations(o),l===h?o.cumulativeDuration=i:(i=0,l=h),!u&&o.snapOptions.in&&(o.resumeAnchor=i9(null,r.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,n)||(o.appendInPlace=!1)),!o.appendInPlace&&c+1u$?(this.log(`"${t.identifier}" resumption ${r} not aligned with estimated timeline end ${a}`),!1):!Object.keys(n).some(l=>{const o=n[l].details,c=o.edge;if(r>=c)return this.log(`"${t.identifier}" resumption ${r} past ${l} playlist end ${c}`),!1;const d=i9(null,o.fragments,r);if(!d)return this.log(`"${t.identifier}" resumption ${r} does not align with any fragments in ${l} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const u=l==="audio"?.175:0;return Math.abs(d.start-r){const y=m.data,v=y==null?void 0:y.ASSETS;if(!Array.isArray(v)){const b=this.assignAssetListError(t,yr.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),f.url,p,x);this.hls.trigger(Ot.ERROR,b);return}t.assetListResponse=y,this.hls.trigger(Ot.ASSET_LIST_LOADED,{event:t,assetListResponse:y,networkDetails:x})},onError:(m,p,f,x)=>{const y=this.assignAssetListError(t,yr.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${m.code} ${m.text} (${p.url})`),p.url,x,f);this.hls.trigger(Ot.ERROR,y)},onTimeout:(m,p,f)=>{const x=this.assignAssetListError(t,yr.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${p.url})`),p.url,m,f);this.hls.trigger(Ot.ERROR,x)}};return o.load(c,u,h),this.hls.trigger(Ot.ASSET_LIST_LOADING,{event:t}),o}assignAssetListError(t,n,r,a,i,l){return t.error=r,{type:wo.NETWORK_ERROR,details:n,fatal:!1,interstitial:t,url:a,error:r,networkDetails:l,stats:i}}}function _4t(s){var t;s==null||(t=s.play())==null||t.catch(()=>{})}function EB(s,t){return`[${s}] Advancing timeline position to ${t}`}class wor extends PN{constructor(t,n){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled||!this.schedule)return;const a=r-this.timelinePos;if(Math.abs(a)<1/7056e5)return;const l=a<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=r,this.bufferedPos=r;const o=this.playingItem;if(!o){this.checkBuffer();return}if(l&&this.schedule.resetErrorsInRange(r,r-a)&&this.updateSchedule(!0),this.checkBuffer(),l&&r=o.end){var c;const p=this.findItemIndex(o);let f=this.schedule.findItemIndexAtTime(r);if(f===-1&&(f=p+(l?-1:1),this.log(`seeked ${l?"back ":""}to position not covered by schedule ${r} (resolving from ${p} to ${f})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!l&&f>p){const x=this.schedule.findJumpRestrictedIndex(p+1,f);if(x>p){this.setSchedulePosition(x);return}}this.setSchedulePosition(f);return}const d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){const p=o.event.assetList[0];p&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(r,p))}return}const u=d.timelineStart,h=d.duration||0;if(l&&r=u+h){var m;(m=o.event)!=null&&m.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(r)),this.setScheduleToAssetAtTime(r,d)}},this.onTimeupdate=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),r>this.timelinePos)this.timelinePos=r,r>this.bufferedPos&&this.checkBuffer();else return;const a=this.playingItem;if(!a||this.playingLastItem)return;if(r>=a.end){this.timelinePos=a.end;const o=this.findItemIndex(a);this.setSchedulePosition(o+1)}const i=this.playingAsset;if(!i)return;const l=i.timelineStart+(i.duration||0);r>=l&&this.setScheduleToAssetAtTime(r,i)},this.onScheduleUpdate=(r,a)=>{const i=this.schedule;if(!i)return;const l=this.playingItem,o=i.events||[],c=i.items||[],d=i.durations,u=r.map(x=>x.identifier),h=!!(o.length||u.length);(h||a)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o} Schedule: ${c.map(x=>ak(x))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);let m=null,p=null;l&&(m=this.updateItem(l,this.timelinePos),this.itemsMatch(l,m)?this.playingItem=m:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const f=this.bufferingItem;if(f&&(p=this.updateItem(f,this.bufferedPos),this.itemsMatch(f,p)?this.bufferingItem=p:f.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(f.event,null))),r.forEach(x=>{x.assetList.forEach(y=>{this.clearAssetPlayer(y.identifier,null)})}),this.playerQueue.forEach(x=>{if(x.interstitial.appendInPlace){const y=x.assetItem.timelineStart,v=x.timelineOffset-y;if(v)try{x.timelineOffset=y}catch(b){Math.abs(v)>u$&&this.warn(`${b} ("${x.assetId}" ${x.timelineOffset}->${y})`)}}}),h||a){if(this.hls.trigger(Ot.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:d,removedIds:u}),this.isInterstitial(l)&&u.includes(l.event.identifier)){this.warn(`Interstitial "${l.event.identifier}" removed while playing`),this.primaryFallback(l.event);return}l&&this.trimInPlace(m,l),f&&p!==m&&this.trimInPlace(p,f),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=n,this.assetListLoader=new _or(t),this.schedule=new bor(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(Ot.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Ot.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Ot.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ot.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Ot.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Ot.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(Ot.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(Ot.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(Ot.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(Ot.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(Ot.BUFFER_APPENDED,this.onBufferAppended,this),t.on(Ot.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Ot.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(Ot.MEDIA_ENDED,this.onMediaEnded,this),t.on(Ot.ERROR,this.onError,this),t.on(Ot.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(Ot.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Ot.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Ot.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ot.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Ot.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Ot.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(Ot.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(Ot.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(Ot.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(Ot.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(Ot.BUFFER_CODECS,this.onBufferCodecs,this),t.off(Ot.BUFFER_APPENDED,this.onBufferAppended,this),t.off(Ot.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Ot.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(Ot.MEDIA_ENDED,this.onMediaEnded,this),t.off(Ot.ERROR,this.onError,this),t.off(Ot.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var t;(t=this.getBufferingPlayer())==null||t.resumeBuffering()}pauseBuffering(){var t;(t=this.getBufferingPlayer())==null||t.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)}removeMediaListeners(t){w_(t,"play",this.onPlay),w_(t,"pause",this.onPause),w_(t,"seeking",this.onSeeking),w_(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,n){const r=this.media=n.media;ob(r,"seeking",this.onSeeking),ob(r,"timeupdate",this.onTimeupdate),ob(r,"play",this.onPlay),ob(r,"pause",this.onPause)}onMediaAttached(t,n){const r=this.effectivePlayingItem,a=this.detachedData;if(this.detachedData=null,r===null)this.checkStart();else if(!a){this.clearScheduleState();const i=this.findItemIndex(r);this.setSchedulePosition(i)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,n){const r=!!n.transferMedia,a=this.media;if(this.media=null,!r&&(a&&this.removeMediaListeners(a),this.detachedData)){const i=this.getBufferingPlayer();i&&(this.log(`Removing schedule state for detachedData and ${i}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,i.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,n=()=>t.bufferingItem||t.waitingItem,r=h=>h&&t.getAssetPlayer(h.identifier),a=(h,m,p,f,x)=>{if(h){let y=h[m].start;const v=h.event;if(v){if(m==="playout"||v.timelineOccupancy!==LTe.Point){const b=r(p);(b==null?void 0:b.interstitial)===v&&(y+=b.assetItem.startOffset+b[x])}}else{const b=f==="bufferedPos"?l():t[f];y+=b-h.start}return y}return 0},i=(h,m)=>{var p;if(h!==0&&m!=="primary"&&(p=t.schedule)!=null&&p.length){var f;const x=t.schedule.findItemIndexAtTime(h),y=(f=t.schedule.items)==null?void 0:f[x];if(y){const v=y[m].start-y.start;return h+v}}return h},l=()=>{const h=t.bufferedPos;return h===Number.MAX_VALUE?o("primary"):Math.max(h,0)},o=h=>{var m,p;return(m=t.primaryDetails)!=null&&m.live?t.primaryDetails.edge:((p=t.schedule)==null?void 0:p.durations[h])||0},c=(h,m)=>{var p,f;const x=t.effectivePlayingItem;if(x!=null&&(p=x.event)!=null&&p.restrictions.skip||!t.schedule)return;t.log(`seek to ${h} "${m}"`);const y=t.effectivePlayingItem,v=t.schedule.findItemIndexAtTime(h,m),b=(f=t.schedule.items)==null?void 0:f[v],N=t.getBufferingPlayer(),S=N==null?void 0:N.interstitial,A=S==null?void 0:S.appendInPlace,T=y&&t.itemsMatch(y,b);if(y&&(A||T)){const L=r(t.playingAsset),M=(L==null?void 0:L.media)||t.primaryMedia;if(M){const I=m==="primary"?M.currentTime:a(y,m,t.playingAsset,"timelinePos","currentTime"),R=h-I,z=(A?I:M.currentTime)+R;if(z>=0&&(!L||A||z<=L.duration)){M.currentTime=z;return}}}if(b){let L=h;if(m!=="primary"){const I=b[m].start,R=h-I;L=b.start+R}const M=!t.isInterstitial(b);if((!t.isInterstitial(y)||y.event.appendInPlace)&&(M||b.event.appendInPlace)){const I=t.media||(A?N==null?void 0:N.media:null);I&&(I.currentTime=L)}else if(y){const I=t.findItemIndex(y);if(v>I){const z=t.schedule.findJumpRestrictedIndex(I+1,v);if(z>I){t.setSchedulePosition(z);return}}let R=0;if(M)t.timelinePos=L,t.checkBuffer();else{const z=b.event.assetList,$=h-(b[m]||b).start;for(let H=z.length;H--;){const V=z[H];if(V.duration&&$>=V.startOffset&&${const h=t.effectivePlayingItem;if(t.isInterstitial(h))return h;const m=n();return t.isInterstitial(m)?m:null},u={get bufferedEnd(){const h=n(),m=t.bufferingItem;if(m&&m===h){var p;return a(m,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-m.playout.start||((p=t.bufferingAsset)==null?void 0:p.startOffset)||0}return 0},get currentTime(){const h=d(),m=t.effectivePlayingItem;return m&&m===h?a(m,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-m.playout.start:0},set currentTime(h){const m=d(),p=t.effectivePlayingItem;p&&p===m&&c(h+p.playout.start,"playout")},get duration(){const h=d();return h?h.playout.end-h.playout.start:0},get assetPlayers(){var h;const m=(h=d())==null?void 0:h.event.assetList;return m?m.map(p=>t.getAssetPlayer(p.identifier)):[]},get playingIndex(){var h;const m=(h=d())==null?void 0:h.event;return m&&t.effectivePlayingAsset?m.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var h;return((h=t.schedule)==null||(h=h.events)==null?void 0:h.slice(0))||[]},get schedule(){var h;return((h=t.schedule)==null||(h=h.items)==null?void 0:h.slice(0))||[]},get interstitialPlayer(){return d()?u:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return n()},get bufferingIndex(){const h=n();return t.findItemIndex(h)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const h=t.effectivePlayingItem;return t.findItemIndex(h)},primary:{get bufferedEnd(){return l()},get currentTime(){const h=t.timelinePos;return h>0?h:0},set currentTime(h){c(h,"primary")},get duration(){return o("primary")},get seekableStart(){var h;return((h=t.primaryDetails)==null?void 0:h.fragmentStart)||0}},integrated:{get bufferedEnd(){return a(n(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return a(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(h){c(h,"integrated")},get duration(){return o("integrated")},get seekableStart(){var h;return i(((h=t.primaryDetails)==null?void 0:h.fragmentStart)||0,"integrated")}},skip:()=>{const h=t.effectivePlayingItem,m=h==null?void 0:h.event;if(m&&!m.restrictions.skip){const p=t.findItemIndex(h);if(m.appendInPlace){const f=h.playout.start+h.event.duration;c(f+.001,"playout")}else t.advanceAfterAssetEnded(m,p,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const n=this.playingItem,r=(t=this.schedule)==null?void 0:t.items;return!this.playbackStarted||!n||!r?!1:this.findItemIndex(n)===r.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var t,n;if(this.mediaSelection===null)return;const r=this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&!r.event.appendInPlace)return;let a=this.media;!a&&(t=this.bufferingItem)!=null&&(t=t.event)!=null&&t.appendInPlace&&(a=this.primaryMedia);const i=(n=a)==null?void 0:n.currentTime;if(!(i===void 0||!Bi(i)))return i}get primaryMedia(){var t;return this.media||((t=this.detachedData)==null?void 0:t.media)||null}isInterstitial(t){return!!(t!=null&&t.event)}retreiveMediaSource(t,n){const r=this.getAssetPlayer(t);r&&this.transferMediaFromPlayer(r,n)}transferMediaFromPlayer(t,n){const r=t.interstitial.appendInPlace,a=t.media;if(r&&a===this.primaryMedia){if(this.bufferingAsset=null,(!n||this.isInterstitial(n)&&!n.event.appendInPlace)&&n&&a){this.detachedData={media:a};return}const i=t.transferMedia();this.log(`transfer MediaSource from ${t} ${fm(i)}`),this.detachedData=i}else n&&a&&(this.shouldPlay||(this.shouldPlay=!a.paused))}transferMediaTo(t,n){var r,a;if(t.media===n)return;let i=null;const l=this.hls,o=t!==l,c=o&&t.interstitial.appendInPlace,d=(r=this.detachedData)==null?void 0:r.mediaSource;let u;if(l.media)c&&(i=l.transferMedia(),this.detachedData=i),u="Primary";else if(d){const f=this.getBufferingPlayer();f?(i=f.transferMedia(),u=`${f}`):u="detached MediaSource"}else u="detached media";if(!i){if(d)i=this.detachedData,this.log(`using detachedData: MediaSource ${fm(i)}`);else if(!this.detachedData||l.media===n){const f=this.playerQueue;f.length>1&&f.forEach(x=>{if(o&&x.interstitial.appendInPlace!==c){const y=x.interstitial;this.clearInterstitial(x.interstitial,null),y.appendInPlace=!1,y.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${y}`)}}),this.hls.detachMedia(),this.detachedData={media:n}}}const h=i&&"mediaSource"in i&&((a=i.mediaSource)==null?void 0:a.readyState)!=="closed",m=h&&i?i:n;this.log(`${h?"transfering MediaSource":"attaching media"} to ${o?t:"Primary"} from ${u} (media.currentTime: ${n.currentTime})`);const p=this.schedule;if(m===i&&p){const f=o&&t.assetId===p.assetIdAtEnd;m.overrides={duration:p.duration,endOfStream:!o||f,cueRemoval:!o}}t.attachMedia(m)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,n=t==null?void 0:t.events;if(!n||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const r=this.timelinePos,a=this.effectivePlayingItem;if(r===-1){const i=this.hls.startPosition;if(this.timelinePos=i,n.length===0)this.setSchedulePosition(0);else if(n[0].cue.pre){this.log(EB("checkStart (preroll)",i));const l=t.findEventIndex(n[0].identifier);this.setSchedulePosition(l)}else if(i>=0||!this.primaryLive){this.log(EB("checkStart",i));const l=this.timelinePos=i>0?i:0,o=t.findItemIndexAtTime(l);this.setSchedulePosition(o)}else this.hls.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(a&&!this.playingItem){this.log(EB("checkStart (playing item)",a.start));const i=t.findItemIndex(a);this.setSchedulePosition(i)}}advanceAssetBuffering(t,n){const r=t.event,a=r.findAssetIndex(n),i=$ze(r,a);if(!r.isAssetPastPlayoutLimit(i))this.bufferedToEvent(t,i);else if(this.schedule){var l;const o=(l=this.schedule.items)==null?void 0:l[this.findItemIndex(t)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(t,n,r){const a=$ze(t,r);if(t.isAssetPastPlayoutLimit(a)){if(this.schedule){const i=this.schedule.items;if(i){const l=n+1,o=i.length;if(l>=o){this.setSchedulePosition(-1);return}const c=t.resumeTime;this.timelinePos=0?a[t]:null;this.log(`setSchedulePosition ${t}, ${n} (${i&&ak(i)}) pos: ${this.timelinePos}`);const l=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(l)){const u=l.event,h=this.playingAsset,m=h==null?void 0:h.identifier,p=m?this.getAssetPlayer(m):null;if(p&&m&&(!this.eventItemsMatch(l,i)||n!==void 0&&m!==u.assetList[n].identifier)){var c;const f=u.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${f+1}/${u.assetList.length} ${JB(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(Ot.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:f,event:u,schedule:a.slice(0),scheduleIndex:t,player:p}),l!==this.playingItem){this.itemsMatch(l,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),f);return}this.retreiveMediaSource(m,i),p.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&p.detachMedia()}if(!this.eventItemsMatch(l,i)&&(this.endedItem=l,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${ak(l)}`),u.hasPlayed=!0,this.hls.trigger(Ot.INTERSTITIAL_ENDED,{event:u,schedule:a.slice(0),scheduleIndex:t}),u.cue.once)){var d;this.updateSchedule();const f=(d=this.schedule)==null?void 0:d.items;if(i&&f){const x=this.findItemIndex(i);this.advanceSchedule(x,f,n,l,o)}return}}this.advanceSchedule(t,a,n,l,o)}advanceSchedule(t,n,r,a,i){const l=this.schedule;if(!l)return;const o=n[t]||null,c=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(u=>{const h=u.interstitial,m=l.findEventIndex(h.identifier);(mt+1)&&this.clearInterstitial(h,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const u=o.event;if(r===void 0){r=l.findAssetIndex(u,this.timelinePos);const f=$ze(u,r-1);if(u.isAssetPastPlayoutLimit(f)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,t,r);return}r=f}const h=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let m=this.preloadAssets(u,r);if(this.eventItemsMatch(o,h||a)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${ak(o)} ${u.appendInPlace?"append in place":""}`),this.hls.trigger(Ot.INTERSTITIAL_STARTED,{event:u,schedule:n.slice(0),scheduleIndex:t})),!u.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${u}`);return}if(u.assetListLoader&&(u.assetListLoader.destroy(),u.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${u}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const p=u.assetList[r];if(!p){this.advanceAfterAssetEnded(u,t,r||0);return}if(m||(m=this.getAssetPlayer(p.identifier)),m===null||m.destroyed){const f=u.assetList.length;this.warn(`asset ${r+1}/${f} player destroyed ${u}`),m=this.createAssetPlayer(u,p,r),m.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(p))return;this.startAssetPlayer(m,r,n,t,c),this.shouldPlay&&_4t(m.media)}else o?(this.resumePrimary(o,t,a),this.shouldPlay&&_4t(this.hls.media)):i&&this.isInterstitial(a)&&(this.endedItem=null,this.playingItem=a,a.event.appendInPlace||this.attachPrimary(l.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var t;return(t=this.mediaSelection)==null?void 0:t.main.details}get primaryLive(){var t;return!!((t=this.primaryDetails)!=null&&t.live)}resumePrimary(t,n,r){var a,i;if(this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(t),this.log(`resuming ${ak(t)}`),!((a=this.detachedData)!=null&&a.mediaSource)){let o=this.timelinePos;(o=t.end)&&(o=this.getPrimaryResumption(t,n),this.log(EB("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,t)}if(!r)return;const l=(i=this.schedule)==null?void 0:i.items;l&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${ak(t)}`),this.hls.trigger(Ot.INTERSTITIALS_PRIMARY_RESUMED,{schedule:l.slice(0),scheduleIndex:n}),this.checkBuffer())}getPrimaryResumption(t,n){const r=t.start;if(this.primaryLive){const a=this.primaryDetails;if(n===0)return this.hls.startPosition;if(a&&(ra.edge))return this.hls.liveSyncPosition||-1}return r}isAssetBuffered(t){const n=this.getAssetPlayer(t.identifier);return n!=null&&n.hls?n.hls.bufferedToEnd:uc.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,n,r){n?this.setBufferingItem(n):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const a=this.primaryMedia;if(!a)return;const i=this.hls;i.media?this.checkBuffer():(this.transferMediaTo(i,a),r&&this.startLoadingPrimaryAt(t,r)),r||(this.log(EB("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,r))}startLoadingPrimaryAt(t,n){var r;const a=this.hls;!a.loadingEnabled||!a.media||Math.abs((((r=a.mainForwardBufferInfo)==null?void 0:r.start)||a.media.currentTime)-t)>.5?a.startLoad(t,n):a.bufferingEnabled||a.resumeBuffering()}onManifestLoading(){var t;this.stopLoad(),(t=this.schedule)==null||t.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(Ot.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(Ot.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,n){if(n.level===-1||!this.schedule)return;const r=this.hls.levels[n.level];if(!r.details)return;const a=_h(_h({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=a,this.schedule.parseInterstitialDateRanges(a,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(t,n){const r=this.hls.audioTracks[n.id],a=this.mediaSelection;if(!a){this.altSelection=_h(_h({},this.altSelection),{},{audio:r});return}const i=_h(_h({},a),{},{audio:r});this.mediaSelection=i}onSubtitleTrackUpdated(t,n){const r=this.hls.subtitleTracks[n.id],a=this.mediaSelection;if(!a){this.altSelection=_h(_h({},this.altSelection),{},{subtitles:r});return}const i=_h(_h({},a),{},{subtitles:r});this.mediaSelection=i}onAudioTrackSwitching(t,n){const r=T5t(n);this.playerQueue.forEach(({hls:a})=>a&&(a.setAudioOption(n)||a.setAudioOption(r)))}onSubtitleTrackSwitch(t,n){const r=T5t(n);this.playerQueue.forEach(({hls:a})=>a&&(a.setSubtitleOption(n)||n.id!==-1&&a.setSubtitleOption(r)))}onBufferCodecs(t,n){const r=n.tracks;r&&(this.requiredTracks=r)}onBufferAppended(t,n){this.checkBuffer()}onBufferFlushed(t,n){const r=this.playingItem;if(r&&!this.itemsMatch(r,this.bufferingItem)&&!this.isInterstitial(r)){const a=this.timelinePos;this.bufferedPos=a,this.checkBuffer()}}onBufferedToEnd(t){if(!this.schedule)return;const n=this.schedule.events;if(this.bufferedPos.25){t.event.assetList.forEach((i,l)=>{t.event.isAssetPastPlayoutLimit(l)&&this.clearAssetPlayer(i.identifier,null)});const r=t.end+.25,a=uc.bufferInfo(this.primaryMedia,r,0);(a.end>r||(a.nextStart||0)>r)&&(this.log(`trim buffered interstitial ${ak(t)} (was ${ak(n)})`),this.attachPrimary(r,null,!0),this.flushFrontBuffer(r))}}itemsMatch(t,n){return!!n&&(t===n||t.event&&n.event&&this.eventItemsMatch(t,n)||!t.event&&!n.event&&this.findItemIndex(t)===this.findItemIndex(n))}eventItemsMatch(t,n){var r;return!!n&&(t===n||t.event.identifier===((r=n.event)==null?void 0:r.identifier))}findItemIndex(t,n){return t&&this.schedule?this.schedule.findItemIndex(t,n):-1}updateSchedule(t=!1){var n;const r=this.mediaSelection;r&&((n=this.schedule)==null||n.updateSchedule(r,[],t))}checkBuffer(t){var n;const r=(n=this.schedule)==null?void 0:n.items;if(!r)return;const a=uc.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=a.len<1),this.updateBufferedPos(a.end,r,t)}updateBufferedPos(t,n,r){const a=this.schedule,i=this.bufferingItem;if(this.bufferedPos>t||!a)return;if(n.length===1&&this.itemsMatch(n[0],i)){this.bufferedPos=t;return}const l=this.playingItem,o=this.findItemIndex(l);let c=a.findItemIndexAtTime(t);if(this.bufferedPos=i.end||(d=m.event)!=null&&d.appendInPlace&&t+.01>=m.start)&&(c=h),this.isInterstitial(i)){const p=i.event;if(h-o>1&&p.appendInPlace===!1||p.assetList.length===0&&p.assetListLoader)return}if(this.bufferedPos=t,c>u&&c>o)this.bufferedToItem(m);else{const p=this.primaryDetails;this.primaryLive&&p&&t>p.edge-p.targetduration&&m.start{const i=this.getAssetPlayer(a.identifier);return!(i!=null&&i.bufferedInPlaceToEnd(n))})}setBufferingItem(t){const n=this.bufferingItem,r=this.schedule;if(!this.itemsMatch(t,n)&&r){const{items:a,events:i}=r;if(!a||!i)return n;const l=this.isInterstitial(t),o=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const c=o?o.remaining:n?n.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${ak(t)}`+(n?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(l){const d=r.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((u,h)=>{const m=this.getAssetPlayer(u.identifier);m&&(h===d&&m.loadSource(),m.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(Ot.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:i.slice(0),schedule:a.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return n}bufferedToItem(t,n=0){const r=this.setBufferingItem(t);if(!this.playbackDisabled){if(this.isInterstitial(t))this.bufferedToEvent(t,n);else if(r!==null){this.bufferingAsset=null;const a=this.detachedData;a?a.mediaSource?this.attachPrimary(t.start,t,!0):this.preloadPrimary(t):this.preloadPrimary(t)}}}preloadPrimary(t){const n=this.findItemIndex(t),r=this.getPrimaryResumption(t,n);this.startLoadingPrimaryAt(r)}bufferedToEvent(t,n){const r=t.event,a=r.assetList.length===0&&!r.assetListLoader,i=r.cue.once;if(a||!i){const l=this.preloadAssets(r,n);if(l!=null&&l.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(l,o)}}}preloadAssets(t,n){const r=t.assetUrl,a=t.assetList.length,i=a===0&&!t.assetListLoader,l=t.cue.once;if(i){const c=t.timelineStart;if(t.appendInPlace){var o;const m=this.playingItem;!this.isInterstitial(m)&&(m==null||(o=m.nextEvent)==null?void 0:o.identifier)===t.identifier&&this.flushFrontBuffer(c+.25)}let d,u=0;if(!this.playingItem&&this.primaryLive&&(u=this.hls.startPosition,u===-1&&(u=this.hls.liveSyncPosition||0)),u&&!(t.cue.pre||t.cue.post)){const m=u-c;m>0&&(d=Math.round(m*1e3)/1e3)}if(this.log(`Load interstitial asset ${n+1}/${r?1:a} ${t}${d?` live-start: ${u} start-offset: ${d}`:""}`),r)return this.createAsset(t,0,0,c,t.duration,r);const h=this.assetListLoader.loadAssetList(t,d);h&&(t.assetListLoader=h)}else if(!l&&a){for(let d=n;d{this.hls.trigger(Ot.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:a})})}getAssetPlayerQueueIndex(t){const n=this.playerQueue;for(let r=0;r1){const A=n.duration;A&&S{if(S.live){var A;const M=new Error(`Interstitials MUST be VOD assets ${t}`),I={fatal:!0,type:wo.OTHER_ERROR,details:yr.INTERSTITIAL_ASSET_ITEM_ERROR,error:M},R=((A=this.schedule)==null?void 0:A.findEventIndex(t.identifier))||-1;this.handleAssetItemError(I,t,R,r,M.message);return}const T=S.edge-S.fragmentStart,L=n.duration;(x||L===null||T>L)&&(x=!1,this.log(`Interstitial asset "${h}" duration change ${L} > ${T}`),n.duration=T,this.updateSchedule())};f.on(Ot.LEVEL_UPDATED,(S,{details:A})=>y(A)),f.on(Ot.LEVEL_PTS_UPDATED,(S,{details:A})=>y(A)),f.on(Ot.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const v=(S,A)=>{const T=this.getAssetPlayer(h);if(T&&A.tracks){T.off(Ot.BUFFER_CODECS,v),T.tracks=A.tracks;const L=this.primaryMedia;this.bufferingAsset===T.assetItem&&L&&!T.media&&this.bufferAssetPlayer(T,L)}};f.on(Ot.BUFFER_CODECS,v);const b=()=>{var S;const A=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${A}`),!A||!this.schedule)return;const T=this.schedule.findEventIndex(t.identifier),L=(S=this.schedule.items)==null?void 0:S[T];this.isInterstitial(L)&&this.advanceAssetBuffering(L,n)};f.on(Ot.BUFFERED_TO_END,b);const N=S=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const T=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,T,S)};return f.once(Ot.MEDIA_ENDED,N(r)),f.once(Ot.PLAYOUT_LIMIT_REACHED,N(1/0)),f.on(Ot.ERROR,(S,A)=>{if(!this.schedule)return;const T=this.getAssetPlayer(h);if(A.details===yr.BUFFER_STALLED_ERROR){if(T!=null&&T.appendInPlace){this.handleInPlaceStall(t);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(A,t,this.schedule.findEventIndex(t.identifier),r,`Asset player error ${A.error} ${t}`)}),f.on(Ot.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const A=new Error(`Asset player destroyed unexpectedly ${h}`),T={fatal:!0,type:wo.OTHER_ERROR,details:yr.INTERSTITIAL_ASSET_ITEM_ERROR,error:A};this.handleAssetItemError(T,t,this.schedule.findEventIndex(t.identifier),r,A.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${JB(n)}`),this.hls.trigger(Ot.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:n,assetListIndex:r,event:t,player:f}),f}clearInterstitial(t,n){this.clearAssetPlayers(t,n),t.reset()}clearAssetPlayers(t,n){t.assetList.forEach(r=>{this.clearAssetPlayer(r.identifier,n)})}resetAssetPlayer(t){const n=this.getAssetPlayerQueueIndex(t);if(n!==-1){this.log(`reset asset player "${t}" after error`);const r=this.playerQueue[n];this.transferMediaFromPlayer(r,null),r.resetDetails()}}clearAssetPlayer(t,n){const r=this.getAssetPlayerQueueIndex(t);if(r!==-1){const a=this.playerQueue[r];this.log(`clear ${a} toSegment: ${n&&ak(n)}`),this.transferMediaFromPlayer(a,n),this.playerQueue.splice(r,1),a.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,n,r,a,i){const{interstitial:l,assetItem:o,assetId:c}=t,d=l.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!u||u.identifier!==c)&&(u&&(this.clearAssetPlayer(u.identifier,r[a]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${n+1}/${d} ${JB(o)}`),this.hls.trigger(Ot.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:n,event:l,schedule:r.slice(0),scheduleIndex:a,player:t})),this.bufferAssetPlayer(t,i)}bufferAssetPlayer(t,n){var r,a;if(!this.schedule)return;const{interstitial:i,assetItem:l}=t,o=this.schedule.findEventIndex(i.identifier),c=(r=this.schedule.items)==null?void 0:r[o];if(!c)return;t.loadSource(),this.setBufferingItem(c),this.bufferingAsset=l;const d=this.getBufferingPlayer();if(d===t)return;const u=i.appendInPlace;if(u&&(d==null?void 0:d.interstitial.appendInPlace)===!1)return;const h=(d==null?void 0:d.tracks)||((a=this.detachedData)==null?void 0:a.tracks)||this.requiredTracks;if(u&&l!==this.playingAsset){if(!t.tracks){this.log(`Waiting for track info before buffering ${t}`);return}if(h&&!Pss(h,t.tracks)){const m=new Error(`Asset ${JB(l)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),p={fatal:!0,type:wo.OTHER_ERROR,details:yr.INTERSTITIAL_ASSET_ITEM_ERROR,error:m},f=i.findAssetIndex(l);this.handleAssetItemError(p,i,o,f,m.message);return}}this.transferMediaTo(t,n)}handleInPlaceStall(t){const n=this.schedule,r=this.primaryMedia;if(!n||!r)return;const a=r.currentTime,i=n.findAssetIndex(t,a),l=t.assetList[i];if(l){const o=this.getAssetPlayer(l.identifier);if(o){const c=o.currentTime||a-l.timelineStart,d=o.duration-c;if(this.warn(`Stalled at ${c} of ${c+d} in ${o} ${t} (media.currentTime: ${a})`),c&&(d/r.playbackRate<.5||o.bufferedInPlaceToEnd(r))&&o.hls){const u=n.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,u,i)}}}}advanceInPlace(t){const n=this.primaryMedia;n&&n.currentTime!x.error))n.error=f;else for(let x=a;x{const v=parseFloat(x.DURATION);this.createAsset(i,y,u,c+u,v,x.URI),u+=v}),i.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${d}) ${i}`);const h=this.waitingItem,m=(h==null?void 0:h.event.identifier)===l;this.updateSchedule();const p=(a=this.bufferingItem)==null?void 0:a.event;if(m){var f;const x=this.schedule.findEventIndex(l),y=(f=this.schedule.items)==null?void 0:f[x];if(y){if(!this.playingItem&&this.timelinePos>y.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==x){i.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${i}`),this.log(i.error.message),this.updateSchedule(!0),this.primaryFallback(i);return}this.setBufferingItem(y)}this.setSchedulePosition(x)}else if((p==null?void 0:p.identifier)===l){const x=i.assetList[0];if(x){const y=this.getAssetPlayer(x.identifier);if(p.appendInPlace){const v=this.primaryMedia;y&&v&&this.bufferAssetPlayer(y,v)}else y&&y.loadSource()}}}onError(t,n){if(this.schedule)switch(n.details){case yr.ASSET_LIST_PARSING_ERROR:case yr.ASSET_LIST_LOAD_ERROR:case yr.ASSET_LIST_LOAD_TIMEOUT:{const r=n.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break}case yr.BUFFER_STALLED_ERROR:{const r=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&r.event.appendInPlace){this.handleInPlaceStall(r.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const w4t=500;class jor extends Brt{constructor(t,n,r){super(t,n,r,"subtitle-stream-controller",io.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(Ot.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Ot.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(Ot.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(Ot.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(Ot.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(Ot.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(Ot.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Ot.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(Ot.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(Ot.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(Ot.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(Ot.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,n){this.stopLoad(),this.state=aa.IDLE,this.setInterval(w4t),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,n){this.tracksBuffered=[],super.onMediaDetaching(t,n)}onLevelLoaded(t,n){this.mainDetails=n.details}onSubtitleFragProcessed(t,n){const{frag:r,success:a}=n;if(this.fragContextChanged(r)||(Fg(r)&&(this.fragPrevious=r),this.state=aa.IDLE),!a)return;const i=this.tracksBuffered[this.currentTrackId];if(!i)return;let l;const o=r.start;for(let d=0;d=i[d].start&&o<=i[d].end){l=i[d];break}const c=r.start+r.duration;l?l.end=c:(l={start:o,end:c},i.push(l)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null),this.media&&this.tick()}onBufferFlushing(t,n){const{startOffset:r,endOffset:a}=n;if(r===0&&a!==Number.POSITIVE_INFINITY){const i=a-1;if(i<=0)return;n.endOffsetSubtitles=Math.max(0,i),this.tracksBuffered.forEach(l=>{for(let o=0;onew Wte(r));return}this.tracksBuffered=[],this.levels=n.map(r=>{const a=new Wte(r);return this.tracksBuffered[a.id]=[],a}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,io.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(t,n){var r;if(this.currentTrackId=n.id,!((r=this.levels)!=null&&r.length)||this.currentTrackId===-1){this.clearInterval();return}const a=this.levels[this.currentTrackId];a!=null&&a.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,a&&this.state!==aa.STOPPED&&this.setInterval(w4t)}onSubtitleTrackLoaded(t,n){var r;const{currentTrackId:a,levels:i}=this,{details:l,id:o}=n;if(!i){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const c=i[o];if(o>=i.length||!c)return;this.log(`Subtitle track ${o} loaded [${l.startSN},${l.endSN}]${l.lastPartSn?`[part-${l.lastPartSn}-${l.lastPartIndex}]`:""},duration:${l.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(l.live||(r=c.details)!=null&&r.live){if(l.deltaUpdateFailed)return;const h=this.mainDetails;if(!h){this.startFragRequested=!1;return}const m=h.fragments[0];if(!c.details)l.hasProgramDateTime&&h.hasProgramDateTime?(MTe(l,h),d=l.fragmentStart):m&&(d=m.start,zKe(l,d));else{var u;d=this.alignPlaylists(l,c.details,(u=this.levelLastLoaded)==null?void 0:u.details),d===0&&m&&(d=m.start,zKe(l,d))}h&&!this.startFragRequested&&this.setStartPosition(h,d)}c.details=l,this.levelLastLoaded=c,o===a&&(this.hls.trigger(Ot.SUBTITLE_TRACK_UPDATED,{details:l,id:o,groupId:n.groupId}),this.tick(),l.live&&!this.fragCurrent&&this.media&&this.state===aa.IDLE&&(i9(null,l.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(t){const{frag:n,payload:r}=t,a=n.decryptdata,i=this.hls;if(!this.fragContextChanged(n)&&r&&r.byteLength>0&&a!=null&&a.key&&a.iv&&c$(a.method)){const l=performance.now();this.decrypter.decrypt(new Uint8Array(r),a.key.buffer,a.iv.buffer,Frt(a.method)).catch(o=>{throw i.trigger(Ot.ERROR,{type:wo.MEDIA_ERROR,details:yr.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:n}),o}).then(o=>{const c=performance.now();i.trigger(Ot.FRAG_DECRYPTED,{frag:n,payload:o,stats:{tstart:l,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=aa.IDLE})}}doTick(){if(!this.media){this.state=aa.IDLE;return}if(this.state===aa.IDLE){const{currentTrackId:t,levels:n}=this,r=n==null?void 0:n[t];if(!r||!n.length||!r.details||this.waitForLive(r))return;const{config:a}=this,i=this.getLoadPosition(),l=uc.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,a.maxBufferHole),{end:o,len:c}=l,d=r.details,u=this.hls.maxBufferLength+d.levelTargetDuration;if(c>u)return;const h=d.fragments,m=h.length,p=d.edge;let f=null;const x=this.fragPrevious;if(op-b?0:b;f=i9(x,h,Math.max(h[0].start,o),N),!f&&x&&x.start{if(a=a>>>0,a>i-1)throw new DOMException(`Failed to execute '${r}' on 'TimeRanges': The index provided (${a}) is greater than the maximum bound (${i})`);return t[a][r]};this.buffered={get length(){return t.length},end(r){return n("end",r,t.length)},start(r){return n("start",r,t.length)}}}}const kor={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Xns=s=>String.fromCharCode(kor[s]||s),uk=15,dC=100,Sor={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Cor={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Aor={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Eor={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Tor=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Mor{constructor(){this.time=null,this.verboseLevel=0}log(t,n){if(this.verboseLevel>=t){const r=typeof n=="function"?n():n;Ah.log(`${this.time} [${t}] ${r}`)}}}const iI=function(t){const n=[];for(let r=0;rdC&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=dC)}moveCursor(t){const n=this.pos+t;if(t>1)for(let r=this.pos+1;r=144&&this.backSpace();const n=Xns(t);if(this.pos>=dC){this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+n+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(n,this.currPenState),this.moveCursor(1)}clearFromPos(t){let n;for(n=t;n"pacData = "+fm(t));let n=t.row-1;if(this.nrRollUpRows&&n"bkgData = "+fm(t)),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const t=this.currRow+1-this.nrRollUpRows,n=this.rows.splice(t,1)[0];n.clear(),this.rows.splice(this.currRow,0,n),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const n=[];let r="",a=-1;for(let i=0;i0&&(t?r="["+n.join(" | ")+"]":r=n.join(` `)),r}getTextAndFormat(){return this.rows}}class j4t{constructor(t,n,r){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=n,this.mode=null,this.verbose=0,this.displayedMemory=new Vze(r),this.nonDisplayedMemory=new Vze(r),this.lastOutputScreen=new Vze(r),this.currRollUpRow=this.displayedMemory.rows[uk-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[uk-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,()=>"MODE="+t),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}insertChars(t){for(let r=0;rn+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const n={flash:!1};if(n.underline=t%2===1,n.italics=t>=46,n.italics)n.foreground="white";else{const r=Math.floor(t/2)-16,a=["white","green","blue","cyan","red","yellow","magenta"];n.foreground=a[r]}this.logger.log(2,"MIDROW: "+fm(n)),this.writeScreen.setPen(n)}outputDataUpdate(t=!1){const n=this.logger.time;n!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=n:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,n,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:n),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class N4t{constructor(t,n,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Ror(),this.logger=void 0;const a=this.logger=new Mor;this.channels=[null,new j4t(t,n,a),new j4t(t+1,r,a)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,n){this.channels[t].setHandler(n)}addData(t,n){this.logger.time=t;for(let r=0;r"["+iI([n[r],n[r+1]])+"] -> ("+iI([a,i])+")");const c=this.cmdHistory;if(a>=16&&a<=31){if(Ior(a,i,c)){Zce(null,null,c),this.logger.log(3,()=>"Repeated command ("+iI([a,i])+") is dropped");continue}Zce(a,i,this.cmdHistory),l=this.parseCmd(a,i),l||(l=this.parseMidrow(a,i)),l||(l=this.parsePAC(a,i)),l||(l=this.parseBackgroundAttributes(a,i))}else Zce(null,null,c);if(!l&&(o=this.parseChars(a,i),o)){const u=this.currentChannel;u&&u>0?this.channels[u].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!l&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+iI([a,i])+" orig: "+iI([n[r],n[r+1]]))}}parseCmd(t,n){const r=(t===20||t===28||t===21||t===29)&&n>=32&&n<=47,a=(t===23||t===31)&&n>=33&&n<=35;if(!(r||a))return!1;const i=t===20||t===21||t===23?1:2,l=this.channels[i];return t===20||t===21||t===28||t===29?n===32?l.ccRCL():n===33?l.ccBS():n===34?l.ccAOF():n===35?l.ccAON():n===36?l.ccDER():n===37?l.ccRU(2):n===38?l.ccRU(3):n===39?l.ccRU(4):n===40?l.ccFON():n===41?l.ccRDC():n===42?l.ccTR():n===43?l.ccRTD():n===44?l.ccEDM():n===45?l.ccCR():n===46?l.ccENM():n===47&&l.ccEOC():l.ccTO(n-32),this.currentChannel=i,!0}parseMidrow(t,n){let r=0;if((t===17||t===25)&&n>=32&&n<=47){if(t===17?r=1:r=2,r!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const a=this.channels[r];return a?(a.ccMIDROW(n),this.logger.log(3,()=>"MIDROW ("+iI([t,n])+")"),!0):!1}return!1}parsePAC(t,n){let r;const a=(t>=17&&t<=23||t>=25&&t<=31)&&n>=64&&n<=127,i=(t===16||t===24)&&n>=64&&n<=95;if(!(a||i))return!1;const l=t<=23?1:2;n>=64&&n<=95?r=l===1?Sor[t]:Aor[t]:r=l===1?Cor[t]:Eor[t];const o=this.channels[l];return o?(o.setPAC(this.interpretPAC(r,n)),this.currentChannel=l,!0):!1}interpretPAC(t,n){let r;const a={color:null,italics:!1,indent:null,underline:!1,row:t};return n>95?r=n-96:r=n-64,a.underline=(r&1)===1,r<=13?a.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(a.italics=!0,a.color="white"):a.indent=Math.floor((r-16)/2)*4,a}parseChars(t,n){let r,a=null,i=null;if(t>=25?(r=2,i=t-8):(r=1,i=t),i>=17&&i<=19){let l;i===17?l=n+80:i===18?l=n+112:l=n+144,this.logger.log(2,()=>"Special char '"+Xns(l)+"' in channel "+r),a=[l]}else t>=32&&t<=127&&(a=n===0?[t]:[t,n]);return a&&this.logger.log(3,()=>"Char codes = "+iI(a).join(",")),a}parseBackgroundAttributes(t,n){const r=(t===16||t===24)&&n>=32&&n<=47,a=(t===23||t===31)&&n>=45&&n<=47;if(!(r||a))return!1;let i;const l={};t===16||t===24?(i=Math.floor((n-32)/2),l.background=Tor[i],n%2===1&&(l.background=l.background+"_semi")):n===45?l.background="transparent":(l.foreground="black",n===47&&(l.underline=!0));const o=t<=23?1:2;return this.channels[o].setBkgData(l),!0}reset(){for(let t=0;t100)throw new Error("Position must be between 0 and 100.");T=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",i({},h,{get:function(){return L},set:function(R){const z=a(R);if(!z)throw new SyntaxError("An invalid or illegal string was specified.");L=z,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",i({},h,{get:function(){return M},set:function(R){if(R<0||R>100)throw new Error("Size must be between 0 and 100.");M=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",i({},h,{get:function(){return I},set:function(R){const z=a(R);if(!z)throw new SyntaxError("An invalid or illegal string was specified.");I=z,this.hasBeenReset=!0}})),u.displayState=void 0}return l.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},l}();class Dor{decode(t,n){if(!t)return"";if(typeof t!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function Jns(s){function t(r,a,i,l){return(r|0)*3600+(a|0)*60+(i|0)+parseFloat(l||0)}const n=s.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return n?parseFloat(n[2])>59?t(n[2],n[3],0,n[4]):t(n[1],n[2],n[3],n[4]):null}class Oor{constructor(){this.values=Object.create(null)}set(t,n){!this.get(t)&&n!==""&&(this.values[t]=n)}get(t,n,r){return r?this.has(t)?this.values[t]:n[r]:this.has(t)?this.values[t]:n}has(t){return t in this.values}alt(t,n,r){for(let a=0;a=0&&r<=100)return this.set(t,r),!0}return!1}}function ers(s,t,n,r){const a=r?s.split(r):[s];for(const i in a){if(typeof a[i]!="string")continue;const l=a[i].split(n);if(l.length!==2)continue;const o=l[0],c=l[1];t(o,c)}}const WKe=new Qrt(0,0,""),Xce=WKe.align==="middle"?"middle":"center";function For(s,t,n){const r=s;function a(){const o=Jns(s);if(o===null)throw new Error("Malformed timestamp: "+r);return s=s.replace(/^[^\sa-zA-Z-]+/,""),o}function i(o,c){const d=new Oor;ers(o,function(m,p){let f;switch(m){case"region":for(let x=n.length-1;x>=0;x--)if(n[x].id===p){d.set(m,n[x].region);break}break;case"vertical":d.alt(m,p,["rl","lr"]);break;case"line":f=p.split(","),d.integer(m,f[0]),d.percent(m,f[0])&&d.set("snapToLines",!1),d.alt(m,f[0],["auto"]),f.length===2&&d.alt("lineAlign",f[1],["start",Xce,"end"]);break;case"position":f=p.split(","),d.percent(m,f[0]),f.length===2&&d.alt("positionAlign",f[1],["start",Xce,"end","line-left","line-right","auto"]);break;case"size":d.percent(m,p);break;case"align":d.alt(m,p,["start",Xce,"end","left","right"]);break}},/:/,/\s/),c.region=d.get("region",null),c.vertical=d.get("vertical","");let u=d.get("line","auto");u==="auto"&&WKe.line===-1&&(u=-1),c.line=u,c.lineAlign=d.get("lineAlign","start"),c.snapToLines=d.get("snapToLines",!0),c.size=d.get("size",100),c.align=d.get("align",Xce);let h=d.get("position","auto");h==="auto"&&WKe.position===50&&(h=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=h}function l(){s=s.replace(/^\s+/,"")}if(l(),t.startTime=a(),l(),s.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+r);s=s.slice(3),l(),t.endTime=a(),l(),i(s,t)}function trs(s){return s.replace(//gi,` `)}class zor{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Dor,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const n=this;t&&(n.buffer+=n.decoder.decode(t,{stream:!0}));function r(){let i=n.buffer,l=0;for(i=trs(i);l")===-1){n.cue.id=i;continue}case"CUE":if(!n.cue){n.state="BADCUE";continue}try{For(i,n.cue,n.regionList)}catch{n.cue=null,n.state="BADCUE";continue}n.state="CUETEXT";continue;case"CUETEXT":{const o=i.indexOf("-->")!==-1;if(!i||o&&(l=!0)){n.oncue&&n.cue&&n.oncue(n.cue),n.cue=null,n.state="ID";continue}if(n.cue===null)continue;n.cue.text&&(n.cue.text+=` `),n.cue.text+=i}continue;case"BADCUE":i||(n.state="ID")}}}catch{n.state==="CUETEXT"&&n.cue&&n.oncue&&n.oncue(n.cue),n.cue=null,n.state=n.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||t.state==="HEADER")&&(t.buffer+=` `,t.parse()),t.state==="INITIAL"||t.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(n){t.onparsingerror&&t.onparsingerror(n)}return t.onflush&&t.onflush(),this}}const Bor=/\r\n|\n\r|\n|\r/g,Hze=function(t,n,r=0){return t.slice(r,r+n.length)===n},Uor=function(t){let n=parseInt(t.slice(-3));const r=parseInt(t.slice(-6,-4)),a=parseInt(t.slice(-9,-7)),i=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!Bi(n)||!Bi(r)||!Bi(a)||!Bi(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return n+=1e3*r,n+=60*1e3*a,n+=60*60*1e3*i,n};function Jrt(s,t,n){return CJ(s.toString())+CJ(t.toString())+CJ(n)}const qor=function(t,n,r){let a=t[n],i=t[a.prevCC];if(!i||!i.new&&a.new){t.ccOffset=t.presentationOffset=a.start,a.new=!1;return}for(;(l=i)!=null&&l.new;){var l;t.ccOffset+=a.start-i.start,a.new=!1,a=i,i=t[a.prevCC]}t.presentationOffset=r};function $or(s,t,n,r,a,i,l){const o=new zor,c=uj(new Uint8Array(s)).trim().replace(Bor,` `).split(` `),d=[],u=t?Kar(t.baseTime,t.timescale):0;let h="00:00.000",m=0,p=0,f,x=!0;o.oncue=function(y){const v=n[r];let b=n.ccOffset;const N=(m-u)/9e4;if(v!=null&&v.new&&(p!==void 0?b=n.ccOffset=v.start:qor(n,r,N)),N){if(!t){f=new Error("Missing initPTS for VTT MPEGTS");return}b=N-n.presentationOffset}const S=y.endTime-y.startTime,A=Tw((y.startTime+b-p)*9e4,a*9e4)/9e4;y.startTime=Math.max(A,0),y.endTime=Math.max(A+S,0);const T=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(T)),y.id||(y.id=Jrt(y.startTime,y.endTime,T)),y.endTime>0&&d.push(y)},o.onparsingerror=function(y){f=y},o.onflush=function(){if(f){l(f);return}i(d)},c.forEach(y=>{if(x)if(Hze(y,"X-TIMESTAMP-MAP=")){x=!1,y.slice(16).split(",").forEach(v=>{Hze(v,"LOCAL:")?h=v.slice(6):Hze(v,"MPEGTS:")&&(m=parseInt(v.slice(7)))});try{p=Uor(h)/1e3}catch(v){f=v}return}else y===""&&(x=!1);o.parse(y+` `)}),o.flush()}const Gze="stpp.ttml.im1t",srs=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,nrs=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Vor={left:"start",center:"center",right:"end",start:"start",end:"end"};function k4t(s,t,n,r){const a=sd(new Uint8Array(s),["mdat"]);if(a.length===0){r(new Error("Could not parse IMSC1 mdat"));return}const i=a.map(o=>uj(o)),l=War(t.baseTime,1,t.timescale);try{i.forEach(o=>n(Hor(o,l)))}catch(o){r(o)}}function Hor(s,t){const a=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!a)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},l=Object.keys(i).reduce((h,m)=>(h[m]=a.getAttribute(`ttp:${m}`)||i[m],h),{}),o=a.getAttribute("xml:space")!=="preserve",c=S4t(Wze(a,"styling","style")),d=S4t(Wze(a,"layout","region")),u=Wze(a,"body","[begin]");return[].map.call(u,h=>{const m=rrs(h,o);if(!m||!h.hasAttribute("begin"))return null;const p=Yze(h.getAttribute("begin"),l),f=Yze(h.getAttribute("dur"),l);let x=Yze(h.getAttribute("end"),l);if(p===null)throw C4t(h);if(x===null){if(f===null)throw C4t(h);x=p+f}const y=new Qrt(p-t,x-t,m);y.id=Jrt(y.startTime,y.endTime,y.text);const v=d[h.getAttribute("region")],b=c[h.getAttribute("style")],N=Gor(v,b,c),{textAlign:S}=N;if(S){const A=Vor[S];A&&(y.lineAlign=A),y.align=S}return Yh(y,N),y}).filter(h=>h!==null)}function Wze(s,t,n){const r=s.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(n)):[]}function S4t(s){return s.reduce((t,n)=>{const r=n.getAttribute("xml:id");return r&&(t[r]=n),t},{})}function rrs(s,t){return[].slice.call(s.childNodes).reduce((n,r,a)=>{var i;return r.nodeName==="br"&&a?n+` `:(i=r.childNodes)!=null&&i.length?rrs(r,t):t?n+r.textContent.trim().replace(/\s+/g," "):n+r.textContent},"")}function Gor(s,t,n){const r="http://www.w3.org/ns/ttml#styling";let a=null;const i=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],l=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return l&&n.hasOwnProperty(l)&&(a=n[l]),i.reduce((o,c)=>{const d=Kze(t,r,c)||Kze(s,r,c)||Kze(a,r,c);return d&&(o[c]=d),o},{})}function Kze(s,t,n){return s&&s.hasAttributeNS(t,n)?s.getAttributeNS(t,n):null}function C4t(s){return new Error(`Could not parse ttml timestamp ${s}`)}function Yze(s,t){if(!s)return null;let n=Jns(s);return n===null&&(srs.test(s)?n=Wor(s,t):nrs.test(s)&&(n=Kor(s,t))),n}function Wor(s,t){const n=srs.exec(s),r=(n[4]|0)+(n[5]|0)/t.subFrameRate;return(n[1]|0)*3600+(n[2]|0)*60+(n[3]|0)+r/t.frameRate}function Kor(s,t){const n=nrs.exec(s),r=Number(n[1]);switch(n[2]){case"h":return r*3600;case"m":return r*60;case"ms":return r*1e3;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}class Qce{constructor(t,n){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=n}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,n,r){(this.startTime===null||this.startTime>t)&&(this.startTime=t),this.endTime=n,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class Yor{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=E4t(),this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(Ot.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Ot.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ot.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Ot.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(Ot.FRAG_LOADING,this.onFragLoading,this),t.on(Ot.FRAG_LOADED,this.onFragLoaded,this),t.on(Ot.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(Ot.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(Ot.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(Ot.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(Ot.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(Ot.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Ot.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ot.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Ot.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(Ot.FRAG_LOADING,this.onFragLoading,this),t.off(Ot.FRAG_LOADED,this.onFragLoaded,this),t.off(Ot.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(Ot.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(Ot.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(Ot.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(Ot.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new Qce(this,"textTrack1"),n=new Qce(this,"textTrack2"),r=new Qce(this,"textTrack3"),a=new Qce(this,"textTrack4");this.cea608Parser1=new N4t(1,t,n),this.cea608Parser2=new N4t(3,r,a)}addCues(t,n,r,a,i){let l=!1;for(let o=i.length;o--;){const c=i[o],d=Zor(c[0],c[1],n,r);if(d>=0&&(c[0]=Math.min(c[0],n),c[1]=Math.max(c[1],r),l=!0,d/(r-n)>.5))return}if(l||i.push([n,r]),this.config.renderTextTracksNatively){const o=this.captionsTracks[t];this.Cues.newCue(o,n,r,a)}else{const o=this.Cues.newCue(null,n,r,a);this.hls.trigger(Ot.CUES_PARSED,{type:"captions",cues:o,track:t})}}onInitPtsFound(t,{frag:n,id:r,initPTS:a,timescale:i,trackId:l}){const{unparsedVttFrags:o}=this;r===io.MAIN&&(this.initPTS[n.cc]={baseTime:a,timescale:i,trackId:l}),o.length&&(this.unparsedVttFrags=[],o.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(Ot.FRAG_LOADED,c):this.hls.trigger(Ot.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:c.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(t,n){const{media:r}=this;if(r)for(let a=0;a{DU(a[i]),delete a[i]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=E4t(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:t}=this;if(!t)return;const n=t.textTracks;if(n)for(let r=0;ri.textCodec===Gze);if(this.config.enableWebVTT||a&&this.config.enableIMSC1){if(Rns(this.tracks,r)){this.tracks=r;return}if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){const l=this.media,o=l?o3e(l.textTracks):null;if(this.tracks.forEach((c,d)=>{let u;if(o){let h=null;for(let m=0;md!==null).map(d=>d.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const l=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(Ot.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:l})}}}onManifestLoaded(t,n){this.config.enableCEA708Captions&&n.captions&&n.captions.forEach(r=>{const a=/(?:CC|SERVICE)([1-4])/.exec(r.instreamId);if(!a)return;const i=`textTrack${a[1]}`,l=this.captionsProperties[i];l&&(l.label=r.name,r.lang&&(l.languageCode=r.lang),l.media=r)})}closedCaptionsForLevel(t){const n=this.hls.levels[t.level];return n==null?void 0:n.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,n){if(this.enabled&&n.frag.type===io.MAIN){var r,a;const{cea608Parser1:i,cea608Parser2:l,lastSn:o}=this,{cc:c,sn:d}=n.frag,u=(r=(a=n.part)==null?void 0:a.index)!=null?r:-1;i&&l&&(d!==o+1||d===o&&u!==this.lastPartIndex+1||c!==this.lastCc)&&(i.reset(),l.reset()),this.lastCc=c,this.lastSn=d,this.lastPartIndex=u}}onFragLoaded(t,n){const{frag:r,payload:a}=n;if(r.type===io.SUBTITLE)if(a.byteLength){const i=r.decryptdata,l="stats"in n;if(i==null||!i.encrypted||l){const o=this.tracks[r.level],c=this.vttCCs;c[r.cc]||(c[r.cc]={start:r.start,prevCC:this.prevCC,new:!0},this.prevCC=r.cc),o&&o.textCodec===Gze?this._parseIMSC1(r,a):this._parseVTTs(n)}}else this.hls.trigger(Ot.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,n){const r=this.hls;k4t(n,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),r.trigger(Ot.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},a=>{r.logger.log(`Failed to parse IMSC1: ${a}`),r.trigger(Ot.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:a})})}_parseVTTs(t){var n;const{frag:r,payload:a}=t,{initPTS:i,unparsedVttFrags:l}=this,o=i.length-1;if(!i[r.cc]&&o===-1){l.push(t);return}const c=this.hls,d=(n=r.initSegment)!=null&&n.data?_N(r.initSegment.data,new Uint8Array(a)).buffer:a;$or(d,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,u=>{this._appendCues(u,r.level),c.trigger(Ot.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})},u=>{const h=u.message==="Missing initPTS for VTT MPEGTS";h?l.push(t):this._fallbackToIMSC1(r,a),c.logger.log(`Failed to parse VTT cue: ${u}`),!(h&&o>r.cc)&&c.trigger(Ot.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:u})})}_fallbackToIMSC1(t,n){const r=this.tracks[t.level];r.textCodec||k4t(n,this.initPTS[t.cc],()=>{r.textCodec=Gze,this._parseIMSC1(t,n)},()=>{r.textCodec="wvtt"})}_appendCues(t,n){const r=this.hls;if(this.config.renderTextTracksNatively){const a=this.textTracks[n];if(!a||a.mode==="disabled")return;t.forEach(i=>Yns(a,i))}else{const a=this.tracks[n];if(!a)return;const i=a.default?"default":"subtitles"+n;r.trigger(Ot.CUES_PARSED,{type:"subtitles",cues:t,track:i})}}onFragDecrypted(t,n){const{frag:r}=n;r.type===io.SUBTITLE&&this.onFragLoaded(Ot.FRAG_LOADED,n)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,n){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:r,samples:a}=n;if(!(r.type===io.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let i=0;iGKe(o[c],n,r))}if(this.config.renderTextTracksNatively&&n===0&&a!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>GKe(o[c],n,a))}}}extractCea608Data(t){const n=[[],[]],r=t[0]&31;let a=2;for(let i=0;i=16?c--:c++;const p=trs(d.trim()),f=Jrt(t,n,p);s!=null&&(h=s.cues)!=null&&h.getCueById(f)||(l=new u(t,n,p),l.id=f,l.line=m+1,l.align="left",l.position=10+Math.min(80,Math.floor(c*8/32)*10),a.push(l))}return s&&a.length&&(a.sort((m,p)=>m.line==="auto"||p.line==="auto"?0:m.line>8&&p.line>8?p.line-m.line:m.line-p.line),a.forEach(m=>Yns(s,m))),a}};function Jor(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const elr=/(\d+)-(\d+)\/(\d+)/;class T4t{constructor(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||rlr,this.controller=new self.AbortController,this.stats=new Mrt}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var t;this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,n,r){const a=this.stats;if(a.loading.start)throw new Error("Loader can only be used once.");a.loading.start=self.performance.now();const i=tlr(t,this.controller.signal),l=t.responseType==="arraybuffer",o=l?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:d}=n.loadPolicy;this.context=t,this.config=n,this.callbacks=r,this.request=this.fetchSetup(t,i),self.clearTimeout(this.requestTimeout),n.timeout=c&&Bi(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,t,this.response))},n.timeout),(Zte(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(h=>{var m;this.response=this.loader=h;const p=Math.max(self.performance.now(),a.loading.start);if(self.clearTimeout(this.requestTimeout),n.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,t,this.response))},d-(p-a.loading.start)),!h.ok){const{status:x,statusText:y}=h;throw new alr(y||"fetch, bad network response",x,h)}a.loading.first=p,a.total=nlr(h.headers)||a.total;const f=(m=this.callbacks)==null?void 0:m.onProgress;return f&&Bi(n.highWaterMark)?this.loadProgressively(h,a,t,n.highWaterMark,f):l?h.arrayBuffer():t.responseType==="json"?h.json():h.text()}).then(h=>{var m,p;const f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),a.loading.end=Math.max(self.performance.now(),a.loading.first);const x=h[o];x&&(a.loaded=a.total=x);const y={url:f.url,data:h,code:f.status},v=(m=this.callbacks)==null?void 0:m.onProgress;v&&!Bi(n.highWaterMark)&&v(a,t,h,f),(p=this.callbacks)==null||p.onSuccess(y,a,t,f)}).catch(h=>{var m;if(self.clearTimeout(this.requestTimeout),a.aborted)return;const p=h&&h.code||0,f=h?h.message:null;(m=this.callbacks)==null||m.onError({code:p,text:f},t,h?h.details:null,a)})}getCacheAge(){let t=null;if(this.response){const n=this.response.headers.get("age");t=n?parseFloat(n):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,n,r,a=0,i){const l=new fns,o=t.body.getReader(),c=()=>o.read().then(d=>{if(d.done)return l.dataLength&&i(n,r,l.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const u=d.value,h=u.length;return n.loaded+=h,h=a&&i(n,r,l.flush().buffer,t)):i(n,r,u.buffer,t),c()}).catch(()=>Promise.reject());return c()}}function tlr(s,t){const n={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Yh({},s.headers))};return s.rangeEnd&&n.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),n}function slr(s){const t=elr.exec(s);if(t)return parseInt(t[2])-parseInt(t[1])+1}function nlr(s){const t=s.get("Content-Range");if(t){const r=slr(t);if(Bi(r))return r}const n=s.get("Content-Length");if(n)return parseInt(n)}function rlr(s,t){return new self.Request(s.url,t)}class alr extends Error{constructor(t,n,r){super(t),this.code=void 0,this.details=void 0,this.code=n,this.details=r}}const ilr=/^age:\s*[\d.]+\s*$/im;class irs{constructor(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new Mrt,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,t.readyState!==4&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,n,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=n,this.callbacks=r,this.loadInternal()}loadInternal(){const{config:t,context:n}=this;if(!t||!n)return;const r=this.loader=new self.XMLHttpRequest,a=this.stats;a.loading.first=0,a.loaded=0,a.aborted=!1;const i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!(this.loader!==r||this.stats.aborted))return i(r,n.url)}).catch(l=>{if(!(this.loader!==r||this.stats.aborted))return r.open("GET",n.url,!0),i(r,n.url)}).then(()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,n,t)}).catch(l=>{var o;(o=this.callbacks)==null||o.onError({code:r.status,text:l.message},n,r,a)}):this.openAndSendXhr(r,n,t)}openAndSendXhr(t,n,r){t.readyState||t.open("GET",n.url,!0);const a=n.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:l}=r.loadPolicy;if(a)for(const o in a)t.setRequestHeader(o,a[o]);n.rangeEnd&&t.setRequestHeader("Range","bytes="+n.rangeStart+"-"+(n.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=n.responseType,self.clearTimeout(this.requestTimeout),r.timeout=i&&Bi(i)?i:l,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),t.send()}readystatechange(){const{context:t,loader:n,stats:r}=this;if(!t||!n)return;const a=n.readyState,i=this.config;if(!r.aborted&&a>=2&&(r.loading.first===0&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),a===4)){self.clearTimeout(this.requestTimeout),n.onreadystatechange=null,n.onprogress=null;const d=n.status,u=n.responseType==="text"?n.responseText:null;if(d>=200&&d<300){const f=u??n.response;if(f!=null){var l,o;r.loading.end=Math.max(self.performance.now(),r.loading.first);const x=n.responseType==="arraybuffer"?f.byteLength:f.length;r.loaded=r.total=x,r.bwEstimate=r.total*8e3/(r.loading.end-r.loading.first);const y=(l=this.callbacks)==null?void 0:l.onProgress;y&&y(r,t,f,n);const v={url:n.responseURL,data:f,code:d};(o=this.callbacks)==null||o.onSuccess(v,r,t,n);return}}const h=i.loadPolicy.errorRetry,m=r.retry,p={url:t.url,data:void 0,code:d};if(ATe(h,m,!1,p))this.retry(h);else{var c;Ah.error(`${d} while loading ${t.url}`),(c=this.callbacks)==null||c.onError({code:d,text:n.statusText},t,n,r)}}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry,n=this.stats.retry;if(ATe(t,n,!0))this.retry(t);else{var r;Ah.warn(`timeout while loading ${(r=this.context)==null?void 0:r.url}`);const a=this.callbacks;a&&(this.abortInternal(),a.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:n,stats:r}=this;this.retryDelay=Rrt(t,r.retry),r.retry++,Ah.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${n==null?void 0:n.url}, retrying ${r.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(t){const n=this.stats;n.loaded=t.loaded,t.lengthComputable&&(n.total=t.total)}getCacheAge(){let t=null;if(this.loader&&ilr.test(this.loader.getAllResponseHeaders())){const n=this.loader.getResponseHeader("age");t=n?parseFloat(n):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const olr={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},llr=_h(_h({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:irs,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:yrr,bufferController:cir,capLevelController:Yrt,errorController:jrr,fpsController:dor,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:rns,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:olr},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},clr()),{},{subtitleStreamController:jor,subtitleTrackController:mor,timelineController:Yor,audioStreamController:air,audioTrackController:iir,emeController:d$,cmcdController:ior,contentSteeringController:lor,interstitialsController:wor});function clr(){return{cueHandler:Qor,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function dlr(s,t,n){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const r=KKe(s),a=["manifest","level","frag"],i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return a.forEach(l=>{const o=`${l==="level"?"playlist":l}LoadPolicy`,c=t[o]===void 0,d=[];i.forEach(u=>{const h=`${l}Loading${u}`,m=t[h];if(m!==void 0&&c){d.push(h);const p=r[o].default;switch(t[o]={default:p},u){case"TimeOut":p.maxLoadTimeMs=m,p.maxTimeToFirstByteMs=m;break;case"MaxRetry":p.errorRetry.maxNumRetry=m,p.timeoutRetry.maxNumRetry=m;break;case"RetryDelay":p.errorRetry.retryDelayMs=m,p.timeoutRetry.retryDelayMs=m;break;case"MaxRetryTimeout":p.errorRetry.maxRetryDelayMs=m,p.timeoutRetry.maxRetryDelayMs=m;break}}}),d.length&&n.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${fm(t[o])}`)}),_h(_h({},r),t)}function KKe(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(KKe):Object.keys(s).reduce((t,n)=>(t[n]=KKe(s[n]),t),{}):s}function ulr(s,t){const n=s.loader;n!==T4t&&n!==irs?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):Jor()&&(s.loader=T4t,s.progressive=!0,s.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}const l3e=2,hlr=.1,mlr=.05,plr=100;class flr extends Jss{constructor(t,n){super("gap-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var r;(r=this.media)!=null&&r.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var r;this.ended=((r=this.media)==null?void 0:r.currentTime)||1,this.hls.trigger(Ot.MEDIA_ENDED,{stalled:!1})}},this.hls=t,this.fragmentTracker=n,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(Ot.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Ot.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Ot.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(Ot.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Ot.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Ot.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,n){this.setInterval(plr),this.mediaSource=n.mediaSource;const r=this.media=n.media;ob(r,"playing",this.onMediaPlaying),ob(r,"waiting",this.onMediaWaiting),ob(r,"ended",this.onMediaEnded)}onMediaDetaching(t,n){this.clearInterval();const{media:r}=this;r&&(w_(r,"playing",this.onMediaPlaying),w_(r,"waiting",this.onMediaWaiting),w_(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,n){this.buffered=n.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var t;if(!((t=this.media)!=null&&t.readyState)||!this.hasBuffered)return;const n=this.media.currentTime;this.poll(n,this.lastCurrentTime),this.lastCurrentTime=n}poll(t,n){var r,a;const i=(r=this.hls)==null?void 0:r.config;if(!i)return;const l=this.media;if(!l)return;const{seeking:o}=l,c=this.seeking&&!o,d=!this.seeking&&o,u=l.paused&&!o||l.ended||l.playbackRate===0;if(this.seeking=o,t!==n){n&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,i.nudgeOnVideoHole&&!u&&t>n&&this.nudgeOnVideoHole(t,n)),this.waiting===0&&this.stallResolved(t);return}if(d||c){c&&this.stallResolved(t);return}if(u){this.nudgeRetry=0,this.stallResolved(t),!this.ended&&l.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(Ot.MEDIA_ENDED,{stalled:!1}));return}if(!uc.getBuffered(l).length){this.nudgeRetry=0;return}const h=uc.bufferInfo(l,t,0),m=h.nextStart||0,p=this.fragmentTracker;if(o&&p&&this.hls){const T=M4t(this.hls.inFlightFragments,t),L=h.len>l3e,M=!m||T||m-t>l3e&&!p.getPartialFragment(t);if(L||M)return;this.moved=!1}const f=(a=this.hls)==null?void 0:a.latestLevelDetails;if(!this.moved&&this.stalled!==null&&p){if(!(h.len>0)&&!m)return;const L=Math.max(m,h.start||0)-t,I=!!(f!=null&&f.live)?f.targetduration*2:l3e,R=Jce(t,p);if(L>0&&(L<=I||R)){l.paused||this._trySkipBufferHole(R);return}}const x=i.detectStallWithCurrentTimeMs,y=self.performance.now(),v=this.waiting;let b=this.stalled;if(b===null)if(v>0&&y-v=x||v)&&this.hls){var S;if(((S=this.mediaSource)==null?void 0:S.readyState)==="ended"&&!(f!=null&&f.live)&&Math.abs(t-((f==null?void 0:f.edge)||0))<1){if(this.ended)return;this.ended=t||1,this.hls.trigger(Ot.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return}const A=uc.bufferInfo(l,t,i.maxBufferHole);this._tryFixBufferStall(A,N,t)}stallResolved(t){const n=this.stalled;if(n&&this.hls&&(this.stalled=null,this.stallReported)){const r=self.performance.now()-n;this.log(`playback not stuck anymore @${t}, after ${Math.round(r)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(Ot.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,n){var r;const a=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(r=this.buffered.audio)!=null&&r.length&&a&&a.length>1&&t>a.end(0)){const i=uc.bufferedInfo(uc.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&n>=i.start){const l=uc.timeRangesToArray(a),o=uc.bufferedInfo(l,n,0).bufferedIndex;if(o>-1&&oo)&&u-d<1&&t-d<2){const h=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${d} -> ${u} buffered index: ${c}`);this.warn(h.message),this.media.currentTime+=1e-6;let m=Jce(t,this.fragmentTracker);m&&"fragment"in m?m=m.fragment:m||(m=void 0);const p=uc.bufferInfo(this.media,t,0);this.hls.trigger(Ot.ERROR,{type:wo.MEDIA_ERROR,details:yr.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:m,buffer:p.len,bufferInfo:p})}}}}}_tryFixBufferStall(t,n,r){var a,i;const{fragmentTracker:l,media:o}=this,c=(a=this.hls)==null?void 0:a.config;if(!o||!l||!c)return;const d=(i=this.hls)==null?void 0:i.latestLevelDetails,u=Jce(r,l);if((u||d!=null&&d.live&&r1&&t.len>c.maxBufferHole||t.nextStart&&(t.nextStart-rc.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,n){const r=this.fragmentTracker,a=t.nextStart;if(r&&a){const i=r.getFragAtPos(n,io.MAIN),l=r.getFragAtPos(a,io.MAIN);if(i&&l)return l.sn-i.sn<2}return!1}_reportStall(t){const{hls:n,media:r,stallReported:a,stalled:i}=this;if(!a&&i!==null&&r&&n){this.stallReported=!0;const l=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${fm(t)})`);this.warn(l.message),n.trigger(Ot.ERROR,{type:wo.MEDIA_ERROR,details:yr.BUFFER_STALLED_ERROR,fatal:!1,error:l,buffer:t.len,bufferInfo:t,stalled:{start:i}})}}_trySkipBufferHole(t){var n;const{fragmentTracker:r,media:a}=this,i=(n=this.hls)==null?void 0:n.config;if(!a||!r||!i)return 0;const l=a.currentTime,o=uc.bufferInfo(a,l,0),c=l0&&o.len<1&&a.readyState<3,m=c-l;if(m>0&&(u||h)){if(m>i.maxBufferHole){let f=!1;if(l===0){const x=r.getAppendedFrag(0,io.MAIN);x&&c"u"))return self.VTTCue||self.TextTrackCue}function Zze(s,t,n,r,a){let i=new s(t,n,"");try{i.value=r,a&&(i.type=a)}catch{i=new s(t,n,fm(a?_h({type:a},r):r))}return i}const ede=(()=>{const s=YKe();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class xlr{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(Ot.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t&&(t.on(Ot.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Ot.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Ot.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ot.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(Ot.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Ot.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Ot.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(Ot.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Ot.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Ot.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ot.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(Ot.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Ot.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Ot.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,n){var r;this.media=n.media,((r=n.overrides)==null?void 0:r.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var t;const n=(t=this.hls)==null?void 0:t.latestLevelDetails;n&&this.updateDateRangeCues(n)}onMediaDetaching(t,n){this.media=null,!n.transferMedia&&(this.id3Track&&(this.removeCues&&DU(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const n=this.getID3Track(t.textTracks);return n.mode="hidden",n}getID3Track(t){if(this.media){for(let n=0;nede&&(h=ede),h-u<=0&&(h=u+glr);for(let p=0;pu.type===Dw.audioId3&&c:a==="video"?d=u=>u.type===Dw.emsg&&o:d=u=>u.type===Dw.audioId3&&c||u.type===Dw.emsg&&o,GKe(i,n,r,d)}}onLevelUpdated(t,{details:n}){this.updateDateRangeCues(n,!0)}onLevelPtsUpdated(t,n){Math.abs(n.drift)>.01&&this.updateDateRangeCues(n.details)}updateDateRangeCues(t,n){if(!this.hls||!this.media)return;const{assetPlayerId:r,timelineOffset:a,enableDateRangeMetadataCues:i,interstitialsController:l}=this.hls.config;if(!i)return;const o=YKe();if(r&&a&&!l){const{fragmentStart:x,fragmentEnd:y}=t;let v=this.assetCue;v?(v.startTime=x,v.endTime=y):o&&(v=this.assetCue=Zze(o,x,y,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=r,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:d}=t,u=Object.keys(d);let h=this.dateRangeCuesAppended;if(c&&n){var m;if((m=c.cues)!=null&&m.length){const x=Object.keys(h).filter(y=>!u.includes(y));for(let y=x.length;y--;){var p;const v=x[y],b=(p=h[v])==null?void 0:p.cues;delete h[v],b&&Object.keys(b).forEach(N=>{const S=b[N];if(S){S.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(S)}catch{}}})}}else h=this.dateRangeCuesAppended={}}const f=t.fragments[t.fragments.length-1];if(!(u.length===0||!Bi(f==null?void 0:f.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let x=0;x{if($!==v.id){const H=d[$];if(H.class===v.class&&H.startDate>v.startDate&&(!z||v.startDate.01&&($.startTime=b,$.endTime=T);else if(o){let H=v.attr[z];Orr(z)&&(H=Lss(H));const K=Zze(o,b,T,{key:z,data:H},Dw.dateRange);K&&(K.id=y,this.id3Track.addCue(K),S[z]=K,l&&(z==="X-ASSET-LIST"||z==="X-ASSET-URL")&&K.addEventListener("enter",this.onEventCueEnter))}}h[y]={cues:S,dateRange:v,durationKnown:A}}}}}class ylr{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:n}=this,r=this.levelDetails;if(!n||!r)return;this.currentTime=n.currentTime;const a=this.computeLatency();if(a===null)return;this._latency=a;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:l}=this.config;if(!i||l===1||!r.live)return;const o=this.targetLatency;if(o===null)return;const c=a-o,d=Math.min(this.maxLatency,o+r.targetduration);if(c.05&&this.forwardBufferLength>1){const h=Math.min(2,Math.max(1,l)),m=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,p=Math.min(h,Math.max(1,m));this.changeMediaPlaybackRate(n,p)}else n.playbackRate!==1&&n.playbackRate!==0&&this.changeMediaPlaybackRate(n,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return((t=this.hls)==null?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(t.liveMaxLatencyDuration!==void 0)return t.liveMaxLatencyDuration;const n=this.levelDetails;return n?t.liveMaxLatencyDurationCount*n.targetduration:0}get targetLatency(){const t=this.levelDetails;if(t===null||this.hls===null)return null;const{holdBack:n,partHoldBack:r,targetduration:a}=t,{liveSyncDuration:i,liveSyncDurationCount:l,lowLatencyMode:o}=this.config,c=this.hls.userConfig;let d=o&&r||n;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||d===0)&&(d=i!==void 0?i:l*a);const u=a;return d+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)}set targetLatency(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),n=this.targetLatency;if(t===null||n===null)return null;const r=this.levelDetails;if(r===null)return null;const a=r.edge,i=t-n-this.edgeStalled,l=a-r.totalduration,o=a-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(l,i),o)}get drift(){const t=this.levelDetails;return t===null?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(t===null)return 0;const n=(this.config.lowLatencyMode&&t.partTarget||t.targetduration)*3;return Math.max(t.age-n,0)}get forwardBufferLength(){const{media:t}=this,n=this.levelDetails;if(!t||!n)return 0;const r=t.buffered.length;return(r?t.buffered.end(r-1):n.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(Ot.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Ot.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ot.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Ot.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(Ot.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Ot.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ot.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Ot.ERROR,this.onError,this))}onMediaAttached(t,n){this.media=n.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:n}){n.advanced&&this.onTimeupdate(),!n.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(t,n){var r;n.details===yr.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(r=this.levelDetails)!=null&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,n){var r,a;t.playbackRate!==n&&((r=this.hls)==null||r.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(a=this.targetLatency)==null?void 0:a.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${n}`),t.playbackRate=n)}estimateLiveEdge(){const t=this.levelDetails;return t===null?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return t===null?null:t-this.currentTime}}class vlr extends Krt{constructor(t,n){super(t,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=n,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ot.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Ot.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Ot.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Ot.FRAG_BUFFERED,this.onFragBuffered,this),t.on(Ot.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ot.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Ot.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Ot.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Ot.FRAG_BUFFERED,this.onFragBuffered,this),t.off(Ot.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(n=>{n.loadError=0,n.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,n){this.resetLevels()}onManifestLoaded(t,n){const r=this.hls.config.preferManagedMediaSource,a=[],i={},l={};let o=!1,c=!1,d=!1;n.levels.forEach(u=>{const h=u.attrs;let{audioCodec:m,videoCodec:p}=u;m&&(u.audioCodec=m=NTe(m,r)||void 0),p&&(p=u.videoCodec=Jnr(p));const{width:f,height:x,unknownCodecs:y}=u,v=(y==null?void 0:y.length)||0;if(o||(o=!!(f&&x)),c||(c=!!p),d||(d=!!m),v||m&&!this.isAudioSupported(m)||p&&!this.isVideoSupported(p)){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}const{CODECS:b,"FRAME-RATE":N,"HDCP-LEVEL":S,"PATHWAY-ID":A,RESOLUTION:T,"VIDEO-RANGE":L}=h,I=`${`${A||"."}-`}${u.bitrate}-${T}-${N}-${b}-${L}-${S}`;if(i[I])if(i[I].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const R=l[I]+=1;u.attrs["PATHWAY-ID"]=new Array(R+1).join(".");const z=this.createLevel(u);i[I]=z,a.push(z)}else i[I].addGroupId("audio",h.AUDIO),i[I].addGroupId("text",h.SUBTITLES);else{const R=this.createLevel(u);i[I]=R,l[I]=1,a.push(R)}}),this.filterAndSortMediaOptions(a,n,o,c,d)}createLevel(t){const n=new Wte(t),r=t.supplemental;if(r!=null&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){const a=new Error(`SUPPLEMENTAL-CODECS not supported "${r.videoCodec}"`);this.log(a.message),n.supportedResult=Hss(a,[])}return n}isAudioSupported(t){return Hte(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return Hte(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,n,r,a,i){var l;let o=[],c=[],d=t;const u=((l=n.stats)==null?void 0:l.parsing)||{};if((r||a)&&i&&(d=d.filter(({videoCodec:b,videoRange:N,width:S,height:A})=>(!!b||!!(S&&A))&&crr(N))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let b="no level with compatible codecs found in manifest",N=b;n.levels.length&&(N=`one or more CODECS in variant not supported: ${fm(n.levels.map(A=>A.attrs.CODECS).filter((A,T,L)=>L.indexOf(A)===T))}`,this.warn(N),b+=` (${N})`);const S=new Error(b);this.hls.trigger(Ot.ERROR,{type:wo.MEDIA_ERROR,details:yr.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:n.url,error:S,reason:N})}}),u.end=performance.now();return}n.audioTracks&&(o=n.audioTracks.filter(b=>!b.audioCodec||this.isAudioSupported(b.audioCodec)),L4t(o)),n.subtitles&&(c=n.subtitles,L4t(c));const h=d.slice(0);d.sort((b,N)=>{if(b.attrs["HDCP-LEVEL"]!==N.attrs["HDCP-LEVEL"])return(b.attrs["HDCP-LEVEL"]||"")>(N.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&b.height!==N.height)return b.height-N.height;if(b.frameRate!==N.frameRate)return b.frameRate-N.frameRate;if(b.videoRange!==N.videoRange)return kTe.indexOf(b.videoRange)-kTe.indexOf(N.videoRange);if(b.videoCodec!==N.videoCodec){const S=N5t(b.videoCodec),A=N5t(N.videoCodec);if(S!==A)return A-S}if(b.uri===N.uri&&b.codecSet!==N.codecSet){const S=jTe(b.codecSet),A=jTe(N.codecSet);if(S!==A)return A-S}return b.averageBitrate!==N.averageBitrate?b.averageBitrate-N.averageBitrate:0});let m=h[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==h.length)){for(let b=0;bS&&S===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=A)}break}const f=i&&!a,x=this.hls.config,y=!!(x.audioStreamController&&x.audioTrackController),v={levels:d,audioTracks:o,subtitleTracks:c,sessionData:n.sessionData,sessionKeys:n.sessionKeys,firstLevel:this._firstLevel,stats:n.stats,audio:i,video:a,altAudio:y&&!f&&o.some(b=>!!b.url)};u.end=performance.now(),this.hls.trigger(Ot.MANIFEST_PARSED,v)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const n=this._levels;if(n.length===0)return;if(t<0||t>=n.length){const u=new Error("invalid level idx"),h=t<0;if(this.hls.trigger(Ot.ERROR,{type:wo.OTHER_ERROR,details:yr.LEVEL_SWITCH_ERROR,level:t,fatal:h,error:u,reason:u.message}),h)return;t=Math.min(t,n.length-1)}const r=this.currentLevelIndex,a=this.currentLevel,i=a?a.attrs["PATHWAY-ID"]:void 0,l=n[t],o=l.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=l,r===t&&a&&i===o)return;this.log(`Switching to level ${t} (${l.height?l.height+"p ":""}${l.videoRange?l.videoRange+" ":""}${l.codecSet?l.codecSet+" ":""}@${l.bitrate})${o?" with Pathway "+o:""} from level ${r}${i?" with Pathway "+i:""}`);const c={level:t,attrs:l.attrs,details:l.details,bitrate:l.bitrate,averageBitrate:l.averageBitrate,maxBitrate:l.maxBitrate,realBitrate:l.realBitrate,width:l.width,height:l.height,codecSet:l.codecSet,audioCodec:l.audioCodec,videoCodec:l.videoCodec,audioGroups:l.audioGroups,subtitleGroups:l.subtitleGroups,loaded:l.loaded,loadError:l.loadError,fragmentError:l.fragmentError,name:l.name,id:l.id,uri:l.uri,url:l.url,urlId:0,audioGroupIds:l.audioGroupIds,textGroupIds:l.textGroupIds};this.hls.trigger(Ot.LEVEL_SWITCHING,c);const d=l.details;if(!d||d.live){const u=this.switchParams(l.uri,a==null?void 0:a.details,d);this.loadPlaylist(u)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,this._startLevel===void 0&&(this._startLevel=t),t!==-1&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(this._startLevel===void 0){const t=this.hls.config.startLevel;return t!==void 0?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const n=this.steering.pathways(),r=t.filter(a=>n.indexOf(a)!==-1);if(t.length<1){this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${n}`);return}this.steering.pathwayPriority=r}}onError(t,n){n.fatal||!n.context||n.context.type===hd.LEVEL&&n.context.level===this.level&&this.checkRetry(n)}onFragBuffered(t,{frag:n}){if(n!==void 0&&n.type===io.MAIN){const r=n.elementaryStreams;if(!Object.keys(r).some(i=>!!r[i]))return;const a=this._levels[n.level];a!=null&&a.loadError&&(this.log(`Resetting level error count of ${a.loadError} on frag buffered`),a.loadError=0)}}onLevelLoaded(t,n){var r;const{level:a,details:i}=n,l=n.levelInfo;if(!l){var o;this.warn(`Invalid level index ${a}`),(o=n.deliveryDirectives)!=null&&o.skip&&(i.deltaUpdateFailed=!0);return}if(l===this.currentLevel||n.withoutMultiVariant){l.fragmentError===0&&(l.loadError=0);let c=l.details;c===n.details&&c.advanced&&(c=void 0),this.playlistLoaded(a,n,c)}else(r=n.deliveryDirectives)!=null&&r.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,n){super.loadingPlaylist(t,n);const r=this.getUrlWithDirectives(t.uri,n),a=this.currentLevelIndex,i=t.attrs["PATHWAY-ID"],l=t.details,o=l==null?void 0:l.age;this.log(`Loading level index ${a}${(n==null?void 0:n.msn)!==void 0?" at sn "+n.msn+" part "+n.part:""}${i?" Pathway "+i:""}${o&&l.live?" age "+o.toFixed(1)+(l.type&&" "+l.type||""):""} ${r}`),this.hls.trigger(Ot.LEVEL_LOADING,{url:r,level:a,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:n||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=t)}removeLevel(t){var n;if(this._levels.length===1)return;const r=this._levels.filter((i,l)=>l!==t?!0:(this.steering&&this.steering.removeLevel(i),i===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,i.details&&i.details.fragments.forEach(o=>o.level=-1)),!1));hns(r),this._levels=r,this.currentLevelIndex>-1&&(n=this.currentLevel)!=null&&n.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const a=r.length-1;this._firstLevel=Math.min(this._firstLevel,a),this._startLevel&&(this._startLevel=Math.min(this._startLevel,a)),this.hls.trigger(Ot.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(t,{levels:n}){this._levels=n}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:n,maxHdcpLevel:r}=this.hls;this._maxAutoLevel!==n&&(this._maxAutoLevel=n,this.hls.trigger(Ot.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:n,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function L4t(s){const t={};s.forEach(n=>{const r=n.groupId||"";n.id=t[r]=t[r]||0,t[r]++})}function ors(){return self.SourceBuffer||self.WebKitSourceBuffer}function lrs(){if(!SP())return!1;const t=ors();return!t||t.prototype&&typeof t.prototype.appendBuffer=="function"&&typeof t.prototype.remove=="function"}function blr(){if(!lrs())return!1;const s=SP();return typeof(s==null?void 0:s.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>s.isTypeSupported(Gte(t,"video")))||["mp4a.40.2","fLaC"].some(t=>s.isTypeSupported(Gte(t,"audio"))))}function _lr(){var s;const t=ors();return typeof(t==null||(s=t.prototype)==null?void 0:s.changeType)=="function"}const wlr=100;class jlr extends Brt{constructor(t,n,r){super(t,n,r,"stream-controller",io.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const a=this.media,i=a?a.currentTime:null;if(i===null||!Bi(i)||(this.log(`Media seeked to ${i.toFixed(3)}`),!this.getBufferedFrag(i)))return;const l=this.getFwdBufferInfoAtPos(a,i,io.MAIN,0);if(l===null||l.len===0){this.warn(`Main forward buffer length at ${i} on "seeked" event ${l?l.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(Ot.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Ot.LEVEL_LOADING,this.onLevelLoading,this),t.on(Ot.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Ot.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(Ot.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Ot.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(Ot.BUFFER_CREATED,this.onBufferCreated,this),t.on(Ot.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Ot.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Ot.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(Ot.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Ot.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Ot.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(Ot.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Ot.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(Ot.BUFFER_CREATED,this.onBufferCreated,this),t.off(Ot.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Ot.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Ot.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,n){if(this.levels){const{lastCurrentTime:r,hls:a}=this;if(this.stopLoad(),this.setInterval(wlr),this.level=-1,!this.startFragRequested){let i=a.startLevel;i===-1&&(a.config.testBandwidth&&this.levels.length>1?(i=0,this.bitrateTest=!0):i=a.firstAutoLevel),a.nextLoadLevel=i,this.level=a.loadLevel,this._hasEnoughToStart=!!n}r>0&&t===-1&&!n&&(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),t=r),this.state=aa.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=aa.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case aa.WAITING_LEVEL:{const{levels:t,level:n}=this,r=t==null?void 0:t[n],a=r==null?void 0:r.details;if(a&&(!a.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(a))break;this.state=aa.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=aa.IDLE;break}break}case aa.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===aa.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),(t=this.media)!=null&&t.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:n,levels:r,media:a}=this;if(n===null||!a&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const i=this.buffering?t.nextLoadLevel:t.loadLevel;if(!(r!=null&&r[i]))return;const l=r[i],o=this.getMainFwdBufferInfo();if(o===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(o,c)){const x={};this.altAudio===2&&(x.type="video"),this.hls.trigger(Ot.BUFFER_EOS,x),this.state=aa.ENDED;return}if(!this.buffering)return;t.loadLevel!==i&&t.manualLevel===-1&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=t.nextLoadLevel=i;const d=l.details;if(!d||this.state===aa.WAITING_LEVEL||this.waitForLive(l)){this.level=i,this.state=aa.WAITING_LEVEL,this.startFragRequested=!1;return}const u=o.len,h=this.getMaxBufferLength(l.maxBitrate);if(u>=h)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const m=this.backtrackFragment?this.backtrackFragment.start:o.end;let p=this.getNextFragment(m,d);if(this.couldBacktrack&&!this.fragPrevious&&p&&Fg(p)&&this.fragmentTracker.getState(p)!==e0.OK){var f;const y=((f=this.backtrackFragment)!=null?f:p).sn-d.startSN,v=d.fragments[y-1];v&&p.cc===v.cc&&(p=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(p&&this.isLoopLoading(p,m)){if(!p.gap){const y=this.audioOnly&&!this.altAudio?dm.AUDIO:dm.VIDEO,v=(y===dm.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,y,io.MAIN)}p=this.getNextFragmentLoopLoading(p,d,o,io.MAIN,h)}p&&(this.exceedsMaxBuffer(o,h,p)||(p.initSegment&&!p.initSegment.data&&!this.bitrateTest&&(p=p.initSegment),this.loadFragment(p,l,m)))}loadFragment(t,n,r){const a=this.fragmentTracker.getState(t);a===e0.NOT_LOADED||a===e0.PARTIAL?Fg(t)?this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,n)):super.loadFragment(t,n,r):this._loadInitSegment(t,n):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,io.MAIN)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==0){var t;(((t=this.getLevelDetails())==null?void 0:t.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}nextLevelSwitch(){const{levels:t,media:n}=this;if(n!=null&&n.readyState){let r;const a=this.getAppendedFrag(n.currentTime);a&&a.start>1&&this.flushMainBuffer(0,a.start-1);const i=this.getLevelDetails();if(i!=null&&i.live){const o=this.getMainFwdBufferInfo();if(!o||o.len=l-n.maxFragLookUpTolerance&&i<=o;if(a!==null&&r.duration>a&&(i{this.hls&&this.hls.trigger(Ot.AUDIO_TRACK_SWITCHED,n)}),r.trigger(Ot.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}r.trigger(Ot.AUDIO_TRACK_SWITCHED,n)}}onAudioTrackSwitched(t,n){const r=STe(n.url,this.hls);if(r){const a=this.videoBuffer;a&&this.mediaBuffer!==a&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=a)}this.altAudio=r?2:0,this.tick()}onBufferCreated(t,n){const r=n.tracks;let a,i,l=!1;for(const o in r){const c=r[o];if(c.id==="main"){if(i=o,a=c,o==="video"){const d=r[o];d&&(this.videoBuffer=d.buffer)}}else l=!0}l&&a?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=a.buffer):this.mediaBuffer=this.media}onFragBuffered(t,n){const{frag:r,part:a}=n,i=r.type===io.MAIN;if(i){if(this.fragContextChanged(r)){this.warn(`Fragment ${r.sn}${a?" p: "+a.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}`),this.state===aa.PARSED&&(this.state=aa.IDLE);return}const o=a?a.stats:r.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),Fg(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,a)}const l=this.media;l&&(!this._hasEnoughToStart&&uc.getBuffered(l).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),i&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,n){var r;if(n.fatal){this.state=aa.ERROR;return}switch(n.details){case yr.FRAG_GAP:case yr.FRAG_PARSING_ERROR:case yr.FRAG_DECRYPT_ERROR:case yr.FRAG_LOAD_ERROR:case yr.FRAG_LOAD_TIMEOUT:case yr.KEY_LOAD_ERROR:case yr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(io.MAIN,n);break;case yr.LEVEL_LOAD_ERROR:case yr.LEVEL_LOAD_TIMEOUT:case yr.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===aa.WAITING_LEVEL&&((r=n.context)==null?void 0:r.type)===hd.LEVEL&&(this.state=aa.IDLE);break;case yr.BUFFER_ADD_CODEC_ERROR:case yr.BUFFER_APPEND_ERROR:if(n.parent!=="main")return;this.reduceLengthAndFlushBuffer(n)&&this.resetLoadingState();break;case yr.BUFFER_FULL_ERROR:if(n.parent!=="main")return;this.reduceLengthAndFlushBuffer(n)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case yr.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onFragLoadEmergencyAborted(){this.state=aa.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:n}){if(n!==dm.AUDIO||!this.altAudio){const r=(n===dm.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,n,io.MAIN),this.tick())}}onLevelsUpdated(t,n){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=n.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const n=t.currentTime;let r=this.startPosition;if(r>=0&&n0&&(c{const{hls:a}=this,i=r==null?void 0:r.frag;if(!i||this.fragContextChanged(i))return;n.fragmentError=0,this.state=aa.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const l=i.stats;l.parsing.start=l.parsing.end=l.buffering.start=l.buffering.end=self.performance.now(),a.trigger(Ot.FRAG_LOADED,r),i.bitrateTest=!1}).catch(r=>{this.state===aa.STOPPED||this.state===aa.ERROR||(this.warn(r),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const n=this.playlistType,{hls:r}=this,{remuxResult:a,chunkMeta:i}=t,l=this.getCurrentContext(i);if(!l){this.resetWhenMissingContext(i);return}const{frag:o,part:c,level:d}=l,{video:u,text:h,id3:m,initSegment:p}=a,{details:f}=d,x=this.altAudio?void 0:a.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=aa.PARSING,p){const y=p.tracks;if(y){const S=o.initSegment||o;if(this.unhandledEncryptionError(p,o))return;this._bufferInitSegment(d,y,S,i),r.trigger(Ot.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:n,tracks:y})}const v=p.initPTS,b=p.timescale,N=this.initPTS[o.cc];if(Bi(v)&&(!N||N.baseTime!==v||N.timescale!==b)){const S=p.trackId;this.initPTS[o.cc]={baseTime:v,timescale:b,trackId:S},r.trigger(Ot.INIT_PTS_FOUND,{frag:o,id:n,initPTS:v,timescale:b,trackId:S})}}if(u&&f){x&&u.type==="audiovideo"&&this.logMuxedErr(o);const y=f.fragments[o.sn-1-f.startSN],v=o.sn===f.startSN,b=!y||o.cc>y.cc;if(a.independent!==!1){const{startPTS:N,endPTS:S,startDTS:A,endDTS:T}=u;if(c)c.elementaryStreams[u.type]={startPTS:N,endPTS:S,startDTS:A,endDTS:T};else if(u.firstKeyFrame&&u.independent&&i.id===1&&!b&&(this.couldBacktrack=!0),u.dropped&&u.independent){const L=this.getMainFwdBufferInfo(),M=(L?L.end:this.getLoadPosition())+this.config.maxBufferHole,I=u.firstKeyFramePTS?u.firstKeyFramePTS:N;if(!v&&Ml3e&&(o.gap=!0);o.setElementaryStreamInfo(u.type,N,S,A,T),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,c,i,v||b)}else if(v||b)o.gap=!0;else{this.backtrack(o);return}}if(x){const{startPTS:y,endPTS:v,startDTS:b,endDTS:N}=x;c&&(c.elementaryStreams[dm.AUDIO]={startPTS:y,endPTS:v,startDTS:b,endDTS:N}),o.setElementaryStreamInfo(dm.AUDIO,y,v,b,N),this.bufferFragmentData(x,o,c,i)}if(f&&m!=null&&m.samples.length){const y={id:n,frag:o,details:f,samples:m.samples};r.trigger(Ot.FRAG_PARSING_METADATA,y)}if(f&&h){const y={id:n,frag:o,details:f,samples:h.samples};r.trigger(Ot.FRAG_PARSING_USERDATA,y)}}logMuxedErr(t){this.warn(`${Fg(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,n,r,a){if(this.state!==aa.PARSING)return;this.audioOnly=!!n.audio&&!n.video,this.altAudio&&!this.audioOnly&&(delete n.audio,n.audiovideo&&this.logMuxedErr(r));const{audio:i,video:l,audiovideo:o}=n;if(i){const d=t.audioCodec;let u=t3e(i.codec,d);u==="mp4a"&&(u="mp4a.40.5");const h=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){u&&(u.indexOf("mp4a.40.5")!==-1?u="mp4a.40.2":u="mp4a.40.5");const m=i.metadata;m&&"channelCount"in m&&(m.channelCount||1)!==1&&h.indexOf("firefox")===-1&&(u="mp4a.40.5")}u&&u.indexOf("mp4a.40.5")!==-1&&h.indexOf("android")!==-1&&i.container!=="audio/mpeg"&&(u="mp4a.40.2",this.log(`Android: force audio codec to ${u}`)),d&&d!==u&&this.log(`Swapping manifest audio codec "${d}" for "${u}"`),i.levelCodec=u,i.id=io.MAIN,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${u||""}/${d||""}/${i.codec}]`),delete n.audiovideo}if(l){l.levelCodec=t.videoCodec,l.id=io.MAIN;const d=l.codec;if((d==null?void 0:d.length)===4)switch(d){case"hvc1":case"hev1":l.codec="hvc1.1.6.L120.90";break;case"av01":l.codec="av01.0.04M.08";break;case"avc1":l.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${l.container}, codecs[level/parsed]=[${t.videoCodec||""}/${d}]${l.codec!==d?" parsed-corrected="+l.codec:""}${l.supplemental?" supplemental="+l.supplemental:""}`),delete n.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${t.codecs}/${o.codec}]`),delete n.video,delete n.audio);const c=Object.keys(n);if(c.length){if(this.hls.trigger(Ot.BUFFER_CODECS,n),!this.hls)return;c.forEach(d=>{const h=n[d].initSegment;h!=null&&h.byteLength&&this.hls.trigger(Ot.BUFFER_APPENDING,{type:d,data:h,frag:r,part:null,chunkMeta:a,parent:r.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,io.MAIN)}get maxBufferLength(){const{levels:t,level:n}=this,r=t==null?void 0:t[n];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=aa.IDLE}checkFragmentChanged(){const t=this.media;let n=null;if(t&&t.readyState>1&&t.seeking===!1){const r=t.currentTime;if(uc.isBuffered(t,r)?n=this.getAppendedFrag(r):uc.isBuffered(t,r+.1)&&(n=this.getAppendedFrag(r+.1)),n){this.backtrackFragment=null;const a=this.fragPlaying,i=n.level;(!a||n.sn!==a.sn||a.level!==i)&&(this.fragPlaying=n,this.hls.trigger(Ot.FRAG_CHANGED,{frag:n}),(!a||a.level!==i)&&this.hls.trigger(Ot.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const n=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;return Bi(n)?this.getAppendedFrag(n):null}get currentProgramDateTime(){var t;const n=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;if(Bi(n)){const r=this.getLevelDetails(),a=this.currentFrag||(r?i9(null,r.fragments,n):null);if(a){const i=a.programDateTime;if(i!==null){const l=i+(n-a.start)*1e3;return new Date(l)}}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class Nlr extends PN{constructor(t,n){super("key-loader",n),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const r in this.keyIdToKeyInfo){const a=this.keyIdToKeyInfo[r].loader;if(a){var n;if(t&&t!==((n=a.context)==null?void 0:n.frag.type))return;a.abort()}}}detach(){for(const t in this.keyIdToKeyInfo){const n=this.keyIdToKeyInfo[t];(n.mediaKeySessionContext||n.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyIdToKeyInfo){const n=this.keyIdToKeyInfo[t].loader;n&&n.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(t,n=yr.KEY_LOAD_ERROR,r,a,i){return new kC({type:wo.NETWORK_ERROR,details:n,fatal:!1,frag:t,response:i,error:r,networkDetails:a})}loadClear(t,n,r){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(n.length)for(let a=0,i=n.length;a{if(!this.emeController)return;l.setKeyFormat(o);const c=n3e(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const a=cX(this.config);if(a.length)return this.emeController.getKeySystemAccess(a)}}return null}load(t){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then(n=>this.loadInternal(t,n)):this.loadInternal(t)}loadInternal(t,n){var r,a;n&&t.setKeyFormat(n);const i=t.decryptdata;if(!i){const d=new Error(n?`Expected frag.decryptdata to be defined after setting format ${n}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(t,yr.KEY_LOAD_ERROR,d))}const l=i.uri;if(!l)return Promise.reject(this.createKeyLoadError(t,yr.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${l}"`)));const o=Xze(i);let c=this.keyIdToKeyInfo[o];if((r=c)!=null&&r.decryptdata.key)return i.key=c.decryptdata.key,Promise.resolve({frag:t,keyInfo:c});if(this.emeController&&(a=c)!=null&&a.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(u=>{const{keyInfo:h}=u;return i.key=h.decryptdata.key,{frag:t,keyInfo:h}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${i.keyId?" keyId: "+Zy(i.keyId):""} URI: ${i.uri} from ${t.type} ${t.level}`),c=this.keyIdToKeyInfo[o]={decryptdata:i,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},i.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return i.keyFormat==="identity"?this.loadKeyHTTP(c,t):this.loadKeyEME(c,t);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(c,t);default:return Promise.reject(this.createKeyLoadError(t,yr.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(t,n){const r={frag:n,keyInfo:t};if(this.emeController&&this.config.emeEnabled){var a;if(!t.decryptdata.keyId&&(a=n.initSegment)!=null&&a.data){const l=Unr(n.initSegment.data);if(l.length){let o=l[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${Zy(o)}`),tP.setKeyIdForUri(t.decryptdata.uri,o)):(o=tP.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${Zy(o)}`)),t.decryptdata.keyId=o}}if(!t.decryptdata.keyId&&!Fg(n))return Promise.resolve(r);const i=this.emeController.loadKey(r);return(t.keyLoadPromise=i.then(l=>(t.mediaKeySessionContext=l,r))).catch(l=>{throw t.keyLoadPromise=null,"data"in l&&(l.data.frag=n),l})}return Promise.resolve(r)}loadKeyHTTP(t,n){const r=this.config,a=r.loader,i=new a(r);return n.keyLoader=t.loader=i,t.keyLoadPromise=new Promise((l,o)=>{const c={keyInfo:t,frag:n,responseType:"arraybuffer",url:t.decryptdata.uri},d=r.keyLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(m,p,f,x)=>{const{frag:y,keyInfo:v}=f,b=Xze(v.decryptdata);if(!y.decryptdata||v!==this.keyIdToKeyInfo[b])return o(this.createKeyLoadError(y,yr.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),x));v.decryptdata.key=y.decryptdata.key=new Uint8Array(m.data),y.keyLoader=null,v.loader=null,l({frag:y,keyInfo:v})},onError:(m,p,f,x)=>{this.resetLoader(p),o(this.createKeyLoadError(n,yr.KEY_LOAD_ERROR,new Error(`HTTP Error ${m.code} loading key ${m.text}`),f,_h({url:c.url,data:void 0},m)))},onTimeout:(m,p,f)=>{this.resetLoader(p),o(this.createKeyLoadError(n,yr.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),f))},onAbort:(m,p,f)=>{this.resetLoader(p),o(this.createKeyLoadError(n,yr.INTERNAL_ABORTED,new Error("key loading aborted"),f))}};i.load(c,u,h)})}resetLoader(t){const{frag:n,keyInfo:r,url:a}=t,i=r.loader;n.keyLoader===i&&(n.keyLoader=null,r.loader=null);const l=Xze(r.decryptdata)||a;delete this.keyIdToKeyInfo[l],i&&i.destroy()}}function Xze(s){if(s.keyFormat!==Jy.FAIRPLAY){const t=s.keyId;if(t)return Zy(t)}return s.uri}function I4t(s){const{type:t}=s;switch(t){case hd.AUDIO_TRACK:return io.AUDIO;case hd.SUBTITLE_TRACK:return io.SUBTITLE;default:return io.MAIN}}function Qze(s,t){let n=s.url;return(n===void 0||n.indexOf("data:")===0)&&(n=t.url),n}class klr{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Ot.LEVEL_LOADING,this.onLevelLoading,this),t.on(Ot.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(Ot.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(Ot.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(Ot.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Ot.LEVEL_LOADING,this.onLevelLoading,this),t.off(Ot.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(Ot.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(Ot.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const n=this.hls.config,r=n.pLoader,a=n.loader,i=r||a,l=new i(n);return this.loaders[t.type]=l,l}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const n=this.loaders[t];n&&n.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,n){const{url:r}=n;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:hd.MANIFEST,url:r,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,n){const{id:r,level:a,pathwayId:i,url:l,deliveryDirectives:o,levelInfo:c}=n;this.load({id:r,level:a,pathwayId:i,responseType:"text",type:hd.LEVEL,url:l,deliveryDirectives:o,levelOrTrack:c})}onAudioTrackLoading(t,n){const{id:r,groupId:a,url:i,deliveryDirectives:l,track:o}=n;this.load({id:r,groupId:a,level:null,responseType:"text",type:hd.AUDIO_TRACK,url:i,deliveryDirectives:l,levelOrTrack:o})}onSubtitleTrackLoading(t,n){const{id:r,groupId:a,url:i,deliveryDirectives:l,track:o}=n;this.load({id:r,groupId:a,level:null,responseType:"text",type:hd.SUBTITLE_TRACK,url:i,deliveryDirectives:l,levelOrTrack:o})}onLevelsUpdated(t,n){const r=this.loaders[hd.LEVEL];if(r){const a=r.context;a&&!n.levels.some(i=>i===a.levelOrTrack)&&(r.abort(),delete this.loaders[hd.LEVEL])}}load(t){var n;const r=this.hls.config;let a=this.getInternalLoader(t);if(a){const d=this.hls.logger,u=a.context;if(u&&u.levelOrTrack===t.levelOrTrack&&(u.url===t.url||u.deliveryDirectives&&!t.deliveryDirectives)){u.url===t.url?d.log(`[playlist-loader]: ignore ${t.url} ongoing request`):d.log(`[playlist-loader]: ignore ${t.url} in favor of ${u.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),a.abort()}let i;if(t.type===hd.MANIFEST?i=r.manifestLoadPolicy.default:i=Yh({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),a=this.createInternalLoader(t),Bi((n=t.deliveryDirectives)==null?void 0:n.part)){let d;if(t.type===hd.LEVEL&&t.level!==null?d=this.hls.levels[t.level].details:t.type===hd.AUDIO_TRACK&&t.id!==null?d=this.hls.audioTracks[t.id].details:t.type===hd.SUBTITLE_TRACK&&t.id!==null&&(d=this.hls.subtitleTracks[t.id].details),d){const u=d.partTarget,h=d.targetduration;if(u&&h){const m=Math.max(u*3,h*.8)*1e3;i=Yh({},i,{maxTimeToFirstByteMs:Math.min(m,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(m,i.maxTimeToFirstByteMs)})}}}const l=i.errorRetry||i.timeoutRetry||{},o={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},c={onSuccess:(d,u,h,m)=>{const p=this.getInternalLoader(h);this.resetInternalLoader(h.type);const f=d.data;u.parsing.start=performance.now(),j4.isMediaPlaylist(f)||h.type!==hd.MANIFEST?this.handleTrackOrLevelPlaylist(d,u,h,m||null,p):this.handleMasterPlaylist(d,u,h,m)},onError:(d,u,h,m)=>{this.handleNetworkError(u,h,!1,d,m)},onTimeout:(d,u,h)=>{this.handleNetworkError(u,h,!0,void 0,d)}};a.load(t,o,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:n},forceStartLoad:r}=this.hls;(t||r)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${n}`),this.hls.startLoad(n))}handleMasterPlaylist(t,n,r,a){const i=this.hls,l=t.data,o=Qze(t,r),c=j4.parseMasterPlaylist(l,o);if(c.playlistParsingError){n.parsing.end=performance.now(),this.handleManifestParsingError(t,r,c.playlistParsingError,a,n);return}const{contentSteering:d,levels:u,sessionData:h,sessionKeys:m,startTimeOffset:p,variableList:f}=c;this.variableList=f,u.forEach(b=>{const{unknownCodecs:N}=b;if(N){const{preferManagedMediaSource:S}=this.hls.config;let{audioCodec:A,videoCodec:T}=b;for(let L=N.length;L--;){const M=N[L];Hte(M,"audio",S)?(b.audioCodec=A=A?`${A},${M}`:M,GH.audio[A.substring(0,4)]=2,N.splice(L,1)):Hte(M,"video",S)&&(b.videoCodec=T=T?`${T},${M}`:M,GH.video[T.substring(0,4)]=2,N.splice(L,1))}}});const{AUDIO:x=[],SUBTITLES:y,"CLOSED-CAPTIONS":v}=j4.parseMasterPlaylistMedia(l,o,c);x.length&&!x.some(N=>!N.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),x.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new uf({}),bitrate:0,url:""})),i.trigger(Ot.MANIFEST_LOADED,{levels:u,audioTracks:x,subtitles:y,captions:v,contentSteering:d,url:o,stats:n,networkDetails:a,sessionData:h,sessionKeys:m,startTimeOffset:p,variableList:f})}handleTrackOrLevelPlaylist(t,n,r,a,i){const l=this.hls,{id:o,level:c,type:d}=r,u=Qze(t,r),h=Bi(c)?c:Bi(o)?o:0,m=I4t(r),p=j4.parseLevelPlaylist(t.data,u,h,m,0,this.variableList);if(d===hd.MANIFEST){const f={attrs:new uf({}),bitrate:0,details:p,name:"",url:u};p.requestScheduled=n.loading.start+cns(p,0),l.trigger(Ot.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:u,stats:n,networkDetails:a,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}n.parsing.end=performance.now(),r.levelDetails=p,this.handlePlaylistLoaded(p,t,n,r,a,i)}handleManifestParsingError(t,n,r,a,i){this.hls.trigger(Ot.ERROR,{type:wo.NETWORK_ERROR,details:yr.MANIFEST_PARSING_ERROR,fatal:n.type===hd.MANIFEST,url:t.url,err:r,error:r,reason:r.message,response:t,context:n,networkDetails:a,stats:i})}handleNetworkError(t,n,r=!1,a,i){let l=`A network ${r?"timeout":"error"+(a?" (status "+a.code+")":"")} occurred while loading ${t.type}`;t.type===hd.LEVEL?l+=`: ${t.level} id: ${t.id}`:(t.type===hd.AUDIO_TRACK||t.type===hd.SUBTITLE_TRACK)&&(l+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(l);this.hls.logger.warn(`[playlist-loader]: ${l}`);let c=yr.UNKNOWN,d=!1;const u=this.getInternalLoader(t);switch(t.type){case hd.MANIFEST:c=r?yr.MANIFEST_LOAD_TIMEOUT:yr.MANIFEST_LOAD_ERROR,d=!0;break;case hd.LEVEL:c=r?yr.LEVEL_LOAD_TIMEOUT:yr.LEVEL_LOAD_ERROR,d=!1;break;case hd.AUDIO_TRACK:c=r?yr.AUDIO_TRACK_LOAD_TIMEOUT:yr.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case hd.SUBTITLE_TRACK:c=r?yr.SUBTITLE_TRACK_LOAD_TIMEOUT:yr.SUBTITLE_LOAD_ERROR,d=!1;break}u&&this.resetInternalLoader(t.type);const h={type:wo.NETWORK_ERROR,details:c,fatal:d,url:t.url,loader:u,context:t,error:o,networkDetails:n,stats:i};if(a){const m=(n==null?void 0:n.url)||t.url;h.response=_h({url:m,data:void 0},a)}this.hls.trigger(Ot.ERROR,h)}handlePlaylistLoaded(t,n,r,a,i,l){const o=this.hls,{type:c,level:d,levelOrTrack:u,id:h,groupId:m,deliveryDirectives:p}=a,f=Qze(n,a),x=I4t(a);let y=typeof a.level=="number"&&x===io.MAIN?d:void 0;const v=t.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${t.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(Ot.ERROR,{type:wo.NETWORK_ERROR,details:yr.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:v,reason:v.message,response:n,context:a,level:y,parent:x,networkDetails:i,stats:r});return}t.playlistParsingError=null}if(!t.fragments.length){const b=t.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(Ot.ERROR,{type:wo.NETWORK_ERROR,details:yr.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:b,reason:b.message,response:n,context:a,level:y,parent:x,networkDetails:i,stats:r});return}switch(t.live&&l&&(l.getCacheAge&&(t.ageHeader=l.getCacheAge()||0),(!l.getCacheAge||isNaN(t.ageHeader))&&(t.ageHeader=0)),c){case hd.MANIFEST:case hd.LEVEL:if(y){if(!u)y=0;else if(u!==o.levels[y]){const b=o.levels.indexOf(u);b>-1&&(y=b)}}o.trigger(Ot.LEVEL_LOADED,{details:t,levelInfo:u||o.levels[0],level:y||0,id:h||0,stats:r,networkDetails:i,deliveryDirectives:p,withoutMultiVariant:c===hd.MANIFEST});break;case hd.AUDIO_TRACK:o.trigger(Ot.AUDIO_TRACK_LOADED,{details:t,track:u,id:h||0,groupId:m||"",stats:r,networkDetails:i,deliveryDirectives:p});break;case hd.SUBTITLE_TRACK:o.trigger(Ot.SUBTITLE_TRACK_LOADED,{details:t,track:u,id:h||0,groupId:m||"",stats:r,networkDetails:i,deliveryDirectives:p});break}}}class m4{static get version(){return Kte}static isMSESupported(){return lrs()}static isSupported(){return blr()}static getMediaSource(){return SP()}static get Events(){return Ot}static get MetadataSchema(){return Dw}static get ErrorTypes(){return wo}static get ErrorDetails(){return yr}static get DefaultConfig(){return m4.defaultConfig?m4.defaultConfig:llr}static set DefaultConfig(t){m4.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Urt,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const n=this.logger=Enr(t.debug||!1,"Hls instance",t.assetPlayerId),r=this.config=dlr(m4.DefaultConfig,t,n);this.userConfig=t,r.progressive&&ulr(r,n);const{abrController:a,bufferController:i,capLevelController:l,errorController:o,fpsController:c}=r,d=new o(this),u=this.abrController=new a(this),h=new Nrr(this),m=r.interstitialsController,p=m?this.interstitialsController=new m(this,m4):null,f=this.bufferController=new i(this,h),x=this.capLevelController=new l(this),y=new c(this),v=new klr(this),b=r.contentSteeringController,N=b?new b(this):null,S=this.levelController=new vlr(this,N),A=new xlr(this),T=new Nlr(this.config,this.logger),L=this.streamController=new jlr(this,h,T),M=this.gapController=new flr(this,h);x.setStreamController(L),y.setStreamController(L);const I=[v,S,L];p&&I.splice(1,0,p),N&&I.splice(1,0,N),this.networkControllers=I;const R=[u,f,M,x,y,A,h];this.audioTrackController=this.createController(r.audioTrackController,I);const z=r.audioStreamController;z&&I.push(this.audioStreamController=new z(this,h,T)),this.subtitleTrackController=this.createController(r.subtitleTrackController,I);const $=r.subtitleStreamController;$&&I.push(this.subtititleStreamController=new $(this,h,T)),this.createController(r.timelineController,R),T.emeController=this.emeController=this.createController(r.emeController,R),this.cmcdController=this.createController(r.cmcdController,R),this.latencyController=this.createController(ylr,R),this.coreComponents=R,I.push(d);const H=d.onErrorOut;typeof H=="function"&&this.on(Ot.ERROR,H,d),this.on(Ot.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(t,n){if(t){const r=new t(this);return n&&n.push(r),r}return null}on(t,n,r=this){this._emitter.on(t,n,r)}once(t,n,r=this){this._emitter.once(t,n,r)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,n,r=this,a){this._emitter.off(t,n,r,a)}listeners(t){return this._emitter.listeners(t)}emit(t,n,r){return this._emitter.emit(t,n,r)}trigger(t,n){if(this.config.debug)return this.emit(t,t,n);try{return this.emit(t,t,n)}catch(r){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+r.message+'". Here is a stacktrace:',r),!this.triggeringException){this.triggeringException=!0;const a=t===Ot.ERROR;this.trigger(Ot.ERROR,{type:wo.OTHER_ERROR,details:yr.INTERNAL_EXCEPTION,fatal:a,event:t,error:r}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(Ot.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(n=>n.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(n=>n.destroy()),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const i=new Error(`attachMedia failed: invalid argument (${t})`);this.trigger(Ot.ERROR,{type:wo.OTHER_ERROR,details:yr.ATTACH_MEDIA_ERROR,fatal:!0,error:i});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const n="media"in t,r=n?t.media:t,a=n?t:{media:r};this._media=r,this.trigger(Ot.MEDIA_ATTACHING,a)}detachMedia(){this.logger.log("detachMedia"),this.trigger(Ot.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(Ot.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const n=this.media,r=this._url,a=this._url=Trt.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${a}`),n&&r&&(r!==a||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(n)),this.trigger(Ot.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,n){this.logger.log(`startLoad(${t+(n?", ":"")})`),this.started=!0,this.resumeBuffering();for(let r=0;r{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[io.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[io.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[io.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,n=t==null?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),n&&this.startLoad(n))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=por()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return t===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),t!==-1&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const n=!!t;n!==this.config.capLevelToPlayerSize&&(n?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=n)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){lrr(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:n}}=this;if(!t)return 0;const r=t.length;for(let a=0;a=n)return a;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:n,maxHdcpLevel:r}=this;let a;if(n===-1&&t!=null&&t.length?a=t.length-1:a=n,r)for(let i=a;i--;){const l=t[i].attrs["HDCP-LEVEL"];if(l&&l<=r)return i}return a}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var n;return((n=this.audioTrackController)==null?void 0:n.setAudioOption(t))||null}setSubtitleOption(t){var n;return((n=this.subtitleTrackController)==null?void 0:n.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const n=this.audioTrackController;n&&(n.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const n=this.subtitleTrackController;n&&(n.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return t?t.subtitleDisplay:!1}set subtitleDisplay(t){const n=this.subtitleTrackController;n&&(n.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(t){this.latencyController.targetLatency=t}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!!((t=this.bufferController)!=null&&t.bufferedToEnd)}get interstitialsManager(){var t;return((t=this.interstitialsController)==null?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,n=this.allAudioTracks){const r=Kss(n);return Gss(t,r,navigator.mediaCapabilities)}}m4.defaultConfig=void 0;const Slr=/(?:player\.mediadelivery\.net|iframe\.mediadelivery\.net|iframe\.n\.net|video\.bunnycdn\.com|[a-z0-9-]+\.b-cdn\.net)/i;function OU(s){return!!s&&Slr.test(s)&&!/\.mp4($|\?)/i.test(s)}function Clr(s){const t=s.match(/\/(?:play|embed)\/(\d+)\/([a-z0-9-]+)/i);return t?{libraryId:t[1],videoId:t[2]}:null}function Alr(s,t){if(!s)return null;const n=Clr(s);if(n){const r=new URLSearchParams({autoplay:t!=null&&t.autoplay?"true":"false",muted:t!=null&&t.muted?"true":"false",loop:t!=null&&t.loop?"true":"false",preload:"true",responsive:"true",playsinline:"true"});return`https://player.mediadelivery.net/embed/${n.libraryId}/${n.videoId}?${r.toString()}`}return/player\.mediadelivery\.net\/embed\//i.test(s)?s:/iframe\.mediadelivery\.net\/(?:play|embed)\//i.test(s)?s.replace("iframe.mediadelivery.net/play/","player.mediadelivery.net/embed/").replace("iframe.mediadelivery.net/embed/","player.mediadelivery.net/embed/"):s}function Elr(s){const t=s.match(/https:\/\/[^"']+playlist\.m3u8[^"']*/i);return t?t[0].replace(/&/g,"&").replace(/\u0026/g,"&"):null}const ZKe=j.forwardRef(function({sourceUrl:t,thumbnailUrl:n,autoPlay:r,muted:a,loop:i,playsInline:l=!0,...o},c){const d=j.useRef(null),[u,h]=j.useState(null),m=j.useMemo(()=>Alr(t,{autoplay:!!r,muted:!!a,loop:!!i}),[t,r,a,i]);j.useEffect(()=>{let f=!1;if(!t){h(null);return}if(!OU(t)){h(t);return}if(!m){h(null);return}return h(null),fetch(m).then(async x=>{if(!x.ok)throw new Error(`Failed to load Bunny embed (${x.status})`);const y=await x.text();return Elr(y)}).then(x=>{f||h(x)}).catch(()=>{f||h(null)}),()=>{f=!0}},[m,t]),j.useEffect(()=>{const f=d.current;if(!f||!u)return;let x=null;const y=()=>{if(!r)return;const b=f.play();b&&b.catch(()=>{})};if(f.muted=!!a,f.loop=!!i,u.endsWith(".m3u8")){if(f.canPlayType("application/vnd.apple.mpegurl")){f.src=u;const b=()=>y();return f.addEventListener("loadedmetadata",b),()=>{f.removeEventListener("loadedmetadata",b),f.removeAttribute("src"),f.load()}}return m4.isSupported()?(x=new m4({enableWorker:!0,lowLatencyMode:!0}),x.loadSource(u),x.attachMedia(f),x.on(m4.Events.MANIFEST_PARSED,y),()=>{x==null||x.destroy(),f.removeAttribute("src"),f.load()}):void 0}f.src=u;const v=()=>y();return f.addEventListener("loadedmetadata",v),()=>{f.removeEventListener("loadedmetadata",v),f.removeAttribute("src"),f.load()}},[r,i,a,u]),j.useEffect(()=>{const f=d.current;if(f){if(f.muted=!!a,f.loop=!!i,r&&u){const x=f.play();x&&x.catch(()=>{});return}f.pause()}},[r,i,a,u]);const p=f=>{if(d.current=f,typeof c=="function"){c(f);return}c&&(c.current=f)};return e.jsx("video",{ref:p,poster:n||void 0,autoPlay:r,muted:a,loop:i,playsInline:l,preload:"metadata",...o})}),Tlr={portrait:{sm:{w:130,h:231},md:{w:170,h:302},lg:{w:210,h:373}},landscape:{sm:{w:178,h:100},md:{w:220,h:124},lg:{w:270,h:152}}};function Mlr(){try{let s=localStorage.getItem("vg_visitor_token");return s||(s=crypto.randomUUID(),localStorage.setItem("vg_visitor_token",s)),s}catch{return null}}function R4t(s,t){return!s||s.length===0?!1:s.some(n=>n?n===t?!0:n.endsWith("*")?t.startsWith(n.slice(0,-1)):t.startsWith(n):!1)}function eat({config:s,appSlug:t="video_greeter",preview:n=!1,embedded:r=!1}){const[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(!0),[u,h]=j.useState(!1),[m,p]=j.useState("portrait"),[f,x]=j.useState(!1),[y,v]=j.useState(!1),[b,N]=j.useState({name:"",email:"",phone:""}),[S,A]=j.useState(()=>({width:typeof window<"u"?window.innerWidth:1280,height:typeof window<"u"?window.innerHeight:720})),T=j.useRef(null),L=j.useRef(null),M=j.useRef(!1),I=async(Ne,$e)=>{if(!n)try{await q.from("widget_events").insert({user_id:s.user_id,app_slug:t,event_type:Ne,visitor_token:Mlr(),page_url:typeof window<"u"?window.location.href:null,metadata:$e||{}})}catch{}};j.useEffect(()=>{if(u)return;const Ne=typeof window<"u"?window.location.pathname:"/",$e=s.targeting||{mode:"all"};if($e.mode==="include"&&!R4t($e.include,Ne)||$e.mode==="exclude"&&R4t($e.exclude,Ne))return;const Ve=s.trigger||{type:"immediate"};if(Ve.type==="immediate"||n){i(!0);return}if(Ve.type==="delay"){const qe=(Ve.value||3)*1e3,Ze=setTimeout(()=>i(!0),qe);return()=>clearTimeout(Ze)}if(Ve.type==="scroll"){const qe=(Ve.value||25)/100,Ze=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight>=qe&&(i(!0),window.removeEventListener("scroll",Ze))};return window.addEventListener("scroll",Ze,{passive:!0}),()=>window.removeEventListener("scroll",Ze)}if(Ve.type==="exit_intent"){const qe=Ze=>{Ze.clientY<=0&&i(!0)};return document.addEventListener("mouseleave",qe),()=>document.removeEventListener("mouseleave",qe)}},[u,s.targeting,s.trigger,n]),j.useEffect(()=>{a&&!M.current&&(M.current=!0,I("impression"))},[a]),j.useEffect(()=>{if(l&&L.current&&!OU(s.video_url)){L.current.currentTime=0,L.current.muted=!1,d(!1);const Ne=L.current.play();Ne&&Ne.catch(()=>{})}else l&&OU(s.video_url)&&d(!1)},[l,s.video_url]),j.useEffect(()=>{if(!s.thumbnail_url)return;let Ne=!1;const $e=new Image;return $e.onload=()=>{Ne||p($e.naturalWidth>$e.naturalHeight?"landscape":"portrait")},$e.src=s.thumbnail_url,()=>{Ne=!0}},[s.thumbnail_url]),j.useEffect(()=>{const Ne=()=>{A({width:window.innerWidth,height:window.innerHeight})};return Ne(),window.addEventListener("resize",Ne),()=>window.removeEventListener("resize",Ne)},[]);const R=()=>{o(!0),I("expand")},z=Ne=>{Ne.stopPropagation(),h(!0),o(!1)},$=Ne=>{I("cta_click",{cta_id:Ne.id,label:Ne.label,url:Ne.url})},H=async Ne=>{if(Ne.preventDefault(),n){x(!0);return}if(!(!b.email||!b.name)){v(!0);try{const{error:$e}=await q.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:t,name:b.name,email:b.email,phone:b.phone||void 0,page_url:window.location.href}});if($e)throw $e;I("lead_capture",{email:b.email}),x(!0)}catch($e){console.error("lead submit failed",$e)}finally{v(!1)}}};if(!a||u||!s.video_url&&!s.video_embed_url)return null;const V=Tlr[m][s.size||"md"],K=r?"absolute left-2 bottom-2":n?s.position==="bottom-right"?"absolute right-4 bottom-4":"absolute left-4 bottom-4":s.position==="bottom-right"?"fixed right-4 bottom-4 md:right-6 md:bottom-6":"fixed left-4 bottom-4 md:left-6 md:bottom-6",Z=s.shape==="circle"?"rounded-full":"rounded-2xl",Q=n?m==="landscape"?"w-[280px]":"w-[220px]":m==="landscape"?"w-[360px] sm:w-[420px]":"w-[300px] sm:w-[340px]",le=m==="landscape"?"aspect-video":"aspect-[9/16]",ue=s.agent||{},se=s.lead_form_fields||["name","email","phone"],ne=!!(s.show_socials&&(ue.instagram_url||ue.facebook_url||ue.linkedin_url)),ie=108+(s.ctas||[]).length*48+(s.lead_form_enabled&&!f?72+se.length*42:0)+(f?40:0)+(ne?34:0),ce=Math.max(300,S.height-32),je=Math.max(220,S.width-32),be=Math.max(150,ce-ie),he=Math.floor(m==="landscape"?be*(16/9):be*(9/16)),ge=m==="landscape"?Math.max(220,Math.min(420,je,he)):Math.max(180,Math.min(340,je,he)),ke=r?"bg-white rounded-2xl shadow-2xl overflow-hidden border border-black/10 animate-in fade-in zoom-in-95 duration-300 flex flex-col":`${Q} max-h-[calc(100dvh-2rem)] bg-white rounded-2xl shadow-2xl overflow-hidden border border-black/10 animate-in fade-in zoom-in-95 duration-300 flex flex-col`,Te=r?{width:`${ge}px`,maxHeight:"calc(100dvh - 2rem)"}:void 0,Me=r?"p-3 space-y-2.5":"p-4 space-y-3",Oe=r?"w-9 h-9 rounded-full object-cover":"w-10 h-10 rounded-full object-cover",Se=r?"font-bold text-[15px] text-gray-900 leading-tight":"font-bold text-gray-900 leading-tight",Qe=r?"text-[11px] text-gray-500 mt-0.5":"text-xs text-gray-500 mt-0.5",Ae=r?"w-full px-3 py-1.5 text-sm rounded-lg border border-gray-200 focus:border-gray-900 focus:outline-none bg-white text-gray-900 placeholder:text-gray-400":"w-full px-3 py-2 text-sm rounded-lg border border-gray-200 focus:border-gray-900 focus:outline-none bg-white text-gray-900 placeholder:text-gray-400",Fe=r?"w-full flex items-center justify-center gap-2 px-3 py-2 bg-gray-900 text-white rounded-xl text-sm font-semibold hover:bg-black transition-colors disabled:opacity-60":"w-full flex items-center justify-center gap-2 px-3 py-2.5 bg-gray-900 text-white rounded-xl text-sm font-semibold hover:bg-black transition-colors disabled:opacity-60";return e.jsx("div",{"data-vg-widget":!0,"data-expanded":l?"true":"false",className:`${K} z-[70]`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:l?e.jsxs("div",{className:ke,style:Te,children:[e.jsxs("div",{className:`relative bg-black ${le}`,children:[OU(s.video_url)?e.jsx(ZKe,{ref:L,sourceUrl:s.video_url,thumbnailUrl:s.thumbnail_url,autoPlay:!0,muted:c,loop:!1,className:"w-full h-full object-cover",onLoadedMetadata:Ne=>{const{videoWidth:$e,videoHeight:Ve}=Ne.currentTarget;$e&&Ve&&p($e>Ve?"landscape":"portrait")},onEnded:()=>I("watch_complete")},`expanded-${s.video_url}-${s.thumbnail_url||"no-thumb"}-${l?"on":"off"}`):e.jsx("video",{ref:L,src:s.video_url||void 0,poster:s.thumbnail_url||void 0,autoPlay:!0,playsInline:!0,controls:!1,className:"w-full h-full object-cover",onEnded:()=>I("watch_complete"),onLoadedMetadata:Ne=>{const{videoWidth:$e,videoHeight:Ve}=Ne.currentTarget;$e&&Ve&&p($e>Ve?"landscape":"portrait")}}),e.jsx("button",{onClick:()=>{L.current&&(L.current.muted=!L.current.muted,d(L.current.muted))},className:"absolute bottom-3 right-3 w-9 h-9 rounded-full bg-black/60 hover:bg-black text-white flex items-center justify-center backdrop-blur",children:c?e.jsx(xQ,{className:"w-4 h-4"}):e.jsx(gQ,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>o(!1),className:"absolute top-3 right-3 w-8 h-8 rounded-full bg-black/60 hover:bg-black text-white flex items-center justify-center backdrop-blur","aria-label":"Minimize",children:e.jsx(er,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:Me,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[ue.avatar_url&&e.jsx("img",{src:ue.avatar_url,alt:ue.name||"",className:Oe}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:Se,children:s.greeting_title||"Glad you're here!"}),s.greeting_subtitle&&e.jsx("p",{className:Qe,children:s.greeting_subtitle})]})]}),(s.ctas||[]).length>0&&e.jsx("div",{className:"space-y-2",children:(s.ctas||[]).map(Ne=>{var $e;return e.jsxs("a",{href:Ne.url,target:($e=Ne.url)!=null&&$e.startsWith("http")?"_blank":void 0,rel:"noopener noreferrer",onClick:()=>$(Ne),className:`flex items-center justify-between gap-2 ${r?"px-3 py-2":"px-3.5 py-2.5"} rounded-xl text-sm font-semibold transition-colors ${Ne.style==="secondary"?"bg-gray-100 text-gray-900 hover:bg-gray-200":"bg-gray-900 text-white hover:bg-gray-800"}`,children:[e.jsx("span",{children:Ne.label}),e.jsx(Sr,{className:"w-3.5 h-3.5 opacity-60"})]},Ne.id)})}),s.lead_form_enabled&&!f&&e.jsxs("form",{onSubmit:H,className:"space-y-2 pt-1",children:[se.includes("name")&&e.jsx("input",{type:"text",placeholder:"Name",required:!0,value:b.name,onChange:Ne=>N({...b,name:Ne.target.value}),className:Ae}),se.includes("email")&&e.jsx("input",{type:"email",placeholder:"Email",required:!0,value:b.email,onChange:Ne=>N({...b,email:Ne.target.value}),className:Ae}),se.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:b.phone,onChange:Ne=>N({...b,phone:Ne.target.value}),className:Ae}),e.jsxs("button",{type:"submit",disabled:y,className:Fe,children:[e.jsx($r,{className:"w-3.5 h-3.5"}),y?"Sending...":"Send"]})]}),f&&e.jsx("p",{className:"text-sm text-emerald-600 font-medium text-center py-2",children:"Thanks! I'll be in touch shortly."}),s.show_socials&&(ue.instagram_url||ue.facebook_url||ue.linkedin_url)&&e.jsxs("div",{className:"flex items-center justify-center gap-3 pt-2 border-t border-gray-100",children:[ue.instagram_url&&e.jsx("a",{href:ue.instagram_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>I("cta_click",{social:"instagram"}),children:e.jsx(gm,{className:"w-4 h-4"})}),ue.facebook_url&&e.jsx("a",{href:ue.facebook_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>I("cta_click",{social:"facebook"}),children:e.jsx(zp,{className:"w-4 h-4"})}),ue.linkedin_url&&e.jsx("a",{href:ue.linkedin_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>I("cta_click",{social:"linkedin"}),children:e.jsx(Gg,{className:"w-4 h-4"})})]})]})]}):e.jsxs("div",{className:"relative animate-in fade-in slide-in-from-bottom-4 duration-500",children:[e.jsxs("button",{onClick:R,className:`relative ${Z} overflow-hidden shadow-2xl ring-2 ring-white/40 hover:ring-white/80 hover:scale-105 transition-all bg-black`,style:{width:V.w,height:V.h},"aria-label":"Play video greeting",children:[OU(s.video_url)?e.jsx(ZKe,{ref:T,sourceUrl:s.video_url,thumbnailUrl:s.thumbnail_url,autoPlay:!0,muted:!0,loop:!0,className:"w-full h-full object-cover pointer-events-none",onLoadedMetadata:Ne=>{const{videoWidth:$e,videoHeight:Ve}=Ne.currentTarget;$e&&Ve&&p($e>Ve?"landscape":"portrait")}},`collapsed-${s.video_url}-${s.thumbnail_url||"no-thumb"}`):e.jsx("video",{ref:T,src:s.video_url||void 0,poster:s.thumbnail_url||void 0,autoPlay:!0,muted:!0,loop:!0,playsInline:!0,preload:"metadata",className:"w-full h-full object-cover",onLoadedMetadata:Ne=>{const{videoWidth:$e,videoHeight:Ve}=Ne.currentTarget;$e&&Ve&&p($e>Ve?"landscape":"portrait")}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/40 via-transparent to-transparent pointer-events-none"}),e.jsx("div",{className:"absolute bottom-2 left-1/2 -translate-x-1/2 w-12 h-12 rounded-full bg-white/95 flex items-center justify-center shadow-lg pointer-events-none",children:e.jsx("svg",{viewBox:"0 0 24 24",className:"w-6 h-6 text-black ml-0.5",fill:"currentColor",children:e.jsx("path",{d:"M8 5v14l11-7z"})})}),e.jsx("span",{className:"absolute top-2 right-2 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider bg-red-500 text-white rounded-full animate-pulse",children:"Live"})]}),e.jsx("button",{onClick:z,className:"absolute -top-2 -right-2 w-7 h-7 rounded-full bg-black/80 text-white shadow-lg hover:bg-black flex items-center justify-center","aria-label":"Close",children:e.jsx(er,{className:"w-3.5 h-3.5"})})]})})}function tat({slug:s}){const[t,n]=j.useState(null);return j.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await q.rpc("get_public_video_greeter_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(eat,{config:t}):null}const crs="eip_last_shown",D4t="eip_visitor_token";function Plr(){try{let s=localStorage.getItem(D4t);return s||(s=crypto.randomUUID(),localStorage.setItem(D4t,s)),s}catch{return}}function Llr(s){try{const t=Number(localStorage.getItem(crs)||0);return t?Date.now()-t>s*24*60*60*1e3:!0}catch{return!0}}function Ilr(s){if(!s||s.mode==="all")return!0;const t=window.location.pathname,r=(s.mode==="include"?s.include||[]:s.exclude||[]).some(a=>t.startsWith(a));return s.mode==="include"?r:!r}function drs({config:s,preview:t=!1,forceOpen:n=!1}){const[r,a]=j.useState(n),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState({name:"",email:"",phone:""}),h=j.useRef(!1),m=j.useRef(!1),p=async(T,L={})=>{if(!t)try{await q.from("widget_events").insert({user_id:s.user_id,app_slug:"exit_intent",event_type:T,visitor_token:Plr(),page_url:window.location.href,metadata:L})}catch{}};j.useEffect(()=>{if(t||!Ilr(s.targeting)||!Llr(s.frequency_days))return;const T=/Mobi|Android/i.test(navigator.userAgent),L={low:5,medium:15,high:30}[s.trigger_sensitivity]||15,M=$=>{if(!h.current){h.current=!0,a(!0);try{localStorage.setItem(crs,String(Date.now()))}catch{}p("impression",{reason:$})}},I=$=>{$.clientY<=L&&M("mouse_leave")},R=()=>{s.enable_mobile_back&&T&&M("back_button")};if(s.enable_mobile_back&&T){try{window.history.pushState({eip:!0},"")}catch{}window.addEventListener("popstate",R)}else document.addEventListener("mouseleave",I);let z;return s.enable_time_fallback&&(z=window.setTimeout(()=>M("time_fallback"),Math.max(5,s.time_fallback_seconds)*1e3)),()=>{document.removeEventListener("mouseleave",I),window.removeEventListener("popstate",R),z&&window.clearTimeout(z)}},[s,t]),j.useEffect(()=>{r&&!m.current&&!t&&!h.current&&(m.current=!0)},[r,t]);const f=()=>{a(!1),t||p("close")},x=async T=>{if(T.preventDefault(),t){l(!0);return}if(!(!d.email||!d.name)){c(!0);try{const{error:L}=await q.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:"exit_intent",name:d.name,email:d.email,phone:d.phone||void 0,page_url:window.location.href}});if(L)throw L;p("lead_capture",{email:d.email}),l(!0),s.cta_url&&setTimeout(()=>{window.location.href=s.cta_url},1200)}catch(L){console.error("exit intent submit failed",L)}finally{c(!1)}}};if(!r)return null;const y=s.form_fields||["name","email"],v=s.agent||{},b=[v.first_name,v.last_name].filter(Boolean).join(" "),N=s.use_agent_photo&&v.avatar_url||s.image_url,S=s.theme_color||"#f97316",A=t?"absolute inset-0 flex items-center justify-center p-4 z-10":"fixed inset-0 z-[80] flex items-center justify-center p-4";return e.jsx("div",{className:A,style:{background:t?"transparent":"rgba(0,0,0,0.6)"},children:e.jsxs("div",{className:"relative w-full max-w-md bg-background rounded-2xl shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-300",onClick:T=>T.stopPropagation(),children:[e.jsx("div",{className:"h-2 w-full",style:{background:`linear-gradient(90deg, ${S}, ${Jze(S,-25)})`}}),e.jsx("button",{onClick:f,className:"absolute top-3 right-3 z-10 w-8 h-8 rounded-full bg-background/80 backdrop-blur hover:bg-background flex items-center justify-center text-muted-foreground hover:text-foreground transition","aria-label":"Close",children:e.jsx(er,{className:"w-4 h-4"})}),e.jsxs("div",{className:"p-6 sm:p-7 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[N&&e.jsx("img",{src:N,alt:b||"Agent",className:"w-14 h-14 rounded-full object-cover ring-2 shadow-md",style:{boxShadow:`0 0 0 2px ${S}33`,"--tw-ring-color":S}}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold",style:{background:`${S}1A`,color:S},children:[e.jsx(cn,{className:"w-3 h-3"}),s.offer_label]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:s.headline}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:s.subheadline})]}),i?e.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${S}10`,color:S},children:[e.jsx("div",{className:"text-3xl",children:"🎉"}),e.jsx("p",{className:"text-sm font-medium",style:{color:S},children:s.success_message})]}):s.form_enabled?e.jsxs("form",{onSubmit:x,className:"space-y-2.5",children:[y.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:d.name,onChange:T=>u({...d,name:T.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":S},required:!0}),y.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:d.email,onChange:T=>u({...d,email:T.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":S},required:!0}),y.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:d.phone,onChange:T=>u({...d,phone:T.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":S}}),e.jsx("button",{type:"submit",disabled:o,className:"w-full py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 active:scale-[0.99] transition disabled:opacity-60",style:{background:`linear-gradient(135deg, ${S}, ${Jze(S,-20)})`},children:o?"Sending...":s.cta_label}),e.jsx("p",{className:"text-[10px] text-center text-muted-foreground pt-1",children:"We respect your inbox. Unsubscribe anytime."})]}):e.jsx("a",{href:s.cta_url||"#",onClick:()=>p("cta_click",{url:s.cta_url}),className:"block w-full text-center py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 transition",style:{background:`linear-gradient(135deg, ${S}, ${Jze(S,-20)})`},children:s.cta_label}),b&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground pt-1",children:["Sent personally by ",b]})]})]})})}function Jze(s,t){try{const n=parseInt(s.slice(1),16),r=t<0?0:255,a=Math.abs(t)/100,i=n>>16,l=n>>8&255,o=n&255,c=Math.round((r-i)*a)+i,d=Math.round((r-l)*a)+l,u=Math.round((r-o)*a)+o;return"#"+(16777216+(c<<16)+(d<<8)+u).toString(16).slice(1)}catch{return s}}function sat({slug:s}){const[t,n]=j.useState(null);return j.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await q.rpc("get_public_exit_intent_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(drs,{config:t}):null}const O4t="lm_dismissed",F4t="lm_visitor_token";function Rlr(){try{let s=localStorage.getItem(F4t);return s||(s=crypto.randomUUID(),localStorage.setItem(F4t,s)),s}catch{return}}function Dlr(s){if(!s||s.mode==="all")return!0;const t=window.location.pathname,r=(s.mode==="include"?s.include||[]:s.exclude||[]).some(a=>t.startsWith(a));return s.mode==="include"?r:!r}function nat({config:s,preview:t=!1}){const[n,r]=j.useState(!1),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState({name:"",email:"",phone:""}),m=j.useRef(!1),p=async(N,S={})=>{if(!t)try{await q.from("widget_events").insert({user_id:s.user_id,app_slug:"lead_magnet",event_type:N,visitor_token:Rlr(),page_url:window.location.href,metadata:S})}catch{}};j.useEffect(()=>{if(t){r(!0);return}if(!Dlr(s.targeting))return;try{if(sessionStorage.getItem(O4t))return}catch{}const N=()=>{m.current||(m.current=!0,r(!0),p("impression"))};if(s.trigger_type==="immediate")N();else if(s.trigger_type==="delay"){const S=window.setTimeout(N,Math.max(0,s.trigger_value)*1e3);return()=>window.clearTimeout(S)}else if(s.trigger_type==="scroll"){const S=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight*100>=(s.trigger_value||30)&&N()};return window.addEventListener("scroll",S,{passive:!0}),()=>window.removeEventListener("scroll",S)}},[s,t]);const f=()=>{r(!1);try{sessionStorage.setItem(O4t,"1")}catch{}t||p("close")},x=async N=>{if(N.preventDefault(),t){o(!0);return}if(!(!u.email||!u.name)){d(!0);try{const{error:S}=await q.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:"lead_magnet",name:u.name,email:u.email,phone:u.phone||void 0,page_url:window.location.href}});if(S)throw S;p("lead_capture",{email:u.email}),o(!0),(s.delivery_method==="instant"||s.delivery_method==="both")&&s.download_url&&setTimeout(()=>{const A=document.createElement("a");A.href=s.download_url,A.target="_blank",A.rel="noopener",A.download="",document.body.appendChild(A),A.click(),A.remove()},600)}catch(S){console.error("lead magnet submit failed",S)}finally{d(!1)}}};if(!n)return null;const y=s.theme_color||"#2563eb",v=t?s.position==="bottom-left"?"absolute left-4 bottom-4":"absolute right-4 bottom-4":s.position==="bottom-left"?"fixed left-4 bottom-4 md:left-6 md:bottom-6":"fixed right-4 bottom-4 md:right-6 md:bottom-6";if(s.display_style==="bar")return e.jsxs("div",{className:t?"absolute left-0 right-0 bottom-0 z-10":"fixed left-0 right-0 bottom-0 z-[75]",style:{paddingBottom:"env(safe-area-inset-bottom)"},children:[e.jsx("div",{className:"text-white shadow-2xl",style:{background:`linear-gradient(90deg, ${y}, ${YY(y,-20)})`},children:e.jsxs("div",{className:"max-w-6xl mx-auto px-4 py-3 flex items-center gap-3 flex-wrap",children:[e.jsx(Ro,{className:"w-5 h-5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold truncate",children:s.title}),e.jsx("p",{className:"text-xs text-white/80 truncate",children:s.description})]}),e.jsx("button",{onClick:()=>{i(!0),p("expand")},className:"px-4 py-2 rounded-lg text-sm font-semibold bg-white shrink-0 hover:bg-white/95 transition",style:{color:y},children:s.download_label}),e.jsx("button",{onClick:f,className:"text-white/80 hover:text-white","aria-label":"Close",children:e.jsx(er,{className:"w-4 h-4"})})]})}),a&&b()]});if(!a)return e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>{i(!0),p("expand")},className:`${v} z-[75] group flex items-center gap-3 pl-3 pr-4 py-3 rounded-2xl shadow-2xl hover:shadow-3xl transition-all hover:scale-[1.03] animate-in fade-in slide-in-from-bottom-4 duration-500`,style:{background:`linear-gradient(135deg, ${y}, ${YY(y,-20)})`,paddingBottom:"env(safe-area-inset-bottom)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/20 backdrop-blur flex items-center justify-center text-white",children:e.jsx(ig,{className:"w-5 h-5"})}),e.jsxs("div",{className:"text-left text-white",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider opacity-90 font-semibold",children:s.badge_label}),e.jsx("div",{className:"text-sm font-bold leading-tight max-w-[180px] truncate",children:s.title})]}),e.jsx("button",{onClick:N=>{N.stopPropagation(),f()},className:"ml-1 w-6 h-6 rounded-full bg-white/20 hover:bg-white/30 flex items-center justify-center text-white","aria-label":"Close",children:e.jsx(er,{className:"w-3 h-3"})})]}),a&&b()]});return b();function b(){const N=s.form_fields||["name","email"],S=s.agent||{},A=[S.first_name,S.last_name].filter(Boolean).join(" ");return e.jsx("div",{className:t?"absolute inset-0 flex items-center justify-center p-4 z-20":"fixed inset-0 z-[85] flex items-center justify-center p-4",style:{background:t?"transparent":"rgba(0,0,0,0.6)"},onClick:()=>i(!1),children:e.jsxs("div",{className:"relative w-full max-w-lg bg-background rounded-2xl shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-300",onClick:T=>T.stopPropagation(),children:[e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",style:{background:`linear-gradient(135deg, ${y}, ${YY(y,-25)})`},children:[s.cover_image_url?e.jsx("img",{src:s.cover_image_url,alt:s.title,className:"w-full h-full object-cover opacity-90"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Ur,{className:"w-20 h-20 text-white/40"})}),e.jsxs("div",{className:"absolute top-3 left-3 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold bg-white shadow",style:{color:y},children:[e.jsx(Ro,{className:"w-3 h-3"}),s.badge_label]}),e.jsx("button",{onClick:()=>i(!1),className:"absolute top-3 right-3 w-8 h-8 rounded-full bg-white/95 hover:bg-white flex items-center justify-center text-foreground/70 hover:text-foreground transition","aria-label":"Close",children:e.jsx(er,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"p-6 sm:p-7 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:s.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:s.description})]}),l?e.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${y}10`},children:[e.jsx(pi,{className:"w-8 h-8 mx-auto",style:{color:y}}),e.jsx("p",{className:"text-sm font-medium",style:{color:y},children:s.success_message}),s.download_url&&e.jsx("a",{href:s.download_url,target:"_blank",rel:"noopener",className:"inline-block mt-2 text-xs underline",style:{color:y},children:"Click here if download didn't start"})]}):s.form_enabled?e.jsxs("form",{onSubmit:x,className:"space-y-2.5",children:[N.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:u.name,onChange:T=>h({...u,name:T.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":y},required:!0}),N.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:u.email,onChange:T=>h({...u,email:T.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":y},required:!0}),N.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:u.phone,onChange:T=>h({...u,phone:T.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":y}}),e.jsxs("button",{type:"submit",disabled:c,className:"w-full py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 active:scale-[0.99] transition disabled:opacity-60 inline-flex items-center justify-center gap-2",style:{background:`linear-gradient(135deg, ${y}, ${YY(y,-20)})`},children:[e.jsx(pi,{className:"w-4 h-4"}),c?"Sending...":s.download_label]}),e.jsx("p",{className:"text-[10px] text-center text-muted-foreground pt-1",children:"We'll email you a copy too. No spam — promise."})]}):e.jsx("a",{href:s.download_url||"#",target:"_blank",rel:"noopener",onClick:()=>p("cta_click",{url:s.download_url}),className:"block w-full text-center py-3 rounded-lg font-semibold text-white shadow-lg",style:{background:`linear-gradient(135deg, ${y}, ${YY(y,-20)})`},children:s.download_label}),A&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground",children:["Curated by ",A]})]})]})})}}function YY(s,t){try{const n=parseInt(s.slice(1),16),r=t<0?0:255,a=Math.abs(t)/100,i=n>>16,l=n>>8&255,o=n&255,c=Math.round((r-i)*a)+i,d=Math.round((r-l)*a)+l,u=Math.round((r-o)*a)+o;return"#"+(16777216+(c<<16)+(d<<8)+u).toString(16).slice(1)}catch{return s}}function rat({slug:s}){const[t,n]=j.useState(null);return j.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await q.rpc("get_public_lead_magnet_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(nat,{config:t}):null}function aat({siteConfig:s,className:t="",iconClassName:n=""}){var i;const r=((i=s==null?void 0:s.themeConfig)==null?void 0:i.socialLinks)||null;if(!r)return null;const a=[{key:"facebook",url:r.facebook,Icon:zp,label:"Facebook"},{key:"instagram",url:r.instagram,Icon:gm,label:"Instagram"},{key:"linkedin",url:r.linkedin,Icon:Gg,label:"LinkedIn"},{key:"youtube",url:r.youtube,Icon:Sq,label:"YouTube"}].filter(l=>!!l.url);return a.length?e.jsx("div",{className:`flex items-center gap-3 ${t}`,children:a.map(({key:l,url:o,Icon:c,label:d})=>e.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer","aria-label":d,className:`inline-flex items-center justify-center h-9 w-9 rounded-full border border-current/20 opacity-70 hover:opacity-100 transition-opacity ${n}`,children:e.jsx(c,{className:"h-4 w-4"})},l))}):null}const iat=` id, slug, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, description, video_link, mls_link, co_agent_name, co_agent_brokerage, co_agent_phone, co_agent_email, co_agent_photo_url, photos:listing_photos(id, photo_url, is_primary, sort_order) `;function urs(s){return ct({queryKey:["lead-site-exchange-listings",s],enabled:!!s,staleTime:5*60*1e3,queryFn:async()=>{const{data:t,error:n}=await q.from("listings").select(iat).eq("agent_id",s).eq("show_on_lead_site",!0).eq("is_approved",!0).neq("status","sold").order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function oat(s){return ct({queryKey:["lead-site-sold-listings",s],enabled:!!s,staleTime:5*60*1e3,queryFn:async()=>{const{data:t,error:n}=await q.from("listings").select(iat).eq("agent_id",s).eq("show_on_lead_site",!0).eq("is_approved",!0).eq("status","sold").order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function Mxr(s,t){return ct({queryKey:["lead-site-exchange-listing",s,t],enabled:!!s&&!!t,queryFn:async()=>{const n=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t);let r=q.from("listings").select(iat).eq("agent_id",s).eq("show_on_lead_site",!0).eq("is_approved",!0);r=n?r.eq("id",t):r.eq("slug",t);const{data:a,error:i}=await r.maybeSingle();if(i)throw i;return a??null}})}function Pxr(s){var t;return(t=s==null?void 0:s.photos)!=null&&t.length?[...s.photos].sort((n,r)=>Number(r.is_primary)-Number(n.is_primary)||(n.sort_order??0)-(r.sort_order??0)).map(n=>n.photo_url):[]}function Lxr(s){return s?`$${s.toLocaleString()}`:"Price upon request"}function Olr({children:s,siteConfig:t}){var ke,Te,Me,Oe,Se,Qe,Ae,Fe,Ne;const n=Od(),r=Wn(),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState([]),[m,p]=j.useState([]),[f,x]=j.useState(null),y=j.useRef(null),v=j.useRef(null),{user:b,profile:N,signOut:S}=YIe();Art(t,b==null?void 0:b.id),Ert(t,b==null?void 0:b.id);const A=((ke=t.agent)==null?void 0:ke.full_name)||"Agent",T=t.siteTitle||`${A} Real Estate`,L=n.pathname==="/search",M=n.pathname==="/",I=t.leadRegistrationMode!=="disabled";j.useEffect(()=>{(async()=>{const{data:Ve}=await q.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order",{ascending:!0});h(Ve||[])})()},[t.id]),j.useEffect(()=>{(async()=>{const{data:Ve}=await q.from("lead_site_menu_items").select("*").eq("site_id",t.id).eq("is_visible",!0).order("sort_order",{ascending:!0});p(Ve||[])})()},[t.id]),j.useEffect(()=>{const $e=Ve=>{y.current&&!y.current.contains(Ve.target)&&d(!1),v.current&&!v.current.contains(Ve.target)&&x(null)};return document.addEventListener("mousedown",$e),()=>document.removeEventListener("mousedown",$e)},[]);const R=Nrt(t),z=t==null?void 0:t.bookingUrl,{data:$}=urs(R?t.agentId:null),H=(($==null?void 0:$.length)??0)>0,{data:V}=oat(t.agentId),K=((V==null?void 0:V.length)??0)>0,Z=R?m.filter($e=>{const Ve=String($e.target_url||"").toLowerCase(),qe=String($e.label||"").toLowerCase();return Ve!=="/search"&&!Ve.startsWith("/search?")&&!qe.includes("search")}):m,Q=R&&H&&Z.length>0&&!Z.some($e=>String($e.target_url||"").toLowerCase().startsWith("/listings"))?[...Z,{id:"__my-listings",label:"My Listings",target_url:"/listings",parent_id:null,is_visible:!0}]:Z,le=Q.length>0,ue=[{to:"/",label:"Home"},...R?[]:[{to:"/search",label:"Search"}],...R&&H?[{to:"/listings",label:"My Listings"}]:[],...K?[{to:"/sold",label:"Sold"}]:[],{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],se=le?[]:ue,ne=Q.filter($e=>!$e.parent_id),ie=$e=>Q.filter(Ve=>Ve.parent_id===$e),ce=M?"bg-transparent text-white":"bg-white/95 backdrop-blur text-gray-900 border-b border-gray-100 shadow-sm",je=t.siteTitle||`${A} - Real Estate`,be=t.siteTagline||`Browse homes and listings with ${A}`,he=t.ogImageUrl||((Te=t.agent)==null?void 0:Te.avatar_url)||"",ge=`https://${t.subdomainSlug||""}.thelocalmove.com`;return e.jsxs("div",{className:`flex flex-col ${L?"h-screen overflow-hidden":"min-h-screen"} bg-white`,children:[e.jsx(Srt,{siteConfig:t,pagePath:n.pathname}),e.jsx(Crt,{siteConfig:t}),e.jsxs(dl,{children:[e.jsx("title",{children:je}),e.jsx("meta",{name:"description",content:be}),e.jsx("meta",{property:"og:title",content:je}),e.jsx("meta",{property:"og:description",content:be}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:ge+n.pathname}),he&&e.jsx("meta",{property:"og:image",content:he}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:je}),e.jsx("meta",{name:"twitter:description",content:be}),he&&e.jsx("meta",{name:"twitter:image",content:he}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${ge}${n.pathname}`}),t.subdomainSlug==="matthogg"&&e.jsx("script",{src:"https://analytics.ahrefs.com/analytics.js","data-key":"kyFjzruyvE0yTdMokzgCBw",async:!0})]}),e.jsxs("header",{className:`${M?"absolute":"sticky"} top-0 left-0 right-0 z-50 transition-all ${ce}`,children:[e.jsx("div",{className:"max-w-7xl mx-auto px-6 lg:px-8",children:e.jsxs("div",{className:"flex items-center justify-between h-20",children:[e.jsxs(xr,{to:"/",className:"flex items-center gap-3",children:[t.showTeamLogo&&t.teamLogoUrl?e.jsx("img",{src:t.teamLogoUrl,alt:`${T} logo`,className:"h-10 sm:h-12 w-auto max-w-[180px] object-contain"}):(Me=t.agent)!=null&&Me.avatar_url?e.jsx("img",{src:t.agent.avatar_url,alt:A,className:"h-10 w-10 rounded-full object-cover ring-2 ring-white/20"}):null,e.jsx("div",{children:e.jsx("span",{className:"font-bold text-lg leading-none tracking-tight",children:T})})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[t.bookingUrl&&e.jsx(VA,{bookingUrl:t.bookingUrl,label:"Schedule",size:"sm",className:"order-last ml-3",source:"nav"}),se.map($e=>e.jsx(xr,{to:$e.to,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${n.pathname===$e.to?M?"bg-white/15 text-white":"bg-gray-100 text-gray-900":M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:$e.label},$e.to)),le&&ne.map($e=>{if($e.item_type==="dropdown"){const Ve=ie($e.id);return e.jsxs("div",{ref:v,className:"relative",children:[e.jsxs("button",{onClick:()=>x(f===$e.id?null:$e.id),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[$e.label," ",e.jsx(rl,{className:`h-3.5 w-3.5 transition-transform ${f===$e.id?"rotate-180":""}`})]}),f===$e.id&&Ve.length>0&&e.jsx("div",{className:"absolute top-full right-0 mt-2 w-52 bg-white rounded-xl shadow-xl border border-gray-100 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:Ve.map(qe=>e.jsx(tde,{item:qe,onClick:()=>x(null),className:"w-full text-left px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 hover:text-gray-900 transition-colors block"},qe.id))})]},$e.id)}return e.jsx(tde,{item:$e,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`},$e.id)}),u.length>0&&e.jsxs("div",{ref:y,className:"relative",children:[e.jsxs("button",{onClick:()=>d(!c),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${n.pathname.startsWith("/homes-for-sale-in-")?M?"bg-white/15 text-white":"bg-gray-100 text-gray-900":M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:["Cities ",e.jsx(rl,{className:`h-3.5 w-3.5 transition-transform ${c?"rotate-180":""}`})]}),c&&e.jsx("div",{className:"absolute top-full right-0 mt-2 w-52 bg-white rounded-xl shadow-xl border border-gray-100 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:u.map($e=>e.jsx("button",{onClick:()=>{r(`/homes-for-sale-in-${$e.city_slug}`),d(!1)},className:"w-full text-left px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 hover:text-gray-900 transition-colors",children:$e.city_name},$e.city_slug))})]}),b?e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsxs(xr,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(ko,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Saved"})]}),e.jsxs(xr,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${M?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(So,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:((Oe=N==null?void 0:N.name)==null?void 0:Oe.split(" ")[0])||"Account"})]})]}):I?e.jsx("button",{onClick:()=>o(!0),className:`ml-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${M?"bg-white/15 text-white hover:bg-white/25":"bg-blue-600 text-white hover:bg-blue-700"}`,children:"Sign In"}):null]}),e.jsx("button",{onClick:()=>i(!a),className:`md:hidden p-2 rounded-lg ${M?"text-white hover:bg-white/10":"text-gray-600 hover:bg-gray-100"}`,children:a?e.jsx(er,{className:"h-5 w-5"}):e.jsx(AA,{className:"h-5 w-5"})})]})}),a&&e.jsx("div",{className:`md:hidden border-t ${M?"border-white/10 bg-black/95 backdrop-blur":"border-gray-100 bg-white"} max-h-[calc(100vh-5rem)] overflow-y-auto overscroll-contain`,children:e.jsxs("div",{className:"px-4 py-3 space-y-1 pb-8",children:[t.bookingUrl&&e.jsx(VA,{bookingUrl:t.bookingUrl,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),se.map($e=>e.jsx(xr,{to:$e.to,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${n.pathname===$e.to?M?"bg-white/15 text-white":"bg-gray-100 text-gray-900":M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:$e.label},$e.to)),le&&ne.map($e=>{if($e.item_type==="dropdown"){const Ve=ie($e.id);return e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${M?"text-white/40":"text-gray-400"}`,children:$e.label}),Ve.map(qe=>e.jsx(tde,{item:qe,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},qe.id))]},$e.id)}return e.jsx(tde,{item:$e,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},$e.id)}),u.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${M?"text-white/40":"text-gray-400"}`,children:"Cities"}),u.map($e=>e.jsx(xr,{to:`/homes-for-sale-in-${$e.city_slug}`,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${n.pathname===`/homes-for-sale-in-${$e.city_slug}`?M?"bg-white/15 text-white":"bg-gray-100 text-gray-900":M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:$e.city_name},$e.city_slug))]}),b?e.jsxs(e.Fragment,{children:[e.jsx(xr,{to:"/account",onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:"My Account"}),e.jsx("button",{onClick:async()=>{await S(),i(!1)},className:`block w-full text-left px-3 py-2.5 rounded-lg text-sm font-medium ${M?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:"Sign Out"})]}):I?e.jsx("button",{onClick:()=>{o(!0),i(!1)},className:`block w-full text-left px-3 py-2.5 rounded-lg text-sm font-medium ${M?"text-white/70 hover:bg-white/10":"text-blue-600 hover:bg-blue-50"}`,children:"Sign In / Register"}):null]})})]}),e.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:s}),!L&&e.jsx("footer",{className:"bg-gray-950 text-gray-400",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-16",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-12",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[((Se=t.agent)==null?void 0:Se.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:A,className:"h-16 w-16 rounded-2xl object-cover ring-2 ring-white/10"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-white text-lg tracking-tight",children:A}),e.jsx("p",{className:"text-sm text-gray-500",children:((Qe=t.agent)==null?void 0:Qe.title)||"Real Estate Professional"})]})]}),((Ae=t.agent)==null?void 0:Ae.phone)&&e.jsx("p",{className:"text-sm mt-3",children:e.jsxs("a",{href:`tel:${t.agent.phone}`,className:"hover:text-white transition-colors flex items-center gap-2",children:[e.jsx(ba,{className:"h-3.5 w-3.5"})," ",t.agent.phone]})}),((Fe=t.agent)==null?void 0:Fe.email)&&e.jsx("p",{className:"text-sm mt-1",children:e.jsxs("a",{href:`mailto:${t.agent.email}`,className:"hover:text-white transition-colors flex items-center gap-2",children:[e.jsx(ln,{className:"h-3.5 w-3.5"})," ",t.agent.email]})}),e.jsx(aat,{siteConfig:t,className:"mt-4"})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),e.jsxs("ul",{className:"space-y-3 text-sm",children:[se.map($e=>e.jsx("li",{children:e.jsx(xr,{to:$e.to,className:"hover:text-white transition-colors",children:$e.label})},$e.to)),z&&e.jsx("li",{children:e.jsx("a",{href:z,target:"_blank",rel:"noopener noreferrer",className:"hover:text-white transition-colors",children:"Schedule a Call"})})]}),u.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"font-semibold text-white mt-8 mb-4 text-sm tracking-wider uppercase",children:"Local Areas"}),e.jsx("ul",{className:"space-y-3 text-sm",children:u.map($e=>e.jsx("li",{children:e.jsx(xr,{to:`/homes-for-sale-in-${$e.city_slug}`,className:"hover:text-white transition-colors",children:$e.city_name})},$e.city_slug))})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Get In Touch"}),e.jsx("p",{className:"text-sm text-gray-500 leading-relaxed mb-4",children:R?"Have a real estate question or need a trusted connection? Get in touch today.":"Ready to find your dream home? Get in touch today for a personalized consultation."}),e.jsx(xr,{to:"/contact",className:"inline-block px-5 py-2.5 bg-white text-gray-900 text-sm font-semibold rounded-lg hover:bg-gray-100 transition-colors",children:"Contact Me"})]})]}),e.jsxs("div",{className:"mt-14 pt-6 border-t border-gray-800/50",children:[t.showTeamLogo&&t.teamLogoUrl&&e.jsx("div",{className:"flex items-center justify-center mb-6",children:e.jsx("img",{src:t.teamLogoUrl,alt:"Team",className:"h-12 w-auto object-contain"})}),t.brokerageLegalName&&e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-xs text-gray-500 mb-3",children:[e.jsxs("span",{children:[A," · ",t.brokerageLegalName]}),t.agentLicenseNumber&&e.jsx("span",{children:t.agentLicenseNumber}),t.brokerageLicenseNumber&&e.jsxs("span",{children:["Brokerage #",t.brokerageLicenseNumber]})]}),t.mlsDisclaimerText&&e.jsxs("div",{className:"flex items-start justify-center gap-3 mb-4",children:[t.mlsLogoUrl&&e.jsx("img",{src:t.mlsLogoUrl,alt:"MLS",className:"h-8 w-auto flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-[11px] text-gray-600 leading-relaxed max-w-3xl text-center",children:t.mlsDisclaimerText})]}),e.jsxs("div",{className:"flex items-center justify-center gap-4 text-xs text-gray-600",children:[t.equalHousingEnabled&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"h-5 w-5 text-gray-500",children:e.jsx("path",{d:"M12 2L2 8v2h20V8L12 2zm0 2.5L18.5 8h-13L12 4.5zM4 12v8h4v-6h8v6h4v-8H4zm6 8v-4h4v4h-4z"})}),e.jsx("span",{children:"Equal Housing Opportunity"})]}),e.jsxs("span",{children:["© ",new Date().getFullYear()," ",A,". Powered by LevelUp."]})]})]})]})}),!L&&((Ne=t.agent)==null?void 0:Ne.avatar_url)&&e.jsx(Flr,{agent:t.agent,bookingUrl:z}),l&&e.jsx(krt,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1)}),e.jsx(tat,{slug:t.subdomainSlug}),e.jsx(sat,{slug:t.subdomainSlug}),e.jsx(rat,{slug:t.subdomainSlug})]})}function Flr({agent:s,bookingUrl:t}){var i;const[n,r]=j.useState(!1),a=Wn();return s?e.jsx("div",{className:"fixed bottom-6 right-6 z-40",children:n?e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl border border-gray-200 w-72 overflow-hidden animate-in slide-in-from-bottom-4 fade-in duration-200",children:[e.jsxs("div",{className:"p-5",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("img",{src:s.avatar_url,alt:s.full_name,className:"h-12 w-12 rounded-full object-cover ring-2 ring-gray-100"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-gray-900 text-sm",children:s.full_name}),e.jsx("p",{className:"text-xs text-gray-500",children:s.title||"Real Estate Professional"})]})]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"Have questions about a property or the area? I'm here to help!"}),e.jsxs("div",{className:"space-y-2",children:[s.phone&&e.jsxs("a",{href:`tel:${s.phone}`,className:"flex items-center gap-2 w-full px-3 py-2 bg-gray-50 hover:bg-gray-100 rounded-xl text-sm text-gray-700 transition-colors",children:[e.jsx(ba,{className:"h-4 w-4 text-gray-400"}),s.phone]}),s.email&&e.jsxs("a",{href:`mailto:${s.email}`,className:"flex items-center gap-2 w-full px-3 py-2 bg-gray-50 hover:bg-gray-100 rounded-xl text-sm text-gray-700 transition-colors",children:[e.jsx(ln,{className:"h-4 w-4 text-gray-400"}),"Email Me"]}),e.jsx("button",{onClick:()=>{r(!1),a("/contact")},className:"w-full px-3 py-2.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold rounded-xl transition-colors",children:"Ask a Question"}),t&&e.jsx("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"block text-center w-full px-3 py-2.5 bg-gray-900 hover:bg-gray-800 text-white text-sm font-semibold rounded-xl transition-colors",children:"Schedule a Call"})]})]}),e.jsx("button",{onClick:()=>r(!1),className:"absolute top-3 right-3 p-1 text-gray-400 hover:text-gray-600 rounded-full hover:bg-gray-100",children:e.jsx(er,{className:"h-4 w-4"})})]}):e.jsxs("button",{onClick:()=>r(!0),className:"group flex items-center gap-3 bg-white pl-1.5 pr-5 py-1.5 rounded-full shadow-xl border border-gray-200 hover:shadow-2xl transition-all hover:scale-105",children:[e.jsx("img",{src:s.avatar_url,alt:s.full_name,className:"h-10 w-10 rounded-full object-cover ring-2 ring-blue-100"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-xs font-bold text-gray-900 leading-none",children:(i=s.full_name)==null?void 0:i.split(" ")[0]}),e.jsx("p",{className:"text-[10px] text-blue-600 font-medium mt-0.5",children:"Chat with me →"})]})]})}):null}function tde({item:s,className:t,onClick:n}){const r=s.target_url||"#";return s.item_type==="external"||s.open_in_new_tab?e.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:t,onClick:n,children:s.label}):e.jsx(xr,{to:r,className:t,onClick:n,children:s.label})}const z4t={california:"California DRE License",ca:"California DRE License"};function XKe(s){const t=(s||"").trim();if(!t)return"Real Estate License";const n=t.toLowerCase();return z4t[n]?z4t[n]:`${t.replace(/\b\w/g,a=>a.toUpperCase())} Real Estate License`}function B4t(s){if(s)return s.replace(/^\s*DRE\s*#?\s*/i,"").replace(/^\s*#/,"").trim()||void 0}function zlr({children:s,siteConfig:t}){var Oe,Se,Qe,Ae,Fe,Ne,$e,Ve;const n=Od(),r=Wn(),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,p]=j.useState([]),[f,x]=j.useState(!1),y=j.useRef(null),v=j.useRef(null),{user:b,profile:N,signOut:S}=YIe();Art(t,b==null?void 0:b.id),Ert(t,b==null?void 0:b.id);const A=((Oe=t.agent)==null?void 0:Oe.full_name)||"Agent",T=B4t(t.agentLicenseNumber),L=B4t(t.brokerageLicenseNumber),M=t.siteTitle||`${A} Real Estate`,I=qe=>{if(!qe)return qe;const Ze=A.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ue=new RegExp(`^\\s*${Ze}\\s*[|\\-–—:]\\s*`,"i");return qe.replace(Ue,"").trim()},R=M&&M!==`${A} Real Estate`?M:null,z=R?I(R):null,$=z&&z.toLowerCase()!==A.toLowerCase()?z:null,H=n.pathname==="/search",V=n.pathname==="/",K=t.leadRegistrationMode!=="disabled",Z="#c9a96e",Q=t.bookingUrl;j.useEffect(()=>{const qe=()=>x(window.scrollY>80);return window.addEventListener("scroll",qe,{passive:!0}),()=>window.removeEventListener("scroll",qe)},[]),j.useEffect(()=>{(async()=>{const{data:Ze}=await q.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order",{ascending:!0});p(Ze||[])})()},[t.id]),j.useEffect(()=>{const qe=Ze=>{y.current&&!y.current.contains(Ze.target)&&d(!1),v.current&&!v.current.contains(Ze.target)&&h(!1)};return document.addEventListener("mousedown",qe),()=>document.removeEventListener("mousedown",qe)},[]);const le=(((Se=t.themeConfig)==null?void 0:Se.focusPages)??[]).filter(qe=>qe==null?void 0:qe.slug).map(qe=>({to:`/${qe.slug}`,label:qe.navLabel||qe.title})),ue=wWt(t)||Nrt(t),{data:se}=urs(ue?t.agentId:null),ne=((se==null?void 0:se.length)??0)>0,{data:ie}=oat(t.agentId),ce=((ie==null?void 0:ie.length)??0)>0,je=[{to:"/",label:"Home"},...ue?ne?[{to:"/listings",label:"My Listings"}]:[]:[{to:"/search",label:"Search"}],...ce?[{to:"/sold",label:"Sold"}]:[],{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],be=[...je,...le],he=t.siteTitle||`${A} - Real Estate`,ge=t.siteTagline||`Browse homes and listings with ${A}`,ke=t.ogImageUrl||((Qe=t.agent)==null?void 0:Qe.avatar_url)||"",Te=`https://${t.subdomainSlug||""}.thelocalmove.com`,Me=V?f?"bg-[#0d0b0a]/95 backdrop-blur-lg border-b border-white/5":"bg-transparent":"bg-[#0d0b0a] border-b border-white/5";return e.jsxs("div",{className:`flex flex-col ${H?"h-screen overflow-hidden":"min-h-screen"} bg-[#0d0b0a]`,children:[e.jsx(Srt,{siteConfig:t,pagePath:n.pathname}),e.jsx(Crt,{siteConfig:t}),e.jsxs(dl,{children:[e.jsx("title",{children:he}),e.jsx("meta",{name:"description",content:ge}),e.jsx("meta",{property:"og:title",content:he}),e.jsx("meta",{property:"og:description",content:ge}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:Te+n.pathname}),ke&&e.jsx("meta",{property:"og:image",content:ke}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:he}),e.jsx("meta",{name:"twitter:description",content:ge}),ke&&e.jsx("meta",{name:"twitter:image",content:ke}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${Te}${n.pathname}`}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,400;0,500;0,600;0,700;1,400;1,500&display=swap",rel:"stylesheet"})]}),e.jsxs("header",{className:`${V?"fixed":"sticky"} top-0 left-0 right-0 z-50 transition-all duration-500 ${Me}`,children:[e.jsx("div",{className:"max-w-7xl mx-auto px-6 lg:px-8",children:e.jsxs("div",{className:"flex items-center justify-between min-h-20 py-3 gap-6",children:[e.jsxs(xr,{to:"/",className:"flex items-center gap-3 shrink-0",children:[t.showTeamLogo&&t.teamLogoUrl&&e.jsx("img",{src:t.teamLogoUrl,alt:`${A} brokerage logo`,className:"h-9 sm:h-11 w-auto max-w-[150px] object-contain"}),e.jsxs("span",{className:"flex flex-col leading-tight",children:[e.jsx("span",{className:"block whitespace-nowrap text-white text-base sm:text-lg xl:text-xl tracking-tight",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:A}),t.brokerageLegalName&&e.jsx("span",{className:"hidden sm:block whitespace-nowrap text-[10px] sm:text-[11px] tracking-[0.14em] uppercase text-white/60",children:t.brokerageLegalName}),$&&e.jsx("span",{className:"hidden xl:block whitespace-nowrap text-[10px] tracking-[0.18em] uppercase text-white/40",children:$})]})]}),e.jsxs("nav",{className:"hidden lg:flex items-center justify-end gap-0 flex-1 min-w-0",children:[je.map(qe=>e.jsx(xr,{to:qe.to,className:`whitespace-nowrap px-2.5 xl:px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${n.pathname===qe.to?"text-white":"text-white/40 hover:text-white"}`,children:qe.label},qe.to)),le.length>0&&e.jsxs("div",{ref:v,className:"relative",children:[e.jsxs("button",{onClick:()=>h(!u),className:`flex items-center gap-1 whitespace-nowrap px-2.5 xl:px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${le.some(qe=>n.pathname===qe.to)?"text-white":"text-white/40 hover:text-white"}`,children:["Specialty"," ",e.jsx(rl,{className:`h-3 w-3 transition-transform ${u?"rotate-180":""}`})]}),u&&e.jsx("div",{className:"absolute top-full right-0 mt-2 w-56 bg-[#1a1715] border border-white/10 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:le.map(qe=>e.jsx(xr,{to:qe.to,onClick:()=>h(!1),className:`block px-5 py-2.5 text-xs tracking-wider text-white/50 hover:text-white hover:bg-white/5 uppercase transition-colors ${n.pathname===qe.to?"text-white":""}`,children:qe.label},qe.to))})]}),m.length>0&&e.jsxs("div",{ref:y,className:"relative",children:[e.jsxs("button",{onClick:()=>d(!c),className:`flex items-center gap-1 whitespace-nowrap px-2.5 xl:px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${n.pathname.startsWith("/homes-for-sale-in-")?"text-white":"text-white/40 hover:text-white"}`,children:["Cities ",e.jsx(rl,{className:`h-3 w-3 transition-transform ${c?"rotate-180":""}`})]}),c&&e.jsx("div",{className:"absolute top-full right-0 mt-2 w-56 bg-[#1a1715] border border-white/10 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:m.map(qe=>e.jsx("button",{onClick:()=>{r(`/homes-for-sale-in-${qe.city_slug}`),d(!1)},className:"w-full text-left px-5 py-2.5 text-xs tracking-wider text-white/50 hover:text-white hover:bg-white/5 uppercase transition-colors",children:qe.city_name},qe.city_slug))})]}),b?e.jsxs("div",{className:"flex items-center gap-1 ml-3",children:[e.jsxs(xr,{to:"/account",className:"flex items-center gap-1.5 px-3 py-2 text-xs tracking-wider text-white/40 hover:text-white uppercase transition-colors",children:[e.jsx(ko,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:"Saved"})]}),e.jsxs(xr,{to:"/account",className:"flex items-center gap-1.5 px-3 py-2 text-xs tracking-wider text-white/40 hover:text-white uppercase transition-colors",children:[e.jsx(So,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:((Ae=N==null?void 0:N.name)==null?void 0:Ae.split(" ")[0])||"Account"})]})]}):K?e.jsx("button",{onClick:()=>o(!0),className:"ml-3 px-5 py-2 text-xs tracking-[0.2em] uppercase border border-white/20 text-white/60 hover:bg-white hover:text-black transition-all duration-500",children:"Sign In"}):null,Q&&e.jsx(VA,{bookingUrl:Q,label:"Schedule",size:"sm",className:"ml-3",source:"nav"})]}),e.jsxs("button",{onClick:()=>i(!a),className:"lg:hidden p-2 text-white/60 hover:text-white",children:[e.jsx("div",{className:"flex flex-col items-center gap-0.5",children:a?e.jsx(er,{className:"h-5 w-5"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-6 h-px bg-current"}),e.jsx("div",{className:"w-4 h-px bg-current mt-1.5"}),e.jsx("div",{className:"w-6 h-px bg-current mt-1.5"})]})}),e.jsx("span",{className:"text-[8px] tracking-[0.3em] uppercase mt-1 block",children:"MENU"})]})]})}),a&&e.jsx("div",{className:"lg:hidden border-t border-white/5 bg-[#0d0b0a]/98 backdrop-blur-lg",children:e.jsxs("div",{className:"px-6 py-4 space-y-1",children:[Q&&e.jsx(VA,{bookingUrl:Q,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),je.map(qe=>e.jsx(xr,{to:qe.to,onClick:()=>i(!1),className:`block px-3 py-3 text-xs tracking-[0.2em] uppercase transition-colors ${n.pathname===qe.to?"text-white":"text-white/40 hover:text-white"}`,children:qe.label},qe.to)),le.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 pt-4 pb-2 text-[10px] tracking-[0.3em] uppercase",style:{color:Z},children:"Specialty"}),le.map(qe=>e.jsx(xr,{to:qe.to,onClick:()=>i(!1),className:`block px-3 py-2.5 text-xs tracking-wider uppercase transition-colors ${n.pathname===qe.to?"text-white":"text-white/40 hover:text-white"}`,children:qe.label},qe.to))]}),m.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 pt-4 pb-2 text-[10px] tracking-[0.3em] uppercase",style:{color:Z},children:"Cities"}),m.map(qe=>e.jsx(xr,{to:`/homes-for-sale-in-${qe.city_slug}`,onClick:()=>i(!1),className:"block px-3 py-2.5 text-xs tracking-wider text-white/40 hover:text-white uppercase transition-colors",children:qe.city_name},qe.city_slug))]}),b?e.jsxs(e.Fragment,{children:[e.jsx(xr,{to:"/account",onClick:()=>i(!1),className:"block px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"My Account"}),e.jsx("button",{onClick:async()=>{await S(),i(!1)},className:"block w-full text-left px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"Sign Out"})]}):K?e.jsx("button",{onClick:()=>{o(!0),i(!1)},className:"block w-full text-left px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"Sign In / Register"}):null]})})]}),e.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:s}),!H&&e.jsx("footer",{className:"bg-[#0a0908] text-white/70 border-t border-white/10",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-20",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-16",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-white text-xl tracking-tight mb-3",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:A}),e.jsx("p",{className:"text-white/70 text-xs tracking-[0.15em] uppercase mb-6",children:((Fe=t.agent)==null?void 0:Fe.title)||"Real Estate Professional"}),(T||L)&&e.jsxs("div",{className:"mb-6 p-4 border border-white/10 bg-white/5",children:[T&&e.jsxs("p",{className:"text-sm text-white font-medium tracking-wide",children:[XKe(t.licenseState)," #",T]}),L&&e.jsxs("p",{className:"text-xs text-white/70 tracking-wider uppercase mt-1",children:["Brokerage License #",L]})]}),((Ne=t.agent)==null?void 0:Ne.phone)&&e.jsxs("a",{href:`tel:${t.agent.phone}`,className:"flex items-center gap-3 text-sm text-white/70 hover:text-white transition-colors mb-3",children:[e.jsx(ba,{className:"h-3.5 w-3.5"})," ",t.agent.phone]}),(($e=t.agent)==null?void 0:$e.email)&&e.jsxs("a",{href:`mailto:${t.agent.email}`,className:"flex items-center gap-3 text-sm text-white/70 hover:text-white transition-colors",children:[e.jsx(ln,{className:"h-3.5 w-3.5"})," ",t.agent.email]}),e.jsx(aat,{siteConfig:t,className:"mt-6",iconClassName:"border-white/20"})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6 text-white",style:{color:Z},children:"Quick Links"}),e.jsxs("ul",{className:"space-y-3",children:[be.map(qe=>e.jsx("li",{children:e.jsx(xr,{to:qe.to,className:"text-xs tracking-wider uppercase text-white/70 hover:text-white transition-colors",children:qe.label})},qe.to)),Q&&e.jsx("li",{children:e.jsx("a",{href:Q,target:"_blank",rel:"noopener noreferrer",className:"text-xs tracking-wider uppercase transition-colors hover:opacity-80",style:{color:SW},children:"Schedule a Free Consultation"})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6 text-white",style:{color:Z},children:"Get In Touch"}),e.jsx("p",{className:"text-sm text-white/70 leading-relaxed mb-6",style:{fontFamily:"'Playfair Display', Georgia, serif",fontStyle:"italic"},children:"Ready to experience luxury real estate? Let's connect."}),e.jsxs("div",{className:"flex flex-col items-start gap-3",children:[Q&&e.jsx(VA,{bookingUrl:Q,label:"Schedule a Free Consultation",size:"sm",source:"footer"}),e.jsx(xr,{to:"/contact",className:"inline-block px-8 py-3 text-xs tracking-[0.3em] uppercase border border-white/20 text-white/90 hover:bg-white hover:text-black transition-all duration-500",children:"Contact Me"})]})]})]}),e.jsxs("div",{className:"mt-16 pt-8 border-t border-white/10",children:[t.showTeamLogo&&t.teamLogoUrl&&e.jsx("div",{className:"flex items-center justify-center mb-6",children:e.jsx("img",{src:t.teamLogoUrl,alt:"Team",className:"h-10 w-auto object-contain opacity-70"})}),t.brokerageLegalName&&e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-[11px] text-white/70 tracking-wider uppercase mb-3",children:[e.jsxs("span",{children:[A," · ",t.brokerageLegalName]}),T&&e.jsxs("span",{children:[XKe(t.licenseState)," #",T]}),L&&e.jsxs("span",{children:["Brokerage #",L]})]}),t.mlsDisclaimerText&&e.jsxs("div",{className:"flex items-start justify-center gap-3 mb-4",children:[t.mlsLogoUrl&&e.jsx("img",{src:t.mlsLogoUrl,alt:"MLS",className:"h-6 w-auto flex-shrink-0 mt-0.5 opacity-70"}),e.jsx("p",{className:"text-[11px] text-white/70 leading-relaxed max-w-3xl text-center",children:t.mlsDisclaimerText})]}),e.jsxs("div",{className:"flex items-center justify-center gap-4 text-[11px] text-white/70 tracking-wider uppercase",children:[t.equalHousingEnabled&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"h-4 w-4",children:e.jsx("path",{d:"M12 2L2 8v2h20V8L12 2zm0 2.5L18.5 8h-13L12 4.5zM4 12v8h4v-6h8v6h4v-8H4zm6 8v-4h4v4h-4z"})}),e.jsx("span",{children:"Equal Housing Opportunity"})]}),e.jsxs("span",{children:["© ",new Date().getFullYear()," ",A,". Powered by LevelUp."]})]})]})]})}),!H&&((Ve=t.agent)==null?void 0:Ve.avatar_url)&&e.jsx(Blr,{agent:t.agent,agentLicense:T,siteConfig:t,accentColor:Z}),l&&e.jsx(krt,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1),theme:"luxury",accentColor:Z}),e.jsx(tat,{slug:t.subdomainSlug}),e.jsx(sat,{slug:t.subdomainSlug}),e.jsx(rat,{slug:t.subdomainSlug})]})}function Blr({agent:s,agentLicense:t,siteConfig:n,accentColor:r}){var o;const[a,i]=j.useState(!1),l=Wn();return s?e.jsx("div",{className:"fixed bottom-6 right-6 z-40",children:a?e.jsxs("div",{className:"bg-[#1a1715] border border-white/10 w-72 overflow-hidden animate-in slide-in-from-bottom-4 fade-in duration-200",children:[e.jsxs("div",{className:"p-5",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("img",{src:s.avatar_url,alt:s.full_name,className:"h-12 w-12 rounded-full object-cover ring-1 ring-white/10"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-white text-sm font-medium",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:s.full_name}),e.jsx("p",{className:"text-white/50 text-[10px] tracking-[0.1em] uppercase",children:s.title||"Real Estate Professional"})]})]}),t&&e.jsxs("div",{className:"mb-3 px-3 py-2 bg-white/5 border border-white/10",children:[e.jsx("p",{className:"text-[10px] text-white/50 tracking-wider uppercase",children:XKe(n.licenseState)}),e.jsxs("p",{className:"text-xs text-white font-medium",children:["#",t]})]}),e.jsxs("div",{className:"space-y-2",children:[s.phone&&e.jsxs("a",{href:`tel:${s.phone}`,className:"flex items-center gap-2 w-full px-3 py-2.5 bg-white/5 hover:bg-white/10 text-xs text-white/70 hover:text-white transition-colors tracking-wider",children:[e.jsx(ba,{className:"h-3.5 w-3.5"})," ",s.phone]}),s.email&&e.jsxs("a",{href:`mailto:${s.email}`,className:"flex items-center gap-2 w-full px-3 py-2.5 bg-white/5 hover:bg-white/10 text-xs text-white/70 hover:text-white transition-colors tracking-wider",children:[e.jsx(ln,{className:"h-3.5 w-3.5"})," Email Me"]}),e.jsx("button",{onClick:()=>{i(!1),l("/contact")},className:"w-full px-3 py-2.5 text-xs tracking-[0.2em] uppercase text-black hover:opacity-90 transition-colors",style:{backgroundColor:r},children:"Send a Message"})]})]}),e.jsx("button",{onClick:()=>i(!1),className:"absolute top-3 right-3 p-1 text-white/20 hover:text-white/50",children:e.jsx(er,{className:"h-4 w-4"})})]}):e.jsxs("button",{onClick:()=>i(!0),className:"group flex items-center gap-3 bg-[#1a1715] border border-white/10 pl-1.5 pr-5 py-1.5 hover:border-white/20 transition-all",children:[e.jsx("img",{src:s.avatar_url,alt:s.full_name,className:"h-10 w-10 rounded-full object-cover ring-1 ring-white/10"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-[11px] text-white leading-none",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:(o=s.full_name)==null?void 0:o.split(" ")[0]}),e.jsx("p",{className:"text-[9px] tracking-[0.15em] uppercase mt-1",style:{color:r},children:"Let's connect →"})]})]})}):null}const ZY="#2c1810",x5="#b8860b";function Ulr({children:s,siteConfig:t}){var R,z,$;const n=Od();Wn();const[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState([]),[h,m]=j.useState(!1),p=j.useRef(null),{user:f,profile:x,signOut:y}=YIe();Art(t,f==null?void 0:f.id),Ert(t,f==null?void 0:f.id);const v=((R=t.agent)==null?void 0:R.full_name)||"Agent",b=t.siteTitle||`${v} Land & Ranch`,N=n.pathname==="/",S=t.leadRegistrationMode!=="disabled";j.useEffect(()=>{const H=()=>m(window.scrollY>80);return window.addEventListener("scroll",H,{passive:!0}),()=>window.removeEventListener("scroll",H)},[]),j.useEffect(()=>{(async()=>{const{data:V}=await q.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order");V&&u(V)})()},[t.id]),j.useEffect(()=>{const H=V=>{p.current&&!p.current.contains(V.target)&&c(!1)};return document.addEventListener("mousedown",H),()=>document.removeEventListener("mousedown",H)},[]);const{data:A}=oat(t.agentId),T=((A==null?void 0:A.length)??0)>0,L=[{label:"Home",path:"/"},{label:"Search Properties",path:"/search"},...T?[{label:"Sold",path:"/sold"}]:[],{label:"About",path:"/about"},{label:"Blog",path:"/blog"},{label:"Contact",path:"/contact"}],M=h||!N?"bg-white/95 backdrop-blur-md shadow-sm":"bg-transparent",I=h||!N?ZY:"#ffffff";return e.jsxs("div",{className:"min-h-screen",style:{fontFamily:"'Lora', Georgia, serif"},children:[e.jsxs(dl,{children:[e.jsx("title",{children:b}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;600;700;800&family=Lora:wght@400;500;600&display=swap",rel:"stylesheet"})]}),e.jsx(Srt,{siteConfig:t}),e.jsx(Crt,{siteConfig:t}),e.jsxs("header",{className:`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${M}`,children:[e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between h-16 md:h-20",children:[e.jsxs(xr,{to:"/",className:"flex items-center gap-2.5",children:[e.jsx(kF,{className:"w-7 h-7",style:{color:x5}}),e.jsx("span",{className:"text-lg font-bold tracking-wide",style:{color:I,fontFamily:"'Playfair Display', Georgia, serif"},children:b})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[L.map(H=>e.jsx(xr,{to:H.path,className:"px-4 py-2 text-sm font-medium tracking-wide uppercase transition-colors hover:opacity-80",style:{color:n.pathname===H.path?x5:I},children:H.label},H.path)),d.length>0&&e.jsxs("div",{ref:p,className:"relative",children:[e.jsxs("button",{onClick:()=>c(!o),className:"px-4 py-2 text-sm font-medium tracking-wide uppercase flex items-center gap-1 transition-colors hover:opacity-80",style:{color:I},children:["Areas ",e.jsx(rl,{className:`w-3.5 h-3.5 transition-transform ${o?"rotate-180":""}`})]}),o&&e.jsx("div",{className:"absolute top-full right-0 mt-2 w-56 bg-white rounded-xl shadow-xl border border-gray-100 py-2 animate-in fade-in-0 slide-in-from-top-2",children:d.map(H=>e.jsx(xr,{to:`/homes-for-sale-in-${H.city_slug}`,className:"block px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors",style:{color:ZY},onClick:()=>c(!1),children:H.city_name},H.city_slug))})]}),f?e.jsx("div",{className:"flex items-center gap-2 ml-3",children:e.jsxs(xr,{to:"/account",className:"px-4 py-2 text-sm font-medium rounded-full border-2 transition-all hover:scale-105",style:{borderColor:x5,color:I},children:[e.jsx(So,{className:"w-4 h-4 inline mr-1.5"}),(x==null?void 0:x.name)||"Account"]})}):S?e.jsx("button",{onClick:()=>l(!0),className:"ml-3 px-5 py-2.5 text-sm font-semibold text-white rounded-full hover:shadow-lg transition-all hover:scale-105",style:{backgroundColor:x5},children:"Sign In"}):null]}),e.jsx("button",{onClick:()=>a(!r),className:"md:hidden p-2",style:{color:I},children:r?e.jsx(er,{className:"w-6 h-6"}):e.jsx(AA,{className:"w-6 h-6"})})]})}),r&&e.jsx("div",{className:"md:hidden bg-white border-t border-gray-100 shadow-xl animate-in slide-in-from-top-2",children:e.jsxs("div",{className:"px-4 py-4 space-y-1",children:[L.map(H=>e.jsx(xr,{to:H.path,className:"block px-4 py-3 text-base font-medium rounded-lg hover:bg-gray-50 transition-colors",style:{color:n.pathname===H.path?x5:ZY},onClick:()=>a(!1),children:H.label},H.path)),d.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-4 py-2 text-xs font-semibold tracking-wider uppercase text-gray-400",children:"Areas"}),d.map(H=>e.jsx(xr,{to:`/homes-for-sale-in-${H.city_slug}`,className:"block px-4 py-2.5 text-sm rounded-lg hover:bg-gray-50",style:{color:ZY},onClick:()=>a(!1),children:H.city_name},H.city_slug))]}),!f&&S&&e.jsx("button",{onClick:()=>{l(!0),a(!1)},className:"w-full mt-3 px-5 py-3 text-white font-semibold rounded-full",style:{backgroundColor:x5},children:"Sign In"})]})})]}),e.jsx("main",{children:s}),e.jsx("footer",{className:"py-16 px-4",style:{backgroundColor:ZY},children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-10",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(kF,{className:"w-6 h-6",style:{color:x5}}),e.jsx("span",{className:"text-lg font-bold text-white",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:b})]}),e.jsx("p",{className:"text-white/60 text-sm leading-relaxed",children:"Your trusted specialist in land, ranch, and rural properties. Expert guidance for every acre."}),e.jsx(aat,{siteConfig:t,className:"mt-5",iconClassName:"border-white/20 text-white"})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-white font-semibold mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),e.jsx("div",{className:"space-y-2",children:L.map(H=>e.jsx(xr,{to:H.path,className:"block text-white/60 hover:text-white text-sm transition-colors",children:H.label},H.path))})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-white font-semibold mb-4 text-sm tracking-wider uppercase",children:"Contact"}),e.jsxs("div",{className:"space-y-3",children:[((z=t.agent)==null?void 0:z.phone)&&e.jsxs("a",{href:`tel:${t.agent.phone}`,className:"flex items-center gap-2 text-white/60 hover:text-white text-sm transition-colors",children:[e.jsx(ba,{className:"w-4 h-4",style:{color:x5}}),t.agent.phone]}),(($=t.agent)==null?void 0:$.email)&&e.jsxs("a",{href:`mailto:${t.agent.email}`,className:"flex items-center gap-2 text-white/60 hover:text-white text-sm transition-colors",children:[e.jsx(ln,{className:"w-4 h-4",style:{color:x5}}),t.agent.email]})]})]})]}),e.jsxs("div",{className:"mt-12 pt-8 border-t border-white/10 flex items-center justify-between",children:[e.jsxs("p",{className:"text-white/40 text-xs",children:["© ",new Date().getFullYear()," ",b,". All rights reserved."]}),e.jsx("div",{className:"h-px w-16",style:{backgroundColor:x5}})]})]})}),i&&e.jsx(krt,{open:i,mode:t.leadRegistrationMode==="required"?"required":"optional",siteConfig:t,onSkip:()=>l(!1),onComplete:()=>l(!1)}),e.jsx(tat,{slug:t.subdomainSlug}),e.jsx(sat,{slug:t.subdomainSlug}),e.jsx(rat,{slug:t.subdomainSlug})]})}function qlr(){const{pathname:s}=Od();return j.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[s]),null}const $lr=j.lazy(()=>ui(()=>import("./LeadSiteHome-X2ToJUBR.js"),__vite__mapDeps([0,1,2,3,4]))),Vlr=j.lazy(()=>ui(()=>import("./LeadSiteLuxuryHome-DNqdQpme.js"),__vite__mapDeps([5,2,3,4,6]))),Hlr=j.lazy(()=>ui(()=>import("./LeadSiteLandRanchHome-Cu3w5XwD.js"),__vite__mapDeps([7,1,2,3,4]))),Glr=j.lazy(()=>ui(()=>import("./LeadSiteSearch-RHBL4StH.js"),__vite__mapDeps([8,1,9,4,10]))),Wlr=j.lazy(()=>ui(()=>import("./LeadSiteLuxurySearch-Zi_5OPyE.js"),__vite__mapDeps([11,1,9,4,10]))),Klr=j.lazy(()=>ui(()=>import("./LeadSiteListingDetail-BlqyDqZJ.js"),__vite__mapDeps([12,13,4,14]))),Ylr=j.lazy(()=>ui(()=>import("./LeadSiteLuxuryListingDetail-CqsfTze_.js"),__vite__mapDeps([15,13,4,14]))),Zlr=j.lazy(()=>ui(()=>import("./LeadSiteAbout-DD4Adf1O.js"),[])),Xlr=j.lazy(()=>ui(()=>import("./LeadSiteLuxuryAbout-DWwT2oAh.js"),[])),Qlr=j.lazy(()=>ui(()=>import("./LeadSiteContact-DAKKB6Pj.js"),[])),Jlr=j.lazy(()=>ui(()=>import("./LeadSiteLuxuryContact-eeHSt92y.js"),[])),ecr=j.lazy(()=>ui(()=>import("./LeadSiteConsumerDashboard-Cx0sr1YS.js"),[])),U4t=j.lazy(()=>ui(()=>import("./LeadSiteBlog-BsBMDX5u.js"),[])),tcr=j.lazy(()=>ui(()=>import("./LeadSiteCommunity-BFXfHwj7.js"),[])),scr=j.lazy(()=>ui(()=>import("./LeadSiteSellers-DkK-HgrX.js"),[])),ncr=j.lazy(()=>ui(()=>import("./LeadSiteCityPage-S78hcP0U.js"),__vite__mapDeps([16,4,10]))),rcr=j.lazy(()=>ui(()=>import("./LeadSiteSubdivisionPage-BqZdjsAT.js"),__vite__mapDeps([17,4]))),acr=j.lazy(()=>ui(()=>import("./LeadSiteCustomPage-CSJAWeBf.js"),[])),icr=j.lazy(()=>ui(()=>import("./LeadSiteFocusPage-DZePjoda.js"),__vite__mapDeps([18,3,4]))),ocr=j.lazy(()=>ui(()=>import("./LeadSiteExchangeListings-But2LKOW.js"),[]).then(s=>({default:s.LeadSiteExchangeListingsIndex}))),lcr=j.lazy(()=>ui(()=>import("./LeadSiteExchangeListings-But2LKOW.js"),[]).then(s=>({default:s.LeadSiteSoldListingsIndex}))),ccr=j.lazy(()=>ui(()=>import("./LeadSiteExchangeListings-But2LKOW.js"),[]).then(s=>({default:s.LeadSiteExchangeListingDetail})));function dcr(){return e.jsx("div",{className:"min-h-[60vh] flex items-center justify-center",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent"})})}function ucr(){var u;const{siteConfig:s,themeConfig:t,isLoading:n,error:r}=nnr();if(n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-gray-500",children:"Loading..."})]})});if(r||!s)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50 p-6",children:e.jsxs("div",{className:"text-center max-w-md",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Site Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This lead site is not available or has not been set up yet."})]})});const a=(t==null?void 0:t.themeTier)==="luxury",i=(t==null?void 0:t.themeTier)==="land-ranch",l=i?Ulr:a?zlr:Olr,o=wWt(s),c=!o&&Nrt(s,t),d=i?e.jsx(Hlr,{siteConfig:s,themeConfig:t??void 0}):a?e.jsx(Vlr,{siteConfig:s,themeConfig:t??void 0}):e.jsx($lr,{siteConfig:s,themeConfig:t??void 0});return e.jsxs(anr,{siteConfig:s,children:[e.jsx(qlr,{}),e.jsxs(l,{siteConfig:s,children:[e.jsx(j.Suspense,{fallback:e.jsx(dcr,{}),children:e.jsxs(tee,{children:[e.jsx(ns,{path:"/",element:d}),e.jsx(ns,{path:"/listings",element:e.jsx(ocr,{siteConfig:s})}),e.jsx(ns,{path:"/sold",element:e.jsx(lcr,{siteConfig:s})}),e.jsx(ns,{path:"/listings/:slug",element:e.jsx(ccr,{siteConfig:s})}),e.jsx(ns,{path:"/search",element:o?e.jsx(td,{to:"/listings",replace:!0}):c?e.jsx(td,{to:"/contact",replace:!0}):a?e.jsx(Wlr,{siteConfig:s}):e.jsx(Glr,{siteConfig:s})}),e.jsx(ns,{path:"/listing/:mlsNumber",element:o?e.jsx(td,{to:"/listings",replace:!0}):c?e.jsx(td,{to:"/contact",replace:!0}):a?e.jsx(Ylr,{siteConfig:s}):e.jsx(Klr,{siteConfig:s})}),e.jsx(ns,{path:"/about",element:a?e.jsx(Xlr,{siteConfig:s}):e.jsx(Zlr,{siteConfig:s})}),e.jsx(ns,{path:"/contact",element:a?e.jsx(Jlr,{siteConfig:s}):e.jsx(Qlr,{siteConfig:s})}),e.jsx(ns,{path:"/account",element:e.jsx(ecr,{siteConfig:s})}),e.jsx(ns,{path:"/blog",element:e.jsx(U4t,{siteConfig:s,isLuxury:a})}),e.jsx(ns,{path:"/blog/:slug",element:e.jsx(U4t,{siteConfig:s,isLuxury:a})}),e.jsx(ns,{path:"/sell",element:e.jsx(scr,{siteConfig:s,themeConfig:t??void 0,isLuxury:a})}),e.jsx(ns,{path:"/community",element:e.jsx(tcr,{siteConfig:s,isLuxury:a})}),e.jsx(ns,{path:"/schedule",element:e.jsx(unr,{bookingUrl:s.bookingUrl,agentName:((u=s.agent)==null?void 0:u.full_name)||"your agent"})}),((t==null?void 0:t.focusPages)??[]).map(h=>e.jsx(ns,{path:`/${h.slug}`,element:e.jsx(icr,{siteConfig:s,page:h,accentColor:(t==null?void 0:t.accentColor)||s.accentColor||"#c9a96e"})},h.slug)),e.jsx(ns,{path:"/p/:pageSlug",element:e.jsx(acr,{siteConfig:s})}),e.jsx(ns,{path:"/*",element:e.jsx(hcr,{siteConfig:s,referralMode:c})})]})}),e.jsx(dnr,{bookingUrl:s.bookingUrl})]})]})}function hcr({siteConfig:s,referralMode:t}){const n=Od(),r=n.pathname.match(/^\/homes-in-(.+)$/);if(r)return e.jsx(rcr,{siteConfig:s,subdivisionSlug:r[1]});const a=n.pathname.match(/^\/homes-for-sale-in-(.+)$/);return a?e.jsx(ncr,{siteConfig:s,citySlugOverride:a[1],referralMode:t}):null}function mcr(){const{user:s,loading:t}=vs(),{data:n,isLoading:r}=ct({queryKey:["feature-entitlement","levelup_attract",s==null?void 0:s.id],enabled:!!s,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","levelup_attract").maybeSingle();if(i)throw i;return a?{hasAccess:a.enabled&&(!a.expires_at||new Date(a.expires_at).getTime()>Date.now()),tier:a.tier??null}:{hasAccess:!1,tier:null}}});return{hasAccess:!!(n!=null&&n.hasAccess),tier:(n==null?void 0:n.tier)??null,isLoading:t||r}}function pcr({children:s}){const{user:t,loading:n}=vs(),{hasAccess:r,isLoading:a}=mcr(),i=Od();return j.useEffect(()=>{!n&&!a&&t&&!r&&re.error("LevelUp Attract isn't available for your account yet.")},[n,a,t,r]),n||t&&a?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"})}):t?r?e.jsx(e.Fragment,{children:s}):e.jsx(td,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",i.pathname),e.jsx(td,{to:"/auth",replace:!0}))}function q4t({children:s}){const{user:t,loading:n}=vs(),{hasAccess:r,isLoading:a}=Y6e(),i=Od();return n||t&&a?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"})}):t?r?e.jsx(e.Fragment,{children:s}):e.jsx(td,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",i.pathname),e.jsx(td,{to:"/auth",replace:!0}))}const QKe={buyer:"Buyer",seller:"Seller",local_community:"Local & Community",luxury:"Luxury",new_homes:"New Homes",open_house:"Open House",sphere:"Sphere",personal_brand:"Personal Brand",market_update:"Market Update"},fcr=["First-time buyers","Move-up buyers","Luxury","New construction","Investors","Relocation","Downsizing / seniors","Military / VA","Land & ranch","Waterfront","Condos","Multi-family"],gcr=["Buyers","Sellers","Both equally","Investors","Renters","Builders / developers"],xcr=["Warm & approachable","Bold & direct","Educational & analytical","Playful & funny","Polished & luxury","Down-to-earth & local","High-energy & motivational"],ycr=[{value:"none",label:"Keep it straight — no jokes"},{value:"light",label:"Light — an occasional wink"},{value:"medium",label:"Medium — genuinely funny"},{value:"high",label:"High — lead with the humor"}],vcr=["Under $250k","$250k – $500k","$500k – $750k","$750k – $1M","$1M – $2M","$2M+"],bcr=["Brand new (under 1 year)","1–3 years","3–5 years","5–10 years","10–20 years","20+ years"],_cr=[{value:"dm_keyword",label:"DM me a keyword"},{value:"comment",label:"Comment below"},{value:"link_in_bio",label:"Link in bio"},{value:"call_text",label:"Call or text me"},{value:"soft",label:"Soft — no hard ask"}],wcr=[{value:"instagram",label:"Instagram"},{value:"tiktok",label:"TikTok"},{value:"facebook",label:"Facebook"},{value:"youtube",label:"YouTube Shorts"},{value:"linkedin",label:"LinkedIn"}],jcr=[{value:"15-30s",label:"15–30 seconds"},{value:"30-45s",label:"30–45 seconds"},{value:"45-60s",label:"45–60 seconds"}],Ncr=[{value:"new",label:"Brand new to video — go easy on me"},{value:"building",label:"Building confidence"},{value:"comfortable",label:"Comfortable on camera"},{value:"pro",label:"Very comfortable — push me"}],kcr=[{value:"local",label:"Mostly local market content"},{value:"evergreen",label:"Mostly evergreen content"},{value:"mix",label:"A healthy mix of both"}];function hrs({value:s,label:t}){const[n,r]=j.useState(!1);return s?e.jsxs(U,{type:"button",size:"sm",variant:"ghost",className:"h-7 px-2 text-[11px] font-medium text-muted-foreground hover:text-foreground",onClick:async()=>{await navigator.clipboard.writeText(s),r(!0),re.success(`${t} copied`),setTimeout(()=>r(!1),1600)},children:[n?e.jsx(Xr,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1"}),"Copy"]}):null}function oI({label:s,children:t,copyValue:n}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.09em] text-muted-foreground",children:s}),n?e.jsx(hrs,{value:n,label:s}):null]}),e.jsx("div",{className:"text-[14.5px] leading-relaxed text-foreground whitespace-pre-wrap",children:t})]})}function c3e({reel:s,index:t,onUpdate:n,readOnly:r}){var c;const[a,i]=j.useState(t===0),l=!!s.recorded_at,o=!!s.posted_at;return e.jsx(we,{className:"rounded-2xl border-border/70 overflow-hidden",children:e.jsxs("div",{className:"p-5 sm:p-6",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.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Be,{className:"bg-primary text-primary-foreground border-0 text-[10.5px] font-bold tracking-[0.09em] px-2.5",children:["REEL ",t+1]}),s.category?e.jsx(Be,{variant:"outline",className:"text-[10.5px] font-medium text-muted-foreground",children:QKe[s.category]??s.category}):null,o?e.jsx(Be,{className:"bg-emerald-100 text-emerald-800 border-0 text-[10.5px]",children:"Posted"}):l?e.jsx(Be,{className:"bg-amber-100 text-amber-800 border-0 text-[10.5px]",children:"Recorded"}):null]}),e.jsx("h3",{className:"mt-3 text-lg sm:text-xl font-semibold tracking-tight text-foreground",children:s.topic})]}),!r&&n?e.jsx(U,{type:"button",size:"icon",variant:"ghost","aria-label":s.favorited?"Remove from saved":"Save this reel",className:Mt("h-9 w-9 shrink-0",s.favorited&&"text-amber-500"),onClick:()=>n({favorited:!s.favorited}),children:e.jsx(Ua,{className:Mt("h-4.5 w-4.5",s.favorited&&"fill-current")})}):null]}),e.jsxs("div",{className:"mt-5 rounded-xl bg-muted/60 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.09em] text-muted-foreground",children:"On-screen hook"}),e.jsx(hrs,{value:s.hook,label:"Hook"})]}),e.jsx("p",{className:"mt-1.5 text-[16px] font-semibold leading-snug text-foreground",children:s.hook})]}),e.jsx("div",{className:"mt-5",children:e.jsx(oI,{label:"Script · 30–45 seconds",copyValue:s.script,children:s.script})}),!r&&n?e.jsxs("div",{className:"mt-5 flex flex-wrap gap-2",children:[e.jsxs(U,{type:"button",size:"sm",variant:l?"default":"outline",className:"rounded-full",onClick:()=>n({recorded_at:l?null:new Date().toISOString()}),children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1.5"}),l?"Recorded":"Mark as recorded"]}),e.jsxs(U,{type:"button",size:"sm",variant:o?"default":"outline",className:"rounded-full",onClick:()=>n({posted_at:o?null:new Date().toISOString()}),children:[e.jsx($r,{className:"h-3.5 w-3.5 mr-1.5"}),o?"Posted":"Mark as posted"]})]}):null,e.jsxs(ub,{open:a,onOpenChange:i,children:[e.jsx(hb,{asChild:!0,children:e.jsxs(U,{type:"button",variant:"ghost",size:"sm",className:"mt-4 w-full justify-between text-[13px] font-medium text-muted-foreground hover:text-foreground",children:[a?"Hide caption, hashtags & coaching":"Caption, hashtags & coaching",e.jsx(rl,{className:Mt("h-4 w-4 transition-transform",a&&"rotate-180")})]})}),e.jsxs(mb,{className:"space-y-5 pt-2",children:[e.jsx(hc,{}),s.filming_directions?e.jsx(oI,{label:"How to film it",children:e.jsxs("span",{className:"flex gap-2",children:[e.jsx(WU,{className:"h-4 w-4 mt-0.5 shrink-0 text-muted-foreground"}),e.jsx("span",{children:s.filming_directions})]})}):null,s.caption?e.jsx(oI,{label:"Caption",copyValue:s.caption,children:s.caption}):null,(c=s.hashtags)!=null&&c.length?e.jsx(oI,{label:"Hashtags",copyValue:s.hashtags.join(" "),children:e.jsx("span",{className:"flex flex-wrap gap-1.5",children:s.hashtags.map(d=>e.jsx("span",{className:"rounded-full bg-primary/10 px-2.5 py-1 text-[12.5px] font-medium text-primary",children:d},d))})}):null,s.pinned_comment?e.jsx(oI,{label:"Pinned comment",copyValue:s.pinned_comment,children:s.pinned_comment}):null,s.reply_strategy?e.jsx(oI,{label:"Reply strategy",children:e.jsxs("span",{className:"flex gap-2",children:[e.jsx(Ki,{className:"h-4 w-4 mt-0.5 shrink-0 text-muted-foreground"}),e.jsx("span",{children:s.reply_strategy})]})}):null,s.why_it_works?e.jsxs("div",{className:"rounded-xl border border-primary/20 bg-primary/5 p-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.09em] text-primary",children:[e.jsx(cn,{className:"h-3.5 w-3.5"})," Why this will work"]}),e.jsx("p",{className:"mt-1.5 text-[14px] leading-relaxed text-foreground",children:s.why_it_works})]}):null,s.bonus_idea?e.jsx(oI,{label:"Bonus content idea",children:e.jsxs("span",{className:"flex gap-2",children:[e.jsx(eS,{className:"h-4 w-4 mt-0.5 shrink-0 text-muted-foreground"}),e.jsx("span",{children:s.bonus_idea})]})}):null]})]})]})})}function mrs(s=new Date){const t=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short"}).formatToParts(s),n=i=>t.find(l=>l.type===i).value,r=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"].indexOf(n("weekday")),a=new Date(`${n("year")}-${n("month")}-${n("day")}T12:00:00Z`);return a.setUTCDate(a.getUTCDate()-(r<0?0:r)),a.toISOString().slice(0,10)}function $4t(){const s=mrs(),[t,n,r]=s.split("-").map(Number),a=new Date(Date.UTC(t,n-1,r));return a.setUTCDate(a.getUTCDate()+7),new Intl.DateTimeFormat("en-US",{weekday:"long",month:"long",day:"numeric",timeZone:"UTC"}).format(a)}function AJ(s){const[t,n,r]=s.split("-").map(Number);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"}).format(new Date(Date.UTC(t,n-1,r)))}function lat(s){const{user:t}=vs(),n=s??(t==null?void 0:t.id),r=Qt(),a=ct({queryKey:["weekly-reels-profile",n],enabled:!!n,queryFn:async()=>{const{data:h,error:m}=await q.from("weekly_reel_profiles").select("*").eq("user_id",n).maybeSingle();if(m)throw m;return h??null}}),i=ct({queryKey:["weekly-reels-packs",n],enabled:!!n,queryFn:async()=>{const{data:h,error:m}=await q.from("weekly_reel_packs").select("*").eq("user_id",n).order("week_start_date",{ascending:!1}).limit(52);if(m)throw m;const p=(h??[]).map(x=>x.id);let f=[];if(p.length){const{data:x,error:y}=await q.from("weekly_reels").select("*").in("pack_id",p).order("position",{ascending:!0});if(y)throw y;f=x??[]}return(h??[]).map(x=>({...x,reels:f.filter(y=>y.pack_id===x.id)}))}}),l=yt({mutationFn:async h=>{if(!n)throw new Error("Not signed in");const m={...h,user_id:n,...h.onboarding_completed?{onboarding_completed_at:new Date().toISOString()}:{}},{error:p}=await q.from("weekly_reel_profiles").upsert(m,{onConflict:"user_id"});if(p)throw p},onSuccess:()=>{r.invalidateQueries({queryKey:["weekly-reels-profile",n]})},onError:h=>re.error(h.message)}),o=yt({mutationFn:async({id:h,values:m})=>{const{error:p}=await q.from("weekly_reels").update(m).eq("id",h);if(p)throw p},onSuccess:()=>r.invalidateQueries({queryKey:["weekly-reels-packs",n]}),onError:h=>re.error(h.message)}),c=mrs(),d=(i.data??[]).find(h=>h.week_start_date===c)??null,u=(i.data??[]).filter(h=>h.week_start_date!==c);return{profile:a,packs:i,currentPack:d,history:u,saveProfile:l,updateReel:o,userId:n}}function sde({icon:s,label:t,value:n}){return e.jsxs("div",{className:"neon-tile neon-topline px-4 py-3.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10.5px] font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:[e.jsx(s,{className:"h-3.5 w-3.5"})," ",t]}),e.jsx("div",{className:"neon-stat mt-1.5 text-[17px] font-black leading-snug",children:n})]})}function Scr(){var R,z,$,H,V;const s=Wn(),{user:t}=vs(),{profile:n,packs:r,currentPack:a,history:i,saveProfile:l,updateReel:o}=lat(),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,p]=j.useState(""),[f,x]=j.useState("all"),[y,v]=j.useState("all"),b=(((R=n.data)==null?void 0:R.full_name)||((z=t==null?void 0:t.user_metadata)==null?void 0:z.full_name)||"there").split(" ")[0],N=!!(($=n.data)!=null&&$.onboarding_completed),S=j.useMemo(()=>(r.data??[]).flatMap(K=>K.reels.map(Z=>({reel:Z,pack:K}))),[r.data]),A=j.useMemo(()=>{const K=m.trim().toLowerCase();return S.filter(({pack:Z})=>y==="all"?!0:Z.week_start_date===y).filter(({reel:Z})=>f==="all"?!0:Z.category===f).filter(({reel:Z})=>K?`${Z.topic} ${Z.hook} ${Z.script}`.toLowerCase().includes(K):!0)},[S,m,f,y]),T=S.filter(({reel:K})=>K.favorited),L=async()=>{d(!0);try{const{data:K,error:Z}=await q.functions.invoke("weekly-reels-generate",{body:{action:"generate_pack",force:!0}});if(Z)throw new Error(await Pee(Z));if(K!=null&&K.error)throw new Error(K.error);await r.refetch(),re.success(K!=null&&K.skipped?String(K.skipped):"Your pack is ready")}catch(K){re.error(K instanceof Error?K.message:"Generation failed")}finally{d(!1)}},M=async()=>{if(a){h(!0);try{const{data:K,error:Z}=await q.functions.invoke("weekly-reels-generate",{body:{action:"send_pack_email",packId:a.id}});if(Z)throw new Error(await Pee(Z));if(K!=null&&K.error)throw new Error(K.error);await r.refetch(),re.success(`Sent to ${(K==null?void 0:K.recipient)??"your inbox"}`)}catch(K){re.error(K instanceof Error?K.message:"Could not send the email")}finally{h(!1)}}},I=K=>Z=>o.mutate({id:K.id,values:Z});return!n.isLoading&&!N?e.jsx(qs,{title:"Weekly Reels",children:e.jsx("div",{className:"program-theme-neon relative min-h-screen",children:e.jsx("div",{className:"relative mx-auto w-full max-w-2xl px-4 py-16 sm:px-6",children:e.jsxs(we,{className:"neon-topline p-8 text-center sm:p-12",children:[e.jsx("div",{className:"mx-auto flex h-14 w-14 items-center justify-center rounded-2xl bg-primary/15",children:e.jsx(Gh,{className:"h-7 w-7 text-primary"})}),e.jsx("p",{className:"neon-eyebrow mt-6 font-semibold",children:"Weekly Reels"}),e.jsx("h1",{className:"neon-title mx-auto mt-2 w-fit text-3xl font-black uppercase tracking-tight sm:text-4xl",children:"5 Reels. Every Monday."}),e.jsx("p",{className:"mx-auto mt-3 max-w-md text-[15px] leading-relaxed text-muted-foreground",children:"Tell us about your market, your niche and how you actually talk. Then every Monday at 9:00 AM you get five ready-to-film Reels written for you — hook, word-for-word script, caption, hashtags and all."}),e.jsxs(U,{size:"lg",className:"neon-cta mt-7",onClick:()=>s("/weekly-reels/onboarding"),children:[e.jsx(cn,{className:"h-4 w-4 mr-2"})," Start setup — about 5 minutes"]})]})})})}):e.jsx(qs,{title:"Weekly Reels",children:e.jsx("div",{className:"program-theme-neon relative min-h-screen",children:e.jsxs("div",{className:"relative mx-auto w-full max-w-5xl px-4 py-8 sm:px-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"neon-eyebrow font-semibold",children:"Weekly Reels"}),e.jsxs("h1",{className:"neon-title mt-2 w-fit text-3xl font-black uppercase tracking-tight sm:text-4xl",children:["Welcome back, ",b]}),e.jsx("p",{className:"mt-2 text-[15px] text-muted-foreground",children:"Your Reels for the week, written around your market and your voice."})]}),e.jsxs(U,{variant:"outline",onClick:()=>s("/weekly-reels/onboarding"),children:[e.jsx(R4,{className:"h-4 w-4 mr-2"})," Edit my profile"]})]}),e.jsxs(we,{className:"mt-6 p-5 sm:p-6",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(sde,{icon:zr,label:"Onboarding",value:N?"Complete":"Incomplete"}),e.jsx(sde,{icon:WU,label:"Weekly delivery",value:(H=n.data)!=null&&H.delivery_active?"Active":"Paused"}),e.jsx(sde,{icon:ch,label:"Next pack",value:$4t()}),e.jsx(sde,{icon:ln,label:"Email this week",value:(a==null?void 0:a.delivery_status)==="sent"?"Delivered":(a==null?void 0:a.delivery_status)==="failed"?"Failed":"Scheduled"})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap items-center justify-between gap-3 border-t border-border/60 pt-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(wn,{checked:!!((V=n.data)!=null&&V.delivery_active),onCheckedChange:K=>l.mutate({delivery_active:K}),"aria-label":"Weekly email delivery"}),e.jsx("span",{className:"text-[14px] text-muted-foreground",children:"Email me my pack every Monday at 9:00 AM ET"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a&&a.reels.length?e.jsxs(U,{variant:"outline",size:"sm",onClick:M,disabled:u,children:[u?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Email me this week's pack"]}):null,e.jsxs(U,{size:"sm",className:"neon-cta",onClick:L,disabled:c,children:[c?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(cn,{className:"h-4 w-4 mr-2"}),a&&a.reels.length?"Regenerate this week":"Generate this week's pack"]})]})]})]}),e.jsxs(oa,{defaultValue:"current",className:"mt-8",children:[e.jsxs(la,{children:[e.jsx(Kt,{value:"current",children:"This week"}),e.jsx(Kt,{value:"history",children:"History"}),e.jsxs(Kt,{value:"saved",children:["Saved",T.length?` (${T.length})`:""]})]}),e.jsx(Zt,{value:"current",className:"mt-6",children:r.isLoading?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Et,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):a&&a.reels.length?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2",children:[e.jsxs(Be,{variant:"outline",className:"text-[11.5px]",children:["Week of ",AJ(a.week_start_date)]}),e.jsxs("span",{className:"text-[13px] text-muted-foreground",children:[a.reels.filter(K=>K.posted_at).length," of ",a.reels.length," posted"]})]}),e.jsx("div",{className:"space-y-4",children:a.reels.map((K,Z)=>e.jsx(c3e,{reel:K,index:Z,onUpdate:I(K)},K.id))})]}):e.jsxs(we,{className:"neon-topline p-10 text-center sm:p-14",children:[e.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-muted",children:e.jsx(Gh,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx("h3",{className:"mt-5 text-lg font-semibold text-foreground",children:"This week's pack isn't ready yet"}),e.jsxs("p",{className:"mx-auto mt-2 max-w-sm text-[14.5px] leading-relaxed text-muted-foreground",children:["Packs land every Monday at 9:00 AM Eastern, and we email them to you the moment they're written. Next delivery: ",$4t(),". Don't want to wait? Write them now."]}),e.jsxs(U,{className:"neon-cta mt-6",onClick:L,disabled:c,children:[c?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Generate it now"]})]})}),e.jsxs(Zt,{value:"history",className:"mt-6",children:[e.jsx(we,{className:"rounded-2xl p-4 sm:p-5",children:e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[1fr_auto_auto]",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{value:m,onChange:K=>p(K.target.value),placeholder:"Search topics and scripts...",className:"pl-9"})]}),e.jsxs(Ns,{value:f,onValueChange:x,children:[e.jsx(ws,{className:"sm:w-[190px]",children:e.jsx(ks,{placeholder:"All topics"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All topics"}),Object.entries(QKe).map(([K,Z])=>e.jsx(et,{value:K,children:Z},K))]})]}),e.jsxs(Ns,{value:y,onValueChange:v,children:[e.jsx(ws,{className:"sm:w-[180px]",children:e.jsx(ks,{placeholder:"All weeks"})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All weeks"}),(r.data??[]).map(K=>e.jsx(et,{value:K.week_start_date,children:AJ(K.week_start_date)},K.id))]})]})]})}),A.length?e.jsx(y9,{type:"multiple",className:"mt-4 space-y-3",children:A.map(({reel:K,pack:Z})=>e.jsxs(WP,{value:K.id,className:"rounded-2xl border border-border/70 bg-card px-4 sm:px-5",children:[e.jsx(KP,{className:"py-4 hover:no-underline",children:e.jsxs("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-2 pr-3 text-left",children:[e.jsx(Be,{variant:"outline",className:"text-[10.5px] shrink-0",children:AJ(Z.week_start_date)}),K.category?e.jsx(Be,{className:"bg-muted text-muted-foreground border-0 text-[10.5px] shrink-0",children:QKe[K.category]??K.category}):null,e.jsx("span",{className:"truncate text-[14.5px] font-medium text-foreground",children:K.topic})]})}),e.jsx(YP,{className:"pb-4",children:e.jsx(c3e,{reel:K,index:K.position-1,onUpdate:I(K)})})]},K.id))}):e.jsxs(we,{className:"mt-4 rounded-2xl p-10 text-center sm:p-14",children:[e.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-muted",children:e.jsx(Fr,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx("h3",{className:"mt-5 text-lg font-semibold text-foreground",children:"Nothing here yet"}),e.jsx("p",{className:"mx-auto mt-2 max-w-sm text-[14.5px] text-muted-foreground",children:S.length?"No Reels match these filters. Try widening your search.":"Your past packs will collect here once a few weeks have gone by."})]})]}),e.jsx(Zt,{value:"saved",className:"mt-6",children:T.length?e.jsx("div",{className:"space-y-4",children:T.map(({reel:K},Z)=>e.jsx(c3e,{reel:K,index:Z,onUpdate:I(K)},K.id))}):e.jsxs(we,{className:"rounded-2xl p-10 text-center sm:p-14",children:[e.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-muted",children:e.jsx(Ua,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx("h3",{className:"mt-5 text-lg font-semibold text-foreground",children:"No saved Reels yet"}),e.jsx("p",{className:"mx-auto mt-2 max-w-sm text-[14.5px] text-muted-foreground",children:"Tap the star on any Reel to keep it here — handy for the ones you want to film again next quarter."})]})})]})]})})})}const lI=[{id:"about",title:"About you",blurb:"The basics we put on every script."},{id:"business",title:"Your business",blurb:"Who you serve and where you serve them."},{id:"voice",title:"Your voice",blurb:"So the scripts sound like you, not a robot."},{id:"content",title:"Content preferences",blurb:"Format, length and the ask at the end."},{id:"goals",title:"Goals & compliance",blurb:"What we drive toward, and what we avoid."}];function Ccr(){const s=Wn(),{user:t}=vs(),{profile:n,saveProfile:r}=lat(),[a,i]=j.useState(0),[l,o]=j.useState({specialties:[],client_types:[],brand_voice:[],preferred_reel_length:"30-45s",main_platform:"instagram",content_mix:"mix"}),[c,d]=j.useState(!1),[u,h]=j.useState(!1);j.useEffect(()=>{u||n.isLoading||(o(b=>{var N,S,A,T,L,M;return{...b,...n.data??{},full_name:((N=n.data)==null?void 0:N.full_name)??((S=t==null?void 0:t.user_metadata)==null?void 0:S.full_name)??"",email:((A=n.data)==null?void 0:A.email)??(t==null?void 0:t.email)??"",specialties:((T=n.data)==null?void 0:T.specialties)??[],client_types:((L=n.data)==null?void 0:L.client_types)??[],brand_voice:((M=n.data)==null?void 0:M.brand_voice)??[]}}),h(!0))},[n.isLoading,n.data,t,u]);const m=(b,N)=>o(S=>({...S,[b]:N})),p=(b,N)=>o(S=>{const A=S[b]??[];return{...S,[b]:A.includes(N)?A.filter(T=>T!==N):[...A,N]}}),f=j.useMemo(()=>{var b,N,S;return a===0?!!((b=l.full_name)!=null&&b.trim())&&!!((N=l.email)!=null&&N.trim()):a===1?!!((S=l.primary_market)!=null&&S.trim()):a===2?(l.brand_voice??[]).length>0:!0},[a,l]),x=async(b,N)=>{if(t){d(!0);try{const S=b.name.split(".").pop(),A=`${t.id}/weekly-reels-${N}-${Date.now()}.${S}`,{error:T}=await q.storage.from("avatars").upload(A,b,{upsert:!0});if(T)throw T;const{data:L}=q.storage.from("avatars").getPublicUrl(A);m(N,L.publicUrl),re.success("Image uploaded")}catch(S){re.error(S instanceof Error?S.message:"Upload failed")}finally{d(!1)}}},y=async()=>{await r.mutateAsync({...l,onboarding_completed:!0}),re.success("You're all set — your first pack is on the way."),s("/weekly-reels")},v=async()=>{await r.mutateAsync(l),re.success("Progress saved")};return e.jsx(qs,{title:"Weekly Reels",children:e.jsx("div",{className:"program-theme-neon relative min-h-screen",children:e.jsxs("div",{className:"relative mx-auto w-full max-w-3xl px-4 py-8 sm:px-6",children:[e.jsxs("div",{className:"mb-8",children:[e.jsx("p",{className:"neon-eyebrow font-semibold",children:"Weekly Reels"}),e.jsx("h1",{className:"neon-title mt-2 w-fit text-3xl font-black uppercase tracking-tight sm:text-4xl",children:"Let's make these scripts sound like you"}),e.jsx("p",{className:"mt-2 text-[15px] leading-relaxed text-muted-foreground",children:"Five minutes now means every Monday you get 5 Reels built around your market, your niche and your personality — not generic real estate filler."})]}),e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"flex items-center justify-between text-[12.5px] font-medium text-muted-foreground",children:[e.jsxs("span",{children:["Step ",a+1," of ",lI.length," · ",lI[a].title]}),e.jsxs("span",{className:"neon-stat font-black",children:[Math.round((a+1)/lI.length*100),"%"]})]}),e.jsx(ro,{value:(a+1)/lI.length*100,className:"mt-2 h-1.5"})]}),e.jsxs(we,{className:"neon-topline rounded-2xl p-5 sm:p-7",children:[e.jsx("h2",{className:"text-lg font-semibold tracking-tight text-foreground",children:lI[a].title}),e.jsx("p",{className:"mt-1 text-[14px] text-muted-foreground",children:lI[a].blurb}),e.jsxs("div",{className:"mt-6 space-y-5",children:[a===0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Full name *"}),e.jsx(xe,{value:l.full_name??"",onChange:b=>m("full_name",b.target.value),placeholder:"Jane Realtor"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Email *"}),e.jsx(xe,{type:"email",value:l.email??"",onChange:b=>m("email",b.target.value),placeholder:"jane@brokerage.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Mobile number"}),e.jsx(xe,{value:l.mobile_number??"",onChange:b=>m("mobile_number",b.target.value),placeholder:"Optional"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Brokerage"}),e.jsx(xe,{value:l.brokerage??"",onChange:b=>m("brokerage",b.target.value)})]})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:["headshot_url","logo_url"].map(b=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(te,{children:[b==="headshot_url"?"Headshot":"Logo"," (optional)"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[l[b]?e.jsx("img",{src:l[b],alt:b==="headshot_url"?"Your headshot":"Your logo",className:"h-12 w-12 rounded-lg object-cover"}):null,e.jsxs("label",{className:"flex-1",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:N=>{var A;const S=(A=N.target.files)==null?void 0:A[0];S&&x(S,b)}}),e.jsxs("span",{className:"flex h-10 cursor-pointer items-center justify-center gap-2 rounded-md border border-input text-[13.5px] text-muted-foreground hover:bg-accent",children:[c?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(qa,{className:"h-4 w-4"}),"Upload"]})]})]})]},b))})]}),a===1&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Primary market — city & state *"}),e.jsx(xe,{value:l.primary_market??"",onChange:b=>m("primary_market",b.target.value),placeholder:"Tulsa, OK"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Neighborhoods or service areas"}),e.jsx(Fs,{rows:2,value:l.service_areas??"",onChange:b=>m("service_areas",b.target.value),placeholder:"Jenks, Bixby, Broken Arrow, midtown Tulsa"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Years in real estate"}),e.jsxs(Ns,{value:l.years_in_real_estate??"",onValueChange:b=>m("years_in_real_estate",b),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select"})}),e.jsx(js,{children:bcr.map(b=>e.jsx(et,{value:b,children:b},b))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Typical price point"}),e.jsxs(Ns,{value:l.typical_price_point??"",onValueChange:b=>m("typical_price_point",b),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select"})}),e.jsx(js,{children:vcr.map(b=>e.jsx(et,{value:b,children:b},b))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Primary specialties / niches"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:fcr.map(b=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(xi,{checked:(l.specialties??[]).includes(b),onCheckedChange:()=>p("specialties",b)}),b]},b))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Client types you serve"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:gcr.map(b=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(xi,{checked:(l.client_types??[]).includes(b),onCheckedChange:()=>p("client_types",b)}),b]},b))})]})]}),a===2&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Brand voice — pick everything that fits *"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:xcr.map(b=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(xi,{checked:(l.brand_voice??[]).includes(b),onCheckedChange:()=>p("brand_voice",b)}),b]},b))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Anything else about how you talk?"}),e.jsx(Fs,{rows:2,value:l.brand_voice_notes??"",onChange:b=>m("brand_voice_notes",b.target.value),placeholder:"I say 'y'all' a lot and I hate corporate jargon."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Humor level"}),e.jsx(y_,{value:l.humor_level??"",onValueChange:b=>m("humor_level",b),className:"space-y-1.5",children:ycr.map(b=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(Fh,{value:b.value}),b.label]},b.value))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Personal interests & hobbies"}),e.jsx(Fs,{rows:2,value:l.personal_interests??"",onChange:b=>m("personal_interests",b.target.value),placeholder:"Golf, smoking brisket, coaching my son's baseball team"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Family or community details you're happy to reference"}),e.jsx(Fs,{rows:2,value:l.family_community_notes??"",onChange:b=>m("family_community_notes",b.target.value),placeholder:"Married with two kids, active in the Jenks chamber"})]})]}),a===3&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Preferred Reel length"}),e.jsxs(Ns,{value:l.preferred_reel_length??"30-45s",onValueChange:b=>m("preferred_reel_length",b),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:jcr.map(b=>e.jsx(et,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Preferred CTA style"}),e.jsxs(Ns,{value:l.preferred_cta_style??"",onValueChange:b=>m("preferred_cta_style",b),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select"})}),e.jsx(js,{children:_cr.map(b=>e.jsx(et,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Main social platform"}),e.jsxs(Ns,{value:l.main_platform??"instagram",onValueChange:b=>m("main_platform",b),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:wcr.map(b=>e.jsx(et,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Instagram handle"}),e.jsx(xe,{value:l.instagram_handle??"",onChange:b=>m("instagram_handle",b.target.value),placeholder:"@janerealtor"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Website"}),e.jsx(xe,{value:l.website??"",onChange:b=>m("website",b.target.value),placeholder:"https://janerealtor.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"On-camera comfort level"}),e.jsx(y_,{value:l.content_comfort_level??"",onValueChange:b=>m("content_comfort_level",b),className:"space-y-1.5",children:Ncr.map(b=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(Fh,{value:b.value}),b.label]},b.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Local vs evergreen content"}),e.jsx(y_,{value:l.content_mix??"mix",onValueChange:b=>m("content_mix",b),className:"space-y-1.5",children:kcr.map(b=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(Fh,{value:b.value}),b.label]},b.value))})]})]}),a===4&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Topics you love talking about"}),e.jsx(Fs,{rows:2,value:l.topics_enjoyed??"",onChange:b=>m("topics_enjoyed",b.target.value),placeholder:"Renovation ROI, negotiating repairs, small-town living"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Topics you never want to cover"}),e.jsx(Fs,{rows:2,value:l.topics_avoided??"",onChange:b=>m("topics_avoided",b.target.value),placeholder:"Politics, interest rate predictions, dancing trends"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Lead magnets or offers to promote"}),e.jsx(Fs,{rows:2,value:l.lead_magnets??"",onChange:b=>m("lead_magnets",b.target.value),placeholder:"Free home value report, first-time buyer guide"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Current business goals"}),e.jsx(Fs,{rows:2,value:l.business_goals??"",onChange:b=>m("business_goals",b.target.value),placeholder:"Two listings a month and more sphere referrals"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Compliance or brokerage disclaimer notes"}),e.jsx(Fs,{rows:2,value:l.compliance_notes??"",onChange:b=>m("compliance_notes",b.target.value),placeholder:"Must include brokerage name on any listing content"})]})]})]}),e.jsxs("div",{className:"mt-8 flex flex-wrap items-center justify-between gap-3",children:[e.jsxs(U,{type:"button",variant:"ghost",disabled:a===0,onClick:()=>i(b=>Math.max(0,b-1)),children:[e.jsx(Aa,{className:"h-4 w-4 mr-1.5"})," Back"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(U,{type:"button",variant:"outline",onClick:v,disabled:r.isPending,children:"Save draft"}),ai(b=>b+1),children:["Continue ",e.jsx(Oa,{className:"h-4 w-4 ml-1.5"})]}):e.jsxs(U,{className:"neon-cta",type:"button",onClick:y,disabled:r.isPending,children:[r.isPending?e.jsx(Et,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(Xr,{className:"h-4 w-4 mr-1.5"}),"Finish setup"]})]})]})]})]})})})}function prs(s,t=!1){const{user:n}=vs(),r=Qt(),a=ct({queryKey:["wr-admin-members",s,t,n==null?void 0:n.id],enabled:!!n,queryFn:async()=>{let x=null;if(t){const{data:R,error:z}=await q.from("feature_entitlements").select("user_id").eq("feature_key",pU).eq("enabled",!0);if(z)throw z;if(x=(R??[]).map($=>$.user_id),!x.length)return[]}let y=q.from("profiles").select("id, email, name").order("name",{ascending:!0}).limit(t?1e3:100);if(x&&(y=y.in("id",x)),s.trim()){const R=`%${s.trim()}%`;y=y.or(`email.ilike.${R},name.ilike.${R}`)}const{data:v,error:b}=await y;if(b)throw b;const N=(v??[]).map(R=>R.id);if(!N.length)return[];const[{data:S},{data:A},{data:T}]=await Promise.all([q.from("feature_entitlements").select("user_id, enabled, tier, expires_at").eq("feature_key",pU).in("user_id",N),q.from("weekly_reel_profiles").select("user_id, onboarding_completed, delivery_active, primary_market").in("user_id",N),q.from("weekly_reel_packs").select("id, user_id, week_start_date, generation_status, delivery_status").in("user_id",N).order("week_start_date",{ascending:!1})]),L=new Map((S??[]).map(R=>[R.user_id,R])),M=new Map((A??[]).map(R=>[R.user_id,R])),I=new Map;return(T??[]).forEach(R=>{I.has(R.user_id)||I.set(R.user_id,R)}),(v??[]).map(R=>{const z=L.get(R.id),$=M.get(R.id),H=I.get(R.id);return{user_id:R.id,email:R.email,full_name:R.name,enabled:!!(z!=null&&z.enabled),tier:(z==null?void 0:z.tier)??null,expires_at:(z==null?void 0:z.expires_at)??null,onboarded:!!($!=null&&$.onboarding_completed),delivery_active:($==null?void 0:$.delivery_active)??!1,primary_market:($==null?void 0:$.primary_market)??null,latest_week:(H==null?void 0:H.week_start_date)??null,latest_pack_id:(H==null?void 0:H.id)??null,latest_generation_status:(H==null?void 0:H.generation_status)??null,latest_delivery_status:(H==null?void 0:H.delivery_status)??null}})}}),i=ct({queryKey:["wr-admin-generation-logs"],enabled:!!n,queryFn:async()=>{const{data:x,error:y}=await q.from("weekly_reel_generation_logs").select("*").order("created_at",{ascending:!1}).limit(100);if(y)throw y;return x??[]}}),l=ct({queryKey:["wr-admin-delivery-logs"],enabled:!!n,queryFn:async()=>{const{data:x,error:y}=await q.from("weekly_reel_delivery_logs").select("*").order("created_at",{ascending:!1}).limit(100);if(y)throw y;return x??[]}}),o=()=>{r.invalidateQueries({queryKey:["wr-admin-members"]}),r.invalidateQueries({queryKey:["wr-admin-generation-logs"]}),r.invalidateQueries({queryKey:["wr-admin-delivery-logs"]})},c=yt({mutationFn:async({userId:x,enabled:y})=>{const{error:v}=await q.from("feature_entitlements").upsert({user_id:x,feature_key:pU,enabled:y,tier:"member",enabled_by:n.id,enabled_at:new Date().toISOString()},{onConflict:"user_id,feature_key"});if(v)throw v;await q.from("feature_entitlement_audit").insert({feature_key:pU,target_user_id:x,action:y?"grant":"revoke",performed_by:n.id})},onSuccess:(x,y)=>{o(),re.success(y.enabled?"Access granted":"Access revoked")},onError:x=>re.error(x.message)}),d=async x=>{const{data:y,error:v}=await q.functions.invoke("weekly-reels-generate",{body:x});if(v)throw new Error(await Pee(v));if(y!=null&&y.error)throw new Error(String(y.error));return y},u=yt({mutationFn:x=>d({action:"generate_pack",userId:x.userId,force:x.force??!0}),onSuccess:()=>{o(),re.success("Pack generated")},onError:x=>re.error(x.message)}),h=yt({mutationFn:x=>d({action:"regenerate_reel",reelId:x.reelId,instructions:x.instructions}),onSuccess:()=>{o(),re.success("Reel regenerated")},onError:x=>re.error(x.message)}),m=yt({mutationFn:x=>d({action:"send_pack_email",packId:x.packId}),onSuccess:()=>{o(),re.success("Pack emailed")},onError:x=>re.error(x.message)}),p=yt({mutationFn:x=>d({action:"send_test_email",packId:x.packId,to:x.to}),onSuccess:()=>re.success("Test email sent"),onError:x=>re.error(x.message)}),f=yt({mutationFn:()=>d({action:"run_weekly"}),onSuccess:x=>{o(),re.success(`Weekly run complete${(x==null?void 0:x.processed)!=null?` — ${x.processed} agents`:""}`)},onError:x=>re.error(x.message)});return{members:a,generationLogs:i,deliveryLogs:l,setAccess:c,generatePack:u,regenerateReel:h,sendPack:m,sendTest:p,runWeekly:f}}function FU({value:s}){if(!s)return e.jsx("span",{className:"text-muted-foreground",children:"—"});const t=s==="complete"||s==="sent"?"bg-emerald-100 text-emerald-800":s==="failed"?"bg-red-100 text-red-800":"bg-amber-100 text-amber-800";return e.jsx(Be,{className:`${t} border-0 text-[11px] capitalize`,children:s})}function Acr({member:s,onClose:t}){var m,p,f;const n=prs(""),{packs:r,profile:a}=lat(s==null?void 0:s.user_id),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(null),h=((m=r.data)==null?void 0:m[0])??null;return e.jsx(zs,{open:!!s,onOpenChange:x=>!x&&t(),children:e.jsxs(Ds,{className:"max-w-3xl max-h-[88vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:(s==null?void 0:s.full_name)||(s==null?void 0:s.email)}),e.jsxs(Pr,{children:[((p=a.data)==null?void 0:p.primary_market)??"No market on file"," ·"," ",(f=a.data)!=null&&f.onboarding_completed?"Onboarded":"Onboarding incomplete"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(U,{size:"sm",onClick:()=>s&&n.generatePack.mutate({userId:s.user_id}),disabled:n.generatePack.isPending,children:[n.generatePack.isPending?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Generate pack"]}),e.jsxs(U,{size:"sm",variant:"outline",disabled:!h||n.sendPack.isPending,onClick:()=>h&&n.sendPack.mutate({packId:h.id}),children:[e.jsx(ln,{className:"h-4 w-4 mr-2"})," Email latest pack"]})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-2 rounded-xl bg-muted/60 p-3",children:[e.jsxs("div",{className:"flex-1 min-w-[200px] space-y-1.5",children:[e.jsx(te,{className:"text-[12px]",children:"Send a test copy to"}),e.jsx(xe,{value:i,onChange:x=>l(x.target.value),placeholder:"you@relevelup.com"})]}),e.jsxs(U,{size:"sm",variant:"outline",disabled:!h||!i||n.sendTest.isPending,onClick:()=>h&&n.sendTest.mutate({packId:h.id,to:i}),children:[e.jsx($r,{className:"h-4 w-4 mr-2"})," Send test"]})]}),h?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[13px] text-muted-foreground",children:[e.jsxs(Be,{variant:"outline",children:["Week of ",AJ(h.week_start_date)]}),e.jsx(FU,{value:h.generation_status}),e.jsx(FU,{value:h.delivery_status})]}),h.reels.map((x,y)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(c3e,{reel:x,index:y,readOnly:!0}),d===x.id?e.jsxs("div",{className:"rounded-xl border border-border/70 p-3 space-y-2",children:[e.jsx(Fs,{rows:2,value:o,onChange:v=>c(v.target.value),placeholder:"Optional guidance: make it more local, less salesy, focus on sellers..."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{size:"sm",disabled:n.regenerateReel.isPending,onClick:()=>n.regenerateReel.mutate({reelId:x.id,instructions:o||void 0},{onSuccess:()=>{u(null),c(""),r.refetch()}}),children:[n.regenerateReel.isPending?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(no,{className:"h-4 w-4 mr-2"}),"Regenerate"]}),e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>u(null),children:"Cancel"})]})]}):e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>u(x.id),children:[e.jsx(no,{className:"h-4 w-4 mr-2"})," Regenerate this reel"]})]},x.id))]}):e.jsx("p",{className:"py-6 text-center text-[14px] text-muted-foreground",children:"No packs generated for this agent yet."}),e.jsx(Mr,{children:e.jsx(U,{variant:"outline",onClick:t,children:"Close"})})]})})}function Ecr(){const[s,t]=j.useState(""),[n,r]=j.useState(!1),[a,i]=j.useState(null),l=prs(s,n),o=j.useMemo(()=>l.members.data??[],[l.members.data]);return e.jsxs(qs,{title:"Weekly Reels Admin",children:[e.jsxs("div",{className:"mx-auto w-full max-w-6xl px-4 py-8 sm:px-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-foreground",children:"Weekly Reels"}),e.jsx("p",{className:"mt-1.5 text-[15px] text-muted-foreground",children:"Manage access, generate packs and monitor Monday delivery."})]}),e.jsxs(U,{onClick:()=>l.runWeekly.mutate(),disabled:l.runWeekly.isPending,children:[l.runWeekly.isPending?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Run this week now"]})]}),e.jsxs(oa,{defaultValue:"members",className:"mt-7",children:[e.jsxs(la,{children:[e.jsx(Kt,{value:"members",children:"Members"}),e.jsx(Kt,{value:"generation",children:"Generation log"}),e.jsx(Kt,{value:"delivery",children:"Delivery log"})]}),e.jsxs(Zt,{value:"members",className:"mt-5",children:[e.jsx(we,{className:"rounded-2xl p-4 sm:p-5",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsxs("div",{className:"relative min-w-[220px] flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(xe,{value:s,onChange:c=>t(c.target.value),placeholder:"Search by name or email...",className:"pl-9"})]}),e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px] text-muted-foreground",children:[e.jsx(wn,{checked:n,onCheckedChange:r}),"Only members with access"]})]})}),e.jsx(we,{className:"mt-4 rounded-2xl overflow-hidden",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"Agent"}),e.jsx(Lt,{children:"Market"}),e.jsx(Lt,{children:"Onboarded"}),e.jsx(Lt,{children:"Latest week"}),e.jsx(Lt,{children:"Generation"}),e.jsx(Lt,{children:"Delivery"}),e.jsx(Lt,{className:"text-right",children:"Access"}),e.jsx(Lt,{})]})}),e.jsx(Xa,{children:l.members.isLoading?e.jsx(gn,{children:e.jsx(gt,{colSpan:8,className:"py-10 text-center",children:e.jsx(Et,{className:"mx-auto h-5 w-5 animate-spin text-muted-foreground"})})}):o.length?o.map(c=>e.jsxs(gn,{children:[e.jsxs(gt,{children:[e.jsx("div",{className:"font-medium text-foreground",children:c.full_name||"—"}),e.jsx("div",{className:"text-[12.5px] text-muted-foreground",children:c.email})]}),e.jsx(gt,{className:"text-[13.5px] text-muted-foreground",children:c.primary_market||"—"}),e.jsx(gt,{children:c.onboarded?e.jsx(Be,{className:"bg-emerald-100 text-emerald-800 border-0 text-[11px]",children:"Yes"}):e.jsx("span",{className:"text-muted-foreground",children:"No"})}),e.jsx(gt,{className:"text-[13.5px] text-muted-foreground",children:c.latest_week?AJ(c.latest_week):"—"}),e.jsx(gt,{children:e.jsx(FU,{value:c.latest_generation_status})}),e.jsx(gt,{children:e.jsx(FU,{value:c.latest_delivery_status})}),e.jsx(gt,{className:"text-right",children:e.jsx(wn,{checked:c.enabled,onCheckedChange:d=>l.setAccess.mutate({userId:c.user_id,enabled:d}),"aria-label":`Weekly Reels access for ${c.full_name||c.email}`})}),e.jsx(gt,{className:"text-right",children:e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>i(c),children:"Manage"})})]},c.user_id)):e.jsx(gn,{children:e.jsx(gt,{colSpan:8,className:"py-10 text-center text-muted-foreground",children:"No members match this search."})})})]})})]}),e.jsx(Zt,{value:"generation",className:"mt-5",children:e.jsx(we,{className:"rounded-2xl overflow-hidden",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"When"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{children:"Model"}),e.jsx(Lt,{children:"Tokens"}),e.jsx(Lt,{children:"Cost"}),e.jsx(Lt,{children:"Error"})]})}),e.jsx(Xa,{children:(l.generationLogs.data??[]).map(c=>e.jsxs(gn,{children:[e.jsx(gt,{className:"text-[13px]",children:new Date(c.created_at).toLocaleString("en-US",{timeZone:"America/New_York"})}),e.jsx(gt,{children:e.jsx(FU,{value:c.status})}),e.jsx(gt,{className:"text-[13px] text-muted-foreground",children:c.model??"—"}),e.jsx(gt,{className:"text-[13px]",children:c.total_tokens??0}),e.jsxs(gt,{className:"text-[13px]",children:["$",Number(c.estimated_cost??0).toFixed(4)]}),e.jsx(gt,{className:"max-w-[280px] truncate text-[12.5px] text-muted-foreground",children:c.error_message??"—"})]},c.id))})]})})}),e.jsx(Zt,{value:"delivery",className:"mt-5",children:e.jsx(we,{className:"rounded-2xl overflow-hidden",children:e.jsxs(Ya,{children:[e.jsx(Za,{children:e.jsxs(gn,{children:[e.jsx(Lt,{children:"When"}),e.jsx(Lt,{children:"Recipient"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{children:"Error"})]})}),e.jsx(Xa,{children:(l.deliveryLogs.data??[]).map(c=>e.jsxs(gn,{children:[e.jsx(gt,{className:"text-[13px]",children:new Date(c.created_at).toLocaleString("en-US",{timeZone:"America/New_York"})}),e.jsx(gt,{className:"text-[13px]",children:c.recipient_email??"—"}),e.jsx(gt,{children:e.jsx(FU,{value:c.status})}),e.jsx(gt,{className:"max-w-[280px] truncate text-[12.5px] text-muted-foreground",children:c.failure_reason??"—"})]},c.id))})]})})})]})]}),e.jsx(Acr,{member:a,onClose:()=>i(null)})]})}function cat(){const{user:s}=vs(),t=Qt(),n=ct({queryKey:["attract-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await q.from("attract_settings").select("*").eq("user_id",s.id).maybeSingle();if(l)throw l;return i}}),r=yt({mutationFn:async i=>{const l={...i,user_id:s.id},{data:o,error:c}=await q.from("attract_settings").upsert(l,{onConflict:"user_id"}).select().single();if(c)throw c;return o},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-settings"]}),re.success("Settings saved")},onError:i=>re.error(i.message)}),a=yt({mutationFn:async()=>{const{error:i}=await q.from("attract_settings").update({onboarding_completed_at:null}).eq("user_id",s.id);if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-settings"]}),re.success("Onboarding reset — run it again anytime")}});return{settings:n.data,isLoading:n.isLoading,save:r,upsert:r,resetOnboarding:a}}const frs="v1",om={recency:22,consistency:16,value_delivered:14,kit_engagement:16,event_participation:12,follow_up_discipline:10,pipeline_momentum:10};Object.values(om).reduce((s,t)=>s+t,0);const grs=864e5,Yx=(s,t=new Date)=>Math.floor((new Date(t).getTime()-new Date(s).getTime())/grs),xrs=["touch_logged","call","text","email","dm","meeting","note"];function Tcr(s,t,n=new Date){var x,y,v;const a=t.activities.filter(b=>b.agent_id===s.id).filter(b=>xrs.includes(b.activity_type)).sort((b,N)=>+new Date(N.created_at)-+new Date(b.created_at)),i=s.last_touch_at||((x=a[0])==null?void 0:x.created_at)||null,l=t.shares.filter(b=>b.agent_id===s.id),o=new Set(l.map(b=>b.id)),c=t.kitEvents.filter(b=>o.has(b.share_id)),d={};for(const b of l)d[b.id]=[];for(const b of c)(d[y=b.share_id]||(d[y]=[])).push(b);const u=t.attendees.filter(b=>b.agent_id===s.id),h=t.followUps.filter(b=>b.agent_id===s.id),m=h.filter(b=>!b.completed_at),p=t.stageChanges.filter(b=>b.agent_id===s.id).sort((b,N)=>+new Date(N.created_at)-+new Date(b.created_at)),f=new Set(a.filter(b=>Yx(b.created_at,n)<=180).map(b=>b.created_at.slice(0,7)));return{agent:s,touches:a,lastTouchAt:i,daysSinceTouch:i?Yx(i,n):null,touches90:a.filter(b=>Yx(b.created_at,n)<=90).length,touches30:a.filter(b=>Yx(b.created_at,n)<=30).length,distinctTouchMonths:f.size,shares:l,shareEvents:d,highIntentShares:l.filter(b=>b.engagement_level==="high_intent"||b.engagement_level==="engaged"),lastShareAt:l.map(b=>b.created_at).sort().reverse()[0]||null,totalKitOpens:l.reduce((b,N)=>b+(N.open_count||0),0),downloads:c.filter(b=>b.event_type==="file_download").length,ctaClicks:c.filter(b=>b.event_type==="primary_cta_click"||b.event_type==="external_link_click").length,questions:c.filter(b=>b.event_type==="question_submitted").length,meetingRequests:c.filter(b=>b.event_type==="meeting_requested").length+u.filter(b=>b.meeting_requested).length,attendees:u,attended:u.filter(b=>!!b.checked_in_at||b.status==="attended").length,noShows:u.filter(b=>!!b.no_show_at||b.status==="no_show").length,invitedNotRegistered:u.filter(b=>!!b.invited_at&&!b.registered_at&&!b.checked_in_at).length,openFollowUps:m,overdueFollowUps:m.filter(b=>b.due_at&&new Date(b.due_at)!!b.completed_at),stageChanges:p,lastStageChangeAt:((v=p[0])==null?void 0:v.created_at)||null,daysSinceStageChange:p[0]?Yx(p[0].created_at,n):null,scoreEvents:t.scoreEvents.filter(b=>b.agent_id===s.id)}}const d3e=["new_connection","building_relationship","engaging_with_value","active_conversation","exploring_options","brokerage_presentation","decision_pending","joined"],u3e=["not_right_now","not_a_fit","long_term_relationship"];function Mcr(s,t=new Date){const n=[],r=[],a=[],i=[],l=s.daysSinceTouch;let o=0,c;l===null?(o=0,c="No meaningful touch has ever been logged.",a.push("No logged conversation yet"),i.push("Log your first real conversation with this agent.")):l<=10?(o=om.recency,c=`Last meaningful touch ${l} day(s) ago.`,r.push("Recent personal contact")):l<=21?(o=om.recency*.85,c=`Last touch ${l} days ago.`,r.push("Contact is still fresh")):l<=45?(o=om.recency*.6,c=`Last touch ${l} days ago.`,i.push("Reach out within the next week to keep momentum.")):l<=90?(o=om.recency*.3,c=`Last touch ${l} days ago.`,a.push(`${l} days since a real conversation`),i.push("A personal check-in would meaningfully lift this score.")):(o=om.recency*.05,c=`Last touch ${l} days ago.`,a.push(`Relationship has been quiet for ${l} days`),i.push("Restart the relationship with a no-ask personal check-in.")),n.push({key:"recency",label:"Recency of personal contact",weight:om.recency,earned:Math.round(o),detail:c,direction:o>=om.recency*.6?"positive":"negative"});const d=Math.min(s.distinctTouchMonths,6),u=om.consistency*(d/6),h=s.touches30>6;n.push({key:"consistency",label:"Consistency of touches",weight:om.consistency,earned:Math.round(u),detail:`${d} of the last 6 months had at least one logged touch (${s.touches90} touches in 90 days).`,direction:u>=om.consistency*.5?"positive":"neutral"}),d>=4&&r.push("Consistent rhythm across months"),d<=1&&i.push("Aim for at least one touch per month rather than bursts."),h&&a.push(`${s.touches30} touches in the last 30 days — give them room to breathe`);const m=s.shares.length,p=om.value_delivered*Math.min(m/3,1);n.push({key:"value_delivered",label:"Value delivered",weight:om.value_delivered,earned:Math.round(p),detail:m?`${m} resource kit share(s) sent.`:"No resource kit shared yet.",direction:m?"positive":"neutral"}),m?r.push(`${m} resource kit share(s) delivered`):i.push("Share a relevant Resource Kit — value first, no ask.");const f=(s.totalKitOpens>0?4:0)+Math.min(s.downloads,2)*2+Math.min(s.ctaClicks,2)*2+(s.questions>0?2:0)+(s.meetingRequests>0?4:0),x=Math.min(f,om.kit_engagement);n.push({key:"kit_engagement",label:"Kit engagement",weight:om.kit_engagement,earned:x,detail:m?`${s.totalKitOpens} open(s), ${s.downloads} download(s), ${s.ctaClicks} link click(s), ${s.questions} question(s), ${s.meetingRequests} meeting request(s).`:"Nothing shared yet, so no engagement to measure.",direction:x>0?"positive":"neutral"}),s.meetingRequests>0&&r.push("They asked for a conversation"),m&&s.totalKitOpens===0&&(a.push("Shared kit has never been opened"),i.push("Follow up personally — the kit link was never opened."));const y=Math.min(s.attended,2)*5+(s.attendees.length?2:0)-Math.min(s.noShows,2)*2,v=Math.max(0,Math.min(y,om.event_participation));n.push({key:"event_participation",label:"Event participation",weight:om.event_participation,earned:v,detail:s.attendees.length?`${s.attended} attended, ${s.noShows} no-show(s), ${s.attendees.length} total invitation(s)/registration(s).`:"Never invited to an event.",direction:v>0?"positive":"neutral"}),s.attended>0&&r.push(`${s.attended} event(s) attended`),s.attendees.length||i.push("Invite them to your next event or mastermind."),s.noShows>0&&a.push(`${s.noShows} no-show(s)`);const b=s.completedFollowUps.length+s.openFollowUps.length;let N=b===0?om.follow_up_discipline*.4:om.follow_up_discipline*(s.completedFollowUps.length/b);N-=Math.min(s.overdueFollowUps.length,3)*2,N=Math.max(0,Math.min(N,om.follow_up_discipline)),n.push({key:"follow_up_discipline",label:"Follow-up discipline",weight:om.follow_up_discipline,earned:Math.round(N),detail:b?`${s.completedFollowUps.length} of ${b} follow-ups completed, ${s.overdueFollowUps.length} overdue.`:"No follow-ups created yet.",direction:s.overdueFollowUps.length?"negative":"positive"}),s.overdueFollowUps.length&&(a.push(`${s.overdueFollowUps.length} overdue commitment(s)`),i.push("Clear the overdue follow-up you promised."));const S=d3e.indexOf(s.agent.stage);let A=0,T;if(u3e.includes(s.agent.stage))A=om.pipeline_momentum*.3,T="Relationship is intentionally parked — long-term nurture.";else if(S<0)A=om.pipeline_momentum*.3,T=`Stage "${s.agent.stage}" is outside the advancing ladder.`;else{const I=om.pipeline_momentum*(S/(d3e.length-1)),R=s.daysSinceStageChange!==null&&s.daysSinceStageChange>60;A=R?I*.5:I,T=`Stage ${S+1} of ${d3e.length}`+(s.daysSinceStageChange!==null?`, last moved ${s.daysSinceStageChange} days ago.`:", never moved."),R&&(a.push("Stage has not moved in over 60 days"),i.push("Have the next real conversation that would justify a stage move."))}n.push({key:"pipeline_momentum",label:"Pipeline momentum",weight:om.pipeline_momentum,earned:Math.round(A),detail:T,direction:A>om.pipeline_momentum*.5?"positive":"neutral"});let L=n.reduce((I,R)=>I+R.earned,0);s.agent.temperature==="hot"&&(L+=4,r.push("You marked this relationship hot")),s.agent.temperature==="cold"&&(L-=4,a.push("You marked this relationship cold")),h&&(L-=3),L=Math.max(0,Math.min(100,Math.round(L)));const M=L>=75?"thriving":L>=55?"healthy":L>=35?"cooling":"at_risk";return{agent_id:s.agent.id,score:L,band:M,components:n,positives:r,negatives:a,improvements:Array.from(new Set(i)).slice(0,4),inputs:{days_since_touch:s.daysSinceTouch,touches_90:s.touches90,touches_30:s.touches30,distinct_touch_months_6mo:s.distinctTouchMonths,shares:s.shares.length,kit_opens:s.totalKitOpens,downloads:s.downloads,cta_clicks:s.ctaClicks,questions:s.questions,meeting_requests:s.meetingRequests,events_attended:s.attended,no_shows:s.noShows,invited_not_registered:s.invitedNotRegistered,open_follow_ups:s.openFollowUps.length,overdue_follow_ups:s.overdueFollowUps.length,completed_follow_ups:s.completedFollowUps.length,stage:s.agent.stage,days_since_stage_change:s.daysSinceStageChange,temperature:s.agent.temperature},weights:{...om},engine_version:frs,calculated_at:t.toISOString()}}const yrs=[{key:"high_intent",label:"High-intent engagement",blurb:"They took a real action — respond while it is warm.",tone:"rose"},{key:"renewed_interest",label:"Renewed interest",blurb:"Someone quiet came back and engaged again.",tone:"violet"},{key:"event_follow_up",label:"Event follow-up needed",blurb:"Within 48 hours of an event is where relationships are made.",tone:"indigo"},{key:"resource_follow_up",label:"Resource follow-up needed",blurb:"You shared value — close the loop personally.",tone:"teal"},{key:"overdue_commitment",label:"Overdue commitment",blurb:"You said you would follow up. Keep your word.",tone:"orange"},{key:"going_cold",label:"Relationship going cold",blurb:"Momentum is fading. A no-ask check-in resets it.",tone:"amber"},{key:"no_touch",label:"No meaningful touch recently",blurb:"Long silence. Restart the relationship, do not pitch.",tone:"slate"},{key:"ready_deeper",label:"Ready for a deeper conversation",blurb:"Signals suggest they are open to going further.",tone:"green"}],Pcr={urgent:100,high:70,medium:40,low:15},d2=(s,t=new Date)=>new Date(t.getTime()+s*grs).toISOString(),j5=s=>s.first_name||"there",Lcr=3;function u2(s,t,n={}){var o,c;const r=j5(t.agent),a=(o=t.agent.goals)==null?void 0:o.trim(),i=(c=t.agent.challenges)==null?void 0:c.trim(),l=i?` You mentioned ${i.replace(/\.$/,"")} — that's still on my mind.`:a?` You mentioned ${a.replace(/\.$/,"")} — still thinking about that with you.`:"";switch(s){case"high_intent":return`Hey ${r} — saw you spent some time in the ${n.kitTitle??"resources"} I sent over. No agenda here; I'd just love to hear what stood out and what questions came up.${l} Any chance for a quick call this week?`;case"renewed_interest":return`${r}! You popped back into ${n.kitTitle??"that resource"} I shared a while back — figured I'd check in. How's everything going on your end?${l}`;case"event_follow_up":return`${r}, really glad you were at ${n.eventTitle??"the session"}. What was the most useful part for you? Happy to send over anything specific that would help you put it to work.`;case"event_no_show":return`Hey ${r} — noticed you couldn't make ${n.eventTitle??"the session"}, no worries at all. Life happens. Want me to send you the highlights, or would a quick 1:1 be more useful?`;case"event_invite_nudge":return`${r} — I've got ${n.eventTitle??"a small session"} coming up${n.eventWhen?` on ${n.eventWhen}`:""} and thought of you. Small group, real conversation, nothing salesy. Want me to save you a seat?`;case"resource_follow_up":return`Hey ${r} — I sent over ${n.kitTitle??"a few resources"} a bit ago. Didn't want it to get buried. Did any of it land, or is there something more specific I can pull together for you?`;case"resource_unopened":return`${r}, I sent you ${n.kitTitle??"something"} that I genuinely think would help — might've gone to spam. Want me to just walk you through the short version instead?`;case"overdue_commitment":return`Hey ${r} — I owe you a follow-up on "${n.followUpTitle??"what we talked about"}". Circling back now.${l} When's a good time?`;case"going_cold":return`${r} — it's been a bit. No agenda, genuinely just checking in on you. How's business feeling right now?${l}`;case"no_touch":return`Hey ${r} — long overdue message from me. I've been thinking about our last conversation and wanted to see how you're doing. No pitch, just catching up.`;case"ready_deeper":return`${r}, based on what you've shared I think it's worth a real conversation about what you actually want the next chapter to look like — no pressure either direction. Coffee or a call this week?`;case"share_value":return`${r} — put together ${n.kitTitle?`"${n.kitTitle}"`:"a small set of resources"} that I think fits exactly where you are right now. Sending it because it's useful, not because I want anything. Let me know if it helps.`;default:return`Hey ${r} — checking in. How are things going?${l}`}}function Icr(s,t,n=new Date){const r=[],a=s.agent;if(a.stage==="not_a_fit")return r;const i=s.daysSinceTouch!==null&&s.daysSinceTouch{var v;return(v=t.kits.find(b=>b.id===y))==null?void 0:v.title},o=y=>{r.push({...y,message_source:"rules",rank_score:y.rank_score??Pcr[y.priority]})},c=s.shares.find(y=>y.engagement_level==="high_intent");if(s.meetingRequests>0||s.questions>0||c){const y=c?l(c.kit_id):void 0,v=[s.meetingRequests>0&&`${s.meetingRequests} meeting request(s) submitted`,s.questions>0&&`${s.questions} question(s) asked inside a shared kit`,c&&`Kit engagement is classified High Intent (${c.open_count} opens)`,s.downloads>0&&`${s.downloads} file download(s)`].filter(Boolean);o({agent_id:a.id,rec_key:"high_intent",signal_group:"high_intent",signal_label:"High-intent engagement",action_type:"respond_to_intent",channel:s.meetingRequests>0?"call":"text",title:`Call ${j5(a)} — they are actively engaging`,reasons:v,priority:"urgent",suggested_due_at:d2(1,n),draft_message:u2("high_intent",s,{kitTitle:y}),suggested_kit_id:(c==null?void 0:c.kit_id)??null,source_signals:{meeting_requests:s.meetingRequests,questions:s.questions,downloads:s.downloads,share_id:c==null?void 0:c.id},rank_score:100+s.meetingRequests*5})}const d=s.shares.find(y=>y.last_opened_at&&y.first_opened_at&&Yx(y.last_opened_at,n)<=7&&Yx(y.first_opened_at,y.last_opened_at)>=14&&(y.open_count||0)>1);d&&(s.daysSinceTouch===null||s.daysSinceTouch>21)&&o({agent_id:a.id,rec_key:"renewed_interest",signal_group:"renewed_interest",signal_label:"Renewed interest",action_type:"reengage",channel:"text",title:`${j5(a)} came back to a kit you shared`,reasons:[`Re-opened "${l(d.kit_id)??"a shared kit"}" ${Yx(d.last_opened_at,n)} day(s) ago`,`${d.open_count} total opens`,s.daysSinceTouch===null?"No personal touch logged":`${s.daysSinceTouch} days since your last personal touch`],priority:"high",suggested_due_at:d2(2,n),draft_message:u2("renewed_interest",s,{kitTitle:l(d.kit_id)}),suggested_kit_id:d.kit_id,source_signals:{share_id:d.id,open_count:d.open_count},rank_score:88});const u=s.attendees.filter(y=>y.checked_in_at&&Yx(y.checked_in_at,n)<=7&&y.followup_status!=="done").sort((y,v)=>+new Date(v.checked_in_at)-+new Date(y.checked_in_at))[0];if(u){const y=t.events.find(b=>b.id===u.event_id),v=Math.round((n.getTime()-new Date(u.checked_in_at).getTime())/36e5);o({agent_id:a.id,rec_key:`event_follow_up:${u.event_id}`,signal_group:"event_follow_up",signal_label:"Event follow-up needed",action_type:"event_follow_up",channel:"call",title:`Follow up on ${(y==null?void 0:y.title)??"the event"} — ${v}h since they attended`,reasons:[`Checked in to "${(y==null?void 0:y.title)??"event"}" ${v} hours ago`,`Follow-up status is "${u.followup_status??"pending"}"`,v<=48?"Inside the 48-hour window where follow-up matters most":"Past the ideal 48-hour window — still worth doing today"],priority:v<=48?"urgent":"high",suggested_due_at:d2(v<=48?1:0,n),draft_message:u2("event_follow_up",s,{eventTitle:y==null?void 0:y.title}),suggested_event_id:u.event_id,suggested_kit_id:(y==null?void 0:y.resource_kit_id)??null,source_signals:{attendee_id:u.id,hours_since:v},rank_score:v<=48?96:74})}else{const y=s.attendees.find(v=>v.no_show_at&&Yx(v.no_show_at,n)<=10);if(y){const v=t.events.find(b=>b.id===y.event_id);o({agent_id:a.id,rec_key:`event_no_show:${y.event_id}`,signal_group:"event_follow_up",signal_label:"Event follow-up needed",action_type:"no_show_recovery",channel:"text",title:`${j5(a)} missed ${(v==null?void 0:v.title)??"an event"} — recover gracefully`,reasons:[`Registered but did not attend "${(v==null?void 0:v.title)??"event"}"`,"No-show recovery works best within a week, with zero guilt"],priority:"medium",suggested_due_at:d2(2,n),draft_message:u2("event_no_show",s,{eventTitle:v==null?void 0:v.title}),suggested_event_id:y.event_id,source_signals:{attendee_id:y.id},rank_score:52})}}const h=s.shares.find(y=>y.first_opened_at&&Yx(y.first_opened_at,n)>=3&&Yx(y.first_opened_at,n)<=30&&(s.daysSinceTouch===null||s.lastTouchAt&&new Date(s.lastTouchAt)!y.first_opened_at&&Yx(y.created_at,n)>=5&&y.status==="active");h?o({agent_id:a.id,rec_key:`resource_follow_up:${h.id}`,signal_group:"resource_follow_up",signal_label:"Resource follow-up needed",action_type:"resource_follow_up",channel:"text",title:`Close the loop on "${l(h.kit_id)??"the kit"}"`,reasons:[`Opened ${Yx(h.first_opened_at,n)} day(s) ago`,`${h.open_count} open(s), engagement level "${h.engagement_level}"`,"No personal touch logged since they viewed it"],priority:"high",suggested_due_at:d2(2,n),draft_message:u2("resource_follow_up",s,{kitTitle:l(h.kit_id)}),suggested_kit_id:h.kit_id,source_signals:{share_id:h.id},rank_score:78}):m&&o({agent_id:a.id,rec_key:`resource_unopened:${m.id}`,signal_group:"resource_follow_up",signal_label:"Resource follow-up needed",action_type:"resource_nudge",channel:"text",title:`Shared kit never opened — nudge ${j5(a)} personally`,reasons:[`Shared ${Yx(m.created_at,n)} days ago and never opened`,"A personal message beats a resend"],priority:"medium",suggested_due_at:d2(2,n),draft_message:u2("resource_unopened",s,{kitTitle:l(m.kit_id)}),suggested_kit_id:m.kit_id,source_signals:{share_id:m.id},rank_score:46});const p=s.overdueFollowUps.sort((y,v)=>+new Date(y.due_at)-+new Date(v.due_at))[0];if(p){const y=Yx(p.due_at,n);o({agent_id:a.id,rec_key:`overdue:${p.id}`,signal_group:"overdue_commitment",signal_label:"Overdue commitment",action_type:"clear_overdue",channel:p.touch_type||"call",title:`Overdue ${y} day(s): ${p.title}`,reasons:[`Follow-up "${p.title}" was due ${y} day(s) ago`,`Priority: ${p.priority??"medium"}`],priority:y>7?"urgent":"high",suggested_due_at:d2(0,n),draft_message:u2("overdue_commitment",s,{followUpTitle:p.title}),source_signals:{follow_up_id:p.id,days_late:y},rank_score:92+Math.min(y,8)})}const f=d3e.indexOf(a.stage);if(!u3e.includes(a.stage)&&f>=2&&s.attended>0&&(s.totalKitOpens>0||s.downloads>0)&&(s.daysSinceStageChange===null||s.daysSinceStageChange>21)&&o({agent_id:a.id,rec_key:"ready_deeper",signal_group:"ready_deeper",signal_label:"Ready for a deeper conversation",action_type:"deeper_conversation",channel:"call",title:`Have the honest next-chapter conversation with ${j5(a)}`,reasons:[`Stage "${a.stage}" with real engagement behind it`,`${s.attended} event(s) attended and ${s.totalKitOpens} kit open(s)`,s.daysSinceStageChange!==null?`Stage unchanged for ${s.daysSinceStageChange} days`:"Stage has never moved"],priority:"high",suggested_due_at:d2(4,n),draft_message:u2("ready_deeper",s),source_signals:{stage:a.stage,attended:s.attended},rank_score:72}),s.daysSinceTouch===null&&Yx(a.created_at,n)>7)o({agent_id:a.id,rec_key:"no_first_touch",signal_group:"no_touch",signal_label:"No meaningful touch recently",action_type:"first_conversation",channel:"personal_check_in",title:`You have never logged a conversation with ${j5(a)}`,reasons:[`Added to your pipeline ${Yx(a.created_at,n)} days ago`,"No touch, kit, or event activity logged"],priority:"medium",suggested_due_at:d2(3,n),draft_message:u2("no_touch",s),source_signals:{created_at:a.created_at},rank_score:48});else if(s.daysSinceTouch!==null){const y=a.temperature==="hot"?14:a.temperature==="cold"?90:45;if(s.daysSinceTouch>y){const v=s.daysSinceTouch>y*2;o({agent_id:a.id,rec_key:v?"no_touch_long":"going_cold",signal_group:v?"no_touch":"going_cold",signal_label:v?"No meaningful touch recently":"Relationship going cold",action_type:"check_in",channel:"personal_check_in",title:`${j5(a)} has been quiet for ${s.daysSinceTouch} days`,reasons:[`Last meaningful touch ${s.daysSinceTouch} days ago`,`Your cadence for a "${a.temperature??"warm"}" relationship is ${y} days`,s.touches90?`${s.touches90} touch(es) in the last 90 days`:"No touches in the last 90 days"],priority:v?"high":"medium",suggested_due_at:d2(3,n),draft_message:u2(v?"no_touch":"going_cold",s),source_signals:{days_since_touch:s.daysSinceTouch,threshold:y},rank_score:v?62:44})}}if(!s.shares.length&&!u3e.includes(a.stage)&&t.primaryPillar==="provide"){const y=t.kits.find(v=>v.status==="published"&&(!v.audience||!a.production_context||!0));y&&o({agent_id:a.id,rec_key:"share_first_kit",signal_group:"resource_follow_up",signal_label:"Resource follow-up needed",action_type:"share_kit",channel:"resource_share",title:`Share "${y.title}" with ${j5(a)}`,reasons:["No resource has been shared with this agent yet","Your 90-day plan primary pillar is Provide — lead with value"],priority:"medium",suggested_due_at:d2(5,n),draft_message:u2("share_value",s,{kitTitle:y.title}),suggested_kit_id:y.id,source_signals:{pillar:"provide"},rank_score:38})}if(!s.attendees.length&&!u3e.includes(a.stage)&&t.primaryPillar==="connect"){const y=t.events.filter(v=>v.status==="published"&&v.starts_at&&new Date(v.starts_at)>n).sort((v,b)=>+new Date(v.starts_at)-+new Date(b.starts_at))[0];y&&o({agent_id:a.id,rec_key:`invite_event:${y.id}`,signal_group:"ready_deeper",signal_label:"Ready for a deeper conversation",action_type:"invite_to_event",channel:"event_invitation",title:`Invite ${j5(a)} to ${y.title}`,reasons:["Never invited to an event",`"${y.title}" is published and upcoming`,"Your 90-day plan primary pillar is Connect"],priority:"medium",suggested_due_at:d2(4,n),draft_message:u2("event_invite_nudge",s,{eventTitle:y.title,eventWhen:y.starts_at?new Date(y.starts_at).toLocaleDateString():void 0}),suggested_event_id:y.id,source_signals:{pillar:"connect",event_id:y.id},rank_score:40})}return(i?r.filter(y=>y.priority==="urgent"):r).sort((y,v)=>v.rank_score-y.rank_score).slice(0,3)}const V4t=[{key:"all",label:"Everything",kinds:[]},{key:"conversations",label:"Conversations",kinds:["touch","note","activity"]},{key:"pipeline",label:"Pipeline",kinds:["stage_change","temperature"]},{key:"follow_ups",label:"Follow-ups",kinds:["follow_up_created","follow_up_completed","follow_up_missed"]},{key:"value",label:"Value shared",kinds:["kit_shared","kit_engagement"]},{key:"events",label:"Events",kinds:["event_invited","event_registered","event_attended","event_no_show","event_note"]},{key:"score",label:"Score",kinds:["score"]}],Rcr={page_view:"Viewed the kit",resource_open:"Opened a resource",file_download:"Downloaded a file",video_start:"Started a video",video_complete:"Finished a video",external_link_click:"Clicked a link",primary_cta_click:"Clicked the main call to action",question_submitted:"Submitted a question",meeting_requested:"Requested a meeting"};function Dcr(s,t,n=[],r=new Date){const a=[],i=t.activities.filter(c=>c.agent_id===s.agent.id),l=c=>{var d;return((d=t.kits.find(u=>u.id===c))==null?void 0:d.title)??"Resource kit"},o=c=>{var d;return((d=t.events.find(u=>u.id===c))==null?void 0:d.title)??"Event"};for(const c of i)a.push({id:`act:${c.id}`,kind:xrs.includes(c.activity_type)?c.activity_type==="note"?"note":"touch":"activity",at:c.created_at,title:c.title,detail:c.description??void 0,meta:{activity_type:c.activity_type,pillar:c.pillar}});for(const c of s.stageChanges)a.push({id:`stage:${c.id}`,kind:"stage_change",at:c.created_at,title:`Stage moved to ${c.to_stage.replace(/_/g," ")}`,detail:c.from_stage?`From ${c.from_stage.replace(/_/g," ")}`:void 0});for(const c of t.followUps.filter(d=>d.agent_id===s.agent.id))a.push({id:`fuc:${c.id}`,kind:"follow_up_created",at:c.created_at,title:`Follow-up created: ${c.title}`,detail:c.due_at?`Due ${new Date(c.due_at).toLocaleDateString()}`:void 0}),c.completed_at?a.push({id:`fud:${c.id}`,kind:"follow_up_completed",at:c.completed_at,title:`Follow-up completed: ${c.title}`}):c.due_at&&new Date(c.due_at)d.agent_id===s.agent.id))a.push({id:`en:${c.id}`,kind:"event_note",at:c.created_at,title:`Event note — ${o(c.event_id)}`,detail:c.note});for(const c of s.scoreEvents)a.push({id:`sc:${c.id}`,kind:"score",at:c.created_at,title:`${c.points>0?"+":""}${c.points} Attract score — ${c.category}`,detail:c.description??void 0});return a.sort((c,d)=>+new Date(d.at)-+new Date(c.at))}function Ocr(s,t,n){return s.shares.slice().sort((r,a)=>+new Date(a.created_at)-+new Date(r.created_at)).map(r=>{var m;const a=s.shareEvents[r.id]??[],i=a.filter(p=>p.event_type==="file_download").length,l=a.filter(p=>p.event_type==="primary_cta_click"||p.event_type==="external_link_click").length,o=a.filter(p=>p.event_type==="question_submitted").length,c=a.filter(p=>p.event_type==="meeting_requested").length,d=r.engagement_level==="high_intent"||c>0?"High Intent":r.engagement_level==="engaged"||i>0||l>0||o>0?"Engaged":r.first_opened_at?"Viewed":"Sent",u=t.followUps.filter(p=>p.agent_id===s.agent.id&&new Date(p.created_at)>=new Date(r.created_at)).sort((p,f)=>+new Date(p.created_at)-+new Date(f.created_at))[0]??null,h=s.stageChanges.filter(p=>new Date(p.created_at)>new Date(r.created_at)).sort((p,f)=>+new Date(p.created_at)-+new Date(f.created_at))[0]??null;return{share:r,kitTitle:((m=t.kits.find(p=>p.id===r.kit_id))==null?void 0:m.title)??"Resource kit",shareUrl:`${n}/attract-kit/${r.share_token}`,events:a,firstViewedAt:r.first_opened_at??null,lastViewedAt:r.last_opened_at??null,visits:r.open_count??0,downloads:i,ctaClicks:l,questions:o,meetingRequests:c,classification:d,followUp:u,stageAdvancedAfter:h}})}function Fcr(s,t){const n=new Set(s.shares.map(l=>l.kit_id)),r=t.kits.filter(l=>l.status==="published"&&!n.has(l.id));if(!r.length)return null;const a=r.find(l=>l.pillar&&l.pillar===s.agent.primary_pillar);if(a)return{kit:a,why:`Matches this agent's primary pillar (${s.agent.primary_pillar}) and has not been shared yet.`};const i=r.find(l=>(l.audience??"").toLowerCase().includes("new"));return i&&s.agent.stage==="new_connection"?{kit:i,why:"They are a new connection and this kit is built for early-stage relationships."}:{kit:r[0],why:"Published, relevant, and not yet shared with this agent."}}const Oh=q;function zcr(){const{user:s}=vs();return ct({queryKey:["attract-intel-data",s==null?void 0:s.id],enabled:!!s,staleTime:3e4,queryFn:async()=>{var f,x;const[t,n,r,a,i,l,o,c,d,u,h,m]=await Promise.all([Oh.from("attract_agents").select("*").order("updated_at",{ascending:!1}),Oh.from("attract_activities").select("*").order("created_at",{ascending:!1}).limit(2e3),Oh.from("attract_follow_ups").select("*").order("created_at",{ascending:!1}).limit(2e3),Oh.from("attract_kit_shares").select("*").order("created_at",{ascending:!1}).limit(1e3),Oh.from("attract_kit_events").select("*").order("created_at",{ascending:!1}).limit(2e3),Oh.from("attract_event_attendees").select("*").order("created_at",{ascending:!1}).limit(2e3),Oh.from("attract_events").select("id, title, starts_at, status, resource_kit_id, public_slug").limit(500),Oh.from("attract_pipeline_history").select("*").order("created_at",{ascending:!1}).limit(2e3),Oh.from("attract_score_events").select("*").order("created_at",{ascending:!1}).limit(2e3),Oh.from("attract_resource_kits").select("id, title, audience, pillar, status, is_template").eq("is_template",!1),Oh.from("attract_event_notes").select("*").order("created_at",{ascending:!1}).limit(1e3),Oh.from("attract_settings").select("primary_pillar, attraction_style, ninety_day_plan").eq("user_id",s.id).maybeSingle()]),p=[t,n,r,a,i,l,o,c,d,u,h].find(y=>y.error);if(p)throw p.error;return{agents:t.data??[],activities:n.data??[],followUps:r.data??[],shares:a.data??[],kitEvents:i.data??[],attendees:l.data??[],events:o.data??[],stageChanges:c.data??[],scoreEvents:d.data??[],kits:u.data??[],eventNotes:h.data??[],primaryPillar:((f=m==null?void 0:m.data)==null?void 0:f.primary_pillar)??((x=m==null?void 0:m.data)==null?void 0:x.attraction_style)??null}}})}function CW(){const s=zcr(),t=j.useMemo(()=>{if(!s.data)return[];const r=new Date;return s.data.agents.map(a=>{const i=Tcr(a,s.data,r),l=Mcr(i,r),o=Icr(i,s.data,r);return{agent:a,signals:i,score:l,recommendations:o,primary:o[0]??null}})},[s.data]),n=j.useMemo(()=>new Map(t.map(r=>[r.agent.id,r])),[t]);return{...s,dataset:s.data,intel:t,byId:n}}function Bcr(s){const{dataset:t,byId:n,isLoading:r,error:a,refetch:i}=CW(),l=s?n.get(s)??null:null,o=j.useMemo(()=>l&&t?Dcr(l.signals,t,t.eventNotes??[]):[],[l,t]),c=j.useMemo(()=>l&&t?Ocr(l.signals,t,typeof window<"u"?window.location.origin:""):[],[l,t]),d=j.useMemo(()=>l&&t?Fcr(l.signals,t):null,[l,t]);return{item:l,dataset:t,timeline:o,valueShared:c,nextKit:d,isLoading:r,error:a,refetch:i}}function vrs(){const{user:s}=vs(),t=Qt();return yt({mutationFn:async({items:n,silent:r})=>{if(!s||!n.length)return{count:0,silent:r};const a=n.map(i=>({user_id:s.id,agent_id:i.agent.id,score:i.score.score,band:i.score.band,components:i.score.components,positives:i.score.positives,negatives:i.score.negatives,improvements:i.score.improvements,inputs:i.score.inputs,weights:i.score.weights,engine_version:frs,calculated_at:i.score.calculated_at}));for(let i=0;i{t.invalidateQueries({queryKey:["attract-score-snapshots"]}),n&&!r&&re.success(`Recalculated ${n} relationship score${n===1?"":"s"}`)},onError:n=>re.error(n.message??"Could not save scores")})}function JIe(){const{user:s}=vs();return ct({queryKey:["attract-recommendations",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Oh.from("attract_recommendations").select("*").order("rank_score",{ascending:!1});if(n)throw n;return t??[]}})}function e8e(){const{user:s}=vs(),t=Qt();return yt({mutationFn:async n=>{if(!s)return{inserted:0,refreshed:0};const r=n.flatMap(u=>u.recommendations),{data:a,error:i}=await Oh.from("attract_recommendations").select("id, agent_id, rec_key, status, snoozed_until");if(i)throw i;const l=new Map((a??[]).map(u=>[`${u.agent_id}|${u.rec_key}`,u])),o=[],c=[],d=new Date;for(const u of r){const h=`${u.agent_id}|${u.rec_key}`,m=l.get(h),p={user_id:s.id,agent_id:u.agent_id,rec_key:u.rec_key,signal_group:u.signal_group,action_type:u.action_type,channel:u.channel,title:u.title,reasons:u.reasons,priority:u.priority,rank_score:u.rank_score,suggested_due_at:u.suggested_due_at,draft_message:u.draft_message,message_source:u.message_source,suggested_kit_id:u.suggested_kit_id??null,suggested_event_id:u.suggested_event_id??null,source_signals:u.source_signals};m?m.status==="open"?c.push({id:m.id,patch:{...p,generated_at:d.toISOString()}}):m.status==="snoozed"&&m.snoozed_until&&new Date(m.snoozed_until)<=d&&c.push({id:m.id,patch:{...p,status:"open",snoozed_until:null,generated_at:d.toISOString()}}):o.push(p)}if(o.length){const{error:u}=await Oh.from("attract_recommendations").insert(o);if(u)throw u}for(const u of c)await Oh.from("attract_recommendations").update(u.patch).eq("id",u.id);return{inserted:o.length,refreshed:c.length}},onSuccess:()=>t.invalidateQueries({queryKey:["attract-recommendations"]}),onError:n=>re.error(n.message??"Could not sync recommendations")})}function Ucr(){const{user:s}=vs(),t=Qt(),n=()=>{t.invalidateQueries({queryKey:["attract-recommendations"]}),t.invalidateQueries({queryKey:["attract-followups"]}),t.invalidateQueries({queryKey:["attract-intel-data"]}),t.invalidateQueries({queryKey:["attract-activities"]})},r=yt({mutationFn:async({id:c,patch:d})=>{const{error:u}=await Oh.from("attract_recommendations").update(d).eq("id",c);if(u)throw u},onSuccess:n,onError:c=>re.error(c.message)}),a=yt({mutationFn:async c=>{const{error:d}=await Oh.from("attract_recommendations").update({status:"dismissed",dismissed_at:new Date().toISOString()}).eq("id",c);if(d)throw d},onSuccess:()=>{n(),re.success("Dismissed")}}),i=yt({mutationFn:async({id:c,days:d})=>{const u=new Date(Date.now()+d*864e5).toISOString(),{error:h}=await Oh.from("attract_recommendations").update({status:"snoozed",snoozed_until:u}).eq("id",c);if(h)throw h},onSuccess:()=>{n(),re.success("Snoozed")}}),l=yt({mutationFn:async c=>{if(c.follow_up_id){const{data:h}=await Oh.from("attract_follow_ups").select("id, completed_at").eq("id",c.follow_up_id).maybeSingle();if(h&&!h.completed_at)return{id:h.id,existed:!0}}const{data:d,error:u}=await Oh.from("attract_follow_ups").insert({user_id:s.id,agent_id:c.agent_id,title:c.title,touch_type:c.channel,due_at:c.suggested_due_at,priority:c.priority==="urgent"?"high":c.priority,notes:[c.draft_message,"","Why: "+(c.reasons??[]).join(" · ")].join(` `)}).select("id").single();if(u)throw u;return await Oh.from("attract_recommendations").update({follow_up_id:d.id}).eq("id",c.id),{id:d.id,existed:!1}},onSuccess:c=>{n(),re.success(c.existed?"Follow-up already exists":"Follow-up created")},onError:c=>re.error(c.message)}),o=yt({mutationFn:async({rec:c,note:d})=>{const u=new Date().toISOString(),{error:h}=await Oh.from("attract_activities").insert({user_id:s.id,agent_id:c.agent_id,activity_type:"touch_logged",title:c.title,description:d||c.draft_message,pillar:c.signal_group==="event_follow_up"?"connect":c.signal_group==="resource_follow_up"?"provide":null,metadata:{recommendation_id:c.id,channel:c.channel,rec_key:c.rec_key}});if(h)throw h;c.follow_up_id&&await Oh.from("attract_follow_ups").update({completed_at:u}).eq("id",c.follow_up_id).is("completed_at",null),await Oh.from("attract_score_events").insert({user_id:s.id,agent_id:c.agent_id,category:"follow_up",points:2,description:`Completed: ${c.title}`});const{error:m}=await Oh.from("attract_recommendations").update({status:"completed",completed_at:u}).eq("id",c.id);if(m)throw m},onSuccess:()=>{n(),t.invalidateQueries({queryKey:["attract-score"]}),re.success("Logged — timeline and score updated")},onError:c=>re.error(c.message)});return{update:r,dismiss:a,snooze:i,createFollowUp:l,logCompleted:o}}function qcr(){const{user:s}=vs(),t=Qt();return yt({mutationFn:async n=>{const{error:r}=await Oh.from("attract_activities").insert({user_id:s.id,...n});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-intel-data"]}),t.invalidateQueries({queryKey:["attract-activities"]}),t.invalidateQueries({queryKey:["attract-agents"]}),re.success("Logged")},onError:n=>re.error(n.message)})}const H4t={thriving:{label:"Thriving",ring:"ring-emerald-200",text:"text-emerald-700",bg:"bg-emerald-50"},healthy:{label:"Healthy",ring:"ring-teal-200",text:"text-teal-700",bg:"bg-teal-50"},cooling:{label:"Cooling",ring:"ring-amber-200",text:"text-amber-700",bg:"bg-amber-50"},at_risk:{label:"At risk",ring:"ring-rose-200",text:"text-rose-700",bg:"bg-rose-50"}};function dat({score:s,className:t}){const n=H4t[s.band]??H4t.cooling;return e.jsxs(Be,{variant:"outline",className:Mt("rounded-full gap-1.5 font-medium",n.bg,n.text,"border-transparent ring-1",n.ring,t),children:[e.jsx("span",{className:"tabular-nums font-semibold",children:s.score}),e.jsx("span",{className:"opacity-70",children:"·"}),e.jsx("span",{children:n.label})]})}function brs({score:s}){return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-baseline gap-3",children:[e.jsx("div",{className:"text-4xl font-semibold tabular-nums text-slate-900",children:s.score}),e.jsx("div",{className:"text-slate-400 text-sm",children:"/ 100"}),e.jsx(dat,{score:s})]}),e.jsxs("div",{className:"text-[12px] text-slate-500",children:["Calculated ",new Date(s.calculated_at).toLocaleString()," · engine ",s.engine_version," · rules only, no AI guessing."]}),e.jsx("div",{className:"space-y-2.5",children:s.components.map(t=>{const n=t.weight?Math.round(t.earned/t.weight*100):0;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-[13px]",children:[e.jsx("span",{className:"font-medium text-slate-800",children:t.label}),e.jsxs("span",{className:"tabular-nums text-slate-500",children:[t.earned,e.jsxs("span",{className:"text-slate-300",children:["/",t.weight]})]})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-100 mt-1 overflow-hidden",children:e.jsx("div",{className:Mt("h-full rounded-full transition-all",n>=70?"bg-emerald-500":n>=40?"bg-amber-400":"bg-rose-400"),style:{width:`${Math.max(n,2)}%`}})}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-1 leading-snug",children:t.detail})]},t.key)})}),!!s.positives.length&&e.jsxs("div",{className:"rounded-xl bg-emerald-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] uppercase tracking-wider font-semibold text-emerald-700 mb-1.5",children:[e.jsx(rc,{className:"h-3.5 w-3.5"})," Helping"]}),e.jsx("ul",{className:"text-[12.5px] text-emerald-900/80 space-y-1 list-disc pl-4",children:s.positives.map((t,n)=>e.jsx("li",{children:t},n))})]}),!!s.negatives.length&&e.jsxs("div",{className:"rounded-xl bg-rose-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] uppercase tracking-wider font-semibold text-rose-700 mb-1.5",children:[e.jsx(nS,{className:"h-3.5 w-3.5"})," Hurting"]}),e.jsx("ul",{className:"text-[12.5px] text-rose-900/80 space-y-1 list-disc pl-4",children:s.negatives.map((t,n)=>e.jsx("li",{children:t},n))})]}),!!s.improvements.length&&e.jsxs("div",{className:"rounded-xl bg-violet-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] uppercase tracking-wider font-semibold text-violet-700 mb-1.5",children:[e.jsx(Z2,{className:"h-3.5 w-3.5"})," What would improve it"]}),e.jsx("ul",{className:"text-[12.5px] text-violet-900/80 space-y-1 list-disc pl-4",children:s.improvements.map((t,n)=>e.jsx("li",{children:t},n))})]})]})}function G4t({className:s}){const{intel:t}=CW(),[n,r]=j.useState(""),[a,i]=j.useState(!1),l=Wn(),o=j.useMemo(()=>{const c=n.trim().toLowerCase();return c?t.filter(d=>{const u=d.agent;return[u.first_name,u.last_name,u.brokerage,u.city,u.email,...u.tags??[]].filter(Boolean).join(" ").toLowerCase().includes(c)}).slice(0,6):[]},[t,n]);return e.jsxs("div",{className:Mt("relative",s),children:[e.jsx(Fr,{className:"h-3.5 w-3.5 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx("input",{value:n,onChange:c=>{r(c.target.value),i(!0)},onFocus:()=>i(!0),onBlur:()=>setTimeout(()=>i(!1),150),placeholder:"Search relationships","aria-label":"Search relationships",className:"w-full h-9 rounded-full bg-white/5 border border-white/10 pl-9 pr-3 text-[12.5px] text-white placeholder:text-slate-500 focus:outline-none focus:ring-1 focus:ring-violet-500/60"}),a&&!!o.length&&e.jsx("div",{className:"absolute z-50 mt-1.5 w-full rounded-xl bg-white shadow-xl ring-1 ring-slate-200 overflow-hidden",children:o.map(c=>e.jsxs("button",{onMouseDown:()=>{l(`/attract/agents/${c.agent.id}`),r(""),i(!1)},className:"w-full text-left px-3 py-2.5 hover:bg-slate-50 flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[13px] font-medium text-slate-900 truncate",children:[c.agent.first_name,c.agent.last_name].filter(Boolean).join(" ")}),e.jsxs("span",{className:"block text-[11px] text-slate-500 truncate capitalize",children:[c.agent.stage.replace(/_/g," "),c.agent.brokerage?` · ${c.agent.brokerage}`:""]})]}),e.jsx(dat,{score:c.score})]},c.agent.id))}),a&&!!n.trim()&&!o.length&&e.jsxs("div",{className:"absolute z-50 mt-1.5 w-full rounded-xl bg-white shadow-xl ring-1 ring-slate-200 px-3 py-2.5 text-[12.5px] text-slate-500",children:['No relationships match "',n,'".']})]})}const eBe=[{to:"/attract",label:"Today",icon:eN,exact:!0,hint:"Your five best moves"},{to:"/attract/agents",label:"Agents",icon:Bn,hint:"Your recruiting pipeline"},{to:"/attract/toolkit",label:"Toolkit",icon:og,hint:"Kits, scripts, objections"},{to:"/attract/calculator",label:"Calculator",icon:Qw,hint:"Show them their numbers"},{to:"/attract/attract-page",label:"Attract Page",icon:Ok,hint:"Your public join page"},{to:"/attract/results",label:"Results",icon:Cl,hint:"Who joined, what worked"}];function $cr(){const s=Od(),{settings:t,isLoading:n}=cat(),r=!n&&!!t&&!t.onboarding_completed_at,a=s.pathname==="/attract/onboarding";if(r&&!a&&!s.pathname.startsWith("/attract/settings"))return e.jsx(td,{to:"/attract/onboarding",replace:!0});const i=(o,c)=>{const d=o.icon;return e.jsx(BT,{to:o.to,end:o.exact,className:({isActive:u})=>Mt("group relative flex items-center gap-3 rounded-xl px-3 py-2.5 text-[13.5px] font-medium transition-all",u?"bg-white/[0.08] text-white ring-1 ring-inset ring-white/15":"text-slate-400 hover:bg-white/[0.04] hover:text-white"),children:({isActive:u})=>e.jsxs(e.Fragment,{children:[e.jsx("span",{className:Mt("absolute left-0 top-1/2 -translate-y-1/2 h-6 w-[3px] rounded-r-full bg-gradient-to-b from-violet-400 to-indigo-500 transition-opacity",u?"opacity-100":"opacity-0")}),e.jsx(d,{className:Mt("h-4 w-4 flex-shrink-0",u?"text-violet-300":"opacity-70 group-hover:opacity-100")}),e.jsxs("span",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"block truncate",children:o.label}),e.jsx("span",{className:"block text-[10.5px] text-slate-500 font-normal truncate",children:o.hint})]})]})},o.to)},l=[{to:"/attract/follow-up",label:"Follow-Up Center"},{to:"/attract/opportunities",label:"Opportunities"},{to:"/attract/settings",label:"Settings"}];return e.jsxs("div",{className:"attract-root min-h-screen bg-[#F5F6FA] text-slate-900",children:[e.jsx("style",{children:` .attract-root { --a-primary: 139 92 246; --a-primary-strong: 109 40 217; --a-indigo: 79 70 229; --a-teal: 20 184 166; --a-green: 22 163 74; --a-orange: 249 115 22; --a-rose: 244 63 94; } .attract-root .btn-primary { background: linear-gradient(135deg, rgb(var(--a-primary)) 0%, rgb(var(--a-indigo)) 100%); } `}),e.jsxs("div",{className:"flex min-h-screen",children:[e.jsxs("aside",{className:"hidden lg:flex w-[264px] flex-col bg-[#0B0F1E] text-slate-200 border-r border-white/5 relative",children:[e.jsx("div",{className:"pointer-events-none absolute -top-24 -left-16 h-64 w-64 rounded-full bg-violet-700/20 blur-3xl"}),e.jsxs("div",{className:"relative px-5 py-6 border-b border-white/[0.07]",children:[e.jsxs(BT,{to:"/dashboard",className:"inline-flex items-center gap-1.5 text-[10.5px] uppercase tracking-[0.16em] text-slate-500 hover:text-white transition-colors",children:[e.jsx(Aa,{className:"h-3 w-3"})," LevelUp Hub"]}),e.jsxs("div",{className:"mt-3.5 flex items-center gap-2.5",children:[e.jsx("div",{className:"h-9 w-9 rounded-xl bg-gradient-to-br from-violet-500 to-indigo-600 grid place-items-center shadow-lg shadow-violet-900/50",children:e.jsx(IM,{className:"h-4 w-4 text-white"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[14.5px] font-semibold tracking-tight text-white leading-none",children:"ATTRACT"}),e.jsx("div",{className:"text-[10.5px] text-slate-500 leading-tight mt-1",children:"Recruit agents to your team"})]})]})]}),e.jsx("div",{className:"relative px-3.5 pt-3.5",children:e.jsx(G4t,{})}),e.jsxs("nav",{className:"relative flex-1 overflow-y-auto py-3 px-2.5 space-y-1",children:[eBe.map(o=>i(o)),e.jsx("div",{className:"pt-5 pb-1 px-3 text-[10px] uppercase tracking-[0.16em] text-slate-600 font-semibold",children:"More"}),l.map(o=>e.jsx(BT,{to:o.to,className:({isActive:c})=>Mt("block rounded-lg px-3 py-2 text-[12.5px]",c?"bg-white/10 text-white":"text-slate-500 hover:text-white hover:bg-white/5"),children:o.label},o.to))]}),e.jsx("div",{className:"relative px-3.5 py-4 border-t border-white/5",children:e.jsxs("div",{className:"rounded-xl bg-gradient-to-br from-violet-600/20 to-indigo-600/10 ring-1 ring-inset ring-violet-500/20 p-3.5",children:[e.jsx("div",{className:"text-[11px] font-semibold text-violet-200",children:"One job"}),e.jsx("div",{className:"text-[11.5px] text-slate-400 mt-1 leading-snug",children:"Move one agent one step closer today. Verify compensation details before you share them."})]})})]}),e.jsxs("div",{className:"lg:hidden fixed top-0 inset-x-0 z-40 bg-[#0B0F1E]/95 backdrop-blur text-white px-4 py-3 flex items-center gap-3 border-b border-white/10",children:[e.jsx(BT,{to:"/dashboard",className:"text-slate-400",children:e.jsx(Aa,{className:"h-4 w-4"})}),e.jsx("div",{className:"h-8 w-8 rounded-lg bg-gradient-to-br from-violet-500 to-indigo-600 grid place-items-center",children:e.jsx(IM,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13px] font-semibold tracking-tight",children:"ATTRACT"}),e.jsx("div",{className:"text-[10px] text-slate-400",children:"Recruit agents to your team"})]}),e.jsxs(my,{children:[e.jsx($ne,{asChild:!0,children:e.jsx("button",{className:"text-slate-300 p-1","aria-label":"Open menu",children:e.jsx(AA,{className:"h-5 w-5"})})}),e.jsx(g0,{side:"right",className:"bg-[#0B0F1E] text-slate-200 border-white/10 w-[280px] overflow-y-auto",children:e.jsxs("div",{className:"pt-6",children:[e.jsx(G4t,{className:"mb-4"}),e.jsx("div",{className:"space-y-1",children:eBe.map(o=>i(o))}),e.jsx("div",{className:"mt-5 mb-1 px-3 text-[10px] uppercase tracking-[0.16em] text-slate-600 font-semibold",children:"More"}),l.map(o=>e.jsx(BT,{to:o.to,className:({isActive:c})=>Mt("block rounded-lg px-3 py-2.5 text-[13px]",c?"bg-white/10 text-white":"text-slate-400 hover:bg-white/5"),children:o.label},o.to))]})})]})]}),e.jsx("div",{className:"lg:hidden fixed bottom-0 inset-x-0 z-40 bg-[#0B0F1E]/95 backdrop-blur border-t border-white/10 flex pb-[env(safe-area-inset-bottom)]",children:eBe.slice(0,5).map(o=>{const c=o.icon;return e.jsxs(BT,{to:o.to,end:o.exact,className:({isActive:d})=>Mt("flex-1 min-w-0 flex flex-col items-center gap-1 py-2.5 text-[10px]",d?"text-white":"text-slate-500"),children:[e.jsx(c,{className:"h-4 w-4"}),e.jsx("span",{className:"truncate max-w-[70px]",children:o.label})]},o.to)})}),e.jsx("main",{className:"flex-1 min-w-0 pt-16 lg:pt-0 pb-24 lg:pb-0",children:e.jsx("div",{className:"max-w-[1360px] mx-auto px-4 sm:px-6 lg:px-9 py-6 lg:py-9",children:e.jsx(LZe,{})},s.pathname)})]})]})}function uat(s=!0){const{intel:t,isLoading:n}=CW(),r=vrs(),a=e8e(),i=j.useRef(!1);return j.useEffect(()=>{if(!s||n||i.current||!t.length)return;const o=sessionStorage.getItem("attract-intel-sync"),c=new Date().toISOString().slice(0,13);if(o===c){i.current=!0;return}i.current=!0,sessionStorage.setItem("attract-intel-sync",c),r.mutate({items:t,silent:!0}),a.mutate(t)},[s,n,t]),{runNow:()=>{r.mutate({items:t}),a.mutate(t)},isSyncing:r.isPending||a.isPending}}function Vcr(){const{user:s}=vs(),t=Qt(),n=ct({queryKey:["attract-daily-plan",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await q.from("attract_daily_plan").select("*").order("sort_order");if(i)throw i;return a??[]}}),r=yt({mutationFn:async a=>{const i=!a.completed,{error:l}=await q.from("attract_daily_plan").update({completed:i,progress:i?a.target:0}).eq("id",a.id);if(l)throw l},onSuccess:()=>t.invalidateQueries({queryKey:["attract-daily-plan"]})});return{items:n.data??[],isLoading:n.isLoading,toggle:r}}const XY=q;function EE(){const{user:s}=vs(),t=Qt(),n=ct({queryKey:["attract-agents",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await q.from("attract_agents").select("*").order("updated_at",{ascending:!1});if(u)throw u;return d??[]}}),r=()=>{["attract-agents","attract-intel","attract-intelligence","attract-agent-intel","attract-activities","attract-followups","attract-recommendations","attract-score","attract_milestones","attract-daily-plan"].forEach(d=>t.invalidateQueries({queryKey:[d]}))},a=yt({mutationFn:async d=>{const u={...d,user_id:s.id},{data:h,error:m}=d.id?await q.from("attract_agents").update(u).eq("id",d.id).select().single():await q.from("attract_agents").insert(u).select().single();if(m)throw m;return h},onSuccess:()=>{r(),re.success("Saved")},onError:d=>re.error(d.message)}),i=yt({mutationFn:async({id:d,to_stage:u,from_stage:h})=>{const{error:m}=await q.from("attract_agents").update({stage:u}).eq("id",d);if(m)throw m;await q.from("attract_pipeline_history").insert({user_id:s.id,agent_id:d,from_stage:h??null,to_stage:u})},onSuccess:()=>r(),onError:d=>re.error(d.message)}),l=yt({mutationFn:async({id:d,values:u,changedLabels:h,previousStage:m})=>{const{stage:p,...f}=u;if(Object.keys(f).length){const{error:x}=await XY.from("attract_agents").update(f).eq("id",d);if(x)throw x}if(p&&p!==m){const{error:x}=await XY.from("attract_agents").update({stage:p}).eq("id",d);if(x)throw x;await XY.from("attract_pipeline_history").insert({user_id:s.id,agent_id:d,from_stage:m??null,to_stage:p})}h.length&&await XY.rpc("award_attract_activity",{_user_id:s.id,_activity_type:"note",_title:"Contact details updated",_description:`Updated: ${h.join(", ")}`,_pillar:"connect",_agent_id:d,_metadata:{},_dedupe_minutes:1})},onSuccess:()=>{r(),re.success("Contact updated")},onError:d=>re.error(d.message??"Could not save contact")}),o=yt({mutationFn:async({id:d,archived:u})=>{const{error:h}=await XY.from("attract_agents").update({is_archived:u}).eq("id",d);if(h)throw h},onSuccess:(d,u)=>{r(),re.success(u.archived?"Removed from active pipeline":"Restored to pipeline")},onError:d=>re.error(d.message)}),c=yt({mutationFn:async d=>{const{error:u}=await q.from("attract_agents").delete().eq("id",d);if(u)throw u},onSuccess:()=>{r(),re.success("Contact permanently deleted")},onError:d=>re.error(d.message)});return{agents:n.data??[],activeAgents:(n.data??[]).filter(d=>!d.is_archived),isLoading:n.isLoading,upsertAgent:a,saveAgentDetails:l,moveStage:i,archiveAgent:o,deleteAgent:c}}function t8e(){const{user:s}=vs(),t=Qt(),n=ct({queryKey:["attract-followups",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await q.from("attract_follow_ups").select("*").order("due_at",{ascending:!0,nullsFirst:!1});if(i)throw i;return a??[]}}),r=yt({mutationFn:async a=>{const{error:i}=await q.from("attract_follow_ups").update({completed_at:new Date().toISOString()}).eq("id",a);if(i)throw i},onSuccess:()=>t.invalidateQueries({queryKey:["attract-followups"]})});return{followUps:n.data??[],isLoading:n.isLoading,complete:r}}function _rs(s=12){const{user:t}=vs(),n=ct({queryKey:["attract-activities",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{const{data:r,error:a}=await q.from("attract_activities").select("*").order("created_at",{ascending:!1}).limit(s);if(a)throw a;return r??[]}});return{activities:n.data??[],isLoading:n.isLoading}}const W4t={call:{icon:ba,label:"Call"},text:{icon:Ki,label:"Text"},email:{icon:ln,label:"Email"},dm:{icon:$r,label:"DM"},resource_share:{icon:tj,label:"Share a kit"},event_invitation:{icon:sv,label:"Invite to event"},personal_check_in:{icon:$X,label:"Personal check-in"}},K4t={urgent:"bg-rose-50 text-rose-700 ring-rose-200",high:"bg-orange-50 text-orange-700 ring-orange-200",medium:"bg-amber-50 text-amber-700 ring-amber-200",low:"bg-slate-50 text-slate-600 ring-slate-200"};function Hcr(s){var t;return((t=yrs.find(n=>n.key===s))==null?void 0:t.blurb)??""}function wrs(s){var t;return((t=yrs.find(n=>n.key===s))==null?void 0:t.label)??s.replace(/_/g," ")}function ITe({rec:s,agentName:t,agentStage:n,kitTitle:r,eventTitle:a,compact:i,showAgentLink:l=!0,className:o}){const{update:c,dismiss:d,snooze:u,createFollowUp:h,logCompleted:m}=Ucr(),[p,f]=j.useState(!1),[x,y]=j.useState(s.draft_message??""),v=c.isPending||d.isPending||u.isPending||h.isPending||m.isPending,b=W4t[s.channel]??W4t.personal_check_in,N=s.suggested_due_at?new Date(s.suggested_due_at):null,S=N?N{c.mutate({id:s.id,patch:{draft_message:x}},{onSuccess:()=>{f(!1),re.success("Opening message updated")}})},T=async()=>{try{await navigator.clipboard.writeText(s.draft_message??""),re.success("Opening message copied — send it yourself from your phone or inbox")}catch{re.error("Could not copy — select the text manually")}};return e.jsx(we,{className:Mt("rounded-2xl border-slate-200/70 bg-white shadow-sm overflow-hidden",o),children:e.jsxs("div",{className:"p-4 sm:p-5",children:[e.jsxs("div",{className:"flex items-start gap-3 flex-wrap",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-gradient-to-br from-violet-500 to-indigo-600 text-white grid place-items-center shadow-sm flex-shrink-0",children:e.jsx(b.icon,{className:"h-4.5 w-4.5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1 min-w-[180px]",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Be,{variant:"outline",className:Mt("rounded-full text-[10.5px] uppercase tracking-wider font-semibold ring-1 border-transparent",K4t[s.priority]??K4t.medium),children:s.priority}),e.jsx("span",{className:"text-[11px] text-violet-700 font-medium",children:wrs(s.signal_group)}),s.is_demo&&e.jsx(Be,{variant:"outline",className:"rounded-full text-[10px] bg-slate-100 text-slate-500 border-transparent",children:"Demo data"})]}),e.jsx("h3",{className:"text-[15px] font-semibold text-slate-900 mt-1.5 leading-snug",children:s.title}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-1 flex items-center gap-2 flex-wrap",children:[l?e.jsxs(xr,{to:`/attract/agents/${s.agent_id}`,className:"font-medium text-slate-700 hover:text-violet-700 inline-flex items-center gap-0.5",children:[t," ",e.jsx(gi,{className:"h-3 w-3"})]}):e.jsx("span",{className:"font-medium text-slate-700",children:t}),n&&e.jsxs("span",{className:"capitalize",children:["· ",n.replace(/_/g," ")]}),e.jsxs("span",{children:["· ",b.label]}),N&&e.jsxs("span",{className:Mt("inline-flex items-center gap-1",S?"text-rose-600 font-medium":""),children:["· ",e.jsx(Yr,{className:"h-3 w-3"})," ",S?"Due now":`Do by ${N.toLocaleDateString()}`]})]})]}),e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"rounded-full","aria-label":"More recommendation actions",children:e.jsx(ey,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",className:"w-56",children:[e.jsx(DV,{children:"Recommendation"}),e.jsx(l1,{}),e.jsxs(La,{onClick:()=>f(L=>!L),children:[e.jsx(ri,{className:"h-4 w-4 mr-2"})," Edit opening message"]}),e.jsxs(La,{onClick:T,children:[e.jsx(Pa,{className:"h-4 w-4 mr-2"})," Copy message"]}),e.jsx(l1,{}),e.jsxs(La,{onClick:()=>u.mutate({id:s.id,days:3}),children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"})," Snooze 3 days"]}),e.jsxs(La,{onClick:()=>u.mutate({id:s.id,days:7}),children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"})," Snooze 1 week"]}),e.jsxs(La,{className:"text-rose-600",onClick:()=>d.mutate(s.id),children:[e.jsx(er,{className:"h-4 w-4 mr-2"})," Dismiss"]})]})]})]}),!!(s.reasons??[]).length&&e.jsxs("div",{className:"mt-3 rounded-xl bg-slate-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10.5px] uppercase tracking-wider font-semibold text-slate-500 mb-1.5",children:[e.jsx(Jk,{className:"h-3 w-3"})," Why this, right now"]}),e.jsx("ul",{className:"space-y-1",children:s.reasons.map((L,M)=>e.jsxs("li",{className:"text-[12.5px] text-slate-700 flex gap-2",children:[e.jsx("span",{className:"text-violet-500",children:"•"}),e.jsx("span",{children:L})]},M))}),e.jsx("div",{className:"text-[11px] text-slate-400 mt-2",children:Hcr(s.signal_group)})]}),!i&&e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wider font-semibold text-slate-500 mb-1.5",children:"Suggested opening"}),p?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Fs,{value:x,onChange:L=>y(L.target.value),rows:4,className:"text-[13.5px]","aria-label":"Opening message"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{size:"sm",className:"rounded-full btn-primary text-white",onClick:A,disabled:v,children:"Save message"}),e.jsx(U,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>{y(s.draft_message??""),f(!1)},children:"Cancel"})]})]}):e.jsxs("button",{onClick:()=>f(!0),className:"w-full text-left rounded-xl border border-slate-200 bg-white p-3 text-[13.5px] leading-relaxed text-slate-700 hover:border-violet-300 transition-colors",children:[s.draft_message||"No draft message yet — click to write one.",e.jsx("span",{className:"block text-[11px] text-violet-600 mt-1.5",children:"Click to edit before you send"})]})]}),(r||a)&&e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-[11.5px]",children:[r&&e.jsxs("span",{className:"rounded-full bg-teal-50 text-teal-700 px-2.5 py-1",children:["Suggested kit: ",r]}),a&&e.jsxs("span",{className:"rounded-full bg-indigo-50 text-indigo-700 px-2.5 py-1",children:["Suggested event: ",a]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsxs(U,{size:"sm",className:"rounded-full btn-primary text-white",disabled:v,onClick:()=>m.mutate({rec:s}),children:[e.jsx(Xr,{className:"h-3.5 w-3.5 mr-1.5"})," I did this"]}),e.jsxs(U,{size:"sm",variant:"outline",className:"rounded-full",disabled:v,onClick:()=>h.mutate(s),children:[e.jsx(sv,{className:"h-3.5 w-3.5 mr-1.5"})," ",s.follow_up_id?"Follow-up created":"Create follow-up"]}),e.jsxs(U,{size:"sm",variant:"ghost",className:"rounded-full",onClick:T,children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1.5"})," Copy message"]})]}),e.jsx("div",{className:"text-[10.5px] text-slate-400 mt-2",children:"Attract never sends messages for you — copy the opening and send it from your own phone or inbox."})]})})}function Gcr({label:s="Nothing needs attention right now."}){return e.jsxs(we,{className:"rounded-2xl border-dashed border-slate-300 bg-white/60 p-8 text-center",children:[e.jsx("div",{className:"h-11 w-11 rounded-2xl bg-emerald-50 text-emerald-600 grid place-items-center mx-auto mb-3",children:e.jsx(Xr,{className:"h-5 w-5"})}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:s}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:"Log a conversation, share a resource kit, or invite someone to an event and new opportunities will appear here."})]})}const HA=[{key:"new_relationship",label:"New Relationship",help:"You know each other, but you haven’t built much yet.",color:"#94a3b8",legacy:["new_connection"],canonical:"new_connection"},{key:"building",label:"Building Relationship",help:"Real conversations and value are going back and forth.",color:"#38bdf8",legacy:["building_relationship","engaging_with_value","long_term_relationship"],canonical:"building_relationship"},{key:"curious",label:"Brokerage Curious",help:"They’ve started asking questions about how you work.",color:"#8b5cf6",legacy:["active_conversation","exploring_options"],canonical:"active_conversation"},{key:"considering",label:"Considering a Move",help:"They’re actively weighing a change.",color:"#f59e0b",legacy:["brokerage_presentation","decision_pending"],canonical:"decision_pending"},{key:"joined",label:"Joined",help:"They made the move.",color:"#16a34a",legacy:["joined"],canonical:"joined"}],s8e={key:"set_aside",label:"Set Aside",help:"Not a fit right now — the relationship still matters.",color:"#cbd5e1",legacy:["not_right_now","not_a_fit"],canonical:"not_right_now"},jrs=new Map;for(const s of[...HA,s8e])for(const t of s.legacy)jrs.set(t,s);function GA(s){return s?jrs.get(s)??HA[0]:HA[0]}function Nrs(s){return GA(s).label}function hat(s){var n;return((n=[...HA,s8e].find(r=>r.key===s))==null?void 0:n.canonical)??"new_connection"}const tBe={first_name:"",last_name:"",brokerage:"",email:"",phone:"",city:"",source:"",notes:""};function krs({open:s,onOpenChange:t,defaultStageKey:n,onAdded:r}){const{upsertAgent:a,agents:i}=EE(),[l,o]=j.useState({...tBe}),c=h=>m=>o(p=>({...p,[h]:m.target.value})),d=i.find(h=>{var m;return!!l.email&&((m=h.email)==null?void 0:m.toLowerCase())===l.email.trim().toLowerCase()||!!l.phone&&(h.phone??"").replace(/\D/g,"")===l.phone.replace(/\D/g,"")&&l.phone.replace(/\D/g,"").length>6}),u=()=>{a.mutate({...l,first_name:l.first_name.trim(),stage:hat(n??"new_relationship"),temperature:"warm"},{onSuccess:h=>{o({...tBe}),t(!1),r==null||r(h==null?void 0:h.id)}})};return e.jsx(zs,{open:s,onOpenChange:h=>{t(h),h||o({...tBe})},children:e.jsxs(Ds,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Add a relationship"}),e.jsx(Pr,{className:"text-[13px]",children:"Just the basics. You can fill in the rest whenever it comes up naturally."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"First name *"}),e.jsx(xe,{value:l.first_name,onChange:c("first_name"),autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Last name"}),e.jsx(xe,{value:l.last_name,onChange:c("last_name")})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(te,{children:"Brokerage"}),e.jsx(xe,{value:l.brokerage,onChange:c("brokerage"),placeholder:"Where they hang their license"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Email"}),e.jsx(xe,{type:"email",value:l.email,onChange:c("email")})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Phone"}),e.jsx(xe,{value:l.phone,onChange:c("phone")})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Market"}),e.jsx(xe,{value:l.city,onChange:c("city"),placeholder:"City or area"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"How you know each other"}),e.jsx(xe,{value:l.source,onChange:c("source"),placeholder:"Co-op deal, event, referral…"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(te,{children:"Note (optional)"}),e.jsx(Fs,{rows:2,value:l.notes,onChange:c("notes"),placeholder:"Anything worth remembering"})]})]}),d&&e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-200 px-3 py-2 text-[12.5px] text-amber-900",children:["Heads up — ",d.first_name," ",d.last_name??""," already has this contact info in your relationships."]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsx(U,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 text-white",disabled:!l.first_name.trim()||a.isPending,onClick:u,children:"Add relationship"})]})]})})}function Wcr(){const{user:s}=vs();return ct({queryKey:["attract-score",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_score_events").select("category, points, description, created_at");if(n)throw n;const r=t??[],a=r.reduce((l,o)=>l+(o.points??0),0),i={};for(const l of r)i[l.category]=(i[l.category]??0)+l.points;return{total:Math.min(a,100),rows:r,byCategory:i}}})}const Kcr=[{key:"relationships_added",label:"Relationships Added",icon:zk,target:15},{key:"follow_ups_completed",label:"Follow-Ups Completed",icon:zr,target:15},{key:"resources_shared",label:"Resources Shared",icon:jd,target:15},{key:"content_posted",label:"Agent Content Posted",icon:Th,target:15},{key:"events_connections",label:"Events / Connections",icon:Xk,target:20},{key:"brokerage_conversations",label:"Brokerage Conversations",icon:QX,target:20}];function Ycr(){const{data:s}=Wcr(),t=(s==null?void 0:s.total)??0,n=(s==null?void 0:s.byCategory)??{},r=2*Math.PI*54,a=t/100*r;return e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Your Attract Score"}),e.jsx("div",{className:"text-[19px] font-semibold text-slate-900 mt-1",children:"Great progress! Keep building relationships and providing value."})]}),e.jsx(rc,{className:"h-5 w-5 text-violet-500"})]}),e.jsxs("div",{className:"flex items-center gap-6 flex-col sm:flex-row",children:[e.jsxs("div",{className:"relative h-36 w-36 flex-shrink-0",children:[e.jsxs("svg",{viewBox:"0 0 120 120",className:"h-full w-full -rotate-90",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"attract-score",x1:"0",x2:"1",y1:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(139 92 246)"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(79 70 229)"})]})}),e.jsx("circle",{cx:"60",cy:"60",r:"54",stroke:"rgb(226 232 240)",strokeWidth:"10",fill:"none"}),e.jsx("circle",{cx:"60",cy:"60",r:"54",stroke:"url(#attract-score)",strokeWidth:"10",fill:"none",strokeLinecap:"round",strokeDasharray:`${a} ${r}`,style:{transition:"stroke-dasharray 800ms ease"}})]}),e.jsxs("div",{className:"absolute inset-0 grid place-items-center flex-col text-center",children:[e.jsxs("div",{className:"flex items-baseline gap-1",children:[e.jsx("span",{className:"text-4xl font-semibold tracking-tight text-slate-900",children:t}),e.jsx("span",{className:"text-sm text-slate-500 font-medium",children:"/100"})]}),e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-slate-400",children:"this cycle"})]})]}),e.jsx("div",{className:"flex-1 space-y-2 w-full",children:Kcr.map(i=>{const l=n[i.key]??0,o=Math.min(100,Math.round(l/i.target*100)),c=i.icon;return e.jsxs("div",{className:"grid grid-cols-[16px_1fr_60px_auto] items-center gap-2.5",children:[e.jsx(c,{className:"h-4 w-4 text-slate-500"}),e.jsx("span",{className:"text-[12.5px] text-slate-700 truncate",children:i.label}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-100 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-violet-500 to-indigo-500",style:{width:`${o}%`}})}),e.jsx("span",{className:"text-[11px] tabular-nums text-slate-500 font-medium w-8 text-right",children:l})]},i.key)})})]}),e.jsx("div",{className:"mt-5 flex justify-end",children:e.jsx(U,{variant:"outline",size:"sm",className:"rounded-full",children:"View Score Breakdown"})})]})}function Srs(s){const{user:t}=vs();return ct({queryKey:["attract-events",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let n=q.from("attract_events").select("*").eq("is_template",!1).order("starts_at",{ascending:!0});const{data:r,error:a}=await n;if(a)throw a;return r??[]}})}function mat(s){return ct({queryKey:["attract-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_events").select("*").eq("id",s).single();if(n)throw n;return t}})}function Crs(s){return ct({queryKey:["attract-event-attendees",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_event_attendees").select("*, attract_agents(id, first_name, last_name, primary_pillar, stage)").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function Zcr(s){return ct({queryKey:["attract-event-invitations",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_event_invitations").select("*, attract_agents(id, first_name, last_name)").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function Xcr(s){return ct({queryKey:["attract-event-notes",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_event_notes").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function Ars(){return ct({queryKey:["attract-event-templates"],queryFn:async()=>{const{data:s,error:t}=await q.from("attract_event_templates").select("*").order("title");if(t)throw t;return s??[]}})}function Qcr(){const{user:s}=vs(),t=Qt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r={user_id:s.id,title:n.title||"Untitled event",starts_at:n.starts_at||new Date(Date.now()+7*864e5).toISOString(),status:"draft",...n},{data:a,error:i}=await q.from("attract_events").insert(r).select().single();if(i)throw i;return a},onSuccess:()=>t.invalidateQueries({queryKey:["attract-events"]})})}function Ers(){const s=Qt();return yt({mutationFn:async({id:t,patch:n})=>{const{data:r,error:a}=await q.from("attract_events").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["attract-events"]}),s.invalidateQueries({queryKey:["attract-event",t.id]})}})}function Jcr(){const s=Qt();return yt({mutationFn:async t=>{const{error:n}=await q.from("attract_events").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["attract-events"]})})}function Trs(){const{user:s}=vs(),t=Qt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r={user_id:s.id,...n},{data:a,error:i}=n.id?await q.from("attract_event_attendees").update(r).eq("id",n.id).select().single():await q.from("attract_event_attendees").insert(r).select().single();if(i)throw i;return a},onSuccess:n=>{t.invalidateQueries({queryKey:["attract-event-attendees",n.event_id]}),t.invalidateQueries({queryKey:["attract-event",n.event_id]})}})}function edr(){const{user:s}=vs(),t=Qt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("attract_event_notes").insert({user_id:s.id,...n}).select().single();if(a)throw a;return r},onSuccess:n=>t.invalidateQueries({queryKey:["attract-event-notes",n.event_id]})})}function tdr(){const{user:s}=vs(),t=Qt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("attract_event_invitations").insert({user_id:s.id,...n}).select().single();if(a)throw a;return r},onSuccess:n=>t.invalidateQueries({queryKey:["attract-event-invitations",n.event_id]})})}function sdr(){const{user:s}=vs(),t=Qt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("attract_events").select("*").eq("id",n).single();if(a)throw a;const{id:i,public_slug:l,check_in_token:o,published_at:c,registration_count:d,attendance_count:u,created_at:h,updated_at:m,...p}=r,{data:f,error:x}=await q.from("attract_events").insert({...p,title:r.title+" (Copy)",status:"draft"}).select().single();if(x)throw x;return f},onSuccess:()=>t.invalidateQueries({queryKey:["attract-events"]})})}function n8e(s){return`${window.location.origin}/attract-event/${s}`}function ndr(s,t){return`${window.location.origin}/attract-event-checkin/${s}?a=${encodeURIComponent(t)}`}function Mrs(s){const t=l=>l.toISOString().replace(/[-:]/g,"").replace(/\.\d{3}/,""),n=new Date(s.starts_at),r=s.ends_at?new Date(s.ends_at):new Date(n.getTime()+60*60*1e3),a=[s.location,s.address,s.virtual_url].filter(Boolean).join(" — ");return["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//LevelUp Attract//EN","BEGIN:VEVENT",`UID:${`${Date.now()}@attract.levelup`}`,`DTSTAMP:${t(new Date)}`,`DTSTART:${t(n)}`,`DTEND:${t(r)}`,`SUMMARY:${(s.title||"").replace(/\n/g," ")}`,`DESCRIPTION:${(s.description||"").replace(/\n/g,"\\n")}`,`LOCATION:${a.replace(/\n/g," ")}`,"END:VEVENT","END:VCALENDAR"].join(`\r `)}function rdr(){const{data:s=[]}=Srs(),t=s.slice(0,3);return e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Upcoming Events"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Places where relationships happen"})]}),e.jsxs(U,{variant:"outline",size:"sm",className:"rounded-full gap-1",children:[e.jsx(an,{className:"h-3.5 w-3.5"})," Create"]})]}),e.jsxs("div",{className:"space-y-3",children:[t.map(n=>{var i,l;const r=new Date(n.starts_at),a=((l=(i=n.attract_event_attendees)==null?void 0:i[0])==null?void 0:l.count)??0;return e.jsxs("div",{className:"flex items-center gap-4 p-3 rounded-xl hover:bg-slate-50 transition-colors",children:[e.jsxs("div",{className:"w-14 flex-shrink-0 text-center rounded-xl bg-gradient-to-br from-violet-500 to-indigo-600 text-white py-2",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wider opacity-90",children:Gs(r,"MMM")}),e.jsx("div",{className:"text-xl font-semibold leading-tight",children:Gs(r,"d")})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[14px] font-semibold text-slate-900 truncate",children:n.title}),e.jsxs("div",{className:"text-[12px] text-slate-500 flex items-center gap-2 mt-0.5",children:[e.jsx("span",{children:Gs(r,"p")}),"·",n.event_type==="virtual"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Wr,{className:"h-3 w-3"})," Virtual"]}):e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(ni,{className:"h-3 w-3"})," ",n.location]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:a}),e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"RSVPs"})]})]},n.id)}),t.length===0&&e.jsxs("div",{className:"text-center py-8 text-slate-500",children:[e.jsx(Xk,{className:"h-6 w-6 mx-auto text-slate-300 mb-2"}),e.jsx("div",{className:"text-sm",children:"No upcoming events yet."})]})]})]})}function adr(s){var r;const t=(s==null?void 0:s.user_metadata)??{},n=t.full_name||t.name||((r=s==null?void 0:s.email)==null?void 0:r.split("@")[0])||"there";return String(n).split(" ")[0]}function idr(){const s=new Date().getHours();return s<12?"Good morning":s<18?"Good afternoon":"Good evening"}const Y4t=20;function odr(){const{user:s}=vs(),{intel:t,byId:n,isLoading:r}=CW(),{data:a=[],isLoading:i}=JIe(),l=e8e();uat();const{items:o,toggle:c}=Vcr(),{agents:d,isLoading:u}=EE(),{followUps:h}=t8e(),{activities:m}=_rs(200),[p,f]=j.useState(!1),x=r||i||u,y=j.useMemo(()=>{const S=Date.now();return a.filter(A=>A.status==="open"||A.status==="snoozed"&&A.snoozed_until&&+new Date(A.snoozed_until)<=S).sort((A,T)=>T.rank_score-A.rank_score).slice(0,5)},[a]),v=j.useMemo(()=>{const S=new Date;S.setHours(0,0,0,0),S.setDate(S.getDate()-(S.getDay()+6)%7);const A=m.filter(M=>new Date(M.created_at)>=S).length,T=h.filter(M=>M.completed_at&&new Date(M.completed_at)>=S).length,L=A+T;return{moves:L,pct:Math.min(100,Math.round(L/Y4t*100))}},[m,h]),b=S=>{var T;const A=(T=n.get(S))==null?void 0:T.agent;return A?[A.first_name,A.last_name].filter(Boolean).join(" "):"this relationship"},N=d.length>0;return e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(krs,{open:p,onOpenChange:f}),e.jsxs("div",{className:"relative overflow-hidden rounded-3xl bg-[#0B0F1E] text-white px-6 py-7 md:px-8 md:py-9 mb-7",children:[e.jsx("div",{className:"pointer-events-none absolute -top-24 -right-12 h-64 w-64 rounded-full bg-violet-600/30 blur-3xl"}),e.jsx("div",{className:"pointer-events-none absolute -bottom-28 left-6 h-56 w-56 rounded-full bg-indigo-500/20 blur-3xl"}),e.jsx("div",{className:"pointer-events-none absolute inset-0 opacity-[0.06]",style:{backgroundImage:"radial-gradient(circle at 20% 20%, white 1px, transparent 1px), radial-gradient(circle at 80% 60%, white 1px, transparent 1px)",backgroundSize:"46px 46px"}}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full bg-white/10 ring-1 ring-inset ring-white/15 px-3 py-1 text-[10.5px] uppercase tracking-[0.18em] font-semibold text-violet-200 mb-3",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-violet-400"})," Today"]}),e.jsxs("h1",{className:"text-[26px] md:text-[34px] font-semibold tracking-tight leading-[1.12]",children:[idr(),", ",adr(s),". Here are your best moves today."]}),e.jsx("p",{className:"text-slate-300/90 mt-2 text-[14px]",children:"One agent, one step closer. That is the whole job today."}),e.jsxs("div",{className:"mt-6 rounded-2xl bg-white/[0.06] ring-1 ring-inset ring-white/10 px-4 py-3.5 backdrop-blur-sm",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-3",children:[e.jsxs("div",{className:"text-[13.5px] text-slate-300",children:[e.jsxs("span",{className:"font-semibold text-white tabular-nums",children:[v.moves," of ",Y4t]})," meaningful moves completed this week"]}),e.jsx("span",{className:"text-[11px] uppercase tracking-wider text-slate-500",children:"This week"})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-white/10 mt-2.5 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-violet-400 to-indigo-400 transition-all",style:{width:`${v.pct}%`}})})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h2",{className:"text-[13px] font-semibold uppercase tracking-wider text-slate-600",children:"Today’s actions"}),!x&&e.jsxs(U,{variant:"ghost",size:"sm",className:"rounded-full text-slate-500 h-8",onClick:()=>l.mutate(t),disabled:l.isPending,children:[e.jsx(no,{className:Mt("h-3.5 w-3.5 mr-1.5",l.isPending&&"animate-spin")})," Refresh"]})]}),x?e.jsxs("div",{className:"space-y-3","aria-busy":"true",children:[e.jsx("div",{className:"text-[13px] text-slate-500",children:"Looking at your relationships…"}),[0,1,2].map(S=>e.jsx(xn,{className:"h-40 w-full rounded-2xl"},S))]}):y.length?e.jsx("div",{className:"space-y-3",children:y.map(S=>{var A;return e.jsx(ITe,{rec:S,agentName:b(S.agent_id),agentStage:Nrs((A=n.get(S.agent_id))==null?void 0:A.agent.stage)},S.id)})}):N?e.jsxs(we,{className:"rounded-2xl border-dashed border-slate-300 bg-white/60 p-8 text-center",children:[e.jsx(cn,{className:"h-6 w-6 mx-auto text-violet-500 mb-2"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"You’re caught up."}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1 max-w-md mx-auto",children:"No follow-ups are due. This is a great time to reconnect with someone you haven’t spoken with recently, or share one useful resource."}),e.jsxs("div",{className:"flex gap-2 justify-center mt-4 flex-wrap",children:[e.jsx(U,{className:"rounded-full btn-primary text-white",asChild:!0,children:e.jsx(xr,{to:"/attract/agents?view=attention",children:"See who’s gone quiet"})}),e.jsx(U,{variant:"outline",className:"rounded-full",asChild:!0,children:e.jsx(xr,{to:"/attract/toolkit/kits",children:"Share something useful"})})]})]}):e.jsxs(we,{className:"rounded-2xl border-dashed border-slate-300 bg-white/60 p-8 text-center",children:[e.jsx("div",{className:"h-11 w-11 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(zl,{className:"h-5 w-5"})}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Start with five people you already know."}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1 max-w-md mx-auto",children:"Add your first five relationships and Attract will begin recommending meaningful next steps — based only on things that actually happened."}),e.jsxs(U,{className:"rounded-full btn-primary text-white mt-4",onClick:()=>f(!0),children:[e.jsx(zl,{className:"h-4 w-4 mr-1.5"})," Add your first relationship"]})]}),!!o.length&&e.jsxs(we,{className:"mt-6 p-5 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsx("div",{className:"text-[13px] font-semibold uppercase tracking-wider text-slate-600 mb-3",children:"Your daily rhythm"}),e.jsx("ul",{className:"space-y-1",children:o.map(S=>e.jsxs("li",{onClick:()=>c.mutate(S),className:"flex items-center gap-3 px-2 py-2 rounded-xl hover:bg-slate-50 cursor-pointer transition-colors",children:[e.jsx(xi,{checked:S.completed,className:"border-slate-300 data-[state=checked]:bg-violet-600 data-[state=checked]:border-violet-600"}),e.jsx("span",{className:Mt("flex-1 text-[13.5px]",S.completed?"line-through text-slate-400":"text-slate-800"),children:S.label}),e.jsxs("span",{className:"text-[11px] tabular-nums text-slate-400",children:[S.progress,"/",S.target]})]},S.id))})]}),e.jsxs("div",{className:"mt-6 grid grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsx(nde,{icon:zl,label:"Add an agent",onClick:()=>f(!0)}),e.jsx(nde,{icon:Qw,label:"Run their numbers",to:"/attract/calculator"}),e.jsx(nde,{icon:tj,label:"Share a value kit",to:"/attract/toolkit/kits"}),e.jsx(nde,{icon:OF,label:"Handle an objection",to:"/attract/toolkit/objections"})]}),e.jsxs("div",{className:"mt-6 space-y-3",children:[e.jsxs(ub,{children:[e.jsxs(hb,{className:"w-full flex items-center justify-between rounded-2xl bg-white border border-slate-200/70 px-4 py-3 text-[13.5px] font-medium text-slate-700 hover:bg-slate-50",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Xk,{className:"h-4 w-4 text-violet-500"})," Upcoming conversations & events"]}),e.jsx(rl,{className:"h-4 w-4 text-slate-400"})]}),e.jsx(mb,{className:"pt-3",children:e.jsx(rdr,{})})]}),e.jsxs(ub,{children:[e.jsxs(hb,{className:"w-full flex items-center justify-between rounded-2xl bg-white border border-slate-200/70 px-4 py-3 text-[13.5px] font-medium text-slate-700 hover:bg-slate-50",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(cn,{className:"h-4 w-4 text-violet-500"})," View coaching insights"]}),e.jsx(rl,{className:"h-4 w-4 text-slate-400"})]}),e.jsx(mb,{className:"pt-3",children:e.jsx(Ycr,{})})]})]}),e.jsx("div",{className:"mt-6 flex justify-center",children:e.jsx(U,{variant:"ghost",className:"rounded-full text-violet-700",asChild:!0,children:e.jsxs(xr,{to:"/attract/agents?view=attention",children:["See everyone who needs attention ",e.jsx(Oa,{className:"h-3.5 w-3.5 ml-1.5"})]})})}),e.jsx("p",{className:"mt-6 text-center text-[11.5px] text-slate-400 max-w-lg mx-auto",children:"Attract never sends messages for you, and it only recommends actions backed by something that actually happened. Verify brokerage and compensation details before you share them."})]})}function nde({icon:s,label:t,to:n,onClick:r}){const a=e.jsxs("div",{className:"rounded-2xl bg-white border border-slate-200/70 px-4 py-4 text-left hover:border-violet-300 hover:shadow-sm transition-all h-full",children:[e.jsx(s,{className:"h-4.5 w-4.5 text-violet-600 mb-2"}),e.jsx("div",{className:"text-[13.5px] font-medium text-slate-800",children:t})]});return n?e.jsx(xr,{to:n,children:a}):e.jsx("button",{className:"text-left w-full",onClick:r,children:a})}function TE({eyebrow:s,title:t,description:n,actions:r,stats:a,className:i}){return e.jsxs("div",{className:Mt("relative overflow-hidden rounded-3xl bg-[#0B0F1E] text-white mb-7 px-6 py-7 md:px-8 md:py-8",i),children:[e.jsx("div",{className:"pointer-events-none absolute -top-24 -right-16 h-64 w-64 rounded-full bg-violet-600/30 blur-3xl"}),e.jsx("div",{className:"pointer-events-none absolute -bottom-28 left-10 h-56 w-56 rounded-full bg-indigo-500/20 blur-3xl"}),e.jsx("div",{className:"pointer-events-none absolute inset-0 opacity-[0.06]",style:{backgroundImage:"radial-gradient(circle at 20% 20%, white 1px, transparent 1px), radial-gradient(circle at 80% 60%, white 1px, transparent 1px)",backgroundSize:"46px 46px"}}),e.jsxs("div",{className:"relative flex flex-col md:flex-row md:items-end md:justify-between gap-5",children:[e.jsxs("div",{className:"min-w-0",children:[s&&e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full bg-white/10 ring-1 ring-inset ring-white/15 px-3 py-1 text-[10.5px] uppercase tracking-[0.18em] font-semibold text-violet-200 mb-3",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-violet-400"}),s]}),e.jsx("h1",{className:"text-[26px] md:text-[34px] font-semibold tracking-tight leading-[1.12]",children:t}),n&&e.jsx("p",{className:"text-slate-300/90 mt-2 max-w-2xl text-[14px] leading-relaxed",children:n})]}),r&&e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:r})]}),a&&a.length>0&&e.jsx("div",{className:"relative mt-6 grid grid-cols-2 lg:grid-cols-4 gap-2.5",children:a.map(l=>e.jsxs("div",{className:"rounded-2xl bg-white/[0.06] ring-1 ring-inset ring-white/10 px-4 py-3 backdrop-blur-sm",children:[e.jsx("div",{className:Mt("text-[22px] font-semibold tabular-nums leading-none",l.tone??"text-white"),children:l.value}),e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-400 mt-1.5",children:l.label})]},l.label))})]})}function Prs(){return e.jsxs("div",{className:"rounded-2xl border border-violet-200 bg-violet-50/60 px-5 py-3.5 text-[13px] text-violet-900 flex items-start gap-3",children:[e.jsx("div",{className:"h-6 w-6 rounded-full bg-violet-600 grid place-items-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-white text-[11px] font-bold",children:"✓"})}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:"Build relationships first."})," ","Personalize every message and verify brokerage and compensation information before sharing."]})]})}function ldr(s){const t=[];let n="",r=[],a=!1;for(let o=0;oo.some(c=>c.trim()!==""));if(!i.length)return[];const l=i[0].map(o=>o.trim().toLowerCase());return i.slice(1).map(o=>{const c={};return l.forEach((d,u)=>{c[d]=(o[u]??"").trim()}),c})}const uC=(s,t)=>{for(const n of t)if(s[n])return s[n];return""};function cdr({open:s,onOpenChange:t}){const{user:n}=vs(),r=Qt(),[a,i]=j.useState([]),[l,o]=j.useState(""),[c,d]=j.useState(!1),u=()=>{i([]),o("")},h=async f=>{if(!f)return;const x=await f.text(),y=ldr(x);if(!y.length){re.error("That file looks empty.");return}o(f.name),i(y)},m=a.map(f=>{const x=uC(f,["name","full name","full_name"]),y=uC(f,["first name","first_name","firstname"])||x.split(" ")[0]||"",v=uC(f,["last name","last_name","lastname"])||x.split(" ").slice(1).join(" ")||null;return{first_name:y,last_name:v,email:uC(f,["email","email address","e-mail"])||null,phone:uC(f,["phone","phone number","mobile","cell"])||null,brokerage:uC(f,["brokerage","company","office"])||null,city:uC(f,["city"])||null,state:uC(f,["state","province"])||null,notes:uC(f,["notes","note"])||null,source:"csv_import",stage:"prospect"}}).filter(f=>f.first_name),p=async()=>{if(!(!n||!m.length)){d(!0);try{const f=m.map(y=>({...y,user_id:n.id}));let x=0;for(let y=0;y{f||u(),t(f)},children:e.jsxs(Ds,{className:"sm:max-w-lg",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Import relationships"}),e.jsx(Pr,{children:"Upload a CSV. We'll look for columns like name, email, phone, brokerage, city, state and notes."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(xe,{type:"file",accept:".csv,text/csv",onChange:f=>{var x;return h((x=f.target.files)==null?void 0:x[0])}}),!!a.length&&e.jsxs("div",{className:"rounded-xl border p-3 text-sm space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(Qk,{className:"h-4 w-4"})," ",l]}),e.jsxs("div",{className:"text-muted-foreground",children:[m.length," of ",a.length," rows ready to import."]}),e.jsxs("div",{className:"text-muted-foreground text-xs",children:["Preview: ",m.slice(0,3).map(f=>`${f.first_name} ${f.last_name??""}`.trim()).join(", "),m.length>3?"…":""]})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{onClick:p,disabled:c||!m.length,children:[e.jsx(qa,{className:"h-4 w-4 mr-1.5"}),c?"Importing…":`Import ${m.length||""}`.trim()]})]})]})})}const ddr=["new_connection","building_relationship","engaging_with_value","active_conversation","exploring_options","brokerage_presentation","decision_pending","joined","long_term_relationship","not_right_now","not_a_fit"],udr={first_name:"first name",last_name:"last name",preferred_name:"preferred name",email:"email",phone:"phone",website_url:"website",instagram_url:"Instagram",linkedin_url:"LinkedIn",facebook_url:"Facebook",other_url:"other link",brokerage:"brokerage",team_name:"team",city:"city",state:"state",postal_code:"ZIP",market_area:"market area",source:"source",relationship_owner:"relationship owner",stage:"stage",temperature:"temperature",primary_pillar:"primary pillar",tags:"tags",goals:"goals",challenges:"challenges",interests:"interests",production_context:"production context",notes:"notes",birthday_on:"birthday",work_anniversary_on:"work anniversary",license_anniversary_on:"license anniversary",next_follow_up_at:"next follow-up",photo_url:"photo"},z0=s=>typeof s=="string"&&s.trim()===""?null:s,TB=s=>{const t=s.trim();return t?/^https?:\/\//i.test(t)?t:`https://${t}`:null},hdr=s=>{const t=s.trim();if(!t)return null;const n=t.replace(/[^\d]/g,"");return n.length===10?`(${n.slice(0,3)}) ${n.slice(3,6)}-${n.slice(6)}`:t},QY=s=>(s??"").replace(/[^\d]/g,""),mdr=s=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.trim()),rde=s=>s?String(s).slice(0,10):"";function Z4t(s){return{first_name:s.first_name??"",last_name:s.last_name??"",preferred_name:s.preferred_name??"",email:s.email??"",phone:s.phone??"",website_url:s.website_url??"",instagram_url:s.instagram_url??"",linkedin_url:s.linkedin_url??"",facebook_url:s.facebook_url??"",other_url:s.other_url??"",photo_url:s.photo_url??"",brokerage:s.brokerage??"",team_name:s.team_name??"",city:s.city??"",state:s.state??"",postal_code:s.postal_code??"",market_area:s.market_area??"",source:s.source??"",relationship_owner:s.relationship_owner??"",stage:s.stage,temperature:s.temperature??"warm",primary_pillar:s.primary_pillar??"none",tags:(s.tags??[]).join(", "),goals:s.goals??"",challenges:s.challenges??"",interests:s.interests??"",production_context:s.production_context??"",notes:s.notes??"",birthday_on:rde(s.birthday_on),work_anniversary_on:rde(s.work_anniversary_on),license_anniversary_on:rde(s.license_anniversary_on),next_follow_up_at:rde(s.next_follow_up_at)}}function MB({title:s,hint:t,children:n}){return e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-600",children:s}),t&&e.jsx("p",{className:"text-[12px] text-slate-500 mt-0.5",children:t})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:n})]})}function Ep({label:s,value:t,onChange:n,className:r,...a}){return e.jsxs("div",{className:r,children:[e.jsx(te,{className:"text-[12px] text-slate-600",children:s}),e.jsx(xe,{className:"mt-1",value:t,onChange:i=>n(i.target.value),...a})]})}function Lrs({agent:s,open:t,onOpenChange:n,onDeleted:r}){const{agents:a,saveAgentDetails:i,archiveAgent:l,deleteAgent:o}=EE(),[c,d]=j.useState({}),[u,h]=j.useState(!1),[m,p]=j.useState(!1),[f,x]=j.useState(!1);j.useEffect(()=>{s&&t&&(d(Z4t(s)),x(!1))},[s==null?void 0:s.id,t]);const y=j.useMemo(()=>s?Z4t(s):{},[s]),v=j.useMemo(()=>Object.keys(c).filter(M=>String(c[M]??"")!==String(y[M]??"")),[c,y]),b=v.length>0,N=(M,I)=>d(R=>({...R,[M]:I}));if(!s)return null;const S=M=>{if(!M&&b){h(!0);return}n(M)},A=()=>{var z;const M=(z=c.email)==null?void 0:z.trim().toLowerCase(),I=QY(c.phone),R=`${c.first_name} ${c.last_name}`.trim().toLowerCase();return a.filter($=>{var H;return $.id===s.id||$.is_archived?!1:!!(M&&((H=$.email)==null?void 0:H.toLowerCase())===M||I.length>=10&&QY($.phone)===I||R&&`${$.first_name} ${$.last_name??""}`.trim().toLowerCase()===R)})},T=()=>{var $,H,V;if(!(($=c.first_name)!=null&&$.trim())){re.error("First name is required");return}if((H=c.email)!=null&&H.trim()&&!mdr(c.email)){re.error("That email address looks incomplete");return}const M=A(),I=M.some(K=>{var Z,Q;return((Z=c.email)==null?void 0:Z.trim())&&((Q=K.email)==null?void 0:Q.toLowerCase())===c.email.trim().toLowerCase()||QY(c.phone).length>=10&&QY(K.phone)===QY(c.phone)});if(M.length&&!f){x(!0),re.warning(I?`${M[0].first_name} ${M[0].last_name??""} already uses this email or phone. Save again to confirm.`:"A contact named the same already exists. Save again to confirm.");return}const R={first_name:c.first_name.trim(),last_name:z0(c.last_name),preferred_name:z0(c.preferred_name),email:(V=c.email)!=null&&V.trim()?c.email.trim().toLowerCase():null,phone:hdr(c.phone??""),website_url:TB(c.website_url??""),instagram_url:TB(c.instagram_url??""),linkedin_url:TB(c.linkedin_url??""),facebook_url:TB(c.facebook_url??""),other_url:TB(c.other_url??""),photo_url:TB(c.photo_url??""),brokerage:z0(c.brokerage),team_name:z0(c.team_name),city:z0(c.city),state:z0(c.state),postal_code:z0(c.postal_code),market_area:z0(c.market_area),source:z0(c.source),relationship_owner:z0(c.relationship_owner),temperature:c.temperature,primary_pillar:c.primary_pillar==="none"?null:c.primary_pillar,tags:String(c.tags??"").split(",").map(K=>K.trim()).filter(Boolean),goals:z0(c.goals),challenges:z0(c.challenges),interests:z0(c.interests),production_context:z0(c.production_context),notes:z0(c.notes),birthday_on:z0(c.birthday_on),work_anniversary_on:z0(c.work_anniversary_on),license_anniversary_on:z0(c.license_anniversary_on),next_follow_up_at:c.next_follow_up_at?new Date(`${c.next_follow_up_at}T12:00:00`).toISOString():null,stage:c.stage},z={};if(v.forEach(K=>{K in R&&(z[K]=R[K])}),!Object.keys(z).length){n(!1);return}i.mutate({id:s.id,values:z,changedLabels:v.map(K=>udr[K]??K),previousStage:s.stage},{onSuccess:()=>n(!1)})},L=A();return e.jsxs(e.Fragment,{children:[e.jsx(my,{open:t,onOpenChange:S,children:e.jsxs(g0,{side:"right",className:"w-full sm:max-w-xl overflow-y-auto p-0",children:[e.jsx("div",{className:"sticky top-0 z-10 bg-gradient-to-r from-[#0B0F1E] to-[#1d1b4b] text-white px-5 py-4",children:e.jsxs(vv,{className:"space-y-1 text-left",children:[e.jsxs(bv,{className:"text-white text-lg",children:["Edit ",[s.first_name,s.last_name].filter(Boolean).join(" ")]}),e.jsx(pG,{className:"text-slate-300 text-[12.5px]",children:"Only the fields you change are saved. Stage changes are recorded in pipeline history."})]})}),e.jsxs("div",{className:"px-5 py-5 space-y-7 pb-40",children:[!!L.length&&e.jsxs("div",{className:"rounded-xl bg-amber-50 ring-1 ring-amber-200 p-3 text-[12.5px] text-amber-800 flex gap-2",children:[e.jsx(tc,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsxs("span",{children:["Possible duplicate: ",L.slice(0,3).map(M=>`${M.first_name} ${M.last_name??""}`.trim()).join(", "),". You can still save — just double-check first."]})]}),e.jsxs(MB,{title:"Basic info",children:[e.jsx(Ep,{label:"First name *",value:c.first_name,onChange:M=>N("first_name",M)}),e.jsx(Ep,{label:"Last name",value:c.last_name,onChange:M=>N("last_name",M)}),e.jsx(Ep,{label:"Preferred name",value:c.preferred_name,onChange:M=>N("preferred_name",M),placeholder:"What they go by"}),e.jsx(Ep,{label:"Photo / headshot URL",value:c.photo_url,onChange:M=>N("photo_url",M),placeholder:"https://…"})]}),e.jsxs(MB,{title:"Contact & social",children:[e.jsx(Ep,{label:"Email",type:"email",value:c.email,onChange:M=>N("email",M)}),e.jsx(Ep,{label:"Phone",value:c.phone,onChange:M=>N("phone",M)}),e.jsx(Ep,{label:"Website",value:c.website_url,onChange:M=>N("website_url",M)}),e.jsx(Ep,{label:"Instagram",value:c.instagram_url,onChange:M=>N("instagram_url",M)}),e.jsx(Ep,{label:"LinkedIn",value:c.linkedin_url,onChange:M=>N("linkedin_url",M)}),e.jsx(Ep,{label:"Facebook",value:c.facebook_url,onChange:M=>N("facebook_url",M)}),e.jsx(Ep,{label:"Other link",value:c.other_url,onChange:M=>N("other_url",M),className:"sm:col-span-2"})]}),e.jsxs(MB,{title:"Brokerage & market",children:[e.jsx(Ep,{label:"Brokerage",value:c.brokerage,onChange:M=>N("brokerage",M)}),e.jsx(Ep,{label:"Team",value:c.team_name,onChange:M=>N("team_name",M)}),e.jsx(Ep,{label:"City",value:c.city,onChange:M=>N("city",M)}),e.jsx(Ep,{label:"State",value:c.state,onChange:M=>N("state",M)}),e.jsx(Ep,{label:"ZIP / postal code",value:c.postal_code,onChange:M=>N("postal_code",M)}),e.jsx(Ep,{label:"Market / service area",value:c.market_area,onChange:M=>N("market_area",M)})]}),e.jsxs(MB,{title:"Relationship intelligence",hint:"These drive scoring, recommendations, filters and reports.",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-[12px] text-slate-600",children:"Pipeline stage"}),e.jsxs(Ns,{value:c.stage,onValueChange:M=>N("stage",M),children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{})}),e.jsx(js,{children:ddr.map(M=>e.jsx(et,{value:M,className:"capitalize",children:M.replace(/_/g," ")},M))})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-[12px] text-slate-600",children:"Temperature"}),e.jsxs(Ns,{value:c.temperature,onValueChange:M=>N("temperature",M),children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{})}),e.jsx(js,{children:["cold","warm","hot"].map(M=>e.jsx(et,{value:M,className:"capitalize",children:M},M))})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-[12px] text-slate-600",children:"Primary pillar"}),e.jsxs(Ns,{value:c.primary_pillar,onValueChange:M=>N("primary_pillar",M),children:[e.jsx(ws,{className:"mt-1",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"Not set"}),["produce","influence","provide","connect"].map(M=>e.jsx(et,{value:M,className:"capitalize",children:M},M))]})]})]}),e.jsx(Ep,{label:"Source",value:c.source,onChange:M=>N("source",M),placeholder:"Event, referral, social…"}),e.jsx(Ep,{label:"Relationship owner",value:c.relationship_owner,onChange:M=>N("relationship_owner",M),placeholder:"You, or a teammate"}),e.jsx(Ep,{label:"Tags (comma separated)",value:c.tags,onChange:M=>N("tags",M),className:"sm:col-span-2"}),!!String(c.tags??"").trim()&&e.jsx("div",{className:"sm:col-span-2 flex flex-wrap gap-1.5 -mt-1",children:String(c.tags).split(",").map(M=>M.trim()).filter(Boolean).map(M=>e.jsx(Be,{variant:"outline",className:"rounded-full text-[11px]",children:M},M))})]}),e.jsxs(MB,{title:"Important dates",hint:"Birthdays and anniversaries feed Milestones & Celebrations automatically — no duplicate entry needed.",children:[e.jsx(Ep,{label:"Birthday",type:"date",value:c.birthday_on,onChange:M=>N("birthday_on",M)}),e.jsx(Ep,{label:"Work anniversary",type:"date",value:c.work_anniversary_on,onChange:M=>N("work_anniversary_on",M)}),e.jsx(Ep,{label:"License anniversary",type:"date",value:c.license_anniversary_on,onChange:M=>N("license_anniversary_on",M)}),e.jsx(Ep,{label:"Next follow-up",type:"date",value:c.next_follow_up_at,onChange:M=>N("next_follow_up_at",M)})]}),e.jsxs(MB,{title:"Notes",children:[e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(te,{className:"text-[12px] text-slate-600",children:"Goals"}),e.jsx(Fs,{className:"mt-1",rows:2,value:c.goals,onChange:M=>N("goals",M.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(te,{className:"text-[12px] text-slate-600",children:"Challenges"}),e.jsx(Fs,{className:"mt-1",rows:2,value:c.challenges,onChange:M=>N("challenges",M.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(te,{className:"text-[12px] text-slate-600",children:"Interests"}),e.jsx(Fs,{className:"mt-1",rows:2,value:c.interests,onChange:M=>N("interests",M.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(te,{className:"text-[12px] text-slate-600",children:"Production context"}),e.jsx(Fs,{className:"mt-1",rows:2,value:c.production_context,onChange:M=>N("production_context",M.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(te,{className:"text-[12px] text-slate-600",children:"Personal notes"}),e.jsx(Fs,{className:"mt-1",rows:4,value:c.notes,onChange:M=>N("notes",M.target.value)})]})]}),e.jsxs("section",{className:"rounded-xl ring-1 ring-rose-200 bg-rose-50/60 p-4 space-y-3",children:[e.jsx("h3",{className:"text-[11px] uppercase tracking-wider font-semibold text-rose-700",children:"Danger zone"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(U,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>l.mutate({id:s.id,archived:!s.is_archived},{onSuccess:()=>n(!1)}),children:[e.jsx(n1,{className:"h-3.5 w-3.5 mr-1.5"}),s.is_archived?"Restore to pipeline":"Remove from pipeline (archive)"]}),e.jsxs(U,{variant:"destructive",size:"sm",className:"rounded-full",onClick:()=>p(!0),children:[e.jsx(In,{className:"h-3.5 w-3.5 mr-1.5"})," Delete permanently"]})]}),e.jsx("p",{className:"text-[12px] text-rose-700/80",children:"Archiving keeps every note, touch and score. Deleting is permanent."})]})]}),e.jsxs("div",{className:"sticky bottom-0 bg-white/95 backdrop-blur border-t px-5 py-3 flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-[12px] text-slate-500",children:i.isPending?"Saving…":b?`${v.length} unsaved change${v.length>1?"s":""}`:"All changes saved"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{variant:"ghost",className:"rounded-full",onClick:()=>S(!1),children:[e.jsx(er,{className:"h-4 w-4 mr-1"})," Cancel"]}),e.jsxs(U,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 text-white",disabled:!b||i.isPending,onClick:T,children:[i.isPending&&e.jsx(Et,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save changes"]})]})]})]})}),e.jsx(Fl,{open:u,onOpenChange:h,children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Discard unsaved changes?"}),e.jsxs(Ll,{children:["You have ",v.length," unsaved change(s) on this contact."]})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Keep editing"}),e.jsx(_l,{onClick:()=>{h(!1),n(!1)},children:"Discard"})]})]})}),e.jsx(Fl,{open:m,onOpenChange:p,children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Delete this contact permanently?"}),e.jsx(Ll,{children:"This removes their timeline, follow-ups, pipeline history, scores and recommendations. Event, kit and transaction records will stay but will no longer be linked to anyone. This cannot be undone."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{className:"bg-rose-600 hover:bg-rose-700",onClick:()=>o.mutate(s.id,{onSuccess:()=>{p(!1),n(!1),r==null||r()}}),children:"Delete forever"})]})]})})]})}function pdr(){const s=Wn(),[t,n]=fc(),{agents:r,activeAgents:a,isLoading:i,moveStage:l}=EE(),{followUps:o,complete:c}=t8e(),{data:d=[]}=JIe();uat();const u=t.get("view")||"attention",h=V=>n(K=>(K.set("view",V),K),{replace:!0}),[m,p]=j.useState(""),[f,x]=j.useState("all"),[y,v]=j.useState(!1),[b,N]=j.useState(!1),[S,A]=j.useState(!1),[T,L]=j.useState(null),[M,I]=j.useState(null),R=V=>!!V.is_archived!==y||f!=="all"&&GA(V.stage).key!==f?!1:m.trim()?`${V.first_name} ${V.last_name??""} ${V.brokerage??""} ${V.city??""} ${(V.tags??[]).join(" ")} ${V.email??""}`.toLowerCase().includes(m.trim().toLowerCase()):!0,z=j.useMemo(()=>r.filter(R),[r,m,f,y]),$=j.useMemo(()=>{const V=vf(new Date),K=o.filter(ne=>!ne.completed_at),Z=d.filter(ne=>ne.status==="open"),Q=K.filter(ne=>ne.due_at&&rS(new Date(ne.due_at),V)),le=K.filter(ne=>ne.due_at&&ry(new Date(ne.due_at))),ue=a.filter(ne=>{const ie=ne.last_touch_at?new Date(ne.last_touch_at):null;return ie?Date.now()-+ie>45*864e5:!!ne.created_at&&Date.now()-+new Date(ne.created_at)>14*864e5}),se=a.filter(ne=>!ne.next_follow_up_at&&!K.some(ie=>ie.agent_id===ne.id));return{overdue:Q,dueToday:le,quiet:ue,noNextStep:se,openRecs:Z}},[o,d,a]),H=V=>{const K=r.find(Z=>Z.id===V);return K?`${K.first_name} ${K.last_name??""}`.trim():"Someone"};return a.length,$.overdue.length,$.dueToday.length,$.quiet.length,e.jsxs("div",{children:[e.jsx(krs,{open:b,onOpenChange:N,onAdded:V=>V&&s(`/attract/agents/${V}`)}),e.jsx(cdr,{open:S,onOpenChange:A}),e.jsx(Lrs,{agent:T?r.find(V=>V.id===T.id)??T:null,open:!!T,onOpenChange:V=>!V&&L(null)}),e.jsx(TE,{eyebrow:"Agents",title:"Your recruiting pipeline",description:"Every agent you're building with, who needs attention today, and what you promised them.",stats:[{label:"In pipeline",value:a.length},{label:"Overdue",value:$.overdue.length,tone:$.overdue.length?"text-rose-400":void 0},{label:"Due today",value:$.dueToday.length,tone:$.dueToday.length?"text-amber-400":void 0},{label:"Gone quiet",value:$.quiet.length}],actions:e.jsxs(e.Fragment,{children:[e.jsxs(U,{variant:"outline",className:"rounded-full bg-white/10 text-white border-white/20 hover:bg-white/20 hover:text-white",onClick:()=>A(!0),children:[e.jsx(qa,{className:"h-3.5 w-3.5 mr-1.5"})," Import"]}),e.jsxs(U,{className:"rounded-full bg-white text-slate-900 hover:bg-slate-100",onClick:()=>N(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-1"})," Add agent"]})]})}),e.jsxs(we,{className:"p-3 rounded-2xl flex flex-wrap items-center gap-2 mb-5",children:[e.jsxs("div",{className:"relative flex-1 min-w-[220px]",children:[e.jsx(Fr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(xe,{value:m,onChange:V=>p(V.target.value),placeholder:"Search name, brokerage, market, tag…",className:"pl-9 rounded-full h-9","aria-label":"Search relationships"})]}),e.jsxs(Ns,{value:f,onValueChange:x,children:[e.jsx(ws,{className:"w-[190px] h-9 rounded-full text-[13px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"all",children:"All stages"}),[...HA,s8e].map(V=>e.jsx(et,{value:V.key,children:V.label},V.key))]})]}),e.jsxs(U,{variant:y?"default":"outline",size:"sm",className:"rounded-full h-9",onClick:()=>v(V=>!V),children:[e.jsx(n1,{className:"h-3.5 w-3.5 mr-1.5"})," ",y?"Archived":"Active"]}),e.jsx("div",{className:"flex bg-slate-100 rounded-full p-0.5",children:[["attention","Needs attention"],["stages","Stages"],["list","List"]].map(([V,K])=>e.jsxs("button",{onClick:()=>h(V),className:Mt("rounded-full h-8 px-3 text-[12.5px] font-medium transition-colors",u===V?"bg-white text-slate-900 shadow-sm":"text-slate-500 hover:text-slate-800"),children:[V==="stages"?e.jsx(Hg,{className:"h-3.5 w-3.5 mr-1 inline"}):V==="list"?e.jsx(m0,{className:"h-3.5 w-3.5 mr-1 inline"}):null,K]},V))})]}),i?e.jsxs("div",{className:"space-y-3","aria-busy":"true",children:[e.jsx("div",{className:"text-[13px] text-slate-500",children:"Loading your relationships…"}),[0,1,2].map(V=>e.jsx(xn,{className:"h-24 w-full rounded-2xl"},V))]}):r.length?u==="attention"?e.jsxs("div",{className:"space-y-6",children:[e.jsx(ade,{title:"Overdue commitments",tone:"#f43f5e",items:$.overdue,render:V=>e.jsx(X4t,{f:V,name:H(V.agent_id),onDone:()=>c.mutate(V.id)},V.id)}),e.jsx(ade,{title:"Due today",tone:"#f97316",items:$.dueToday,render:V=>e.jsx(X4t,{f:V,name:H(V.agent_id),onDone:()=>c.mutate(V.id)},V.id)}),e.jsx(ade,{title:"Haven't talked in a while",tone:"#8b5cf6",items:$.quiet.filter(R),render:V=>e.jsx(sBe,{a:V,note:V.last_touch_at?`Last touch ${Gs(new Date(V.last_touch_at),"MMM d")}`:"No meaningful touch yet"},V.id)}),e.jsx(ade,{title:"No next step set",tone:"#94a3b8",items:$.noNextStep.filter(R),render:V=>e.jsx(sBe,{a:V,note:"Decide one small next step"},V.id)}),!$.overdue.length&&!$.dueToday.length&&!$.quiet.length&&!$.noNextStep.length&&e.jsxs(we,{className:"rounded-2xl border-dashed border-slate-300 bg-white/60 p-8 text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Nothing needs attention."}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1",children:"Great time to reconnect with someone you haven’t spoken with recently."})]})]}):u==="stages"?e.jsxs(Gi,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:HA.length*290},children:HA.map(V=>{const K=z.filter(Z=>GA(Z.stage).key===V.key);return e.jsxs("div",{className:"w-[275px] flex-shrink-0",onDragOver:Z=>{Z.preventDefault(),Z.dataTransfer.dropEffect="move"},onDrop:Z=>{Z.preventDefault();const Q=r.find(le=>le.id===M);Q&&GA(Q.stage).key!==V.key&&l.mutate({id:Q.id,to_stage:hat(V.key),from_stage:Q.stage}),I(null)},children:[e.jsxs("div",{className:"px-1 mb-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{background:V.color}}),e.jsx("h3",{className:"text-[13px] font-semibold text-slate-800",children:V.label}),e.jsx(Be,{variant:"secondary",className:"text-[10px] h-5 px-1.5",children:K.length})]}),e.jsx("div",{className:"text-[11px] text-slate-400 mt-0.5 pl-4.5",children:V.help})]}),e.jsxs("div",{className:"rounded-2xl bg-slate-100/60 p-2 space-y-2 min-h-[180px]",children:[K.map(Z=>e.jsxs("div",{draggable:!0,onDragStart:()=>I(Z.id),onClick:()=>s(`/attract/agents/${Z.id}`),className:"bg-white rounded-xl p-3 cursor-pointer hover:shadow-md border-l-[3px] transition-all",style:{borderLeftColor:V.color},children:[e.jsxs("div",{className:"text-[13.5px] font-semibold text-slate-900 truncate",children:[Z.first_name," ",Z.last_name]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 flex items-center gap-1 mt-0.5 truncate",children:[e.jsx(_i,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:Z.brokerage??"Brokerage not set"})]}),!Z.email&&!Z.phone&&e.jsx("div",{className:"mt-1.5 text-[10.5px] text-amber-700",children:"No contact info yet"})]},Z.id)),!K.length&&e.jsx("div",{className:"text-[11.5px] text-slate-400 text-center py-4",children:"Drag someone here"})]})]},V.key)})}),e.jsx(Vne,{orientation:"horizontal"})]}):e.jsxs(we,{className:"rounded-2xl divide-y divide-slate-100 overflow-hidden",children:[z.map(V=>e.jsx(sBe,{a:V,onEdit:()=>L(V)},V.id)),!z.length&&e.jsx("div",{className:"p-10 text-center text-[13px] text-slate-500",children:"No one matches this view."})]}):e.jsx(fdr,{onAdd:()=>N(!0)})]})}function ade({title:s,tone:t,items:n,render:r}){return n.length?e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{background:t}}),e.jsx("h3",{className:"text-[13px] font-semibold uppercase tracking-wider text-slate-700",children:s}),e.jsx(Be,{variant:"secondary",className:"text-[10px]",children:n.length})]}),e.jsx(we,{className:"rounded-2xl divide-y divide-slate-100 overflow-hidden",children:n.slice(0,12).map(r)})]}):null}function X4t({f:s,name:t,onDone:n}){return e.jsxs("div",{className:"flex items-start gap-3 p-4 hover:bg-slate-50",children:[e.jsx(xi,{checked:!1,onCheckedChange:n,className:"mt-0.5","aria-label":"Mark complete"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:s.title}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:[s.agent_id?e.jsxs(xr,{to:`/attract/agents/${s.agent_id}`,className:"hover:text-violet-700",children:["for ",t]}):"Personal task",s.due_at&&e.jsxs(e.Fragment,{children:[" · due ",Gs(new Date(s.due_at),"MMM d")]})]})]})]})}function sBe({a:s,note:t,onEdit:n}){var i,l;const r=GA(s.stage),a=`${((i=s.first_name)==null?void 0:i[0])??""}${((l=s.last_name)==null?void 0:l[0])??""}`.toUpperCase();return e.jsxs("div",{className:"flex items-center gap-3 p-4 hover:bg-slate-50",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-violet-100 text-violet-700 grid place-items-center text-[12px] font-semibold flex-shrink-0",children:a||"?"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs(xr,{to:`/attract/agents/${s.id}`,className:"text-[13.5px] font-medium text-slate-900 hover:text-violet-700",children:[s.first_name," ",s.last_name]}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5 flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(_i,{className:"h-3 w-3"}),s.brokerage??"Brokerage not set"]}),s.city&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ni,{className:"h-3 w-3"}),s.city]}),t&&e.jsxs("span",{className:"text-slate-400",children:["· ",t]})]})]}),e.jsx(Be,{variant:"outline",className:"rounded-full text-[10.5px] hidden sm:inline-flex",style:{borderColor:`${r.color}55`,color:r.color},children:r.label}),n&&e.jsx(U,{variant:"ghost",size:"sm",className:"rounded-full",onClick:n,children:"Edit"})]})}function fdr({onAdd:s}){return e.jsxs(we,{className:"rounded-2xl border-dashed border-slate-300 bg-white/60 p-10 text-center",children:[e.jsx("div",{className:"h-11 w-11 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(zk,{className:"h-5 w-5"})}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Add your first five relationships"}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1 max-w-md mx-auto",children:"Start with agents you already know — co-op partners, people from your office, agents you met at an event. Attract will begin recommending meaningful next steps."}),e.jsxs(U,{className:"rounded-full btn-primary text-white mt-4",onClick:s,children:[e.jsx(an,{className:"h-4 w-4 mr-1.5"})," Add a relationship"]})]})}const gdr={call:ba,email:ln,coffee:M4,gift:Ro,text:ln,event:ch};function xdr(){const{followUps:s,complete:t}=t8e(),{agents:n}=EE(),r=j.useMemo(()=>{const l=vf(new Date),o=[],c=[],d=[],u=[],h=[];for(const m of s){if(m.completed_at){h.push(m);continue}if(!m.due_at){u.push(m);continue}const p=new Date(m.due_at);rS(p,l)?o.push(m):ry(p)?c.push(m):n3s(p)?d.push(m):u.push(m)}return{overdue:o,today:c,tomorrow:d,later:u,done:h}},[s]),a=new Map(n.map(l=>[l.id,l])),i=[{label:"Overdue",value:r.overdue.length,tone:"text-rose-600 bg-rose-50",icon:Vo},{label:"Due Today",value:r.today.length,tone:"text-orange-600 bg-orange-50",icon:Yr},{label:"Completed This Week",value:r.done.filter(l=>l.completed_at&&new Date(l.completed_at)>jh(new Date,-7)).length,tone:"text-emerald-600 bg-emerald-50",icon:zr}];return e.jsxs("div",{children:[e.jsx(TE,{eyebrow:"Follow-Up Center",title:"One list. One rhythm. One relationship at a time.",description:"Everything you promised to do — organized so it never feels like a to-do list."}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mb-6",children:i.map(l=>e.jsxs(we,{className:"p-5 rounded-2xl flex items-center gap-4",children:[e.jsx("div",{className:`h-11 w-11 rounded-xl grid place-items-center ${l.tone}`,children:e.jsx(l.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-semibold text-slate-900",children:l.value}),e.jsx("div",{className:"text-[12px] uppercase tracking-wider text-slate-500",children:l.label})]})]},l.label))}),e.jsx("div",{className:"mb-6",children:e.jsx(Prs,{})}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(JY,{title:"Overdue",items:r.overdue,agentMap:a,onComplete:l=>t.mutate(l),tone:"rose"}),e.jsx(JY,{title:"Today",items:r.today,agentMap:a,onComplete:l=>t.mutate(l),tone:"orange"}),e.jsx(JY,{title:"Tomorrow",items:r.tomorrow,agentMap:a,onComplete:l=>t.mutate(l),tone:"violet"}),e.jsx(JY,{title:"Later This Week",items:r.later,agentMap:a,onComplete:l=>t.mutate(l),tone:"slate"}),r.done.length>0&&e.jsx(JY,{title:"Recently Completed",items:r.done.slice(0,5),agentMap:a,onComplete:()=>{},tone:"emerald",done:!0})]})]})}function JY({title:s,items:t,agentMap:n,onComplete:r,tone:a,done:i}){if(t.length===0)return null;const l={rose:"#f43f5e",orange:"#f97316",violet:"#8b5cf6",slate:"#94a3b8",emerald:"#10b981"};return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{background:l[a]}}),e.jsx("h3",{className:"text-[13px] font-semibold uppercase tracking-wider text-slate-700",children:s}),e.jsx(Be,{variant:"secondary",className:"text-[10px]",children:t.length})]}),e.jsx(we,{className:"rounded-2xl divide-y divide-slate-100 overflow-hidden",children:t.map(o=>{const c=n.get(o.agent_id),d=gdr[o.touch_type??""]??ln;return e.jsxs("div",{className:`flex items-start gap-3 p-4 hover:bg-slate-50 ${i?"opacity-60":""}`,children:[e.jsx(xi,{checked:!!o.completed_at,onCheckedChange:()=>r(o.id),className:"mt-1"}),e.jsx("div",{className:"h-8 w-8 rounded-lg grid place-items-center flex-shrink-0",style:{background:`${l[a]}18`,color:l[a]},children:e.jsx(d,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:o.title}),c&&e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["for ",c.first_name," ",c.last_name," · ",c.brokerage]}),o.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1",children:o.notes})]}),o.due_at&&e.jsx("div",{className:"text-[11.5px] text-slate-500 whitespace-nowrap",children:Gs(new Date(o.due_at),"MMM d")}),e.jsx(U,{variant:"ghost",size:"sm",children:"Snooze"})]},o.id)})})]})}function ydr(){const{user:s}=vs(),t=ct({queryKey:["attract-resources",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:r,error:a}=await q.from("attract_resources").select("*").order("created_at",{ascending:!1});if(a)throw a;return r??[]}}),n=ct({queryKey:["attract-resource-shares",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:r,error:a}=await q.from("attract_resource_shares").select("*").order("created_at",{ascending:!1});if(a)throw a;return r??[]}});return{resources:t.data??[],shares:n.data??[],isLoading:t.isLoading}}const vdr={pdf:Ur,link:ad,video:Wr,tool:O4,guide:ig},bdr={script:"bg-violet-100 text-violet-700",checklist:"bg-teal-100 text-teal-700",tool:"bg-orange-100 text-orange-700",guide:"bg-indigo-100 text-indigo-700",masterclass:"bg-rose-100 text-rose-700"};function _dr(){const{resources:s,isLoading:t}=ydr(),[n,r]=j.useState(""),[a,i]=j.useState("all"),l=Array.from(new Set(s.map(c=>c.category).filter(Boolean))),o=s.filter(c=>(a==="all"||c.category===a)&&(!n||`${c.title} ${c.description??""}`.toLowerCase().includes(n.toLowerCase())));return e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-5",children:[e.jsx("div",{className:"text-[13px] text-slate-500",children:"Every resource, script, and tool you use — ready to share in one click."}),e.jsxs(U,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",children:[e.jsx(an,{className:"h-4 w-4 mr-1"})," Add Resource"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-5",children:[e.jsxs("div",{className:"relative flex-1 min-w-[240px] max-w-md",children:[e.jsx(Fr,{className:"h-4 w-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx(xe,{value:n,onChange:c=>r(c.target.value),placeholder:"Search resources…",className:"pl-9 rounded-full bg-white"})]}),e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[e.jsx(U,{size:"sm",variant:a==="all"?"default":"outline",className:"rounded-full h-8",onClick:()=>i("all"),children:"All"}),l.map(c=>e.jsx(U,{size:"sm",variant:a===c?"default":"outline",className:"rounded-full h-8 capitalize",onClick:()=>i(c),children:c},c))]})]}),t?e.jsx("div",{className:"py-24 text-center text-slate-500",children:"Loading resources…"}):o.length===0?e.jsx(we,{className:"p-12 text-center rounded-2xl",children:e.jsx("div",{className:"text-slate-500",children:"No resources yet. Add your first shareable asset above."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:o.map(c=>{const d=vdr[c.resource_type]??Ur;return e.jsxs(we,{className:"p-5 rounded-2xl hover:shadow-md transition-all group",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-violet-50 grid place-items-center text-violet-600",children:e.jsx(d,{className:"h-5 w-5"})}),c.category&&e.jsx(Be,{className:`${bdr[c.category]??"bg-slate-100 text-slate-700"} border-0 capitalize`,children:c.category})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"font-semibold text-slate-900",children:c.title}),c.description&&e.jsx("div",{className:"text-[13px] text-slate-600 mt-1 line-clamp-2",children:c.description})]}),e.jsxs("div",{className:"mt-4 pt-4 border-t border-slate-100 flex items-center justify-between text-[12px] text-slate-500",children:[e.jsx("div",{children:"Shared 0×"}),e.jsxs(U,{size:"sm",variant:"outline",className:"rounded-full gap-1",children:[e.jsx(jd,{className:"h-3.5 w-3.5"})," Share"]})]})]},c.id)})})]})}const Irs=[{step:"First outreach",icon:Ki,color:"#7c3aed",title:"After you meet at a closing or showing",channel:"Text",body:"Hey {{first_name}} — {{your_name}} from the {{address}} deal. You were easy to work with, which is rarer than it should be. I keep a short list of agents I like doing business with and you made it. Coffee sometime in the next couple weeks?"},{step:"First outreach",icon:Ki,color:"#7c3aed",title:"Congratulate a recent close",channel:"DM",body:"Saw your closing at {{property}} — nice work {{first_name}}. Those aren’t easy in this market. If you ever want to trade notes on what’s actually getting deals across the line right now, I’m always up for a coffee."},{step:"Value first",icon:$r,color:"#4f46e5",title:"Send something useful, no ask",channel:"Email",body:`Hey {{first_name}} — I put this together for my own business and figured you’d get more out of it than my hard drive will: {{resource_link}} No agenda. If it saves you an hour this week, that’s a win.`},{step:"Value first",icon:$r,color:"#4f46e5",title:"Share the kit after a good conversation",channel:"Email",body:`Great talking today {{first_name}}. Here’s the {{kit_name}} I mentioned — everything in there is what I actually run in my business: {{kit_link}} Steal any of it. If a piece of it doesn’t make sense, text me and I’ll walk you through it.`},{step:"The coffee ask",icon:M4,color:"#0d9488",title:"Direct, low-pressure invite",channel:"Text",body:"Hey {{first_name}}, any chance you’re free for a 30-minute coffee in the next two weeks? No agenda — I just want to hear how the year is actually going for you."},{step:"The coffee ask",icon:M4,color:"#0d9488",title:'When they ask "what’s this about?"',channel:"Text",body:"Honestly? I like how you work and I think we’d both get something out of knowing each other better. If at some point it makes sense to talk about what I’m building, we can — but that’s not why I’m asking."},{step:"The numbers talk",icon:a1,color:"#c9a84c",title:"Open the comp conversation",channel:"Text",body:"{{first_name}} — you mentioned fees eating into your year. I have a calculator that runs your actual production against what you’d have kept here. Takes four minutes and I’ll send you the sheet either way. Want me to run it?"},{step:"The numbers talk",icon:a1,color:"#c9a84c",title:"Follow-up with the one-pager",channel:"Email",body:`Here’s the breakdown we ran, {{first_name}}. Same production, two different outcomes. {{summary}} No pressure and no follow-up spam. If you want to walk through the assumptions, I’m around.`},{step:"When they go quiet",icon:IA,color:"#f97316",title:"After they ghost you",channel:"Text",body:"Hey {{first_name}} — no reply needed. Assuming things got busy, which is a good problem. I’ll check back in a few months. If anything changes before then, you know where I am."},{step:"When they go quiet",icon:IA,color:"#f97316",title:"The quarterly re-open",channel:"Text",body:"Hey {{first_name}} — quarter’s wrapping up. How did it land for you? Genuinely curious, no ask attached."},{step:"When they say no",icon:IA,color:"#94a3b8",title:"Keep the relationship, drop the pitch",channel:"Text",body:"Totally respect that {{first_name}}. I’m not going anywhere and neither is the offer. I’d still like to stay in touch — I’ll send you anything useful I come across, and if the situation ever changes, one text is all it takes."},{step:"After they join",icon:a1,color:"#16a34a",title:"Day one welcome",channel:"Text",body:"Welcome aboard {{first_name}}. Here’s what happens this week: 1) onboarding call Tuesday, 2) database imported by Thursday, 3) your first campaign live by Friday. I’ll drive all three. You just keep selling."}],wdr=["All",...Array.from(new Set(Irs.map(s=>s.step)))];function jdr(){const[s,t]=j.useState(""),[n,r]=j.useState("All"),a=j.useMemo(()=>Irs.filter(l=>(n==="All"||l.step===n)&&(!s||`${l.title} ${l.body} ${l.step}`.toLowerCase().includes(s.toLowerCase()))),[s,n]),i=l=>{navigator.clipboard.writeText(l),re.success("Script copied")};return e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-5",children:[e.jsxs("div",{className:"relative flex-1 min-w-[240px] max-w-sm",children:[e.jsx(Fr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(xe,{value:s,onChange:l=>t(l.target.value),placeholder:"Search scripts…",className:"pl-9 rounded-full h-9 bg-white","aria-label":"Search scripts"})]}),e.jsx("div",{className:"flex gap-1.5 flex-wrap",children:wdr.map(l=>e.jsx("button",{onClick:()=>r(l),className:Mt("rounded-full h-9 px-3.5 text-[12.5px] font-medium border transition-colors",n===l?"bg-slate-900 text-white border-slate-900":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"),children:l},l))})]}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:a.map(l=>{const o=l.icon;return e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200/80 flex flex-col",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("div",{className:"h-9 w-9 rounded-xl grid place-items-center flex-shrink-0",style:{background:`${l.color}18`,color:l.color},children:e.jsx(o,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[14.5px] font-semibold text-slate-900 leading-snug",children:l.title}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:l.step})]})]}),e.jsx(Be,{variant:"outline",className:"rounded-full text-[10px] uppercase tracking-wider flex-shrink-0",children:l.channel})]}),e.jsx("p",{className:"mt-4 text-[13.5px] text-slate-700 leading-relaxed whitespace-pre-wrap",children:l.body}),e.jsx("div",{className:"mt-auto pt-4 flex justify-end",children:e.jsxs(U,{variant:"outline",size:"sm",className:"rounded-full gap-1.5",onClick:()=>i(l.body),children:[e.jsx(Pa,{className:"h-3.5 w-3.5"})," Copy"]})})]},l.title)})}),e.jsx("p",{className:"mt-6 text-center text-[11.5px] text-slate-400 max-w-xl mx-auto",children:"Merge fields are placeholders — replace them with real details before sending. A script that sounds like a script gets ignored."})]})}const Ndr=s=>s.toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});function kdr(){const{agents:s}=EE(),{activities:t}=_rs(365),n=j.useMemo(()=>s.filter(c=>GA(c.stage).key==="joined"),[s]),r=j.useMemo(()=>{const c=i5s(new Date),d=yXe(new Date),u=y=>y.joined_at?new Date(y.joined_at):new Date(y.updated_at),h=n.filter(y=>u(y)>=c).length,m=n.filter(y=>u(y)>=d).length,p=n.map(y=>nv(u(y),new Date(y.created_at))).filter(y=>Number.isFinite(y)&&y>=0),f=p.length?Math.round(p.reduce((y,v)=>y+v,0)/p.length):null,x=n.reduce((y,v)=>y+(v.est_revenue_share??0),0);return{thisQuarter:h,thisYear:m,avgDays:f,revShare:x}},[n]),a=j.useMemo(()=>{const c=s.filter(d=>!d.is_archived);return HA.map(d=>({stage:d.label,count:c.filter(u=>GA(u.stage).key===d.key).length,color:d.color}))},[s]),i=j.useMemo(()=>{const c=s.filter(h=>!h.is_archived),d=c.length,u=c.filter(h=>GA(h.stage).key==="joined").length;return d?Math.round(u/d*100):0},[s]),l=j.useMemo(()=>Array.from({length:12},(d,u)=>{const h=new Date;return h.setDate(1),h.setMonth(h.getMonth()-(11-u)),h}).map(d=>{const u=new Date(d);u.setMonth(u.getMonth()+1);const h=t.filter(p=>{const f=new Date(p.created_at);return f>=d&&f{const f=p.joined_at?new Date(p.joined_at):new Date(p.updated_at);return f>=d&&f{var d;const c=new Map;for(const u of n){const h=((d=u.source)==null?void 0:d.trim())||"Unknown";c.set(h,(c.get(h)??0)+1)}return Array.from(c.entries()).map(([u,h])=>({source:u,count:h})).sort((u,h)=>h.count-u.count).slice(0,6)},[n]);return e.jsxs("div",{children:[e.jsx(TE,{eyebrow:"Results",title:"Who joined, and what actually got them there.",description:"No score, no gamification — just the numbers that tell you where to spend next month.",stats:[{label:"Joined this quarter",value:r.thisQuarter,tone:"text-emerald-400"},{label:"Joined this year",value:r.thisYear},{label:"Avg. days to join",value:r.avgDays??"—"},{label:"Est. annual rev share",value:Ndr(r.revShare)}]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-5",children:[e.jsxs(we,{className:"p-6 rounded-2xl",children:[e.jsxs("div",{className:"flex items-baseline justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500",children:"Pipeline"}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900 mt-0.5",children:"Where everyone stands"})]}),e.jsxs(Be,{variant:"outline",className:"rounded-full",children:[i,"% joined"]})]}),e.jsx(oj,{width:"100%",height:260,children:e.jsxs(RLe,{data:a,layout:"vertical",margin:{left:28},children:[e.jsx(wb,{type:"number",tick:{fontSize:11},allowDecimals:!1}),e.jsx(jb,{dataKey:"stage",type:"category",tick:{fontSize:11},width:120}),e.jsx(Tg,{cursor:{fill:"#f8fafc"}}),e.jsx(pN,{dataKey:"count",radius:[0,8,8,0],children:a.map((c,d)=>e.jsx(VG,{fill:c.color},d))})]})})]}),e.jsxs(we,{className:"p-6 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500",children:"Momentum"}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900 mt-0.5 mb-4",children:"Touches vs. joins · last 12 months"}),e.jsx(oj,{width:"100%",height:260,children:e.jsxs(Att,{data:l,children:[e.jsx(wb,{dataKey:"month",tick:{fontSize:11}}),e.jsx(jb,{tick:{fontSize:11},allowDecimals:!1}),e.jsx(Tg,{}),e.jsx(gP,{type:"monotone",dataKey:"touches",stroke:"#8b5cf6",strokeWidth:2.5,dot:!1,name:"Touches"}),e.jsx(gP,{type:"monotone",dataKey:"joins",stroke:"#16a34a",strokeWidth:2.5,dot:{r:3},name:"Joins"})]})})]}),e.jsxs(we,{className:"p-6 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500",children:"Attribution"}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900 mt-0.5 mb-4",children:"What produced the joins"}),o.length===0?e.jsx("div",{className:"text-[13px] text-slate-500 py-10 text-center",children:"No one has joined yet. Sources appear here the moment they do."}):e.jsx("div",{className:"space-y-2.5",children:o.map(c=>{const d=o[0].count||1;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-[13px] mb-1",children:[e.jsx("span",{className:"text-slate-700 capitalize",children:c.source.replace(/_/g," ")}),e.jsx("span",{className:"font-semibold text-slate-900 tabular-nums",children:c.count})]}),e.jsx("div",{className:"h-2 rounded-full bg-slate-100 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-violet-500 to-indigo-500",style:{width:`${c.count/d*100}%`}})})]},c.source)})})]}),e.jsxs(we,{className:"p-6 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(Al,{className:"h-4 w-4 text-amber-500"}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:"Agents who joined"})]}),n.length===0?e.jsx("div",{className:"text-[13px] text-slate-500 py-10 text-center",children:"Your first join shows up here — with how long it took and where it came from."}):e.jsx("div",{className:"divide-y divide-slate-100",children:n.slice(0,8).map(c=>{const d=c.joined_at?new Date(c.joined_at):new Date(c.updated_at),u=nv(d,new Date(c.created_at));return e.jsxs(xr,{to:`/attract/agents/${c.id}`,className:"flex items-center justify-between gap-3 py-3 group",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-[13.5px] font-medium text-slate-900 truncate",children:[c.first_name," ",c.last_name]}),e.jsxs("div",{className:"text-[12px] text-slate-500 truncate",children:[Gs(d,"MMM d, yyyy"),u>=0?` · ${u} days from first touch`:""]})]}),e.jsx(Oa,{className:"h-4 w-4 text-slate-300 group-hover:text-violet-600 transition-colors"})]},c.id)})}),e.jsx(U,{variant:"outline",className:"rounded-full w-full mt-4",asChild:!0,children:e.jsx(xr,{to:"/attract/agents",children:"Open the pipeline"})})]})]})]})}function Sdr(){const{settings:s,upsert:t,resetOnboarding:n}=cat(),[r,a]=j.useState({});j.useEffect(()=>{s&&a(s)},[s]);const i=l=>a({...r,...l});return e.jsxs("div",{className:"max-w-3xl",children:[e.jsx(TE,{eyebrow:"Attract Settings",title:"Your attraction philosophy.",description:"A one-time setup that keeps every touch you send true to who you are."}),e.jsxs(we,{className:"p-5 rounded-2xl mb-6 flex flex-col md:flex-row md:items-center gap-4 bg-gradient-to-r from-violet-50 to-indigo-50 border-violet-100",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-white text-violet-700 grid place-items-center shadow-sm",children:e.jsx(Gu,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-[13.5px] font-semibold text-slate-900",children:"Your 90-day plan"}),e.jsx("div",{className:"text-[12.5px] text-slate-600",children:s!=null&&s.onboarding_completed_at?`Primary pillar: ${s.primary_pillar??s.attraction_style??"balanced"} · Outcome: ${s.ninety_day_outcome??"—"}`:"You haven't completed onboarding yet."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{asChild:!0,variant:"outline",className:"rounded-full",children:e.jsx(xr,{to:"/attract/settings",children:"View plan"})}),e.jsxs(U,{variant:"outline",className:"rounded-full",onClick:()=>n.mutate(),children:[e.jsx(Kg,{className:"h-4 w-4 mr-1.5"})," Rerun onboarding"]})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(we,{className:"p-6 rounded-2xl",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-1",children:"Your voice & story"}),e.jsx("p",{className:"text-[13px] text-slate-600 mb-5",children:"Used to personalize scripts, invites, and shared content."}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Elevator introduction"}),e.jsx(Fs,{rows:3,value:r.elevator_intro??"",onChange:l=>i({elevator_intro:l.target.value}),placeholder:"I help agents scale their business by trading isolation for a real team..."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Focus market"}),e.jsx(xe,{value:r.focus_market??"",onChange:l=>i({focus_market:l.target.value}),placeholder:"Orange County, CA"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Annual attraction goal"}),e.jsx(xe,{type:"number",value:r.annual_attract_goal??"",onChange:l=>i({annual_attract_goal:Number(l.target.value)||null}),placeholder:"12"})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:'Your "why" for attraction'}),e.jsx(Fs,{rows:3,value:r.why_statement??"",onChange:l=>i({why_statement:l.target.value}),placeholder:"Because the right agents in the right room change everyone's business..."})]})]})]}),e.jsxs(we,{className:"p-6 rounded-2xl",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-1",children:"Cadence & rhythm"}),e.jsx("p",{className:"text-[13px] text-slate-600 mb-5",children:"How often should we remind you to show up for agents at each stage?"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Hot leads follow-up"}),e.jsxs(Ns,{value:String(r.hot_cadence_days??3),onValueChange:l=>i({hot_cadence_days:Number(l)}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"1",children:"Every day"}),e.jsx(et,{value:"3",children:"Every 3 days"}),e.jsx(et,{value:"7",children:"Every week"})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Warm leads follow-up"}),e.jsxs(Ns,{value:String(r.warm_cadence_days??14),onValueChange:l=>i({warm_cadence_days:Number(l)}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"7",children:"Weekly"}),e.jsx(et,{value:"14",children:"Every 2 weeks"}),e.jsx(et,{value:"30",children:"Monthly"})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Long-term nurture"}),e.jsxs(Ns,{value:String(r.longterm_cadence_days??60),onValueChange:l=>i({longterm_cadence_days:Number(l)}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"30",children:"Monthly"}),e.jsx(et,{value:"60",children:"Every 2 months"}),e.jsx(et,{value:"90",children:"Quarterly"})]})]})]}),e.jsx("div",{className:"flex flex-col justify-end",children:e.jsxs("div",{className:"flex items-center justify-between rounded-xl bg-slate-50 p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-medium text-slate-900",children:"Weekly digest email"}),e.jsx("div",{className:"text-[11.5px] text-slate-500",children:"Every Sunday at 6pm"})]}),e.jsx(wn,{checked:r.weekly_digest_enabled??!0,onCheckedChange:l=>i({weekly_digest_enabled:l})})]})})]})]}),e.jsxs(we,{className:"p-6 rounded-2xl bg-gradient-to-br from-violet-50 to-indigo-50 border-violet-100",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-1",children:"The Attract Trust Reminder"}),e.jsx("p",{className:"text-[13.5px] text-slate-700 leading-relaxed",children:"Attract is never a sales funnel. Every touch you make here should be something you'd be proud of if the agent saw every note you'd taken about them. Real relationships. On a rhythm. For years."})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(U,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 px-8",onClick:()=>t.mutate(r),disabled:t.isPending,children:"Save Settings"})})]})]})}const Q4t=[{to:"/attract/toolkit/kits",label:"Value kits",icon:dh,blurb:"Bundles worth opening"},{to:"/attract/toolkit/scripts",label:"Scripts",icon:EA,blurb:"What to say, word for word"},{to:"/attract/toolkit/objections",label:"Objections",icon:OF,blurb:"Answers that hold up"},{to:"/attract/toolkit/events",label:"Events",icon:Xk,blurb:"Rooms worth being in"},{to:"/attract/toolkit/content",label:"Content",icon:Lg,blurb:"Posts that attract"},{to:"/attract/toolkit/resources",label:"Library",icon:tj,blurb:"Everything else you share"}];function Cdr(){const{pathname:s}=Od(),t=Q4t.find(n=>s.startsWith(n.to));return e.jsxs("div",{children:[e.jsx(TE,{eyebrow:"Recruiting toolkit",title:"Everything you hand an agent — in one place.",description:(t==null?void 0:t.blurb)??"Kits, scripts, objection answers, events and content. Nothing else to hunt for."}),e.jsx("div",{className:"-mt-2 mb-7 overflow-x-auto",children:e.jsx("div",{className:"inline-flex min-w-full gap-1 rounded-2xl bg-white p-1.5 border border-slate-200/80 shadow-sm",children:Q4t.map(n=>{const r=n.icon;return e.jsxs(BT,{to:n.to,className:({isActive:a})=>Mt("group relative flex items-center gap-2 rounded-xl px-4 py-2.5 text-[13px] font-medium whitespace-nowrap transition-all",a?"bg-gradient-to-r from-violet-600 to-indigo-600 text-white shadow-md shadow-violet-600/20":"text-slate-600 hover:bg-slate-50 hover:text-slate-900"),children:[e.jsx(r,{className:"h-4 w-4 opacity-90"}),n.label]},n.to)})})}),e.jsx(LZe,{})]})}const Rrs=[{category:"Model",q:'"Isn’t this just an MLM?"',opener:"Fair question — and the answer is no, and here is the actual difference.",a:"You are paid on real estate commissions you earn. Revenue share is a marketing expense the brokerage pays out of company dollar for agents you personally attract. You never buy inventory, never pay to join a downline, and you never have to recruit anyone to make money here. If you sell zero and attract zero, you still keep more of your commission than you do today."},{category:"Model",q:'"What does it actually cost me?"',opener:"Let me show you your exact numbers instead of a brochure.",a:"A one-time start-up fee, a small monthly technology fee, and a per-transaction broker review fee until you cap. No desk fee, no royalty fee, no franchise fee. Run your last 12 months through the calculator with me and you will see the real difference in take-home, not a hypothetical."},{category:"Brand",q:'"I’d lose my brand and my team."',opener:"Your name stays your name.",a:"You keep your brand, your team, your logo and your database. Branding requirements are minimal, and your marketing stays yours. Most agents who move end up building their brand harder here because nothing is taken off the top to fund someone else’s."},{category:"Loyalty",q:'"I’m loyal to my broker."',opener:"That says a lot about you, and I would never ask you to be disloyal.",a:"Loyalty is the reason I want you on my team — you are exactly the kind of person I would want in the room. But loyalty runs both ways. Look at what you paid in splits and fees last year and ask whether that investment came back to you. If it did, stay. If it did not, you owe it to your family to at least see the math."},{category:"Support",q:'"I need a broker I can actually reach."',opener:"You get two lines of support, not a call center.",a:"State broker support is available and free — real brokers, same day. And you get me directly. Text me at 9pm on a Sunday when a deal is falling apart and I answer. That is the part of this you cannot get from a sign-up link."},{category:"Support",q:'"There’s no office. I’d be on my own."',opener:"You would have more people around you, not fewer.",a:"There are 80+ hours of live training every week and a mastermind you can join from anywhere. Most agents in a physical office talk to two people a week. The agents who move usually tell me they feel less alone, not more — because the room is always open."},{category:"Timing",q:'"What happens to my pending deals?"',opener:"We map every pending file before you sign anything.",a:"Most agents close pendings at their current brokerage, or transfer them depending on their independent contractor agreement. We go through them one by one so there are no surprises and no lost commission."},{category:"Timing",q:'"Now isn’t a good time."',opener:"Then let us pick the time together instead of dropping it.",a:"There is never a clean window in this business. But the transition is typically 24 to 72 hours — application, license transfer, MLS update. If you are mid-listing season, we start the paperwork the week after your next closing. Put a date on the calendar and I will handle the checklist."},{category:"Money",q:'"I’m already capped where I am."',opener:"Then this year is the exact right year to look.",a:"Capping resets on your anniversary. If you move right after your cap year ends, you keep the benefit of the cap you already paid for and start fresh under a lower one. Send me your anniversary date and I will show you the ideal move window."},{category:"Money",q:'"Revenue share sounds too good to be true."',opener:"It is a marketing budget, not magic.",a:"Every brokerage spends money attracting agents — billboards, recruiters, sign-on bonuses. This one pays that budget to the agents who bring people instead. It is paid monthly out of company dollar on production, it is capped per tier, and it is willable. That is the whole mechanism."}],Adr=["All",...Array.from(new Set(Rrs.map(s=>s.category)))];function Edr(){const[s,t]=j.useState(""),[n,r]=j.useState("All"),a=j.useMemo(()=>Rrs.filter(l=>(n==="All"||l.category===n)&&(!s||`${l.q} ${l.a} ${l.opener}`.toLowerCase().includes(s.toLowerCase()))),[s,n]),i=l=>{navigator.clipboard.writeText(`${l.opener} ${l.a}`),re.success("Answer copied")};return e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-5",children:[e.jsxs("div",{className:"relative flex-1 min-w-[240px] max-w-sm",children:[e.jsx(Fr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(xe,{value:s,onChange:l=>t(l.target.value),placeholder:"Search an objection…",className:"pl-9 rounded-full h-9 bg-white","aria-label":"Search objections"})]}),e.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Adr.map(l=>e.jsx("button",{onClick:()=>r(l),className:Mt("rounded-full h-9 px-3.5 text-[12.5px] font-medium border transition-colors",n===l?"bg-slate-900 text-white border-slate-900":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"),children:l},l))})]}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:a.map(l=>e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200/80 flex flex-col",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("div",{className:"h-9 w-9 rounded-xl bg-violet-50 text-violet-600 grid place-items-center flex-shrink-0",children:e.jsx(OF,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 leading-snug",children:l.q})]}),e.jsx(Be,{variant:"outline",className:"rounded-full text-[10px] uppercase tracking-wider flex-shrink-0",children:l.category})]}),e.jsxs("div",{className:"mt-4 rounded-xl bg-amber-50/70 border border-amber-100 px-3.5 py-2.5 flex items-start gap-2",children:[e.jsx(eS,{className:"h-3.5 w-3.5 text-amber-600 mt-0.5 flex-shrink-0"}),e.jsx("div",{className:"text-[12.5px] text-amber-900 font-medium",children:l.opener})]}),e.jsx("p",{className:"mt-3 text-[13.5px] text-slate-700 leading-relaxed",children:l.a}),e.jsx("div",{className:"mt-auto pt-4 flex justify-end",children:e.jsxs(U,{variant:"outline",size:"sm",className:"rounded-full gap-1.5",onClick:()=>i(l),children:[e.jsx(Pa,{className:"h-3.5 w-3.5"})," Copy answer"]})})]},l.q))}),a.length===0&&e.jsx(we,{className:"p-12 rounded-2xl text-center border-dashed text-slate-500",children:"No objection matches that search."}),e.jsx("p",{className:"mt-6 text-center text-[11.5px] text-slate-400 max-w-xl mx-auto",children:"Verify compensation details against your brokerage’s current published materials before sharing. These are conversation starters, not compliance-approved marketing."})]})}const Drs={hero:!0,credibility:!0,story:!0,value_stack:!0,calculator:!0,sponsor:!0,testimonials:!0,faq:!0,lead_magnet:!0,event:!0,final_cta:!0,disclaimer:!0},J4t={hero:"Hero",credibility:"Credibility strip",story:"Why I moved (story)",value_stack:"Value stack",calculator:"Earnings / cap calculator",sponsor:"What you get from me",testimonials:"Proof / testimonials",faq:"Objection-handling FAQ",lead_magnet:"Free download",event:"Upcoming event",final_cta:"Final CTA",disclaimer:"Income disclaimer"},Tdr=[{title:"80/20 split with a $16K cap",body:"Keep 100% of your commission after you cap — no desk fees, no royalty fees, no franchise fees.",proof:"Capped agents keep 100% for the rest of their anniversary year."},{title:"Revenue share",body:"Get paid on the production of agents you attract — income that keeps working when you are not.",proof:"7 tiers, paid monthly, willable to your family."},{title:"Stock awards & ICON",body:"Earn equity for your first transaction, capping, and attracting — plus ICON Agent stock awards.",proof:"Ownership in a publicly traded company (NASDAQ: EXPI)."},{title:"Healthcare options",body:"Access to health, dental and vision plan options built for independent contractors.",proof:"Available through the eXp agent healthcare program."},{title:"Tools included",body:"CRM, IDX website, lead engine, transaction management, and marketing tools with no monthly bill.",proof:"Included in your annual technology fee."},{title:"80+ hours of live training weekly",body:"Cloud campus training with top producers — join from anywhere, replays on demand.",proof:"Live in eXp World, every week."},{title:"Worldwide referral network",body:"Tens of thousands of agents across the globe you can refer to and receive from.",proof:"One brokerage, 20+ countries."},{title:"Keep your brand",body:"Run your team, your brand and your business your way — no office politics, no cap on growth.",proof:"You own your database and your brand."}],Mdr=[{q:"Is this an MLM?",a:"No. You are paid on real estate commissions you earn. Revenue share is a marketing expense the brokerage pays out of company dollar for agents you personally attract — you never buy inventory, pay to join a downline, or recruit to get paid."},{q:"Do I lose my brand or my team?",a:"No. You keep your name, your team, your logo, and your database. Brokerage branding requirements are minimal and your marketing stays yours."},{q:"What happens to my pending deals?",a:"Most agents close pendings at their current brokerage, or transfer them depending on their agreement. We map every pending file before you sign anything."},{q:"How long does the transition take?",a:"Typically 24-72 hours. Application, license transfer with the state, MLS update, and onboarding. I walk you through each step personally."},{q:"What if I need support or a broker on the phone?",a:"State broker support is available and free. Plus you get me — direct access, not a call center."},{q:"What does it actually cost?",a:"A one-time start-up fee, a small monthly technology fee, and a per-transaction broker review fee until you cap. No desk, royalty, or franchise fees. I will show you the exact math for your production."}],Pdr=[{title:"A 30-day onboarding plan",body:"A written plan for your first 30 days — systems set up, database imported, first campaign live."},{title:"Weekly mastermind",body:"A small-group call with agents at your level, focused on real pipeline, not theory."},{title:"Lead & listing systems",body:"The exact marketing systems I use — plug them into your business on day one."},{title:"Direct access to me",body:"Text me. I answer. You are not a number in someone’s downline."}],Ldr="Any income or earnings figures shown are illustrative examples only and are not a guarantee of results. Individual results depend entirely on individual effort, market conditions, and business decisions. Nothing here is an offer of employment or of securities.",Idr={enabled:!0,title:"The Brokerage Comparison Worksheet",body:"A one-page worksheet that shows exactly what you are paying today vs. what you would keep here. No pressure, no follow-up spam.",cta:"Send me the worksheet",file_url:""},eU={enabled:!0,title:"What would you have kept last year?",cap:16e3,split:80,transaction_fee:250,current_split:70,current_monthly_fees:150};function Rdr(s){return{template:"exp_2026",agent_name:s,agent_title:"eXp Realty",eyebrow:"For agents who are done paying for a desk they never use",headline:"Keep more of what you earn — and build something that pays you after the closing.",subheadline:"A private look at how the business actually works here: the numbers, the tools, the support, and what I personally do for the agents who join with me.",cta_label:"Book a confidential 15-min call",story_title:"Why I moved",story_body:"I was not unhappy. I was capped out — paying for an office I never used, watching my splits shrink, and with nothing to show for the agents I sent business to. Here is exactly what changed after I moved, the numbers included.",primary_color:"#0f1b3d",accent_color:"#c9a84c",value_cards:Tdr,sponsor_cards:Pdr,faqs:Mdr,lead_magnet:Idr,calculator:eU,sections:Drs,disclaimer:Ldr,credibility:[],seo_title:`${s} | A confidential look at joining eXp Realty`,seo_description:"See the real numbers, tools, and support behind the move — plus what you get personally when you partner with me."}}function Ors(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}const B0=s=>s.toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});function Ddr(){const{user:s}=vs(),[t,n]=j.useState(""),[r,a]=j.useState(18),[i,l]=j.useState(45e4),[o,c]=j.useState(2.5),[d,u]=j.useState(eU.current_split),[h,m]=j.useState(eU.current_monthly_fees),[p,f]=j.useState(395),[x,y]=j.useState(eU.split),[v,b]=j.useState(eU.cap),[N,S]=j.useState(eU.transaction_fee),[A,T]=j.useState(85),L=j.useMemo(()=>{const R=r*i*(o/100),z=R*(1-d/100),$=h*12+p*r,H=R-z-$,V=R*(1-x/100),K=Math.min(V,v),Z=V>=v,Q=A*12+N*r,le=R-K-Q,ue=x<100?v/(1-x/100):0,se=R>0?Math.ceil(ue/(R/r)):0;return{gci:R,currentNet:H,currentSplitCost:z,currentFees:$,newNet:le,newSplitCost:K,newFees:Q,capped:Z,sidesToCap:se,difference:le-H}},[r,i,o,d,h,p,x,v,N,A]),M=j.useMemo(()=>[`${t?`${t} — `:""}What last year would have looked like`,"",`${r} sides · ${B0(i)} average price · ${o}% commission`,`Gross commission income: ${B0(L.gci)}`,"","Where you are now",` Brokerage split: -${B0(L.currentSplitCost)}`,` Fees: -${B0(L.currentFees)}`,` You keep: ${B0(L.currentNet)}`,"","Where you could be",` Brokerage split (capped at ${B0(v)}): -${B0(L.newSplitCost)}`,` Fees: -${B0(L.newFees)}`,` You keep: ${B0(L.newNet)}`,"",`Difference: ${L.difference>=0?"+":""}${B0(L.difference)} per year`,L.capped?`You would cap in roughly ${L.sidesToCap} sides and keep 100% after that.`:"","","Illustrative only — not a guarantee of results. Verify current fees and caps before making a decision."].filter(Boolean).join(` `),[t,r,i,o,L,v]),I=()=>{var $;const R=encodeURIComponent(t?`${t.split(" ")[0]} — the numbers we talked about`:"The numbers we talked about"),z=encodeURIComponent(`${M} — ${(($=s==null?void 0:s.user_metadata)==null?void 0:$.full_name)??""}`);window.location.href=`mailto:?subject=${R}&body=${z}`};return e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsx(TE,{eyebrow:"The value conversation",title:"Show them their own numbers.",description:"Open this live in a coffee meeting. Enter their real production, and let the math do the convincing.",actions:e.jsxs(e.Fragment,{children:[e.jsxs(U,{variant:"outline",className:"rounded-full bg-white/10 text-white border-white/20 hover:bg-white/20 hover:text-white",onClick:()=>{navigator.clipboard.writeText(M),re.success("Summary copied")},children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1.5"})," Copy"]}),e.jsxs(U,{variant:"outline",className:"rounded-full bg-white/10 text-white border-white/20 hover:bg-white/20 hover:text-white",onClick:()=>window.print(),children:[e.jsx(PA,{className:"h-3.5 w-3.5 mr-1.5"})," Print"]}),e.jsxs(U,{className:"rounded-full bg-white text-slate-900 hover:bg-slate-100",onClick:I,children:[e.jsx(ln,{className:"h-4 w-4 mr-1.5"})," Email it"]})]})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[1fr_420px] gap-6 items-start",children:[e.jsxs("div",{className:"space-y-5",children:[e.jsxs(we,{className:"p-6 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-5",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-violet-50 text-violet-600 grid place-items-center",children:e.jsx(Qw,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:"Their production"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(hC,{label:"Agent name (optional)",children:e.jsx(xe,{value:t,onChange:R=>n(R.target.value),placeholder:"Jordan Reyes"})}),e.jsx(hC,{label:"Sides closed last year",children:e.jsx(xe,{type:"number",value:r,onChange:R=>a(Number(R.target.value)||0)})}),e.jsx(hC,{label:"Average sale price",children:e.jsx(xe,{type:"number",value:i,onChange:R=>l(Number(R.target.value)||0)})}),e.jsx(hC,{label:"Commission %",children:e.jsx(xe,{type:"number",step:"0.1",value:o,onChange:R=>c(Number(R.target.value)||0)})})]}),e.jsxs("div",{className:"mt-5 rounded-xl bg-slate-50 px-4 py-3 flex items-center justify-between",children:[e.jsx("span",{className:"text-[13px] text-slate-600",children:"Gross commission income"}),e.jsx("span",{className:"text-[18px] font-semibold text-slate-900 tabular-nums",children:B0(L.gci)})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5",children:[e.jsxs(we,{className:"p-6 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500 mb-4",children:"Where they are now"}),e.jsx(e3t,{label:"Their split to the agent",suffix:"%",value:d,min:50,max:100,onChange:u}),e.jsx(hC,{label:"Monthly fees (desk, tech, royalty)",className:"mt-4",children:e.jsx(xe,{type:"number",value:h,onChange:R=>m(Number(R.target.value)||0)})}),e.jsx(hC,{label:"Per-transaction fee",className:"mt-4",children:e.jsx(xe,{type:"number",value:p,onChange:R=>f(Number(R.target.value)||0)})})]}),e.jsxs(we,{className:"p-6 rounded-2xl ring-1 ring-violet-200",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-violet-600 mb-4",children:"Where they could be"}),e.jsx(e3t,{label:"Split to the agent",suffix:"%",value:x,min:50,max:100,onChange:y}),e.jsx(hC,{label:"Annual cap",className:"mt-4",children:e.jsx(xe,{type:"number",value:v,onChange:R=>b(Number(R.target.value)||0)})}),e.jsx(hC,{label:"Per-transaction fee",className:"mt-4",children:e.jsx(xe,{type:"number",value:N,onChange:R=>S(Number(R.target.value)||0)})}),e.jsx(hC,{label:"Monthly technology fee",className:"mt-4",children:e.jsx(xe,{type:"number",value:A,onChange:R=>T(Number(R.target.value)||0)})})]})]})]}),e.jsxs("div",{className:"lg:sticky lg:top-6 space-y-4",children:[e.jsxs(we,{className:"relative overflow-hidden rounded-3xl bg-[#0B0F1E] text-white p-7 border-0",children:[e.jsx("div",{className:"pointer-events-none absolute -top-20 -right-10 h-52 w-52 rounded-full bg-emerald-500/20 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-slate-400",children:"Annual difference"}),e.jsxs("div",{className:`mt-2 text-[42px] font-semibold tracking-tight tabular-nums leading-none ${L.difference>=0?"text-emerald-400":"text-rose-400"}`,children:[L.difference>=0?"+":"",B0(L.difference)]}),e.jsx("div",{className:"text-[13px] text-slate-300 mt-2",children:L.difference>=0?"more in their pocket on the exact same production.":"less — be honest about it and focus on the other value."}),e.jsxs("div",{className:"mt-6 space-y-3",children:[e.jsx(t3t,{label:"Keeps today",value:B0(L.currentNet),muted:!0}),e.jsx(t3t,{label:"Would keep here",value:B0(L.newNet),strong:!0})]}),L.capped&&e.jsxs("div",{className:"mt-5 rounded-xl bg-white/[0.07] ring-1 ring-inset ring-white/10 px-4 py-3 flex items-start gap-2.5",children:[e.jsx(rc,{className:"h-4 w-4 text-emerald-400 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-[12.5px] text-slate-200",children:["They’d cap in roughly ",e.jsxs("span",{className:"font-semibold text-white",children:[L.sidesToCap," sides"]})," and keep ",e.jsx("span",{className:"font-semibold text-white",children:"100%"})," of every commission after that."]})]})]})]}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500 mb-3",children:"Breakdown"}),e.jsx(ide,{label:"Split cost today",value:`-${B0(L.currentSplitCost)}`}),e.jsx(ide,{label:"Fees today",value:`-${B0(L.currentFees)}`}),e.jsx("div",{className:"h-px bg-slate-100 my-2.5"}),e.jsx(ide,{label:"Split cost here",value:`-${B0(L.newSplitCost)}`}),e.jsx(ide,{label:"Fees here",value:`-${B0(L.newFees)}`})]}),e.jsx("p",{className:"text-[11px] text-slate-400 leading-relaxed px-1",children:"Illustrative only and not a guarantee of results. Verify current caps, fees and splits against published brokerage materials before sharing with an agent."})]})]})]})}function hC({label:s,children:t,className:n}){return e.jsxs("div",{className:n,children:[e.jsx(te,{className:"text-[12px] text-slate-600",children:s}),e.jsx("div",{className:"mt-1.5",children:t})]})}function e3t({label:s,value:t,min:n,max:r,suffix:a,onChange:i}){return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{className:"text-[12px] text-slate-600",children:s}),e.jsxs("span",{className:"text-[13px] font-semibold text-slate-900 tabular-nums",children:[t,a]})]}),e.jsx(rg,{className:"mt-3",value:[t],min:n,max:r,step:1,onValueChange:l=>i(l[0])})]})}function t3t({label:s,value:t,strong:n,muted:r}){return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:`text-[13px] ${r?"text-slate-400":"text-slate-300"}`,children:s}),e.jsx("span",{className:`tabular-nums ${n?"text-[20px] font-semibold text-white":"text-[15px] text-slate-300"}`,children:t})]})}function ide({label:s,value:t}){return e.jsxs("div",{className:"flex items-center justify-between py-1",children:[e.jsx("span",{className:"text-[12.5px] text-slate-600",children:s}),e.jsx("span",{className:"text-[12.5px] font-medium text-slate-900 tabular-nums",children:t})]})}function Odr(){const s=Wn(),{data:t=[],isLoading:n}=Srs(),r=sdr(),a=Jcr(),[i,l]=j.useState("all"),[o,c]=j.useState(""),d=j.useMemo(()=>t.filter(u=>!(i!=="all"&&u.status!==i||o&&!u.title.toLowerCase().includes(o.toLowerCase()))),[t,i,o]);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-3",children:[e.jsx("div",{className:"text-[13px] text-slate-500",children:"Every room you have built — drafted, live, and complete."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(xe,{placeholder:"Search events",className:"pl-9 rounded-full w-[240px] bg-white",value:o,onChange:u=>c(u.target.value)})]}),e.jsxs(U,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 hover:from-violet-700 hover:to-indigo-700",onClick:()=>s("/attract/events/new"),children:[e.jsx(an,{className:"h-4 w-4 mr-2"})," New event"]})]})]}),e.jsxs(oa,{value:i,onValueChange:u=>l(u),children:[e.jsxs(la,{className:"rounded-full bg-white border border-slate-200",children:[e.jsxs(Kt,{value:"all",className:"rounded-full",children:["All (",t.length,")"]}),e.jsxs(Kt,{value:"draft",className:"rounded-full",children:["Drafts (",t.filter(u=>u.status==="draft").length,")"]}),e.jsxs(Kt,{value:"published",className:"rounded-full",children:["Published (",t.filter(u=>u.status==="published").length,")"]}),e.jsxs(Kt,{value:"completed",className:"rounded-full",children:["Completed (",t.filter(u=>u.status==="completed").length,")"]})]}),e.jsx(Zt,{value:i,className:"mt-5",children:n?e.jsx(we,{className:"p-12 rounded-2xl text-center text-slate-500",children:"Loading events…"}):d.length===0?e.jsxs(we,{className:"p-12 rounded-2xl text-center border-dashed",children:[e.jsx(pa,{className:"h-8 w-8 text-slate-300 mx-auto"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mt-3",children:"No events here yet"}),e.jsx("div",{className:"text-slate-500 mt-1",children:"Start with a small coffee or a mastermind — one conversation is enough."}),e.jsxs(U,{className:"mt-4 rounded-full",onClick:()=>s("/attract/events/new"),children:[e.jsx(an,{className:"h-4 w-4 mr-2"})," Create your first event"]})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5",children:d.map(u=>e.jsxs(we,{className:"group rounded-2xl border-slate-200 bg-white overflow-hidden hover:shadow-md transition",children:[e.jsxs("div",{className:"h-32 bg-gradient-to-br from-violet-500 to-indigo-600 relative",children:[u.cover_image_url&&e.jsx("img",{src:u.cover_image_url,alt:"",className:"absolute inset-0 h-full w-full object-cover"}),e.jsxs("div",{className:"absolute top-3 left-3 flex gap-2",children:[e.jsx(Be,{className:u.status==="published"?"bg-emerald-500":u.status==="completed"?"bg-slate-500":u.status==="cancelled"?"bg-rose-500":"bg-amber-500",children:u.status}),u.related_pillar&&e.jsx(Be,{variant:"secondary",className:"bg-white/90 text-slate-800 capitalize",children:u.related_pillar})]})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("button",{onClick:()=>s(`/attract/events/${u.id}`),className:"text-left block w-full",children:[e.jsx("div",{className:"text-[15.5px] font-semibold text-slate-900 line-clamp-1",children:u.title}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-0.5",children:Gs(new Date(u.starts_at),"EEE, MMM d · h:mm a")})]}),e.jsxs("div",{className:"flex items-center gap-3 text-[12px] text-slate-500 mt-3",children:[u.format==="virtual"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Wr,{className:"h-3.5 w-3.5"})," Virtual"]}):u.format==="hybrid"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Wr,{className:"h-3.5 w-3.5"})," Hybrid"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ni,{className:"h-3.5 w-3.5"})," ",u.location||"In person"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3.5 w-3.5"})," ",u.registration_count,u.capacity?` / ${u.capacity}`:""]})]}),e.jsxs("div",{className:"flex items-center justify-between mt-4",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(U,{variant:"ghost",size:"sm",className:"h-8 rounded-full text-slate-500",onClick:()=>r.mutate(u.id),children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1"})," Duplicate"]}),u.status==="published"&&u.public_slug&&e.jsxs(U,{variant:"ghost",size:"sm",className:"h-8 rounded-full text-slate-500",onClick:()=>{navigator.clipboard.writeText(n8e(u.public_slug)),re.success("Registration link copied")},children:[e.jsx(Sr,{className:"h-3.5 w-3.5 mr-1"})," Link"]})]}),e.jsx(U,{variant:"ghost",size:"sm",className:"h-8 rounded-full text-rose-600 hover:bg-rose-50",onClick:async()=>{await Yi("Delete this event?")&&a.mutate(u.id)},children:e.jsx(In,{className:"h-3.5 w-3.5"})})]})]})]},u.id))})})]})]})}const tU=["attract-kits"],eZ=s=>["attract-kit-items",s],tZ=s=>["attract-kit-shares",s??"all"],Fdr=s=>["attract-kit-events",s??"all"],zdr=["attract-kit-templates"];function pat(){const{user:s}=vs(),t=Qt(),n=ct({queryKey:[...tU,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await q.from("attract_resource_kits").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=yt({mutationFn:async o=>{if(!s)throw new Error("not authenticated");const{data:c,error:d}=await q.from("attract_resource_kits").insert({user_id:s.id,title:o.title||"Untitled Kit",...o}).select("*").single();if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:tU})}),a=yt({mutationFn:async({id:o,patch:c})=>{const{data:d,error:u}=await q.from("attract_resource_kits").update(c).eq("id",o).select("*").single();if(u)throw u;return d},onSuccess:()=>t.invalidateQueries({queryKey:tU})}),i=yt({mutationFn:async o=>{const{error:c}=await q.from("attract_resource_kits").delete().eq("id",o);if(c)throw c},onSuccess:()=>t.invalidateQueries({queryKey:tU})}),l=yt({mutationFn:async o=>{const{data:c,error:d}=await q.rpc("duplicate_attract_kit",{_kit_id:o});if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:tU})});return{kits:n.data??[],isLoading:n.isLoading,create:r,update:a,remove:i,duplicate:l}}function Frs(s){return ct({queryKey:["attract-kit",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_resource_kits").select("*").eq("id",s).single();if(n)throw n;return t}})}function Bdr(s){const t=Qt(),n=ct({queryKey:eZ(s??""),enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await q.from("attract_resource_kit_items").select("*").eq("kit_id",s).order("sort_order");if(c)throw c;return o??[]}}),r=yt({mutationFn:async o=>{var u;const{data:c,error:d}=await q.from("attract_resource_kit_items").insert({kit_id:s,type:"text",title:"New item",sort_order:((u=n.data)==null?void 0:u.length)??0,...o}).select("*").single();if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:eZ(s??"")})}),a=yt({mutationFn:async({id:o,patch:c})=>{const{error:d}=await q.from("attract_resource_kit_items").update(c).eq("id",o);if(d)throw d},onSuccess:()=>t.invalidateQueries({queryKey:eZ(s??"")})}),i=yt({mutationFn:async o=>{const{error:c}=await q.from("attract_resource_kit_items").delete().eq("id",o);if(c)throw c},onSuccess:()=>t.invalidateQueries({queryKey:eZ(s??"")})}),l=yt({mutationFn:async o=>{await Promise.all(o.map((c,d)=>q.from("attract_resource_kit_items").update({sort_order:d}).eq("id",c)))},onSuccess:()=>t.invalidateQueries({queryKey:eZ(s??"")})});return{items:n.data??[],isLoading:n.isLoading,add:r,update:a,remove:i,reorder:l}}function zrs(s){const{user:t}=vs(),n=Qt(),r=ct({queryKey:tZ(s),enabled:!!t,queryFn:async()=>{let l=q.from("attract_kit_shares").select("*").order("created_at",{ascending:!1});s&&(l=l.eq("kit_id",s));const{data:o,error:c}=await l;if(c)throw c;return o??[]}}),a=yt({mutationFn:async l=>{if(!t)throw new Error("not authenticated");const{data:o,error:c}=await q.from("attract_kit_shares").insert({owner_user_id:t.id,...l}).select("*").single();if(c)throw c;return o},onSuccess:l=>{var o;n.invalidateQueries({queryKey:tZ(s)}),n.invalidateQueries({queryKey:tZ()});try{(o=navigator.clipboard)==null||o.writeText(Brs(l.share_token)),re.success("Share link created and copied")}catch{re.success("Share link created")}},onError:l=>re.error((l==null?void 0:l.message)||"Could not create share link")}),i=yt({mutationFn:async l=>{const{error:o}=await q.from("attract_kit_shares").update({status:"revoked"}).eq("id",l);if(o)throw o},onSuccess:()=>{n.invalidateQueries({queryKey:tZ(s)}),n.invalidateQueries({queryKey:tZ()}),re.success("Link revoked")},onError:l=>re.error((l==null?void 0:l.message)||"Could not revoke link")});return{shares:r.data??[],isLoading:r.isLoading,create:a,revoke:i}}function Udr(s){return ct({queryKey:Fdr(s),queryFn:async()=>{let t=q.from("attract_kit_events").select("*").order("created_at",{ascending:!1}).limit(500);s&&(t=t.eq("kit_id",s));const{data:n,error:r}=await t;if(r)throw r;return n??[]}})}function qdr(){return ct({queryKey:zdr,queryFn:async()=>{const{data:s,error:t}=await q.from("attract_kit_templates").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s??[]}})}function $dr(){const s=Qt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.rpc("clone_attract_kit_template",{_template_id:t});if(r)throw r;return n},onSuccess:()=>s.invalidateQueries({queryKey:tU})})}function Brs(s){return`${typeof window<"u"?window.location.origin:""}/attract-kit/${s}`}const Vdr=[{key:"coffee",label:"Coffee & Conversation"},{key:"roundtable",label:"Roundtable"},{key:"mastermind",label:"Mastermind"},{key:"workshop",label:"Workshop / Webinar"},{key:"dinner",label:"Dinner / Happy Hour"},{key:"networking",label:"Networking Event"},{key:"custom",label:"Custom"}];function s3t(){const{eventId:s}=Di(),t=Wn(),[n]=fc(),r=n.get("type"),a=!!s,{data:i}=mat(s),{data:l=[]}=Ars(),{kits:o}=pat(),c=Qcr(),d=Ers(),[u,h]=j.useState({title:"",description:"",event_type_key:r||"coffee",intended_audience:"",related_pillar:"connect",starts_at:new Date(Date.now()+7*864e5).toISOString().slice(0,16),ends_at:"",timezone:"America/New_York",format:"in_person",location:"",address:"",virtual_url:"",capacity:"",waitlist_enabled:!0,host_name:"",cohosts:[],agenda:[],learning_outcomes:[],registration_questions:[],confirmation_message:"",resource_kit_id:null,kit_delivery_trigger:"after_attendance",followup_hours:48});j.useEffect(()=>{i&&h({...i,starts_at:i.starts_at?i.starts_at.slice(0,16):"",ends_at:i.ends_at?i.ends_at.slice(0,16):"",capacity:i.capacity??"",cohosts:i.cohosts||[],agenda:i.agenda||[],learning_outcomes:i.learning_outcomes||[],registration_questions:i.registration_questions||[]})},[i]);const m=v=>h(b=>({...b,...v})),p=j.useMemo(()=>l.slice(0,4),[l]),f=v=>{m({title:v.title,description:v.description,event_type_key:v.event_type_key,related_pillar:v.related_pillar,intended_audience:v.intended_audience,agenda:v.suggested_agenda||[],learning_outcomes:v.suggested_outcomes||[],registration_questions:v.suggested_questions||[],confirmation_message:v.suggested_confirmation}),re.success(`Loaded "${v.title}"`)},x=async(v={})=>{const b={...u,starts_at:u.starts_at?new Date(u.starts_at).toISOString():new Date().toISOString(),ends_at:u.ends_at?new Date(u.ends_at).toISOString():null,capacity:u.capacity===""?null:Number(u.capacity),status:v.publish?"published":u.status||"draft"};if(a)await d.mutateAsync({id:s,patch:b}),re.success(v.publish?"Published":"Saved");else{const N=await c.mutateAsync(b);re.success(v.publish?"Event published":"Draft saved"),t(`/attract/events/${N.id}${v.publish?"":"/edit"}`,{replace:!0})}},y=i!=null&&i.public_slug?n8e(i.public_slug):null;return e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(U,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>t("/attract/toolkit/events"),children:[e.jsx(Aa,{className:"h-4 w-4 mr-2"})," All events"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[y&&e.jsxs(U,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(y),re.success("Registration link copied")},children:[e.jsx(Rc,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]}),e.jsxs(U,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>x(),children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"})," Save draft"]}),e.jsxs(U,{size:"sm",className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>x({publish:!0}),children:[e.jsx(pv,{className:"h-4 w-4 mr-2"})," ",(i==null?void 0:i.status)==="published"?"Update published":"Publish"]})]})]}),!a&&p.length>0&&e.jsxs(we,{className:"p-5 rounded-2xl border-violet-200 bg-gradient-to-br from-violet-50 to-indigo-50",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(cn,{className:"h-4 w-4 text-violet-600"}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:"Start from a premium template"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:p.map(v=>e.jsxs("button",{onClick:()=>f(v),className:"text-left rounded-xl bg-white/70 border border-white p-3 hover:bg-white transition",children:[e.jsx("div",{className:"text-[13.5px] font-semibold text-slate-900",children:v.title}),e.jsx("div",{className:"text-[12px] text-slate-600 line-clamp-2 mt-0.5",children:v.description})]},v.id))})]}),e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 1"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Event basics"}),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(te,{children:"Title"}),e.jsx(xe,{value:u.title,onChange:v=>m({title:v.target.value}),placeholder:"Coffee & Systems Roundtable"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Event type"}),e.jsxs(Ns,{value:u.event_type_key,onValueChange:v=>m({event_type_key:v}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:Vdr.map(v=>e.jsx(et,{value:v.key,children:v.label},v.key))})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Related pillar"}),e.jsxs(Ns,{value:u.related_pillar||"connect",onValueChange:v=>m({related_pillar:v}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"produce",children:"Produce"}),e.jsx(et,{value:"influence",children:"Influence"}),e.jsx(et,{value:"provide",children:"Provide"}),e.jsx(et,{value:"connect",children:"Connect"})]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(te,{children:"Intended audience"}),e.jsx(xe,{value:u.intended_audience||"",onChange:v=>m({intended_audience:v.target.value}),placeholder:"Producing agents 1–5 years in"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(te,{children:"Description"}),e.jsx(Fs,{rows:4,value:u.description||"",onChange:v=>m({description:v.target.value}),placeholder:"What is this event and why does it matter?"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Starts at"}),e.jsx(xe,{type:"datetime-local",value:u.starts_at||"",onChange:v=>m({starts_at:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Ends at"}),e.jsx(xe,{type:"datetime-local",value:u.ends_at||"",onChange:v=>m({ends_at:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Time zone"}),e.jsxs(Ns,{value:u.timezone||"America/New_York",onValueChange:v=>m({timezone:v}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:["America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Phoenix"].map(v=>e.jsx(et,{value:v,children:v},v))})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Format"}),e.jsxs(Ns,{value:u.format,onValueChange:v=>m({format:v}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"in_person",children:"In person"}),e.jsx(et,{value:"virtual",children:"Virtual"}),e.jsx(et,{value:"hybrid",children:"Hybrid"})]})]})]}),u.format!=="virtual"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(te,{children:"Venue / location name"}),e.jsx(xe,{value:u.location||"",onChange:v=>m({location:v.target.value}),placeholder:"Rise Coffee — Downtown"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Address"}),e.jsx(xe,{value:u.address||"",onChange:v=>m({address:v.target.value}),placeholder:"123 Main St, City, ST"})]})]}),u.format!=="in_person"&&e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(te,{children:"Virtual meeting URL"}),e.jsx(xe,{value:u.virtual_url||"",onChange:v=>m({virtual_url:v.target.value}),placeholder:"https://zoom.us/…"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Capacity (optional)"}),e.jsx(xe,{type:"number",value:u.capacity,onChange:v=>m({capacity:v.target.value}),placeholder:"No limit"})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-6",children:[e.jsx(wn,{checked:u.waitlist_enabled,onCheckedChange:v=>m({waitlist_enabled:v}),id:"wl"}),e.jsx(te,{htmlFor:"wl",className:"cursor-pointer",children:"Allow waitlist if full"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Host name (as shown publicly)"}),e.jsx(xe,{value:u.host_name||"",onChange:v=>m({host_name:v.target.value}),placeholder:"Jeremy from LevelUp"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Cover image URL"}),e.jsx(xe,{value:u.cover_image_url||"",onChange:v=>m({cover_image_url:v.target.value}),placeholder:"https://…"})]})]})]}),e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 2"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Experience & agenda"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(te,{children:"Agenda"}),e.jsxs(U,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>m({agenda:[...u.agenda||[],{time:"",item:""}]}),children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1"})," Add item"]})]}),e.jsxs("div",{className:"space-y-2",children:[(u.agenda||[]).map((v,b)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{className:"w-24",value:v.time||"",onChange:N=>{const S=[...u.agenda];S[b]={...S[b],time:N.target.value},m({agenda:S})},placeholder:"0:00"}),e.jsx(xe,{value:v.item||"",onChange:N=>{const S=[...u.agenda];S[b]={...S[b],item:N.target.value},m({agenda:S})},placeholder:"What happens here"}),e.jsx(U,{size:"icon",variant:"ghost",onClick:()=>m({agenda:u.agenda.filter((N,S)=>S!==b)}),children:e.jsx(er,{className:"h-4 w-4"})})]},b)),(u.agenda||[]).length===0&&e.jsx("div",{className:"text-[12px] text-slate-400",children:"Add each moment of the event so attendees know what to expect."})]})]}),e.jsx(hc,{}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(te,{children:"What attendees will receive"}),e.jsxs(U,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>m({learning_outcomes:[...u.learning_outcomes||[],""]}),children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1"})," Add outcome"]})]}),e.jsx("div",{className:"space-y-2",children:(u.learning_outcomes||[]).map((v,b)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:v,onChange:N=>{const S=[...u.learning_outcomes];S[b]=N.target.value,m({learning_outcomes:S})},placeholder:"One clear, honest outcome"}),e.jsx(U,{size:"icon",variant:"ghost",onClick:()=>m({learning_outcomes:u.learning_outcomes.filter((N,S)=>S!==b)}),children:e.jsx(er,{className:"h-4 w-4"})})]},b))})]})]})]}),e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 3"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Registration page"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(te,{children:"Registration questions"}),e.jsxs(U,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>m({registration_questions:[...u.registration_questions||[],{key:`q${(u.registration_questions||[]).length+1}`,label:"",type:"text"}]}),children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1"})," Add question"]})]}),e.jsx("div",{className:"space-y-2",children:(u.registration_questions||[]).map((v,b)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(xe,{className:"flex-1",value:v.label,onChange:N=>{const S=[...u.registration_questions];S[b]={...S[b],label:N.target.value,key:v.key||`q${b+1}`},m({registration_questions:S})},placeholder:"Question shown to registrants"}),e.jsxs(Ns,{value:v.type,onValueChange:N=>{const S=[...u.registration_questions];S[b]={...S[b],type:N},m({registration_questions:S})},children:[e.jsx(ws,{className:"w-32",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"text",children:"Short text"}),e.jsx(et,{value:"long",children:"Long text"})]})]}),e.jsx(U,{size:"icon",variant:"ghost",onClick:()=>m({registration_questions:u.registration_questions.filter((N,S)=>S!==b)}),children:e.jsx(er,{className:"h-4 w-4"})})]},b))})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Confirmation message (shown after registration)"}),e.jsx(Fs,{rows:3,value:u.confirmation_message||"",onChange:v=>m({confirmation_message:v.target.value}),placeholder:"You are in — come with one honest question."})]})]})]}),e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 4"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Resource Kit & 48-hour follow-up"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Attach a Resource Kit"}),e.jsxs(Ns,{value:u.resource_kit_id||"none",onValueChange:v=>m({resource_kit_id:v==="none"?null:v}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"None"})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"None"}),(o||[]).map(v=>e.jsx(et,{value:v.id,children:v.title},v.id))]})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Deliver kit"}),e.jsxs(Ns,{value:u.kit_delivery_trigger||"after_attendance",onValueChange:v=>m({kit_delivery_trigger:v}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"on_registration",children:"On registration"}),e.jsx(et,{value:"on_confirmation",children:"On confirmation"}),e.jsx(et,{value:"on_check_in",children:"At check-in"}),e.jsx(et,{value:"after_attendance",children:"After attendance"}),e.jsx(et,{value:"manual",children:"Only manually"})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Default follow-up window (hours)"}),e.jsx(xe,{type:"number",value:u.followup_hours??48,onChange:v=>m({followup_hours:Number(v.target.value)})})]})]}),!u.resource_kit_id&&e.jsx("div",{className:"text-[12px] text-amber-700 bg-amber-50 border border-amber-200 rounded-lg p-3 mt-4",children:"Tip: attach a Resource Kit so attendees leave with something valuable — and so follow-ups have a natural reason."})]}),e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 5"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-3",children:"Review & publish"}),e.jsxs("div",{className:"text-[13px] text-slate-600 leading-relaxed",children:["Publishing generates a premium public registration page at"," ",e.jsxs("code",{className:"bg-slate-100 px-1.5 py-0.5 rounded text-slate-800",children:["/attract-event/",(i==null?void 0:i.public_slug)||""]})," ","and enables the personal invitation flow. You can unpublish or cancel at any time."]}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[(!u.title||!u.starts_at)&&e.jsx(Be,{variant:"secondary",className:"bg-rose-50 text-rose-700 border-rose-200",children:"Add title and start time"}),(u.agenda||[]).length===0&&e.jsx(Be,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No agenda yet"}),(u.learning_outcomes||[]).length===0&&e.jsx(Be,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No stated outcomes"}),!u.resource_kit_id&&e.jsx(Be,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No Resource Kit attached"})]}),e.jsxs("div",{className:"flex justify-end gap-2 mt-5",children:[e.jsxs(U,{variant:"outline",className:"rounded-full",onClick:()=>x(),children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"})," Save draft"]}),e.jsxs(U,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>x({publish:!0}),children:[e.jsx(pv,{className:"h-4 w-4 mr-2"})," Publish"]})]})]})]})}const h3e=s=>s?[s.first_name,s.last_name].filter(Boolean).join(" "):"";function Hdr(){const{eventId:s}=Di(),t=Wn(),{data:n}=mat(s),{data:r=[]}=Crs(s),{data:a=[]}=Zcr(s),{data:i=[]}=Xcr(s),{agents:l}=EE(),{data:o=[]}=Ars(),c=Trs(),d=edr(),u=tdr(),h=Ers(),m=j.useMemo(()=>{const x=r.length,y=r.filter(I=>I.status==="registered"||I.status==="confirmed").length,v=r.filter(I=>I.status==="attended").length,b=r.filter(I=>I.status==="no_show").length,N=r.filter(I=>I.status==="waitlisted").length,S=y+v+b,A=S>0?Math.round(v/S*100):0,T=a.length>0?Math.round(a.filter(I=>I.viewed_at).length/a.length*100):0,L=r.filter(I=>I.followup_status==="done").length,M=v>0?Math.round(L/v*100):0;return{total:x,registered:y,attended:v,noShow:b,waitlist:N,attendRate:A,invView:T,followed:L,followedRate:M}},[r,a]);if(!n)return e.jsx("div",{className:"p-8 text-slate-500",children:"Loading…"});const p=n.public_slug?n8e(n.public_slug):null,f=()=>{const x=new Blob([Mrs(n)],{type:"text/calendar"}),y=URL.createObjectURL(x),v=document.createElement("a");v.href=y,v.download=`${n.public_slug||"event"}.ics`,v.click(),URL.revokeObjectURL(y)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs(U,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>t("/attract/toolkit/events"),children:[e.jsx(Aa,{className:"h-4 w-4 mr-2"})," All events"]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(U,{variant:"outline",size:"sm",className:"rounded-full",onClick:f,children:[e.jsx(pi,{className:"h-3.5 w-3.5 mr-2"})," ICS"]}),p&&e.jsxs(U,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(p),re.success("Link copied")},children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]}),p&&e.jsx(U,{variant:"outline",size:"sm",className:"rounded-full",asChild:!0,children:e.jsxs("a",{href:p,target:"_blank",rel:"noreferrer",children:[e.jsx(Sr,{className:"h-3.5 w-3.5 mr-2"})," Preview page"]})}),e.jsxs(U,{size:"sm",className:"rounded-full",onClick:()=>t(`/attract/events/${n.id}/checkin`),children:[e.jsx(Sf,{className:"h-3.5 w-3.5 mr-2"})," Check-in mode"]}),e.jsx(U,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>t(`/attract/events/${n.id}/edit`),children:"Edit"})]})]}),e.jsx(we,{className:"p-6 rounded-2xl border-slate-200 bg-gradient-to-br from-slate-900 to-slate-800 text-white",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 mb-2",children:[e.jsx(Be,{className:n.status==="published"?"bg-emerald-500":n.status==="completed"?"bg-slate-500":n.status==="cancelled"?"bg-rose-500":"bg-amber-500",children:n.status}),n.related_pillar&&e.jsx(Be,{variant:"secondary",className:"bg-white/10 border-white/10 text-white capitalize",children:n.related_pillar}),n.event_type_key&&e.jsx(Be,{variant:"secondary",className:"bg-white/10 border-white/10 text-white capitalize",children:n.event_type_key.replace("_"," ")})]}),e.jsx("div",{className:"text-2xl md:text-3xl font-semibold",children:n.title}),e.jsxs("div",{className:"text-white/70 mt-1 flex items-center gap-4 flex-wrap",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(pa,{className:"h-4 w-4"})," ",Gs(new Date(n.starts_at),"EEE, MMM d · h:mm a")]}),n.format==="virtual"?e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Wr,{className:"h-4 w-4"})," Virtual"]}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ni,{className:"h-4 w-4"})," ",n.location||"In person"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Bn,{className:"h-4 w-4"})," ",n.registration_count," registered",n.capacity?` / ${n.capacity}`:""]})]})]}),n.status==="draft"&&e.jsx(U,{className:"rounded-full bg-white text-slate-900 hover:bg-white/90",onClick:async()=>{await h.mutateAsync({id:n.id,patch:{status:"published"}}),re.success("Published")},children:"Publish now"}),n.status==="published"&&new Date(n.starts_at){await h.mutateAsync({id:n.id,patch:{status:"completed"}}),re.success("Marked completed")},children:"Mark completed"})]})}),e.jsxs(oa,{defaultValue:"overview",children:[e.jsxs(la,{className:"rounded-full bg-white border border-slate-200 flex-wrap h-auto",children:[e.jsx(Kt,{value:"overview",className:"rounded-full",children:"Overview"}),e.jsxs(Kt,{value:"invitations",className:"rounded-full",children:["Invitations (",a.length,")"]}),e.jsxs(Kt,{value:"registrations",className:"rounded-full",children:["Registrations (",r.length,")"]}),e.jsxs(Kt,{value:"notes",className:"rounded-full",children:["Notes (",i.length,")"]}),e.jsx(Kt,{value:"kit",className:"rounded-full",children:"Resource Kit"}),e.jsx(Kt,{value:"followup",className:"rounded-full",children:"48-hour follow-up"}),e.jsx(Kt,{value:"analytics",className:"rounded-full",children:"Analytics"})]}),e.jsxs(Zt,{value:"overview",className:"mt-5",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-6",children:[e.jsx(h2,{icon:Bn,label:"Registered",value:m.registered+m.attended}),e.jsx(h2,{icon:Xr,label:"Attended",value:m.attended}),e.jsx(h2,{icon:Cl,label:"Attendance rate",value:`${m.attendRate}%`}),e.jsx(h2,{icon:cy,label:"Follow-up completion",value:`${m.followedRate}%`})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200 bg-white lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Agenda"}),(n.agenda||[]).length===0?e.jsx("div",{className:"text-[13px] text-slate-400",children:"No agenda yet"}):e.jsx("ul",{className:"space-y-2",children:n.agenda.map((x,y)=>e.jsxs("li",{className:"flex gap-3 text-[14px]",children:[e.jsx("span",{className:"text-slate-500 tabular-nums w-16 shrink-0",children:x.time||""}),e.jsx("span",{className:"text-slate-800",children:x.item})]},y))}),(n.learning_outcomes||[]).length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mt-6 mb-2",children:"What attendees receive"}),e.jsx("ul",{className:"space-y-1.5",children:n.learning_outcomes.map((x,y)=>e.jsxs("li",{className:"text-[13.5px] text-slate-700 flex gap-2",children:[e.jsx(Xr,{className:"h-4 w-4 text-emerald-600 shrink-0 mt-0.5"})," ",x]},y))})]})]}),e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Share"}),p?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[12px] text-slate-500 mb-1",children:"Registration page"}),e.jsx("div",{className:"text-[12.5px] font-mono bg-slate-50 border border-slate-200 rounded-lg p-2 break-all",children:p}),e.jsxs(U,{size:"sm",variant:"outline",className:"rounded-full mt-2 w-full",onClick:()=>{navigator.clipboard.writeText(p),re.success("Copied")},children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]})]}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"Publish the event to generate a shareable registration link."}),n.check_in_token&&e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"text-[12px] text-slate-500 mb-1",children:"Check-in mode"}),e.jsxs(U,{size:"sm",variant:"outline",className:"rounded-full w-full",onClick:()=>t(`/attract/events/${n.id}/checkin`),children:[e.jsx(Sf,{className:"h-3.5 w-3.5 mr-2"})," Open check-in"]})]})]})]})]}),e.jsx(Zt,{value:"invitations",className:"mt-5",children:e.jsx(Gdr,{eventId:n.id,eventSlug:n.public_slug,agents:l,invitations:a,templates:o,onCreate:u.mutate})}),e.jsx(Zt,{value:"registrations",className:"mt-5",children:e.jsx(Wdr,{eventId:n.id,attendees:r,onUpsert:c.mutate,checkInToken:n.check_in_token})}),e.jsx(Zt,{value:"notes",className:"mt-5",children:e.jsx(Kdr,{eventId:n.id,attendees:r,notes:i,onCreate:d.mutate})}),e.jsx(Zt,{value:"kit",className:"mt-5",children:e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Resource Kit"}),n.resource_kit_id?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:"A Resource Kit is attached to this event."}),e.jsxs("div",{className:"text-[13px] text-slate-600 mt-1",children:["Deliver trigger: ",e.jsx("span",{className:"font-medium capitalize",children:(n.kit_delivery_trigger||"after_attendance").replace(/_/g," ")})]}),e.jsx(U,{variant:"outline",className:"rounded-full mt-4",onClick:()=>t(`/attract/toolkit/kits/${n.resource_kit_id}/analytics`),children:"Open kit analytics"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[15px] text-slate-700",children:"No kit attached yet. Attach one so attendees leave with something valuable."}),e.jsxs("div",{className:"flex gap-2 mt-4",children:[e.jsx(U,{className:"rounded-full",onClick:()=>t(`/attract/events/${n.id}/edit`),children:"Attach a kit"}),e.jsx(U,{variant:"outline",className:"rounded-full",onClick:()=>t("/attract/toolkit/kits/new"),children:"Create a new kit"})]})]})]})}),e.jsx(Zt,{value:"followup",className:"mt-5",children:e.jsx(Ydr,{eventId:n.id,attendees:r,onUpsert:c.mutate})}),e.jsxs(Zt,{value:"analytics",className:"mt-5",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(h2,{icon:$r,label:"Invitations sent",value:a.length}),e.jsx(h2,{icon:Sr,label:"Invitation view rate",value:`${m.invView}%`}),e.jsx(h2,{icon:Bn,label:"Registered",value:m.registered+m.attended}),e.jsx(h2,{icon:Xr,label:"Attended",value:m.attended}),e.jsx(h2,{icon:Cl,label:"Attendance rate",value:`${m.attendRate}%`}),e.jsx(h2,{icon:cy,label:"Follow-up complete (48h)",value:`${m.followedRate}%`}),e.jsx(h2,{icon:EA,label:"Notes captured",value:i.length}),e.jsx(h2,{icon:zl,label:"Meetings requested",value:r.filter(x=>x.meeting_requested).length})]}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-3",children:["Where attribution is uncertain, we label movement as ",e.jsx("em",{children:"influenced"})," rather than caused."]})]})]})]})}function h2({icon:s,label:t,value:n}){return e.jsxs(we,{className:"p-4 rounded-2xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"flex items-center gap-2 text-slate-500 text-[12px]",children:[e.jsx(s,{className:"h-3.5 w-3.5"})," ",t]}),e.jsx("div",{className:"text-[24px] font-semibold tabular-nums text-slate-900 mt-2",children:n})]})}function Gdr({eventId:s,eventSlug:t,agents:n,invitations:r,templates:a,onCreate:i}){const[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,p]=j.useState("email"),[f,x]=j.useState(""),y=a==null?void 0:a[0],v=()=>{if(!y)return;const N=m==="sms"?y.suggested_invitation_sms:m==="dm"?y.suggested_invitation_dm:y.suggested_invitation_email,S=t?`${window.location.origin}/attract-event/${t}`:"";x((N||"").replaceAll("{{first_name}}",(c||"friend").split(" ")[0]).replaceAll("{{link}}",S).replaceAll("{{date}}",""))},b=()=>{if(!c||m==="email"&&!u){re.error("Add a name and email");return}const N=n.find(S=>S.id===l);i({event_id:s,agent_id:l||null,recipient_name:c||h3e(N),recipient_email:u||(N==null?void 0:N.email),channel:m,message_body:f,status:"sent"}),d(""),h(""),x(""),o(""),re.success("Invitation logged")};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200 bg-white lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Log a personal invitation"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Attract agent (optional)"}),e.jsxs(Ns,{value:l||"none",onValueChange:N=>{o(N==="none"?"":N);const S=n.find(A=>A.id===N);S&&(d(h3e(S)),h(S.email||""))},children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Pick an agent"})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"Guest (not in pipeline)"}),n.map(N=>e.jsx(et,{value:N.id,children:h3e(N)},N.id))]})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Channel"}),e.jsxs(Ns,{value:m,onValueChange:p,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"email",children:"Email"}),e.jsx(et,{value:"sms",children:"Text message"}),e.jsx(et,{value:"dm",children:"DM"}),e.jsx(et,{value:"call",children:"Phone call"}),e.jsx(et,{value:"in_person",children:"In person"})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Recipient name"}),e.jsx(xe,{value:c,onChange:N=>d(N.target.value)})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Recipient email"}),e.jsx(xe,{value:u,onChange:N=>h(N.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(te,{children:"Message"}),y&&e.jsxs(U,{size:"sm",variant:"ghost",className:"rounded-full text-xs",onClick:v,children:[e.jsx(cn,{className:"h-3 w-3 mr-1"})," Draft from template"]})]}),e.jsx(Fs,{rows:5,value:f,onChange:N=>x(N.target.value),placeholder:"Write it like you would to a friend."})]})]}),e.jsxs("div",{className:"flex justify-between items-center mt-4",children:[e.jsx("div",{className:"text-[12px] text-slate-500",children:"Never auto-sent. This just logs that you invited them."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{variant:"outline",className:"rounded-full",onClick:()=>{f&&(navigator.clipboard.writeText(f),re.success("Copied"))},children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-2"})," Copy message"]}),e.jsxs(U,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:b,children:[e.jsx($r,{className:"h-3.5 w-3.5 mr-2"})," Log invitation"]})]})]})]}),e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Recent invitations"}),r.length===0?e.jsx("div",{className:"text-[13px] text-slate-400",children:"None yet."}):e.jsx("div",{className:"space-y-2 max-h-[520px] overflow-auto",children:r.map(N=>e.jsxs("div",{className:"rounded-xl border border-slate-100 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-[13px] font-medium text-slate-900",children:N.recipient_name||N.recipient_email}),e.jsx(Be,{variant:"secondary",className:"capitalize",children:N.status})]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:["via ",N.channel," · ",Nd(new Date(N.sent_at))," ago",N.view_count>0?` · viewed ${N.view_count}×`:""]})]},N.id))})]})]})}function Wdr({eventId:s,attendees:t,onUpsert:n,checkInToken:r}){const[a,i]=j.useState(""),[l,o]=j.useState(""),c=()=>{if(!a){re.error("Add a name");return}n({event_id:s,guest_name:a,guest_email:l||null,status:"attended",checked_in_at:new Date().toISOString(),invitation_source:"walk_in"}),i(""),o(""),re.success("Walk-in added")};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs(we,{className:"p-4 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Add a walk-in guest"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-2",children:[e.jsx(xe,{placeholder:"Name",value:a,onChange:d=>i(d.target.value)}),e.jsx(xe,{placeholder:"Email (optional)",value:l,onChange:d=>o(d.target.value)}),e.jsxs(U,{className:"rounded-full md:col-span-2",onClick:c,children:[e.jsx(zl,{className:"h-4 w-4 mr-2"})," Add & check in"]})]})]}),e.jsx(we,{className:"rounded-2xl border-slate-200 bg-white overflow-hidden",children:t.length===0?e.jsx("div",{className:"p-8 text-center text-slate-400",children:"No registrations yet"}):e.jsx("div",{className:"divide-y divide-slate-100",children:t.map(d=>e.jsxs("div",{className:"p-4 flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[14px] font-semibold text-slate-900",children:d.guest_name||h3e(d.attract_agents)||d.guest_email}),e.jsxs("div",{className:"text-[12px] text-slate-500",children:[d.guest_email," · ",d.invitation_source||"direct"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Be,{variant:"secondary",className:"capitalize",children:d.status}),e.jsxs(Ns,{value:d.status,onValueChange:u=>n({id:d.id,event_id:s,status:u,checked_in_at:u==="attended"&&!d.checked_in_at?new Date().toISOString():d.checked_in_at}),children:[e.jsx(ws,{className:"h-8 w-40 text-xs",children:e.jsx(ks,{})}),e.jsx(js,{children:["invited","registered","confirmed","waitlisted","attended","no_show","cancelled"].map(u=>e.jsx(et,{value:u,className:"text-xs",children:u.replace("_"," ")},u))})]}),r&&d.personalized_token&&e.jsx(U,{variant:"ghost",size:"sm",className:"rounded-full text-xs",onClick:()=>{navigator.clipboard.writeText(ndr(r,d.personalized_token)),re.success("Check-in link copied")},children:e.jsx(Pa,{className:"h-3.5 w-3.5"})})]})]},d.id))})})]})}function Kdr({eventId:s,attendees:t,notes:n,onCreate:r}){const[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState("warm"),[u,h]=j.useState(!1),[m,p]=j.useState(""),f=()=>{if(!l.trim()){re.error("Add a note");return}const x=t.find(y=>y.id===a);r({event_id:s,attendee_id:a||null,agent_id:(x==null?void 0:x.agent_id)||null,note:l,temperature:c,recommended_next_action:m||null,wants_one_on_one:u}),o(""),i(""),p(""),h(!1),re.success("Note captured")};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200 bg-white lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Capture one honest note"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Attendee (optional)"}),e.jsxs(Ns,{value:a||"none",onValueChange:x=>i(x==="none"?"":x),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Anyone in the room"})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"General note"}),t.map(x=>e.jsx(et,{value:x.id,children:x.guest_name||x.guest_email},x.id))]})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Note"}),e.jsx(Fs,{rows:4,value:l,onChange:x=>o(x.target.value),placeholder:"One real thing they said. One thing you noticed."})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Relationship temperature"}),e.jsxs(Ns,{value:c,onValueChange:d,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:["cold","warm","hot"].map(x=>e.jsx(et,{value:x,children:x},x))})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(te,{children:"Recommended next action"}),e.jsx(xe,{value:m,onChange:x=>p(x.target.value),placeholder:"Text them the resource. Book a coffee."})]})]}),e.jsxs("label",{className:"flex items-center gap-2 text-[13px] text-slate-700",children:[e.jsx("input",{type:"checkbox",checked:u,onChange:x=>h(x.target.checked)}),"They should get a one-on-one conversation"]})]}),e.jsx("div",{className:"flex justify-end mt-4",children:e.jsxs(U,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:f,children:[e.jsx(an,{className:"h-4 w-4 mr-2"})," Save note"]})})]}),e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Notes from this event"}),n.length===0?e.jsx("div",{className:"text-[13px] text-slate-400",children:"None yet."}):e.jsx("div",{className:"space-y-3 max-h-[520px] overflow-auto",children:n.map(x=>{const y=t.find(v=>v.id===x.attendee_id);return e.jsxs("div",{className:"rounded-xl border border-slate-100 p-3",children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:(y==null?void 0:y.guest_name)||"General"}),e.jsx("div",{className:"text-[13px] text-slate-700 mt-1 whitespace-pre-wrap",children:x.note}),e.jsxs("div",{className:"flex items-center gap-2 mt-2 flex-wrap text-[11px] text-slate-500",children:[x.temperature&&e.jsx(Be,{variant:"secondary",className:"capitalize",children:x.temperature}),x.wants_one_on_one&&e.jsx(Be,{className:"bg-emerald-500",children:"Wants 1:1"}),x.recommended_next_action&&e.jsxs("span",{children:["Next: ",x.recommended_next_action]})]})]},x.id)})})]})]})}function Ydr({eventId:s,attendees:t,onUpsert:n}){const r=j.useMemo(()=>({attended_engaged:t.filter(l=>l.status==="attended"&&l.temperature==="hot"),attended_no_notes:t.filter(l=>l.status==="attended"),no_show:t.filter(l=>l.status==="no_show"),meeting_requested:t.filter(l=>l.meeting_requested),not_followed:t.filter(l=>l.status==="attended"&&l.followup_status!=="done")}),[t]),a=(l,o)=>n({id:l,event_id:s,followup_status:o}),i=({title:l,list:o,color:c})=>e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("div",{className:`h-2 w-2 rounded-full ${c}`}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:l}),e.jsxs("div",{className:"text-[12px] text-slate-500",children:["(",o.length,")"]})]}),o.length===0?e.jsx("div",{className:"text-[12px] text-slate-400",children:"Nobody here."}):e.jsx("div",{className:"space-y-2",children:o.map(d=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-xl border border-slate-100 p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:d.guest_name||d.guest_email}),e.jsxs("div",{className:"text-[11.5px] text-slate-500",children:[d.status," · followup: ",d.followup_status||"pending"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(U,{size:"sm",variant:"ghost",className:"rounded-full h-8",onClick:()=>a(d.id,"in_progress"),children:"In progress"}),e.jsx(U,{size:"sm",className:"rounded-full h-8 bg-emerald-600 hover:bg-emerald-700",onClick:()=>a(d.id,"done"),children:e.jsx(Xr,{className:"h-3 w-3"})})]})]},d.id))})]});return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(i,{title:"Attended and engaged",list:r.attended_engaged,color:"bg-emerald-500"}),e.jsx(i,{title:"Attended (no notes yet)",list:r.attended_no_notes,color:"bg-violet-500"}),e.jsx(i,{title:"Registered but no-show",list:r.no_show,color:"bg-amber-500"}),e.jsx(i,{title:"Meeting requested",list:r.meeting_requested,color:"bg-pink-500"}),e.jsx(i,{title:"Not yet followed up",list:r.not_followed,color:"bg-rose-500"})]})}var AW={},Zdr=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},Urs={},Ej={};let fat;const Xdr=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];Ej.getSymbolSize=function(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return t*4+17};Ej.getSymbolTotalCodewords=function(t){return Xdr[t]};Ej.getBCHDigit=function(s){let t=0;for(;s!==0;)t++,s>>>=1;return t};Ej.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');fat=t};Ej.isKanjiModeEnabled=function(){return typeof fat<"u"};Ej.toSJIS=function(t){return fat(t)};var r8e={};(function(s){s.L={bit:1},s.M={bit:0},s.Q={bit:3},s.H={bit:2};function t(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return s.L;case"m":case"medium":return s.M;case"q":case"quartile":return s.Q;case"h":case"high":return s.H;default:throw new Error("Unknown EC Level: "+n)}}s.isValid=function(r){return r&&typeof r.bit<"u"&&r.bit>=0&&r.bit<4},s.from=function(r,a){if(s.isValid(r))return r;try{return t(r)}catch{return a}}})(r8e);function qrs(){this.buffer=[],this.length=0}qrs.prototype={get:function(s){const t=Math.floor(s/8);return(this.buffer[t]>>>7-s%8&1)===1},put:function(s,t){for(let n=0;n>>t-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(s){const t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),s&&(this.buffer[t]|=128>>>this.length%8),this.length++}};var Qdr=qrs;function xae(s){if(!s||s<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=s,this.data=new Uint8Array(s*s),this.reservedBit=new Uint8Array(s*s)}xae.prototype.set=function(s,t,n,r){const a=s*this.size+t;this.data[a]=n,r&&(this.reservedBit[a]=!0)};xae.prototype.get=function(s,t){return this.data[s*this.size+t]};xae.prototype.xor=function(s,t,n){this.data[s*this.size+t]^=n};xae.prototype.isReserved=function(s,t){return this.reservedBit[s*this.size+t]};var Jdr=xae,$rs={};(function(s){const t=Ej.getSymbolSize;s.getRowColCoords=function(r){if(r===1)return[];const a=Math.floor(r/7)+2,i=t(r),l=i===145?26:Math.ceil((i-13)/(2*a-2))*2,o=[i-7];for(let c=1;c=0&&a<=7},s.from=function(a){return s.isValid(a)?parseInt(a,10):void 0},s.getPenaltyN1=function(a){const i=a.size;let l=0,o=0,c=0,d=null,u=null;for(let h=0;h=5&&(l+=t.N1+(o-5)),d=p,o=1),p=a.get(m,h),p===u?c++:(c>=5&&(l+=t.N1+(c-5)),u=p,c=1)}o>=5&&(l+=t.N1+(o-5)),c>=5&&(l+=t.N1+(c-5))}return l},s.getPenaltyN2=function(a){const i=a.size;let l=0;for(let o=0;o=10&&(o===1488||o===93)&&l++,c=c<<1&2047|a.get(u,d),u>=10&&(c===1488||c===93)&&l++}return l*t.N3},s.getPenaltyN4=function(a){let i=0;const l=a.data.length;for(let c=0;c=0;){const l=i[0];for(let c=0;c0){const i=new Uint8Array(this.degree);return i.set(r,a),i}return r};var tur=gat,Krs={},gL={},xat={};xat.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40};var N3={};const Yrs="[0-9]+",sur="[A-Z $%*+\\-./:]+";let Qte="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Qte=Qte.replace(/u/g,"\\u");const nur="(?:(?![A-Z0-9 $%*+\\-./:]|"+Qte+`)(?:.|[\r ]))+`;N3.KANJI=new RegExp(Qte,"g");N3.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");N3.BYTE=new RegExp(nur,"g");N3.NUMERIC=new RegExp(Yrs,"g");N3.ALPHANUMERIC=new RegExp(sur,"g");const rur=new RegExp("^"+Qte+"$"),aur=new RegExp("^"+Yrs+"$"),iur=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");N3.testKanji=function(t){return rur.test(t)};N3.testNumeric=function(t){return aur.test(t)};N3.testAlphanumeric=function(t){return iur.test(t)};(function(s){const t=xat,n=N3;s.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},s.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},s.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},s.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},s.MIXED={bit:-1},s.getCharCountIndicator=function(i,l){if(!i.ccBits)throw new Error("Invalid mode: "+i);if(!t.isValid(l))throw new Error("Invalid version: "+l);return l>=1&&l<10?i.ccBits[0]:l<27?i.ccBits[1]:i.ccBits[2]},s.getBestModeForData=function(i){return n.testNumeric(i)?s.NUMERIC:n.testAlphanumeric(i)?s.ALPHANUMERIC:n.testKanji(i)?s.KANJI:s.BYTE},s.toString=function(i){if(i&&i.id)return i.id;throw new Error("Invalid mode")},s.isValid=function(i){return i&&i.bit&&i.ccBits};function r(a){if(typeof a!="string")throw new Error("Param is not a string");switch(a.toLowerCase()){case"numeric":return s.NUMERIC;case"alphanumeric":return s.ALPHANUMERIC;case"kanji":return s.KANJI;case"byte":return s.BYTE;default:throw new Error("Unknown mode: "+a)}}s.from=function(i,l){if(s.isValid(i))return i;try{return r(i)}catch{return l}}})(gL);(function(s){const t=Ej,n=a8e,r=r8e,a=gL,i=xat,l=7973,o=t.getBCHDigit(l);function c(m,p,f){for(let x=1;x<=40;x++)if(p<=s.getCapacity(x,f,m))return x}function d(m,p){return a.getCharCountIndicator(m,p)+4}function u(m,p){let f=0;return m.forEach(function(x){const y=d(x.mode,p);f+=y+x.getBitsLength()}),f}function h(m,p){for(let f=1;f<=40;f++)if(u(m,f)<=s.getCapacity(f,p,a.MIXED))return f}s.from=function(p,f){return i.isValid(p)?parseInt(p,10):f},s.getCapacity=function(p,f,x){if(!i.isValid(p))throw new Error("Invalid QR Code version");typeof x>"u"&&(x=a.BYTE);const y=t.getSymbolTotalCodewords(p),v=n.getTotalCodewordsCount(p,f),b=(y-v)*8;if(x===a.MIXED)return b;const N=b-d(x,p);switch(x){case a.NUMERIC:return Math.floor(N/10*3);case a.ALPHANUMERIC:return Math.floor(N/11*2);case a.KANJI:return Math.floor(N/13);case a.BYTE:default:return Math.floor(N/8)}},s.getBestVersionForData=function(p,f){let x;const y=r.from(f,r.M);if(Array.isArray(p)){if(p.length>1)return h(p,y);if(p.length===0)return 1;x=p[0]}else x=p;return c(x.mode,x.getLength(),y)},s.getEncodedBits=function(p){if(!i.isValid(p)||p<7)throw new Error("Invalid QR Code version");let f=p<<12;for(;t.getBCHDigit(f)-o>=0;)f^=l<=0;)a^=Xrs<0&&(r=this.data.substr(n),a=parseInt(r,10),t.put(a,i*3+1))};var cur=KH;const dur=gL,nBe=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function YH(s){this.mode=dur.ALPHANUMERIC,this.data=s}YH.getBitsLength=function(t){return 11*Math.floor(t/2)+6*(t%2)};YH.prototype.getLength=function(){return this.data.length};YH.prototype.getBitsLength=function(){return YH.getBitsLength(this.data.length)};YH.prototype.write=function(t){let n;for(n=0;n+2<=this.data.length;n+=2){let r=nBe.indexOf(this.data[n])*45;r+=nBe.indexOf(this.data[n+1]),t.put(r,11)}this.data.length%2&&t.put(nBe.indexOf(this.data[n]),6)};var uur=YH;const hur=gL;function ZH(s){this.mode=hur.BYTE,typeof s=="string"?this.data=new TextEncoder().encode(s):this.data=new Uint8Array(s)}ZH.getBitsLength=function(t){return t*8};ZH.prototype.getLength=function(){return this.data.length};ZH.prototype.getBitsLength=function(){return ZH.getBitsLength(this.data.length)};ZH.prototype.write=function(s){for(let t=0,n=this.data.length;t=33088&&n<=40956)n-=33088;else if(n>=57408&&n<=60351)n-=49472;else throw new Error("Invalid SJIS character: "+this.data[t]+` Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),s.put(n,13)}};var gur=XH,Jrs={exports:{}};(function(s){var t={single_source_shortest_paths:function(n,r,a){var i={},l={};l[r]=0;var o=t.PriorityQueue.make();o.push(r,0);for(var c,d,u,h,m,p,f,x,y;!o.empty();){c=o.pop(),d=c.value,h=c.cost,m=n[d]||{};for(u in m)m.hasOwnProperty(u)&&(p=m[u],f=h+p,x=l[u],y=typeof l[u]>"u",(y||x>f)&&(l[u]=f,o.push(u,f),i[u]=d))}if(typeof a<"u"&&typeof l[a]>"u"){var v=["Could not find a path from ",r," to ",a,"."].join("");throw new Error(v)}return i},extract_shortest_path_from_predecessor_list:function(n,r){for(var a=[],i=r;i;)a.push(i),n[i],i=n[i];return a.reverse(),a},find_path:function(n,r,a){var i=t.single_source_shortest_paths(n,r,a);return t.extract_shortest_path_from_predecessor_list(i,a)},PriorityQueue:{make:function(n){var r=t.PriorityQueue,a={},i;n=n||{};for(i in r)r.hasOwnProperty(i)&&(a[i]=r[i]);return a.queue=[],a.sorter=n.sorter||r.default_sorter,a},default_sorter:function(n,r){return n.cost-r.cost},push:function(n,r){var a={value:n,cost:r};this.queue.push(a),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};s.exports=t})(Jrs);var xur=Jrs.exports;(function(s){const t=gL,n=cur,r=uur,a=mur,i=gur,l=N3,o=Ej,c=xur;function d(v){return unescape(encodeURIComponent(v)).length}function u(v,b,N){const S=[];let A;for(;(A=v.exec(N))!==null;)S.push({data:A[0],index:A.index,mode:b,length:A[0].length});return S}function h(v){const b=u(l.NUMERIC,t.NUMERIC,v),N=u(l.ALPHANUMERIC,t.ALPHANUMERIC,v);let S,A;return o.isKanjiModeEnabled()?(S=u(l.BYTE,t.BYTE,v),A=u(l.KANJI,t.KANJI,v)):(S=u(l.BYTE_KANJI,t.BYTE,v),A=[]),b.concat(N,S,A).sort(function(L,M){return L.index-M.index}).map(function(L){return{data:L.data,mode:L.mode,length:L.length}})}function m(v,b){switch(b){case t.NUMERIC:return n.getBitsLength(v);case t.ALPHANUMERIC:return r.getBitsLength(v);case t.KANJI:return i.getBitsLength(v);case t.BYTE:return a.getBitsLength(v)}}function p(v){return v.reduce(function(b,N){const S=b.length-1>=0?b[b.length-1]:null;return S&&S.mode===N.mode?(b[b.length-1].data+=N.data,b):(b.push(N),b)},[])}function f(v){const b=[];for(let N=0;N=0&&o<=6&&(c===0||c===6)||c>=0&&c<=6&&(o===0||o===6)||o>=2&&o<=4&&c>=2&&c<=4?s.set(i+o,l+c,!0,!0):s.set(i+o,l+c,!1,!0))}}function Sur(s){const t=s.size;for(let n=8;n>o&1)===1,s.set(a,i,l,!0),s.set(i,a,l,!0)}function iBe(s,t,n){const r=s.size,a=jur.getEncodedBits(t,n);let i,l;for(i=0;i<15;i++)l=(a>>i&1)===1,i<6?s.set(i,8,l,!0):i<8?s.set(i+1,8,l,!0):s.set(r-15+i,8,l,!0),i<8?s.set(8,r-i-1,l,!0):i<9?s.set(8,15-i-1+1,l,!0):s.set(8,15-i-1,l,!0);s.set(r-8,8,1,!0)}function Eur(s,t){const n=s.size;let r=-1,a=n-1,i=7,l=0;for(let o=n-1;o>0;o-=2)for(o===6&&o--;;){for(let c=0;c<2;c++)if(!s.isReserved(a,o-c)){let d=!1;l>>i&1)===1),s.set(a,o-c,d),i--,i===-1&&(l++,i=7)}if(a+=r,a<0||n<=a){a-=r,r=-r;break}}}function Tur(s,t,n){const r=new yur;n.forEach(function(c){r.put(c.mode.bit,4),r.put(c.getLength(),Nur.getCharCountIndicator(c.mode,s)),c.write(r)});const a=o8e.getSymbolTotalCodewords(s),i=tYe.getTotalCodewordsCount(s,t),l=(a-i)*8;for(r.getLengthInBits()+4<=l&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);const o=(l-r.getLengthInBits())/8;for(let c=0;c=7&&Aur(c,t),Eur(c,l),isNaN(r)&&(r=eYe.getBestMask(c,iBe.bind(null,c,n))),eYe.applyMask(r,c),iBe(c,n,r),{modules:c,version:t,errorCorrectionLevel:n,maskPattern:r,segments:a}}Urs.create=function(t,n){if(typeof t>"u"||t==="")throw new Error("No input text");let r=rBe.M,a,i;return typeof n<"u"&&(r=rBe.from(n.errorCorrectionLevel,rBe.M),a=DTe.from(n.version),i=eYe.from(n.maskPattern),n.toSJISFunc&&o8e.setToSJISFunction(n.toSJISFunc)),Pur(t,a,r,i)};var eas={},yat={};(function(s){function t(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw new Error("Color should be defined as hex string");let r=n.slice().replace("#","").split("");if(r.length<3||r.length===5||r.length>8)throw new Error("Invalid hex color: "+n);(r.length===3||r.length===4)&&(r=Array.prototype.concat.apply([],r.map(function(i){return[i,i]}))),r.length===6&&r.push("F","F");const a=parseInt(r.join(""),16);return{r:a>>24&255,g:a>>16&255,b:a>>8&255,a:a&255,hex:"#"+r.slice(0,6).join("")}}s.getOptions=function(r){r||(r={}),r.color||(r.color={});const a=typeof r.margin>"u"||r.margin===null||r.margin<0?4:r.margin,i=r.width&&r.width>=21?r.width:void 0,l=r.scale||4;return{width:i,scale:i?4:l,margin:a,color:{dark:t(r.color.dark||"#000000ff"),light:t(r.color.light||"#ffffffff")},type:r.type,rendererOpts:r.rendererOpts||{}}},s.getScale=function(r,a){return a.width&&a.width>=r+a.margin*2?a.width/(r+a.margin*2):a.scale},s.getImageWidth=function(r,a){const i=s.getScale(r,a);return Math.floor((r+a.margin*2)*i)},s.qrToImageData=function(r,a,i){const l=a.modules.size,o=a.modules.data,c=s.getScale(l,i),d=Math.floor((l+i.margin*2)*c),u=i.margin*c,h=[i.color.light,i.color.dark];for(let m=0;m=u&&p>=u&&m"u"&&(!l||!l.getContext)&&(c=l,l=void 0),l||(d=r()),c=t.getOptions(c);const u=t.getImageWidth(i.modules.size,c),h=d.getContext("2d"),m=h.createImageData(u,u);return t.qrToImageData(m.data,i,c),n(h,d,u),h.putImageData(m,0,0),d},s.renderToDataURL=function(i,l,o){let c=o;typeof c>"u"&&(!l||!l.getContext)&&(c=l,l=void 0),c||(c={});const d=s.render(i,l,c),u=c.type||"image/png",h=c.rendererOpts||{};return d.toDataURL(u,h.quality)}})(eas);var tas={};const Lur=yat;function a3t(s,t){const n=s.a/255,r=t+'="'+s.hex+'"';return n<1?r+" "+t+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function oBe(s,t,n){let r=s+t;return typeof n<"u"&&(r+=" "+n),r}function Iur(s,t,n){let r="",a=0,i=!1,l=0;for(let o=0;o0&&c>0&&s[o-1]||(r+=i?oBe("M",c+n,.5+d+n):oBe("m",a,0),a=0,i=!1),c+1':"",d="',u='viewBox="0 0 '+o+" "+o+'"',m=''+c+d+` `;return typeof r=="function"&&r(null,m),m};const Rur=Zdr,sYe=Urs,sas=eas,Dur=tas;function vat(s,t,n,r,a){const i=[].slice.call(arguments,1),l=i.length,o=typeof i[l-1]=="function";if(!o&&!Rur())throw new Error("Callback required as last argument");if(o){if(l<2)throw new Error("Too few arguments provided");l===2?(a=n,n=t,t=r=void 0):l===3&&(t.getContext&&typeof a>"u"?(a=r,r=void 0):(a=r,r=n,n=t,t=void 0))}else{if(l<1)throw new Error("Too few arguments provided");return l===1?(n=t,t=r=void 0):l===2&&!t.getContext&&(r=n,n=t,t=void 0),new Promise(function(c,d){try{const u=sYe.create(n,r);c(s(u,t,r))}catch(u){d(u)}})}try{const c=sYe.create(n,r);a(null,s(c,t,r))}catch(c){a(c)}}AW.create=sYe.create;AW.toCanvas=vat.bind(null,sas.render);AW.toDataURL=vat.bind(null,sas.renderToDataURL);AW.toString=vat.bind(null,function(s,t,n){return Dur.render(s,n)});function Our(){const{eventId:s}=Di(),t=Wn(),{data:n}=mat(s),{data:r=[]}=Crs(s),a=Trs(),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),p=n!=null&&n.public_slug?n8e(n.public_slug):"";j.useEffect(()=>{p&&AW.toDataURL(p,{width:320,margin:1}).then(m).catch(()=>{})},[p]);const f=j.useMemo(()=>i?r.filter(v=>(v.guest_name||"").toLowerCase().includes(i.toLowerCase())||(v.guest_email||"").toLowerCase().includes(i.toLowerCase())):r,[r,i]),x=v=>{a.mutate({id:v.id,event_id:s,status:"attended",checked_in_at:new Date().toISOString()}),re.success(`${v.guest_name||"Guest"} checked in`)},y=()=>{o&&(a.mutate({event_id:s,guest_name:o,guest_email:d||null,status:"attended",checked_in_at:new Date().toISOString(),invitation_source:"walk_in"}),c(""),u(""),re.success("Walk-in checked in"))};return n?e.jsx("div",{className:"min-h-screen bg-slate-50",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 md:p-6",children:[e.jsxs(U,{variant:"ghost",size:"sm",className:"rounded-full mb-3",onClick:()=>t(`/attract/events/${s}`),children:[e.jsx(Aa,{className:"h-4 w-4 mr-2"})," Back to event"]}),e.jsxs(we,{className:"p-5 rounded-2xl bg-gradient-to-br from-slate-900 to-slate-800 text-white border-0",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-widest text-white/60",children:"Check-in mode"}),e.jsx("div",{className:"text-xl font-semibold mt-1",children:n.title}),e.jsxs("div",{className:"text-white/70 text-[13px] mt-0.5",children:[n.registration_count," registered · ",n.attendance_count," checked in"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mt-4",children:[e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[13px] font-semibold text-slate-900",children:[e.jsx(Sf,{className:"h-4 w-4"})," Registration QR"]}),h?e.jsx("img",{src:h,alt:"QR code",className:"mx-auto mt-3 h-56 w-56"}):e.jsx("div",{className:"text-[12px] text-slate-400 mt-3",children:"Publish this event to generate a QR code."}),p&&e.jsx("div",{className:"text-[11px] font-mono text-center text-slate-500 mt-2 break-all",children:p})]}),e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-900 mb-3",children:"Add walk-in"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(xe,{placeholder:"Name",value:o,onChange:v=>c(v.target.value)}),e.jsx(xe,{placeholder:"Email (optional)",value:d,onChange:v=>u(v.target.value)}),e.jsxs(U,{className:"w-full rounded-full",onClick:y,children:[e.jsx(zl,{className:"h-4 w-4 mr-2"})," Add & check in"]})]})]})]}),e.jsxs(we,{className:"mt-4 rounded-2xl border-slate-200 bg-white overflow-hidden",children:[e.jsxs("div",{className:"p-3 border-b border-slate-100 relative",children:[e.jsx(Fr,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(xe,{placeholder:"Search attendees",value:i,onChange:v=>l(v.target.value),className:"pl-9 rounded-full border-slate-200"})]}),f.length===0?e.jsx("div",{className:"p-8 text-center text-slate-400 text-[13px]",children:"No matches."}):e.jsx("div",{className:"divide-y divide-slate-100 max-h-[60vh] overflow-auto",children:f.map(v=>{const b=v.status==="attended";return e.jsxs("div",{className:"p-4 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 truncate",children:v.guest_name||v.guest_email}),e.jsx("div",{className:"text-[12px] text-slate-500 truncate",children:v.guest_email})]}),b?e.jsxs(Be,{className:"bg-emerald-500",children:[e.jsx(Xr,{className:"h-3 w-3 mr-1"})," Checked in"]}):e.jsxs(U,{size:"lg",className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>x(v),children:[e.jsx(Xr,{className:"h-5 w-5 mr-2"})," Check in"]})]},v.id)})})]})]})}):e.jsx("div",{className:"p-8 text-slate-500",children:"Loading…"})}const Fur=["Brand-new agents","Producing solo agents","Team leaders","Luxury agents","New construction agents","Agents struggling with marketing","Agents needing better systems/support","Agents interested in additional income"],zur=["Lead generation","Database marketing","Listing marketing","Social media/video","Open houses","Negotiation","Systems and technology","Team building","Leadership","New construction","Luxury","Business planning"],i3t=[{key:"produce",icon:Al,title:"Produce",blurb:"Attract through visible production and excellence.",example:"Publish weekly market updates, share every closing story with the lesson attached."},{key:"influence",icon:cn,title:"Influence",blurb:"Teach publicly and earn a following of agents.",example:"Host a monthly masterclass. Post 3 authority pieces a week."},{key:"provide",icon:UX,title:"Provide",blurb:"Give resources, tools, and referrals that make agents better.",example:"Send curated resource kits and warm referrals to the right people."},{key:"connect",icon:Xk,title:"Connect",blurb:"Bring the right people into the same room.",example:"Host quarterly masterminds and 1:1 coffees on a repeatable rhythm."},{key:"balanced",icon:IM,title:"Balanced Plan",blurb:"A little of all four. Best for veteran attractors.",example:"Rotate weekly focus between production, teaching, providing, and connecting."}],Bur=[{key:"new_relationships",label:"New agent relationships / month"},{key:"follow_ups",label:"Meaningful follow-ups / month"},{key:"content_pieces",label:"Agent-focused posts / month"},{key:"resources_shared",label:"Resources shared / month"},{key:"events",label:"Events hosted or attended / month"},{key:"brokerage_conversations",label:"Brokerage curiosity conversations / month"}],o3t=["Build 25 meaningful agent relationships","Host 3 masterminds or events","Start a weekly agent newsletter","Share 30 valuable resources","Schedule 10 brokerage curiosity conversations","Help 5 agents solve a meaningful business challenge"];function l3t(s){const t=(o,c=2)=>Math.max(2,Math.ceil((o||1)*c)),n={new_relationships:t(s.baseline.new_relationships/4,1.6),follow_ups:t(s.baseline.follow_ups/4,1.4),content_pieces:t(s.baseline.content_pieces/4,1.5),resources_shared:t(s.baseline.resources_shared/4,1.5),events:Math.max(1,Math.round((s.baseline.events||0)/4)),brokerage_conversations:Math.max(1,Math.round((s.baseline.brokerage_conversations||0)/4))},r=["Add 3 agents you already know to your Attract Pipeline","Review your last 5 closed transactions in the Transaction Tracker","Write your first Authority Content piece in Content Studio","Send one thoughtful resource to an agent you respect","Schedule one coffee or Zoom this week","Set your Follow-Up cadence in Settings","Book your next agent event on the calendar"],a={produce:"Post one production story + one market insight per week.",influence:"Post 3 authority pieces per week; go long-form once a month.",provide:"Share 2 resources per week and 1 warm referral per month.",connect:"One 1:1 per week + one small event per month.",balanced:"Rotate a Produce, Influence, Provide, and Connect focus week each month."},i={produce:"Transaction-to-Relationship Tracker",influence:"Authority Content Studio",provide:"Resource Library",connect:"Events & Follow-Up Center",balanced:"Dashboard Daily Plan"},l={produce:"Publish a 90-day production journal recap",influence:"Host a free 45-minute masterclass on your best system",provide:'Curate a "Top 10 tools every agent needs" resource kit',connect:"Invite 8 agents to a small-format mastermind",balanced:"Run a single flagship event featuring all four pillars"};return{primary_pillar:s.style,weekly_targets:n,first_7_days:r,content_rhythm:a[s.style],suggested_tool:i[s.style],suggested_offer:l[s.style],outcome:s.outcome,generated_at:new Date().toISOString()}}function Uur(){const s=Wn(),{settings:t,save:n}=cat(),[r,a]=j.useState(0),[i,l]=j.useState([]),[o,c]=j.useState([]),[d,u]=j.useState(null),[h,m]=j.useState({}),[p,f]=j.useState("");j.useEffect(()=>{var N,S;t&&((N=t.audiences)!=null&&N.length&&l(t.audiences),(S=t.teachables)!=null&&S.length&&c(t.teachables),t.attraction_style&&u(t.attraction_style),t.activity_baseline&&m(t.activity_baseline),t.ninety_day_outcome&&f(t.ninety_day_outcome))},[t==null?void 0:t.user_id]);const x=["Welcome","Audience","Teach","Style","Baseline","Outcome","Plan"],y=j.useMemo(()=>r===1?i.length>0:r===2?o.length>0:r===3?!!d:r===5?!!p:!0,[r,i,o,d,p]),v=(N,S,A)=>{A(N.includes(S)?N.filter(T=>T!==S):[...N,S])},b=async()=>{if(!d)return;const N=l3t({style:d,baseline:h,outcome:p});await n.mutateAsync({audiences:i,teachables:o,attraction_style:d,activity_baseline:h,ninety_day_outcome:p,ninety_day_plan:N,primary_pillar:d,onboarding_completed_at:new Date().toISOString()}),re.success("Your 90-day plan is ready."),s("/attract")};return e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("div",{className:"flex items-center gap-2 mb-8",children:x.map((N,S)=>e.jsx("div",{className:Mt("h-1.5 flex-1 rounded-full transition-colors",S<=r?"bg-violet-600":"bg-slate-200")},N))}),e.jsx(_G,{mode:"wait",children:e.jsxs(kr.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},transition:{duration:.25},children:[r===0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"A strategy session"}),e.jsx("h1",{className:"text-4xl md:text-5xl font-semibold tracking-tight text-slate-900",children:"Build an attraction business people want to be part of."}),e.jsx("p",{className:"text-slate-600 mt-4 text-lg leading-relaxed",children:"Attract isn't a recruiting funnel. It's a way of doing business where the right agents naturally find you — because you produce, teach, provide, and connect at a rhythm no one else in your market keeps."}),e.jsx("div",{className:"mt-8 grid grid-cols-2 md:grid-cols-4 gap-3",children:i3t.filter(N=>N.key!=="balanced").map(N=>e.jsxs(we,{className:"p-4 rounded-2xl border-slate-200",children:[e.jsx(N.icon,{className:"h-5 w-5 text-violet-600 mb-2"}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:N.title}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:N.blurb})]},N.key))})]}),r===1&&e.jsx(sZ,{icon:Bn,eyebrow:"Who can you best help?",title:"Pick every audience where you naturally shine.",subtitle:"You can adjust these anytime.",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:Fur.map(N=>e.jsx(lBe,{label:N,active:i.includes(N),onClick:()=>v(i,N,l)},N))})}),r===2&&e.jsx(sZ,{icon:Kh,eyebrow:"What can you genuinely teach?",title:"Choose the areas you'd feel proud to teach on stage.",subtitle:"Content and events will pull from here.",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:zur.map(N=>e.jsx(lBe,{label:N,active:o.includes(N),onClick:()=>v(o,N,c)},N))})}),r===3&&e.jsx(sZ,{icon:IM,eyebrow:"Your primary attraction style",title:"Which of these fits how you already show up?",subtitle:"This becomes your default pillar and shapes every recommendation.",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:i3t.map(N=>e.jsx(we,{onClick:()=>u(N.key),className:Mt("p-5 rounded-2xl cursor-pointer transition-all border-2",d===N.key?"border-violet-600 bg-violet-50/70 shadow-md":"border-slate-200 hover:border-violet-300"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-violet-100 text-violet-700 grid place-items-center",children:e.jsx(N.icon,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-[14px] font-semibold text-slate-900",children:N.title}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5",children:N.blurb}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 italic mt-2",children:["Example: ",N.example]})]}),d===N.key&&e.jsx(Xr,{className:"h-5 w-5 text-violet-600"})]})},N.key))})}),r===4&&e.jsx(sZ,{icon:Lm,eyebrow:"Current baseline",title:"Roughly, what are you doing today?",subtitle:"Estimate is fine. We use this to set realistic 90-day targets.",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:Bur.map(N=>e.jsxs("div",{children:[e.jsx(te,{className:"text-[12.5px] text-slate-700",children:N.label}),e.jsx(xe,{type:"number",min:0,value:h[N.key]??"",onChange:S=>m({...h,[N.key]:Number(S.target.value)||0})})]},N.key))})}),r===5&&e.jsx(sZ,{icon:Gu,eyebrow:"90-day outcome",title:"Pick one outcome to chase for the next 90 days.",subtitle:"One clear promise to yourself is worth ten vague hopes.",children:e.jsxs("div",{className:"space-y-2",children:[o3t.map(N=>e.jsx(lBe,{label:N,active:p===N,onClick:()=>f(N),full:!0},N)),e.jsxs("div",{className:"mt-3",children:[e.jsx(te,{className:"text-[12.5px] text-slate-700",children:"Or write your own"}),e.jsx(Fs,{rows:2,placeholder:"A specific outcome you can measure in 90 days...",value:o3t.includes(p)?"":p,onChange:N=>f(N.target.value)})]})]})}),r===6&&d&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"Your plan"}),e.jsx("h2",{className:"text-3xl font-semibold tracking-tight text-slate-900",children:"You're ready. Here's your 90-day plan."}),e.jsx(qur,{plan:l3t({style:d,baseline:h,outcome:p})})]})]},r)}),e.jsxs("div",{className:"mt-10 flex items-center justify-between",children:[e.jsxs(U,{variant:"ghost",onClick:()=>r===0?s("/attract"):a(r-1),children:[e.jsx(Aa,{className:"h-4 w-4 mr-1"})," ",r===0?"Skip for now":"Back"]}),r<6?e.jsxs(U,{className:"bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full px-6",disabled:!y,onClick:()=>a(r+1),children:["Continue ",e.jsx(Oa,{className:"h-4 w-4 ml-1"})]}):e.jsxs(U,{className:"bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full px-6",onClick:b,disabled:n.isPending,children:[e.jsx(pv,{className:"h-4 w-4 mr-1.5"})," Activate my 90-day plan"]})]})]})}function sZ({icon:s,eyebrow:t,title:n,subtitle:r,children:a}){return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:[e.jsx(s,{className:"h-3.5 w-3.5"})," ",t]}),e.jsx("h2",{className:"text-3xl font-semibold tracking-tight text-slate-900",children:n}),r&&e.jsx("p",{className:"text-slate-600 mt-1.5 mb-6",children:r}),e.jsx("div",{className:"mt-6",children:a})]})}function lBe({label:s,active:t,onClick:n,full:r}){return e.jsx("button",{type:"button",onClick:n,className:Mt("text-left rounded-xl border px-4 py-3 text-[13.5px] transition-colors",r?"w-full":"",t?"border-violet-600 bg-violet-50 text-violet-900 shadow-sm":"border-slate-200 bg-white hover:border-violet-300 text-slate-800"),children:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[t&&e.jsx(Xr,{className:"h-4 w-4 text-violet-600"})," ",s]})})}function qur({plan:s}){return e.jsxs("div",{className:"mt-6 space-y-6",children:[e.jsxs(we,{className:"p-6 rounded-2xl bg-gradient-to-br from-violet-600 to-indigo-700 text-white border-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] opacity-80",children:"Primary focus"}),e.jsx("div",{className:"text-3xl font-semibold mt-1 capitalize",children:s.primary_pillar}),e.jsx("div",{className:"text-white/85 mt-2",children:s.content_rhythm}),e.jsxs("div",{className:"text-[13px] mt-4 rounded-xl bg-white/10 p-3",children:[e.jsx("span",{className:"opacity-80",children:"90-day outcome:"})," ",s.outcome]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Weekly targets"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:Object.entries(s.weekly_targets).map(([t,n])=>e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold text-slate-900 tabular-nums",children:n}),e.jsx("div",{className:"text-[11.5px] text-slate-500 capitalize mt-0.5",children:t.replace(/_/g," ")})]},t))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"First 7 days"}),e.jsx(we,{className:"p-5 rounded-2xl",children:e.jsx("ul",{className:"space-y-2",children:s.first_7_days.map((t,n)=>e.jsxs("li",{className:"flex items-start gap-2.5 text-[13.5px] text-slate-800",children:[e.jsx("div",{className:"h-5 w-5 rounded-full bg-violet-100 text-violet-700 grid place-items-center text-[11px] font-semibold flex-shrink-0 mt-0.5",children:n+1}),t]},n))})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Recommended first tool"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:s.suggested_tool})]}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Suggested first offer"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:s.suggested_offer})]})]})]})}function $ur(){const{user:s}=vs(),t=Qt(),n=ct({queryKey:["attract-content",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await q.from("attract_content_drafts").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=yt({mutationFn:async o=>{const{data:c,error:d}=await q.functions.invoke("attract-content-generate",{body:o});if(d)throw d;if(c!=null&&c.error)throw new Error(c.error);return c},onSuccess:o=>{t.invalidateQueries({queryKey:["attract-content"]}),o.demo?re.info("Demo generation used — configure AI provider for live results"):re.success("Content generated")},onError:o=>re.error(o.message)}),a=yt({mutationFn:async o=>{const{data:c,error:d}=await q.from("attract_content_drafts").update(o).eq("id",o.id).select().single();if(d)throw d;return c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),re.success("Saved")}}),i=yt({mutationFn:async o=>{const{error:c}=await q.from("attract_content_drafts").update({status:"posted",posted_at:new Date().toISOString()}).eq("id",o);if(c)throw c;await q.rpc("award_attract_activity",{_user_id:s.id,_activity_type:"content_posted",_title:"Posted authority content",_description:null,_pillar:"influence",_agent_id:null,_metadata:{draft_id:o},_dedupe_minutes:30})},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),t.invalidateQueries({queryKey:["attract-activities"]}),re.success("Marked as posted")}}),l=yt({mutationFn:async o=>{const{error:c}=await q.from("attract_content_drafts").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),re.success("Draft removed")}});return{drafts:n.data??[],isLoading:n.isLoading,generate:r,save:a,markPosted:i,remove:l}}const nYe=[{key:"transaction_lesson",label:"Transaction Lesson",blurb:"A real story from a recent deal that teaches something.",fields:[{key:"what_happened",label:"What happened?",placeholder:"A short version of the story."},{key:"challenge",label:"What challenge came up?"},{key:"what_you_did",label:"What did you do?"},{key:"lesson",label:"What can another agent learn?"}]},{key:"behind_the_business",label:"Behind the Business",blurb:"A peek behind how you run the day-to-day.",fields:[{key:"topic",label:"What are you sharing?",placeholder:"A morning routine, tool stack, client system..."},{key:"why",label:"Why does it matter?"},{key:"takeaway",label:"What can they take away?"}]},{key:"unpopular_opinion",label:"Unpopular Industry Opinion",blurb:"Say what most people are afraid to say.",fields:[{key:"opinion",label:"What is your actual opinion?"},{key:"why",label:"Why do you believe it?"},{key:"example",label:"What real example supports it?"}]},{key:"system_win",label:"A System That Improved My Business",blurb:"A specific system with a before/after.",fields:[{key:"system",label:"What is the system?"},{key:"before",label:"What was life like before?"},{key:"after",label:"What changed after?"}]},{key:"mistake_to_avoid",label:"Mistake Agents Can Avoid",blurb:"A mistake you made or watched happen — and the fix.",fields:[{key:"mistake",label:"What is the mistake?"},{key:"result",label:"What did it cost?"},{key:"fix",label:"How do you avoid it now?"}]},{key:"do_differently",label:"What I Would Do Differently",blurb:"Reflection on a past year, launch, or transaction.",fields:[{key:"period",label:"What period are you reflecting on?"},{key:"what",label:"What would you do differently?"},{key:"why",label:"Why?"}]},{key:"leadership_lesson",label:"Leadership Lesson",blurb:"A moment that shaped how you lead.",fields:[{key:"story",label:"The moment/story"},{key:"lesson",label:"The lesson"}]},{key:"tool_tip",label:"Tool or Technology Tip",blurb:"A tool + how you use it + why it matters.",fields:[{key:"tool",label:"Which tool?"},{key:"how",label:"How do you use it?"},{key:"impact",label:"The impact on your business"}]},{key:"market_strategy",label:"Market Strategy",blurb:"Something you're seeing in your market that others are missing.",fields:[{key:"observation",label:"What are you seeing?"},{key:"strategy",label:"What are you doing about it?"},{key:"takeaway",label:"How can they apply it?"}]},{key:"event_promo",label:"Event Promotion",blurb:"Promote an event without sounding like a pitch.",fields:[{key:"event",label:"Event name"},{key:"who",label:"Who is it for?"},{key:"walk_away",label:"What will they walk away with?"},{key:"when_where",label:"When and where"}]}],Vur=["Direct","Educational","Fun","Contrarian","Encouraging"],Hur=["short","medium","long"],Gur=["instagram","linkedin","facebook","youtube","email"],OTe={idea:{label:"Idea",color:"bg-slate-100 text-slate-700"},draft:{label:"Draft",color:"bg-amber-100 text-amber-800"},ready:{label:"Ready",color:"bg-emerald-100 text-emerald-800"},posted:{label:"Posted",color:"bg-violet-100 text-violet-800"}};function Wur(){const{drafts:s,isLoading:t,generate:n,save:r,markPosted:a,remove:i}=$ur(),[l,o]=j.useState(!1),[c,d]=j.useState(null),u=j.useMemo(()=>({ready:s.filter(h=>h.status==="ready"),draft:s.filter(h=>h.status==="draft"),idea:s.filter(h=>h.status==="idea"),posted:s.filter(h=>h.status==="posted")}),[s]);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-5",children:[e.jsx("div",{className:"text-[13px] text-slate-500 max-w-xl",children:"Turn your real experience into agent-focused content that builds authority — without sounding like a brokerage pitch."}),e.jsxs(U,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>{d(null),o(!0)},children:[e.jsx(Lg,{className:"h-4 w-4 mr-1.5"})," New Content"]})]}),e.jsxs("div",{className:"mb-6 rounded-2xl border border-amber-200 bg-amber-50/70 px-5 py-3.5 text-[13px] text-amber-900 flex items-start gap-3",children:[e.jsx(cn,{className:"h-4 w-4 mt-0.5"}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:"80/20 rule:"})," Aim for 80% useful industry, business, and personal content — and no more than 20% direct brokerage content."]})]}),e.jsxs(oa,{defaultValue:"all",className:"mb-8",children:[e.jsxs(la,{children:[e.jsxs(Kt,{value:"all",children:["All (",s.length,")"]}),e.jsxs(Kt,{value:"ready",children:["Ready (",u.ready.length,")"]}),e.jsxs(Kt,{value:"draft",children:["Draft (",u.draft.length,")"]}),e.jsxs(Kt,{value:"posted",children:["Posted (",u.posted.length,")"]})]}),e.jsx(Zt,{value:"all",children:e.jsx(cde,{drafts:s,isLoading:t,onOpen:h=>{d(h),o(!0)},onPosted:h=>a.mutate(h),onRemove:h=>i.mutate(h),onEmpty:()=>{d(null),o(!0)}})}),e.jsx(Zt,{value:"ready",children:e.jsx(cde,{drafts:u.ready,isLoading:t,onOpen:h=>{d(h),o(!0)},onPosted:h=>a.mutate(h),onRemove:h=>i.mutate(h),onEmpty:()=>{d(null),o(!0)}})}),e.jsx(Zt,{value:"draft",children:e.jsx(cde,{drafts:u.draft,isLoading:t,onOpen:h=>{d(h),o(!0)},onPosted:h=>a.mutate(h),onRemove:h=>i.mutate(h),onEmpty:()=>{d(null),o(!0)}})}),e.jsx(Zt,{value:"posted",children:e.jsx(cde,{drafts:u.posted,isLoading:t,onOpen:h=>{d(h),o(!0)},onPosted:()=>{},onRemove:h=>i.mutate(h),onEmpty:()=>{d(null),o(!0)}})})]}),e.jsx(Prs,{}),e.jsx(Kur,{open:l,editing:c,onClose:()=>{o(!1),d(null)},generate:n,save:r,markPosted:h=>a.mutate(h)})]})}function cde({drafts:s,isLoading:t,onOpen:n,onPosted:r,onRemove:a,onEmpty:i}){return t?e.jsx("div",{className:"space-y-3 mt-4",children:[0,1,2].map(l=>e.jsx(we,{className:"p-5 rounded-2xl h-24 animate-pulse bg-slate-100"},l))}):s.length===0?e.jsxs(we,{className:"p-10 rounded-2xl text-center mt-4",children:[e.jsx("div",{className:"h-14 w-14 rounded-2xl bg-violet-100 grid place-items-center mx-auto mb-4",children:e.jsx(Pg,{className:"h-6 w-6 text-violet-700"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-900",children:"Start your first authority piece"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 max-w-md mx-auto mt-2",children:"Pick a real experience, answer 3 quick questions, and get a script, caption, carousel outline, and email — all in one shot."}),e.jsxs(U,{className:"mt-6 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:i,children:[e.jsx(an,{className:"h-4 w-4 mr-1.5"})," Create your first draft"]})]}):e.jsx("div",{className:"space-y-3 mt-4",children:s.map(l=>{var c,d;const o=((c=nYe.find(u=>u.key===l.mode))==null?void 0:c.label)??l.mode;return e.jsx(we,{className:"p-5 rounded-2xl hover:shadow-md transition-shadow",children:e.jsxs("div",{className:"flex items-start gap-4",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(Be,{className:Mt("text-[10.5px] border-0",OTe[l.status].color),children:OTe[l.status].label}),e.jsx(Be,{variant:"outline",className:"text-[10.5px]",children:o}),l.tone&&e.jsx(Be,{variant:"outline",className:"text-[10.5px]",children:l.tone}),l.ratio_flag&&e.jsxs(Be,{className:"text-[10.5px] bg-amber-100 text-amber-900 border-0 gap-1",children:[e.jsx(tc,{className:"h-3 w-3"})," Sounds promotional"]})]}),e.jsx("div",{className:"text-[14px] font-semibold text-slate-900 mt-2 line-clamp-1",children:l.topic??((d=l.hook_options)==null?void 0:d[0])??"Untitled draft"}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:l.caption??l.script??""}),e.jsx("div",{className:"text-[11px] text-slate-500 mt-2",children:l.posted_at?`Posted ${Gs(new Date(l.posted_at),"MMM d")}`:`Updated ${Gs(new Date(l.updated_at),"MMM d")}`})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(U,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>n(l),children:"Open"}),l.status!=="posted"&&e.jsxs(U,{size:"sm",variant:"ghost",className:"text-emerald-700",onClick:()=>r(l.id),children:[e.jsx(Xr,{className:"h-3.5 w-3.5 mr-1"})," Posted"]}),e.jsx(U,{size:"sm",variant:"ghost",className:"text-rose-600",onClick:()=>a(l.id),children:e.jsx(In,{className:"h-3.5 w-3.5"})})]})]})},l.id)})})}function Kur({open:s,editing:t,onClose:n,generate:r,save:a,markPosted:i}){const[l,o]=j.useState((t==null?void 0:t.mode)??"transaction_lesson"),[c,d]=j.useState((t==null?void 0:t.input_json)??{}),[u,h]=j.useState((t==null?void 0:t.topic)??""),[m,p]=j.useState((t==null?void 0:t.tone)??"Educational"),[f,x]=j.useState((t==null?void 0:t.length)??"medium"),[y,v]=j.useState((t==null?void 0:t.platforms)??["instagram"]),[b,N]=j.useState((t==null?void 0:t.include_brokerage_reference)??!1),[S,A]=j.useState(t??null),[T,L]=j.useState(""),[M,I]=j.useState((t==null?void 0:t.status)??"draft"),R=nYe.find(H=>H.key===l),z=async H=>{const V=await r.mutateAsync({mode:l,topic:u,inputs:c,tone:m,length:f,platforms:y,include_brokerage_reference:b,refinement:H??T,draft_id:S==null?void 0:S.id});V!=null&&V.draft&&A(V.draft),L("")},$=async H=>{if(!S)return;const V=await a.mutateAsync({id:S.id,...H});A(V)};return e.jsx(zs,{open:s,onOpenChange:H=>!H&&n(),children:e.jsx(Ds,{className:"max-w-5xl max-h-[92vh] overflow-hidden p-0",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-[320px_1fr] max-h-[92vh]",children:[e.jsxs("div",{className:"border-r bg-slate-50 p-5 overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{className:"text-base",children:"Content Studio"}),e.jsx(Pr,{className:"text-[12px]",children:R.blurb})]}),e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-[12px]",children:"Content mode"}),e.jsxs(Ns,{value:l,onValueChange:H=>{o(H),d({})},children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:nYe.map(H=>e.jsx(et,{value:H.key,children:H.label},H.key))})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-[12px]",children:"Topic (optional)"}),e.jsx(xe,{value:u,onChange:H=>h(H.target.value),placeholder:"1-line summary"})]}),R.fields.map(H=>e.jsxs("div",{children:[e.jsx(te,{className:"text-[12px]",children:H.label}),e.jsx(Fs,{rows:2,value:c[H.key]??"",onChange:V=>d({...c,[H.key]:V.target.value}),placeholder:H.placeholder})]},H.key)),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-[12px]",children:"Tone"}),e.jsxs(Ns,{value:m,onValueChange:p,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:Vur.map(H=>e.jsx(et,{value:H,children:H},H))})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-[12px]",children:"Length"}),e.jsxs(Ns,{value:f,onValueChange:x,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:Hur.map(H=>e.jsx(et,{value:H,children:H},H))})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-[12px]",children:"Platforms"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1",children:Gur.map(H=>e.jsx("button",{type:"button",onClick:()=>v(y.includes(H)?y.filter(V=>V!==H):[...y,H]),className:Mt("rounded-full px-2.5 py-1 text-[11px] capitalize border",y.includes(H)?"bg-violet-600 text-white border-violet-600":"bg-white border-slate-200 text-slate-700"),children:H},H))})]}),e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-slate-700",children:[e.jsx("input",{type:"checkbox",checked:b,onChange:H=>N(H.target.checked)}),"Include a light brokerage reference"]}),e.jsxs(U,{className:"w-full bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full",onClick:()=>z(),disabled:r.isPending,children:[e.jsx(Lg,{className:"h-4 w-4 mr-1.5"})," ",r.isPending?"Generating…":S?"Regenerate":"Generate content"]})]})]}),e.jsx("div",{className:"overflow-y-auto p-6",children:S?e.jsxs("div",{className:"space-y-5",children:[S.ratio_flag&&e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-3 text-[12.5px] text-amber-900 flex items-start gap-2",children:[e.jsx(tc,{className:"h-4 w-4 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-semibold",children:"Heads up — this leans promotional."}),e.jsx("div",{children:"Not blocking anything, but you can rewrite it to feel more like teaching."})]}),e.jsx(U,{size:"sm",variant:"outline",onClick:()=>z("Make this less salesy — focus purely on the lesson."),children:"Less salesy"})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Be,{className:Mt("text-[10.5px] border-0",OTe[M].color),children:OTe[M].label}),e.jsxs(Ns,{value:M,onValueChange:H=>{I(H),$({status:H})},children:[e.jsx(ws,{className:"h-8 w-32 text-[12px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"idea",children:"Idea"}),e.jsx(et,{value:"draft",children:"Draft"}),e.jsx(et,{value:"ready",children:"Ready"}),e.jsx(et,{value:"posted",children:"Posted"})]})]}),e.jsx(xe,{type:"date",className:"h-8 w-40 text-[12px]",value:S.planned_at?S.planned_at.slice(0,10):"",onChange:H=>$({planned_at:H.target.value?new Date(H.target.value).toISOString():null})}),S.status!=="posted"&&e.jsxs(U,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>i(S.id),children:[e.jsx($r,{className:"h-3.5 w-3.5 mr-1"})," Mark posted"]}),e.jsx(U,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(xr,{to:`/attract/toolkit/kits/new?seed=${encodeURIComponent(S.topic||S.mode)}`,children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1"})," Turn into a kit"]})})]}),e.jsx(PB,{title:"Hook options",children:e.jsx("div",{className:"space-y-1.5",children:(S.hook_options??[]).map((H,V)=>e.jsxs("div",{className:"rounded-xl bg-slate-50 p-3 text-[13.5px] text-slate-800 flex items-start gap-2",children:[e.jsxs("span",{className:"text-violet-600 font-semibold",children:[V+1,"."]}),e.jsx("span",{className:"flex-1",children:H}),e.jsx(rYe,{value:H})]},V))})}),e.jsx(PB,{title:"Teleprompter script",children:e.jsx(cBe,{value:S.script??"",onSave:H=>$({script:H})})}),e.jsx(PB,{title:"Social caption",children:e.jsx(cBe,{value:S.caption??"",onSave:H=>$({caption:H})})}),e.jsx(PB,{title:"Carousel outline",children:e.jsx("div",{className:"space-y-1.5",children:(S.carousel_outline??[]).map((H,V)=>e.jsxs("div",{className:"rounded-xl bg-slate-50 p-3 text-[13px]",children:[e.jsxs("div",{className:"text-[10.5px] uppercase tracking-wider text-slate-500 font-semibold",children:["Slide ",H.slide??V+1]}),e.jsx("div",{className:"text-slate-800 mt-0.5",children:H.text})]},V))})}),e.jsx(PB,{title:"Email lesson",children:e.jsx(cBe,{value:S.email_lesson??"",onSave:H=>$({email_lesson:H})})}),e.jsx(PB,{title:"CTA options",children:e.jsx("div",{className:"space-y-1.5",children:(S.cta_options??[]).map((H,V)=>e.jsxs("div",{className:"rounded-xl bg-slate-50 p-3 text-[13px] text-slate-800 flex items-start gap-2",children:[e.jsx("span",{className:"flex-1",children:H}),e.jsx(rYe,{value:H})]},V))})}),e.jsxs("div",{className:"rounded-xl border border-slate-200 p-3",children:[e.jsx("div",{className:"text-[12px] font-semibold text-slate-700 mb-2",children:"Refine further"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:["Make this sound more like me","Shorten the hook","Add a real example","Make it less salesy"].map(H=>e.jsx(U,{size:"sm",variant:"outline",className:"text-[11.5px]",onClick:()=>z(H),children:H},H))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:T,onChange:H=>L(H.target.value),placeholder:"Custom refinement…"}),e.jsxs(U,{variant:"outline",onClick:()=>z(),disabled:r.isPending,children:[e.jsx(no,{className:"h-3.5 w-3.5 mr-1"})," Regenerate"]})]})]})]}):e.jsx("div",{className:"h-full flex items-center justify-center text-center text-slate-500",children:e.jsxs("div",{children:[e.jsx(mq,{className:"h-10 w-10 text-violet-300 mx-auto mb-3"}),e.jsx("div",{className:"text-[14px] font-medium text-slate-700",children:"Fill in the story on the left, then generate."}),e.jsx("div",{className:"text-[12.5px] mt-1",children:"You'll get a script, caption, carousel, email, and hooks in one shot."})]})})})]})})})}function PB({title:s,children:t}){return e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2 flex items-center gap-1.5",children:[e.jsx(pa,{className:"h-3 w-3 opacity-0"})," ",s]}),t]})}function cBe({value:s,onSave:t}){const[n,r]=j.useState(s);return e.jsxs("div",{children:[e.jsx(Fs,{rows:5,value:n,onChange:a=>r(a.target.value),className:"text-[13.5px]"}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(U,{size:"sm",variant:"outline",onClick:()=>t(n),children:"Save edit"}),e.jsx(rYe,{value:n})]})]})}function rYe({value:s}){return e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(s),re.success("Copied")},children:e.jsx(Pa,{className:"h-3.5 w-3.5"})})}const Yur={draft:"bg-slate-100 text-slate-700",published:"bg-emerald-100 text-emerald-800",archived:"bg-amber-100 text-amber-800"};function Zur(){const{kits:s,isLoading:t,create:n,duplicate:r,remove:a}=pat(),i=Wn(),l=async()=>{const o=await n.mutateAsync({title:"Untitled Kit",status:"draft"});i(`/attract/toolkit/kits/${o.id}/edit`)};return e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-5",children:[e.jsx("div",{className:"text-[13px] text-slate-500",children:"Package the value you already share, then track what actually creates conversations."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{variant:"outline",asChild:!0,className:"rounded-full",children:e.jsxs(xr,{to:"/attract/toolkit/kits/templates",children:[e.jsx(tj,{className:"h-4 w-4 mr-2"}),"Starter library"]})}),e.jsxs(U,{onClick:l,className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",children:[e.jsx(an,{className:"h-4 w-4 mr-2"}),"New kit"]})]})]}),t&&e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading kits…"}),!t&&s.length===0&&e.jsxs(we,{className:"p-10 text-center rounded-2xl border-dashed border-slate-300 bg-white",children:[e.jsx(cn,{className:"h-8 w-8 mx-auto text-violet-500"}),e.jsx("div",{className:"mt-3 text-lg font-semibold",children:"You haven't built a kit yet."}),e.jsx("p",{className:"text-slate-600 max-w-md mx-auto mt-1 text-sm",children:"Start from a starter template or a blank kit. Bundle 3–7 pieces of real value and share with agents you'd love to work alongside."}),e.jsxs("div",{className:"flex gap-2 justify-center mt-5",children:[e.jsx(U,{variant:"outline",asChild:!0,children:e.jsx(xr,{to:"/attract/toolkit/kits/templates",children:"Browse starter library"})}),e.jsx(U,{onClick:l,className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:"Start a blank kit"})]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:s.map(o=>{var c;return e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200 bg-white hover:shadow-md transition-shadow flex flex-col",children:[e.jsx("div",{className:"flex 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(Be,{className:Yur[o.status]+" capitalize",children:o.status}),o.pillar&&e.jsx(Be,{variant:"outline",className:"capitalize",children:o.pillar})]}),e.jsx("div",{className:"mt-2 text-[16px] font-semibold text-slate-900 line-clamp-2",children:o.title}),o.audience&&e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["For ",o.audience]})]})}),o.description&&e.jsx("p",{className:"text-[13px] text-slate-600 mt-3 line-clamp-3",children:o.description}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-1",children:(c=o.tags)==null?void 0:c.slice(0,4).map(d=>e.jsxs(Be,{variant:"secondary",className:"text-[10.5px]",children:["#",d]},d))}),e.jsxs("div",{className:"mt-auto pt-4 flex items-center gap-2 flex-wrap",children:[e.jsx(U,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs(xr,{to:`/attract/toolkit/kits/${o.id}/edit`,children:[e.jsx(lq,{className:"h-3.5 w-3.5 mr-1.5"}),"Edit"]})}),e.jsx(U,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs(xr,{to:`/attract/toolkit/kits/${o.id}/analytics`,children:[e.jsx(Cl,{className:"h-3.5 w-3.5 mr-1.5"}),"Analytics"]})}),e.jsx(U,{size:"sm",variant:"ghost",onClick:async()=>{const d=await r.mutateAsync(o.id);re.success("Duplicated"),i(`/attract/toolkit/kits/${d}/edit`)},children:e.jsx(Pa,{className:"h-3.5 w-3.5"})}),e.jsx(U,{size:"sm",variant:"ghost",onClick:async()=>{await Yi("Delete this kit? Shares and events will also be removed.")&&a.mutate(o.id,{onSuccess:()=>re.success("Deleted")})},children:e.jsx(In,{className:"h-3.5 w-3.5 text-rose-600"})})]})]},o.id)})})]})}const Xur={pdf:Ur,video:lu,link:Rc,checklist:cy,template:EA,text:Ur,content_studio:cn,resource:Ur};function nas({kit:s,items:t,owner:n,personalNote:r,mode:a="public",onEvent:i}){const l=(o,c,d)=>i==null?void 0:i(o,c,d);return e.jsxs("div",{className:"bg-[#0B0F1E] text-slate-100 rounded-2xl overflow-hidden",children:[s.cover_image_url?e.jsxs("div",{className:"aspect-[16/7] bg-slate-800 relative",children:[e.jsx("img",{src:s.cover_image_url,alt:"",className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0B0F1E] to-transparent"})]}):e.jsx("div",{className:"h-24 bg-gradient-to-br from-violet-700 via-indigo-700 to-slate-900"}),e.jsxs("div",{className:"p-5 md:p-8",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[n.avatar_url?e.jsx("img",{src:n.avatar_url,alt:"",className:"h-11 w-11 rounded-full object-cover ring-2 ring-white/10"}):e.jsx("div",{className:"h-11 w-11 rounded-full bg-white/10 grid place-items-center text-white/70 font-semibold",children:n.display_name.slice(0,1)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-semibold",children:n.display_name}),n.brokerage&&e.jsx("div",{className:"text-[11px] text-slate-400",children:n.brokerage})]})]}),e.jsx("h1",{className:"mt-5 text-2xl md:text-3xl font-semibold tracking-tight text-white",children:s.title}),s.audience&&e.jsxs("div",{className:"text-[12px] uppercase tracking-widest text-violet-300 mt-1",children:["For ",s.audience]}),s.description&&e.jsx("p",{className:"text-slate-300 mt-3 text-[14.5px] leading-relaxed",children:s.description}),(r||s.intro_text)&&e.jsxs(we,{className:"mt-6 p-4 bg-white/5 border-white/10 text-slate-200",children:[r&&e.jsx("div",{className:"text-[13px] whitespace-pre-line",children:r}),r&&s.intro_text&&e.jsx("div",{className:"my-2 border-t border-white/10"}),s.intro_text&&e.jsx("div",{className:"text-[13px] whitespace-pre-line text-slate-300",children:s.intro_text})]}),s.intro_video_url&&e.jsx("div",{className:"mt-5 aspect-video rounded-xl overflow-hidden bg-black",children:e.jsx("iframe",{src:Qur(s.intro_video_url),className:"w-full h-full",allow:"autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0,title:"Intro video",onLoad:()=>l("video_start")})}),e.jsx("div",{className:"mt-8 space-y-3",children:t.filter(o=>!o.is_hidden).map(o=>{var d,u;const c=Xur[o.type]??Ur;return e.jsx(we,{className:"p-4 bg-white/5 border-white/10 text-slate-100",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-violet-600/20 text-violet-300 grid place-items-center flex-shrink-0",children:e.jsx(c,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[14px] font-semibold text-white",children:o.title}),o.description&&e.jsx("div",{className:"text-[12.5px] text-slate-300 mt-0.5",children:o.description}),o.type==="checklist"&&((d=o.content)==null?void 0:d.items)&&e.jsx("ul",{className:"mt-2 space-y-1 text-[13px] text-slate-200",children:o.content.items.map((h,m)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-violet-400",children:"•"}),h]},m))}),(o.type==="text"||o.type==="template")&&((u=o.content)==null?void 0:u.body)&&e.jsx("div",{className:"mt-2 text-[13px] text-slate-300 whitespace-pre-line",children:o.content.body}),o.url&&["video","pdf","link","resource"].includes(o.type)&&e.jsxs("div",{className:"mt-3 flex gap-2 flex-wrap",children:[e.jsx(U,{size:"sm",variant:"secondary",asChild:!0,onClick:()=>l("resource_open",o.id),children:e.jsxs("a",{href:o.url,target:"_blank",rel:"noreferrer",children:[e.jsx(Sr,{className:"h-3.5 w-3.5 mr-1.5"}),"Open"]})}),o.allow_download&&o.type!=="link"&&e.jsx(U,{size:"sm",variant:"outline",asChild:!0,onClick:()=>l("file_download",o.id),children:e.jsxs("a",{href:o.url,target:"_blank",rel:"noreferrer",download:!0,children:[e.jsx(pi,{className:"h-3.5 w-3.5 mr-1.5"}),"Download"]})}),o.type==="link"&&e.jsx(U,{size:"sm",variant:"outline",asChild:!0,onClick:()=>l("external_link_click",o.id),children:e.jsx("a",{href:o.url,target:"_blank",rel:"noreferrer",children:"Visit"})})]})]})]})},o.id)})}),s.cta_label&&s.cta_url&&e.jsx("div",{className:"mt-8 text-center",children:e.jsx(U,{size:"lg",asChild:!0,className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>l("primary_cta_click"),children:e.jsx("a",{href:s.cta_url,target:"_blank",rel:"noreferrer",children:s.cta_label})})}),e.jsx("div",{className:"mt-10 pt-6 border-t border-white/10 text-[11px] text-slate-500 leading-relaxed",children:"Brokerage and compensation information should always be verified in writing. Nothing shared here constitutes a formal offer, agreement, or guarantee of income."})]})]})}function Qur(s){try{const t=new URL(s);if(t.hostname.includes("youtube.com")||t.hostname.includes("youtu.be")){const n=t.hostname.includes("youtu.be")?t.pathname.slice(1):t.searchParams.get("v");if(n)return`https://www.youtube.com/embed/${n}`}if(t.hostname.includes("vimeo.com")){const n=t.pathname.split("/").filter(Boolean).pop();if(n)return`https://player.vimeo.com/video/${n}`}return t.hostname.includes("loom.com")?s.replace("/share/","/embed/"):s}catch{return s}}const Jur=[{value:"text",label:"Text lesson"},{value:"checklist",label:"Checklist"},{value:"template",label:"Template / Script"},{value:"video",label:"Video / Embed"},{value:"pdf",label:"PDF / File"},{value:"link",label:"External link"},{value:"content_studio",label:"Content Studio output"},{value:"resource",label:"Existing resource"}];function c3t(){var H,V;const{kitId:s}=Di(),[t]=fc(),n=Wn(),{user:r}=vs(),a=s===void 0,{create:i,update:l}=pat(),{data:o,isLoading:c}=Frs(s),{items:d,add:u,update:h,remove:m,reorder:p}=Bdr(s),{shares:f,create:x,revoke:y}=zrs(s),{agents:v}=EE(),[b,N]=j.useState(null),[S,A]=j.useState("desktop"),[T,L]=j.useState("idle"),M=j.useRef(null);j.useEffect(()=>{a&&!b&&(async()=>{const K=t.get("seed"),Z=await i.mutateAsync({title:K?`From: ${K}`:"Untitled Kit",status:"draft"});n(`/attract/toolkit/kits/${Z.id}/edit`,{replace:!0})})()},[a]),j.useEffect(()=>{o&&N(o)},[o==null?void 0:o.id]);const I=K=>{s&&(N(Z=>({...Z,...K})),L("saving"),clearTimeout(M.current),M.current=setTimeout(async()=>{try{await l.mutateAsync({id:s,patch:K}),L("saved"),setTimeout(()=>L("idle"),1500)}catch(Z){re.error(Z.message??"Save failed"),L("idle")}},800))},R=async K=>{!s||!r||await u.mutateAsync({user_id:r.id,type:K,title:`New ${K.replace("_"," ")}`})},z=(K,Z)=>{const Q=[...d],le=K+Z;le<0||le>=Q.length||([Q[K],Q[le]]=[Q[le],Q[K]],p.mutate(Q.map(ue=>ue.id)))},$=f.filter(K=>K.status==="active");return a||!b?e.jsx("div",{className:"text-slate-500 text-sm",children:"Preparing your kit…"}):c?e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading…"}):e.jsxs("div",{children:[e.jsx(TE,{eyebrow:"Provide · Kit builder",title:b.title||"Untitled Kit",description:T==="saving"?"Saving…":T==="saved"?"Saved":`Last edited ${Gs(new Date(b.updated_at),"MMM d, h:mm a")}`,actions:e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx(U,{variant:"outline",size:"sm",asChild:!0,className:"rounded-full",children:e.jsxs(xr,{to:"/attract/toolkit/kits",children:[e.jsx(Aa,{className:"h-4 w-4 mr-1"}),"Kits"]})}),e.jsx(U,{variant:"outline",size:"sm",asChild:!0,className:"rounded-full",children:e.jsx(xr,{to:`/attract/toolkit/kits/${s}/analytics`,children:"Analytics"})}),e.jsxs(Ns,{value:b.status,onValueChange:K=>I({status:K}),children:[e.jsx(ws,{className:"w-[130px] rounded-full",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"draft",children:"Draft"}),e.jsx(et,{value:"published",children:"Published"}),e.jsx(et,{value:"archived",children:"Archived"})]})]})]})}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-12 gap-6",children:[e.jsxs("div",{className:"xl:col-span-4 space-y-4",children:[e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Kit details"}),e.jsxs("div",{className:"space-y-3 mt-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Title"}),e.jsx(xe,{value:b.title??"",onChange:K=>I({title:K.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Short description"}),e.jsx(Fs,{rows:3,value:b.description??"",onChange:K=>I({description:K.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Cover image URL"}),e.jsx(xe,{placeholder:"https://…",value:b.cover_image_url??"",onChange:K=>I({cover_image_url:K.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Audience"}),e.jsx(xe,{placeholder:"e.g. New agents",value:b.audience??"",onChange:K=>I({audience:K.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Pillar"}),e.jsxs(Ns,{value:b.pillar??"",onValueChange:K=>I({pillar:K}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Choose"})}),e.jsxs(js,{children:[e.jsx(et,{value:"produce",children:"Produce"}),e.jsx(et,{value:"influence",children:"Influence"}),e.jsx(et,{value:"provide",children:"Provide"}),e.jsx(et,{value:"connect",children:"Connect"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Tags (comma separated)"}),e.jsx(xe,{value:(b.tags??[]).join(", "),onChange:K=>I({tags:K.target.value.split(",").map(Z=>Z.trim()).filter(Boolean)})})]})]})]}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Personal welcome"}),e.jsxs("div",{className:"space-y-3 mt-3",children:[e.jsx(Fs,{rows:4,placeholder:"Write a short personal note that opens the kit.",value:b.intro_text??"",onChange:K=>I({intro_text:K.target.value})}),e.jsxs("div",{children:[e.jsx(te,{children:"Intro video URL (optional)"}),e.jsx(xe,{placeholder:"Loom/YouTube/Vimeo",value:b.intro_video_url??"",onChange:K=>I({intro_video_url:K.target.value})})]})]})]}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Call to action"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Button label"}),e.jsx(xe,{value:b.cta_label??"",onChange:K=>I({cta_label:K.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Button URL"}),e.jsx(xe,{placeholder:"https://…",value:b.cta_url??"",onChange:K=>I({cta_url:K.target.value})})]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(te,{children:"Expiration (optional)"}),e.jsx(xe,{type:"datetime-local",value:b.expires_at?b.expires_at.slice(0,16):"",onChange:K=>I({expires_at:K.target.value?new Date(K.target.value).toISOString():null})})]})]}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Share this kit"}),e.jsx(ehr,{kitId:s,agents:v,shares:$,onCreate:K=>x.mutate(K),onRevoke:K=>y.mutate(K),status:b.status})]})]}),e.jsx("div",{className:"xl:col-span-5 space-y-4",children:e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Kit sections"}),e.jsx("div",{className:"text-[13px] text-slate-600",children:"Drag order using arrows. Reorder to change how visitors experience the kit."})]}),e.jsxs(Ns,{onValueChange:K=>R(K),children:[e.jsx(ws,{className:"w-[180px]",children:e.jsx(ks,{placeholder:"+ Add item"})}),e.jsx(js,{children:Jur.map(K=>e.jsx(et,{value:K.value,children:K.label},K.value))})]})]}),e.jsxs("div",{className:"mt-4 space-y-3",children:[d.length===0&&e.jsx("div",{className:"text-center text-sm text-slate-500 py-10 border border-dashed rounded-xl",children:"No sections yet. Add your first item above."}),d.map((K,Z)=>{var Q,le;return e.jsx(we,{className:"p-4 border-slate-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("button",{className:"text-slate-400 hover:text-slate-700",onClick:()=>z(Z,-1),children:e.jsx(cp,{className:"h-4 w-4"})}),e.jsx("button",{className:"text-slate-400 hover:text-slate-700",onClick:()=>z(Z,1),children:e.jsx(ag,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Be,{variant:"outline",className:"capitalize",children:K.type.replace("_"," ")}),e.jsx(xe,{className:"flex-1",value:K.title,onChange:ue=>h.mutate({id:K.id,patch:{title:ue.target.value}})})]}),e.jsx(Fs,{rows:2,placeholder:"Short description",value:K.description??"",onChange:ue=>h.mutate({id:K.id,patch:{description:ue.target.value}})}),["video","pdf","link","resource"].includes(K.type)&&e.jsx(xe,{placeholder:"URL",value:K.url??"",onChange:ue=>h.mutate({id:K.id,patch:{url:ue.target.value}})}),["text","template"].includes(K.type)&&e.jsx(Fs,{rows:4,placeholder:"Body text or script",value:((Q=K.content)==null?void 0:Q.body)??"",onChange:ue=>h.mutate({id:K.id,patch:{content:{...K.content??{},body:ue.target.value}}})}),K.type==="checklist"&&e.jsx(Fs,{rows:5,placeholder:"One item per line",value:(((le=K.content)==null?void 0:le.items)??[]).join(` `),onChange:ue=>h.mutate({id:K.id,patch:{content:{items:ue.target.value.split(` `).map(se=>se.trim()).filter(Boolean)}}})}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-slate-600",children:[e.jsx(wn,{checked:K.allow_download,onCheckedChange:ue=>h.mutate({id:K.id,patch:{allow_download:ue}})}),"Allow download"]}),e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-slate-600",children:[e.jsx(wn,{checked:!K.is_hidden,onCheckedChange:ue=>h.mutate({id:K.id,patch:{is_hidden:!ue}})}),"Visible"]}),e.jsxs("button",{className:"ml-auto text-rose-600 text-[12px] flex items-center gap-1",onClick:()=>m.mutate(K.id),children:[e.jsx(In,{className:"h-3.5 w-3.5"}),"Delete"]})]})]})]})},K.id)})]})]})}),e.jsx("div",{className:"xl:col-span-3",children:e.jsxs(we,{className:"p-4 rounded-2xl xl:sticky xl:top-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Live preview"}),e.jsx(oa,{value:S,onValueChange:K=>A(K),children:e.jsxs(la,{className:"h-8",children:[e.jsx(Kt,{value:"desktop",className:"h-6 px-2",children:e.jsx(X2,{className:"h-3.5 w-3.5"})}),e.jsx(Kt,{value:"mobile",className:"h-6 px-2",children:e.jsx(i1,{className:"h-3.5 w-3.5"})})]})})]}),e.jsx("div",{className:S==="mobile"?"max-w-[320px] mx-auto":"",children:e.jsx(nas,{kit:b,items:d,owner:{display_name:((H=r==null?void 0:r.user_metadata)==null?void 0:H.full_name)||(r==null?void 0:r.email)||"You",avatar_url:((V=r==null?void 0:r.user_metadata)==null?void 0:V.avatar_url)??null,brokerage:null},mode:"preview"})})]})})]})]})}function ehr({kitId:s,agents:t,shares:n,onCreate:r,onRevoke:a,status:i}){const[l,o]=j.useState("general"),[c,d]=j.useState("");return i!=="published"?e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-3",children:"Publish this kit to generate share links."}):e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[e.jsxs(Ns,{value:l,onValueChange:u=>o(u),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Choose agent"})}),e.jsxs(js,{children:[e.jsx(et,{value:"general",children:"General share link"}),t.map(u=>e.jsxs(et,{value:u.id,children:[u.first_name," ",u.last_name??""]},u.id))]})]}),e.jsx(Fs,{rows:2,placeholder:"Optional personal note shown on the page",value:c,onChange:u=>d(u.target.value)}),e.jsxs(U,{size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>{r({kit_id:s,agent_id:l==="general"?null:l,personal_note:c||null}),d("")},children:[e.jsx(jd,{className:"h-4 w-4 mr-2"}),"Create share link"]})]}),e.jsxs("div",{className:"space-y-2",children:[n.length===0&&e.jsx("div",{className:"text-[12px] text-slate-500",children:"No active links yet."}),n.map(u=>{var p;const h=Brs(u.share_token),m=u.agent_id?((p=t.find(f=>f.id===u.agent_id))==null?void 0:p.first_name)??"Agent":"General";return e.jsxs("div",{className:"border rounded-lg p-2.5 text-[12.5px]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium",children:m}),e.jsx(Be,{variant:"secondary",className:"capitalize",children:u.engagement_level.replace("_"," ")})]}),e.jsx("div",{className:"text-slate-500 truncate mt-1",children:h}),e.jsxs("div",{className:"flex gap-1 mt-2",children:[e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(h),re.success("Link copied")},children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1"}),"Copy"]}),e.jsx(U,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:h,target:"_blank",rel:"noreferrer",children:[e.jsx(Sr,{className:"h-3.5 w-3.5 mr-1"}),"Open"]})}),e.jsxs(U,{size:"sm",variant:"ghost",className:"text-rose-600",onClick:()=>a(u.id),children:[e.jsx(_F,{className:"h-3.5 w-3.5 mr-1"}),"Revoke"]})]})]},u.id)})]})]})}const thr={page_view:"Views",resource_open:"Resource opens",file_download:"Downloads",video_start:"Video starts",video_complete:"Video completes",external_link_click:"Link clicks",primary_cta_click:"CTA clicks",question_submitted:"Questions",meeting_requested:"Meetings requested"};function shr(){const{kitId:s}=Di(),{data:t}=Frs(s),{shares:n}=zrs(s),{data:r=[]}=Udr(s),a=j.useMemo(()=>{const l=d=>r.filter(u=>u.event_type===d).length,o=new Set(n.filter(d=>d.agent_id).map(d=>d.agent_id)).size,c=n.filter(d=>d.first_opened_at).length;return{shares:n.length,uniqueAgents:o,viewRate:n.length?Math.round(c/n.length*100):0,engaged:n.filter(d=>["engaged","high_intent"].includes(d.engagement_level)).length,downloads:l("file_download"),ctaClicks:l("primary_cta_click"),questions:l("question_submitted"),meetings:l("meeting_requested")}},[n,r]),i=j.useMemo(()=>{const l=new Map;return r.forEach(o=>{const c=Gs(new Date(o.created_at),"MMM d");l.set(c,(l.get(c)??0)+1)}),Array.from(l.entries()).reverse().map(([o,c])=>({date:o,count:c}))},[r]);return e.jsxs("div",{children:[e.jsx(TE,{eyebrow:"Kit analytics",title:(t==null?void 0:t.title)??"Kit",description:"Which value is actually creating conversations.",actions:e.jsx(U,{variant:"outline",size:"sm",asChild:!0,className:"rounded-full",children:e.jsxs(xr,{to:`/attract/toolkit/kits/${s}/edit`,children:[e.jsx(Aa,{className:"h-4 w-4 mr-1"}),"Edit"]})})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mb-6",children:[e.jsx(xT,{label:"Shares",value:a.shares,icon:xa,tone:"violet"}),e.jsx(xT,{label:"Unique agents",value:a.uniqueAgents,icon:xa,tone:"indigo"}),e.jsx(xT,{label:"View rate",value:`${a.viewRate}%`,icon:xa,tone:"teal"}),e.jsx(xT,{label:"Engaged",value:a.engaged,icon:Ch,tone:"emerald"}),e.jsx(xT,{label:"Downloads",value:a.downloads,icon:pi,tone:"orange"}),e.jsx(xT,{label:"CTA clicks",value:a.ctaClicks,icon:Ch,tone:"rose"}),e.jsx(xT,{label:"Questions",value:a.questions,icon:vu,tone:"violet"}),e.jsx(xT,{label:"Meetings",value:a.meetings,icon:ch,tone:"indigo"})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-6",children:[e.jsxs(we,{className:"p-5 rounded-2xl xl:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Engagement over time"}),e.jsx("div",{className:"h-64",children:e.jsx(oj,{width:"100%",height:"100%",children:e.jsxs(Att,{data:i,children:[e.jsx($7,{strokeDasharray:"3 3",stroke:"#eee"}),e.jsx(wb,{dataKey:"date",fontSize:11}),e.jsx(jb,{fontSize:11,allowDecimals:!1}),e.jsx(Tg,{}),e.jsx(gP,{type:"monotone",dataKey:"count",stroke:"#7c3aed",strokeWidth:2})]})})})]}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"By event type"}),e.jsx("div",{className:"space-y-2",children:Object.entries(thr).map(([l,o])=>{const c=r.filter(d=>d.event_type===l).length;return e.jsxs("div",{className:"flex justify-between text-[13px]",children:[e.jsx("span",{className:"text-slate-600",children:o}),e.jsx("span",{className:"font-semibold tabular-nums",children:c})]},l)})})]})]}),e.jsxs(we,{className:"p-5 rounded-2xl mt-6",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-3",children:"Recipients"}),e.jsxs("div",{className:"space-y-2",children:[n.length===0&&e.jsx("div",{className:"text-sm text-slate-500",children:"No one has been shared this kit yet."}),n.map(l=>e.jsxs("div",{className:"flex items-center justify-between border-b py-2 text-[13px]",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:l.agent_id?"Personalized":"General link"}),e.jsxs("div",{className:"text-slate-500 text-[11.5px]",children:["Created ",Gs(new Date(l.created_at),"MMM d")," · ",l.open_count," opens",l.last_opened_at&&` · last opened ${Gs(new Date(l.last_opened_at),"MMM d")}`]})]}),e.jsx(Be,{variant:"secondary",className:"capitalize",children:l.engagement_level.replace("_"," ")})]},l.id))]})]})]})}function xT({label:s,value:t,icon:n,tone:r}){const a={violet:"text-violet-700 bg-violet-50",indigo:"text-indigo-700 bg-indigo-50",teal:"text-teal-700 bg-teal-50",emerald:"text-emerald-700 bg-emerald-50",orange:"text-orange-700 bg-orange-50",rose:"text-rose-700 bg-rose-50"};return e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:`h-8 w-8 rounded-lg grid place-items-center ${a[r]}`,children:e.jsx(n,{className:"h-4 w-4"})}),e.jsx("div",{className:"mt-2 text-[22px] font-semibold tabular-nums",children:t}),e.jsx("div",{className:"text-[11.5px] text-slate-500",children:s})]})}function nhr(){const{data:s=[],isLoading:t}=qdr(),n=$dr(),r=Wn(),a=async i=>{try{const l=await n.mutateAsync(i);re.success("Added to your drafts"),r(`/attract/toolkit/kits/${l}/edit`)}catch(l){re.error(l.message??"Could not clone template")}};return e.jsxs("div",{children:[e.jsx(TE,{eyebrow:"Starter library",title:"LevelUp Starter Kits",description:"Ten proven relationship-first kits. Duplicate any of them into your workspace and personalize the parts that matter.",actions:e.jsx(U,{variant:"outline",asChild:!0,className:"rounded-full",children:e.jsxs(xr,{to:"/attract/toolkit/kits",children:[e.jsx(Aa,{className:"h-4 w-4 mr-2"}),"Back to my kits"]})})}),t&&e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading templates…"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:s.map(i=>{var l;return e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200 bg-white flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10.5px] uppercase tracking-widest text-violet-700 font-semibold",children:[e.jsx(cn,{className:"h-3.5 w-3.5"})," Starter kit"]}),e.jsx("div",{className:"mt-2 text-[17px] font-semibold text-slate-900",children:i.title}),i.audience&&e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["For ",i.audience]}),e.jsx("p",{className:"text-[13px] text-slate-600 mt-2 line-clamp-3",children:i.description}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-1",children:[i.pillar&&e.jsx(Be,{variant:"outline",className:"capitalize",children:i.pillar}),(i.tags??[]).slice(0,4).map(o=>e.jsxs(Be,{variant:"secondary",className:"text-[10.5px]",children:["#",o]},o))]}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-3",children:[((l=i.suggested_items)==null?void 0:l.length)??0," suggested sections"]}),e.jsxs(U,{className:"mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>a(i.id),children:[e.jsx(Lg,{className:"h-4 w-4 mr-2"}),"Use this kit"]})]},i.id)})})]})}const rhr=q,ahr=[...HA,s8e],ihr={hot:Xd,warm:eN,cold:$w},nZ=({label:s})=>e.jsxs("span",{className:"text-slate-400 italic",children:["Not recorded",s?` — add ${s}`:""]}),yT=s=>[s.first_name,s.last_name].filter(Boolean).join(" "),ohr=s=>{var t,n;return`${((t=s.first_name)==null?void 0:t[0])??""}${((n=s.last_name)==null?void 0:n[0])??""}`.toUpperCase()||"?"};function LB({label:s,children:t}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wider text-slate-400 font-semibold",children:s}),e.jsx("div",{className:"text-[13.5px] text-slate-800 mt-0.5 break-words",children:t})]})}const lhr={touch:"bg-violet-500",note:"bg-slate-400",stage_change:"bg-indigo-500",follow_up_created:"bg-amber-400",follow_up_completed:"bg-emerald-500",follow_up_missed:"bg-rose-500",kit_shared:"bg-teal-500",kit_engagement:"bg-teal-400",event_invited:"bg-indigo-300",event_registered:"bg-indigo-400",event_attended:"bg-emerald-500",event_no_show:"bg-rose-400",event_note:"bg-slate-400",score:"bg-green-500",temperature:"bg-orange-400",activity:"bg-slate-300"};function chr(){const{agentId:s}=Di(),t=Wn(),{item:n,timeline:r,valueShared:a,nextKit:i,isLoading:l,error:o,refetch:c}=Bcr(s),{data:d=[]}=JIe(),{upsertAgent:u,moveStage:h}=EE(),{followUps:m,complete:p}=t8e(),f=qcr(),{gmailEmail:x}=Ax(),[y,v]=j.useState("all"),[b,N]=j.useState(!1),[S,A]=j.useState(!1),[T,L]=j.useState("call"),[M,I]=j.useState(""),[R,z]=j.useState(""),[$,H]=j.useState(!1),[V,K]=j.useState(""),[Z,Q]=j.useState(!1),[le,ue]=j.useState(""),[se,ne]=j.useState(new Date(Date.now()+3*864e5).toISOString().slice(0,10)),[ie,ce]=j.useState(null),[je,be]=j.useState(!1),he=j.useMemo(()=>d.filter(Ne=>Ne.agent_id===s&&Ne.status==="open").sort((Ne,$e)=>$e.rank_score-Ne.rank_score),[d,s]),ge=j.useMemo(()=>m.filter(Ne=>Ne.agent_id===s),[m,s]),ke=j.useMemo(()=>{const Ne=V4t.find($e=>$e.key===y);return!Ne||!Ne.kinds.length?r:r.filter($e=>Ne.kinds.includes($e.kind))},[r,y]);if(l)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(xn,{className:"h-8 w-40"}),e.jsx(xn,{className:"h-40 w-full rounded-2xl"}),e.jsx(xn,{className:"h-64 w-full rounded-2xl"})]});if(o)return e.jsxs(we,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"We couldn't load this relationship."}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:o.message}),e.jsxs(U,{className:"rounded-full mt-4",onClick:()=>c(),children:[e.jsx(no,{className:"h-4 w-4 mr-2"})," Try again"]})]});if(!n)return e.jsxs(we,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Agent not found"}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:"This relationship may have been removed from your pipeline."}),e.jsx(U,{className:"rounded-full mt-4",onClick:()=>t("/attract/agents"),children:"Back to relationships"})]});const Te=n.agent,Me=n.signals,Oe=ihr[Te.temperature??""]??eN,Se=()=>{f.mutate({agent_id:Te.id,activity_type:T,title:M||`${T.replace(/_/g," ")} with ${yT(Te)}`,description:R||void 0},{onSuccess:()=>{N(!1),I(""),z("")}})},Qe=async()=>{var $e;if(!V.trim())return;const Ne=[($e=Te.notes)==null?void 0:$e.trim(),`[${new Date().toLocaleDateString()}] ${V.trim()}`].filter(Boolean).join(` `);u.mutate({id:Te.id,first_name:Te.first_name,notes:Ne},{onSuccess:()=>{H(!1),K(""),c()}}),f.mutate({agent_id:Te.id,activity_type:"note",title:"Note added",description:V.trim()})},Ae=async()=>{if(!le.trim()){re.error("Give the follow-up a title");return}if(ge.find(qe=>!qe.completed_at&&qe.title.trim().toLowerCase()===le.trim().toLowerCase())){re.error("An open follow-up with that title already exists");return}const{data:$e}=await q.auth.getUser(),{error:Ve}=await rhr.from("attract_follow_ups").insert({user_id:$e.user.id,agent_id:Te.id,title:le.trim(),due_at:new Date(`${se}T12:00:00`).toISOString(),touch_type:"call",priority:"medium"});if(Ve){re.error(Ve.message);return}re.success("Follow-up created"),Q(!1),ue(""),c()},Fe=()=>{ie&&(window.open(ie.href,"_self"),f.mutate({agent_id:Te.id,activity_type:ie.kind,title:`${ie.kind==="call"?"Called":ie.kind==="text"?"Texted":"Emailed"} ${yT(Te)}`}),ce(null))};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[12px] text-slate-500",children:[e.jsx(xr,{to:"/attract",className:"hover:text-violet-700",children:"Attract"}),e.jsx(gi,{className:"h-3 w-3"}),e.jsx(xr,{to:"/attract/agents",className:"hover:text-violet-700",children:"Relationships"}),e.jsx(gi,{className:"h-3 w-3"}),e.jsx("span",{className:"text-slate-800 font-medium truncate",children:yT(Te)})]}),e.jsxs(we,{className:"rounded-2xl border-slate-200/70 overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-[#0B0F1E] via-[#141a33] to-[#1d1b4b] p-5 sm:p-6 text-white",children:[e.jsxs(U,{variant:"ghost",size:"sm",className:"text-slate-300 hover:text-white -ml-2 mb-3 rounded-full",onClick:()=>t(-1),children:[e.jsx(Aa,{className:"h-3.5 w-3.5 mr-1.5"})," Back"]}),e.jsxs("div",{className:"flex items-start gap-4 flex-wrap",children:[Te.photo_url?e.jsx("img",{src:Te.photo_url,alt:`${yT(Te)} headshot`,className:"h-16 w-16 rounded-2xl object-cover ring-2 ring-white/20"}):e.jsx("div",{className:"h-16 w-16 rounded-2xl bg-gradient-to-br from-violet-500 to-indigo-600 grid place-items-center text-xl font-semibold ring-2 ring-white/10",children:ohr(Te)}),e.jsxs("div",{className:"flex-1 min-w-[220px]",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:yT(Te)}),e.jsxs("div",{className:"text-[13px] text-slate-300 mt-1 flex flex-wrap items-center gap-x-2 gap-y-1",children:[e.jsx("span",{children:Te.brokerage||"Brokerage not recorded"}),e.jsx("span",{className:"opacity-40",children:"·"}),e.jsx("span",{children:[Te.city,Te.state].filter(Boolean).join(", ")||"Market not recorded"}),Te.is_demo&&e.jsx(Be,{className:"bg-amber-400/20 text-amber-200 border-transparent rounded-full",children:"Demo record"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-3",children:[e.jsx(Be,{className:"rounded-full bg-white/10 text-white border-transparent",children:Nrs(Te.stage)}),e.jsxs(Be,{className:"rounded-full bg-white/10 text-white border-transparent capitalize inline-flex items-center gap-1",children:[e.jsx(Oe,{className:"h-3 w-3"})," ",Te.temperature??"temperature unset"]}),e.jsx(dat,{score:n.score,className:"bg-white/10 text-white ring-white/20"}),(Te.tags??[]).map(Ne=>e.jsx(Be,{variant:"outline",className:"rounded-full bg-transparent text-slate-200 border-white/20",children:Ne},Ne))]})]}),e.jsxs("div",{className:"text-[12px] text-slate-300 space-y-1 min-w-[190px]",children:[e.jsx("div",{children:Te.email?e.jsx("a",{className:"hover:text-white underline decoration-white/30",href:`mailto:${Te.email}`,children:Te.email}):"No email on file"}),e.jsx("div",{children:Te.phone?e.jsx("a",{className:"hover:text-white underline decoration-white/30",href:`tel:${Te.phone}`,children:Te.phone}):"No phone on file"}),e.jsxs("div",{children:["Last meaningful touch: ",Me.lastTouchAt?`${new Date(Me.lastTouchAt).toLocaleDateString()} (${Me.daysSinceTouch}d ago)`:"never logged"]}),e.jsxs("div",{children:["Next follow-up: ",Te.next_follow_up_at?new Date(Te.next_follow_up_at).toLocaleDateString():"none scheduled"]}),e.jsxs("div",{children:["Source: ",Te.source||"not recorded"," · Owner: ",Te.relationship_owner||"you"]})]})]})]}),e.jsxs("div",{className:"p-3 sm:p-4 bg-white flex flex-wrap gap-2",children:[e.jsxs(U,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>A(!0),children:[e.jsx(ri,{className:"h-3.5 w-3.5 mr-1.5"})," Edit contact"]}),e.jsxs(zs,{open:b,onOpenChange:N,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{size:"sm",className:"rounded-full btn-primary text-white",children:[e.jsx(zr,{className:"h-3.5 w-3.5 mr-1.5"})," Log touch"]})}),e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Log a conversation"}),e.jsx(Pr,{children:"This records what already happened — it does not send anything."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Type"}),e.jsxs(Ns,{value:T,onValueChange:L,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:["call","text","email","dm","meeting","note"].map(Ne=>e.jsx(et,{value:Ne,className:"capitalize",children:Ne},Ne))})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Title"}),e.jsx(xe,{value:M,onChange:Ne=>I(Ne.target.value),placeholder:`Call with ${Te.first_name}`})]}),e.jsxs("div",{children:[e.jsx(te,{children:"What happened"}),e.jsx(Fs,{rows:4,value:R,onChange:Ne=>z(Ne.target.value)})]})]}),e.jsx(Mr,{children:e.jsx(U,{className:"rounded-full btn-primary text-white",onClick:Se,disabled:f.isPending,children:"Log it"})})]})]}),e.jsxs(zs,{open:$,onOpenChange:H,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{size:"sm",variant:"outline",className:"rounded-full",children:[e.jsx(zF,{className:"h-3.5 w-3.5 mr-1.5"})," Add note"]})}),e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Add a relationship note"})}),e.jsx(Fs,{rows:5,value:V,onChange:Ne=>K(Ne.target.value),placeholder:"What did you learn about them?"}),e.jsx(Mr,{children:e.jsx(U,{className:"rounded-full btn-primary text-white",onClick:Qe,children:"Save note"})})]})]}),e.jsxs(U,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Te.phone,onClick:()=>Te.phone&&ce({kind:"call",href:`tel:${Te.phone}`}),children:[e.jsx(ba,{className:"h-3.5 w-3.5 mr-1.5"})," Call"]}),e.jsxs(U,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Te.phone,onClick:()=>Te.phone&&ce({kind:"text",href:`sms:${Te.phone}`}),children:[e.jsx(Ki,{className:"h-3.5 w-3.5 mr-1.5"})," Text"]}),e.jsxs(U,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Te.email,onClick:()=>Te.email&&be(!0),children:[e.jsx(ln,{className:"h-3.5 w-3.5 mr-1.5"})," Email"]}),e.jsx(U,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(xr,{to:"/attract/toolkit/kits",children:[e.jsx(tj,{className:"h-3.5 w-3.5 mr-1.5"})," Share kit"]})}),e.jsx(U,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(xr,{to:"/attract/toolkit/events",children:[e.jsx(sv,{className:"h-3.5 w-3.5 mr-1.5"})," Invite to event"]})}),e.jsxs(zs,{open:Z,onOpenChange:Q,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{size:"sm",variant:"outline",className:"rounded-full",children:[e.jsx(Yr,{className:"h-3.5 w-3.5 mr-1.5"})," Create follow-up"]})}),e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Create a follow-up"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"What will you do?"}),e.jsx(xe,{value:le,onChange:Ne=>ue(Ne.target.value),placeholder:"Call about their Q3 goals"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Due"}),e.jsx(xe,{type:"date",value:se,onChange:Ne=>ne(Ne.target.value)})]})]}),e.jsx(Mr,{children:e.jsx(U,{className:"rounded-full btn-primary text-white",onClick:Ae,children:"Create"})})]})]}),e.jsxs(Ns,{value:GA(Te.stage).key,onValueChange:Ne=>{const $e=hat(Ne);$e!==Te.stage&&h.mutate({id:Te.id,to_stage:$e,from_stage:Te.stage})},children:[e.jsxs(ws,{className:"w-[230px] h-9 rounded-full text-[13px]","aria-label":"Change relationship stage",children:[e.jsx(S4,{className:"h-3.5 w-3.5 mr-1.5 opacity-60"}),e.jsx(ks,{})]}),e.jsx(js,{children:ahr.map(Ne=>e.jsx(et,{value:Ne.key,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{background:Ne.color}}),Ne.label]})},Ne.key))})]})]})]}),e.jsx(zs,{open:!!ie,onOpenChange:Ne=>!Ne&&ce(null),children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsxs($s,{children:["Open your ",(ie==null?void 0:ie.kind)==="email"?"email app":(ie==null?void 0:ie.kind)==="text"?"messaging app":"phone app","?"]}),e.jsx(Pr,{children:"Attract will open your own device app so you send it personally. Nothing is sent by LevelUp. We'll log this as a touch."})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"ghost",className:"rounded-full",onClick:()=>ce(null),children:"Cancel"}),e.jsx(U,{className:"rounded-full btn-primary text-white",onClick:Fe,children:"Continue"})]})]})}),e.jsxs(oa,{defaultValue:"overview",children:[e.jsx(la,{className:"rounded-full bg-white border border-slate-200 p-1 flex-wrap h-auto",children:["overview","timeline","value","events","followups","notes"].map(Ne=>e.jsx(Kt,{value:Ne,className:"rounded-full text-[13px] capitalize data-[state=active]:bg-violet-600 data-[state=active]:text-white",children:Ne==="value"?"Value shared":Ne==="followups"?"Follow-ups":Ne==="notes"?"Notes & insights":Ne},Ne))}),e.jsxs(Zt,{value:"overview",className:"mt-5 space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-5",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-5",children:[e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-600 mb-3",children:"Next best relationship touch"}),he[0]?e.jsx(ITe,{rec:he[0],agentName:yT(Te),agentStage:Te.stage,showAgentLink:!1,className:"border-0 shadow-none"}):e.jsx("div",{className:"text-[13.5px] text-slate-500",children:"No open recommendation right now. Recommendations appear when real signals exist — a kit opened, an event attended, an overdue commitment, or silence beyond your cadence."})]}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-3",children:"What we actually know"}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsx(LB,{label:"Goals",children:Te.goals||e.jsx(nZ,{label:"their goals"})}),e.jsx(LB,{label:"Challenges",children:Te.challenges||e.jsx(nZ,{label:"their challenges"})}),e.jsx(LB,{label:"Interests",children:Te.interests||e.jsx(nZ,{label:"interests"})}),e.jsx(LB,{label:"Production context",children:Te.production_context||e.jsx(nZ,{label:"production context"})}),e.jsx(LB,{label:"Primary pillar",children:Te.primary_pillar?e.jsx("span",{className:"capitalize",children:Te.primary_pillar}):e.jsx(nZ,{label:"a pillar"})}),e.jsx(LB,{label:"Added to pipeline",children:new Date(Te.created_at).toLocaleDateString()})]})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-4 gap-3",children:[{label:"Touches (90d)",value:Me.touches90},{label:"Kits shared",value:Me.shares.length},{label:"Kit opens",value:Me.totalKitOpens},{label:"Events attended",value:Me.attended}].map(Ne=>e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:Ne.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:Ne.label})]},Ne.label))})]}),e.jsxs(we,{className:"p-5 rounded-2xl h-fit",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-3",children:"Relationship health"}),e.jsx(brs,{score:n.score})]})]}),he.length>1&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500",children:"Other open recommendations"}),he.slice(1).map(Ne=>e.jsx(ITe,{rec:Ne,agentName:yT(Te),showAgentLink:!1,compact:!0},Ne.id))]})]}),e.jsx(Zt,{value:"timeline",className:"mt-5",children:e.jsxs(we,{className:"p-4 sm:p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap mb-4",children:[e.jsx("div",{className:"flex gap-1.5 flex-wrap",children:V4t.map(Ne=>e.jsx("button",{onClick:()=>v(Ne.key),className:Mt("rounded-full px-3 py-1.5 text-[12px] font-medium transition-colors",y===Ne.key?"bg-violet-600 text-white":"bg-slate-100 text-slate-600 hover:bg-slate-200"),children:Ne.label},Ne.key))}),e.jsxs(U,{size:"sm",className:"rounded-full btn-primary text-white",onClick:()=>N(!0),children:[e.jsx(zr,{className:"h-3.5 w-3.5 mr-1.5"})," Log something"]})]}),ke.length?e.jsxs("ol",{className:"relative pl-5 sm:pl-6",children:[e.jsx("span",{"aria-hidden":!0,className:"absolute left-1.5 top-1 bottom-1 w-px bg-slate-200"}),ke.map(Ne=>e.jsxs("li",{className:"relative pb-5",children:[e.jsx("span",{"aria-hidden":!0,className:Mt("absolute -left-[15px] sm:-left-[18px] top-1.5 h-2.5 w-2.5 rounded-full ring-2 ring-white",lhr[Ne.kind]??"bg-slate-300")}),e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:Ne.title}),Ne.detail&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5 whitespace-pre-wrap",children:Ne.detail}),e.jsxs("div",{className:"text-[11px] text-slate-400 mt-1",children:[new Date(Ne.at).toLocaleString()," · ",e.jsx("span",{className:"capitalize",children:Ne.kind.replace(/_/g," ")})]})]},Ne.id))]}):e.jsx("div",{className:"py-10 text-center text-[13.5px] text-slate-500",children:"Nothing in this view yet. Log a conversation to start the history."})]})}),e.jsxs(Zt,{value:"value",className:"mt-5 space-y-4",children:[i&&e.jsxs(we,{className:"p-4 rounded-2xl bg-gradient-to-r from-teal-50 to-emerald-50 border-teal-100",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wider font-semibold text-teal-700",children:"Suggested next kit"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 mt-1",children:i.kit.title}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5",children:i.why}),e.jsx(U,{size:"sm",className:"rounded-full mt-3 btn-primary text-white",asChild:!0,children:e.jsx(xr,{to:"/attract/toolkit/kits",children:"Open Resource Kits"})})]}),a.length?a.map(Ne=>e.jsxs(we,{className:"p-4 sm:p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:Ne.kitTitle}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["Sent ",new Date(Ne.share.created_at).toLocaleDateString()," ·",Ne.firstViewedAt?` first viewed ${new Date(Ne.firstViewedAt).toLocaleDateString()}`:" never viewed",Ne.lastViewedAt?` · last viewed ${new Date(Ne.lastViewedAt).toLocaleDateString()}`:""]})]}),e.jsx(Be,{variant:"outline",className:Mt("rounded-full border-transparent ring-1",Ne.classification==="High Intent"?"bg-rose-50 text-rose-700 ring-rose-200":Ne.classification==="Engaged"?"bg-teal-50 text-teal-700 ring-teal-200":Ne.classification==="Viewed"?"bg-amber-50 text-amber-700 ring-amber-200":"bg-slate-50 text-slate-600 ring-slate-200"),children:Ne.classification})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-5 gap-3 mt-4",children:[["Visits",Ne.visits],["Downloads",Ne.downloads],["Link clicks",Ne.ctaClicks],["Questions",Ne.questions],["Meeting asks",Ne.meetingRequests]].map(([$e,Ve])=>e.jsxs("div",{className:"rounded-xl bg-slate-50 p-2.5",children:[e.jsx("div",{className:"text-[17px] font-semibold tabular-nums text-slate-900",children:Ve}),e.jsx("div",{className:"text-[10.5px] text-slate-500",children:$e})]},$e))}),e.jsxs("div",{className:"mt-3 text-[12.5px] text-slate-600 space-y-1",children:[e.jsxs("div",{children:["Link status: ",e.jsx("span",{className:"capitalize font-medium",children:Ne.share.status})]}),e.jsxs("div",{children:["Follow-up after sharing: ",Ne.followUp?`${Ne.followUp.title}${Ne.followUp.completed_at?" (completed)":" (open)"}`:"none created"]}),e.jsxs("div",{children:["Stage movement after sharing: ",Ne.stageAdvancedAfter?`moved to ${Ne.stageAdvancedAfter.to_stage.replace(/_/g," ")} on ${new Date(Ne.stageAdvancedAfter.created_at).toLocaleDateString()}`:"no stage movement yet"]})]}),e.jsx(U,{size:"sm",variant:"outline",className:"rounded-full mt-3",asChild:!0,children:e.jsxs("a",{href:Ne.shareUrl,target:"_blank",rel:"noreferrer",children:["Open share link ",e.jsx(Sr,{className:"h-3.5 w-3.5 ml-1.5"})]})})]},Ne.share.id)):e.jsxs(we,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Nothing shared yet"}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:"Value first is how this whole system works. Share a Resource Kit to begin."})]})]}),e.jsx(Zt,{value:"events",className:"mt-5 space-y-3",children:Me.attendees.length?Me.attendees.map(Ne=>e.jsx(we,{className:"p-4 rounded-2xl",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx(xr,{to:`/attract/events/${Ne.event_id}`,className:"text-[14.5px] font-semibold text-slate-900 hover:text-violet-700",children:"View event"}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:[Ne.invited_at&&`Invited ${new Date(Ne.invited_at).toLocaleDateString()} · `,Ne.registered_at?`Registered ${new Date(Ne.registered_at).toLocaleDateString()}`:"Not registered",Ne.checked_in_at&&` · Attended ${new Date(Ne.checked_in_at).toLocaleDateString()}`,Ne.no_show_at&&" · No-show"]})]}),e.jsx(Be,{variant:"outline",className:"rounded-full capitalize",children:Ne.followup_status?`follow-up ${Ne.followup_status}`:Ne.status??"invited"})]})},Ne.id)):e.jsxs(we,{className:"p-8 rounded-2xl text-center",children:[e.jsx(zk,{className:"h-6 w-6 mx-auto text-slate-400 mb-2"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Never invited to an event"}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:"Events are the fastest way to deepen a relationship."}),e.jsx(U,{size:"sm",className:"rounded-full mt-4 btn-primary text-white",asChild:!0,children:e.jsx(xr,{to:"/attract/toolkit/events",children:"See your events"})})]})}),e.jsx(Zt,{value:"followups",className:"mt-5 space-y-3",children:ge.length?ge.map(Ne=>{const $e=!Ne.completed_at&&Ne.due_at&&new Date(Ne.due_at)p.mutate(Ne.id),children:[e.jsx(zr,{className:"h-3.5 w-3.5 mr-1.5"})," Complete"]})]},Ne.id)}):e.jsxs(we,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"No follow-ups yet"}),e.jsx(U,{size:"sm",className:"rounded-full mt-4 btn-primary text-white",onClick:()=>Q(!0),children:"Create one"})]})}),e.jsxs(Zt,{value:"notes",className:"mt-5 space-y-4",children:[e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500",children:"Your notes"}),e.jsx(U,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>H(!0),children:"Add note"})]}),Te.notes?e.jsx("div",{className:"text-[13.5px] text-slate-700 whitespace-pre-wrap",children:Te.notes}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"No notes recorded yet."})]}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-2",children:"What the data says"}),e.jsx("ul",{className:"text-[13px] text-slate-700 space-y-1.5 list-disc pl-4",children:[...n.score.positives.map(Ne=>`Strength: ${Ne}`),...n.score.negatives.map(Ne=>`Risk: ${Ne}`),...n.score.improvements.map(Ne=>`Next: ${Ne}`)].map((Ne,$e)=>e.jsx("li",{children:Ne},$e))})]})]})]}),e.jsx(Lrs,{agent:Te,open:S,onOpenChange:A,onDeleted:()=>t("/attract/agents")}),Te.email&&e.jsx(wS,{open:je,onOpenChange:be,contact:{id:Te.id,first_name:Te.preferred_name||Te.first_name,last_name:Te.last_name||"",email:Te.email},gmailEmail:x,sendSource:"attract",logTouchpoint:!1,onSendComplete:()=>{f.mutate({agent_id:Te.id,activity_type:"email",title:`Emailed ${yT(Te)}`})}})]})}const dhr=[{key:"all",label:"Everything"},{key:"high_intent",label:"High intent"},{key:"resource_follow_up",label:"Value shared"},{key:"event_follow_up",label:"Events"},{key:"commitment",label:"Commitments"},{key:"silence",label:"Going quiet"},{key:"stage",label:"Stage momentum"},{key:"new_relationship",label:"New connections"}];function uhr(){const{intel:s,byId:t,isLoading:n,error:r,refetch:a}=CW(),{data:i=[],isLoading:l}=JIe(),o=e8e();uat();const[c,d]=j.useState(""),[u,h]=j.useState("all"),[m,p]=j.useState("open"),f=v=>{var N;const b=(N=t.get(v))==null?void 0:N.agent;return b?[b.first_name,b.last_name].filter(Boolean).join(" "):"Unknown agent"},x=j.useMemo(()=>{const v=Date.now();return i.filter(b=>m==="open"?b.status==="open"||b.status==="snoozed"&&b.snoozed_until&&+new Date(b.snoozed_until)<=v:m==="snoozed"?b.status==="snoozed":m==="done"?b.status==="completed":m==="dismissed"?b.status==="dismissed":!0).filter(b=>u==="all"||b.signal_group===u).filter(b=>{if(!c.trim())return!0;const N=c.toLowerCase();return f(b.agent_id).toLowerCase().includes(N)||b.title.toLowerCase().includes(N)||(b.reasons??[]).join(" ").toLowerCase().includes(N)}).sort((b,N)=>N.rank_score-b.rank_score)},[i,m,u,c,t]),y=j.useMemo(()=>{const v=i.filter(b=>b.status==="open");return{open:v.length,urgent:v.filter(b=>b.priority==="urgent").length,highIntent:v.filter(b=>b.signal_group==="high_intent").length,overdue:v.filter(b=>b.suggested_due_at&&+new Date(b.suggested_due_at)e.jsx(xn,{className:"h-28 w-full rounded-2xl"},v))}):r?e.jsxs(we,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"We couldn't load your opportunities."}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:r.message}),e.jsxs(U,{className:"rounded-full mt-4",onClick:()=>a(),children:[e.jsx(no,{className:"h-4 w-4 mr-2"})," Try again"]})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-end justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Relationship Intelligence"}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-slate-900 mt-0.5",children:"Who needs attention"}),e.jsx("p",{className:"text-[13.5px] text-slate-500 mt-1 max-w-2xl",children:"Ranked by real signals only — value they engaged with, events they attended, commitments you made, and silence past your cadence. Nothing here is invented."})]}),e.jsxs(U,{variant:"outline",className:"rounded-full",onClick:()=>o.mutate(s),disabled:o.isPending,children:[e.jsx(no,{className:Mt("h-3.5 w-3.5 mr-1.5",o.isPending&&"animate-spin")})," Recalculate"]})]}),e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[{label:"Open recommendations",value:y.open},{label:"Urgent",value:y.urgent},{label:"High intent signals",value:y.highIntent},{label:"Past suggested date",value:y.overdue}].map(v=>e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:v.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:v.label})]},v.label))}),e.jsxs(we,{className:"p-3 rounded-2xl flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-[220px]",children:[e.jsx(Fr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(xe,{value:c,onChange:v=>d(v.target.value),placeholder:"Search agents or reasons",className:"pl-9 rounded-full h-9","aria-label":"Search recommendations"})]}),e.jsxs(Ns,{value:u,onValueChange:h,children:[e.jsxs(ws,{className:"w-[190px] h-9 rounded-full text-[13px]",children:[e.jsx(K2,{className:"h-3.5 w-3.5 mr-1.5 opacity-60"}),e.jsx(ks,{})]}),e.jsx(js,{children:dhr.map(v=>e.jsx(et,{value:v.key,children:v.label},v.key))})]}),e.jsxs(Ns,{value:m,onValueChange:p,children:[e.jsx(ws,{className:"w-[150px] h-9 rounded-full text-[13px]",children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"open",children:"Needs action"}),e.jsx(et,{value:"snoozed",children:"Snoozed"}),e.jsx(et,{value:"done",children:"Completed"}),e.jsx(et,{value:"dismissed",children:"Dismissed"}),e.jsx(et,{value:"all",children:"All"})]})]})]}),x.length?e.jsx("div",{className:"space-y-3",children:x.map(v=>{var b;return e.jsx(ITe,{rec:v,agentName:f(v.agent_id),agentStage:(b=t.get(v.agent_id))==null?void 0:b.agent.stage},v.id)})}):i.length?e.jsx(Gcr,{label:"Nothing matches this view. Try switching the filter."}):e.jsxs(we,{className:"p-10 rounded-2xl text-center",children:[e.jsx(cn,{className:"h-6 w-6 mx-auto text-violet-500 mb-2"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"No recommendations yet"}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1 max-w-md mx-auto",children:"Attract only recommends what it can prove. Add agents to your pipeline, share a Resource Kit, or invite someone to an event — real signals will show up here."}),e.jsxs("div",{className:"flex gap-2 justify-center mt-4",children:[e.jsx(U,{className:"rounded-full btn-primary text-white",asChild:!0,children:e.jsx(xr,{to:"/attract/agents",children:"Open pipeline"})}),e.jsx(U,{variant:"outline",className:"rounded-full",asChild:!0,children:e.jsx(xr,{to:"/attract/toolkit/kits",children:"Share a kit"})})]})]}),!!x.length&&e.jsxs("div",{className:"text-[11.5px] text-slate-400",children:["Showing ",x.length," of ",i.length," tracked recommendations · grouped signals: ",[...new Set(x.map(v=>wrs(v.signal_group)))].join(", ")]})]})}const dBe=s=>[s.first_name,s.last_name].filter(Boolean).join(" ");function hhr(s=new Date){const t=new Date(s),n=t.getDay(),r=n===0?-6:1-n;return t.setDate(t.getDate()+r),t.setHours(0,0,0,0),t}function mhr(s,t,n=new Date){const r=hhr(n),a=new Date(r.getTime()+6*864e5),i=new Date(n.getTime()-7*864e5),c=s.filter(M=>M.primary).slice().sort((M,I)=>I.primary.rank_score-M.primary.rank_score||M.score.score-I.score.score).slice(0,5).map((M,I)=>({agent_id:M.agent.id,agent_name:dBe(M.agent),rank:I+1,reason:M.primary.reasons.join(" · "),channel:M.primary.channel,draft_message:M.primary.draft_message,score:M.score.score,stage:M.agent.stage})),d=M=>s.map(I=>{const R=M(I);return R?{agent_id:I.agent.id,agent_name:dBe(I.agent),detail:R}:null}).filter(Boolean).slice(0,8),u=d(M=>M.signals.meetingRequests>0||M.signals.questions>0||M.signals.highIntentShares.some(I=>I.engagement_level==="high_intent")?`${M.signals.meetingRequests} meeting request(s), ${M.signals.questions} question(s), ${M.signals.totalKitOpens} kit open(s)`:null),h=d(M=>M.recommendations.some(I=>I.rec_key==="renewed_interest")?"Came back to a kit you shared after going quiet":null),m=d(M=>M.signals.overdueFollowUps.length?`${M.signals.overdueFollowUps.length} overdue follow-up(s) — oldest: ${M.signals.overdueFollowUps[0].title}`:null),p=d(M=>M.signals.daysSinceTouch!==null&&M.signals.daysSinceTouch>60?`${M.signals.daysSinceTouch} days since a real conversation`:null),f=t.shares.filter(M=>new Date(M.created_at)>=i),x={shares:f.length,opened:t.shares.filter(M=>M.first_opened_at&&new Date(M.first_opened_at)>=i).length,engaged:t.shares.filter(M=>M.engagement_level==="engaged").length,high_intent:t.shares.filter(M=>M.engagement_level==="high_intent").length,downloads:t.kitEvents.filter(M=>M.event_type==="file_download"&&new Date(M.created_at)>=i).length,questions:t.kitEvents.filter(M=>M.event_type==="question_submitted"&&new Date(M.created_at)>=i).length},y={invited:t.attendees.filter(M=>M.invited_at&&new Date(M.invited_at)>=i).length,registered:t.attendees.filter(M=>M.registered_at&&new Date(M.registered_at)>=i).length,attended:t.attendees.filter(M=>M.checked_in_at&&new Date(M.checked_in_at)>=i).length,no_shows:t.attendees.filter(M=>M.no_show_at&&new Date(M.no_show_at)>=i).length,follow_ups_pending:t.attendees.filter(M=>M.checked_in_at&&M.followup_status!=="done").length,upcoming:t.events.filter(M=>M.starts_at&&new Date(M.starts_at)>n&&M.status==="published").sort((M,I)=>+new Date(M.starts_at)-+new Date(I.starts_at)).slice(0,3).map(M=>({title:M.title,starts_at:M.starts_at??null}))},v=[...s.filter(M=>M.agent.next_follow_up_at&&new Date(M.agent.next_follow_up_at)>n&&Yx(n,M.agent.next_follow_up_at)<=7).slice(0,5).map(M=>({label:dBe(M.agent),detail:`Follow-up scheduled ${new Date(M.agent.next_follow_up_at).toLocaleDateString()}`})),...y.upcoming.map(M=>({label:M.title,detail:M.starts_at?`Event on ${new Date(M.starts_at).toLocaleDateString()}`:"Event scheduled"}))].slice(0,6),b=t.activities.filter(M=>new Date(M.created_at)>=i),N={produce:0,influence:0,provide:0,connect:0};for(const M of b)M.pillar&&N[M.pillar]!==void 0&&N[M.pillar]++;const S=Object.entries(N).map(([M,I])=>({pillar:M,count:I})),A=S.slice().sort((M,I)=>M.count-I.count)[0],T=t.primaryPillar?`Your 90-day primary pillar is ${t.primaryPillar}. This week your lightest pillar was ${A.pillar} (${A.count} activities) — give it one deliberate rep.`:`Your lightest pillar this week was ${A.pillar} (${A.count} activities). Pick one action there.`,L={advanced:t.stageChanges.filter(M=>new Date(M.created_at)>=i).length,follow_ups_completed:t.followUps.filter(M=>M.completed_at&&new Date(M.completed_at)>=i).length,conversations_logged:b.filter(M=>["touch_logged","call","text","email","dm","meeting"].includes(M.activity_type)).length,kits_shared:f.length};return{week_start:r.toISOString().slice(0,10),week_end:a.toISOString().slice(0,10),generated_at:n.toISOString(),conversations:c,high_intent:u,renewed:h,overdue:m,stale:p,kit_summary:x,event_summary:y,upcoming_opportunities:v,pillar_balance:S,recommended_focus:T,wins:L}}const cI=q,phr=[{first_name:"Dana",last_name:"Reyes (Demo)",stage:"engaging_with_value",temperature:"hot",brokerage:"Summit Realty",city:"Tulsa",state:"OK",goals:"Wants to double GCI",challenges:"No systems"},{first_name:"Marcus",last_name:"Webb (Demo)",stage:"building_relationship",temperature:"warm",brokerage:"Keystone Group",city:"Jenks",state:"OK",goals:"More listings",challenges:"Lead follow-up"},{first_name:"Priya",last_name:"Nair (Demo)",stage:"active_conversation",temperature:"hot",brokerage:"Northline",city:"Bixby",state:"OK",goals:"Team building",challenges:"Time management"}];function fhr(){const{user:s}=vs(),t=Qt(),{intel:n,dataset:r,isLoading:a,refetch:i}=CW(),l=e8e(),o=vrs(),[c,d]=j.useState(""),[u,h]=j.useState(!1),m=j.useMemo(()=>r?mhr(n,r):null,[n,r]),p=j.useMemo(()=>{const y=c.toLowerCase().trim();return n.filter(v=>!y||`${v.agent.first_name} ${v.agent.last_name??""}`.toLowerCase().includes(y))},[n,c]),f=async()=>{if(!s)return;h(!0);const{data:y}=await cI.from("attract_agents").select("id").eq("user_id",s.id).eq("is_demo",!0);if((y??[]).length){re.info("Demo agents already exist"),h(!1);return}const{data:v,error:b}=await cI.from("attract_agents").insert(phr.map(S=>({...S,user_id:s.id,is_demo:!0,source:"demo_seed"}))).select("id, first_name");if(b){re.error(b.message),h(!1);return}const N=Date.now();await cI.from("attract_activities").insert((v??[]).map((S,A)=>({user_id:s.id,agent_id:S.id,activity_type:"touch_logged",pillar:"connect",title:`Demo conversation with ${S.first_name}`,created_at:new Date(N-(A+1)*14*864e5).toISOString()}))),await cI.from("attract_follow_ups").insert({user_id:s.id,agent_id:v[0].id,title:"Demo overdue commitment",touch_type:"call",priority:"high",due_at:new Date(N-6*864e5).toISOString()}),re.success("Demo relationships seeded"),h(!1),t.invalidateQueries({queryKey:["attract-intel-data"]}),i()},x=async()=>{if(!s)return;h(!0);const{data:y}=await cI.from("attract_agents").select("id").eq("user_id",s.id).eq("is_demo",!0),v=(y??[]).map(b=>b.id);if(!v.length){re.info("No demo data to clear"),h(!1);return}for(const b of["attract_recommendations","attract_agent_scores","attract_follow_ups","attract_activities"])await cI.from(b).delete().in("agent_id",v);await cI.from("attract_agents").delete().in("id",v),re.success("Demo data removed"),h(!1),t.invalidateQueries({queryKey:["attract-intel-data"]}),i()};return a?e.jsx(xn,{className:"h-72 w-full rounded-2xl"}):e.jsxs("div",{className:"p-4 sm:p-6 max-w-6xl mx-auto space-y-5",children:[e.jsx(U,{variant:"ghost",size:"sm",className:"rounded-full -ml-2",asChild:!0,children:e.jsxs(xr,{to:"/admin",children:[e.jsx(Aa,{className:"h-3.5 w-3.5 mr-1.5"})," Admin"]})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Attract Intelligence Debug"}),e.jsx("p",{className:"text-[13.5px] text-muted-foreground mt-1",children:"Full transparency into scores, signals and recommendations for your own Attract data. Demo records are flagged and removable."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(U,{variant:"outline",className:"rounded-full",onClick:()=>{o.mutate({items:n}),l.mutate(n)},disabled:l.isPending||o.isPending,children:[e.jsx(no,{className:"h-3.5 w-3.5 mr-1.5"})," Recompute & persist"]}),e.jsxs(U,{variant:"outline",className:"rounded-full",onClick:f,disabled:u,children:[e.jsx(SX,{className:"h-3.5 w-3.5 mr-1.5"})," Seed demo relationships"]}),e.jsxs(U,{variant:"outline",className:"rounded-full text-destructive",onClick:x,disabled:u,children:[e.jsx(In,{className:"h-3.5 w-3.5 mr-1.5"})," Clear demo data"]})]}),e.jsxs(oa,{defaultValue:"agents",children:[e.jsxs(la,{className:"rounded-full",children:[e.jsx(Kt,{value:"agents",className:"rounded-full",children:"Scores & signals"}),e.jsx(Kt,{value:"digest",className:"rounded-full",children:"Digest payload"})]}),e.jsxs(Zt,{value:"agents",className:"mt-4 space-y-3",children:[e.jsx(xe,{value:c,onChange:y=>d(y.target.value),placeholder:"Filter by name",className:"max-w-sm rounded-full"}),!p.length&&e.jsx(we,{className:"p-6 rounded-2xl text-[13.5px] text-muted-foreground",children:"No agents in your Attract pipeline."}),p.map(y=>e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx(xr,{to:`/attract/agents/${y.agent.id}`,className:"text-[15px] font-semibold hover:text-violet-700",children:[y.agent.first_name,y.agent.last_name].filter(Boolean).join(" ")}),e.jsxs("div",{className:"text-[12px] text-muted-foreground mt-0.5 capitalize",children:[y.agent.stage.replace(/_/g," ")," · ",y.agent.temperature??"no temperature"," · ",y.signals.daysSinceTouch??"—"," days since touch"]})]}),y.agent.is_demo&&e.jsx(Be,{variant:"outline",className:"rounded-full",children:"Demo"})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4 mt-4",children:[e.jsx(brs,{score:y.score}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-muted-foreground mb-1.5",children:["Recommendations (",y.recommendations.length,")"]}),y.recommendations.length?e.jsx("ul",{className:"space-y-2",children:y.recommendations.map(v=>e.jsxs("li",{className:"text-[12.5px]",children:[e.jsx("span",{className:"font-medium",children:v.title}),e.jsxs("span",{className:"text-muted-foreground",children:[" · ",v.signal_group," · rank ",v.rank_score," · ",v.priority]}),e.jsx("div",{className:"text-muted-foreground",children:v.reasons.join(" · ")})]},v.rec_key))}):e.jsx("div",{className:"text-[13px] text-muted-foreground",children:"None generated."})]})]}),e.jsxs("details",{className:"mt-3",children:[e.jsx("summary",{className:"text-[12px] cursor-pointer text-muted-foreground",children:"Raw signals"}),e.jsx("pre",{className:"text-[11px] bg-muted p-3 rounded-lg overflow-auto mt-2 max-h-72",children:JSON.stringify({touches90:y.signals.touches90,kitShares:y.signals.shares.length,kitOpens:y.signals.totalKitOpens,questions:y.signals.questions,meetingRequests:y.signals.meetingRequests,overdueFollowUps:y.signals.overdueFollowUps.length,attended:y.signals.attended},null,2)})]})]},y.agent.id))]}),e.jsx(Zt,{value:"digest",className:"mt-4",children:e.jsx(we,{className:"p-4 rounded-2xl",children:e.jsx("pre",{className:"text-[11px] bg-muted p-3 rounded-lg overflow-auto max-h-[600px]",children:JSON.stringify(m,null,2)})})})]})]})}const d3t=[{key:"today",pillar:"core",title:"Today",route:"/attract",status:"live",tables:["attract_recommendations","attract_follow_ups","attract_daily_plan"],notes:"Prioritized daily queue of recruiting moves."},{key:"agents",pillar:"core",title:"Agents (pipeline)",route:"/attract/agents",status:"live",tables:["attract_agents","attract_pipeline_history"],notes:"Needs-attention, stage board and list in one page."},{key:"agent_detail",pillar:"core",title:"Agent detail",route:"/attract/agents/:agentId",status:"live",tables:["attract_agents","attract_activities","attract_follow_ups"],notes:"Timeline, touches, kits shared, notes."},{key:"calculator",pillar:"core",title:"Comp calculator",route:"/attract/calculator",status:"live",tables:[],notes:"Live split/cap comparison; copy, print or email the one-pager."},{key:"attract_page",pillar:"core",title:"Attraction landing page",route:"/attract/attract-page",status:"live",tables:["attract_landing_pages","attract_landing_events"],notes:"Public join page with lead magnet and calculator."},{key:"results",pillar:"core",title:"Results",route:"/attract/results",status:"live",tables:["attract_agents","attract_activities"],notes:"Joins, pipeline conversion, days-to-join, attribution."},{key:"follow_up",pillar:"core",title:"Follow-Up Center",route:"/attract/follow-up",status:"live",tables:["attract_follow_ups"],notes:"Every commitment on one list."},{key:"opportunities",pillar:"core",title:"Opportunities",route:"/attract/opportunities",status:"live",tables:["attract_recommendations","attract_agent_scores"],notes:"Ranked, explainable recommendations."},{key:"settings",pillar:"core",title:"Settings",route:"/attract/settings",status:"live",tables:["attract_settings"],notes:"Goals, audience, cadence."},{key:"resource_kits",pillar:"toolkit",title:"Value kits",route:"/attract/toolkit/kits",status:"live",tables:["attract_resource_kits","attract_resource_kit_items","attract_kit_shares","attract_kit_events"],notes:"Build, share, track engagement."},{key:"kit_templates",pillar:"toolkit",title:"Starter kit library",route:"/attract/toolkit/kits/templates",status:"live",tables:["attract_kit_templates"],notes:"10 starter kits, clone to own."},{key:"scripts",pillar:"toolkit",title:"Recruiting scripts",route:"/attract/toolkit/scripts",status:"live",tables:[],notes:"Funnel-staged scripts with copy-to-clipboard."},{key:"objections",pillar:"toolkit",title:"Objection answers",route:"/attract/toolkit/objections",status:"live",tables:[],notes:"Opener + full answer per objection, searchable."},{key:"event_engine",pillar:"toolkit",title:"Events",route:"/attract/toolkit/events",status:"live",tables:["attract_events","attract_event_attendees","attract_event_invitations","attract_event_notes"],notes:"Builder, public registration, invitations, QR check-in."},{key:"checkin",pillar:"toolkit",title:"Mobile check-in",route:"/attract/events/:eventId/checkin",status:"live",tables:["attract_event_attendees"],notes:"QR + manual check-in."},{key:"content_studio",pillar:"toolkit",title:"Content Studio",route:"/attract/toolkit/content",status:"live",tables:["attract_content_drafts"],notes:"AI-assisted recruiting content drafts."},{key:"value_library",pillar:"toolkit",title:"Resource library",route:"/attract/toolkit/resources",status:"partial",tables:["attract_resources"],notes:"Read + save works; no categorization/search yet."}],u3t={live:"Live",partial:"Partial",placeholder:"Placeholder",integration_required:"Integration required"},ghr={live:"bg-emerald-50 text-emerald-700 border-emerald-200",partial:"bg-amber-50 text-amber-700 border-amber-200",placeholder:"bg-slate-100 text-slate-600 border-slate-200",integration_required:"bg-rose-50 text-rose-700 border-rose-200"};function xhr(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),a=j.useMemo(()=>d3t.filter(l=>{const o=s.toLowerCase().trim();return n!=="all"&&l.status!==n?!1:!o||`${l.title} ${l.pillar} ${l.route??""}`.toLowerCase().includes(o)}),[s,n]),i=j.useMemo(()=>{const l={live:0,partial:0,placeholder:0,integration_required:0};return d3t.forEach(o=>{l[o.status]++}),l},[]);return e.jsxs("div",{className:"p-4 sm:p-6 max-w-6xl mx-auto space-y-5",children:[e.jsx(U,{variant:"ghost",size:"sm",className:"rounded-full -ml-2",asChild:!0,children:e.jsxs(xr,{to:"/admin",children:[e.jsx(Aa,{className:"h-3.5 w-3.5 mr-1.5"})," Admin"]})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Attract Pillar Tools QA"}),e.jsx("p",{className:"text-[13.5px] text-muted-foreground mt-1",children:"Private status map of every Attract tool — route, database dependencies, and what still needs work."})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Object.keys(i).map(l=>e.jsxs(we,{className:"p-4 rounded-2xl cursor-pointer",onClick:()=>r(n===l?"all":l),children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums",children:i[l]}),e.jsx("div",{className:"text-[12px] text-muted-foreground",children:u3t[l]})]},l))}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx(xe,{value:s,onChange:l=>t(l.target.value),placeholder:"Filter tools",className:"max-w-sm rounded-full"}),n!=="all"&&e.jsx(U,{variant:"outline",className:"rounded-full",onClick:()=>r("all"),children:"Clear status filter"})]}),e.jsx("div",{className:"space-y-2",children:a.map(l=>e.jsx(we,{className:"p-4 rounded-2xl",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15px] font-semibold",children:l.title}),e.jsx(Be,{variant:"outline",className:"rounded-full capitalize",children:l.pillar}),e.jsx(Be,{variant:"outline",className:`rounded-full ${ghr[l.status]}`,children:u3t[l.status]})]}),e.jsx("div",{className:"text-[12.5px] text-muted-foreground mt-1",children:l.notes||"—"}),e.jsxs("div",{className:"text-[11.5px] text-muted-foreground mt-1",children:["Tables: ",l.tables.length?l.tables.join(", "):"none"]})]}),l.route&&!l.route.includes(":")?e.jsx(U,{variant:"outline",size:"sm",className:"rounded-full",asChild:!0,children:e.jsxs(xr,{to:l.route,children:[l.route," ",e.jsx(Sr,{className:"h-3 w-3 ml-1.5"})]})}):e.jsx("span",{className:"text-[12px] text-muted-foreground",children:l.route??"No route"})]})},`${l.pillar}-${l.key}`))})]})}function yhr(){var c;const{shareToken:s}=Di(),[t,n]=j.useState("loading"),[r,a]=j.useState(null),[i,l]=j.useState(!1);j.useEffect(()=>{(async()=>{if(!s){n("not_found");return}const{data:d,error:u}=await q.rpc("public_get_attract_kit",{_token:s});if(u){n("error");return}if(!d||d.status!=="ok"){n((d==null?void 0:d.status)??"not_found");return}a(d),n("ok"),q.rpc("public_log_attract_kit_event",{_token:s,_event_type:"page_view",_item_id:null,_metadata:{}})})()},[s]);const o=(d,u,h)=>{s&&q.rpc("public_log_attract_kit_event",{_token:s,_event_type:d,_item_id:u??null,_metadata:h??{}})};return t==="loading"?e.jsx("div",{className:"min-h-screen bg-[#05070f] grid place-items-center text-slate-300",children:"Loading…"}):t!=="ok"?e.jsx("div",{className:"min-h-screen bg-[#05070f] grid place-items-center px-6",children:e.jsxs(we,{className:"max-w-md w-full p-8 bg-white/5 border-white/10 text-slate-100 rounded-2xl text-center",children:[e.jsx(Vo,{className:"h-8 w-8 text-amber-400 mx-auto"}),e.jsx("div",{className:"mt-3 text-xl font-semibold",children:t==="expired"?"This kit has expired":t==="revoked"?"This kit is no longer available":t==="not_found"?"This kit could not be found":"Something went wrong"}),e.jsx("p",{className:"text-slate-400 mt-2 text-sm",children:"Please reach out to the person who shared it with you for an updated link."})]})}):e.jsx("div",{className:"min-h-screen bg-[#05070f]",children:e.jsxs("div",{className:"max-w-3xl mx-auto py-6 px-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10.5px] uppercase tracking-widest text-violet-400 font-semibold justify-center py-3",children:[e.jsx(cn,{className:"h-3.5 w-3.5"})," A LevelUp Attract kit"]}),e.jsx(nas,{kit:r.kit,items:r.items,owner:r.owner,personalNote:(c=r.share)==null?void 0:c.personal_note,mode:"public",onEvent:o}),e.jsx(we,{className:"mt-6 p-6 bg-white/5 border-white/10 text-slate-100 rounded-2xl",children:i?e.jsx(vhr,{token:s,onSent:()=>l(!1),onEvent:o}):e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold",children:"Have a question about this?"}),e.jsxs("p",{className:"text-slate-400 text-[13px] mt-1",children:["Send a private note — ",r.owner.display_name," will get it right away."]}),e.jsx(U,{className:"mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>l(!0),children:"Ask a question"})]})}),e.jsx("div",{className:"text-center text-[11px] text-slate-600 mt-6 pb-10",children:"Powered by LevelUp Attract"})]})})}function vhr({token:s,onSent:t,onEvent:n}){const[r,a]=j.useState(""),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(!1),h=async()=>{if(o.trim().length<2)return re.error("Please add a short message");u(!0);const{data:m,error:p}=await q.rpc("public_submit_attract_kit_question",{_token:s,_name:r,_email:i,_message:o});if(u(!1),p||!(m!=null&&m.ok))return re.error("Could not send — please try again");re.success("Sent — thank you!"),t()};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-[14px] font-semibold",children:"Send a private message"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:[e.jsx(xe,{placeholder:"Your name (optional)",value:r,onChange:m=>a(m.target.value),className:"bg-white/5 border-white/10 text-white placeholder:text-slate-500"}),e.jsx(xe,{placeholder:"Your email (optional)",value:i,onChange:m=>l(m.target.value),className:"bg-white/5 border-white/10 text-white placeholder:text-slate-500"})]}),e.jsx(Fs,{rows:4,placeholder:"What's your question?",value:o,onChange:m=>c(m.target.value),className:"bg-white/5 border-white/10 text-white placeholder:text-slate-500"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{variant:"outline",onClick:()=>{n("meeting_requested"),re.success("Request sent")},children:"Request a conversation"}),e.jsx(U,{onClick:h,disabled:d,className:"bg-gradient-to-r from-violet-600 to-indigo-600 ml-auto",children:d?"Sending…":"Send question"})]})]})}function bhr(){const{slug:s}=Di(),[t]=fc(),n=t.get("inv")||null,[r,a]=j.useState("loading"),[i,l]=j.useState(null),[o,c]=j.useState({name:"",email:"",phone:"",answers:{}}),[d,u]=j.useState(!1),[h,m]=j.useState(null);j.useEffect(()=>{s&&(async()=>{const{data:x,error:y}=await q.rpc("public_get_attract_event",{_slug:s});if(y||!x||x.error){a((x==null?void 0:x.error)||"not_found");return}l(x),a("ok"),n&&q.rpc("public_track_attract_invitation_view",{_token:n})})()},[s,n]);const p=async()=>{u(!0);const{data:x,error:y}=await q.rpc("public_register_attract_event",{_slug:s,_name:o.name,_email:o.email,_phone:o.phone||null,_answers:o.answers||{},_invitation_token:n});if(u(!1),y){alert("Something went wrong. Please try again.");return}const v=x;if(v!=null&&v.error){alert(v.error==="invalid_email"?"That email looks off.":v.error==="full"?"This event is full.":"Could not register.");return}m(v)},f=()=>{if(!i)return;const x=new Blob([Mrs(i)],{type:"text/calendar"}),y=document.createElement("a");y.href=URL.createObjectURL(x),y.download=`${s}.ics`,y.click()};if(r==="loading")return e.jsx("div",{className:"min-h-screen grid place-items-center text-slate-400",children:"Loading…"});if(r!=="ok"||!i){const x=r==="cancelled"?"This event was cancelled.":r==="not_available"?"This event is not open for registration.":"This event could not be found.";return e.jsx("div",{className:"min-h-screen grid place-items-center px-6 text-center",children:e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-semibold text-slate-900",children:x}),e.jsx("div",{className:"text-slate-500 mt-2",children:"The link may have expired."})]})})}return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-violet-50",children:e.jsxs("div",{className:"max-w-3xl mx-auto px-4 py-10 md:py-16",children:[i.cover_image_url&&e.jsx("div",{className:"rounded-3xl overflow-hidden mb-8 aspect-[16/7] bg-slate-100",children:e.jsx("img",{src:i.cover_image_url,alt:"",className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.2em] text-violet-600 font-semibold mb-3",children:"You are invited"}),e.jsx("h1",{className:"text-3xl md:text-5xl font-semibold tracking-tight text-slate-900",children:i.title}),i.host&&e.jsxs("div",{className:"text-slate-600 mt-3 text-[15px]",children:["Hosted by ",e.jsx("span",{className:"font-semibold",children:i.host.name}),i.host.brokerage_name?` · ${i.host.brokerage_name}`:""]})]}),e.jsxs(we,{className:"p-6 rounded-3xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 text-[14px]",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(pa,{className:"h-5 w-5 text-violet-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-slate-500 text-[12px]",children:"When"}),e.jsx("div",{className:"font-semibold text-slate-900",children:Gs(new Date(i.starts_at),"EEEE, MMMM d · h:mm a")}),e.jsx("div",{className:"text-slate-500 text-[12px]",children:i.timezone})]})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[i.format==="virtual"?e.jsx(Wr,{className:"h-5 w-5 text-violet-600 mt-0.5"}):e.jsx(ni,{className:"h-5 w-5 text-violet-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-slate-500 text-[12px]",children:"Where"}),e.jsx("div",{className:"font-semibold text-slate-900",children:i.format==="virtual"?"Virtual — link sent after registration":i.location||"In person"}),i.address&&e.jsx("div",{className:"text-slate-500 text-[12px]",children:i.address})]})]}),i.capacity&&e.jsxs("div",{className:"flex items-start gap-3 md:col-span-2",children:[e.jsx(Bn,{className:"h-5 w-5 text-violet-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-slate-500 text-[12px]",children:"Room size"}),e.jsx("div",{className:"font-semibold text-slate-900",children:i.seats_left===0?"Waitlist only":`${i.seats_left} of ${i.capacity} seats left`})]})]})]}),i.description&&e.jsx("p",{className:"text-[15px] text-slate-700 leading-relaxed mt-5",children:i.description}),(i.learning_outcomes||[]).length>0&&e.jsxs("div",{className:"mt-5",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"What you will receive"}),e.jsx("ul",{className:"space-y-1.5",children:i.learning_outcomes.map((x,y)=>e.jsxs("li",{className:"flex gap-2 text-[14px] text-slate-800",children:[e.jsx(Xr,{className:"h-4 w-4 text-emerald-600 shrink-0 mt-0.5"})," ",x]},y))})]}),(i.agenda||[]).length>0&&e.jsxs("div",{className:"mt-5",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Agenda"}),e.jsx("ul",{className:"space-y-1",children:i.agenda.map((x,y)=>e.jsxs("li",{className:"flex gap-3 text-[13.5px]",children:[e.jsx("span",{className:"text-slate-500 tabular-nums w-16 shrink-0",children:x.time}),e.jsx("span",{className:"text-slate-800",children:x.item})]},y))})]})]}),h?e.jsxs(we,{className:"mt-6 p-8 rounded-3xl border-emerald-200 bg-emerald-50 text-center",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-emerald-500 text-white grid place-items-center",children:e.jsx(Xr,{className:"h-7 w-7"})}),e.jsx("div",{className:"text-2xl font-semibold text-slate-900 mt-4",children:h.status==="waitlisted"?"You are on the waitlist":"You are in."}),i.confirmation_message&&e.jsx("div",{className:"text-[15px] text-slate-700 mt-2 max-w-lg mx-auto",children:i.confirmation_message}),e.jsxs(U,{variant:"outline",className:"rounded-full mt-5",onClick:f,children:[e.jsx(pi,{className:"h-4 w-4 mr-2"})," Add to calendar"]})]}):e.jsxs(we,{className:"mt-6 p-6 rounded-3xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"text-lg font-semibold text-slate-900 mb-1 flex items-center gap-2",children:[e.jsx(cn,{className:"h-4 w-4 text-violet-600"})," Save your seat"]}),e.jsx("div",{className:"text-[13px] text-slate-500 mb-4",children:"The room is small on purpose."}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Full name"}),e.jsx(xe,{value:o.name,onChange:x=>c({...o,name:x.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Email"}),e.jsx(xe,{type:"email",value:o.email,onChange:x=>c({...o,email:x.target.value})})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Phone (optional)"}),e.jsx(xe,{value:o.phone,onChange:x=>c({...o,phone:x.target.value})})]})]}),(i.registration_questions||[]).map(x=>e.jsxs("div",{children:[e.jsx(te,{children:x.label}),x.type==="long"?e.jsx(Fs,{rows:3,value:o.answers[x.key]||"",onChange:y=>c({...o,answers:{...o.answers,[x.key]:y.target.value}})}):e.jsx(xe,{value:o.answers[x.key]||"",onChange:y=>c({...o,answers:{...o.answers,[x.key]:y.target.value}})})]},x.key))]}),e.jsx(U,{disabled:d,className:"w-full mt-5 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 h-11",onClick:p,children:d?"Saving…":i.seats_left===0?"Join the waitlist":"Save my seat"}),e.jsx("div",{className:"text-[11.5px] text-slate-400 text-center mt-3",children:"Build relationships first. We will only email you about this event."})]})]})})}function _hr(){const{token:s}=Di(),[t]=fc(),n=t.get("a"),[r,a]=j.useState("loading"),[i,l]=j.useState("");return j.useEffect(()=>{if(!s||!n){a("error");return}(async()=>{const{data:o}=await q.rpc("public_check_in_attendee",{_check_in_token:s,_attendee_token:n}),c=o;c!=null&&c.ok?(l(c.name||""),a(c.already?"already":"ok")):a("error")})()},[s,n]),e.jsx("div",{className:"min-h-screen grid place-items-center bg-slate-50 px-4",children:e.jsxs(we,{className:"p-8 rounded-3xl border-slate-200 bg-white max-w-md w-full text-center",children:[r==="loading"&&e.jsx("div",{className:"text-slate-500",children:"Checking you in…"}),(r==="ok"||r==="already")&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-emerald-500 text-white grid place-items-center",children:e.jsx(Xr,{className:"h-7 w-7"})}),e.jsx("div",{className:"text-2xl font-semibold mt-4 text-slate-900",children:r==="already"?"Already checked in":"You are in!"}),i&&e.jsxs("div",{className:"text-slate-600 mt-1",children:["Welcome, ",i,"."]}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-4",children:"Find your seat and enjoy the room."})]}),r==="error"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xl font-semibold text-slate-900",children:"We could not check you in."}),e.jsx("div",{className:"text-slate-500 mt-2",children:"Please see the host at the door."})]})]})})}const dde=s=>s.toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});function whr(s){if(!s)return"";const t=s.match(/(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|embed\/|shorts\/))([\w-]{6,})/);if(t)return`https://www.youtube.com/embed/${t[1]}?autoplay=1&rel=0`;const n=s.match(/vimeo\.com\/(\d+)/);if(n)return`https://player.vimeo.com/video/${n[1]}?autoplay=1`;const r=s.match(/loom\.com\/(?:share|embed)\/([\w-]+)/);return r?`https://www.loom.com/embed/${r[1]}`:s}function ras({cfg:s,onSubmitLead:t,onTrack:n,preview:r}){var L,M,I;const a=s.primary_color||"#0f1b3d",i=s.accent_color||"#c9a84c",l=s.sections||{},[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(!1),[p,f]=j.useState({first_name:"",last_name:"",email:"",phone:"",brokerage:"",message:""}),[x,y]=j.useState({first_name:"",email:""}),v=s.calculator||{},[b,N]=j.useState(15e4),S=j.useMemo(()=>{const R=Number(v.cap??16e3),z=Number(v.split??80)/100,$=Number(v.transaction_fee??250),H=Number(v.current_split??70)/100,V=Number(v.current_monthly_fees??150),K=Math.min(b*(1-z),R),Z=b-K-$*12,Q=b*H-V*12;return{here:Math.max(Z,0),current:Math.max(Q,0),diff:Math.max(Z-Q,0),capped:K>=R}},[b,v]),A=async(R,z,$)=>{if(r||!t){u(R);return}m(!0);try{await t({first_name:z.first_name||"",last_name:z.last_name||"",email:z.email||"",phone:z.phone||"",brokerage:z.brokerage||"",message:z.message||"",source:R,metadata:$}),u(R)}catch(H){ka({title:"We couldn't send that",description:(H==null?void 0:H.message)||"Please try again in a moment.",variant:"destructive"})}finally{m(!1)}},T=R=>e.jsxs("a",{href:"#connect",onClick:()=>n==null?void 0:n("cta_click","hero"),className:"group inline-flex items-center gap-3 rounded-full px-8 py-4 text-base font-semibold shadow-2xl transition-transform hover:scale-[1.03]",style:{backgroundColor:i,color:"#10131c"},children:[R||s.cta_label||"Book a confidential 15-min call",e.jsx(Oa,{className:"h-4 w-4 transition-transform group-hover:translate-x-1"})]});return e.jsxs("div",{className:"min-h-screen bg-[#0b0e17] text-white antialiased",children:[l.hero!==!1&&e.jsxs("section",{className:"relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(160deg, ${a} 0%, #05070d 75%)`}}),s.hero_image_url&&e.jsx("div",{className:"absolute inset-0 bg-cover bg-center opacity-20",style:{backgroundImage:`url(${s.hero_image_url})`}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.06]",style:{backgroundImage:"radial-gradient(circle at 20% 20%, white 1px, transparent 1px)",backgroundSize:"48px 48px"}}),e.jsxs("div",{className:"relative z-10 mx-auto grid max-w-6xl items-center gap-12 px-6 py-24 md:grid-cols-[1.2fr_.8fr] md:py-32",children:[e.jsxs("div",{children:[s.logo_url&&e.jsx("img",{src:s.logo_url,alt:"",className:"mb-8 h-10 w-auto"}),s.eyebrow&&e.jsx("span",{className:"mb-5 inline-block text-xs font-medium uppercase tracking-[0.22em]",style:{color:i},children:s.eyebrow}),e.jsx("h1",{className:"mb-6 text-4xl font-bold leading-[1.08] tracking-tight md:text-6xl",children:s.headline}),e.jsx("p",{className:"mb-10 max-w-xl text-lg font-light leading-relaxed text-white/70",children:s.subheadline}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[T(),s.calendar_url&&e.jsxs("a",{href:s.calendar_url,target:"_blank",rel:"noreferrer",onClick:()=>n==null?void 0:n("cta_click","calendar"),className:"inline-flex items-center gap-2 rounded-full border border-white/25 px-6 py-4 text-sm font-medium text-white/85 backdrop-blur transition-colors hover:bg-white/10",children:[e.jsx(pa,{className:"h-4 w-4"})," See my calendar"]})]})]}),s.headshot_url&&e.jsxs("div",{className:"relative mx-auto w-full max-w-xs",children:[e.jsx("div",{className:"absolute -inset-3 rounded-[2rem] opacity-40 blur-2xl",style:{background:i}}),e.jsx("img",{src:s.headshot_url,alt:s.agent_name||"",className:"relative w-full rounded-[1.75rem] object-cover shadow-2xl"}),e.jsxs("div",{className:"relative mt-5 text-center",children:[e.jsx("div",{className:"text-lg font-semibold",children:s.agent_name}),e.jsx("div",{className:"text-sm text-white/55",children:s.agent_title})]})]})]})]}),l.credibility!==!1&&(s.credibility||[]).length>0&&e.jsx("section",{className:"border-y border-white/10 bg-white/[0.03]",children:e.jsx("div",{className:"mx-auto grid max-w-6xl grid-cols-2 gap-8 px-6 py-10 md:grid-cols-4",children:(s.credibility||[]).map((R,z)=>e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-2xl font-bold md:text-3xl",style:{color:i},children:R.value}),e.jsx("div",{className:"mt-1 text-xs uppercase tracking-wider text-white/50",children:R.label})]},z))})}),l.story!==!1&&(s.story_body||s.story_video_url)&&e.jsxs("section",{className:"mx-auto max-w-5xl px-6 py-20 md:py-28",children:[e.jsx("h2",{className:"mb-6 text-3xl font-bold tracking-tight md:text-4xl",children:s.story_title||"Why I moved"}),s.story_video_url&&e.jsx("div",{className:"mb-8 aspect-video overflow-hidden rounded-2xl border border-white/10 bg-black",children:o?e.jsx("iframe",{src:whr(s.story_video_url),className:"h-full w-full",allow:"autoplay; fullscreen",allowFullScreen:!0,title:"Story"}):e.jsxs("button",{onClick:()=>{c(!0),n==null||n("cta_click","story_video")},className:"group relative flex h-full w-full items-center justify-center bg-cover bg-center",style:{backgroundImage:s.hero_image_url?`url(${s.hero_image_url})`:void 0},children:[e.jsx("div",{className:"absolute inset-0 bg-black/55"}),e.jsx($h,{className:"relative h-20 w-20 text-white/90 transition-transform group-hover:scale-110"})]})}),e.jsx("p",{className:"max-w-3xl whitespace-pre-line text-lg font-light leading-relaxed text-white/70",children:s.story_body})]}),l.value_stack!==!1&&(s.value_cards||[]).length>0&&e.jsx("section",{className:"border-y border-white/10 bg-white/[0.02] py-20 md:py-28",children:e.jsxs("div",{className:"mx-auto max-w-6xl px-6",children:[e.jsx("h2",{className:"mb-3 text-3xl font-bold tracking-tight md:text-4xl",children:"What you actually get"}),e.jsx("p",{className:"mb-12 max-w-2xl text-white/60",children:"No hype. Here is the model, in plain English."}),e.jsx("div",{className:"grid gap-5 md:grid-cols-2 lg:grid-cols-3",children:(s.value_cards||[]).map((R,z)=>e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 transition-colors hover:border-white/25",children:[e.jsx("div",{className:"mb-3 flex h-9 w-9 items-center justify-center rounded-lg",style:{backgroundColor:`${i}22`,color:i},children:e.jsx(Xr,{className:"h-4 w-4"})}),e.jsx("h3",{className:"mb-2 text-lg font-semibold",children:R.title}),e.jsx("p",{className:"text-sm leading-relaxed text-white/65",children:R.body}),R.proof&&e.jsx("p",{className:"mt-3 text-xs uppercase tracking-wider text-white/40",children:R.proof})]},z))})]})}),l.calculator!==!1&&v.enabled!==!1&&e.jsx("section",{className:"py-20 md:py-28",children:e.jsx("div",{className:"mx-auto max-w-4xl px-6",children:e.jsxs("div",{className:"rounded-3xl border border-white/10 bg-gradient-to-b from-white/[0.06] to-transparent p-8 md:p-12",children:[e.jsx("h2",{className:"mb-2 text-3xl font-bold tracking-tight md:text-4xl",children:v.title||"Run your own numbers"}),e.jsx("p",{className:"mb-8 text-white/60",children:"Move the slider to your gross commission income for the year."}),e.jsxs("div",{className:"mb-8",children:[e.jsxs("div",{className:"mb-3 flex items-baseline justify-between",children:[e.jsx(te,{className:"text-white/70",children:"Your annual GCI"}),e.jsx("span",{className:"text-2xl font-bold",style:{color:i},children:dde(b)})]}),e.jsx("input",{type:"range",min:25e3,max:1e6,step:5e3,value:b,onChange:R=>N(Number(R.target.value)),onMouseUp:()=>n==null?void 0:n("calculator_run","calculator",{gci:b}),onTouchEnd:()=>n==null?void 0:n("calculator_run","calculator",{gci:b}),className:"w-full accent-white"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-2xl border border-white/10 p-5",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-white/45",children:"Where you are now"}),e.jsx("div",{className:"mt-2 text-2xl font-semibold text-white/80",children:dde(S.current)})]}),e.jsxs("div",{className:"rounded-2xl border p-5",style:{borderColor:i},children:[e.jsx("div",{className:"text-xs uppercase tracking-wider",style:{color:i},children:"With me"}),e.jsx("div",{className:"mt-2 text-2xl font-bold",children:dde(S.here)}),S.capped&&e.jsx("div",{className:"mt-1 text-xs text-white/50",children:"You would cap this year."})]}),e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.04] p-5",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-white/45",children:"Difference"}),e.jsxs("div",{className:"mt-2 text-2xl font-bold",style:{color:i},children:["+",dde(S.diff)]})]})]}),e.jsx("p",{className:"mt-6 text-xs leading-relaxed text-white/35",children:"Estimates only, based on the assumptions above. Your actual numbers depend on your production and agreements."}),e.jsx("div",{className:"mt-8",children:T("Show me my exact numbers")})]})})}),l.sponsor!==!1&&(s.sponsor_cards||[]).length>0&&e.jsx("section",{className:"border-y border-white/10 bg-white/[0.02] py-20 md:py-28",children:e.jsxs("div",{className:"mx-auto max-w-5xl px-6",children:[e.jsx("h2",{className:"mb-3 text-3xl font-bold tracking-tight md:text-4xl",children:"What you get from me"}),e.jsx("p",{className:"mb-12 max-w-2xl text-white/60",children:"The brokerage is the same for everyone. Who you partner with is not."}),e.jsx("div",{className:"grid gap-5 md:grid-cols-2",children:(s.sponsor_cards||[]).map((R,z)=>e.jsxs("div",{className:"flex gap-4 rounded-2xl border border-white/10 p-6",children:[e.jsx("div",{className:"mt-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-sm font-bold",style:{backgroundColor:i,color:"#10131c"},children:z+1}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-1.5 font-semibold",children:R.title}),e.jsx("p",{className:"text-sm leading-relaxed text-white/65",children:R.body})]})]},z))})]})}),l.testimonials!==!1&&(s.testimonials||[]).length>0&&e.jsx("section",{className:"py-20 md:py-28",children:e.jsxs("div",{className:"mx-auto max-w-6xl px-6",children:[e.jsx("h2",{className:"mb-12 text-3xl font-bold tracking-tight md:text-4xl",children:"Agents who made the move"}),e.jsx("div",{className:"grid gap-5 md:grid-cols-3",children:(s.testimonials||[]).map((R,z)=>e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6",children:[e.jsx(tS,{className:"mb-4 h-6 w-6",style:{color:i}}),e.jsxs("p",{className:"text-sm leading-relaxed text-white/75",children:['"',R.quote,'"']}),e.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[R.photo_url?e.jsx("img",{src:R.photo_url,alt:R.name,className:"h-10 w-10 rounded-full object-cover"}):e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full bg-white/10",children:e.jsx(Ua,{className:"h-4 w-4 text-white/50"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:R.name}),R.role&&e.jsx("div",{className:"text-xs text-white/45",children:R.role})]})]})]},z))})]})}),l.faq!==!1&&(s.faqs||[]).length>0&&e.jsx("section",{className:"border-y border-white/10 bg-white/[0.02] py-20 md:py-28",children:e.jsxs("div",{className:"mx-auto max-w-3xl px-6",children:[e.jsx("h2",{className:"mb-10 text-3xl font-bold tracking-tight md:text-4xl",children:"The questions everyone asks"}),e.jsx(y9,{type:"single",collapsible:!0,className:"w-full",children:(s.faqs||[]).map((R,z)=>e.jsxs(WP,{value:`faq-${z}`,className:"border-white/10",children:[e.jsx(KP,{className:"text-left text-base font-medium text-white hover:no-underline",children:R.q}),e.jsx(YP,{className:"text-sm leading-relaxed text-white/65",children:R.a})]},z))})]})}),l.lead_magnet!==!1&&((L=s.lead_magnet)==null?void 0:L.enabled)!==!1&&((M=s.lead_magnet)==null?void 0:M.title)&&e.jsx("section",{className:"py-20",children:e.jsx("div",{className:"mx-auto max-w-3xl px-6",children:e.jsxs("div",{className:"rounded-3xl border border-white/10 bg-white/[0.04] p-8 md:p-10",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2 text-xs uppercase tracking-widest",style:{color:i},children:[e.jsx(pi,{className:"h-3.5 w-3.5"})," Free, no strings"]}),e.jsx("h3",{className:"mb-2 text-2xl font-bold",children:s.lead_magnet.title}),e.jsx("p",{className:"mb-6 text-white/65",children:s.lead_magnet.body}),d==="lead_magnet"?e.jsxs("div",{className:"rounded-xl border border-white/15 p-4 text-sm text-white/80",children:["On its way. Check your inbox",s.lead_magnet.file_url?" — or grab it now:":"."," ",s.lead_magnet.file_url&&e.jsx("a",{href:s.lead_magnet.file_url,target:"_blank",rel:"noreferrer",className:"underline",style:{color:i},children:"download"})]}):e.jsxs("form",{className:"flex flex-col gap-3 sm:flex-row",onSubmit:R=>{R.preventDefault(),A("lead_magnet",{first_name:x.first_name,email:x.email,message:`Requested: ${s.lead_magnet.title}`})},children:[e.jsx(xe,{required:!0,placeholder:"First name",value:x.first_name,onChange:R=>y(z=>({...z,first_name:R.target.value})),className:"h-12 border-white/15 bg-white/5 text-white placeholder:text-white/35"}),e.jsx(xe,{required:!0,type:"email",placeholder:"Email",value:x.email,onChange:R=>y(z=>({...z,email:R.target.value})),className:"h-12 border-white/15 bg-white/5 text-white placeholder:text-white/35"}),e.jsx(U,{type:"submit",disabled:h,className:"h-12 shrink-0 font-semibold",style:{backgroundColor:i,color:"#10131c"},children:s.lead_magnet.cta||"Send it"})]})]})})}),l.event!==!1&&((I=s.event_block)==null?void 0:I.title)&&e.jsx("section",{className:"pb-20",children:e.jsx("div",{className:"mx-auto max-w-3xl px-6",children:e.jsxs("div",{className:"flex flex-col items-start justify-between gap-5 rounded-2xl border p-6 md:flex-row md:items-center",style:{borderColor:`${i}55`},children:[e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 text-xs uppercase tracking-widest",style:{color:i},children:"Coming up"}),e.jsx("div",{className:"text-lg font-semibold",children:s.event_block.title}),s.event_block.when&&e.jsx("div",{className:"text-sm text-white/55",children:s.event_block.when})]}),s.event_block.url&&e.jsx("a",{href:s.event_block.url,target:"_blank",rel:"noreferrer",onClick:()=>n==null?void 0:n("cta_click","event"),className:"rounded-full px-6 py-3 text-sm font-semibold",style:{backgroundColor:i,color:"#10131c"},children:"Save my seat"})]})})}),l.final_cta!==!1&&e.jsxs("section",{id:"connect",className:"relative overflow-hidden py-24",children:[e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(200deg, ${a}, #05070d)`}}),e.jsxs("div",{className:"relative z-10 mx-auto max-w-xl px-6",children:[e.jsxs("div",{className:"mb-8 text-center",children:[e.jsx("h2",{className:"mb-3 text-3xl font-bold tracking-tight md:text-4xl",children:"Let's have a confidential conversation"}),e.jsx("p",{className:"text-white/60",children:"No pitch, no pressure. You will get straight answers and your real numbers."})]}),d&&d!=="lead_magnet"?e.jsxs("div",{className:"rounded-3xl border border-white/15 bg-white/5 p-10 text-center",children:[e.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full",style:{backgroundColor:i,color:"#10131c"},children:e.jsx(Xr,{className:"h-6 w-6"})}),e.jsx("h3",{className:"mb-2 text-xl font-semibold",children:"Got it — talk soon."}),e.jsxs("p",{className:"text-white/60",children:[s.agent_name||"I"," will reach out personally.",s.calendar_url&&" Want to skip the wait? Grab a time below."]}),s.calendar_url&&e.jsxs("a",{href:s.calendar_url,target:"_blank",rel:"noreferrer",className:"mt-6 inline-flex items-center gap-2 rounded-full px-6 py-3 text-sm font-semibold",style:{backgroundColor:i,color:"#10131c"},children:[e.jsx(pa,{className:"h-4 w-4"})," Pick a time"]})]}):e.jsxs("form",{onSubmit:R=>{R.preventDefault(),A("attraction_page",p,{gci:b})},className:"space-y-4 rounded-3xl border border-white/10 bg-white/[0.05] p-8 backdrop-blur",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-sm text-white/70",children:"First name *"}),e.jsx(xe,{required:!0,value:p.first_name,onChange:R=>f(z=>({...z,first_name:R.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-sm text-white/70",children:"Last name"}),e.jsx(xe,{value:p.last_name,onChange:R=>f(z=>({...z,last_name:R.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-sm text-white/70",children:"Email *"}),e.jsx(xe,{required:!0,type:"email",value:p.email,onChange:R=>f(z=>({...z,email:R.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-sm text-white/70",children:"Phone"}),e.jsx(xe,{value:p.phone,onChange:R=>f(z=>({...z,phone:R.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-sm text-white/70",children:"Current brokerage"}),e.jsx(xe,{value:p.brokerage,onChange:R=>f(z=>({...z,brokerage:R.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-sm text-white/70",children:"What would you want to know?"}),e.jsx(Fs,{rows:3,value:p.message,onChange:R=>f(z=>({...z,message:R.target.value})),className:"resize-none border-white/15 bg-white/5 text-white"})]}),e.jsx(U,{type:"submit",disabled:h,className:"h-12 w-full text-base font-semibold",style:{backgroundColor:i,color:"#10131c"},children:h?"Sending…":s.cta_label||"Book a confidential 15-min call"}),e.jsxs("div",{className:"flex items-center justify-center gap-2 pt-1 text-xs text-white/40",children:[e.jsx(Im,{className:"h-3.5 w-3.5"})," 100% confidential. Never shared with your broker."]})]}),(s.phone||s.email)&&e.jsxs("div",{className:"mt-6 flex flex-wrap justify-center gap-5 text-sm text-white/50",children:[s.phone&&e.jsxs("a",{href:`tel:${s.phone}`,className:"inline-flex items-center gap-2 hover:text-white",children:[e.jsx(ba,{className:"h-4 w-4"})," ",s.phone]}),s.email&&e.jsx("a",{href:`mailto:${s.email}`,className:"hover:text-white",children:s.email})]})]})]}),l.disclaimer!==!1&&s.disclaimer&&e.jsx("footer",{className:"border-t border-white/10 px-6 py-10",children:e.jsx("p",{className:"mx-auto max-w-3xl text-center text-xs leading-relaxed text-white/35",children:s.disclaimer})}),l.final_cta!==!1&&e.jsx("div",{className:"sticky bottom-0 z-40 border-t border-white/10 bg-[#0b0e17]/95 p-3 backdrop-blur md:hidden",children:e.jsxs("a",{href:"#connect",onClick:()=>n==null?void 0:n("cta_click","sticky"),className:"flex items-center justify-center gap-2 rounded-full py-3.5 text-sm font-semibold",style:{backgroundColor:i,color:"#10131c"},children:[s.cta_label||"Book a confidential 15-min call"," ",e.jsx(Oa,{className:"h-4 w-4"})]})})]})}const ude=q;function jhr(){const{slug:s}=Di(),[t,n]=j.useState(null),[r,a]=j.useState("loading");j.useEffect(()=>{if(!s)return;let o=!1;return(async()=>{const{data:c,error:d}=await ude.rpc("public_get_attract_landing_page",{_slug:s});if(!o){if(d||!c||c.error){a("missing");return}n(c),a("ready"),ude.rpc("public_track_attract_landing_event",{_slug:s,_event_type:"view",_section_key:null,_metadata:{referrer:document.referrer||null}})}})(),()=>{o=!0}},[s]);const i=(o,c,d)=>{s&&ude.rpc("public_track_attract_landing_event",{_slug:s,_event_type:o,_section_key:c??null,_metadata:d??{}})},l=async o=>{const{data:c,error:d}=await ude.rpc("public_submit_attract_landing_lead",{_slug:s,_first_name:o.first_name,_last_name:o.last_name,_email:o.email,_phone:o.phone,_brokerage:o.brokerage,_message:o.message,_source:o.source,_metadata:o.metadata??{}});if(d)throw d;if(c&&c.error)throw new Error(String(c.error))};return r==="loading"?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0e17]",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-white/20 border-t-white"})}):r==="missing"?e.jsxs("div",{className:"flex min-h-screen flex-col items-center justify-center bg-[#0b0e17] px-6 text-center text-white",children:[e.jsx("h1",{className:"mb-2 text-2xl font-semibold",children:"This page isn't available"}),e.jsx("p",{className:"text-white/50",children:"The link may have changed or the page is no longer published."})]}):e.jsxs(e.Fragment,{children:[e.jsxs(dl,{children:[e.jsx("title",{children:t.seo_title||`${t.agent_name} | Partner with me`}),e.jsx("meta",{name:"description",content:t.seo_description||""}),t.noindex&&e.jsx("meta",{name:"robots",content:"noindex,nofollow"}),e.jsx("meta",{property:"og:title",content:t.seo_title||t.headline||""}),e.jsx("meta",{property:"og:description",content:t.seo_description||t.subheadline||""}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"})]}),e.jsx(ras,{cfg:t,onSubmitLead:l,onTrack:i})]})}const h3t={media_mode:"photo",show_property_snapshot:!0,show_discover:!0,show_testimonial:!0};function aas(s){const t=(s??"").trim();if(!t)return null;const n=t.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([\w-]{6,})/);if(n)return{kind:"iframe",src:`https://www.youtube.com/embed/${n[1]}`};const r=t.match(/vimeo\.com\/(?:video\/)?(\d+)/);if(r)return{kind:"iframe",src:`https://player.vimeo.com/video/${r[1]}`};const a=t.match(/loom\.com\/(?:share|embed)\/([\w-]+)/);return a?{kind:"iframe",src:`https://www.loom.com/embed/${a[1]}`}:/\.(mp4|webm|mov|m4v)(\?|$)/i.test(t)?{kind:"file",src:t}:{kind:"iframe",src:t}}const h$=[{id:"fresh_perspective",name:"Fresh Perspective",tagline:"A new set of eyes",description:"Optimistic and forward-looking. Perfect for sellers who are frustrated but still motivated.",accent:"from-sky-500/20 to-sky-500/0",previewHeadline:"A Fresh Look At Your Home",previewBody:"Sometimes all a great home needs is a new perspective — and a plan built for today’s buyer."},{id:"second_chance",name:"Second Chance",tagline:"Empathy first",description:"Warm and human. Acknowledges the disappointment, then pivots to hope and a concrete plan.",accent:"from-amber-500/25 to-amber-500/0",previewHeadline:"Let’s Give Your Home A Second Chance It Deserves",previewBody:"Many great homes don’t sell the first time for reasons that can be fixed with the right strategy."},{id:"luxury_relaunch",name:"Luxury Relaunch",tagline:"Refined & understated",description:"Premium positioning language for higher price points and discerning sellers.",accent:"from-yellow-600/25 to-yellow-600/0",previewHeadline:"A Considered Relaunch For A Distinctive Home",previewBody:"Presentation, positioning and buyer curation — the three levers that move exceptional properties."},{id:"marketing_review",name:"Marketing Review",tagline:"Data forward",description:"Analytical and consultative. Leads with exposure gaps and a marketing scorecard.",accent:"from-emerald-500/22 to-emerald-500/0",previewHeadline:"Your Property Marketing Score",previewBody:"I reviewed your previous listing across six marketing dimensions. Here’s what I found."},{id:"neighborhood_expert",name:"Neighborhood Expert",tagline:"Hyper-local",description:"Leans on local buyer demand and comparable activity in the immediate area.",accent:"from-teal-500/22 to-teal-500/0",previewHeadline:"What’s Really Happening On Your Street",previewBody:"Buyer activity in your neighborhood tells a very different story than the headlines."},{id:"personal_introduction",name:"Personal Introduction",tagline:"Neighbor to neighbor",description:"Conversational and personal — feels like a handwritten note, not a marketing piece.",accent:"from-rose-500/22 to-rose-500/0",previewHeadline:"Hi — I’m Your Neighbor Who Happens To Sell Homes",previewBody:"I noticed your home came off the market and I wanted to reach out personally."},{id:"professional_review",name:"Professional Review",tagline:"Credible & structured",description:"Polished, businesslike and process-driven. Great for analytical sellers.",accent:"from-indigo-500/22 to-indigo-500/0",previewHeadline:"A Professional Review Of Your Previous Listing",previewBody:"A clear, structured assessment — and the exact process I would use to relaunch."}],ias=[{id:"professional",name:"Professional",note:"Clean structure, confident tone"},{id:"luxury",name:"Luxury",note:"Serif headlines, gold rules, generous space"},{id:"friendly",name:"Friendly",note:"Warm, conversational, approachable"},{id:"minimal",name:"Minimal",note:"Short, direct, nothing extra"},{id:"modern",name:"Modern",note:"Crisp sans type, bold accents"}],Nhr=["New Lead","Attempting Contact","Conversation Started","Nurturing","Appointment Requested","Appointment Scheduled","Listing Presentation","Listing Signed","Long Term Follow Up","Lost"],khr=[{value:"immediately",label:"As soon as possible"},{value:"1-3",label:"In the next 1–3 months"},{value:"3-6",label:"In 3–6 months"},{value:"6-12",label:"In 6–12 months"},{value:"just_curious",label:"Just curious for now"}],Shr=["Not enough showings","No offers","Marketing felt thin","Communication from my agent","Priced too high","Timing / market conditions","Something else"];function Chr(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function Ahr(s){const t=Chr(s)||"property",n=Math.random().toString(36).slice(2,7);return`${t}-${n}`}function AP(s){return s==null?"—":`$${Number(s).toLocaleString("en-US",{maximumFractionDigits:0})}`}const m3t="https://dashboard.relevelup.com";function aYe(){if(typeof window>"u")return m3t;const s=window.location.hostname;return s==="localhost"||s==="127.0.0.1"||s==="dashboard.relevelup.com"?window.location.origin:m3t}function oas(s){return`${aYe()}/revival/${s}`}const p3t=[Fr,Cl,_x,Gu,kF,cn];function f3t(){const s="revival_sid";let t=sessionStorage.getItem(s);return t||(t=Math.random().toString(36).slice(2)+Date.now().toString(36),sessionStorage.setItem(s,t)),t}async function uBe(s){const{data:t,error:n}=await q.functions.invoke("listing-revival-public",{body:s});if(n)throw n;if(t!=null&&t.error)throw new Error(String(t.error));return t}function Ehr(){var I,R;const{slug:s=""}=Di(),[t]=fc(),[n,r]=j.useState(null),[a,i]=j.useState(!0),[l,o]=j.useState(!1),[c,d]=j.useState(!1),u=j.useRef(null),[h,m]=j.useState({first_name:"",last_name:"",email:"",phone:"",still_selling:"",timeline:"",frustration:"",preferred_contact:"email",comments:"",wants_plan:!0,honeypot:""}),p=(z,$)=>m(H=>({...H,[z]:$}));j.useEffect(()=>{let z=!0;return(async()=>{try{const $=await uBe({action:"get",slug:s});if(!z)return;r($),await uBe({action:"track",slug:s,event_type:t.get("src")==="qr"?"qr_scan":"page_view",session_id:f3t(),metadata:{referrer:document.referrer||null}})}catch{z&&r(null)}finally{z&&i(!1)}})(),()=>{z=!1}},[s,t]);const x=((n==null?void 0:n.campaign.content)??{}).landing,y=(n==null?void 0:n.campaign.landing_config)??{},v=(n==null?void 0:n.property)??((I=n==null?void 0:n.campaign)==null?void 0:I.property),b=n==null?void 0:n.agent,N=y.media_mode??"photo",S=aas(y.video_url),A=y.media_image_url||(v==null?void 0:v.photo_url)||null;j.useEffect(()=>{v!=null&&v.property_address&&(document.title=`Your Free Property Review — ${v.property_address}`)},[v==null?void 0:v.property_address]);const T=j.useMemo(()=>(x==null?void 0:x.discover)??[],[x]),L=async z=>{if(z.preventDefault(),!(!h.first_name.trim()||!h.email.trim()&&!h.phone.trim())){o(!0);try{await uBe({action:"submit",slug:s,session_id:f3t(),...h}),d(!0),window.scrollTo({top:0,behavior:"smooth"})}catch{o(!1)}}};if(a)return e.jsx("div",{className:"min-h-screen grid place-items-center bg-[#f7f5f1]",children:e.jsx(Et,{className:"h-6 w-6 animate-spin text-[#0f2540]"})});if(!n)return e.jsx("div",{className:"min-h-screen grid place-items-center bg-[#f7f5f1] px-6 text-center",children:e.jsxs("div",{children:[e.jsx(ra,{className:"h-8 w-8 mx-auto text-[#0f2540]"}),e.jsx("h1",{className:"revival-serif text-2xl mt-3 text-[#0f2540]",children:"This review is no longer available"}),e.jsx("p",{className:"text-[#4a5568] mt-1",children:"The link may have expired. Please reach out to your agent directly."})]})});const M=n.campaign.theme??"estate";return e.jsxs("div",{className:`revival-theme revival-theme-${M} min-h-screen`,children:[e.jsxs("header",{className:"revival-dark relative overflow-hidden",children:[v!=null&&v.photo_url?e.jsx("img",{src:v.photo_url,alt:v.property_address,className:"absolute inset-0 h-full w-full object-cover opacity-25"}):null,e.jsx("div",{className:"relative mx-auto max-w-5xl px-6 py-16 sm:py-24 text-center",children:e.jsxs(kr.div,{initial:{opacity:0,y:18},animate:{opacity:1,y:0},transition:{duration:.6},children:[e.jsx("div",{className:"revival-eyebrow text-accent",children:(x==null?void 0:x.eyebrow)??"A complimentary review"}),e.jsx("h1",{className:"revival-serif text-4xl sm:text-[54px] leading-[1.08] mt-3",children:(x==null?void 0:x.headline)??"Your Free Real Estate Relaunch Review"}),e.jsx("p",{className:"text-white/75 text-lg mt-4 max-w-2xl mx-auto",children:(x==null?void 0:x.subheadline)??"A personalized look at why your home didn’t sell — and exactly what to do next."}),e.jsxs("div",{className:"mt-4 inline-flex items-center gap-2 rounded-full bg-white/10 px-4 py-2 text-sm",children:[e.jsx(ra,{className:"h-4 w-4 text-accent"})," ",v==null?void 0:v.property_address]}),e.jsx("div",{className:"mt-8",children:e.jsx(U,{size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>{var z;return(z=u.current)==null?void 0:z.scrollIntoView({behavior:"smooth"})},children:(x==null?void 0:x.cta)??"Get my free review"})})]})})]}),e.jsxs("main",{className:"mx-auto max-w-5xl px-6 py-14 space-y-14",children:[c?e.jsxs(kr.div,{initial:{opacity:0,scale:.97},animate:{opacity:1,scale:1},className:"revival-tile p-10 text-center",children:[e.jsx(zr,{className:"h-12 w-12 mx-auto text-accent"}),e.jsx("h2",{className:"revival-serif text-3xl mt-4",children:"Your review is on its way"}),e.jsxs("p",{className:"text-muted-foreground mt-2 max-w-lg mx-auto",children:[(b==null?void 0:b.name)??"Your agent"," has been notified and will personally prepare your Property Revival Plan. Watch your inbox — you’ll hear back shortly."]}),e.jsx(U,{className:"mt-6",asChild:!0,children:e.jsx("a",{href:`/revival/${s}/plan`,children:"View your Property Revival Plan"})})]}):null,e.jsxs("section",{className:`grid gap-8 items-center ${N==="none"?"":"lg:grid-cols-2"}`,children:[e.jsxs("div",{children:[e.jsxs("div",{className:"revival-eyebrow text-muted-foreground",children:["A word from ",(b==null?void 0:b.name)??"your agent"]}),e.jsx("p",{className:"mt-3 text-lg leading-relaxed",children:x==null?void 0:x.intro}),b?e.jsxs("div",{className:"mt-6 flex items-center gap-4",children:[b.avatar_url?e.jsx("img",{src:b.avatar_url,alt:b.name??"",className:"h-14 w-14 rounded-full object-cover"}):null,e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:b.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[b.title??"Real Estate Specialist",b.brokerage_name?` · ${b.brokerage_name}`:""]})]})]}):null]}),N==="video"&&S?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"revival-tile aspect-video overflow-hidden",children:S.kind==="file"?e.jsx("video",{src:S.src,controls:!0,playsInline:!0,className:"h-full w-full object-cover"}):e.jsx("iframe",{src:S.src,title:"Agent introduction",className:"h-full w-full",allowFullScreen:!0})}),y.video_caption?e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:y.video_caption}):null]}):N==="photo"&&A?e.jsx("div",{className:"revival-tile aspect-video overflow-hidden",children:e.jsx("img",{src:A,alt:(v==null?void 0:v.property_address)??"Property",className:"h-full w-full object-cover"})}):N!=="none"?e.jsx("div",{className:"revival-tile aspect-video grid place-items-center bg-muted/70",children:e.jsxs("div",{className:"text-center",children:[e.jsx($h,{className:"h-12 w-12 mx-auto text-accent"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:["A personal introduction from ",(b==null?void 0:b.name)??"your agent"]})]})}):null]}),v&&y.show_property_snapshot!==!1?e.jsxs("section",{className:"revival-tile overflow-hidden grid md:grid-cols-[1.1fr_1fr]",children:[v.photo_url?e.jsx("img",{src:v.photo_url,alt:v.property_address,className:"h-full w-full object-cover min-h-[220px]"}):e.jsx("div",{className:"revival-dark min-h-[220px]"}),e.jsxs("div",{className:"p-7",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Your property"}),e.jsx("h3",{className:"revival-serif text-2xl mt-1",children:v.property_address}),e.jsx("p",{className:"text-muted-foreground",children:[v.city,v.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mt-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Original"}),e.jsx("div",{className:"text-lg font-semibold",children:AP(v.original_price)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Final"}),e.jsx("div",{className:"text-lg font-semibold",children:AP(v.final_price)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Days listed"}),e.jsx("div",{className:"text-lg font-semibold",children:v.days_on_market??"—"})]})]})]})]}):null,T.length&&y.show_discover!==!1?e.jsxs("section",{children:[e.jsx("h2",{className:"revival-serif text-3xl text-center",children:"Inside your free review"}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 mt-7",children:T.map((z,$)=>{const H=p3t[$%p3t.length];return e.jsxs(kr.div,{initial:{opacity:0,y:18},whileInView:{opacity:1,y:0},viewport:{once:!0},transition:{delay:$*.06,duration:.45},className:"revival-tile p-6",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-accent/15 grid place-items-center",children:e.jsx(H,{className:"h-5 w-5 text-accent-foreground"})}),e.jsx("div",{className:"font-semibold mt-3",children:z.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 leading-relaxed",children:z.body})]},$)})})]}):null,(R=x==null?void 0:x.testimonial)!=null&&R.quote&&y.show_testimonial!==!1?e.jsxs("section",{className:"revival-dark rounded-3xl p-10 text-center",children:[e.jsxs("p",{className:"revival-serif text-2xl leading-relaxed max-w-3xl mx-auto",children:["“",x.testimonial.quote,"”"]}),e.jsx("p",{className:"text-accent text-sm mt-4 uppercase tracking-[0.2em]",children:x.testimonial.author})]}):null,e.jsxs("section",{ref:u,className:"revival-tile p-7 sm:p-10",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"No obligation, no pressure"}),e.jsx("h2",{className:"revival-serif text-3xl mt-1",children:"Request your free review"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:"Takes 60 seconds. Your information is never shared."})]}),e.jsxs("form",{onSubmit:L,className:"grid gap-4 sm:grid-cols-2 mt-7 max-w-2xl mx-auto",children:[e.jsx("input",{type:"text",tabIndex:-1,autoComplete:"off",className:"hidden",value:h.honeypot,onChange:z=>p("honeypot",z.target.value)}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"First name *"}),e.jsx(xe,{required:!0,value:h.first_name,onChange:z=>p("first_name",z.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Last name"}),e.jsx(xe,{value:h.last_name,onChange:z=>p("last_name",z.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Email"}),e.jsx(xe,{type:"email",value:h.email,onChange:z=>p("email",z.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Phone"}),e.jsx(xe,{value:h.phone,onChange:z=>p("phone",z.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Are you still interested in selling?"}),e.jsxs(Ns,{value:h.still_selling,onValueChange:z=>p("still_selling",z),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select one"})}),e.jsxs(js,{children:[e.jsx(et,{value:"yes",children:"Yes"}),e.jsx(et,{value:"maybe",children:"Maybe — depends on the plan"}),e.jsx(et,{value:"no",children:"Not right now"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Your timeline"}),e.jsxs(Ns,{value:h.timeline,onValueChange:z=>p("timeline",z),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select one"})}),e.jsx(js,{children:khr.map(z=>e.jsx(et,{value:z.value,children:z.label},z.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Biggest frustration last time"}),e.jsxs(Ns,{value:h.frustration,onValueChange:z=>p("frustration",z),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select one"})}),e.jsx(js,{children:Shr.map(z=>e.jsx(et,{value:z,children:z},z))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Preferred contact method"}),e.jsxs(Ns,{value:h.preferred_contact,onValueChange:z=>p("preferred_contact",z),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"email",children:"Email"}),e.jsx(et,{value:"phone",children:"Phone call"}),e.jsx(et,{value:"text",children:"Text message"})]})]})]}),e.jsxs("div",{className:"sm:col-span-2 space-y-1.5",children:[e.jsx(te,{children:"Anything you'd like me to know?"}),e.jsx(Fs,{rows:3,value:h.comments,onChange:z=>p("comments",z.target.value)})]}),e.jsxs("label",{className:"sm:col-span-2 flex items-center gap-3 text-sm",children:[e.jsx(xi,{checked:h.wants_plan,onCheckedChange:z=>p("wants_plan",!!z)}),"Send me the full Property Revival Plan for my home"]}),e.jsx("div",{className:"sm:col-span-2",children:e.jsx(U,{type:"submit",size:"lg",className:"w-full bg-accent text-accent-foreground hover:bg-accent/90",disabled:l,children:l?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"})," Sending…"]}):(x==null?void 0:x.cta)??"Get my free review"})})]})]})]}),e.jsxs("footer",{className:"revival-dark py-10 text-center",children:[e.jsx("div",{className:"text-lg font-semibold",children:b==null?void 0:b.name}),e.jsx("div",{className:"text-accent text-sm",children:(b==null?void 0:b.title)??"Real Estate Specialist"}),e.jsx("div",{className:"text-white/60 text-sm mt-2",children:[b==null?void 0:b.phone,b==null?void 0:b.email].filter(Boolean).join(" · ")}),b!=null&&b.brokerage_name?e.jsx("div",{className:"text-white/40 text-xs mt-3",children:b.brokerage_name}):null]})]})}const gw="#0f2540",P5="#c9a227";function rZ({children:s,className:t,footer:n,page:r}){return e.jsxs("div",{"data-revival-plan-page":"",className:Mt("revival-plan-page relative mx-auto w-full max-w-[816px] bg-white text-[#1a2230]","aspect-[8.5/11] overflow-hidden flex flex-col shadow-[0_30px_70px_-40px_rgba(15,37,64,.6)]",t),children:[s,n!==void 0?e.jsxs("div",{className:"absolute bottom-0 inset-x-0 flex items-center justify-between px-10 pb-6 text-[10px] tracking-[0.22em] uppercase text-[#0f2540]/45",children:[e.jsx("span",{children:n}),r?e.jsx("span",{children:String(r).padStart(2,"0")}):null]}):null]})}function hde({eyebrow:s,title:t}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] tracking-[0.28em] uppercase font-bold",style:{color:P5},children:s}),e.jsx("h2",{className:"revival-serif text-[30px] leading-tight mt-1",style:{color:gw},children:t}),e.jsx("div",{className:"mt-3 h-[3px] w-14 rounded-full",style:{background:P5}})]})}function Thr({label:s,value:t}){const n=Math.max(0,Math.min(5,Number(t)||0));return e.jsxs("div",{className:"rounded-xl border border-[#0f2540]/12 px-4 py-3",children:[e.jsxs("div",{className:"flex items-baseline justify-between",children:[e.jsx("span",{className:"text-[12.5px] font-semibold capitalize",style:{color:gw},children:s.replace(/_/g," ")}),e.jsxs("span",{className:"text-[12px] tabular-nums text-[#0f2540]/60",children:[n," ",e.jsx("span",{className:"text-[10px]",children:"/ 5"})]})]}),e.jsx("div",{className:"mt-2 flex gap-1",children:[1,2,3,4,5].map(r=>e.jsx("span",{className:"h-[6px] flex-1 rounded-full",style:{background:r<=n?P5:"rgba(15,37,64,.10)"}},r))})]})}function iYe({plan:s,property:t,agent:n,url:r,className:a}){var u,h,m;const i=t.property_address??"Your Property",l=[t.city,t.state].filter(Boolean).join(", "),o=Object.entries((s==null?void 0:s.scores)??{}),c=(s==null?void 0:s.strategy_weeks)??[],d=n.name?`${n.name} · Property Revival Plan`:"Property Revival Plan";return e.jsxs("div",{className:Mt("space-y-8",a),children:[e.jsxs(rZ,{children:[e.jsxs("div",{className:"relative h-[52%] overflow-hidden",style:{background:gw},children:[t.photo_url?e.jsx("img",{src:t.photo_url,alt:i,className:"absolute inset-0 h-full w-full object-cover opacity-55"}):null,e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(180deg, rgba(15,37,64,.35), ${gw})`}}),e.jsxs("div",{className:"relative h-full flex flex-col justify-end px-12 pb-9 text-white",children:[n.brokerage_name?e.jsx("div",{className:"text-[10.5px] tracking-[0.3em] uppercase text-white/70 font-bold",children:n.brokerage_name}):null,e.jsxs("div",{className:"text-[11px] tracking-[0.3em] uppercase font-bold mt-3",style:{color:P5},children:["Prepared exclusively for ",t.seller_name||"you"]}),e.jsx("h1",{className:"revival-serif text-[46px] leading-[1.05] mt-2",children:"Property Revival Plan"}),e.jsxs("p",{className:"text-white/80 mt-2 text-[15px]",children:[i,l?` · ${l}`:""]})]})]}),e.jsxs("div",{className:"flex-1 px-12 pt-8 flex flex-col",children:[e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[{k:"Original price",v:AP(t.original_price)},{k:"Final price",v:AP(t.final_price)},{k:"Days on market",v:t.days_on_market??"—"}].map(p=>e.jsxs("div",{className:"rounded-xl border border-[#0f2540]/12 px-4 py-4 text-center",children:[e.jsx("div",{className:"text-[9.5px] tracking-[0.22em] uppercase text-[#0f2540]/50",children:p.k}),e.jsx("div",{className:"text-[20px] font-bold mt-1",style:{color:gw},children:p.v})]},p.k))}),s!=null&&s.intro?e.jsx("p",{className:"mt-7 text-[14.5px] leading-7 text-[#28313f]",children:s.intro}):null,e.jsxs("div",{className:"mt-auto mb-12 flex items-center gap-5 border-t border-[#0f2540]/10 pt-6",children:[n.avatar_url?e.jsx("img",{src:n.avatar_url,alt:n.name??"",className:"h-[74px] w-[74px] rounded-full object-cover"}):null,e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-[17px] font-bold",style:{color:gw},children:n.name}),e.jsxs("div",{className:"text-[12px] text-[#0f2540]/60",children:[n.title??"Real Estate Specialist",n.brokerage_name?` · ${n.brokerage_name}`:""]}),e.jsx("div",{className:"text-[12px] text-[#0f2540]/70 mt-1",children:[n.phone,n.email].filter(Boolean).join(" · ")})]}),r?e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"rounded-lg border border-[#0f2540]/15 p-2 bg-white",children:e.jsx(fS,{value:r,size:64,level:"M",fgColor:gw})}),e.jsx("div",{className:"text-[8.5px] tracking-[0.18em] uppercase text-[#0f2540]/45 mt-1",children:"View online"})]}):null]})]})]}),o.length?e.jsx(rZ,{footer:d,page:2,children:e.jsxs("div",{className:"px-12 pt-12 flex-1 flex flex-col",children:[e.jsx(hde,{eyebrow:"Section One",title:"Marketing scorecard"}),e.jsx("p",{className:"mt-4 text-[14px] leading-7 text-[#28313f]",children:"A review of how the previous listing performed across the six areas that most influence a sale. Each area is rated on a 1–5 scale, where 5 means the listing was doing everything today’s buyers respond to."}),e.jsx("div",{className:"mt-6 grid grid-cols-2 gap-3",children:o.map(([p,f])=>e.jsx(Thr,{label:p,value:Number(f)},p))}),(u=s==null?void 0:s.buyers_experienced)!=null&&u.length?e.jsxs("div",{className:"mt-8",children:[e.jsx("div",{className:"text-[10.5px] tracking-[0.28em] uppercase font-bold",style:{color:P5},children:"What buyers experienced"}),e.jsx("ul",{className:"mt-3 space-y-2",children:s.buyers_experienced.slice(0,5).map((p,f)=>e.jsxs("li",{className:"flex gap-3 text-[13.5px] leading-6 text-[#28313f]",children:[e.jsx("span",{className:"mt-[7px] h-[6px] w-[6px] shrink-0 rounded-full",style:{background:P5}}),p]},f))})]}):null]})}):null,(h=s==null?void 0:s.differently)!=null&&h.length?e.jsx(rZ,{footer:d,page:3,children:e.jsxs("div",{className:"px-12 pt-12 flex-1 flex flex-col",children:[e.jsx(hde,{eyebrow:"Section Two",title:"What we would do differently"}),e.jsxs("p",{className:"mt-4 text-[14px] leading-7 text-[#28313f]",children:["Every point below is part of the plan for ",i," — not a general list."]}),e.jsx("div",{className:"mt-6 grid grid-cols-2 gap-3",children:s.differently.slice(0,10).map((p,f)=>e.jsxs("div",{className:"rounded-xl border border-[#0f2540]/12 px-4 py-3 flex gap-3",children:[e.jsx("span",{className:"h-[22px] w-[22px] shrink-0 rounded-full grid place-items-center text-[11px] font-bold text-white",style:{background:gw},children:f+1}),e.jsx("span",{className:"text-[13px] leading-6 text-[#28313f]",children:p})]},f))})]})}):null,c.length?e.jsx(rZ,{footer:d,page:4,children:e.jsxs("div",{className:"px-12 pt-12 flex-1 flex flex-col",children:[e.jsx(hde,{eyebrow:"Section Three",title:"Your relaunch strategy"}),e.jsxs("p",{className:"mt-4 text-[14px] leading-7 text-[#28313f]",children:["A week-by-week plan for bringing ",i," back to market with momentum."]}),e.jsx("div",{className:"mt-6 space-y-3",children:c.slice(0,5).map((p,f)=>e.jsxs("div",{className:"rounded-xl border border-[#0f2540]/12 p-5 flex gap-5",children:[e.jsx("div",{className:"h-11 w-11 shrink-0 rounded-xl grid place-items-center text-white font-bold",style:{background:gw},children:f+1}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] tracking-[0.26em] uppercase font-bold",style:{color:P5},children:p.week}),e.jsx("div",{className:"text-[16px] font-semibold mt-0.5",style:{color:gw},children:p.title}),e.jsx("p",{className:"text-[13px] leading-6 text-[#28313f] mt-1",children:p.body})]})]},f))})]})}):null,e.jsx(rZ,{footer:d,page:5,children:e.jsxs("div",{className:"px-12 pt-12 flex-1 flex flex-col",children:[e.jsx(hde,{eyebrow:"Section Four",title:"Your next steps"}),(m=s==null?void 0:s.questions)!=null&&m.length?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-5 text-[10.5px] tracking-[0.28em] uppercase font-bold",style:{color:P5},children:"Questions to ask any agent"}),e.jsx("ol",{className:"mt-3 space-y-2",children:s.questions.slice(0,6).map((p,f)=>e.jsxs("li",{className:"flex gap-3 text-[13.5px] leading-6 text-[#28313f]",children:[e.jsxs("span",{className:"text-[12px] font-bold tabular-nums",style:{color:gw},children:[f+1,"."]}),p]},f))})]}):null,e.jsxs("div",{className:"mt-8 rounded-2xl p-8 text-white",style:{background:gw},children:[e.jsx("div",{className:"text-[10.5px] tracking-[0.28em] uppercase font-bold",style:{color:P5},children:"An invitation"}),e.jsx("p",{className:"mt-3 text-[14.5px] leading-7 text-white/85",children:(s==null?void 0:s.invitation)??"Let’s walk through this plan together — no pressure, just helpful guidance."}),e.jsxs("div",{className:"mt-6 flex items-center gap-5",children:[n.avatar_url?e.jsx("img",{src:n.avatar_url,alt:n.name??"",className:"h-[64px] w-[64px] rounded-full object-cover"}):null,e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-[16px] font-bold",children:n.name}),e.jsx("div",{className:"text-[12px] text-white/60",children:n.title??"Real Estate Specialist"}),e.jsx("div",{className:"text-[12.5px] mt-1",style:{color:P5},children:[n.phone,n.email,n.website_url].filter(Boolean).join(" · ")})]}),r?e.jsx("div",{className:"rounded-lg bg-white p-2",children:e.jsx(fS,{value:r,size:60,level:"M",fgColor:gw})}):null]})]})]})})]})}const aZ=[15,37,64],hBe=[201,162,39],g3t=[31,41,55],mde=[107,114,128];async function Mhr(s,t=8){return AW.toDataURL(s,{margin:0,scale:t,color:{dark:"#0f2540",light:"#ffffff"}})}function Phr(s){return[s.title,s.brokerage_name,s.phone,s.email,s.website_url].filter(Boolean).map(String)}function bat(s){return s.replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase().slice(0,60)}async function Lhr(s){const{campaign:t,agent:n,url:r,photoDataUrl:a}=s,i=t.property,l=new No({unit:"pt",format:[648,432],orientation:"landscape"}),o=648,c=432;if(l.setFillColor(...aZ),l.rect(0,0,o,c,"F"),a)try{l.addImage(a,"JPEG",0,0,o,c*.62)}catch{}l.setFillColor(...aZ),l.rect(0,c*.6,o,c*.4,"F"),l.setFillColor(...hBe),l.rect(0,c*.6-4,o,4,"F"),l.setTextColor(...hBe),l.setFont("helvetica","bold"),l.setFontSize(9),l.text("LISTING REVIVAL",44,c*.6+34),l.setTextColor(255,255,255),l.setFont("times","normal"),l.setFontSize(28),l.text(l.splitTextToSize(s.headline??"Your home deserves a second chance.",o-88),44,c*.6+68),l.setFont("helvetica","normal"),l.setFontSize(11),l.setTextColor(220,224,232),l.text(l.splitTextToSize(s.subhead??`A complimentary marketing review for ${(i==null?void 0:i.property_address)??"your property"}.`,o-88),44,c*.6+118),l.addPage([648,432],"landscape"),l.setFillColor(255,255,255),l.rect(0,0,o,c,"F"),l.setFillColor(...aZ),l.rect(0,0,10,c,"F");const d=44;l.setTextColor(...aZ),l.setFont("times","normal"),l.setFontSize(19),l.text(n.name??"",d,54),l.setFont("helvetica","normal"),l.setFontSize(9),l.setTextColor(...mde),l.text(Phr(n).join(" · "),d,72,{maxWidth:o/2+40}),l.setDrawColor(...hBe),l.setLineWidth(1),l.line(d,88,o/2+60,88),l.setTextColor(...g3t),l.setFont("times","normal"),l.setFontSize(11.5);const u=s.message??`I noticed ${(i==null?void 0:i.property_address)??"your home"} recently came off the market. I put together a private, no-obligation review of what buyers saw — and exactly what I would do differently to get it sold. Scan the code and it's yours in seconds.`;l.text(l.splitTextToSize(u,o/2+16),d,112);const h=await Mhr(r);l.addImage(h,"PNG",d,c-150,108,108),l.setFont("helvetica","bold"),l.setFontSize(10),l.setTextColor(...aZ),l.text("Scan for your free review",d+122,c-112),l.setFont("helvetica","normal"),l.setFontSize(8.5),l.setTextColor(...mde),l.text(r,d+122,c-96,{maxWidth:220});const m=o/2+96;l.setDrawColor(210,214,220),l.setLineWidth(.7),l.rect(m,132,o-m-44,116),l.setFontSize(8),l.setTextColor(...mde),l.text("MAILING ADDRESS",m+10,126),l.setFontSize(11),l.setTextColor(...g3t),[(i==null?void 0:i.seller_name)??"Current Resident",(i==null?void 0:i.mailing_address)??(i==null?void 0:i.property_address)??"",[(i==null?void 0:i.mailing_city)??(i==null?void 0:i.city),(i==null?void 0:i.mailing_state)??(i==null?void 0:i.state),(i==null?void 0:i.mailing_zip)??(i==null?void 0:i.zip)].filter(Boolean).join(", ")].filter(Boolean).forEach((f,x)=>l.text(String(f),m+14,162+x*18,{maxWidth:o-m-72})),l.setDrawColor(210,214,220),l.rect(o-118,40,74,62),l.setFontSize(7.5),l.setTextColor(...mde),l.text("POSTAGE",o-96,74),l.save(`revival-postcard-${bat((i==null?void 0:i.property_address)??t.name)}.pdf`)}async function las(s){try{const n=await(await fetch(s,{mode:"cors"})).blob();return await new Promise(r=>{const a=new FileReader;a.onloadend=()=>r(String(a.result)),a.onerror=()=>r(null),a.readAsDataURL(n)})}catch{return null}}async function Ihr(s,t){const{toPng:n}=await ui(async()=>{const{toPng:d}=await Promise.resolve().then(()=>PUt);return{toPng:d}},void 0),r=Array.from(s.querySelectorAll("img")),a=r.map(d=>d.getAttribute("src")??"");await Promise.all(r.map(async(d,u)=>{const h=a[u];if(!h||h.startsWith("data:"))return;const m=await las(h);m&&d.setAttribute("src",m)}));let i;try{i=await n(s,{pixelRatio:3,cacheBust:!0,backgroundColor:"#ffffff",width:s.offsetWidth,height:s.offsetHeight})}finally{r.forEach((d,u)=>{a[u]&&d.setAttribute("src",a[u])})}const l=new No({unit:"pt",format:"letter",compress:!0}),o=l.internal.pageSize.getWidth(),c=l.internal.pageSize.getHeight();l.addImage(i,"PNG",0,0,o,c,void 0,"FAST"),l.save(`revival-letter-${bat(t)}.pdf`)}async function cas(s,t){const{toPng:n}=await ui(async()=>{const{toPng:d}=await Promise.resolve().then(()=>PUt);return{toPng:d}},void 0),r=Array.from(s.querySelectorAll("[data-revival-plan-page]"));if(!r.length)return;const a=Array.from(s.querySelectorAll("img")),i=a.map(d=>d.getAttribute("src")??"");await Promise.all(a.map(async(d,u)=>{const h=i[u];if(!h||h.startsWith("data:"))return;const m=await las(h);m&&d.setAttribute("src",m)}));const l=new No({unit:"pt",format:"letter",compress:!0}),o=l.internal.pageSize.getWidth(),c=l.internal.pageSize.getHeight();try{for(let d=0;d0&&l.addPage(),l.addImage(h,"PNG",0,0,o,c,void 0,"FAST")}}finally{a.forEach((d,u)=>{i[u]&&d.setAttribute("src",i[u])})}l.save(`revival-plan-${bat(t)}.pdf`)}function x3t(){var m,p,f;const{slug:s=""}=Di(),[t,n]=j.useState(null),[r,a]=j.useState(!0),[i,l]=j.useState(!1),o=j.useRef(null),c=((m=t==null?void 0:t.campaign)==null?void 0:m.property)??(t==null?void 0:t.property)??null,d=async()=>{if(o.current){l(!0);try{await cas(o.current,(c==null?void 0:c.property_address)??"plan")}finally{l(!1)}}};if(j.useEffect(()=>{let x=!0;return(async()=>{try{const{data:y,error:v}=await q.functions.invoke("listing-revival-public",{body:{action:"get",slug:s}});if(v)throw v;if(!x)return;n(y),await q.functions.invoke("listing-revival-public",{body:{action:"track",slug:s,event_type:"plan_view"}})}catch{x&&n(null)}finally{x&&a(!1)}})(),()=>{x=!1}},[s]),j.useEffect(()=>{c!=null&&c.property_address&&(document.title=`Property Revival Plan — ${c.property_address}`)},[c==null?void 0:c.property_address]),r)return e.jsx("div",{className:"min-h-screen grid place-items-center bg-[#f7f5f1]",children:e.jsx(Et,{className:"h-6 w-6 animate-spin text-[#0f2540]"})});if(!t||!((f=(p=t.campaign)==null?void 0:p.content)!=null&&f.plan))return e.jsx("div",{className:"min-h-screen grid place-items-center bg-[#f7f5f1] px-6 text-center",children:e.jsxs("div",{children:[e.jsx(ra,{className:"h-8 w-8 mx-auto text-[#0f2540]"}),e.jsx("h1",{className:"revival-serif text-2xl mt-3 text-[#0f2540]",children:"This plan is no longer available"})]})});const{agent:u}=t,h=t.campaign.content.plan;return e.jsxs("div",{className:`revival-theme revival-theme-${t.campaign.theme??"estate"} min-h-screen bg-[#f7f5f1]`,children:[e.jsxs("div",{className:"mx-auto max-w-[900px] px-4 sm:px-6 py-8 sm:py-12",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-6",children:[e.jsxs("div",{className:"revival-eyebrow text-[#0f2540]/60",children:["Prepared for ",(c==null?void 0:c.property_address)??"your home"]}),e.jsxs("button",{onClick:d,disabled:i,className:"inline-flex items-center gap-2 rounded-full bg-[#0f2540] text-white px-5 py-2.5 text-sm font-semibold disabled:opacity-60",children:[i?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(pi,{className:"h-4 w-4"}),"Download PDF"]})]}),e.jsx("div",{ref:o,children:e.jsx(iYe,{plan:h,property:c??{property_address:"",city:null,state:null,photo_url:null,original_price:null,final_price:null,days_on_market:null},agent:u})}),u!=null&&u.phone||u!=null&&u.email?e.jsxs("div",{className:"mt-10 flex flex-wrap justify-center gap-3",children:[u.phone?e.jsxs("a",{href:`tel:${u.phone}`,className:"rounded-full bg-[#c9a227] text-[#0f2540] px-6 py-3 font-semibold",children:["Call ",u.phone]}):null,u.email?e.jsxs("a",{href:`mailto:${u.email}`,className:"rounded-full border border-[#0f2540]/25 text-[#0f2540] px-6 py-3 font-semibold",children:["Email ",u.name]}):null]}):null]}),e.jsxs("footer",{className:"py-10 text-center border-t border-border",children:[u!=null&&u.avatar_url?e.jsx("img",{src:u.avatar_url,alt:u.name??"",className:"h-16 w-16 rounded-full object-cover mx-auto"}):null,e.jsx("div",{className:"text-lg font-semibold mt-3",children:u==null?void 0:u.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:(u==null?void 0:u.title)??"Real Estate Specialist"}),u!=null&&u.brokerage_name?e.jsx("div",{className:"text-xs text-muted-foreground mt-2",children:u.brokerage_name}):null]})]})}function Rhr(){const{user:s}=vs();return ct({queryKey:["revival-campaigns",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("listing_revival_campaigns").select("*, property:listing_revival_properties(*)").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function Dhr(s){return ct({queryKey:["revival-campaign",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("listing_revival_campaigns").select("*, property:listing_revival_properties(*)").eq("id",s).maybeSingle();if(n)throw n;return t??null}})}function Ohr(){const{user:s}=vs();return ct({queryKey:["revival-properties",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("listing_revival_properties").select("*").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function das(){const{user:s}=vs();return ct({queryKey:["revival-leads",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("listing_revival_leads").select("*").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function Fhr(){const{user:s}=vs();return ct({queryKey:["revival-tasks",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("listing_revival_tasks").select("*").order("due_date",{ascending:!0});if(n)throw n;return t??[]}})}function uas(){const{user:s}=vs();return ct({queryKey:["revival-events",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("listing_revival_events").select("*").order("created_at",{ascending:!1}).limit(1e3);if(n)throw n;return t??[]}})}function _at(){const s=Qt(),t=()=>{["revival-campaigns","revival-campaign","revival-properties","revival-leads","revival-tasks","revival-events"].forEach(c=>s.invalidateQueries({queryKey:[c]}))},n=yt({mutationFn:async c=>{const{data:d,error:u}=await q.functions.invoke("listing-revival-generate",{body:c});if(u)throw u;if(d!=null&&d.error)throw new Error(String(d.error));return d},onSuccess:t,onError:c=>re.error(c.message)}),r=yt({mutationFn:async c=>{const{error:d}=await q.from("listing_revival_campaigns").update(c.patch).eq("id",c.id);if(d)throw d},onSuccess:()=>{t(),re.success("Saved")},onError:c=>re.error(c.message)}),a=yt({mutationFn:async c=>{const{error:d}=await q.from("listing_revival_properties").update(c.patch).eq("id",c.id);if(d)throw d},onSuccess:()=>{t(),re.success("Property updated")},onError:c=>re.error(c.message)}),i=yt({mutationFn:async c=>{const{error:d}=await q.from("listing_revival_campaigns").delete().eq("id",c);if(d)throw d},onSuccess:()=>{t(),re.success("Campaign deleted")},onError:c=>re.error(c.message)}),l=yt({mutationFn:async c=>{const{error:d}=await q.from("listing_revival_campaigns").update({status:c.archived?"archived":"active",published:!c.archived}).eq("id",c.id);if(d)throw d;return c},onSuccess:c=>{t(),re.success(c.archived?"Campaign archived":"Campaign restored")},onError:c=>re.error(c.message)}),o=yt({mutationFn:async c=>{const{error:d}=await q.from("listing_revival_tasks").update({completed_at:c.done?new Date().toISOString():null}).eq("id",c.id);if(d)throw d},onSuccess:t,onError:c=>re.error(c.message)});return{generate:n,saveCampaign:r,saveProperty:a,deleteCampaign:i,archiveCampaign:l,toggleTask:o,invalidate:t}}const zhr=[{id:"dashboard",label:"Dashboard",icon:Lm},{id:"campaigns",label:"Campaigns",icon:cn},{id:"properties",label:"Properties",icon:ra},{id:"letters",label:"Letters",icon:ln},{id:"landing",label:"Landing Pages",icon:fl},{id:"plans",label:"Revival Plans",icon:Ur},{id:"followup",label:"Follow Up",icon:iy},{id:"analytics",label:"Analytics",icon:Cl},{id:"templates",label:"Templates",icon:ej},{id:"settings",label:"Settings",icon:R4}];function Qb({label:s,value:t,icon:n,delay:r=0,hint:a}){return e.jsxs(kr.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{delay:r,duration:.45,ease:[.22,1,.36,1]},className:"revival-tile p-5",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("span",{className:"revival-eyebrow text-muted-foreground",children:s}),e.jsx(n,{className:"h-4 w-4 text-accent"})]}),e.jsx("div",{className:"mt-3 text-3xl font-bold tabular-nums tracking-tight",children:t}),a?e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:a}):null]})}function Bhr(){const s=Wn(),[t,n]=j.useState("dashboard"),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState(null),d=NJn(),u=Rhr(),h=Ohr(),m=das(),p=Fhr(),f=uas(),{toggleTask:x,archiveCampaign:y,deleteCampaign:v}=_at(),b=u.data??[],N=m.data??[],S=f.data??[],A=p.data??[],T=j.useMemo(()=>{const V=K=>S.filter(Z=>Z.event_type===K).length;return{properties:(h.data??[]).length,campaigns:b.length,letters:b.filter(K=>{var Z;return(Z=K.content)==null?void 0:Z.letter}).length,qr:V("qr_scan"),visits:V("page_view"),planViews:V("plan_view"),leads:N.length,appointments:V("appointment"),won:N.filter(K=>K.stage==="listing_signed").length,hot:N.filter(K=>K.temperature==="hot").length}},[b,N,S,h.data]),L=j.useMemo(()=>{const V=[];for(let K=13;K>=0;K--){const Z=new Date(Date.now()-K*864e5),Q=Z.toISOString().slice(0,10);V.push({day:Gs(Z,"MMM d"),visits:S.filter(le=>le.event_type==="page_view"&&le.created_at.startsWith(Q)).length,scans:S.filter(le=>le.event_type==="qr_scan"&&le.created_at.startsWith(Q)).length,leads:N.filter(le=>le.created_at.startsWith(Q)).length})}return V},[S,N]),M=V=>V.status==="archived",I=b.filter(V=>{var Z,Q;if(i?!M(V):M(V))return!1;const K=r.trim().toLowerCase();return K?`${V.name} ${((Z=V.property)==null?void 0:Z.property_address)??""} ${((Q=V.property)==null?void 0:Q.seller_name)??""}`.toLowerCase().includes(K):!0}),R=b.filter(M).length,z=V=>s(`/apps/listing-revival/campaigns/${V}`),$=V=>{navigator.clipboard.writeText(oas(V)),re.success("Landing page link copied")},H=V=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"relative max-w-sm flex-1 min-w-[200px]",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:r,onChange:K=>a(K.target.value),placeholder:"Search campaigns…",className:"pl-9"})]}),e.jsxs(U,{variant:i?"default":"outline",size:"sm",onClick:()=>l(K=>!K),children:[e.jsx(n1,{className:"h-3.5 w-3.5 mr-1.5"}),i?"Viewing archived":`Archived (${R})`]})]}),I.length===0?e.jsx("div",{className:"revival-tile p-10 text-center text-muted-foreground",children:i?"No archived campaigns.":V}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:I.map((K,Z)=>{var ne,ie,ce,je;const Q=h$.find(be=>be.id===K.style),le=N.filter(be=>be.campaign_id===K.id).length,ue=S.filter(be=>be.campaign_id===K.id&&be.event_type==="page_view").length,se=M(K);return e.jsxs(kr.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{delay:Math.min(Z*.04,.3),duration:.4},className:Mt("revival-tile overflow-hidden",se&&"opacity-80"),children:[e.jsxs("div",{className:"h-28 bg-muted relative",children:[(ne=K.property)!=null&&ne.photo_url?e.jsx("img",{src:K.property.photo_url,alt:K.property.property_address??"",className:"h-full w-full object-cover",loading:"lazy"}):e.jsx("div",{className:"h-full w-full revival-dark grid place-items-center",children:e.jsx(ra,{className:"h-7 w-7 text-accent"})}),e.jsx(Be,{className:"absolute top-3 left-3 bg-background/90 text-foreground border-0",children:(Q==null?void 0:Q.name)??K.style}),se?e.jsx(Be,{className:"absolute top-3 right-3 bg-foreground/85 text-background border-0",children:"Archived"}):null]}),e.jsxs("div",{className:"p-4",children:[e.jsx("div",{className:"font-semibold leading-tight",children:((ie=K.property)==null?void 0:ie.property_address)??K.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:((ce=K.property)==null?void 0:ce.seller_name)??"Homeowner"}),e.jsxs("div",{className:"mt-3 flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fl,{className:"h-3.5 w-3.5"}),ue]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3.5 w-3.5"}),le]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ra,{className:"h-3.5 w-3.5"}),((je=K.property)==null?void 0:je.days_on_market)??"—"," DOM"]})]}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsxs(U,{size:"sm",className:"flex-1",onClick:()=>z(K.id),children:["Open ",e.jsx(Oa,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsx(U,{size:"sm",variant:"outline",onClick:()=>$(K.slug),children:e.jsx(Pa,{className:"h-3.5 w-3.5"})}),e.jsx(U,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:`/revival/${K.slug}`,target:"_blank",rel:"noreferrer",children:e.jsx(Sr,{className:"h-3.5 w-3.5"})})}),e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsx(U,{size:"sm",variant:"outline",children:e.jsx(ey,{className:"h-3.5 w-3.5"})})}),e.jsxs(Eu,{align:"end",children:[e.jsx(La,{onClick:()=>y.mutate({id:K.id,archived:!se}),children:se?e.jsxs(e.Fragment,{children:[e.jsx(jM,{className:"h-4 w-4 mr-2"})," Restore campaign"]}):e.jsxs(e.Fragment,{children:[e.jsx(n1,{className:"h-4 w-4 mr-2"})," Archive campaign"]})}),e.jsx(l1,{}),e.jsxs(La,{className:"text-destructive focus:text-destructive",onClick:()=>{var be;return c({id:K.id,name:((be=K.property)==null?void 0:be.property_address)??K.name})},children:[e.jsx(In,{className:"h-4 w-4 mr-2"})," Delete permanently"]})]})]})]})]})]},K.id)})}),e.jsx(Fl,{open:!!o,onOpenChange:K=>!K&&c(null),children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Delete this campaign?"}),e.jsxs(Ll,{children:[o==null?void 0:o.name," — the letter, landing page, QR link, plan and follow-up tasks will be permanently removed. This can't be undone. Archive instead if you may need it later."]})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{o&&v.mutate(o.id),c(null)},children:"Delete permanently"})]})]})})]});return!d.isLoading&&!d.hasAccess?e.jsx(qs,{title:"Listing Revival",children:e.jsx("div",{className:"revival-theme -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)] grid place-items-center",children:e.jsxs("div",{className:"revival-tile p-10 text-center max-w-lg",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-2xl revival-dark grid place-items-center",children:e.jsx(cn,{className:"h-6 w-6 text-accent"})}),e.jsx("h2",{className:"revival-serif text-2xl mt-4",children:"Listing Revival is invite-only"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:"This tool is currently being rolled out to select LevelUp members. Reach out to your coach to request early access."})]})})}):e.jsx(qs,{title:"Listing Revival",children:e.jsxs("div",{className:"revival-theme relative -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)]",children:[e.jsxs(kr.div,{initial:{opacity:0,y:18},animate:{opacity:1,y:0},transition:{duration:.55,ease:[.22,1,.36,1]},className:"revival-dark rounded-3xl px-6 sm:px-10 py-9 relative overflow-hidden",children:[e.jsx("div",{className:"absolute -right-10 -top-16 h-56 w-56 rounded-full bg-accent/20 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"revival-eyebrow text-accent",children:"Listing Revival"}),e.jsx("h1",{className:"revival-serif text-3xl sm:text-[42px] leading-tight mt-2 max-w-2xl",children:"Turn Expired Listings Into Listing Appointments."}),e.jsx("p",{className:"text-white/70 mt-3 max-w-xl",children:"Import a property, choose a style, click once. Your letter, QR code, landing page, Property Revival Plan, emails, texts and follow-up tasks are built in under two minutes."}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3",children:[e.jsxs(U,{size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>s("/apps/listing-revival/new"),children:[e.jsx(an,{className:"h-4 w-4 mr-1"})," New Campaign"]}),e.jsx(U,{size:"lg",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",onClick:()=>n("campaigns"),children:"View campaigns"})]})]})]}),e.jsxs(oa,{value:t,onValueChange:n,className:"mt-6",children:[e.jsx(la,{className:"flex w-full overflow-x-auto no-scrollbar justify-start bg-transparent p-0 gap-2 h-auto",children:zhr.map(V=>e.jsxs(Kt,{value:V.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground rounded-full border border-border bg-card px-4 py-2 text-sm whitespace-nowrap",children:[e.jsx(V.icon,{className:"h-3.5 w-3.5 mr-1.5"}),V.label]},V.id))}),e.jsxs(Zt,{value:"dashboard",className:"mt-6 space-y-6",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-2 lg:grid-cols-5",children:[e.jsx(Qb,{label:"Properties",value:T.properties,icon:ra,delay:0}),e.jsx(Qb,{label:"Campaigns",value:T.campaigns,icon:cn,delay:.04}),e.jsx(Qb,{label:"Letters",value:T.letters,icon:ln,delay:.08}),e.jsx(Qb,{label:"QR Scans",value:T.qr,icon:Sf,delay:.12}),e.jsx(Qb,{label:"Page Visits",value:T.visits,icon:fl,delay:.16}),e.jsx(Qb,{label:"Plans Viewed",value:T.planViews,icon:Ur,delay:.2}),e.jsx(Qb,{label:"Seller Leads",value:T.leads,icon:Bn,delay:.24}),e.jsx(Qb,{label:"Appointments",value:T.appointments,icon:cv,delay:.28}),e.jsx(Qb,{label:"Listings Won",value:T.won,icon:Al,delay:.32}),e.jsx(Qb,{label:"Hot Leads",value:T.hot,icon:Xd,delay:.36,hint:"Score 75+"})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-3",children:[e.jsxs("div",{className:"revival-tile p-5 lg:col-span-2",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Last 14 days"}),e.jsx("div",{className:"text-lg font-semibold mt-1",children:"Homeowner engagement"}),e.jsx("div",{className:"h-64 mt-4",children:e.jsx(oj,{width:"100%",height:"100%",children:e.jsxs(Ett,{data:L,children:[e.jsxs("defs",{children:[e.jsxs("linearGradient",{id:"revVisits",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:0})]}),e.jsxs("linearGradient",{id:"revLeads",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--accent))",stopOpacity:.5}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--accent))",stopOpacity:0})]})]}),e.jsx($7,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",vertical:!1}),e.jsx(wb,{dataKey:"day",tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))"}),e.jsx(jb,{allowDecimals:!1,tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))",width:28}),e.jsx(Tg,{contentStyle:{borderRadius:12,border:"1px solid hsl(var(--border))"}}),e.jsx(M_,{type:"monotone",dataKey:"visits",stroke:"hsl(var(--primary))",fill:"url(#revVisits)",strokeWidth:2}),e.jsx(M_,{type:"monotone",dataKey:"leads",stroke:"hsl(var(--accent))",fill:"url(#revLeads)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Recent activity"}),e.jsxs("div",{className:"mt-3 space-y-3 max-h-64 overflow-auto pr-1",children:[S.slice(0,20).map(V=>e.jsxs("div",{className:"flex items-start gap-3 text-sm",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-accent mt-1.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium capitalize",children:V.event_type.replace(/_/g," ")}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Gs(new Date(V.created_at),"MMM d, h:mm a")})]})]},V.id)),S.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No activity yet. Mail your first letter to start tracking."}):null]})]})]}),e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Upcoming follow ups"}),e.jsxs("div",{className:"mt-3 space-y-2",children:[A.filter(V=>!V.completed_at).slice(0,6).map(V=>e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-border px-4 py-3",children:[e.jsx(xi,{checked:!!V.completed_at,onCheckedChange:K=>x.mutate({id:V.id,done:!!K})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:V.title}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:V.detail})]}),e.jsx(Be,{variant:"outline",children:Gs(new Date(`${V.due_date}T12:00:00`),"MMM d")})]},V.id)),A.filter(V=>!V.completed_at).length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing due. Create a campaign to generate your follow-up plan."}):null]})]})]}),e.jsx(Zt,{value:"campaigns",className:"mt-6",children:H("No campaigns yet — click New Campaign to build your first one.")}),e.jsx(Zt,{value:"properties",className:"mt-6",children:e.jsx("div",{className:"revival-tile overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/60 text-left",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3 font-semibold",children:"Property"}),e.jsx("th",{className:"px-4 py-3 font-semibold",children:"Seller"}),e.jsx("th",{className:"px-4 py-3 font-semibold",children:"Original"}),e.jsx("th",{className:"px-4 py-3 font-semibold",children:"Final"}),e.jsx("th",{className:"px-4 py-3 font-semibold",children:"DOM"}),e.jsx("th",{className:"px-4 py-3 font-semibold",children:"Expired"})]})}),e.jsxs("tbody",{children:[(h.data??[]).map(V=>e.jsxs("tr",{className:"border-t border-border",children:[e.jsx("td",{className:"px-4 py-3 font-medium",children:V.property_address}),e.jsx("td",{className:"px-4 py-3",children:V.seller_name??"—"}),e.jsx("td",{className:"px-4 py-3",children:AP(V.original_price)}),e.jsx("td",{className:"px-4 py-3",children:AP(V.final_price)}),e.jsx("td",{className:"px-4 py-3",children:V.days_on_market??"—"}),e.jsx("td",{className:"px-4 py-3",children:V.expiration_date??"—"})]},V.id)),(h.data??[]).length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-10 text-center text-muted-foreground",children:"No properties imported yet."})}):null]})]})})}),e.jsx(Zt,{value:"letters",className:"mt-6",children:H("Letters appear here once you create a campaign.")}),e.jsx(Zt,{value:"landing",className:"mt-6",children:H("Landing pages appear here once you create a campaign.")}),e.jsx(Zt,{value:"plans",className:"mt-6",children:H("Property Revival Plans appear here once you create a campaign.")}),e.jsxs(Zt,{value:"followup",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Open tasks"}),e.jsxs("div",{className:"mt-3 space-y-2",children:[A.filter(V=>!V.completed_at).map(V=>e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-border px-4 py-3",children:[e.jsx(xi,{checked:!1,onCheckedChange:()=>x.mutate({id:V.id,done:!0})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:V.title}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:V.detail})]}),e.jsx(Be,{variant:"outline",className:"capitalize",children:V.channel})]},V.id)),A.filter(V=>!V.completed_at).length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"All caught up."}):null]})]}),e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Seller leads"}),e.jsxs("div",{className:"mt-3 space-y-2",children:[N.map(V=>e.jsxs("div",{className:"rounded-xl border border-border px-4 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium",children:[V.first_name,V.last_name].filter(Boolean).join(" ")||"Homeowner"}),e.jsxs(Be,{className:Mt("capitalize border-0",V.temperature==="hot"&&"bg-red-500/15 text-red-600",V.temperature==="warm"&&"bg-amber-500/15 text-amber-700",V.temperature==="nurture"&&"bg-sky-500/15 text-sky-700",V.temperature==="low"&&"bg-muted text-muted-foreground"),children:[V.temperature," · ",V.lead_score]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:[V.timeline?`Timeline: ${V.timeline} · `:"",V.next_action]})]},V.id)),N.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No seller leads captured yet."}):null]})]})]}),e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Opportunity pipeline"}),e.jsx("div",{className:"mt-4 flex gap-2 overflow-x-auto no-scrollbar pb-1",children:Nhr.map(V=>{const K=V.toLowerCase().replace(/ /g,"_"),Z=N.filter(Q=>Q.stage===K).length;return e.jsxs("div",{className:"min-w-[150px] rounded-xl border border-border p-3",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:V}),e.jsx("div",{className:"text-2xl font-bold tabular-nums",children:Z})]},V)})})]})]}),e.jsxs(Zt,{value:"analytics",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-2 lg:grid-cols-4",children:[e.jsx(Qb,{label:"Lead capture %",value:`${T.visits?Math.round(T.leads/T.visits*100):0}%`,icon:Bn}),e.jsx(Qb,{label:"Scan → visit",value:`${T.qr?Math.round(T.visits/T.qr*100):0}%`,icon:Sf}),e.jsx(Qb,{label:"Appointments",value:T.appointments,icon:cv}),e.jsx(Qb,{label:"Conversion %",value:`${T.leads?Math.round(T.won/T.leads*100):0}%`,icon:Al})]}),e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Campaign performance"}),e.jsx("div",{className:"h-72 mt-4",children:e.jsx(oj,{width:"100%",height:"100%",children:e.jsxs(RLe,{data:b.slice(0,10).map(V=>{var K;return{name:(((K=V.property)==null?void 0:K.property_address)??V.name).slice(0,18),visits:S.filter(Z=>Z.campaign_id===V.id&&Z.event_type==="page_view").length,leads:N.filter(Z=>Z.campaign_id===V.id).length}}),children:[e.jsx($7,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",vertical:!1}),e.jsx(wb,{dataKey:"name",tick:{fontSize:10},stroke:"hsl(var(--muted-foreground))"}),e.jsx(jb,{allowDecimals:!1,tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))",width:28}),e.jsx(Tg,{contentStyle:{borderRadius:12,border:"1px solid hsl(var(--border))"}}),e.jsx(pN,{dataKey:"visits",fill:"hsl(var(--primary))",radius:[6,6,0,0]}),e.jsx(pN,{dataKey:"leads",fill:"hsl(var(--accent))",radius:[6,6,0,0]})]})})})]})]}),e.jsxs(Zt,{value:"templates",className:"mt-6 space-y-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Campaign styles"}),e.jsx("div",{className:"grid gap-3 mt-3 md:grid-cols-2 xl:grid-cols-3",children:h$.map(V=>e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:Mt("h-1.5 w-full rounded-full bg-gradient-to-r mb-4",V.accent)}),e.jsx("div",{className:"font-semibold",children:V.name}),e.jsx("div",{className:"text-xs uppercase tracking-wider text-accent-foreground/70",children:V.tagline}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:V.description}),e.jsxs("p",{className:"revival-serif text-[15px] mt-3 leading-snug",children:["“",V.previewHeadline,"”"]})]},V.id))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Letter templates"}),e.jsx("div",{className:"grid gap-3 mt-3 sm:grid-cols-2 lg:grid-cols-5",children:ias.map(V=>e.jsxs("div",{className:"revival-tile p-4",children:[e.jsx("div",{className:"font-semibold",children:V.name}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:V.note})]},V.id))})]})]}),e.jsx(Zt,{value:"settings",className:"mt-6",children:e.jsxs("div",{className:"revival-tile p-6 space-y-4 max-w-2xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:"Branding"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Letters, landing pages and emails automatically pull your name, photo, phone, brokerage and website from your LevelUp profile."}),e.jsx(U,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>s("/profile"),children:"Edit my profile"})]}),e.jsxs("div",{className:"border-t border-border pt-4",children:[e.jsx("div",{className:"font-semibold",children:"Agent OS integration"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Every seller submission creates or updates a contact, applies the ListingRevival, ExpiredSeller and LandingPageLead tags, opens an opportunity in your pipeline, logs the activity and creates your next follow-up task automatically."})]}),e.jsxs("div",{className:"border-t border-border pt-4",children:[e.jsx("div",{className:"font-semibold",children:"Availability"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Listing Revival is currently in private beta and visible to LevelUp admins only."})]})]})})]})]})})}const y3t=["Import the property","Choose the campaign style","Generate everything"];function Uhr(){var b;const s=Wn(),{user:t}=vs(),{generate:n,invalidate:r}=_at(),[a,i]=j.useState(0),[l,o]=j.useState(!1),[c,d]=j.useState(h$[0].id),[u,h]=j.useState("professional"),[m,p]=j.useState({property_address:"",city:"",state:"",zip:"",seller_name:"",seller_email:"",seller_phone:"",mailing_address:"",mailing_city:"",mailing_state:"",mailing_zip:"",original_price:"",final_price:"",days_on_market:"",expiration_date:"",mls_link:"",photo_url:"",agent_notes:""}),f=(N,S)=>p(A=>({...A,[N]:S})),x=a===0?m.property_address.trim().length>3:!0,y=async()=>{if(t){o(!0);try{const{data:N,error:S}=await q.from("listing_revival_properties").insert({owner_user_id:t.id,property_address:m.property_address.trim(),city:m.city||null,state:m.state||null,zip:m.zip||null,seller_name:m.seller_name||null,seller_email:m.seller_email||null,seller_phone:m.seller_phone||null,mailing_address:m.mailing_address||null,mailing_city:m.mailing_city||null,mailing_state:m.mailing_state||null,mailing_zip:m.mailing_zip||null,original_price:m.original_price?Number(m.original_price):null,final_price:m.final_price?Number(m.final_price):null,days_on_market:m.days_on_market?Number(m.days_on_market):null,expiration_date:m.expiration_date||null,mls_link:m.mls_link||null,photo_url:m.photo_url||null,agent_notes:m.agent_notes||null}).select().single();if(S)throw S;const{data:A,error:T}=await q.from("listing_revival_campaigns").insert({owner_user_id:t.id,property_id:N.id,name:m.property_address.trim(),slug:Ahr(m.property_address),style:c,letter_template:u,status:"generating",published:!0}).select().single();if(T)throw T;await n.mutateAsync({campaignId:A.id}),r(),re.success("Campaign built — everything is ready."),s(`/apps/listing-revival/campaigns/${A.id}`)}catch(N){re.error(N instanceof Error?N.message:"Could not create the campaign")}finally{o(!1)}}},v=(N,S,A={})=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:S}),e.jsx(xe,{value:m[N],onChange:T=>f(N,T.target.value),...A})]});return e.jsx(qs,{title:"New Revival Campaign",children:e.jsxs("div",{className:"revival-theme -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)]",children:[e.jsxs(U,{variant:"ghost",size:"sm",className:"gap-2 mb-4",onClick:()=>s("/apps/listing-revival"),children:[e.jsx(Aa,{className:"h-4 w-4"})," Back to Listing Revival"]}),e.jsx("div",{className:"flex items-center gap-3 mb-6",children:y3t.map((N,S)=>e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsx("div",{className:Mt("h-9 w-9 rounded-full grid place-items-center text-sm font-bold shrink-0 transition-colors",Sf("photo_url",N??""),label:"Property photo",prefix:"revival-property"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Agent notes"}),e.jsx(Fs,{rows:6,value:m.agent_notes,onChange:N=>f("agent_notes",N.target.value),placeholder:"Anything you know: why it didn't sell, condition, seller's motivation, photos were poor, etc."})]})]})]}):null,a===1?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"revival-tile p-6",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Step two"}),e.jsx("h2",{className:"revival-serif text-2xl mt-1",children:"Pick the voice of the campaign"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"The style shapes the letter, the landing page and the whole email and text sequence."}),e.jsx("div",{className:"grid gap-3 mt-5 md:grid-cols-2 xl:grid-cols-3",children:h$.map(N=>e.jsxs("button",{type:"button",onClick:()=>d(N.id),className:Mt("text-left rounded-2xl border p-5 transition-all",c===N.id?"border-accent ring-2 ring-accent/40 bg-accent/[0.04]":"border-border hover:border-accent/50"),children:[e.jsx("div",{className:Mt("h-1.5 w-full rounded-full bg-gradient-to-r mb-4",N.accent)}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"font-semibold",children:N.name}),c===N.id?e.jsx(Xr,{className:"h-4 w-4 text-accent"}):null]}),e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-muted-foreground",children:N.tagline}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:N.description}),e.jsxs("div",{className:"mt-3 rounded-xl bg-muted/60 p-3",children:[e.jsx("p",{className:"revival-serif text-[14px] leading-snug",children:N.previewHeadline}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:N.previewBody})]})]},N.id))})]}),e.jsxs("div",{className:"revival-tile p-6",children:[e.jsx("div",{className:"font-semibold",children:"Letter design"}),e.jsx("div",{className:"grid gap-3 mt-3 sm:grid-cols-3 lg:grid-cols-5",children:ias.map(N=>e.jsxs("button",{type:"button",onClick:()=>h(N.id),className:Mt("rounded-xl border p-4 text-left transition-all",u===N.id?"border-accent ring-2 ring-accent/40":"border-border hover:border-accent/50"),children:[e.jsx("div",{className:"font-medium",children:N.name}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:N.note})]},N.id))})]})]}):null,a===2?e.jsxs("div",{className:"revival-tile p-8 text-center max-w-2xl mx-auto",children:[e.jsx("div",{className:"mx-auto h-16 w-16 rounded-2xl revival-dark grid place-items-center",children:e.jsx(Lg,{className:"h-7 w-7 text-accent"})}),e.jsx("h2",{className:"revival-serif text-2xl mt-4",children:"Build the full campaign"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"One click creates the personalized letter with its QR code, the private landing page, the Property Revival Plan, a 7-email sequence, 5 texts, your call and video scripts, and a 30-day follow-up task plan."}),e.jsxs("div",{className:"mt-6 rounded-2xl border border-border p-5 text-left space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Property"}),e.jsx("span",{className:"font-medium",children:m.property_address||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Seller"}),e.jsx("span",{className:"font-medium",children:m.seller_name||"Homeowner"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Style"}),e.jsx("span",{className:"font-medium",children:(b=h$.find(N=>N.id===c))==null?void 0:b.name})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Letter"}),e.jsx("span",{className:"font-medium capitalize",children:u})]})]}),e.jsx(U,{size:"lg",className:"mt-6 w-full bg-accent text-accent-foreground hover:bg-accent/90",disabled:l,onClick:y,children:l?e.jsxs(e.Fragment,{children:[e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"})," Building your campaign…"]}):e.jsxs(e.Fragment,{children:[e.jsx(cn,{className:"h-4 w-4 mr-2"})," Generate campaign"]})})]}):null]},a)}),a<2?e.jsxs("div",{className:"flex justify-between mt-6",children:[e.jsx(U,{variant:"outline",disabled:a===0,onClick:()=>i(N=>N-1),children:"Back"}),e.jsxs(U,{disabled:!x,onClick:()=>i(N=>N+1),children:["Continue ",e.jsx(Oa,{className:"h-4 w-4 ml-1"})]})]}):e.jsx("div",{className:"flex justify-start mt-6",children:e.jsx(U,{variant:"outline",disabled:l,onClick:()=>i(1),children:"Back"})})]})})}const v3t={professional:{head:"font-semibold tracking-tight",body:"",rule:"bg-[#0f2540]",size:15},luxury:{head:"revival-serif font-normal tracking-tight",body:"revival-serif",rule:"bg-[#c9a227]",size:15.5},friendly:{head:"font-semibold",body:"",rule:"bg-[#c9a227]",size:15},minimal:{head:"font-medium tracking-tight",body:"",rule:"bg-neutral-300",size:14.5},modern:{head:"font-bold tracking-tighter uppercase",body:"",rule:"bg-[#0f2540]",size:15}};function qhr(s){return s<=900?1:s<=1150?.94:s<=1400?.88:s<=1700?.82:s<=2100?.76:.7}function b3t({campaign:s,letter:t,agent:n,url:r,className:a}){var h,m;const i=v3t[s.letter_template]??v3t.professional,l=s.property,o=t.paragraphs??[],c=o.join(" ").length+(((h=t.closing)==null?void 0:h.length)??0)+(((m=t.greeting)==null?void 0:m.length)??0),d=qhr(c),u={fontSize:`${(i.size*d).toFixed(2)}px`,lineHeight:1.6};return e.jsxs("div",{id:"revival-letter-sheet",className:Mt("mx-auto w-full max-w-[816px] bg-white text-[#1a2230] shadow-[0_30px_70px_-40px_rgba(15,37,64,.6)]","aspect-[8.5/11] overflow-hidden flex flex-col",a),children:[e.jsxs("div",{className:"flex items-stretch",children:[e.jsxs("div",{className:"flex-1 px-10 pt-9 pb-6",children:[n.brokerage_name?e.jsx("div",{className:"text-[11px] tracking-[0.28em] uppercase text-[#0f2540]/70 font-bold",children:n.brokerage_name}):null,e.jsx("div",{className:"text-2xl font-bold tracking-tight text-[#0f2540] mt-1",children:n.name??"Your Name"})]}),e.jsxs("div",{className:"w-[46%] bg-[#0f2540] text-white px-8 py-6 flex flex-col justify-center [clip-path:polygon(9%_0,100%_0,100%_100%,0_100%)]",children:[e.jsx("div",{className:"text-[10.5px] tracking-[0.2em] uppercase text-white/70",children:"A personal review prepared"}),e.jsx("div",{className:"text-[12px] tracking-[0.2em] uppercase font-bold text-[#c9a227]",children:"exclusively for you"})]})]}),e.jsxs("div",{className:"grid grid-cols-[1.15fr_1fr] gap-8 px-10 flex-1 min-h-0 pb-2",children:[e.jsxs("div",{className:"min-h-0 flex flex-col",children:[e.jsx("h1",{className:Mt("text-[#0f2540]",i.head),style:{fontSize:`${(30*Math.max(d,.82)).toFixed(1)}px`,lineHeight:1.12},children:t.greeting.replace(/,$/,"")}),e.jsx("div",{className:Mt("mt-1 h-[3px] w-16 rounded-full",i.rule)}),e.jsxs("div",{className:Mt("mt-4 text-[#28313f] flex flex-col",i.body),style:{...u,gap:`${(.7*d).toFixed(2)}em`},children:[o.map((p,f)=>e.jsx("p",{children:p},f)),t.closing?e.jsx("p",{className:"font-semibold text-[#0f2540]",children:t.closing}):null]}),e.jsxs("div",{className:"mt-auto pt-4",children:[e.jsx("div",{style:{fontSize:`${(13*d).toFixed(1)}px`},className:"text-[#28313f]",children:"Sincerely,"}),e.jsx("div",{className:"revival-serif italic text-[#0f2540] leading-tight mt-1",style:{fontSize:`${(26*d).toFixed(1)}px`},children:t.signature||n.name})]})]}),e.jsxs("div",{className:"min-h-0 space-y-4 pt-2",children:[l!=null&&l.photo_url?e.jsxs("div",{className:"overflow-hidden rounded-lg",children:[e.jsx("img",{src:l.photo_url,alt:l.property_address??"Property",className:"h-[190px] w-full object-cover",loading:"lazy"}),e.jsxs("div",{className:"bg-[#0f2540] text-white px-4 py-3 text-[11.5px] grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-white/60",children:"Property"}),e.jsx("div",{className:"font-semibold leading-tight",children:l.property_address})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-white/60",children:"Days on market"}),e.jsx("div",{className:"font-semibold",children:l.days_on_market??"—"})]})]})]}):null,e.jsxs("div",{className:"rounded-xl border border-[#c9a227]/45 p-4 text-center",children:[e.jsx("div",{className:"inline-block bg-[#c9a227] text-[#0f2540] text-[10px] font-extrabold tracking-[0.18em] uppercase px-3 py-1 rounded",children:"Scan to unlock"}),e.jsxs("div",{className:"revival-serif text-[19px] text-[#0f2540] leading-tight mt-2",children:["Your Private",e.jsx("br",{}),"Property Review"]}),e.jsx("div",{className:"flex justify-center my-3",children:e.jsx(fS,{value:r,size:116,level:"M",fgColor:"#0f2540"})}),e.jsx("div",{className:"text-[11px] text-[#28313f]",children:"Scan the QR code or visit"}),e.jsx("div",{className:"text-[11.5px] font-bold text-[#0f2540] break-all",children:r.replace(/^https?:\/\//,"")})]}),e.jsx("p",{className:"text-[11px] leading-5 text-[#4a5568] italic",children:t.ps})]})]}),e.jsxs("div",{className:"mt-4 bg-[#0f2540] text-white px-10 py-5 flex items-center gap-5",children:[n.avatar_url?e.jsx("img",{src:n.avatar_url,alt:n.name??"Agent",className:"h-16 w-16 rounded-lg object-cover"}):null,e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-lg font-bold tracking-wide uppercase",children:n.name}),e.jsx("div",{className:"text-[#c9a227] text-[12.5px] font-semibold",children:n.title??"Real Estate Specialist"})]}),e.jsxs("div",{className:"text-[12px] space-y-0.5 text-right text-white/85",children:[n.phone?e.jsx("div",{children:n.phone}):null,n.email?e.jsx("div",{children:n.email}):null,n.website_url?e.jsx("div",{children:n.website_url.replace(/^https?:\/\//,"")}):null]})]})]})}function has({letter:s,saving:t,onSave:n,onCancel:r}){const[a,i]=j.useState(s);j.useEffect(()=>{i(s)},[s]);const l=(u,h)=>i(m=>({...m,[u]:h})),o=(u,h)=>i(m=>({...m,paragraphs:m.paragraphs.map((p,f)=>f===u?h:p)})),c=()=>i(u=>({...u,paragraphs:[...u.paragraphs,""]})),d=u=>i(h=>({...h,paragraphs:h.paragraphs.filter((m,p)=>p!==u)}));return e.jsxs("div",{className:"rounded-xl border border-border bg-card p-5 space-y-5 max-w-3xl",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-semibold",children:"Edit letter"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your edits are saved to this campaign and used in the PDF."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{size:"sm",variant:"ghost",onClick:r,disabled:t,children:[e.jsx(er,{className:"h-3.5 w-3.5 mr-1.5"})," Cancel"]}),e.jsxs(U,{size:"sm",onClick:()=>n({...a,paragraphs:a.paragraphs.map(u=>u.trim()).filter(Boolean)}),disabled:t,children:[t?e.jsx(Et,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Ho,{className:"h-3.5 w-3.5 mr-1.5"}),"Save letter"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs",children:"Greeting"}),e.jsx(xe,{value:a.greeting??"",onChange:u=>l("greeting",u.target.value),placeholder:"Dear Jane,"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{className:"text-xs",children:"Body paragraphs"}),e.jsxs(U,{size:"sm",variant:"outline",onClick:c,children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1.5"})," Add paragraph"]})]}),a.paragraphs.map((u,h)=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx(Fs,{value:u,onChange:m=>o(h,m.target.value),rows:4,className:"flex-1"}),e.jsx(U,{size:"icon",variant:"ghost",onClick:()=>d(h),"aria-label":"Remove paragraph",children:e.jsx(In,{className:"h-4 w-4 text-muted-foreground"})})]},h))]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs",children:"Closing line"}),e.jsx(xe,{value:a.closing??"",onChange:u=>l("closing",u.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs",children:"Signature"}),e.jsx(xe,{value:a.signature??"",onChange:u=>l("signature",u.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"text-xs",children:"P.S."}),e.jsx(Fs,{value:a.ps??"",onChange:u=>l("ps",u.target.value),rows:2})]})]})}function _3t(s){if(!s)return null;const t=Math.floor(s/60),n=Math.round(s%60);return`${t}:${String(n).padStart(2,"0")}`}function $hr(s){return s.share_token?`https://video.relevelup.com/thumb/${s.share_token}`:s.thumbnail_url}function Vhr({video:s}){const[t,n]=j.useState(!1),r=$hr(s);return!r||t?e.jsx("div",{className:"h-full w-full grid place-items-center bg-gradient-to-br from-muted to-muted/40",children:e.jsx($h,{className:"h-7 w-7 text-muted-foreground/70"})}):e.jsx("img",{src:r,alt:s.title??"Video thumbnail",loading:"lazy",onError:()=>n(!0),className:"h-full w-full object-cover transition-transform duration-300 group-hover:scale-[1.04]"})}const Hhr=(()=>{if(typeof window>"u"||window.self===window.top)return!1;try{const s=document.featurePolicy;if(s!=null&&s.allowsFeature)return!(s.allowsFeature("camera")&&s.allowsFeature("microphone"))}catch{}return!0})();function Ghr({open:s,onOpenChange:t,onSelect:n,propertyAddress:r}){const{user:a}=vs(),[i,l]=j.useState("library"),[o,c]=j.useState([]),[d,u]=j.useState(!1),[h,m]=j.useState(""),[p,f]=j.useState("record"),[x,y]=j.useState(0),[v,b]=j.useState(0),N=f3(),S=j.useCallback(async()=>{if(a){u(!0);try{const{data:I,error:R}=await q.from("agent_videos").select("id, title, recipient_name, playback_url, thumbnail_url, share_token, duration_seconds, created_at").eq("owner_user_id",a.id).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(60);if(R)throw R;c(I??[])}catch{re.error("Could not load your video library")}finally{u(!1)}}},[a]);j.useEffect(()=>{s&&S()},[s,S]);const A=j.useMemo(()=>{const I=h.trim().toLowerCase();return I?o.filter(R=>`${R.title??""} ${R.recipient_name??""}`.toLowerCase().includes(I)):o},[o,h]),T=I=>{if(!I.playback_url){re.error("That video has no playable link yet");return}n(I.playback_url),t(!1)},L=I=>{!I&&(p==="uploading"||p==="processing")||(t(I),I||(f("record"),y(0),b(0)))},M=j.useCallback(async(I,R)=>{f("uploading");const z=r?`Listing Revival — ${r}`:"Listing Revival intro";try{const{videoId:$,libraryId:H}=await cL(z),{uploadUrl:V,apiKey:K}=await dL($),Z=new XMLHttpRequest;Z.upload.onprogress=ie=>{ie.lengthComputable&&y(ie.loaded/ie.total*100)},await new Promise((ie,ce)=>{Z.onload=()=>Z.status>=200&&Z.status<300?ie():ce(new Error("Upload failed")),Z.onerror=()=>ce(new Error("Upload failed")),Z.open("PUT",V),Z.setRequestHeader("AccessKey",K),Z.send(I)}),f("processing");const Q=`https://iframe.mediadelivery.net/embed/${H}/${$}`,le=Date.now(),ue=9e4;let se=0;for(;se<4;){if(await new Promise(ce=>setTimeout(ce,3e3)),Date.now()-le>ue){await N.mutateAsync({bunny_video_id:$,playback_url:`https://iframe.mediadelivery.net/play/${H}/${$}`,file_size_mb:I.size/(1024*1024),title:z,status:"processing",touch_type:"video"}),n(Q),re.success("Video saved — still encoding, it will appear shortly."),f("done"),setTimeout(()=>L(!1),1200);return}const ie=await fN($);if(se=ie.status,b(ie.encodeProgress||0),se===5||se===6)throw new Error("Video processing failed")}const ne=await fN($);await N.mutateAsync({bunny_video_id:$,playback_url:ne.directPlayUrl||Q,thumbnail_url:ne.thumbnailUrl,preview_url:ne.previewUrl||null,duration_seconds:ne.length||R,file_size_mb:(ne.storageSize||I.size)/(1024*1024),title:z,status:"ready",touch_type:"video"}),n(ne.directPlayUrl||Q),re.success("Video recorded and added to your landing page!"),f("done"),setTimeout(()=>L(!1),1200)}catch($){console.error("Revival recording upload error:",$),re.error("Failed to process video. Please try again."),f("record")}},[N,n,r]);return e.jsx(zs,{open:s,onOpenChange:L,children:e.jsxs(Ds,{className:"max-w-4xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Add a video to your landing page"}),e.jsx(Pr,{children:"Pick one you already recorded, or record a brand new one right here without leaving Listing Revival."})]}),e.jsxs(oa,{value:i,onValueChange:l,children:[e.jsxs(la,{className:"grid w-full grid-cols-2",children:[e.jsxs(Kt,{value:"library",children:[e.jsx(Gh,{className:"h-3.5 w-3.5 mr-1.5"})," My library"]}),e.jsxs(Kt,{value:"record",children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1.5"})," Record new"]})]}),e.jsxs(Zt,{value:"library",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:h,onChange:I=>m(I.target.value),placeholder:"Search your videos…",className:"pl-9"})]}),d?e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:Array.from({length:6}).map((I,R)=>e.jsx(xn,{className:"aspect-video rounded-xl"},R))}):A.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed border-border p-10 text-center",children:[e.jsx($h,{className:"h-8 w-8 mx-auto text-muted-foreground/60"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:o.length===0?"No finished videos yet — record one on the next tab.":"No videos match that search."}),e.jsxs(U,{size:"sm",variant:"outline",className:"mt-3",onClick:()=>l("record"),children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1.5"})," Record a video now"]})]}):e.jsx("div",{className:"grid gap-3 sm:grid-cols-3 max-h-[55vh] overflow-y-auto pr-1",children:A.map(I=>e.jsxs("button",{type:"button",onClick:()=>T(I),className:"group text-left rounded-xl border border-border bg-card overflow-hidden transition hover:border-primary hover:shadow-md focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsxs("div",{className:"aspect-video bg-muted overflow-hidden relative",children:[e.jsx(Vhr,{video:I}),_3t(I.duration_seconds)?e.jsx("span",{className:"absolute bottom-1.5 right-1.5 rounded bg-foreground/80 px-1.5 py-0.5 text-[10px] font-medium text-background",children:_3t(I.duration_seconds)}):null]}),e.jsxs("div",{className:"p-2.5",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:I.title||I.recipient_name||"Untitled video"}),I.created_at?e.jsx("div",{className:"text-[11px] text-muted-foreground",children:Gs(new Date(I.created_at),"MMM d, yyyy")}):null]})]},I.id))})]}),e.jsxs(Zt,{value:"record",className:"mt-4",children:[p==="record"?e.jsxs("div",{className:"space-y-3",children:[Hhr?e.jsxs("div",{className:"rounded-xl border border-border bg-muted/40 p-3 flex flex-wrap items-center gap-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground flex-1 min-w-[220px]",children:"This editor preview blocks camera access. Open the app in its own browser tab — recording works right here in the popup for your agents."}),e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>window.open(window.location.href,"_blank","noopener"),children:[e.jsx(Sr,{className:"h-3.5 w-3.5 mr-1.5"})," Open in new tab"]})]}):null,e.jsx(kE,{maxDurationSeconds:600,onRecordingComplete:M,onError:I=>re.error(I)})]}):null,p==="uploading"?e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Et,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading your video…"}),e.jsx(ro,{value:x,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(x),"%"]})]}):null,p==="processing"?e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Et,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing your video…"}),e.jsx(ro,{value:v,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(v),"%"]})]}):null,p==="done"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(Yo,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video added to your landing page!"})]}):null]})]})]})})}const Whr=[{id:"photo",label:"Property photo",hint:"Shows the listing photo. Best if you have no video.",icon:pc},{id:"video",label:"Video",hint:"Record one here, pick from your library, or paste a link.",icon:Wr},{id:"none",label:"Nothing",hint:"Hide the media block entirely for a clean, text-only intro.",icon:Vg}];function Khr({campaignId:s,content:t,landingConfig:n,propertyPhotoUrl:r,saving:a,onSave:i}){var A;const[l,o]=j.useState(t.landing),[c,d]=j.useState({...h3t,...n}),[u,h]=j.useState(!1),[m,p]=j.useState(!1);j.useEffect(()=>{o(t.landing)},[t.landing]),j.useEffect(()=>{d({...h3t,...n})},[n]);const f=(T,L)=>{o(M=>({...M??{},[T]:L})),h(!0)},x=(T,L)=>{d(M=>({...M,[T]:L})),h(!0)},y=(l==null?void 0:l.discover)??[],v=T=>f("discover",T),b=j.useMemo(()=>aas(c.video_url),[c.video_url]),N=c.media_image_url||r||null,S=()=>{i({content:{...t,landing:l},landing_config:c}),h(!1)};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("div",{className:"revival-eyebrow text-muted-foreground",children:"Landing page editor"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Everything here updates your public page instantly after saving."})]}),e.jsxs(U,{size:"sm",onClick:S,disabled:!u||a,children:[a?e.jsx(Et,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Ho,{className:"h-3.5 w-3.5 mr-1.5"}),"Save changes"]})]}),e.jsxs("div",{className:"revival-tile p-6 space-y-4",children:[e.jsx("div",{className:"font-semibold",children:"Headline & intro"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Eyebrow"}),e.jsx(xe,{value:(l==null?void 0:l.eyebrow)??"",onChange:T=>f("eyebrow",T.target.value),placeholder:"A complimentary review"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Button text"}),e.jsx(xe,{value:(l==null?void 0:l.cta)??"",onChange:T=>f("cta",T.target.value),placeholder:"Get my free review"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Headline"}),e.jsx(xe,{value:(l==null?void 0:l.headline)??"",onChange:T=>f("headline",T.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Subheadline"}),e.jsx(Fs,{rows:2,value:(l==null?void 0:l.subheadline)??"",onChange:T=>f("subheadline",T.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Personal intro paragraph"}),e.jsx(Fs,{rows:5,value:(l==null?void 0:l.intro)??"",onChange:T=>f("intro",T.target.value)})]})]}),e.jsxs("div",{className:"revival-tile p-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:"Intro media"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No video? Choose the property photo and the page still looks complete."})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:Whr.map(T=>{const L=(c.media_mode??"photo")===T.id;return e.jsxs("button",{type:"button",onClick:()=>x("media_mode",T.id),className:`text-left rounded-xl border p-4 transition ${L?"border-accent ring-1 ring-accent":"border-border hover:border-accent/50"}`,children:[e.jsx(T.icon,{className:`h-5 w-5 ${L?"text-accent":"text-muted-foreground"}`}),e.jsx("div",{className:"font-medium mt-2",children:T.label}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:T.hint})]},T.id)})}),(c.media_mode??"photo")==="video"?e.jsxs("div",{className:"space-y-3 rounded-xl border border-border p-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Video link"}),e.jsx(xe,{value:c.video_url??"",onChange:T=>x("video_url",T.target.value),placeholder:"Paste a YouTube, Vimeo, Loom or .mp4 link"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Or record a new video right here — it saves to your library automatically."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(U,{type:"button",size:"sm",onClick:()=>p(!0),children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1.5"})," Record or choose a video"]}),c.video_url?e.jsxs(U,{type:"button",size:"sm",variant:"ghost",onClick:()=>x("video_url",""),children:[e.jsx(In,{className:"h-3.5 w-3.5 mr-1.5"})," Remove video"]}):null]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Caption under the video"}),e.jsx(xe,{value:c.video_caption??"",onChange:T=>x("video_caption",T.target.value),placeholder:"A personal introduction"})]}),e.jsx("div",{className:"aspect-video rounded-lg overflow-hidden bg-muted grid place-items-center",children:(b==null?void 0:b.kind)==="file"?e.jsx("video",{src:b.src,controls:!0,className:"h-full w-full object-cover"}):b?e.jsx("iframe",{src:b.src,title:"Video preview",className:"h-full w-full",allowFullScreen:!0}):e.jsxs("div",{className:"text-center text-sm text-muted-foreground",children:[e.jsx($h,{className:"h-8 w-8 mx-auto mb-1 opacity-60"})," Your video preview appears here"]})})]}):null,(c.media_mode??"photo")==="photo"?e.jsxs("div",{className:"space-y-3 rounded-xl border border-border p-4",children:[e.jsx(q9,{label:"Photo shown next to your intro",value:c.media_image_url??"",onChange:T=>x("media_image_url",T),prefix:"revival-landing",hint:"Leave empty to use the property photo from this campaign."}),N?e.jsx("img",{src:N,alt:"Landing media",className:"rounded-lg w-full max-h-64 object-cover"}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No property photo on this campaign yet — add one here or the media block will be hidden."})]}):null]}),e.jsxs("div",{className:"revival-tile p-6 space-y-4",children:[e.jsx("div",{className:"font-semibold",children:"Sections"}),[["show_property_snapshot","Property snapshot","Address, pricing history and days on market."],["show_discover","Inside your free review","The cards explaining what the seller receives."],["show_testimonial","Testimonial","The quote from a past client."]].map(([T,L,M])=>e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:L}),e.jsx("p",{className:"text-xs text-muted-foreground",children:M})]}),e.jsx(wn,{checked:c[T]!==!1,onCheckedChange:I=>x(T,I)})]},T))]}),e.jsxs("div",{className:"revival-tile p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"font-semibold",children:"Review highlights"}),e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>v([...y,{title:"",body:""}]),children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1.5"})," Add card"]})]}),y.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No highlight cards yet."}):null,y.map((T,L)=>e.jsxs("div",{className:"rounded-xl border border-border p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Be,{variant:"outline",children:L+1}),e.jsx(xe,{value:T.title,placeholder:"Card title",onChange:M=>v(y.map((I,R)=>R===L?{...I,title:M.target.value}:I))}),e.jsx(U,{size:"icon",variant:"ghost",onClick:()=>v(y.filter((M,I)=>I!==L)),children:e.jsx(In,{className:"h-4 w-4"})})]}),e.jsx(Fs,{rows:2,value:T.body,placeholder:"What this card explains",onChange:M=>v(y.map((I,R)=>R===L?{...I,body:M.target.value}:I))})]},L))]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(U,{onClick:S,disabled:!u||a,children:[a?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-2"}),"Save changes"]})}),e.jsx(Ghr,{open:m,onOpenChange:p,propertyAddress:((A=t==null?void 0:t.landing)==null?void 0:A.headline)??null,onSelect:T=>{x("video_url",T),x("media_mode","video")}})]})}const mBe={intro:"",scores:{},buyers_experienced:[],differently:[],strategy_weeks:[],questions:[],resources:[],invitation:""},Yhr=s=>Math.min(5,Math.max(1,Math.round(s||1)));function Zhr({plan:s,saving:t,onSave:n}){const[r,a]=j.useState({...mBe,...s});j.useEffect(()=>{a({...mBe,...s})},[s]);const i=(o,c)=>a(d=>({...d,[o]:c})),l=(o,c,d)=>e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{children:c}),e.jsxs(U,{type:"button",size:"sm",variant:"ghost",onClick:()=>i(o,[...r[o]??[],""]),children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d}),e.jsxs("div",{className:"space-y-2",children:[(r[o]??[]).map((u,h)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Fs,{value:u,rows:2,onChange:m=>{const p=[...r[o]??[]];p[h]=m.target.value,i(o,p)}}),e.jsx(U,{type:"button",size:"icon",variant:"ghost",onClick:()=>i(o,(r[o]??[]).filter((m,p)=>p!==h)),children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]},h)),(r[o]??[]).length===0?e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"Nothing yet."}):null]})]});return e.jsxs("div",{className:"revival-tile p-5 space-y-7",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"revival-eyebrow text-accent-foreground/70",children:"Edit plan"}),e.jsx("h3",{className:"revival-serif text-xl mt-1",children:"Make it yours"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Every word in the seller presentation can be rewritten here. Changes update the preview, the PDF and the live plan page."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{type:"button",size:"sm",variant:"ghost",onClick:()=>a({...mBe,...s}),children:[e.jsx(Kg,{className:"h-3.5 w-3.5 mr-1.5"})," Reset"]}),e.jsxs(U,{type:"button",size:"sm",disabled:t,className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>n(r),children:[t?e.jsx(Et,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Ho,{className:"h-3.5 w-3.5 mr-1.5"}),"Save plan"]})]})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"plan-intro",children:"Introduction"}),e.jsx(Fs,{id:"plan-intro",rows:4,value:r.intro,onChange:o=>i("intro",o.target.value)})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{children:"Marketing scorecard (1–5)"}),e.jsxs(U,{type:"button",size:"sm",variant:"ghost",onClick:()=>i("scores",{...r.scores,[`Category ${Object.keys(r.scores??{}).length+1}`]:3}),children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1"})," Add category"]})]}),e.jsx("div",{className:"space-y-2",children:Object.entries(r.scores??{}).map(([o,c],d)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{value:o,onChange:u=>{const h=Object.entries(r.scores??{});h[d]=[u.target.value,c],i("scores",Object.fromEntries(h))}}),e.jsx(xe,{type:"number",min:1,max:5,className:"w-20",value:c,onChange:u=>i("scores",{...r.scores,[o]:Yhr(Number(u.target.value))})}),e.jsx(U,{type:"button",size:"icon",variant:"ghost",onClick:()=>{const u={...r.scores??{}};delete u[o],i("scores",u)},children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]},`${o}-${d}`))})]}),l("buyers_experienced","What buyers experienced","Honest observations about the previous listing."),l("differently","What we will do differently","The concrete changes you are proposing."),e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{children:"Relaunch timeline"}),e.jsxs(U,{type:"button",size:"sm",variant:"ghost",onClick:()=>i("strategy_weeks",[...r.strategy_weeks??[],{week:`Week ${(r.strategy_weeks??[]).length+1}`,title:"",body:""}]),children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1"})," Add week"]})]}),e.jsx("div",{className:"space-y-3",children:(r.strategy_weeks??[]).map((o,c)=>e.jsxs("div",{className:"rounded-xl border p-3 space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{className:"w-28",value:o.week,placeholder:"Week 1",onChange:d=>{const u=[...r.strategy_weeks??[]];u[c]={...o,week:d.target.value},i("strategy_weeks",u)}}),e.jsx(xe,{value:o.title,placeholder:"Title",onChange:d=>{const u=[...r.strategy_weeks??[]];u[c]={...o,title:d.target.value},i("strategy_weeks",u)}}),e.jsx(U,{type:"button",size:"icon",variant:"ghost",onClick:()=>i("strategy_weeks",(r.strategy_weeks??[]).filter((d,u)=>u!==c)),children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]}),e.jsx(Fs,{rows:2,value:o.body,placeholder:"What happens this week",onChange:d=>{const u=[...r.strategy_weeks??[]];u[c]={...o,body:d.target.value},i("strategy_weeks",u)}})]},c))})]}),l("questions","Questions for the seller","Prompts you want to discuss at the appointment."),e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{children:"Resources"}),e.jsxs(U,{type:"button",size:"sm",variant:"ghost",onClick:()=>i("resources",[...r.resources??[],{title:"",body:""}]),children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1"})," Add resource"]})]}),e.jsx("div",{className:"space-y-3",children:(r.resources??[]).map((o,c)=>e.jsxs("div",{className:"rounded-xl border p-3 space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:o.title,placeholder:"Title",onChange:d=>{const u=[...r.resources??[]];u[c]={...o,title:d.target.value},i("resources",u)}}),e.jsx(U,{type:"button",size:"icon",variant:"ghost",onClick:()=>i("resources",(r.resources??[]).filter((d,u)=>u!==c)),children:e.jsx(In,{className:"h-4 w-4 text-destructive"})})]}),e.jsx(Fs,{rows:2,value:o.body,onChange:d=>{const u=[...r.resources??[]];u[c]={...o,body:d.target.value},i("resources",u)}})]},c))})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx(te,{htmlFor:"plan-invitation",children:"Closing invitation"}),e.jsx(Fs,{id:"plan-invitation",rows:3,value:r.invitation,onChange:o=>i("invitation",o.target.value)})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(U,{type:"button",disabled:t,className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>n(r),children:[t?e.jsx(Et,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(Ho,{className:"h-4 w-4 mr-1.5"}),"Save plan"]})})]})}const Xhr=[{key:"letter",label:"Letter",icon:ln,blurb:"Personalized print-ready letter mailed to the homeowner."},{key:"qr_scan",label:"QR Scan",icon:Sf,blurb:"Homeowner scans the unique code on the letter."},{key:"page_view",label:"Landing Page",icon:fl,blurb:"Private property review page opens on their phone."},{key:"form_submit",label:"Lead Form",icon:iy,blurb:"They request the plan — Agent OS is updated instantly."},{key:"plan_view",label:"Revival Plan",icon:Ur,blurb:"The full Property Revival Plan is delivered."},{key:"email",label:"Email Sequence",icon:$r,blurb:"Seven branded emails nurture the conversation."},{key:"sms",label:"Text Sequence",icon:Ki,blurb:"Five short texts keep momentum going."},{key:"appointment",label:"Appointment",icon:cv,blurb:"They book a complimentary strategy session."},{key:"listing",label:"Listing Signed",icon:Eh,blurb:"The relaunch begins."}];function Qhr({counts:s,onStep:t,activeStep:n}){return e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:Xhr.map((r,a)=>{const i=r.icon,l=s[r.key]??0,o=l>0;return e.jsxs(kr.button,{type:"button",onClick:()=>t==null?void 0:t(r.key),initial:{opacity:0,y:16},animate:{opacity:1,y:0},transition:{delay:a*.05,duration:.45,ease:[.22,1,.36,1]},className:Mt("revival-tile text-left p-5 relative overflow-hidden group",n===r.key&&"ring-2 ring-accent"),children:[e.jsx("div",{className:"absolute right-4 top-4 text-[11px] font-bold tracking-widest text-muted-foreground",children:String(a+1).padStart(2,"0")}),e.jsx("div",{className:Mt("h-11 w-11 rounded-xl grid place-items-center transition-colors",o?"bg-accent/20 text-accent-foreground":"bg-muted text-muted-foreground"),children:e.jsx(i,{className:"h-5 w-5"})}),e.jsx("div",{className:"mt-3 font-semibold",children:r.label}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 leading-relaxed",children:r.blurb}),e.jsxs("div",{className:"mt-3 flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl font-bold tabular-nums",children:l}),e.jsx("span",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:o?"recorded":"waiting"})]}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-1 bg-gradient-to-r from-accent to-accent/0 origin-left transition-transform duration-500 scale-x-0 group-hover:scale-x-100"})]},r.key)})})}function Jhr({open:s,onOpenChange:t,campaignId:n,email:r,ctaUrl:a,seller:i}){const{user:l}=vs(),[o,c]=j.useState([]),[d,u]=j.useState(""),[h,m]=j.useState([]),[p,f]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState("View your property review"),[N,S]=j.useState(""),[A,T]=j.useState(!1),[L,M]=j.useState(!1),I=j.useRef(null);j.useEffect(()=>{!s||!r||(c([]),u(""),m([]),f(r.subject||""),y(r.body||""),S(""))},[s,r==null?void 0:r.key,r==null?void 0:r.subject]),j.useEffect(()=>{if(!s||!r)return;const V=setTimeout(async()=>{T(!0);try{const{data:K,error:Z}=await q.functions.invoke("listing-revival-email",{body:{campaign_id:n,subject:p,body:x,preview_text:r.preview,cta_label:v,cta_url:a,preview_only:!0}});if(Z)throw Z;K!=null&&K.html&&S(K.html)}catch{}finally{T(!1)}},400);return()=>clearTimeout(V)},[s,n,p,x,v,a,r==null?void 0:r.key]),j.useEffect(()=>{I.current&&clearTimeout(I.current);const V=d.trim();if(!l||V.length<2||/\S+@\S+\.\S+/.test(V)){m([]);return}return I.current=setTimeout(async()=>{const K=`%${V}%`,Z=q,{data:Q}=await Z.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",l.id).not("email","is",null).or(`first_name.ilike.${K},last_name.ilike.${K},email.ilike.${K}`).order("first_name",{ascending:!0}).limit(6);m(Q||[])},200),()=>{I.current&&clearTimeout(I.current)}},[d,l==null?void 0:l.id]);const R=V=>{V.email&&(c(K=>K.some(Z=>Z.email.toLowerCase()===V.email.toLowerCase())?K:[...K,V]),u(""),m([]))},z=()=>{const V=d.trim();if(!/\S+@\S+\.\S+/.test(V)){re.error("Enter a valid email address");return}R({email:V})},$=j.useMemo(()=>!!r&&o.length>0&&p.trim().length>0&&!L,[r,o,p,L]),H=async()=>{if(r){M(!0);try{const{data:V,error:K}=await q.functions.invoke("listing-revival-email",{body:{campaign_id:n,subject:p,body:x,preview_text:r.preview,cta_label:v,cta_url:a,email_key:r.key,recipients:o}});if(K)throw K;if(!(V!=null&&V.success))throw new Error((V==null?void 0:V.error)||"Could not send the email");re.success(V.failed?`Sent to ${V.sent} · ${V.failed} failed`:`Email sent to ${V.sent} ${V.sent===1?"contact":"contacts"}`),t(!1)}catch(V){re.error((V==null?void 0:V.message)||"Could not send the email")}finally{M(!1)}}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-4 w-4"})," Send this email"]}),e.jsx(Pr,{children:"Pick contacts from your Agent OS database — they receive the fully branded HTML version."})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[1fr_1.1fr]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Recipients"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:d,onChange:V=>u(V.target.value),placeholder:"Search contacts or type an email",onKeyDown:V=>{V.key==="Enter"&&(V.preventDefault(),z())}}),e.jsx(U,{type:"button",variant:"outline",size:"icon",onClick:z,children:e.jsx(an,{className:"h-4 w-4"})})]}),h.length>0&&e.jsx("div",{className:"rounded-xl border divide-y overflow-hidden",children:h.map(V=>e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-2 hover:bg-muted/60 flex items-center gap-2",onClick:()=>R({email:V.email,first_name:V.first_name,last_name:V.last_name,contact_id:V.id}),children:[e.jsx(So,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm",children:[V.first_name,V.last_name].filter(Boolean).join(" ")||V.email}),e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:V.email})]},V.id))}),(i==null?void 0:i.email)&&!o.some(V=>V.email.toLowerCase()===i.email.toLowerCase())&&e.jsxs(U,{type:"button",size:"sm",variant:"ghost",onClick:()=>R({email:i.email,first_name:(i.name||"").split(" ")[0]}),children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1.5"})," Add seller (",i.email,")"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 pt-1",children:o.map(V=>e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[[V.first_name,V.last_name].filter(Boolean).join(" ")||V.email,e.jsx("button",{type:"button",onClick:()=>c(K=>K.filter(Z=>Z.email!==V.email)),children:e.jsx(er,{className:"h-3 w-3"})})]},V.email))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Subject"}),e.jsx(xe,{value:p,onChange:V=>f(V.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Message"}),e.jsx(Fs,{rows:10,value:x,onChange:V=>y(V.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ",e.jsx("code",{children:"{{first_name}}"}),", ",e.jsx("code",{children:"{{address}}"})," or ",e.jsx("code",{children:"{{agent_name}}"})," to personalize."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Button label"}),e.jsx(xe,{value:v,onChange:V=>b(V.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{className:"flex items-center gap-2",children:["Live preview ",A&&e.jsx(Et,{className:"h-3 w-3 animate-spin"})]}),e.jsx("div",{className:"rounded-xl border overflow-hidden bg-muted/30 h-[520px]",children:N?e.jsx("iframe",{title:"Email preview",srcDoc:N,className:"w-full h-full border-0"}):e.jsx("div",{className:"h-full grid place-items-center text-sm text-muted-foreground",children:"Building preview…"})})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{onClick:H,disabled:!$,children:[L?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx($r,{className:"h-4 w-4 mr-2"}),"Send to ",o.length||0]})]})]})})}const w3t=s=>({property_address:(s==null?void 0:s.property_address)??"",city:(s==null?void 0:s.city)??"",state:(s==null?void 0:s.state)??"",zip:(s==null?void 0:s.zip)??"",seller_name:(s==null?void 0:s.seller_name)??"",seller_email:(s==null?void 0:s.seller_email)??"",seller_phone:(s==null?void 0:s.seller_phone)??"",mailing_address:(s==null?void 0:s.mailing_address)??"",mailing_city:(s==null?void 0:s.mailing_city)??"",mailing_state:(s==null?void 0:s.mailing_state)??"",mailing_zip:(s==null?void 0:s.mailing_zip)??"",original_price:(s==null?void 0:s.original_price)!=null?String(s.original_price):"",final_price:(s==null?void 0:s.final_price)!=null?String(s.final_price):"",days_on_market:(s==null?void 0:s.days_on_market)!=null?String(s.days_on_market):"",expiration_date:(s==null?void 0:s.expiration_date)??"",mls_link:(s==null?void 0:s.mls_link)??"",photo_url:(s==null?void 0:s.photo_url)??"",agent_notes:(s==null?void 0:s.agent_notes)??""});function emr({open:s,onOpenChange:t,property:n,saving:r,onSave:a}){const[i,l]=j.useState(()=>w3t(n));j.useEffect(()=>{s&&l(w3t(n))},[s,n]);const o=(h,m)=>l(p=>({...p,[h]:m})),c=(h,m,p="text")=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:m}),e.jsx(xe,{type:p,value:i[h],onChange:f=>o(h,f.target.value)})]}),d=h=>h.trim()===""?null:Number(h),u=()=>{a({property_address:i.property_address.trim()||null,city:i.city.trim()||null,state:i.state.trim()||null,zip:i.zip.trim()||null,seller_name:i.seller_name.trim()||null,seller_email:i.seller_email.trim()||null,seller_phone:i.seller_phone.trim()||null,mailing_address:i.mailing_address.trim()||null,mailing_city:i.mailing_city.trim()||null,mailing_state:i.mailing_state.trim()||null,mailing_zip:i.mailing_zip.trim()||null,original_price:d(i.original_price),final_price:d(i.final_price),days_on_market:d(i.days_on_market),expiration_date:i.expiration_date||null,mls_link:i.mls_link.trim()||null,photo_url:i.photo_url.trim()||null,agent_notes:i.agent_notes.trim()||null})};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Edit property details"}),e.jsx(Pr,{children:"Update the address, pricing, seller info or photo. Letters, landing pages and emails use this information."})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsx(q9,{label:"Property photo",value:i.photo_url,onChange:h=>o("photo_url",h??""),prefix:"revival-property",hint:"Upload a new photo or paste an image URL. This shows on the campaign card and landing page."}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx("div",{className:"sm:col-span-2",children:c("property_address","Property address")}),c("city","City"),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[c("state","State"),c("zip","Zip")]}),c("seller_name","Seller name"),c("seller_email","Seller email","email"),c("seller_phone","Seller phone"),c("expiration_date","Expiration date","date"),c("original_price","Original list price","number"),c("final_price","Final list price","number"),c("days_on_market","Days on market","number"),c("mls_link","MLS link"),e.jsx("div",{className:"sm:col-span-2",children:c("mailing_address","Mailing address (if different)")}),c("mailing_city","Mailing city"),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[c("mailing_state","Mailing state"),c("mailing_zip","Mailing zip")]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs",children:"Agent notes"}),e.jsx(Fs,{rows:4,value:i.agent_notes,onChange:h=>o("agent_notes",h.target.value),placeholder:"Why it didn't sell, condition, seller motivation…"})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(U,{onClick:u,disabled:r,children:[r?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Save changes"]})]})]})})}const tmr=[{id:"estate",name:"Estate Navy",description:"The signature look — deep navy, gold rules, serif headlines.",bg:"#0f2540",surface:"#ffffff",ink:"#1f2937",muted:"#6b7280",accent:"#c9a227",accentInk:"#0f2540",headingFont:'Georgia, "Times New Roman", serif',bodyFont:'"Helvetica Neue", Helvetica, Arial, sans-serif',swatch:["#0f2540","#c9a227","#ffffff"]},{id:"coastal",name:"Coastal",description:"Airy sea-glass blues and sand — perfect for beach markets.",bg:"#0d3b45",surface:"#fbfaf6",ink:"#12303a",muted:"#5c7a80",accent:"#4ea6a0",accentInk:"#04262b",headingFont:'"Iowan Old Style", Georgia, serif',bodyFont:'"Helvetica Neue", Helvetica, Arial, sans-serif',swatch:["#0d3b45","#4ea6a0","#fbfaf6"]},{id:"ranch",name:"Land & Ranch",description:"Earthy clay and saddle tones for land, farm and ranch.",bg:"#2f2a22",surface:"#fdfaf4",ink:"#2b2620",muted:"#7a6f60",accent:"#b4703a",accentInk:"#fff8ef",headingFont:"Georgia, serif",bodyFont:'"Helvetica Neue", Helvetica, Arial, sans-serif',swatch:["#2f2a22","#b4703a","#fdfaf4"]},{id:"modern",name:"Modern Mono",description:"Editorial black and white with a single sharp accent.",bg:"#111113",surface:"#ffffff",ink:"#111113",muted:"#6d6d73",accent:"#e0483c",accentInk:"#ffffff",headingFont:'"Helvetica Neue", Helvetica, Arial, sans-serif',bodyFont:'"Helvetica Neue", Helvetica, Arial, sans-serif',swatch:["#111113","#e0483c","#ffffff"]}],j3t="c0a11111-0000-4000-8000-000000000030";function smr(){var ne,ie,ce,je,be,he,ge,ke,Te,Me,Oe,Se,Qe,Ae,Fe,Ne,$e,Ve,qe,Ze,Ue,Ye,Ge,He,tt,pt,ft,qt,Ut;const{id:s}=Di(),t=Wn(),{user:n}=vs(),r=Dhr(s),a=uas(),i=das(),{generate:l,saveCampaign:o,saveProperty:c,deleteCampaign:d}=_at(),[u,h]=j.useState(""),[m,p]=j.useState(null),[f,x]=j.useState(!1),[y,v]=j.useState(!1),[b,N]=j.useState(!1),[S,A]=j.useState(null),T=ct({queryKey:["revival-drip-campaigns",n==null?void 0:n.id],enabled:!!n,queryFn:async()=>{const{data:Wt}=await q.from("drip_campaigns").select("id, name").eq("owner_user_id",n.id).order("name");return Wt??[]}}),L=yt({mutationFn:async()=>{if(!n)throw new Error("Not signed in");const[{data:Wt},{data:us}]=await Promise.all([q.from("drip_campaigns").select("*").eq("id",j3t).maybeSingle(),q.from("drip_campaign_steps").select("*").eq("campaign_id",j3t).order("step_order")]);if(!Wt)throw new Error("Starter campaign not found");const{data:zt,error:bt}=await q.from("drip_campaigns").insert({owner_user_id:n.id,name:Wt.name,description:Wt.description,category:Wt.category,icon:Wt.icon,cover_color:Wt.cover_color,goal:Wt.goal,is_active:!0,is_starter:!1}).select("id, name").single();if(bt)throw bt;if(us!=null&&us.length){const{error:As}=await q.from("drip_campaign_steps").insert(us.map(vt=>({campaign_id:zt.id,step_order:vt.step_order,channel:vt.channel,subject:vt.subject,body:vt.body,delay_type:vt.delay_type,delay_days:vt.delay_days,delay_hours:vt.delay_hours,send_window_start:vt.send_window_start,send_window_end:vt.send_window_end})));if(As)throw As}return zt},onSuccess:async Wt=>{await T.refetch(),o.mutate({id:s,patch:{drip_campaign_id:Wt.id}}),re.success("Expired Listing Revival drip installed and assigned")},onError:Wt=>re.error(Wt.message)}),M=(T.data??[]).some(Wt=>{var us;return(us=Wt.name)==null?void 0:us.startsWith("Expired Listing Revival")}),I=ct({queryKey:["revival-agent-profile",n==null?void 0:n.id],enabled:!!n,queryFn:async()=>{const{data:Wt}=await q.from("profiles").select("name, email, phone, avatar_url, brokerage_name, website_url, title").eq("id",n.id).maybeSingle();return Wt}}),R=r.data,z=(R==null?void 0:R.content)??{},$=R?oas(R.slug):"",H={name:(ne=I.data)==null?void 0:ne.name,title:(ie=I.data)==null?void 0:ie.title,phone:(ce=I.data)==null?void 0:ce.phone,email:(je=I.data)==null?void 0:je.email,website_url:(be=I.data)==null?void 0:be.website_url,avatar_url:(he=I.data)==null?void 0:he.avatar_url,brokerage_name:(ge=I.data)==null?void 0:ge.brokerage_name},V=j.useRef(null),K=async()=>{var us,zt;const Wt=(us=V.current)==null?void 0:us.firstElementChild;if(Wt){p("letter");try{await Ihr(Wt,((zt=R==null?void 0:R.property)==null?void 0:zt.property_address)??(R==null?void 0:R.name)??"letter"),re.success("Letter PDF downloaded")}catch{re.error("Could not build the letter PDF")}finally{p(null)}}},Z=j.useRef(null),Q=async()=>{var us;const Wt=Z.current;if(Wt){p("plan");try{await cas(Wt,((us=R==null?void 0:R.property)==null?void 0:us.property_address)??(R==null?void 0:R.name)??"plan"),re.success("Plan PDF downloaded")}catch{re.error("Could not build the plan PDF")}finally{p(null)}}},le=j.useMemo(()=>{var zt,bt;const Wt=(a.data??[]).filter(As=>As.campaign_id===s),us={};return Wt.forEach(As=>{us[As.event_type]=(us[As.event_type]??0)+1}),us.letter=z.letter?1:0,us.email=((zt=z.emails)==null?void 0:zt.length)??0,us.sms=((bt=z.sms)==null?void 0:bt.length)??0,us.form_submit=(i.data??[]).filter(As=>As.campaign_id===s).length,us},[a.data,i.data,s,z]);if(r.isLoading)return e.jsx(qs,{title:"Campaign",children:e.jsx("div",{className:"grid place-items-center py-24",children:e.jsx(Et,{className:"h-6 w-6 animate-spin"})})});if(!R)return e.jsx(qs,{title:"Campaign",children:e.jsx("div",{className:"py-24 text-center text-muted-foreground",children:"Campaign not found."})});const ue=h$.find(Wt=>Wt.id===R.style),se=Wt=>l.mutate({campaignId:R.id,section:Wt,instruction:u||void 0});return e.jsxs(qs,{title:R.name,children:[e.jsxs("div",{className:"revival-theme -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)]",children:[e.jsxs(U,{variant:"ghost",size:"sm",className:"gap-2 mb-4",onClick:()=>t("/apps/listing-revival"),children:[e.jsx(Aa,{className:"h-4 w-4"})," Back to Listing Revival"]}),e.jsx(kr.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{duration:.45},className:"revival-dark rounded-3xl overflow-hidden",children:e.jsxs("div",{className:"grid lg:grid-cols-[1.4fr_1fr]",children:[e.jsxs("div",{className:"p-7",children:[e.jsx("div",{className:"revival-eyebrow text-accent",children:(ue==null?void 0:ue.name)??R.style}),e.jsx("h1",{className:"revival-serif text-3xl mt-1",children:(ke=R.property)==null?void 0:ke.property_address}),e.jsxs("p",{className:"text-white/70 mt-1",children:[((Te=R.property)==null?void 0:Te.seller_name)??"Homeowner",(Me=R.property)!=null&&Me.city?` · ${R.property.city}, ${R.property.state??""}`:""]}),e.jsxs("div",{className:"mt-5 grid grid-cols-3 gap-4 max-w-md",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-white/50 text-xs uppercase tracking-wider",children:"Original"}),e.jsx("div",{className:"text-lg font-semibold",children:AP((Oe=R.property)==null?void 0:Oe.original_price)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-white/50 text-xs uppercase tracking-wider",children:"Final"}),e.jsx("div",{className:"text-lg font-semibold",children:AP((Se=R.property)==null?void 0:Se.final_price)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-white/50 text-xs uppercase tracking-wider",children:"Days on market"}),e.jsx("div",{className:"text-lg font-semibold",children:((Qe=R.property)==null?void 0:Qe.days_on_market)??"—"})]})]}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-2",children:[e.jsx(U,{size:"sm",className:"bg-accent text-accent-foreground hover:bg-accent/90",asChild:!0,children:e.jsxs("a",{href:`/revival/${R.slug}`,target:"_blank",rel:"noreferrer",children:[e.jsx(Sr,{className:"h-3.5 w-3.5 mr-1.5"})," View landing page"]})}),e.jsxs(U,{size:"sm",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",onClick:()=>N(!0),children:[e.jsx(ri,{className:"h-3.5 w-3.5 mr-1.5"})," Edit property & photo"]}),e.jsxs(U,{size:"sm",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",onClick:()=>{navigator.clipboard.writeText($),re.success("Link copied")},children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1.5"})," Copy link"]}),e.jsxs(U,{size:"sm",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",disabled:l.isPending,onClick:()=>se(),children:[l.isPending?e.jsx(Et,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(no,{className:"h-3.5 w-3.5 mr-1.5"}),"Regenerate all"]})]})]}),e.jsxs("div",{className:"relative min-h-[220px]",children:[(Ae=R.property)!=null&&Ae.photo_url?e.jsx("img",{src:R.property.photo_url,alt:R.property.property_address??"",className:"absolute inset-0 h-full w-full object-cover"}):e.jsxs("button",{type:"button",onClick:()=>N(!0),className:"absolute inset-0 flex flex-col items-center justify-center gap-2 bg-white/5 text-white/70 text-sm hover:bg-white/10",children:[e.jsx(ly,{className:"h-6 w-6"}),"Add a property photo"]}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-[hsl(var(--revival-navy))] via-transparent to-transparent pointer-events-none"})]})]})}),e.jsxs(oa,{defaultValue:"journey",className:"mt-6",children:[e.jsx(la,{className:"flex w-full overflow-x-auto no-scrollbar justify-start bg-transparent p-0 gap-2 h-auto",children:["journey","letter","print","landing","plan","emails","texts","scripts","settings"].map(Wt=>e.jsx(Kt,{value:Wt,className:"capitalize data-[state=active]:bg-primary data-[state=active]:text-primary-foreground rounded-full border border-border bg-card px-4 py-2 text-sm",children:Wt},Wt))}),e.jsxs(Zt,{value:"journey",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(hq,{className:"h-4 w-4"})," The homeowner's journey, tracked end to end."]}),e.jsx(Qhr,{counts:le})]}),e.jsxs(Zt,{value:"letter",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 items-center print:hidden",children:[e.jsxs(U,{size:"sm",disabled:!z.letter||m==="letter",onClick:K,children:[m==="letter"?e.jsx(Et,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(PA,{className:"h-3.5 w-3.5 mr-1.5"}),"Download print-ready PDF"]}),e.jsxs(U,{size:"sm",variant:"outline",disabled:!z.letter,onClick:()=>v(Wt=>!Wt),children:[e.jsx(ri,{className:"h-3.5 w-3.5 mr-1.5"})," ",y?"Close editor":"Edit letter"]}),e.jsxs(U,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>se("letter"),children:[e.jsx(cn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite letter"]}),e.jsx(xe,{value:u,onChange:Wt=>h(Wt.target.value),placeholder:"Optional instruction: e.g. shorter, warmer, mention the pool",className:"max-w-sm"})]}),y&&z.letter?e.jsx(has,{letter:z.letter,saving:o.isPending,onCancel:()=>v(!1),onSave:Wt=>{o.mutate({id:s,patch:{content:{...z,letter:Wt}}},{onSuccess:()=>v(!1)})}}):null,z.letter?e.jsx(b3t,{campaign:R,letter:z.letter,url:$,agent:H}):e.jsx("p",{className:"text-muted-foreground",children:"No letter generated yet."})]}),e.jsx(Zt,{value:"print",className:"mt-6 space-y-4",children:e.jsxs("div",{className:"revival-tile p-6 space-y-5 max-w-2xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Print & mail"}),e.jsx("h3",{className:"revival-serif text-2xl mt-1",children:"Print-ready files"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Vector PDFs built at true print size with the QR code baked in — send them to your printer or mail house as-is."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-xl border border-border p-4",children:[e.jsx("div",{className:"font-semibold",children:"Personalized letter"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:"8.5″ × 11″ · letterhead + signature block"}),e.jsxs(U,{size:"sm",className:"mt-3",disabled:!z.letter||m==="letter",onClick:K,children:[m==="letter"?e.jsx(Et,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(W2,{className:"h-3.5 w-3.5 mr-1.5"}),"Download letter PDF"]})]}),e.jsxs("div",{className:"rounded-xl border border-border p-4",children:[e.jsx("div",{className:"font-semibold",children:"Revival postcard"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:"6″ × 9″ · front and back, mail-ready"}),e.jsxs(U,{size:"sm",className:"mt-3",disabled:m==="postcard",onClick:async()=>{var Wt,us,zt,bt,As,vt,Ws,on,Ms,dn;p("postcard");try{await Lhr({campaign:R,url:$,headline:(Wt=z.landing)==null?void 0:Wt.headline,subhead:(us=z.landing)==null?void 0:us.subheadline,message:(zt=z.landing)==null?void 0:zt.intro,photoDataUrl:((bt=R.property)==null?void 0:bt.photo_url)??null,agent:{name:(As=I.data)==null?void 0:As.name,title:(vt=I.data)==null?void 0:vt.title,phone:(Ws=I.data)==null?void 0:Ws.phone,email:(on=I.data)==null?void 0:on.email,website_url:(Ms=I.data)==null?void 0:Ms.website_url,brokerage_name:(dn=I.data)==null?void 0:dn.brokerage_name}}),re.success("Postcard PDF downloaded")}catch{re.error("Could not build the postcard PDF")}finally{p(null)}},children:[m==="postcard"?e.jsx(Et,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(W2,{className:"h-3.5 w-3.5 mr-1.5"}),"Download postcard PDF"]})]})]}),e.jsxs("div",{className:"rounded-xl bg-muted/50 p-4 text-sm text-muted-foreground",children:["Mailing address on file:"," ",e.jsxs("span",{className:"text-foreground font-medium",children:[((Fe=R.property)==null?void 0:Fe.mailing_address)??((Ne=R.property)==null?void 0:Ne.property_address)??"—",($e=R.property)!=null&&$e.mailing_city?`, ${R.property.mailing_city} ${R.property.mailing_state??""} ${R.property.mailing_zip??""}`:""]})]})]})}),e.jsxs(Zt,{value:"landing",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsxs(U,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>se("landing"),children:[e.jsx(cn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite landing copy"]}),e.jsx(U,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:`/revival/${R.slug}`,target:"_blank",rel:"noreferrer",children:[e.jsx(Sr,{className:"h-3.5 w-3.5 mr-1.5"})," Open live page"]})})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[1fr_auto] items-start",children:[e.jsx(Khr,{campaignId:R.id,content:z,landingConfig:R.landing_config??{},propertyPhotoUrl:(Ve=R.property)==null?void 0:Ve.photo_url,saving:o.isPending,onSave:Wt=>o.mutate({id:R.id,patch:Wt})}),e.jsxs("div",{className:"revival-tile p-6 text-center h-fit",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Campaign QR"}),e.jsx("div",{className:"mt-3",children:e.jsx(fS,{value:$,size:168,level:"M"})}),e.jsx("p",{className:"text-xs text-muted-foreground mt-3 max-w-[180px] break-all",children:$})]})]})]}),e.jsxs(Zt,{value:"plan",className:"mt-6 space-y-4",children:[e.jsx("div",{className:"revival-tile p-5",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"revival-eyebrow text-accent-foreground/70",children:"Seller deliverable"}),e.jsx("h3",{className:"revival-serif text-xl mt-1",children:"The Property Revival Plan"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-2xl",children:"This is the branded presentation your seller receives after they opt in from the landing page or QR code. Preview it below, download it as a PDF to bring to the listing appointment, or share the live link."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(U,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>se("plan"),children:[e.jsx(cn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite plan"]}),e.jsxs(U,{size:"sm",variant:f?"secondary":"outline",onClick:()=>x(Wt=>!Wt),children:[e.jsx(ri,{className:"h-3.5 w-3.5 mr-1.5"})," ",f?"Done editing":"Edit plan"]}),e.jsx(U,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:`/revival/${R.slug}/plan`,target:"_blank",rel:"noreferrer",children:[e.jsx(Sr,{className:"h-3.5 w-3.5 mr-1.5"})," View live plan"]})}),e.jsxs(U,{size:"sm",className:"bg-accent text-accent-foreground hover:bg-accent/90",disabled:!z.plan||m==="plan",onClick:Q,children:[m==="plan"?e.jsx(Et,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(W2,{className:"h-3.5 w-3.5 mr-1.5"}),"Download plan PDF"]})]})]})}),f&&z.plan?e.jsx(Zhr,{plan:z.plan,saving:o.isPending,onSave:Wt=>o.mutate({id:R.id,patch:{content:{...z,plan:Wt}}},{onSuccess:()=>re.success("Plan updated")})}):null,z.plan?e.jsx("div",{className:"rounded-3xl bg-muted/40 p-4 sm:p-8",children:e.jsx(iYe,{plan:z.plan,property:{...R.property??{},seller_name:(qe=R.property)==null?void 0:qe.seller_name},agent:H,url:`${aYe()}/revival/${R.slug}/plan`})}):e.jsx("div",{className:"revival-tile p-10 text-center text-muted-foreground",children:"No plan generated yet — use “Rewrite plan”."})]}),e.jsxs(Zt,{value:"emails",className:"mt-6 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(U,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>se("emails"),children:[e.jsx(cn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite emails"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Each email sends as a fully branded HTML email to contacts you choose."})]}),(z.emails??[]).map((Wt,us)=>e.jsxs("div",{className:"revival-tile p-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-semibold",children:Wt.subject}),e.jsx(Be,{variant:"outline",children:Wt.key})]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:Wt.preview}),e.jsx("p",{className:"mt-3 text-sm whitespace-pre-wrap leading-relaxed",children:Wt.body}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1",children:[e.jsxs(U,{size:"sm",onClick:()=>A(Wt),children:[e.jsx(ln,{className:"h-3.5 w-3.5 mr-1.5"})," Preview & send"]}),e.jsxs(U,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(`${Wt.subject} ${Wt.body}`),re.success("Email copied")},children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1.5"})," Copy"]})]})]},us))]}),e.jsxs(Zt,{value:"texts",className:"mt-6 space-y-3",children:[e.jsxs(U,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>se("sms"),children:[e.jsx(cn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite texts"]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:(z.sms??[]).map((Wt,us)=>e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx(Be,{variant:"outline",children:Wt.key}),e.jsx("p",{className:"mt-2 text-sm leading-relaxed",children:Wt.body}),e.jsxs(U,{size:"sm",variant:"ghost",className:"mt-2",onClick:()=>{navigator.clipboard.writeText(Wt.body),re.success("Text copied")},children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1.5"})," Copy"]})]},us))})]}),e.jsxs(Zt,{value:"scripts",className:"mt-6 space-y-3",children:[e.jsxs(U,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>se("scripts"),children:[e.jsx(cn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite scripts"]}),[["Phone script",(Ze=z.scripts)==null?void 0:Ze.phone],["Voicemail",(Ue=z.scripts)==null?void 0:Ue.voicemail],["Video script",(Ye=z.scripts)==null?void 0:Ye.video],["Door knock",(Ge=z.scripts)==null?void 0:Ge.door_knock]].map(([Wt,us])=>us?e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"font-semibold",children:Wt}),e.jsx("p",{className:"mt-2 text-sm whitespace-pre-wrap leading-relaxed",children:us})]},Wt):null),(((He=z.scripts)==null?void 0:He.objections)??[]).length?e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"font-semibold",children:"Objection handlers"}),e.jsx("div",{className:"mt-3 space-y-3",children:(((tt=z.scripts)==null?void 0:tt.objections)??[]).map((Wt,us)=>e.jsxs("div",{children:[e.jsxs("div",{className:"text-sm font-medium",children:["“",Wt.objection,"”"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:Wt.response})]},us))})]}):null]}),e.jsx(Zt,{value:"settings",className:"mt-6",children:e.jsxs("div",{className:"revival-tile p-6 space-y-5 max-w-xl",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(te,{className:"font-semibold",children:"Landing page live"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Turn off to take the public page offline."})]}),e.jsx(wn,{checked:R.published,onCheckedChange:Wt=>o.mutate({id:R.id,patch:{published:Wt}})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"font-semibold",children:"Campaign name"}),e.jsx(xe,{defaultValue:R.name,onBlur:Wt=>Wt.target.value!==R.name&&o.mutate({id:R.id,patch:{name:Wt.target.value}})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{className:"font-semibold",children:"Landing page theme"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Changes the look of the public page instantly."}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:tmr.map(Wt=>e.jsxs("button",{type:"button",onClick:()=>o.mutate({id:R.id,patch:{theme:Wt.id}}),className:`text-left rounded-xl border p-3 transition-all ${(R.theme??"estate")===Wt.id?"border-accent ring-2 ring-accent/40":"border-border hover:border-accent/50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[Wt.swatch.map(us=>e.jsx("span",{className:"h-4 w-4 rounded-full border border-black/10",style:{background:us}},us)),e.jsx("span",{className:"font-medium ml-1",children:Wt.name})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1.5",children:Wt.description})]},Wt.id))})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border pt-4",children:[e.jsxs("div",{children:[e.jsxs(te,{className:"font-semibold flex items-center gap-1.5",children:[e.jsx(A4,{className:"h-4 w-4"})," Alert me on engagement"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Email me the first time this homeowner scans or visits."})]}),e.jsx(wn,{checked:!!R.alert_on_engagement,onCheckedChange:Wt=>o.mutate({id:R.id,patch:{alert_on_engagement:Wt}})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(te,{className:"font-semibold flex items-center gap-1.5",children:[e.jsx(ln,{className:"h-4 w-4"})," Auto-enroll new leads in a drip"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sellers who submit the form get added to this campaign automatically."}),e.jsxs(Ns,{value:R.drip_campaign_id??"none",onValueChange:Wt=>o.mutate({id:R.id,patch:{drip_campaign_id:Wt==="none"?null:Wt}}),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"No drip campaign"})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"No drip campaign"}),(T.data??[]).map(Wt=>e.jsx(et,{value:Wt.id,children:Wt.name},Wt.id))]})]}),!M&&e.jsxs("div",{className:"mt-3 rounded-xl border border-amber-500/30 bg-amber-500/5 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"Recommended: Expired Listing Revival (8 emails, 45 days)"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"A luxury-styled nurture written for homeowners whose listing expired — confirmation, why homes expire, the 5-part relaunch plan, pricing truth, presentation, a case study, and two graceful closes."}),e.jsx(U,{size:"sm",className:"mt-3",disabled:L.isPending,onClick:()=>L.mutate(),children:L.isPending?"Installing…":"Install & assign to this campaign"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"font-semibold",children:"Internal notes"}),e.jsx(Fs,{rows:4,defaultValue:((pt=R.branding)==null?void 0:pt.notes)??"",onBlur:Wt=>o.mutate({id:R.id,patch:{branding:{...R.branding,notes:Wt.target.value}}})})]}),e.jsx("div",{className:"border-t border-border pt-4",children:e.jsxs(U,{variant:"destructive",size:"sm",onClick:async()=>{await Yi("Delete this campaign? The landing page will stop working.")&&d.mutate(R.id,{onSuccess:()=>t("/apps/listing-revival")})},children:[e.jsx(In,{className:"h-3.5 w-3.5 mr-1.5"})," Delete campaign"]})})]})})]}),z.letter?e.jsx("div",{ref:V,"aria-hidden":!0,className:"pointer-events-none fixed left-[-10000px] top-0 w-[816px]",children:e.jsx(b3t,{campaign:R,letter:z.letter,url:$,agent:H,className:"shadow-none"})}):null,z.plan?e.jsx("div",{ref:Z,"aria-hidden":!0,className:"pointer-events-none fixed left-[-10000px] top-0 w-[816px]",children:e.jsx(iYe,{plan:z.plan,property:{...R.property??{},seller_name:(ft=R.property)==null?void 0:ft.seller_name},agent:H,url:`${aYe()}/revival/${R.slug}/plan`})}):null]}),e.jsx(Jhr,{open:!!S,onOpenChange:Wt=>!Wt&&A(null),campaignId:R.id,email:S,ctaUrl:$,seller:{name:(qt=R.property)==null?void 0:qt.seller_name,email:(Ut=R.property)==null?void 0:Ut.seller_email}}),e.jsx(emr,{open:b,onOpenChange:N,property:R.property,saving:c.isPending,onSave:Wt=>{var us;(us=R.property)!=null&&us.id&&c.mutate({id:R.property.id,patch:Wt},{onSuccess:()=>N(!1)})}})]})}function mas(){const{user:s}=vs();return ct({queryKey:["fsbo-campaigns",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("fsbo_campaigns").select("*, property:fsbo_properties(*)").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function nmr(s){return ct({queryKey:["fsbo-campaign",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("fsbo_campaigns").select("*, property:fsbo_properties(*)").eq("id",s).maybeSingle();if(n)throw n;return t??null}})}function pas(){const{user:s}=vs();return ct({queryKey:["fsbo-properties",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("fsbo_properties").select("*").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function wat(){const{user:s}=vs();return ct({queryKey:["fsbo-leads",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("fsbo_leads").select("*").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function rmr(){const{user:s}=vs();return ct({queryKey:["fsbo-tasks",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("fsbo_tasks").select("*").order("due_date",{ascending:!0});if(n)throw n;return t??[]}})}function jat(){const{user:s}=vs();return ct({queryKey:["fsbo-events",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("fsbo_events").select("*").order("created_at",{ascending:!1}).limit(1e3);if(n)throw n;return t??[]}})}function l8e(){const s=Qt(),t=()=>{["fsbo-campaigns","fsbo-campaign","fsbo-properties","fsbo-leads","fsbo-tasks","fsbo-events"].forEach(c=>s.invalidateQueries({queryKey:[c]}))},n=yt({mutationFn:async c=>{const{data:d,error:u}=await q.functions.invoke("fsbo-generate",{body:c});if(u)throw u;if(d!=null&&d.error)throw new Error(String(d.error));return d},onSuccess:t,onError:c=>re.error(c.message)}),r=yt({mutationFn:async c=>{const{error:d}=await q.from("fsbo_campaigns").update(c.patch).eq("id",c.id);if(d)throw d},onSuccess:()=>{t(),re.success("Saved")},onError:c=>re.error(c.message)}),a=yt({mutationFn:async c=>{const{error:d}=await q.from("fsbo_campaigns").delete().eq("id",c);if(d)throw d},onSuccess:()=>{t(),re.success("Campaign deleted")},onError:c=>re.error(c.message)}),i=yt({mutationFn:async c=>{const{error:d}=await q.from("fsbo_campaigns").update({status:c.archived?"archived":"draft",published:!c.archived}).eq("id",c.id);if(d)throw d;return c},onSuccess:c=>{t(),re.success(c.archived?"Campaign archived":"Campaign restored")},onError:c=>re.error(c.message)}),l=yt({mutationFn:async c=>{const{error:d}=await q.from("fsbo_properties").update(c.patch).eq("id",c.id);if(d)throw d},onSuccess:()=>{t(),re.success("Property details updated")},onError:c=>re.error(c.message)}),o=yt({mutationFn:async c=>{const{error:d}=await q.from("fsbo_tasks").update({completed_at:c.done?new Date().toISOString():null}).eq("id",c.id);if(d)throw d},onSuccess:t,onError:c=>re.error(c.message)});return{generate:n,saveCampaign:r,deleteCampaign:a,archiveCampaign:i,toggleTask:o,updateProperty:l,invalidate:t}}function amr(s){const t=(s??"").trim();if(!t)return null;const n=t.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([\w-]{6,})/);if(n)return{kind:"iframe",src:`https://www.youtube.com/embed/${n[1]}`};const r=t.match(/vimeo\.com\/(?:video\/)?(\d+)/);if(r)return{kind:"iframe",src:`https://player.vimeo.com/video/${r[1]}`};const a=t.match(/loom\.com\/(?:share|embed)\/([\w-]+)/);return a?{kind:"iframe",src:`https://www.loom.com/embed/${a[1]}`}:/\.(mp4|webm|mov|m4v)(\?|$)/i.test(t)?{kind:"file",src:t}:{kind:"iframe",src:t}}const FTe=[{id:"market_expert",name:"Market Expert",tagline:"Data, not pressure",description:"Consultative and informed. Shows the seller what the market is actually doing without pushing them toward an agent.",accent:"from-teal-500/20 to-teal-500/0",previewHeadline:"What the Market Is Really Telling You",previewBody:"A clear look at buyer activity, pricing, and the places FSBO sellers most often miss."},{id:"friendly_neighbor",name:"Friendly Neighbor",tagline:"Helpful advice first",description:"Warm and personal — feels like a neighbor who knows the street and wants the best outcome.",accent:"from-amber-500/20 to-amber-500/0",previewHeadline:"A Friendly Note From the Neighborhood",previewBody:"I saw your home is for sale by owner and I wanted to share a guide that might help."},{id:"professional_review",name:"Professional Review",tagline:"Structured & credible",description:"Polished and businesslike. A clear assessment of the FSBO process with a proven next-step plan.",accent:"from-indigo-500/20 to-indigo-500/0",previewHeadline:"A Professional FSBO Review",previewBody:"An honest, structured look at the advantages, risks, and what a pro would watch."},{id:"equity_advocate",name:"Equity Advocate",tagline:"Maximize net proceeds",description:"Focuses on the money. Helps the seller understand hidden costs and the math behind selling alone.",accent:"from-emerald-500/20 to-emerald-500/0",previewHeadline:"The True Math of Selling On Your Own",previewBody:"Commission isn't the only number that matters. Here's what to count before you decide."},{id:"second_opinion",name:"Second Opinion",tagline:"No pressure perspective",description:"Respectful and non-defensive. Offers a free second opinion for a smart seller who may simply want a fresh set of eyes.",accent:"from-sky-500/20 to-sky-500/0",previewHeadline:"Would a Second Opinion Help?",previewBody:"You know your home best. I just want to offer a free, no-obligation perspective if it's useful."}],fas=[{id:"professional",name:"Professional",note:"Polished and businesslike"},{id:"friendly",name:"Friendly",note:"Warm and conversational"},{id:"consultative",name:"Consultative",note:"Curious and patient"},{id:"minimal",name:"Minimal",note:"Short and direct"},{id:"modern",name:"Modern",note:"Crisp and confident"}],gas=[{value:"single_family",label:"Single Family"},{value:"condo",label:"Condo"},{value:"townhouse",label:"Townhouse"},{value:"multi_family",label:"Multi-Family"},{value:"land",label:"Land"},{value:"luxury",label:"Luxury"},{value:"commercial",label:"Commercial"},{value:"other",label:"Other"}],imr=[{value:"immediately",label:"As soon as possible"},{value:"0-30",label:"In the next 30 days"},{value:"1-3",label:"In the next 1–3 months"},{value:"3-6",label:"In 3–6 months"},{value:"6-12",label:"In 6–12 months"},{value:"just_curious",label:"Just curious for now"}],omr=["Need to sell quickly","Want to maximize net proceeds","Testing the market","Already bought another home","Relocating","Downsizing / Upsizing","Estate sale","Other"],lmr=[{value:"email",label:"Email"},{value:"phone",label:"Phone"},{value:"text",label:"Text"}];function oYe(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function cmr(s){const t=oYe(s)||"property",n=Math.random().toString(36).slice(2,7);return`${t}-${n}`}function lYe(s){return s==null?"—":`$${Number(s).toLocaleString("en-US",{maximumFractionDigits:0})}`}function dmr(){return typeof window>"u"?"":window.location.origin}function xas(s){return`${dmr()}/fsbo/${s}`}const N3t="fsbo_breakthrough";function umr(){const{user:s,loading:t,isAdmin:n}=vs(),{data:r}=ct({queryKey:["feature-entitlement",N3t,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",N3t).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 hmr={property_address:"",city:"",state:"",zip:"",property_type:"single_family",estimated_value:"",seller_name:"",seller_email:"",seller_phone:"",notes:"",photo_url:""};function yas({property:s,open:t,onOpenChange:n}){const{updateProperty:r}=l8e(),[a,i]=j.useState(hmr);j.useEffect(()=>{!t||!s||i({property_address:s.property_address??"",city:s.city??"",state:s.state??"",zip:s.zip??"",property_type:s.property_type??"single_family",estimated_value:s.estimated_value!=null?String(s.estimated_value):"",seller_name:s.seller_name??"",seller_email:s.seller_email??"",seller_phone:s.seller_phone??"",notes:s.notes??"",photo_url:s.photo_url??""})},[t,s]);const l=(d,u)=>i(h=>({...h,[d]:u})),o=(d,u,h={})=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:u}),e.jsx(xe,{value:a[d],onChange:m=>l(d,m.target.value),...h})]}),c=async()=>{s&&(await r.mutateAsync({id:s.id,patch:{property_address:a.property_address.trim()||s.property_address,city:a.city||null,state:a.state||null,zip:a.zip||null,property_type:a.property_type||"single_family",estimated_value:a.estimated_value?Number(a.estimated_value):null,seller_name:a.seller_name||null,seller_email:a.seller_email||null,seller_phone:a.seller_phone||null,notes:a.notes||null,photo_url:a.photo_url||null}}),n(!1))};return e.jsx(zs,{open:t,onOpenChange:n,children:e.jsxs(Ds,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Edit property & seller details"}),e.jsx(Pr,{children:"Update the homeowner's name, phone, email, estimated value and notes. Changes show up everywhere this property appears."})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsx("div",{className:"sm:col-span-2",children:o("property_address","Property address")}),o("city","City"),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o("state","State"),o("zip","Zip")]}),o("estimated_value","Estimated value",{type:"number",placeholder:"895000"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Property type"}),e.jsx("select",{className:"w-full h-10 rounded-md border border-input bg-background px-3 py-2 text-sm",value:a.property_type,onChange:d=>l("property_type",d.target.value),children:gas.map(d=>e.jsx("option",{value:d.value,children:d.label},d.value))})]}),o("seller_name","Seller name"),o("seller_phone","Seller phone"),e.jsx("div",{className:"sm:col-span-2",children:o("seller_email","Seller email",{type:"email"})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Property photo"}),e.jsx(q9,{value:a.photo_url,onChange:d=>l("photo_url",d??""),label:"Property photo",prefix:"fsbo-property"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Agent notes"}),e.jsx(Fs,{rows:6,value:a.notes,onChange:d=>l("notes",d.target.value)})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs(U,{onClick:c,disabled:r.isPending,children:[r.isPending?e.jsx(Et,{className:"h-4 w-4 mr-1 animate-spin"}):null,"Save details"]})]})]})})}const mmr=[{id:"dashboard",label:"Dashboard",icon:Lm},{id:"campaigns",label:"Campaigns",icon:cn},{id:"properties",label:"Properties",icon:ra},{id:"letters",label:"Letters",icon:ln},{id:"landing",label:"Landing Pages",icon:fl},{id:"guides",label:"Seller Guides",icon:Ur},{id:"followup",label:"Follow Up",icon:iy},{id:"analytics",label:"Analytics",icon:Cl},{id:"templates",label:"Templates",icon:ej},{id:"settings",label:"Settings",icon:R4}];function y5({label:s,value:t,icon:n,delay:r=0,hint:a}){return e.jsxs(kr.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{delay:r,duration:.45,ease:[.22,1,.36,1]},className:"fsbo-tile p-5",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("span",{className:"fsbo-eyebrow text-muted-foreground",children:s}),e.jsx(n,{className:"h-4 w-4 text-accent"})]}),e.jsx("div",{className:"mt-3 text-3xl font-bold tabular-nums tracking-tight",children:t}),a?e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:a}):null]})}function pmr(){const s=Wn(),[t,n]=j.useState("dashboard"),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState(null),h=umr(),m=mas(),p=pas(),f=wat(),x=rmr(),y=jat(),{toggleTask:v,archiveCampaign:b,deleteCampaign:N}=l8e(),S=m.data??[],A=f.data??[],T=y.data??[],L=x.data??[],M=j.useMemo(()=>{const Z=Q=>T.filter(le=>le.event_type===Q).length;return{properties:(p.data??[]).length,campaigns:S.length,letters:S.filter(Q=>{var le;return(le=Q.content)==null?void 0:le.letter}).length,qr:Z("qr_scan"),visits:Z("page_view"),guideViews:Z("guide_view"),leads:A.length,appointments:Z("appointment"),listed:A.filter(Q=>Q.temperature==="hot").length,hot:A.filter(Q=>Q.temperature==="hot").length}},[S,A,T,p.data]),I=j.useMemo(()=>{const Z=[];for(let Q=13;Q>=0;Q--){const le=new Date(Date.now()-Q*864e5),ue=le.toISOString().slice(0,10);Z.push({day:Gs(le,"MMM d"),visits:T.filter(se=>se.event_type==="page_view"&&se.created_at.startsWith(ue)).length,scans:T.filter(se=>se.event_type==="qr_scan"&&se.created_at.startsWith(ue)).length,leads:A.filter(se=>se.created_at.startsWith(ue)).length})}return Z},[T,A]),R=Z=>Z.status==="archived",z=S.filter(Z=>{var le,ue;if(i?!R(Z):R(Z))return!1;const Q=r.trim().toLowerCase();return Q?`${Z.name} ${((le=Z.property)==null?void 0:le.property_address)??""} ${((ue=Z.property)==null?void 0:ue.seller_name)??""}`.toLowerCase().includes(Q):!0}),$=S.filter(R).length,H=Z=>s(`/apps/fsbo-breakthrough/campaigns/${Z}`),V=Z=>{navigator.clipboard.writeText(xas(Z)),re.success("Landing page link copied")},K=Z=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"relative max-w-sm flex-1 min-w-[200px]",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{value:r,onChange:Q=>a(Q.target.value),placeholder:"Search campaigns…",className:"pl-9"})]}),e.jsxs(U,{variant:i?"default":"outline",size:"sm",onClick:()=>l(Q=>!Q),children:[e.jsx(n1,{className:"h-3.5 w-3.5 mr-1.5"}),i?"Viewing archived":`Archived (${$})`]})]}),z.length===0?e.jsx("div",{className:"fsbo-tile p-10 text-center text-muted-foreground",children:i?"No archived campaigns.":Z}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:z.map((Q,le)=>{var ce,je,be,he,ge;const ue=FTe.find(ke=>ke.id===Q.style),se=A.filter(ke=>ke.campaign_id===Q.id).length,ne=T.filter(ke=>ke.campaign_id===Q.id&&ke.event_type==="page_view").length,ie=R(Q);return e.jsxs(kr.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{delay:Math.min(le*.04,.3),duration:.4},className:Mt("fsbo-tile overflow-hidden",ie&&"opacity-80"),children:[e.jsxs("div",{className:"h-28 bg-muted relative",children:[(ce=Q.property)!=null&&ce.photo_url?e.jsx("img",{src:Q.property.photo_url,alt:Q.property.property_address??"",className:"h-full w-full object-cover",loading:"lazy"}):e.jsx("div",{className:"h-full w-full fsbo-dark grid place-items-center",children:e.jsx(ra,{className:"h-7 w-7 text-accent"})}),e.jsx(Be,{className:"absolute top-3 left-3 bg-background/90 text-foreground border-0",children:(ue==null?void 0:ue.name)??Q.style}),ie?e.jsx(Be,{className:"absolute top-3 right-3 bg-foreground/85 text-background border-0",children:"Archived"}):null]}),e.jsxs("div",{className:"p-4",children:[e.jsx("div",{className:"font-semibold leading-tight",children:((je=Q.property)==null?void 0:je.property_address)??Q.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:((be=Q.property)==null?void 0:be.seller_name)??"Homeowner"}),e.jsxs("div",{className:"mt-3 flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fl,{className:"h-3.5 w-3.5"}),ne]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3.5 w-3.5"}),se]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ra,{className:"h-3.5 w-3.5"}),((he=Q.property)==null?void 0:he.property_type)??"—"]}),((ge=Q.property)==null?void 0:ge.estimated_value)!=null?e.jsxs("span",{className:"flex items-center gap-1 font-medium text-foreground",children:[e.jsx(yu,{className:"h-3.5 w-3.5"}),lYe(Q.property.estimated_value)]}):null]}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsxs(U,{size:"sm",className:"flex-1",onClick:()=>H(Q.id),children:["Open ",e.jsx(Oa,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsx(U,{size:"sm",variant:"outline",onClick:()=>V(Q.slug),children:e.jsx(Pa,{className:"h-3.5 w-3.5"})}),e.jsx(U,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:`/fsbo/${Q.slug}`,target:"_blank",rel:"noreferrer",children:e.jsx(Sr,{className:"h-3.5 w-3.5"})})}),e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsx(U,{size:"sm",variant:"outline",children:e.jsx(ey,{className:"h-3.5 w-3.5"})})}),e.jsxs(Eu,{align:"end",children:[e.jsxs(La,{disabled:!Q.property,onClick:()=>Q.property&&u(Q.property),children:[e.jsx(ri,{className:"h-4 w-4 mr-2"})," Edit property & seller details"]}),e.jsx(La,{onClick:()=>b.mutate({id:Q.id,archived:!ie}),children:ie?e.jsxs(e.Fragment,{children:[e.jsx(jM,{className:"h-4 w-4 mr-2"})," Restore campaign"]}):e.jsxs(e.Fragment,{children:[e.jsx(n1,{className:"h-4 w-4 mr-2"})," Archive campaign"]})}),e.jsx(l1,{}),e.jsxs(La,{className:"text-destructive focus:text-destructive",onClick:()=>{var ke;return c({id:Q.id,name:((ke=Q.property)==null?void 0:ke.property_address)??Q.name})},children:[e.jsx(In,{className:"h-4 w-4 mr-2"})," Delete permanently"]})]})]})]})]})]},Q.id)})}),e.jsx(Fl,{open:!!o,onOpenChange:Q=>!Q&&c(null),children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Delete this campaign?"}),e.jsxs(Ll,{children:[o==null?void 0:o.name," — the letter, landing page, QR link, seller guide and follow-up tasks will be permanently removed. This can't be undone. Archive instead if you may need it later."]})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{o&&N.mutate(o.id),c(null)},children:"Delete permanently"})]})]})})]});return!h.isLoading&&!h.hasAccess?e.jsx(qs,{title:"By-Owner Breakthrough",children:e.jsx("div",{className:"fsbo-theme -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)] grid place-items-center",children:e.jsxs("div",{className:"fsbo-tile p-10 text-center max-w-lg",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-2xl fsbo-dark grid place-items-center",children:e.jsx(cn,{className:"h-6 w-6 text-accent"})}),e.jsx("h2",{className:"fsbo-serif text-2xl mt-4",children:"By-Owner Breakthrough is invite-only"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:"This tool is currently being rolled out to select LevelUp members. Reach out to your coach to request early access."})]})})}):e.jsx(qs,{title:"By-Owner Breakthrough",children:e.jsxs("div",{className:"fsbo-theme relative -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)]",children:[e.jsxs(kr.div,{initial:{opacity:0,y:18},animate:{opacity:1,y:0},transition:{duration:.55,ease:[.22,1,.36,1]},className:"fsbo-dark rounded-3xl px-6 sm:px-10 py-9 relative overflow-hidden",children:[e.jsx("div",{className:"absolute -right-10 -top-16 h-56 w-56 rounded-full bg-accent/20 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"fsbo-eyebrow text-accent",children:"By-Owner Breakthrough"}),e.jsx("h1",{className:"fsbo-serif text-3xl sm:text-[42px] leading-tight mt-2 max-w-2xl",children:"Turn FSBOs Into Listing Appointments."}),e.jsx("p",{className:"text-white/70 mt-3 max-w-xl",children:"Add a for-sale-by-owner property, choose a voice, and generate a complete campaign: letter, QR code, landing page, seller guide, scripts, and follow-up tasks."}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3",children:[e.jsxs(U,{size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>s("/apps/fsbo-breakthrough/new"),children:[e.jsx(an,{className:"h-4 w-4 mr-1"})," New Campaign"]}),e.jsx(U,{size:"lg",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",onClick:()=>n("campaigns"),children:"View campaigns"})]})]})]}),e.jsxs(oa,{value:t,onValueChange:n,className:"mt-6",children:[e.jsx(la,{className:"flex w-full overflow-x-auto no-scrollbar justify-start bg-transparent p-0 gap-2 h-auto",children:mmr.map(Z=>e.jsxs(Kt,{value:Z.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground rounded-full border border-border bg-card px-4 py-2 text-sm whitespace-nowrap",children:[e.jsx(Z.icon,{className:"h-3.5 w-3.5 mr-1.5"}),Z.label]},Z.id))}),e.jsxs(Zt,{value:"dashboard",className:"mt-6 space-y-6",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-2 lg:grid-cols-5",children:[e.jsx(y5,{label:"Properties",value:M.properties,icon:ra,delay:0}),e.jsx(y5,{label:"Campaigns",value:M.campaigns,icon:cn,delay:.04}),e.jsx(y5,{label:"Letters",value:M.letters,icon:ln,delay:.08}),e.jsx(y5,{label:"QR Scans",value:M.qr,icon:Sf,delay:.12}),e.jsx(y5,{label:"Page Visits",value:M.visits,icon:fl,delay:.16}),e.jsx(y5,{label:"Guide Views",value:M.guideViews,icon:Ur,delay:.2}),e.jsx(y5,{label:"Seller Leads",value:M.leads,icon:Bn,delay:.24}),e.jsx(y5,{label:"Appointments",value:M.appointments,icon:cv,delay:.28}),e.jsx(y5,{label:"Hot Leads",value:M.hot,icon:Xd,delay:.32,hint:"Score 75+"}),e.jsx(y5,{label:"Listings Won",value:M.listed,icon:Al,delay:.36})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-3",children:[e.jsxs("div",{className:"fsbo-tile p-5 lg:col-span-2",children:[e.jsx("div",{className:"fsbo-eyebrow text-muted-foreground",children:"Last 14 days"}),e.jsx("div",{className:"text-lg font-semibold mt-1",children:"Homeowner engagement"}),e.jsx("div",{className:"h-64 mt-4",children:e.jsx(oj,{width:"100%",height:"100%",children:e.jsxs(Ett,{data:I,children:[e.jsxs("defs",{children:[e.jsxs("linearGradient",{id:"fsboVisits",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:0})]}),e.jsxs("linearGradient",{id:"fsboLeads",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--accent))",stopOpacity:.5}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--accent))",stopOpacity:0})]})]}),e.jsx($7,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",vertical:!1}),e.jsx(wb,{dataKey:"day",tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))"}),e.jsx(jb,{allowDecimals:!1,tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))",width:28}),e.jsx(Tg,{contentStyle:{borderRadius:12,border:"1px solid hsl(var(--border))"}}),e.jsx(M_,{type:"monotone",dataKey:"visits",stroke:"hsl(var(--primary))",fill:"url(#fsboVisits)",strokeWidth:2}),e.jsx(M_,{type:"monotone",dataKey:"leads",stroke:"hsl(var(--accent))",fill:"url(#fsboLeads)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsx("div",{className:"fsbo-eyebrow text-muted-foreground",children:"Next up"}),e.jsx("div",{className:"text-lg font-semibold mt-1",children:"Your tasks"}),e.jsxs("div",{className:"mt-4 space-y-2",children:[L.filter(Z=>!Z.completed_at).slice(0,5).map(Z=>e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-muted/40",children:[e.jsx(xi,{checked:!!Z.completed_at,onCheckedChange:Q=>v.mutate({id:Z.id,done:!!Q})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium",children:Z.title}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Z.detail}),Z.due_date?e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Due ",Z.due_date]}):null]})]},Z.id)),!L.filter(Z=>!Z.completed_at).length&&e.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center",children:"No open tasks — create a campaign to get started."})]})]})]})]}),e.jsx(Zt,{value:"campaigns",className:"mt-6",children:K("No campaigns yet. Start with a new FSBO property.")}),e.jsx(Zt,{value:"properties",className:"mt-6",children:e.jsx("div",{className:"space-y-3",children:(p.data??[]).length===0?e.jsx("div",{className:"fsbo-tile p-10 text-center text-muted-foreground",children:"No FSBO properties added yet."}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2 lg:grid-cols-3",children:(p.data??[]).map(Z=>e.jsxs("div",{className:"fsbo-tile p-4",children:[e.jsx("div",{className:"font-semibold",children:Z.property_address}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Z.city,Z.city&&Z.state?", ":"",Z.state]}),e.jsx("div",{className:"mt-2 text-sm",children:Z.seller_name||"—"}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Z.seller_phone||"—"," · ",Z.seller_email||"—"]}),e.jsxs("div",{className:"mt-1 text-sm text-muted-foreground",children:["Est. value ",lYe(Z.estimated_value)]}),e.jsxs(U,{size:"sm",variant:"outline",className:"mt-3",onClick:()=>u(Z),children:[e.jsx(ri,{className:"h-3.5 w-3.5 mr-1.5"})," Edit details"]})]},Z.id))})})}),e.jsx(Zt,{value:"followup",className:"mt-6",children:e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsx("div",{className:"text-lg font-semibold",children:"All follow-up tasks"}),e.jsx("div",{className:"mt-4 space-y-2",children:L.map(Z=>e.jsxs("div",{className:Mt("flex items-start gap-3 p-3 rounded-lg",Z.completed_at?"bg-muted/30":"bg-muted/40"),children:[e.jsx(xi,{checked:!!Z.completed_at,onCheckedChange:Q=>v.mutate({id:Z.id,done:!!Q})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:Mt("text-sm font-medium",Z.completed_at&&"line-through text-muted-foreground"),children:Z.title}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Z.detail}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 capitalize",children:[Z.channel," · ",Z.due_date??"No due date"]})]})]},Z.id))})]})}),e.jsx(Zt,{value:"analytics",className:"mt-6",children:e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsx("div",{className:"text-lg font-semibold",children:"Recent events"}),e.jsx("div",{className:"mt-4 space-y-2",children:T.slice(0,50).map(Z=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-muted/40",children:[e.jsx("div",{className:"text-sm capitalize",children:Z.event_type.replace(/_/g," ")}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Gs(new Date(Z.created_at),"MMM d, h:mm a")})]},Z.id))})]})}),e.jsx(Zt,{value:"letters",className:"mt-6",children:K("Generate letter content by creating a campaign first.")}),e.jsx(Zt,{value:"landing",className:"mt-6",children:K("Generate landing pages by creating a campaign first.")}),e.jsx(Zt,{value:"guides",className:"mt-6",children:K("Generate seller guides by creating a campaign first.")}),e.jsx(Zt,{value:"templates",className:"mt-6",children:e.jsx("div",{className:"grid gap-3 md:grid-cols-2 lg:grid-cols-3",children:fas.map(Z=>e.jsxs("div",{className:"fsbo-tile p-4",children:[e.jsx("div",{className:"font-semibold",children:Z.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Z.note})]},Z.id))})}),e.jsx(Zt,{value:"settings",className:"mt-6",children:e.jsxs("div",{className:"fsbo-tile p-5 max-w-xl",children:[e.jsx("div",{className:"text-lg font-semibold",children:"Settings"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Campaign style, tone, and landing page settings are managed inside each campaign."})]})})]}),e.jsx(yas,{property:d,open:!!d,onOpenChange:Z=>{Z||u(null)}})]})})}const k3t=["Add the property","Choose the campaign voice","Generate everything"];function fmr(){const s=Wn(),{user:t}=vs(),{generate:n,invalidate:r}=l8e(),[a,i]=j.useState(0),[l,o]=j.useState(!1),[c,d]=j.useState(FTe[0].id),[u,h]=j.useState("professional"),[m,p]=j.useState({property_address:"",city:"",state:"",zip:"",property_type:"single_family",estimated_value:"",seller_name:"",seller_email:"",seller_phone:"",notes:"",photo_url:""}),f=(b,N)=>p(S=>({...S,[b]:N})),x=a===0?m.property_address.trim().length>3:!0,y=async()=>{if(t){o(!0);try{const{data:b,error:N}=await q.from("fsbo_properties").insert({owner_user_id:t.id,property_address:m.property_address.trim(),city:m.city||null,state:m.state||null,zip:m.zip||null,property_type:m.property_type||"single_family",estimated_value:m.estimated_value?Number(m.estimated_value):null,seller_name:m.seller_name||null,seller_email:m.seller_email||null,seller_phone:m.seller_phone||null,notes:m.notes||null,photo_url:m.photo_url||null}).select().single();if(N)throw N;const{data:S,error:A}=await q.from("fsbo_campaigns").insert({owner_user_id:t.id,property_id:b.id,name:m.property_address.trim(),slug:cmr(m.property_address),style:c,tone:u,status:"generating",published:!0}).select().single();if(A)throw A;await n.mutateAsync({campaignId:S.id}),r(),re.success("Campaign built — everything is ready."),s(`/apps/fsbo-breakthrough/campaigns/${S.id}`)}catch(b){re.error(b instanceof Error?b.message:"Could not create the campaign")}finally{o(!1)}}},v=(b,N,S={})=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:N}),e.jsx(xe,{value:m[b],onChange:A=>f(b,A.target.value),...S})]});return e.jsx(qs,{title:"New FSBO Campaign",children:e.jsxs("div",{className:"fsbo-theme -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)]",children:[e.jsxs(U,{variant:"ghost",size:"sm",className:"gap-2 mb-4",onClick:()=>s("/apps/fsbo-breakthrough"),children:[e.jsx(Aa,{className:"h-4 w-4"})," Back to By-Owner Breakthrough"]}),e.jsx("div",{className:"flex items-center gap-3 mb-6",children:k3t.map((b,N)=>e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsx("div",{className:Mt("h-9 w-9 rounded-full grid place-items-center text-sm font-bold shrink-0 transition-colors",Nf("property_type",b.target.value),children:gas.map(b=>e.jsx("option",{value:b.value,children:b.label},b.value))})]}),v("seller_name","Seller name"),v("seller_email","Seller email",{type:"email"}),v("seller_phone","Seller phone")]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Property photo"}),e.jsx(q9,{value:m.photo_url,onChange:b=>f("photo_url",b??""),label:"Property photo",prefix:"fsbo-property"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Agent notes"}),e.jsx(Fs,{rows:6,value:m.notes,onChange:b=>f("notes",b.target.value),placeholder:"Anything you know: asking price, why they're selling solo, motivation, photos, etc."})]})]})]}):null,a===1?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"fsbo-tile p-6",children:[e.jsx("div",{className:"fsbo-eyebrow text-muted-foreground",children:"Step two"}),e.jsx("h2",{className:"fsbo-serif text-2xl mt-1",children:"Pick the voice of the campaign"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"The style shapes the letter, the landing page and the whole follow-up sequence."}),e.jsx("div",{className:"grid gap-3 mt-5 md:grid-cols-2 xl:grid-cols-3",children:FTe.map(b=>e.jsxs("button",{onClick:()=>d(b.id),className:Mt("text-left p-5 rounded-xl border transition-all relative overflow-hidden",c===b.id?"border-primary bg-primary/5":"border-border bg-card hover:border-primary/30"),children:[e.jsx("div",{className:Mt("absolute inset-x-0 top-0 h-1 bg-gradient-to-r",b.accent)}),e.jsx("div",{className:"font-semibold",children:b.name}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:b.tagline}),e.jsx("div",{className:"text-sm text-muted-foreground mt-2",children:b.description}),e.jsx("div",{className:"mt-3 text-xs text-primary font-medium",children:b.previewHeadline}),e.jsx("div",{className:"text-xs text-muted-foreground",children:b.previewBody})]},b.id))})]}),e.jsxs("div",{className:"fsbo-tile p-6",children:[e.jsx("div",{className:"fsbo-eyebrow text-muted-foreground",children:"Letter tone"}),e.jsx("div",{className:"grid gap-3 mt-3 sm:grid-cols-2 lg:grid-cols-5",children:fas.map(b=>e.jsxs("button",{onClick:()=>h(b.id),className:Mt("p-4 rounded-xl border text-left transition-all",u===b.id?"border-primary bg-primary/5":"border-border bg-card hover:border-primary/30"),children:[e.jsx("div",{className:"font-medium",children:b.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:b.note})]},b.id))})]})]}):null,a===2?e.jsxs("div",{className:"fsbo-tile p-10 text-center",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-primary/10 grid place-items-center mb-4",children:e.jsx(Lg,{className:"h-6 w-6 text-primary"})}),e.jsx("h2",{className:"fsbo-serif text-2xl",children:"Ready to build your campaign"}),e.jsxs("p",{className:"text-muted-foreground mt-2 max-w-md mx-auto",children:["We'll generate the letter, landing page, seller guide, follow-up scripts, and task sequence for",e.jsxs("span",{className:"font-semibold text-foreground",children:[" ",m.property_address||"this property"]}),"."]}),e.jsx("div",{className:"mt-6 flex justify-center",children:e.jsxs(U,{size:"lg",onClick:y,disabled:l,children:[l?e.jsx(Et,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Generate campaign"]})})]}):null]},a)}),e.jsxs("div",{className:"flex justify-between mt-6",children:[e.jsxs(U,{variant:"outline",disabled:a===0,onClick:()=>i(b=>b-1),children:[e.jsx(Aa,{className:"h-4 w-4 mr-1"})," Back"]}),a<2&&e.jsxs(U,{disabled:!x,onClick:()=>i(b=>b+1),children:["Next ",e.jsx(Oa,{className:"h-4 w-4 ml-1"})]})]})]})})}function gmr(){var ce,je,be,he,ge,ke,Te,Me,Oe,Se,Qe,Ae,Fe,Ne,$e,Ve,qe,Ze,Ue,Ye;const{id:s}=Di(),t=Wn(),{user:n}=vs(),r=nmr(s),a=jat(),i=wat(),{generate:l,saveCampaign:o,deleteCampaign:c}=l8e(),[d,u]=j.useState(""),[h,m]=j.useState(!1),[p,f]=j.useState("letter"),[x,y]=j.useState(!1),[v,b]=j.useState(!1),N=r.data,S=(N==null?void 0:N.content)??{},A=N?xas(N.slug):"",T=ct({queryKey:["fsbo-agent-profile",n==null?void 0:n.id],enabled:!!n,queryFn:async()=>{const{data:Ge}=await q.from("profiles").select("name, email, phone, avatar_url, brokerage_name, website_url, title").eq("id",n.id).maybeSingle();return Ge}}),L={name:(ce=T.data)==null?void 0:ce.name,title:(je=T.data)==null?void 0:je.title,phone:(be=T.data)==null?void 0:be.phone,email:(he=T.data)==null?void 0:he.email,website_url:(ge=T.data)==null?void 0:ge.website_url,avatar_url:(ke=T.data)==null?void 0:ke.avatar_url,brokerage_name:(Te=T.data)==null?void 0:Te.brokerage_name},M=j.useRef(null),I=j.useRef(null),R=j.useMemo(()=>{var tt,pt;const Ge=(a.data??[]).filter(ft=>ft.campaign_id===s),He={};return Ge.forEach(ft=>{He[ft.event_type]=(He[ft.event_type]??0)+1}),He.letter=S.letter?1:0,He.email=((tt=S.emails)==null?void 0:tt.length)??0,He.sms=((pt=S.sms)==null?void 0:pt.length)??0,He.form_submit=(i.data??[]).filter(ft=>ft.campaign_id===s).length,He},[a.data,i.data,s,S]),z=async()=>{var Ge;if(M.current){m(!0);try{const He=await eH(M.current,{pixelRatio:2}),tt=document.createElement("a");tt.href=He;const pt=oYe(((Ge=N==null?void 0:N.property)==null?void 0:Ge.property_address)??"letter");tt.download=`${pt||"letter"}.png`,tt.click(),re.success("Letter image downloaded")}catch{re.error("Could not download letter")}finally{m(!1)}}},$=async()=>{var Ge;if(I.current){m(!0);try{const He=await eH(I.current,{pixelRatio:2}),tt=document.createElement("a");tt.href=He;const pt=oYe(((Ge=N==null?void 0:N.property)==null?void 0:Ge.property_address)??"guide");tt.download=`${pt||"guide"}-guide.png`,tt.click(),re.success("Guide image downloaded")}catch{re.error("Could not download guide")}finally{m(!1)}}},H=Ge=>{var Ut;const He=document.querySelector("[data-print-root]"),tt=He?document.createElement("div"):null;He&&tt&&((Ut=He.parentNode)==null||Ut.insertBefore(tt,He),document.body.appendChild(He));const pt=document.title;document.title=Ge,document.body.classList.add("printing-doc");let ft=!1;const qt=()=>{ft||(ft=!0,He&&(tt!=null&&tt.parentNode)&&tt.parentNode.replaceChild(He,tt),document.body.classList.remove("printing-doc"),document.title=pt,window.removeEventListener("afterprint",qt))};window.addEventListener("afterprint",qt);try{window.print()}finally{setTimeout(qt,1e3)}},V=(((Me=N==null?void 0:N.property)==null?void 0:Me.property_address)??"Campaign").replace(/[\\/:*?"<>|]/g,"-").trim(),K=Ge=>{s&&(l.mutate({campaignId:s,section:Ge,instruction:d}),u(""))};if(r.isLoading)return e.jsx(qs,{title:"Campaign",children:e.jsx("div",{className:"grid place-items-center py-24",children:e.jsx(Et,{className:"h-6 w-6 animate-spin"})})});if(!N)return e.jsx(qs,{title:"Campaign",children:e.jsx("div",{className:"py-12 text-center text-muted-foreground",children:"Campaign not found."})});const Z=FTe.find(Ge=>Ge.id===N.style),Q=S.letter,le=S.landing,ue=S.guide,se=S.emails??[],ne=S.sms??[],ie=S.scripts;return e.jsx(qs,{title:"FSBO Campaign",children:e.jsxs("div",{className:"fsbo-theme -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)]",children:[e.jsxs(U,{variant:"ghost",size:"sm",className:"gap-2 mb-4",onClick:()=>t("/apps/fsbo-breakthrough"),children:[e.jsx(Aa,{className:"h-4 w-4"})," Back to By-Owner Breakthrough"]}),e.jsx(yas,{property:N.property,open:v,onOpenChange:b}),e.jsxs("div",{className:"fsbo-dark rounded-2xl p-6 sm:p-8 relative overflow-hidden",children:[e.jsx("div",{className:"absolute -right-10 -top-16 h-56 w-56 rounded-full bg-accent/20 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col lg:flex-row lg:items-center justify-between gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"fsbo-eyebrow text-accent",children:[(Z==null?void 0:Z.name)??N.style," · ",N.status]}),e.jsx("h1",{className:"fsbo-serif text-2xl sm:text-3xl mt-1",children:((Oe=N.property)==null?void 0:Oe.property_address)??N.name}),e.jsxs("p",{className:"text-white/70 mt-1",children:[((Se=N.property)==null?void 0:Se.seller_name)||"Homeowner"," · ",(Qe=N.property)==null?void 0:Qe.city,(Ae=N.property)!=null&&Ae.city&&((Fe=N.property)!=null&&Fe.state)?", ":"",(Ne=N.property)==null?void 0:Ne.state,($e=N.property)!=null&&$e.estimated_value?` · Est. ${lYe(N.property.estimated_value)}`:""]}),(Ve=N.property)!=null&&Ve.seller_phone||(qe=N.property)!=null&&qe.seller_email?e.jsx("p",{className:"text-white/50 text-sm mt-1",children:[(Ze=N.property)==null?void 0:Ze.seller_phone,(Ue=N.property)==null?void 0:Ue.seller_email].filter(Boolean).join(" · ")}):null]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(U,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20",onClick:()=>b(!0),children:[e.jsx(ri,{className:"h-4 w-4 mr-1"})," Edit details"]}),e.jsx(U,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20",asChild:!0,children:e.jsxs("a",{href:A,target:"_blank",rel:"noreferrer",children:[e.jsx(fl,{className:"h-4 w-4 mr-1"})," Preview"]})}),e.jsxs(U,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20",onClick:()=>{navigator.clipboard.writeText(A),re.success("Copied")},children:[e.jsx(Pa,{className:"h-4 w-4 mr-1"})," Copy link"]}),e.jsxs(U,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20",onClick:()=>K(),children:[e.jsx(no,{className:"h-4 w-4 mr-1"})," Regenerate"]}),e.jsx(U,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20 hover:text-destructive",onClick:()=>c.mutate(N.id),children:e.jsx(In,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"mt-6 grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-white/10 rounded-lg p-3",children:[e.jsx("div",{className:"text-xs text-white/60",children:"Page visits"}),e.jsx("div",{className:"text-xl font-bold",children:R.page_view??0})]}),e.jsxs("div",{className:"bg-white/10 rounded-lg p-3",children:[e.jsx("div",{className:"text-xs text-white/60",children:"QR scans"}),e.jsx("div",{className:"text-xl font-bold",children:R.qr_scan??0})]}),e.jsxs("div",{className:"bg-white/10 rounded-lg p-3",children:[e.jsx("div",{className:"text-xs text-white/60",children:"Leads"}),e.jsx("div",{className:"text-xl font-bold",children:R.form_submit??0})]}),e.jsxs("div",{className:"bg-white/10 rounded-lg p-3",children:[e.jsx("div",{className:"text-xs text-white/60",children:"Guide views"}),e.jsx("div",{className:"text-xl font-bold",children:R.guide_view??0})]})]})]}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsx(xe,{placeholder:"Tell AI what to change (e.g., 'make it shorter', 'focus on luxury buyers')...",value:d,onChange:Ge=>u(Ge.target.value),className:"max-w-xl"}),e.jsx(U,{variant:"outline",onClick:()=>K(),disabled:l.isPending,children:l.isPending?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):e.jsx(cn,{className:"h-4 w-4"})})]}),e.jsxs(oa,{value:p,onValueChange:f,className:"mt-6",children:[e.jsx(la,{className:"flex w-full overflow-x-auto no-scrollbar justify-start bg-transparent p-0 gap-2 h-auto",children:[{id:"letter",label:"Letter",icon:ln},{id:"landing",label:"Landing Page",icon:fl},{id:"guide",label:"Seller Guide",icon:Ur},{id:"scripts",label:"Scripts & Drip",icon:Ki},{id:"leads",label:"Leads",icon:ba}].map(Ge=>e.jsxs(Kt,{value:Ge.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground rounded-full border border-border bg-card px-4 py-2 text-sm whitespace-nowrap",children:[e.jsx(Ge.icon,{className:"h-3.5 w-3.5 mr-1.5"})," ",Ge.label]},Ge.id))}),e.jsxs(Zt,{value:"letter",className:"mt-6",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4","data-print-hide":!0,children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-semibold",children:"Mail-ready letter"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"Prints as a single clean 8.5×11 sheet — no browser header or footer."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>y(Ge=>!Ge),disabled:!Q,children:[e.jsx(ri,{className:"h-4 w-4 mr-1"})," ",x?"Close editor":"Edit letter"]}),e.jsxs(U,{size:"sm",variant:"outline",onClick:z,disabled:h,children:[e.jsx(W2,{className:"h-4 w-4 mr-1"})," Download image"]}),e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>H(V),children:[e.jsx(PA,{className:"h-4 w-4 mr-1"})," Print"]})]})]}),x&&Q?e.jsx("div",{className:"mb-6 print:hidden","data-print-hide":!0,children:e.jsx(has,{letter:Q,saving:o.isPending,onCancel:()=>y(!1),onSave:Ge=>{o.mutate({id:s,patch:{content:{...S,letter:Ge}}},{onSuccess:()=>y(!1)})}})}):null,e.jsx("div",{className:"fsbo-tile p-6 max-w-3xl mx-auto",children:e.jsxs("div",{ref:M,"data-print-root":!0,className:"bg-white text-foreground p-8 sm:p-12 rounded-lg shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between mb-8",children:[e.jsxs("div",{children:[L.name?e.jsx("div",{className:"font-bold text-lg",children:L.name}):null,L.title?e.jsx("div",{className:"text-sm text-gray-600",children:L.title}):null,L.brokerage_name?e.jsx("div",{className:"text-sm text-gray-600",children:L.brokerage_name}):null]}),L.avatar_url?e.jsx("img",{src:L.avatar_url,alt:L.name??"",className:"h-16 w-16 rounded-full object-cover"}):null]}),Q?e.jsxs("div",{className:"space-y-4 text-[15px] leading-relaxed",children:[e.jsx("div",{children:Q.greeting}),Q.paragraphs.map((Ge,He)=>e.jsx("p",{children:Ge},He)),e.jsx("div",{children:Q.closing}),e.jsx("div",{className:"font-semibold","data-print-keep":!0,children:Q.signature}),e.jsx("div",{className:"text-sm text-gray-600 italic mt-4","data-print-keep":!0,children:Q.ps})]}):e.jsx("div",{className:"text-muted-foreground",children:"Letter content not generated yet."}),e.jsxs("div",{className:"mt-8 pt-6 border-t flex items-center gap-4","data-print-keep":!0,children:[e.jsx("div",{className:"h-24 w-24 shrink-0",children:e.jsx(fS,{value:A,size:96})}),e.jsxs("div",{className:"text-sm text-gray-600",children:[e.jsx("div",{className:"font-semibold",children:"Scan for your free guide"}),e.jsx("div",{children:A})]})]})]})})]}),e.jsxs(Zt,{value:"landing",className:"mt-6",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsx("div",{className:"text-lg font-semibold",children:"Landing page copy"}),e.jsx(U,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:A,target:"_blank",rel:"noreferrer",children:[e.jsx(Sr,{className:"h-4 w-4 mr-1"})," Live preview"]})})]}),e.jsx("div",{className:"fsbo-tile p-6 max-w-3xl mx-auto space-y-4",children:le?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm uppercase tracking-wider text-primary",children:le.eyebrow}),e.jsx("h2",{className:"text-3xl font-bold",children:le.headline}),e.jsx("p",{className:"text-lg text-muted-foreground",children:le.subheadline}),e.jsx("p",{className:"text-foreground",children:le.intro}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 mt-4",children:le.discover.map((Ge,He)=>e.jsxs("div",{className:"bg-muted/40 p-4 rounded-lg",children:[e.jsx("div",{className:"font-semibold",children:Ge.title}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Ge.body})]},He))}),e.jsxs("div",{className:"mt-4 p-4 bg-primary/5 border-l-4 border-primary rounded-r-lg",children:[e.jsxs("div",{className:"italic",children:['"',le.testimonial.quote,'"']}),e.jsxs("div",{className:"text-sm font-semibold mt-2",children:["— ",le.testimonial.author]})]}),e.jsx("div",{className:"mt-4",children:e.jsx(U,{size:"lg",children:le.cta})})]}):e.jsx("div",{className:"text-muted-foreground",children:"Landing page content not generated yet."})})]}),e.jsxs(Zt,{value:"guide",className:"mt-6",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4","data-print-hide":!0,children:[e.jsx("div",{className:"text-lg font-semibold",children:"Seller guide"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{size:"sm",variant:"outline",onClick:$,disabled:h,children:[e.jsx(W2,{className:"h-4 w-4 mr-1"})," Download image"]}),e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>H(V),children:[e.jsx(PA,{className:"h-4 w-4 mr-1"})," Print"]}),e.jsx(U,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:`${A}/guide`,target:"_blank",rel:"noreferrer",children:[e.jsx(Sr,{className:"h-4 w-4 mr-1"})," Public view"]})})]})]}),e.jsx("div",{ref:I,"data-print-root":!0,className:"fsbo-tile p-8 max-w-4xl mx-auto space-y-6 bg-white text-foreground",children:ue?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-center pb-6 border-b",children:[e.jsx("div",{className:"text-sm uppercase tracking-wider text-primary",children:"By-Owner Breakthrough"}),e.jsx("h2",{className:"text-3xl font-bold mt-2",children:"FSBO Seller Guide"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:(Ye=N.property)==null?void 0:Ye.property_address})]}),e.jsx("p",{className:"text-lg leading-relaxed",children:ue.intro}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-semibold mb-3",children:"FSBO Reality Checklist"}),e.jsx("ul",{className:"space-y-2",children:ue.checklist.map((Ge,He)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"}),e.jsx("span",{children:Ge})]},He))})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-semibold mb-3",children:"Common Pitfalls"}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:ue.pitfalls.map((Ge,He)=>e.jsxs("div",{className:"bg-muted/30 p-4 rounded-lg",children:[e.jsx("div",{className:"font-semibold",children:Ge.title}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Ge.body})]},He))})]}),e.jsxs("div",{className:"grid gap-6 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-semibold mb-3",children:"Your Advantages"}),e.jsx("ul",{className:"space-y-2",children:ue.seller_advantages.map((Ge,He)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-primary",children:"+"}),e.jsx("span",{children:Ge})]},He))})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-semibold mb-3",children:"What an Agent Brings"}),e.jsx("ul",{className:"space-y-2",children:ue.agent_value.map((Ge,He)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-primary",children:"→"}),e.jsx("span",{children:Ge})]},He))})]})]}),e.jsxs("div",{className:"bg-primary/10 p-6 rounded-xl text-center",children:[e.jsx("h3",{className:"text-xl font-semibold mb-2",children:ue.cta}),e.jsx("p",{className:"text-muted-foreground mb-4",children:ue.cta_body}),e.jsx(U,{size:"lg",children:"Request a Free Consultation"})]})]}):e.jsx("div",{className:"text-muted-foreground",children:"Guide content not generated yet."})})]}),e.jsx(Zt,{value:"scripts",className:"mt-6",children:e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsx("div",{className:"text-lg font-semibold mb-4",children:"Agent scripts"}),ie?e.jsxs("div",{className:"space-y-4",children:[e.jsx(pde,{label:"Phone",text:ie.phone}),e.jsx(pde,{label:"Voicemail",text:ie.voicemail}),e.jsx(pde,{label:"Video",text:ie.video}),e.jsx(pde,{label:"Door knock",text:ie.door_knock}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-semibold mb-2",children:"Objection responses"}),e.jsx("div",{className:"space-y-2",children:ie.objections.map((Ge,He)=>e.jsxs("div",{className:"bg-muted/40 p-3 rounded-lg",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:['"',Ge.objection,'"']}),e.jsx("div",{className:"text-sm mt-1",children:Ge.response})]},He))})]})]}):e.jsx("div",{className:"text-muted-foreground",children:"Scripts not generated yet."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsx("div",{className:"text-lg font-semibold mb-4",children:"Email sequence"}),e.jsxs("div",{className:"space-y-2",children:[se.map((Ge,He)=>e.jsxs("div",{className:"bg-muted/40 p-3 rounded-lg",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Day ",He*4+1]}),e.jsx("div",{className:"font-medium",children:Ge.subject}),e.jsx("div",{className:"text-sm text-muted-foreground truncate",children:Ge.preview})]},Ge.key)),!se.length&&e.jsx("div",{className:"text-muted-foreground",children:"No emails generated yet."})]})]}),e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsx("div",{className:"text-lg font-semibold mb-4",children:"SMS sequence"}),e.jsxs("div",{className:"space-y-2",children:[ne.map((Ge,He)=>e.jsxs("div",{className:"bg-muted/40 p-3 rounded-lg",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Step ",He+1]}),e.jsx("div",{className:"text-sm",children:Ge.body})]},Ge.key)),!ne.length&&e.jsx("div",{className:"text-muted-foreground",children:"No SMS messages generated yet."})]})]})]})]})}),e.jsx(Zt,{value:"leads",className:"mt-6",children:e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsx("div",{className:"text-lg font-semibold mb-4",children:"Seller leads"}),e.jsx("div",{className:"space-y-3",children:(i.data??[]).filter(Ge=>Ge.campaign_id===s).length===0?e.jsx("div",{className:"text-muted-foreground",children:"No leads yet. Share the landing page to start collecting them."}):(i.data??[]).filter(Ge=>Ge.campaign_id===s).map(Ge=>e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg bg-muted/40",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-medium",children:[Ge.first_name," ",Ge.last_name]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Ge.email," · ",Ge.phone]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-1",children:["Timeline: ",Ge.timeline??"—"," · Motivation: ",Ge.motivation??"—"]}),e.jsx("div",{className:"text-sm mt-1",children:Ge.message})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs(Be,{className:Mt(Ge.temperature==="hot"?"bg-red-500/15 text-red-600":"bg-amber-500/15 text-amber-600"),children:[Ge.temperature," · ",Ge.lead_score]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:Gs(new Date(Ge.created_at),"MMM d")})]})]},Ge.id))})]})})]})]})})}function pde({label:s,text:t}){return e.jsxs("div",{className:"bg-muted/40 p-3 rounded-lg",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("div",{className:"text-sm font-semibold",children:s}),e.jsx(U,{size:"sm",variant:"ghost",className:"h-6 px-2",onClick:()=>{navigator.clipboard.writeText(t),re.success("Copied")},children:e.jsx(Pa,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:t})]})}const xmr="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/fsbo-public",S3t="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM";async function uO(s){try{const t=await fetch(xmr,{method:"POST",headers:{"Content-Type":"application/json",apikey:S3t,Authorization:`Bearer ${S3t}`},body:JSON.stringify(s)});return t.ok?await t.json():null}catch{return null}}function ymr(){const{slug:s}=Di(),[t,n]=j.useState(null),[r,a]=j.useState(!0),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState({first_name:"",last_name:"",email:"",phone:"",timeline:"",motivation:"",preferred_contact:"email",message:""});j.useEffect(()=>{s&&(a(!0),uO({action:"get",slug:s}).then(N=>{N!=null&&N.campaign&&n(N),a(!1)}))},[s]),j.useEffect(()=>{if(!s)return;const N=sessionStorage.getItem(`fsbo-${s}`)||crypto.randomUUID();sessionStorage.setItem(`fsbo-${s}`,N),uO({action:"track",slug:s,event_type:"page_view",session_id:N})},[s]);const h=async N=>{if(N.preventDefault(),!s)return;c(!0);const S=sessionStorage.getItem(`fsbo-${s}`)||void 0,A=await uO({action:"submit",slug:s,...d,session_id:S,wants_guide:!0});c(!1),A?l(!0):alert("Could not submit. Please try again.")};if(r)return e.jsx("div",{className:"min-h-screen grid place-items-center bg-stone-50",children:e.jsx(Et,{className:"h-6 w-6 animate-spin text-primary"})});if(!t)return e.jsx("div",{className:"min-h-screen grid place-items-center text-muted-foreground",children:"Landing page not found."});const m=t.campaign,p=m.content??{},f=p.landing,x=t.agent,y=m.property??{},v=p.landing_config??{media_mode:"photo",show_property_snapshot:!0,show_discover:!0,show_testimonial:!0},b=v.video_url?amr(v.video_url):null;return e.jsxs("div",{className:"min-h-screen bg-stone-50 text-stone-900",children:[e.jsxs(dl,{children:[e.jsxs("title",{children:[(f==null?void 0:f.headline)||"Selling On Your Own?"," — ",(x==null?void 0:x.name)||"LevelUp"]}),e.jsx("meta",{name:"description",content:(f==null?void 0:f.subheadline)||"Free FSBO seller guide from a local agent."})]}),e.jsx("div",{className:"bg-gradient-to-br from-[#4a6741] to-[#2d5a3d] text-white",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 py-12 lg:py-20",children:e.jsxs("div",{className:"grid lg:grid-cols-2 gap-10 items-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm uppercase tracking-wider text-[#f4d06f] font-semibold",children:(f==null?void 0:f.eyebrow)||"Free FSBO Seller Guide"}),e.jsx("h1",{className:"text-3xl sm:text-5xl font-bold mt-4 leading-tight",children:(f==null?void 0:f.headline)||"Selling On Your Own? Here's What You Should Know."}),e.jsx("p",{className:"text-lg text-white/80 mt-4",children:(f==null?void 0:f.subheadline)||`A complimentary guide for ${y.property_address||"your home"} created by a local agent.`}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3",children:[e.jsxs("a",{href:"#form",className:"inline-flex items-center gap-2 bg-[#f4d06f] text-[#0f4c5c] px-5 py-3 rounded-lg font-semibold hover:bg-[#f4d06f]/90",children:[(f==null?void 0:f.cta)||"Send Me the Free Guide"," ",e.jsx(Oa,{className:"h-4 w-4"})]}),e.jsx("a",{href:`/fsbo/${s}/guide`,className:"inline-flex items-center gap-2 bg-white/10 text-white px-5 py-3 rounded-lg font-semibold hover:bg-white/20",children:"Read the guide"})]})]}),e.jsx("div",{className:"rounded-2xl overflow-hidden shadow-2xl bg-white/10 ring-1 ring-white/15",children:(b==null?void 0:b.kind)==="iframe"?e.jsx("iframe",{src:b.src,className:"w-full aspect-video block border-0",scrolling:"no",allowFullScreen:!0,title:"Property media"}):(b==null?void 0:b.kind)==="file"?e.jsx("video",{src:b.src,className:"w-full aspect-video object-cover block",controls:!0}):typeof y.photo_url=="string"&&y.photo_url?e.jsx("img",{src:y.photo_url,alt:String(y.property_address||"Property photo"),loading:"eager",className:"w-full aspect-[4/3] object-cover object-center block"}):e.jsx("div",{className:"aspect-[4/3] grid place-items-center text-white/60",children:e.jsx(ra,{className:"h-12 w-12"})})})]})})}),v.show_property_snapshot!==!1&&e.jsx("div",{className:"max-w-5xl mx-auto px-4 sm:px-6 -mt-8",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-lg p-5 flex flex-wrap gap-6 justify-center items-center",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ni,{className:"h-4 w-4 text-[#4a6741]"})," ",e.jsx("span",{className:"font-semibold",children:y.property_address})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ra,{className:"h-4 w-4 text-[#4a6741]"})," ",e.jsx("span",{className:"capitalize",children:String(y.property_type||"").replace("_"," ")})]}),y.estimated_value?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"font-semibold",children:["Est. $",Number(y.estimated_value).toLocaleString()]})}):null]})}),e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 py-16",children:e.jsxs("div",{className:"grid lg:grid-cols-5 gap-12",children:[e.jsxs("div",{className:"lg:col-span-3 space-y-6",children:[e.jsx("div",{className:"text-lg leading-relaxed text-stone-700",children:f==null?void 0:f.intro}),v.show_discover!==!1&&(f==null?void 0:f.discover)&&e.jsx("div",{className:"grid sm:grid-cols-2 gap-4 mt-6",children:f.discover.map((N,S)=>e.jsxs("div",{className:"bg-white p-5 rounded-xl shadow-sm border border-stone-100",children:[e.jsx("div",{className:"font-semibold text-[#4a6741] mb-1",children:N.title}),e.jsx("div",{className:"text-sm text-stone-600",children:N.body})]},S))}),v.show_testimonial!==!1&&(f==null?void 0:f.testimonial)&&e.jsxs("div",{className:"mt-8 bg-[#4a6741]/10 p-6 rounded-2xl border-l-4 border-[#4a6741]",children:[e.jsx("div",{className:"flex gap-1 text-[#f4d06f] mb-2",children:[...Array(5)].map((N,S)=>e.jsx(Ua,{className:"h-4 w-4 fill-current"},S))}),e.jsxs("div",{className:"italic text-lg text-stone-800",children:['"',f.testimonial.quote,'"']}),e.jsxs("div",{className:"font-semibold text-sm mt-3",children:["— ",f.testimonial.author]})]})]}),e.jsx("div",{id:"form",className:"lg:col-span-2",children:e.jsx("div",{className:"bg-white rounded-2xl shadow-lg p-6 sm:p-8 sticky top-6",children:i?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-green-100 grid place-items-center mb-4",children:e.jsx(zr,{className:"h-7 w-7 text-green-600"})}),e.jsx("h3",{className:"text-xl font-bold",children:"Your guide is on the way!"}),e.jsxs("p",{className:"text-stone-600 mt-2",children:["Check your email for the guide. ",(x==null?void 0:x.name)||"The agent"," will follow up soon."]}),e.jsx("a",{href:`/fsbo/${s}/guide`,className:"inline-block mt-4 text-[#4a6741] font-semibold underline",children:"Read it now"})]}):e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsx("h3",{className:"text-xl font-bold",children:(f==null?void 0:f.form_subhead)||"Get your free guide"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{className:"text-xs",children:"First"}),e.jsx(xe,{value:d.first_name,onChange:N=>u(S=>({...S,first_name:N.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{className:"text-xs",children:"Last"}),e.jsx(xe,{value:d.last_name,onChange:N=>u(S=>({...S,last_name:N.target.value})),required:!0})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{className:"text-xs",children:"Email"}),e.jsx(xe,{type:"email",value:d.email,onChange:N=>u(S=>({...S,email:N.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{className:"text-xs",children:"Phone"}),e.jsx(xe,{type:"tel",value:d.phone,onChange:N=>u(S=>({...S,phone:N.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{className:"text-xs",children:"Timeline"}),e.jsxs("select",{className:"w-full h-10 rounded-md border border-input bg-background px-3 py-2 text-sm",value:d.timeline,onChange:N=>u(S=>({...S,timeline:N.target.value})),children:[e.jsx("option",{value:"",children:"Select…"}),imr.map(N=>e.jsx("option",{value:N.value,children:N.label},N.value))]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{className:"text-xs",children:"Preferred contact"}),e.jsx("select",{className:"w-full h-10 rounded-md border border-input bg-background px-3 py-2 text-sm",value:d.preferred_contact,onChange:N=>u(S=>({...S,preferred_contact:N.target.value})),children:lmr.map(N=>e.jsx("option",{value:N.value,children:N.label},N.value))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{className:"text-xs",children:"What prompted you to sell on your own?"}),e.jsxs("select",{className:"w-full h-10 rounded-md border border-input bg-background px-3 py-2 text-sm",value:d.motivation,onChange:N=>u(S=>({...S,motivation:N.target.value})),children:[e.jsx("option",{value:"",children:"Select…"}),omr.map(N=>e.jsx("option",{value:N,children:N},N))]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{className:"text-xs",children:"Message (optional)"}),e.jsx(Fs,{rows:3,value:d.message,onChange:N=>u(S=>({...S,message:N.target.value}))})]}),e.jsxs(U,{type:"submit",className:"w-full",size:"lg",disabled:o,children:[o?e.jsx(Et,{className:"h-4 w-4 animate-spin mr-2"}):null,(f==null?void 0:f.cta)||"Send Me the Free Guide"]}),e.jsxs("p",{className:"text-xs text-stone-500 text-center",children:["No spam. Unsubscribe anytime. Your info helps ",(x==null?void 0:x.name)||"the agent"," tailor the guide."]})]})})})]})}),e.jsx("div",{className:"bg-white border-t border-stone-100",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 py-12",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center gap-6",children:[x!=null&&x.avatar_url?e.jsx("img",{src:x.avatar_url,alt:x.name||"",className:"h-24 w-24 rounded-full object-cover shadow-md"}):null,e.jsxs("div",{className:"text-center sm:text-left",children:[e.jsx("div",{className:"text-xl font-bold",children:x==null?void 0:x.name}),e.jsxs("div",{className:"text-stone-600",children:[x==null?void 0:x.title,x!=null&&x.title&&(x!=null&&x.brokerage)?" · ":"",x==null?void 0:x.brokerage]}),e.jsxs("div",{className:"flex flex-wrap justify-center sm:justify-start gap-2 mt-3",children:[x!=null&&x.phone?e.jsx(U,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`tel:${x.phone}`,children:[e.jsx(ba,{className:"h-4 w-4 mr-1"})," Call"]})}):null,x!=null&&x.email?e.jsx(U,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`mailto:${x.email}`,children:[e.jsx(ln,{className:"h-4 w-4 mr-1"})," Email"]})}):null,x!=null&&x.website_url?e.jsx(U,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:x.website_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Ki,{className:"h-4 w-4 mr-1"})," Website"]})}):null]})]})]})})})]})}function vmr(){const{slug:s}=Di(),[t,n]=j.useState(null),[r,a]=j.useState(!0),[i,l]=j.useState({first_name:"",last_name:"",email:"",phone:"",message:""}),[o,c]=j.useState(!1),[d,u]=j.useState(!1);j.useEffect(()=>{s&&(a(!0),uO({action:"get",slug:s}).then(v=>{v!=null&&v.campaign&&n(v),a(!1)}))},[s]),j.useEffect(()=>{s&&uO({action:"track",slug:s,event_type:"guide_view"})},[s]);const h=async v=>{if(v.preventDefault(),!s||o)return;c(!0);const b=await uO({action:"submit",slug:s,...i,message:`Requested a free consultation from the guide page.${i.message?` — ${i.message}`:""}`,preferred_contact:"either",wants_guide:!1});c(!1),b?(u(!0),uO({action:"track",slug:s,event_type:"consultation_request"})):alert("Could not send your request. Please try again.")};if(r)return e.jsx("div",{className:"min-h-screen grid place-items-center bg-stone-50",children:e.jsx(Et,{className:"h-6 w-6 animate-spin text-primary"})});if(!t)return e.jsx("div",{className:"min-h-screen grid place-items-center text-muted-foreground",children:"Guide not found."});const m=t.campaign,f=(m.content??{}).guide,x=t.agent,y=m.property??{};return e.jsxs("div",{className:"min-h-screen bg-stone-50 text-stone-900",children:[e.jsxs(dl,{children:[e.jsxs("title",{children:["FSBO Seller Guide — ",(y==null?void 0:y.property_address)||"Your home"]}),e.jsx("meta",{name:"description",content:"Free guide for selling your home by owner."})]}),e.jsx("div",{className:"bg-gradient-to-br from-[#4a6741] to-[#2d5a3d] text-white",children:e.jsx("div",{className:"max-w-5xl mx-auto px-4 sm:px-6 py-6",children:e.jsxs(xr,{to:`/fsbo/${s}`,className:"inline-flex items-center gap-1 text-sm text-white/80 hover:text-white",children:[e.jsx(Aa,{className:"h-4 w-4"})," Back to landing page"]})})}),e.jsx("div",{className:"max-w-5xl mx-auto px-4 sm:px-6 py-12",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-lg p-8 sm:p-12",children:[e.jsxs("div",{className:"text-center pb-8 border-b border-stone-100",children:[e.jsx("div",{className:"text-sm uppercase tracking-wider text-[#4a6741] font-semibold",children:"By-Owner Breakthrough"}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-bold mt-2 text-stone-900",children:"FSBO Seller Guide"}),e.jsx("p",{className:"text-stone-600 mt-2 text-lg",children:y==null?void 0:y.property_address})]}),f?e.jsxs("div",{className:"space-y-10 mt-8",children:[e.jsx("p",{className:"text-lg leading-relaxed text-stone-700",children:f.intro}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold mb-4",children:"FSBO Reality Checklist"}),e.jsx("ul",{className:"space-y-3",children:f.checklist.map((v,b)=>e.jsxs("li",{className:"flex items-start gap-3 p-3 bg-stone-50 rounded-lg",children:[e.jsx("span",{className:"text-[#4a6741] font-bold text-lg",children:"✓"}),e.jsx("span",{className:"text-stone-700",children:v})]},b))})]}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold mb-4",children:"Common Pitfalls"}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:f.pitfalls.map((v,b)=>e.jsxs("div",{className:"bg-stone-50 p-5 rounded-xl",children:[e.jsx("div",{className:"font-semibold text-stone-900 mb-1",children:v.title}),e.jsx("div",{className:"text-sm text-stone-600",children:v.body})]},b))})]}),e.jsxs("div",{className:"grid gap-8 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold mb-4",children:"Your Advantages"}),e.jsx("ul",{className:"space-y-3",children:f.seller_advantages.map((v,b)=>e.jsxs("li",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-[#4a6741] font-bold",children:"+"}),e.jsx("span",{className:"text-stone-700",children:v})]},b))})]}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold mb-4",children:"What an Agent Brings"}),e.jsx("ul",{className:"space-y-3",children:f.agent_value.map((v,b)=>e.jsxs("li",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-[#4a6741] font-bold",children:"→"}),e.jsx("span",{className:"text-stone-700",children:v})]},b))})]})]}),e.jsxs("div",{id:"consult",className:"bg-[#4a6741]/10 p-8 rounded-2xl",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("h3",{className:"text-2xl font-bold mb-3 text-stone-900",children:f.cta}),e.jsx("p",{className:"text-stone-600 mb-6 max-w-lg mx-auto",children:f.cta_body})]}),d?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-green-100 grid place-items-center mb-3",children:e.jsx(zr,{className:"h-7 w-7 text-green-600"})}),e.jsx("div",{className:"font-semibold text-lg",children:"Request received"}),e.jsxs("p",{className:"text-stone-600 mt-1",children:[(x==null?void 0:x.name)||"Your agent"," will reach out shortly with an objective look at your home."]})]}):e.jsxs("form",{onSubmit:h,className:"max-w-xl mx-auto space-y-3 bg-white rounded-xl p-6 shadow-sm",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{className:"text-xs",children:"First"}),e.jsx(xe,{value:i.first_name,onChange:v=>l(b=>({...b,first_name:v.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{className:"text-xs",children:"Last"}),e.jsx(xe,{value:i.last_name,onChange:v=>l(b=>({...b,last_name:v.target.value})),required:!0})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{className:"text-xs",children:"Email"}),e.jsx(xe,{type:"email",value:i.email,onChange:v=>l(b=>({...b,email:v.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{className:"text-xs",children:"Phone"}),e.jsx(xe,{type:"tel",value:i.phone,onChange:v=>l(b=>({...b,phone:v.target.value}))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(te,{className:"text-xs",children:"Best time / anything I should know (optional)"}),e.jsx(Fs,{rows:3,value:i.message,onChange:v=>l(b=>({...b,message:v.target.value}))})]}),e.jsxs(U,{type:"submit",size:"lg",className:"w-full",disabled:o,children:[o?e.jsx(Et,{className:"h-4 w-4 animate-spin mr-2"}):null,"Request a Free Consultation"]}),e.jsx("p",{className:"text-xs text-stone-500 text-center",children:"No obligation. No pressure — just clear facts about your home's market."})]})]})]}):e.jsx("div",{className:"text-stone-500 text-center py-12",children:"Guide content not available yet."}),e.jsxs("div",{className:"mt-12 pt-8 border-t border-stone-100 flex flex-col sm:flex-row items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[x!=null&&x.avatar_url?e.jsx("img",{src:x.avatar_url,alt:x.name??"",className:"h-16 w-16 rounded-full object-cover"}):null,e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-lg",children:x==null?void 0:x.name}),e.jsxs("div",{className:"text-sm text-stone-600",children:[x==null?void 0:x.title,x!=null&&x.title&&(x!=null&&x.brokerage)?" · ":"",x==null?void 0:x.brokerage]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[x!=null&&x.phone?e.jsx(U,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`tel:${x.phone}`,children:[e.jsx(ba,{className:"h-4 w-4 mr-1"})," Call"]})}):null,x!=null&&x.email?e.jsx(U,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`mailto:${x.email}`,children:[e.jsx(ln,{className:"h-4 w-4 mr-1"})," Email"]})}):null]})]})]})})]})}function bmr(){const s=mas(),t=pas(),n=wat(),r=jat(),a=Qt(),[i,l]=j.useState(""),o=yt({mutationFn:async()=>{const{data:h,error:m}=await q.from("profiles").select("id");if(m)throw m;const p=new Date().toISOString(),f=(h??[]).map(y=>({user_id:y.id,feature_key:"fsbo_breakthrough",enabled:!0,tier:"beta",expires_at:null,created_at:p,updated_at:p})),{error:x}=await q.from("feature_entitlements").upsert(f,{onConflict:"user_id,feature_key"});if(x)throw x},onSuccess:()=>{re.success("Enabled for all members"),a.invalidateQueries({queryKey:["fsbo-breakthrough-access"]})},onError:h=>re.error(h.message)}),c=j.useMemo(()=>{const h=m=>(r.data??[]).filter(p=>p.event_type===m).length;return{properties:(t.data??[]).length,campaigns:(s.data??[]).length,letters:(s.data??[]).filter(m=>{var p;return(p=m.content)==null?void 0:p.letter}).length,qr:h("qr_scan"),visits:h("page_view"),guideViews:h("guide_view"),leads:(n.data??[]).length,appointments:h("appointment")}},[s.data,r.data,n.data,t.data]),d=j.useMemo(()=>{const h=[];for(let m=13;m>=0;m--){const p=new Date(Date.now()-m*864e5),f=p.toISOString().slice(0,10);h.push({day:Gs(p,"MMM d"),visits:(r.data??[]).filter(x=>x.event_type==="page_view"&&x.created_at.startsWith(f)).length,scans:(r.data??[]).filter(x=>x.event_type==="qr_scan"&&x.created_at.startsWith(f)).length,leads:(n.data??[]).filter(x=>x.created_at.startsWith(f)).length})}return h},[r.data,n.data]),u=(s.data??[]).filter(h=>{var m;return`${h.name} ${((m=h.property)==null?void 0:m.property_address)??""}`.toLowerCase().includes(i.trim().toLowerCase())});return s.isLoading||t.isLoading||n.isLoading||r.isLoading?e.jsx(qs,{title:"By-Owner Breakthrough Admin",children:e.jsx("div",{className:"grid place-items-center py-24",children:e.jsx(Et,{className:"h-6 w-6 animate-spin"})})}):e.jsx(qs,{title:"By-Owner Breakthrough Admin",children:e.jsxs("div",{className:"fsbo-theme -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsx("div",{className:"fsbo-eyebrow text-muted-foreground",children:"Admin"}),e.jsx("h1",{className:"fsbo-serif text-2xl",children:"By-Owner Breakthrough"})]}),e.jsxs(U,{onClick:()=>o.mutate(),disabled:o.isPending,children:[o.isPending?e.jsx(Et,{className:"h-4 w-4 animate-spin mr-2"}):null," Enable all members"]})]}),e.jsxs("div",{className:"grid gap-3 grid-cols-2 lg:grid-cols-4 mb-6",children:[e.jsx(vT,{label:"Properties",value:c.properties,icon:ra}),e.jsx(vT,{label:"Campaigns",value:c.campaigns,icon:ln}),e.jsx(vT,{label:"Page visits",value:c.visits,icon:fl}),e.jsx(vT,{label:"QR scans",value:c.qr,icon:Sf}),e.jsx(vT,{label:"Guide views",value:c.guideViews,icon:Ur}),e.jsx(vT,{label:"Leads",value:c.leads,icon:Bn}),e.jsx(vT,{label:"Appointments",value:c.appointments,icon:Bn}),e.jsx(vT,{label:"Letters",value:c.letters,icon:ln})]}),e.jsxs("div",{className:"fsbo-tile p-5 mb-6",children:[e.jsx("div",{className:"fsbo-eyebrow text-muted-foreground",children:"Last 14 days"}),e.jsx("div",{className:"text-lg font-semibold mt-1",children:"Network-wide engagement"}),e.jsx("div",{className:"h-64 mt-4",children:e.jsx(oj,{width:"100%",height:"100%",children:e.jsxs(Ett,{data:d,children:[e.jsxs("defs",{children:[e.jsxs("linearGradient",{id:"fsboAdminVisits",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:0})]}),e.jsxs("linearGradient",{id:"fsboAdminLeads",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--accent))",stopOpacity:.5}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--accent))",stopOpacity:0})]})]}),e.jsx($7,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",vertical:!1}),e.jsx(wb,{dataKey:"day",tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))"}),e.jsx(jb,{allowDecimals:!1,tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))",width:28}),e.jsx(Tg,{contentStyle:{borderRadius:12,border:"1px solid hsl(var(--border))"}}),e.jsx(M_,{type:"monotone",dataKey:"visits",stroke:"hsl(var(--primary))",fill:"url(#fsboAdminVisits)",strokeWidth:2}),e.jsx(M_,{type:"monotone",dataKey:"scans",stackId:"1",stroke:"hsl(var(--accent))",fill:"url(#fsboAdminLeads)",strokeWidth:2}),e.jsx(M_,{type:"monotone",dataKey:"leads",stackId:"1",stroke:"#5b8a5c",fill:"#5b8a5c",fillOpacity:.15,strokeWidth:2})]})})})]}),e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("div",{className:"text-lg font-semibold",children:"All campaigns"}),e.jsxs("div",{className:"relative w-64",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(xe,{className:"pl-9",placeholder:"Search campaigns…",value:i,onChange:h=>l(h.target.value)})]})]}),e.jsxs("div",{className:"space-y-3",children:[u.map(h=>{var f,x,y,v,b,N;const m=(n.data??[]).filter(S=>S.campaign_id===h.id).length,p=(r.data??[]).filter(S=>S.campaign_id===h.id&&S.event_type==="page_view").length;return e.jsxs("a",{href:`/apps/fsbo-breakthrough/campaigns/${h.id}`,className:"flex items-center justify-between p-4 rounded-xl bg-muted/40 hover:bg-muted/60 transition-colors",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:((f=h.property)==null?void 0:f.property_address)??h.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((x=h.property)==null?void 0:x.seller_name)||"Homeowner"," · ",(y=h.property)==null?void 0:y.city,(v=h.property)!=null&&v.city&&((b=h.property)!=null&&b.state)?", ":"",(N=h.property)==null?void 0:N.state]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(Be,{variant:"secondary",children:[e.jsx(fl,{className:"h-3 w-3 mr-1"}),p]}),e.jsxs(Be,{variant:"secondary",children:[e.jsx(Bn,{className:"h-3 w-3 mr-1"}),m]}),e.jsx(Oa,{className:"h-4 w-4 text-muted-foreground"})]})]},h.id)}),u.length===0&&e.jsx("div",{className:"text-muted-foreground text-center py-8",children:"No campaigns match."})]})]})]})})}function vT({label:s,value:t,icon:n}){return e.jsxs("div",{className:"fsbo-tile p-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("span",{className:"fsbo-eyebrow text-muted-foreground",children:s}),e.jsx(n,{className:"h-4 w-4 text-accent"})]}),e.jsx("div",{className:"mt-2 text-2xl font-bold",children:t})]})}const iZ=q;function _mr(){const{user:s}=vs(),t=Qt(),n=["attract-landing-page",s==null?void 0:s.id],{data:r,isLoading:a}=ct({queryKey:n,enabled:!!s,queryFn:async()=>{const{data:c,error:d}=await iZ.from("attract_landing_pages").select("*").eq("user_id",s.id).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(d)throw d;return c||null}}),{data:i}=ct({queryKey:["attract-landing-analytics",r==null?void 0:r.id],enabled:!!(r!=null&&r.id),queryFn:async()=>{const{data:c,error:d}=await iZ.from("attract_landing_events").select("event_type, section_key, created_at").eq("page_id",r.id).order("created_at",{ascending:!1}).limit(1e3);if(d)throw d;const u=c||[],h=u.filter(f=>f.event_type==="view").length,m=u.filter(f=>f.event_type==="cta_click").length,p=u.filter(f=>f.event_type==="calculator_run").length;return{views:h,ctas:m,calcs:p,conversion:h?Math.round(m/h*100):0}}}),l=yt({mutationFn:async c=>{const d=Ors(c||"my-attraction-page")||"attraction-page";let u=d;for(let f=0;f<5;f++){const{data:x}=await iZ.from("attract_landing_pages").select("id").eq("slug",u).maybeSingle();if(!x)break;u=`${d}-${Math.random().toString(36).slice(2,6)}`}const h=Rdr(c||"Your Name"),{data:m,error:p}=await iZ.from("attract_landing_pages").insert({...h,user_id:s.id,slug:u}).select("*").single();if(p)throw p;return m},onSuccess:()=>{t.invalidateQueries({queryKey:n}),re.success("Attraction page created")},onError:c=>re.error(c.message||"Could not create the page")}),o=yt({mutationFn:async c=>{const{error:d}=await iZ.from("attract_landing_pages").update(c).eq("id",r.id);if(d)throw d},onSuccess:()=>{t.invalidateQueries({queryKey:n}),re.success("Saved")},onError:c=>{var d;return re.error((d=c.message)!=null&&d.includes("duplicate")?"That web address is already taken":c.message||"Could not save")}});return{page:r,isLoading:a,analytics:i,createPage:l,savePage:o}}function wmr(){var y,v,b,N,S,A,T,L,M,I,R,z;const{user:s}=vs(),{page:t,isLoading:n,analytics:r,createPage:a,savePage:i}=_mr(),[l,o]=j.useState(null),[c,d]=j.useState(!1);j.useEffect(()=>{t&&o({...t})},[t]);const u=j.useMemo(()=>l!=null&&l.slug?`${window.location.origin}/join/${l.slug}`:"",[l==null?void 0:l.slug]),h=$=>o(H=>({...H,...$})),m=($,H)=>h({[$]:H}),p=($,H,V)=>m($,l[$].map((K,Z)=>Z===H?{...K,...V}:K)),f=()=>{const{id:$,user_id:H,created_at:V,updated_at:K,...Z}=l;i.mutate({...Z,slug:Ors(Z.slug)})};if(n)return e.jsx("div",{className:"p-10 text-center text-muted-foreground",children:"Loading…"});if(!t)return e.jsxs("div",{className:"mx-auto max-w-2xl px-6 py-16 text-center",children:[e.jsx("div",{className:"mx-auto mb-6 flex h-14 w-14 items-center justify-center rounded-2xl bg-primary/10 text-primary",children:e.jsx(cn,{className:"h-7 w-7"})}),e.jsx("h1",{className:"mb-3 text-3xl font-bold tracking-tight",children:"Your Attraction Landing Page"}),e.jsx("p",{className:"mb-8 text-muted-foreground",children:"A public page built to convert agents — value stack, earnings calculator, objection-handling FAQ, and a confidential contact form that drops every lead straight into your Attract pipeline."}),e.jsx(U,{size:"lg",onClick:()=>{var $;return a.mutate((($=s==null?void 0:s.user_metadata)==null?void 0:$.full_name)||"My Attraction Page")},disabled:a.isPending,children:a.isPending?"Creating…":"Create my page"})]});if(!l)return null;if(c)return e.jsxs("div",{children:[e.jsxs("div",{className:"sticky top-0 z-50 flex items-center justify-between border-b bg-background px-4 py-3",children:[e.jsx("span",{className:"text-sm font-medium",children:"Preview"}),e.jsx(U,{variant:"outline",size:"sm",onClick:()=>d(!1),children:"Back to editor"})]}),e.jsx(ras,{cfg:l,preview:!0})]});const x={...Drs,...l.sections||{}};return e.jsxs("div",{className:"mx-auto max-w-5xl px-4 py-8 md:px-6",children:[e.jsxs("div",{className:"mb-6 flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight md:text-3xl",children:"Attraction Landing Page"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Built to convert producing agents into conversations."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>d(!0),children:[e.jsx(xa,{className:"mr-2 h-4 w-4"})," Preview"]}),l.is_published&&e.jsx(U,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:u,target:"_blank",rel:"noreferrer",children:[e.jsx(Sr,{className:"mr-2 h-4 w-4"})," View live"]})}),e.jsxs(U,{size:"sm",onClick:f,disabled:i.isPending,children:[e.jsx(Ho,{className:"mr-2 h-4 w-4"})," ",i.isPending?"Saving…":"Save changes"]})]})]}),e.jsx("div",{className:"mb-6 grid gap-3 sm:grid-cols-4",children:[{label:"Page views",value:(r==null?void 0:r.views)??0},{label:"CTA clicks",value:(r==null?void 0:r.ctas)??0},{label:"Calculator runs",value:(r==null?void 0:r.calcs)??0},{label:"Click rate",value:`${(r==null?void 0:r.conversion)??0}%`}].map($=>e.jsx(we,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:$.label}),e.jsx("div",{className:"mt-1 text-2xl font-bold",children:$.value})]})},$.label))}),e.jsxs(oa,{defaultValue:"content",children:[e.jsxs(la,{className:"mb-6 flex-wrap",children:[e.jsx(Kt,{value:"content",children:"Content"}),e.jsx(Kt,{value:"proof",children:"Proof & FAQ"}),e.jsx(Kt,{value:"calculator",children:"Calculator"}),e.jsx(Kt,{value:"sections",children:"Sections"}),e.jsx(Kt,{value:"publish",children:"Publish"})]}),e.jsxs(Zt,{value:"content",className:"space-y-6",children:[e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Hero"})}),e.jsxs(Ie,{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(jm,{label:"Your name",value:l.agent_name,onChange:$=>h({agent_name:$})}),e.jsx(jm,{label:"Title / brokerage",value:l.agent_title,onChange:$=>h({agent_title:$})}),e.jsx(jm,{label:"Eyebrow line",value:l.eyebrow,onChange:$=>h({eyebrow:$}),className:"md:col-span-2"}),e.jsxs("div",{className:"md:col-span-2 space-y-1.5",children:[e.jsx(te,{children:"Headline"}),e.jsx(Fs,{rows:2,value:l.headline||"",onChange:$=>h({headline:$.target.value})})]}),e.jsxs("div",{className:"md:col-span-2 space-y-1.5",children:[e.jsx(te,{children:"Subheadline"}),e.jsx(Fs,{rows:3,value:l.subheadline||"",onChange:$=>h({subheadline:$.target.value})})]}),e.jsx(jm,{label:"Button text",value:l.cta_label,onChange:$=>h({cta_label:$})}),e.jsx(jm,{label:"Scheduling link (Calendly etc.)",value:l.calendar_url,onChange:$=>h({calendar_url:$})}),e.jsx(jm,{label:"Headshot URL",value:l.headshot_url,onChange:$=>h({headshot_url:$})}),e.jsx(jm,{label:"Hero background image URL",value:l.hero_image_url,onChange:$=>h({hero_image_url:$})}),e.jsx(jm,{label:"Logo URL",value:l.logo_url,onChange:$=>h({logo_url:$})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(jm,{label:"Primary color",type:"color",value:l.primary_color,onChange:$=>h({primary_color:$})}),e.jsx(jm,{label:"Accent color",type:"color",value:l.accent_color,onChange:$=>h({accent_color:$})})]}),e.jsx(jm,{label:"Phone",value:l.phone,onChange:$=>h({phone:$})}),e.jsx(jm,{label:"Email",value:l.email,onChange:$=>h({email:$})})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Credibility strip"})}),e.jsxs(Ie,{className:"space-y-3",children:[(l.credibility||[]).map(($,H)=>e.jsxs(oZ,{onRemove:()=>m("credibility",l.credibility.filter((V,K)=>K!==H)),children:[e.jsx(xe,{placeholder:"Value (e.g. $42M)",value:$.value||"",onChange:V=>p("credibility",H,{value:V.target.value})}),e.jsx(xe,{placeholder:"Label (e.g. Closed volume)",value:$.label||"",onChange:V=>p("credibility",H,{label:V.target.value})})]},H)),e.jsx(lZ,{onClick:()=>m("credibility",[...l.credibility||[],{value:"",label:""}]),label:"Add stat"})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Your story"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx(jm,{label:"Section title",value:l.story_title,onChange:$=>h({story_title:$})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Story"}),e.jsx(Fs,{rows:6,value:l.story_body||"",onChange:$=>h({story_body:$.target.value})})]}),e.jsx(jm,{label:"Story video URL (YouTube, Vimeo, Loom, MP4)",value:l.story_video_url,onChange:$=>h({story_video_url:$})})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Value stack"})}),e.jsxs(Ie,{className:"space-y-4",children:[(l.value_cards||[]).map(($,H)=>e.jsxs(oZ,{vertical:!0,onRemove:()=>m("value_cards",l.value_cards.filter((V,K)=>K!==H)),children:[e.jsx(xe,{placeholder:"Title",value:$.title||"",onChange:V=>p("value_cards",H,{title:V.target.value})}),e.jsx(Fs,{rows:2,placeholder:"Description",value:$.body||"",onChange:V=>p("value_cards",H,{body:V.target.value})}),e.jsx(xe,{placeholder:"Proof point (optional)",value:$.proof||"",onChange:V=>p("value_cards",H,{proof:V.target.value})})]},H)),e.jsx(lZ,{onClick:()=>m("value_cards",[...l.value_cards||[],{title:"",body:""}]),label:"Add value card"})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"What you get from me"})}),e.jsxs(Ie,{className:"space-y-4",children:[(l.sponsor_cards||[]).map(($,H)=>e.jsxs(oZ,{vertical:!0,onRemove:()=>m("sponsor_cards",l.sponsor_cards.filter((V,K)=>K!==H)),children:[e.jsx(xe,{placeholder:"Title",value:$.title||"",onChange:V=>p("sponsor_cards",H,{title:V.target.value})}),e.jsx(Fs,{rows:2,placeholder:"Description",value:$.body||"",onChange:V=>p("sponsor_cards",H,{body:V.target.value})})]},H)),e.jsx(lZ,{onClick:()=>m("sponsor_cards",[...l.sponsor_cards||[],{title:"",body:""}]),label:"Add commitment"})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Free download & upcoming event"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx(jm,{label:"Download title",value:(y=l.lead_magnet)==null?void 0:y.title,onChange:$=>h({lead_magnet:{...l.lead_magnet,title:$}})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Download description"}),e.jsx(Fs,{rows:2,value:((v=l.lead_magnet)==null?void 0:v.body)||"",onChange:$=>h({lead_magnet:{...l.lead_magnet,body:$.target.value}})})]}),e.jsx(jm,{label:"File URL",value:(b=l.lead_magnet)==null?void 0:b.file_url,onChange:$=>h({lead_magnet:{...l.lead_magnet,file_url:$}})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(jm,{label:"Event title",value:(N=l.event_block)==null?void 0:N.title,onChange:$=>h({event_block:{...l.event_block,title:$}})}),e.jsx(jm,{label:"When",value:(S=l.event_block)==null?void 0:S.when,onChange:$=>h({event_block:{...l.event_block,when:$}})}),e.jsx(jm,{label:"Registration link",value:(A=l.event_block)==null?void 0:A.url,onChange:$=>h({event_block:{...l.event_block,url:$}})})]})]})]})]}),e.jsxs(Zt,{value:"proof",className:"space-y-6",children:[e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Testimonials"})}),e.jsxs(Ie,{className:"space-y-4",children:[(l.testimonials||[]).map(($,H)=>e.jsxs(oZ,{vertical:!0,onRemove:()=>m("testimonials",l.testimonials.filter((V,K)=>K!==H)),children:[e.jsx(Fs,{rows:3,placeholder:"Quote",value:$.quote||"",onChange:V=>p("testimonials",H,{quote:V.target.value})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx(xe,{placeholder:"Name",value:$.name||"",onChange:V=>p("testimonials",H,{name:V.target.value})}),e.jsx(xe,{placeholder:"Role / market",value:$.role||"",onChange:V=>p("testimonials",H,{role:V.target.value})}),e.jsx(xe,{placeholder:"Photo URL",value:$.photo_url||"",onChange:V=>p("testimonials",H,{photo_url:V.target.value})})]})]},H)),e.jsx(lZ,{onClick:()=>m("testimonials",[...l.testimonials||[],{quote:"",name:""}]),label:"Add testimonial"})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Objection-handling FAQ"})}),e.jsxs(Ie,{className:"space-y-4",children:[(l.faqs||[]).map(($,H)=>e.jsxs(oZ,{vertical:!0,onRemove:()=>m("faqs",l.faqs.filter((V,K)=>K!==H)),children:[e.jsx(xe,{placeholder:"Question",value:$.q||"",onChange:V=>p("faqs",H,{q:V.target.value})}),e.jsx(Fs,{rows:3,placeholder:"Answer",value:$.a||"",onChange:V=>p("faqs",H,{a:V.target.value})})]},H)),e.jsx(lZ,{onClick:()=>m("faqs",[...l.faqs||[],{q:"",a:""}]),label:"Add question"})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Income disclaimer"})}),e.jsx(Ie,{children:e.jsx(Fs,{rows:4,value:l.disclaimer||"",onChange:$=>h({disclaimer:$.target.value})})})]})]}),e.jsx(Zt,{value:"calculator",children:e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Earnings calculator"})}),e.jsxs(Ie,{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(jm,{label:"Section title",value:(T=l.calculator)==null?void 0:T.title,onChange:$=>h({calculator:{...l.calculator,title:$}}),className:"md:col-span-2"}),e.jsx(jm,{label:"Cap ($)",type:"number",value:(L=l.calculator)==null?void 0:L.cap,onChange:$=>h({calculator:{...l.calculator,cap:Number($)}})}),e.jsx(jm,{label:"Your split (%)",type:"number",value:(M=l.calculator)==null?void 0:M.split,onChange:$=>h({calculator:{...l.calculator,split:Number($)}})}),e.jsx(jm,{label:"Per-transaction fee ($)",type:"number",value:(I=l.calculator)==null?void 0:I.transaction_fee,onChange:$=>h({calculator:{...l.calculator,transaction_fee:Number($)}})}),e.jsx(jm,{label:"Typical competitor split (%)",type:"number",value:(R=l.calculator)==null?void 0:R.current_split,onChange:$=>h({calculator:{...l.calculator,current_split:Number($)}})}),e.jsx(jm,{label:"Typical competitor monthly fees ($)",type:"number",value:(z=l.calculator)==null?void 0:z.current_monthly_fees,onChange:$=>h({calculator:{...l.calculator,current_monthly_fees:Number($)}})}),e.jsx("p",{className:"text-xs text-muted-foreground md:col-span-2",children:"The calculator shows estimates only and always displays your disclaimer at the bottom of the page."})]})]})}),e.jsx(Zt,{value:"sections",children:e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Show or hide sections"})}),e.jsx(Ie,{className:"divide-y",children:Object.keys(J4t).map($=>e.jsxs("div",{className:"flex items-center justify-between py-3",children:[e.jsx("span",{className:"text-sm",children:J4t[$]}),e.jsx(wn,{checked:x[$]!==!1,onCheckedChange:H=>h({sections:{...x,[$]:H}})})]},$))})]})}),e.jsxs(Zt,{value:"publish",className:"space-y-6",children:[e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Publishing"})}),e.jsxs(Ie,{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Page is live"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Turn on to make your page publicly reachable."})]}),e.jsx(wn,{checked:!!l.is_published,onCheckedChange:$=>h({is_published:$})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Hide from search engines"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Recommended — keep this page for direct outreach only."})]}),e.jsx(wn,{checked:!!l.noindex,onCheckedChange:$=>h({noindex:$})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Web address"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:l.slug||"",onChange:$=>h({slug:$.target.value})}),e.jsx(U,{variant:"outline",onClick:()=>{navigator.clipboard.writeText(u),re.success("Link copied")},children:e.jsx(Pa,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u})]}),e.jsx(jm,{label:"Search title",value:l.seo_title,onChange:$=>h({seo_title:$})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Search description"}),e.jsx(Fs,{rows:2,value:l.seo_description||"",onChange:$=>h({seo_description:$.target.value})})]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"flex items-center gap-2 text-base",children:[e.jsx(Cl,{className:"h-4 w-4"})," Where leads go"]})}),e.jsx(Ie,{className:"text-sm text-muted-foreground",children:"Every submission creates or updates a prospect in your Attract pipeline, logs an activity, and emails you a notification. Calculator runs and CTA clicks are tracked so you can see what is working."})]})]})]}),e.jsx("div",{className:"mt-8 flex justify-end",children:e.jsxs(U,{onClick:f,disabled:i.isPending,children:[e.jsx(Ho,{className:"mr-2 h-4 w-4"})," ",i.isPending?"Saving…":"Save changes"]})})]})}function jm({label:s,value:t,onChange:n,type:r="text",className:a}){return e.jsxs("div",{className:`space-y-1.5 ${a||""}`,children:[e.jsx(te,{children:s}),e.jsx(xe,{type:r,value:t??"",onChange:i=>n(i.target.value)})]})}function oZ({children:s,onRemove:t,vertical:n}){return e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border p-3",children:[e.jsx("div",{className:n?"flex-1 space-y-2":"grid flex-1 gap-2 md:grid-cols-2",children:s}),e.jsx(U,{variant:"ghost",size:"icon",onClick:t,className:"text-muted-foreground hover:text-destructive",children:e.jsx(In,{className:"h-4 w-4"})})]})}function lZ({onClick:s,label:t}){return e.jsxs(U,{variant:"outline",size:"sm",onClick:s,children:[e.jsx(an,{className:"mr-2 h-4 w-4"})," ",t]})}function jmr(s){const{user:t}=vs(),n=Qt(),r=ct({queryKey:["admin-attract-list",s,t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{let o=q.from("profiles").select("id, email, full_name").order("full_name",{ascending:!0}).limit(100);if(s.trim()){const m=`%${s.trim()}%`;o=o.or(`email.ilike.${m},full_name.ilike.${m}`)}const{data:c,error:d}=await o;if(d)throw d;const u=(c??[]).map(m=>m.id);let h={};if(u.length){const{data:m,error:p}=await q.from("feature_entitlements").select("user_id, enabled, tier, enabled_at, expires_at, notes, enabled_by").eq("feature_key","levelup_attract").in("user_id",u);if(p)throw p;(m??[]).forEach(f=>{h[f.user_id]=f})}return(c??[]).map(m=>{var p,f,x,y,v,b;return{user_id:m.id,email:m.email,full_name:m.full_name,enabled:!!((p=h[m.id])!=null&&p.enabled),tier:((f=h[m.id])==null?void 0:f.tier)??null,enabled_at:((x=h[m.id])==null?void 0:x.enabled_at)??null,expires_at:((y=h[m.id])==null?void 0:y.expires_at)??null,notes:((v=h[m.id])==null?void 0:v.notes)??null,enabled_by:((b=h[m.id])==null?void 0:b.enabled_by)??null}})}}),a=ct({queryKey:["admin-attract-audit",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:o,error:c}=await q.from("feature_entitlement_audit").select("*").eq("feature_key","levelup_attract").order("created_at",{ascending:!1}).limit(50);if(c)throw c;return o??[]}}),i=yt({mutationFn:async({target_user_id:o,tier:c,expires_at:d,notes:u})=>{const h={user_id:o,feature_key:"levelup_attract",enabled:!0,tier:c??"beta",enabled_by:t.id,enabled_at:new Date().toISOString(),expires_at:d??null,notes:u??null},{error:m}=await q.from("feature_entitlements").upsert(h,{onConflict:"user_id,feature_key"});if(m)throw m;await q.from("feature_entitlement_audit").insert({feature_key:"levelup_attract",target_user_id:o,action:"grant",tier:h.tier,expires_at:h.expires_at,notes:h.notes,performed_by:t.id})},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-attract-list"]}),n.invalidateQueries({queryKey:["admin-attract-audit"]}),re.success("Access granted")},onError:o=>re.error(o.message)}),l=yt({mutationFn:async o=>{const{error:c}=await q.from("feature_entitlements").update({enabled:!1}).eq("user_id",o).eq("feature_key","levelup_attract");if(c)throw c;await q.from("feature_entitlement_audit").insert({feature_key:"levelup_attract",target_user_id:o,action:"revoke",performed_by:t.id})},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-attract-list"]}),n.invalidateQueries({queryKey:["admin-attract-audit"]}),re.success("Access revoked")},onError:o=>re.error(o.message)});return{list:r,audit:a,grant:i,revoke:l}}function Nmr(){const[s,t]=j.useState(""),{list:n,audit:r,grant:a,revoke:i}=jmr(s),[l,o]=j.useState(null),[c,d]=j.useState(null),[u,h]=j.useState("beta"),[m,p]=j.useState(""),[f,x]=j.useState(""),y=b=>{d(b),h(b.tier??"beta"),p(b.expires_at?b.expires_at.slice(0,10):""),x(b.notes??"")},v=async()=>{c&&(await a.mutateAsync({target_user_id:c.user_id,tier:u,expires_at:m?new Date(m).toISOString():null,notes:f||void 0}),d(null))};return e.jsxs("div",{className:"p-6",children:[e.jsx(Xh,{title:"LevelUp Attract — Access Management",description:"Grant or revoke access to LevelUp Attract for individual members. Every change is audited."}),e.jsx(we,{className:"p-4 rounded-2xl mb-4",children:e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(xe,{value:s,onChange:b=>t(b.target.value),placeholder:"Search by name or email...",className:"pl-9"})]})}),e.jsxs(we,{className:"rounded-2xl overflow-hidden mb-8",children:[e.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto_auto] gap-3 px-5 py-3 text-[11px] uppercase tracking-widest text-slate-500 font-semibold border-b",children:[e.jsx("div",{children:"Member"}),e.jsx("div",{children:"Access"}),e.jsx("div",{children:"Enabled"}),e.jsx("div",{children:"Actions"})]}),n.isLoading&&e.jsx("div",{className:"p-6 text-center text-slate-500 text-sm",children:"Loading members…"}),!n.isLoading&&(n.data??[]).length===0&&e.jsx("div",{className:"p-6 text-center text-slate-500 text-sm",children:"No members match."}),(n.data??[]).map(b=>e.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto_auto] gap-3 px-5 py-3 items-center border-b last:border-0 hover:bg-slate-50",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900 truncate",children:b.full_name||b.email||b.user_id}),e.jsx("div",{className:"text-[11.5px] text-slate-500 truncate",children:b.email})]}),e.jsx("div",{children:b.enabled?e.jsxs(Be,{className:"bg-emerald-100 text-emerald-800 border-0 gap-1",children:[e.jsx(cn,{className:"h-3 w-3"})," ",b.tier??"enabled"]}):e.jsx(Be,{variant:"outline",className:"text-slate-500",children:"Not enabled"})}),e.jsx("div",{className:"text-[11.5px] text-slate-500 whitespace-nowrap",children:b.enabled_at?Gs(new Date(b.enabled_at),"MMM d, yyyy"):"—"}),e.jsx("div",{className:"flex gap-1.5",children:b.enabled?e.jsxs(e.Fragment,{children:[e.jsx(U,{size:"sm",variant:"outline",onClick:()=>y(b),children:"Edit"}),e.jsx(U,{size:"sm",variant:"ghost",className:"text-rose-600",onClick:()=>o({user:b,action:"revoke"}),children:"Revoke"})]}):e.jsxs(U,{size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>y(b),children:[e.jsx(cg,{className:"h-3.5 w-3.5 mr-1"})," Enable"]})})]},b.user_id))]}),e.jsxs(we,{className:"rounded-2xl p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3 text-[12px] uppercase tracking-widest text-slate-500 font-semibold",children:[e.jsx(Y2,{className:"h-3.5 w-3.5"})," Recent audit history"]}),r.isLoading&&e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading…"}),(r.data??[]).length===0&&!r.isLoading&&e.jsx("div",{className:"text-slate-500 text-sm",children:"No changes yet."}),e.jsx("div",{className:"space-y-1.5",children:(r.data??[]).map(b=>e.jsxs("div",{className:"text-[12.5px] text-slate-700 flex items-center gap-2",children:[e.jsx(Be,{variant:"outline",className:"text-[10.5px] capitalize",children:b.action}),e.jsx("span",{className:"font-mono text-[11px] text-slate-500",children:b.target_user_id.slice(0,8)}),b.tier&&e.jsxs("span",{className:"text-slate-500",children:["· ",b.tier]}),b.notes&&e.jsxs("span",{className:"text-slate-500",children:["· ",b.notes]}),e.jsx("span",{className:"text-slate-400 ml-auto",children:Gs(new Date(b.created_at),"MMM d h:mm a")})]},b.id))})]}),e.jsx(zs,{open:!!c,onOpenChange:b=>!b&&d(null),children:e.jsxs(Ds,{children:[e.jsxs(Vs,{children:[e.jsxs($s,{children:[c!=null&&c.enabled?"Update":"Enable"," Attract access"]}),e.jsx(Pr,{children:(c==null?void 0:c.full_name)||(c==null?void 0:c.email)})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Tier"}),e.jsxs(Ns,{value:u,onValueChange:h,children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"beta",children:"Beta"}),e.jsx(et,{value:"standard",children:"Standard"}),e.jsx(et,{value:"pro",children:"Pro"}),e.jsx(et,{value:"founder",children:"Founder"})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Expires (optional)"}),e.jsx(xe,{type:"date",value:m,onChange:b=>p(b.target.value)})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Internal notes (optional)"}),e.jsx(Fs,{rows:2,value:f,onChange:b=>x(b.target.value)})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"ghost",onClick:()=>d(null),children:"Cancel"}),e.jsx(U,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:v,disabled:a.isPending,children:c!=null&&c.enabled?"Save changes":"Enable access"})]})]})}),e.jsx(Fl,{open:!!l,onOpenChange:b=>!b&&o(null),children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Revoke Attract access?"}),e.jsxs(Ll,{children:[(l==null?void 0:l.user.full_name)||(l==null?void 0:l.user.email)," will lose access to LevelUp Attract immediately. Their data is preserved and access can be re-enabled."]})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsxs(_l,{className:"bg-rose-600 hover:bg-rose-700",onClick:async()=>{l&&await i.mutateAsync(l.user.user_id),o(null)},children:[e.jsx(ou,{className:"h-4 w-4 mr-1.5"})," Revoke access"]})]})]})})]})}const kmr=({team:s,onSelect:t})=>{const{data:n}=ct({queryKey:["team-card-info",s.id],queryFn:async()=>{const{data:r}=await q.from("team_members").select("user_id, role").eq("team_id",s.id),a=(r==null?void 0:r.length)||0,i=r==null?void 0:r.find(o=>o.role==="team_leader");let l=null;if(i){const{data:o}=await q.from("profiles").select("name, avatar_url").eq("id",i.user_id).single();l=o}return{count:a,leaderProfile:l}}});return e.jsxs(we,{className:"cursor-pointer hover:shadow-md transition-shadow group",onClick:t,children:[e.jsx(Tt,{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(It,{className:"text-lg truncate",children:s.name}),s.description&&e.jsx(Jn,{className:"mt-1 line-clamp-2",children:s.description})]}),e.jsxs(Be,{variant:"secondary",className:"ml-2 shrink-0",children:[e.jsx(Bn,{className:"h-3 w-3 mr-1"}),(n==null?void 0:n.count)??"…"]})]})}),e.jsxs(Ie,{className:"space-y-3",children:[(n==null?void 0:n.leaderProfile)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ea,{className:"h-6 w-6",children:[e.jsx(Ci,{src:n.leaderProfile.avatar_url||""}),e.jsx(Ta,{className:"text-xs",children:(n.leaderProfile.name||"?").charAt(0).toUpperCase()})]}),e.jsxs("span",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(h0,{className:"h-3 w-3 text-[hsl(var(--chart-4))]"}),n.leaderProfile.name||"Team Leader"]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Im,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"capitalize text-xs",children:s.contact_visibility.replace("_"," ")})]}),s.lead_pond_enabled&&e.jsx(Be,{variant:"outline",className:"text-xs py-0",children:"Lead Pond"}),s.shared_assets_enabled&&e.jsx(Be,{variant:"outline",className:"text-xs py-0",children:"Shared Assets"}),s.shared_videos_enabled&&e.jsx(Be,{variant:"outline",className:"text-xs py-0",children:"Shared Videos"})]})]})]})},Smr=()=>{const{user:s,isAdmin:t,isBrokerageManager:n,brokerageId:r,managedBrokerages:a,selectedBrokerageId:i}=vs(),l=i||(a.length>0?a[0].id:r),o=t?void 0:l||void 0,{teams:c,isLoading:d,createTeam:u,updateTeam:h,deleteTeam:m,addMember:p,removeMember:f,updateMemberRole:x}=_E(o),[y,v]=j.useState(!1),[b,N]=j.useState(null),{data:S}=ct({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:I,error:R}=await q.from("brokerages").select("id, name").order("name");if(R)throw R;return I||[]},enabled:t}),A=(b==null?void 0:b.brokerage_id)||l||null,{data:T}=ct({queryKey:["brokerage-agents-for-teams",t?"all":A],queryFn:async()=>{const I=[];for(let z=0;;z++){let $=q.from("profiles").select("id, name, email, avatar_url, brokerage_id").order("name").range(z*1e3,z*1e3+1e3-1);!t&&A&&($=$.eq("brokerage_id",A));const{data:H,error:V}=await $;if(V)throw V;if(I.push(...H||[]),!H||H.length<1e3)break}return I},enabled:t||!!A}),L=(T||[]).slice().sort((I,R)=>{const z=A&&I.brokerage_id===A?0:1,$=A&&R.brokerage_id===A?0:1;return z!==$?z-$:(I.name||I.email||"").localeCompare(R.name||R.email||"")}),M=async I=>{const R=I.brokerage_id||l||null,z=await u.mutateAsync({name:I.name,brokerage_id:R,description:I.description});if(I.leaderId&&I.leaderId!=="none"&&await p.mutateAsync({team_id:z.id,user_id:I.leaderId,role:"team_leader"}),I.memberIds)for(const $ of I.memberIds)await p.mutateAsync({team_id:z.id,user_id:$,role:"team_member"});v(!1)};return!n&&!t?e.jsx(qs,{title:"Teams",description:"Team Management",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Bn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Access Denied"}),e.jsx("p",{className:"text-muted-foreground",children:"You need brokerage manager access to manage teams."})]})}):e.jsx(qs,{title:"Teams",description:"Create and manage teams within your brokerage",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Teams"}),e.jsx("p",{className:"text-muted-foreground",children:"Organize your agents into teams with leaders and shared resources."})]}),e.jsxs(U,{onClick:()=>v(!0),children:[e.jsx(an,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(dqt,{open:y,onOpenChange:v,onCreateTeam:M,isCreating:u.isPending,brokerageAgents:L,isAdmin:t,allBrokerages:S,activeBrokerageId:l}),d&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(I=>e.jsx(we,{children:e.jsxs(Ie,{className:"p-6",children:[e.jsx(xn,{className:"h-5 w-32 mb-3"}),e.jsx(xn,{className:"h-4 w-48 mb-4"}),e.jsx(xn,{className:"h-8 w-full"})]})},I))}),!d&&c.length===0&&!b&&e.jsx(we,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Bn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Teams Yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Create your first team to organize agents and share resources."}),e.jsxs(U,{onClick:()=>v(!0),children:[e.jsx(an,{className:"mr-2 h-4 w-4"}),"Create Your First Team"]})]})}),!d&&c.length>0&&!b&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:c.map(I=>e.jsx(kmr,{team:I,onSelect:()=>N(I)},I.id))}),b&&e.jsx(cqt,{team:b,brokerageAgents:L,onBack:()=>N(null),onUpdate:I=>h.mutateAsync({id:b.id,...I}).then(R=>N(R)),onAddMember:(I,R)=>p.mutateAsync({team_id:b.id,user_id:I,role:R}),onRemoveMember:I=>f.mutateAsync({team_id:b.id,member_id:I}),onUpdateRole:(I,R)=>x.mutateAsync({team_id:b.id,member_id:I,role:R}),onDeleteTeam:()=>m.mutate(b.id),isUpdating:h.isPending,isAddingMember:p.isPending})]})})},Cmr=({team:s})=>{const{updateTeam:t}=_E(),n=r=>t.mutate({id:s.id,...r});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-lg",children:"Team Settings"}),e.jsx(Jn,{children:"Control how your team shares contacts, leads, and assets."})]}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Contact Visibility"}),e.jsxs(Ns,{defaultValue:s.contact_visibility,onValueChange:r=>n({contact_visibility:r}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"private",children:"Private — Members keep their contacts private"}),e.jsx(et,{value:"leader_only",children:"Leader Only — Only team leaders can see member contacts"}),e.jsx(et,{value:"full_team",children:"Full Team — All team members can see shared contacts"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Lead Pond"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shared lead pool — anyone on the team can contribute leads and claim them."})]}),e.jsx(wn,{checked:s.lead_pond_enabled,onCheckedChange:r=>n({lead_pond_enabled:r})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(te,{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(wn,{checked:s.shared_assets_enabled,onCheckedChange:r=>n({shared_assets_enabled:r})})]})]})]}),s.lead_pond_enabled&&e.jsx(aqt,{teamId:s.id})]})},Amr=()=>{const{data:s,isLoading:t,teams:n,activeTeamId:r,setActiveTeamId:a}=Sj(),{useTeamMembers:i}=_E(),{data:l=[],isLoading:o}=i((s==null?void 0:s.teamId)||"");if(t)return e.jsx(qs,{title:"My Team",description:"Your team",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(xn,{className:"h-8 w-48"}),e.jsx(xn,{className:"h-40 w-full"})]})});if(!s)return e.jsx(qs,{title:"My Team",description:"Your team",children:e.jsx(we,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Bn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No Team Yet"}),e.jsx("p",{className:"text-muted-foreground",children:"You haven't been assigned to a team. Ask your brokerage manager to add you."})]})})});const c=s.team;return e.jsx(qs,{title:"My Team",description:c.name,children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[n.length>1&&e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:n.map(d=>{var u;return e.jsxs("button",{onClick:()=>a(d.teamId),className:"rounded-full border px-3 py-1 text-sm transition-colors "+(d.teamId===r?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground hover:bg-muted"),children:[(u=d.team)==null?void 0:u.name,d.role==="team_leader"&&e.jsx(h0,{className:"ml-1 inline h-3 w-3"})]},d.teamId)})}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:c.name}),e.jsx(Be,{variant:s.role==="team_leader"?"default":"secondary",className:"capitalize",children:s.role==="team_leader"?e.jsxs(e.Fragment,{children:[e.jsx(h0,{className:"mr-1 h-3 w-3"})," Leader"]}):"Member"})]}),c.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:c.description})]}),e.jsxs(oa,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(la,{className:"flex-wrap",children:[e.jsx(Kt,{value:"members",children:"Members"}),c.contact_visibility!=="private"&&e.jsxs(Kt,{value:"contacts",children:[e.jsx(SF,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),c.lead_pond_enabled&&e.jsxs(Kt,{value:"lead-pond",children:[e.jsx(cb,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),c.shared_assets_enabled&&e.jsxs(Kt,{value:"shared-assets",children:[e.jsx(r1,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),s.role==="team_leader"&&e.jsxs(Kt,{value:"settings",children:[e.jsx(qc,{className:"mr-1 h-3.5 w-3.5"}),"Settings"]})]}),e.jsx(Zt,{value:"members",className:"space-y-2",children:o?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(d=>e.jsx(xn,{className:"h-16 w-full"},d))}):l.map(d=>{var u,h,m,p;return e.jsx(we,{children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsxs(Ea,{className:"h-10 w-10",children:[e.jsx(Ci,{src:((u=d.profile)==null?void 0:u.avatar_url)||""}),e.jsx(Ta,{children:(((h=d.profile)==null?void 0:h.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium",children:((m=d.profile)==null?void 0:m.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(p=d.profile)==null?void 0:p.email})]}),d.role==="team_leader"?e.jsxs(Be,{className:"ml-auto bg-amber-500/10 text-amber-600 border-amber-500",children:[e.jsx(h0,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(Be,{variant:"secondary",className:"ml-auto",children:"Member"})]})},d.id)})}),c.contact_visibility!=="private"&&e.jsx(Zt,{value:"contacts",className:"space-y-4",children:e.jsx(yet,{})}),c.lead_pond_enabled&&e.jsx(Zt,{value:"lead-pond",className:"space-y-4",children:e.jsx(vet,{teamId:s.teamId})}),c.shared_assets_enabled&&e.jsx(Zt,{value:"shared-assets",className:"space-y-4",children:e.jsx(lqt,{teamId:s.teamId})}),s.role==="team_leader"&&e.jsx(Zt,{value:"settings",className:"space-y-4",children:e.jsx(Cmr,{team:c})})]},s.teamId)]})})},C3t={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"};function Emr({types:s,onSave:t,onDelete:n}){const[r,a]=j.useState(null),[i,l]=j.useState(!1),o=()=>{a({name:"",description:"",duration_minutes:30,color:"#3B82F6",icon:"Calendar",is_active:!0,qualification_enabled:!1,is_coaching_only:!1}),l(!0)},c=u=>{a({...u}),l(!0)},d=()=>{r!=null&&r.name&&(t(r),l(!1),a(null))};return e.jsxs(e.Fragment,{children:[e.jsxs(we,{children:[e.jsxs(Tt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{children:"Booking Types"}),e.jsx(Jn,{children:"The meeting types prospects can book with you"})]}),e.jsxs(U,{onClick:o,size:"sm",children:[e.jsx(an,{className:"h-4 w-4 mr-1"})," Add Type"]})]}),e.jsx(Ie,{children:s.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No booking types yet. Add one to get started."}):e.jsx("div",{className:"grid gap-3",children:s.map(u=>e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center text-lg",style:{backgroundColor:u.color+"20"},children:C3t[u.icon]||"📅"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:u.name}),!u.is_active&&e.jsx(Be,{variant:"secondary",className:"text-xs",children:"Inactive"}),u.is_coaching_only&&e.jsx(Be,{variant:"outline",className:"text-xs",children:"Coaching only"}),u.qualification_enabled&&e.jsxs(Be,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(ZX,{className:"h-3 w-3"})," Qualifying"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Yr,{className:"h-3 w-3"}),u.duration_minutes," min",u.description&&e.jsxs("span",{children:["· ",u.description.slice(0,60),u.description.length>60?"...":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>c(u),children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>n(u.id),className:"text-destructive hover:text-destructive",children:e.jsx(In,{className:"h-4 w-4"})})]})]},u.id))})})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsxs($s,{children:[r!=null&&r.id?"Edit":"New"," Booking Type"]})}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Name"}),e.jsx(xe,{value:r.name||"",onChange:u=>a({...r,name:u.target.value}),placeholder:"e.g. Listing Consultation"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Description"}),e.jsx(Fs,{value:r.description||"",onChange:u=>a({...r,description:u.target.value}),placeholder:"Brief description for prospects",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Duration (minutes)"}),e.jsx(xe,{type:"number",min:15,max:180,step:15,value:r.duration_minutes||30,onChange:u=>a({...r,duration_minutes:parseInt(u.target.value)||30})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:r.color||"#3B82F6",onChange:u=>a({...r,color:u.target.value}),className:"h-10 w-10 rounded border cursor-pointer"}),e.jsx(xe,{value:r.color||"#3B82F6",onChange:u=>a({...r,color:u.target.value}),className:"flex-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Max bookings per day"}),e.jsx(xe,{type:"number",min:0,max:50,value:r.max_per_day??"",onChange:u=>a({...r,max_per_day:u.target.value===""?null:parseInt(u.target.value)||0}),placeholder:"Unlimited"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank for unlimited. Once this many are booked on a day, the day closes."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Icon"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(C3t).map(([u,h])=>e.jsx("button",{onClick:()=>a({...r,icon:u}),className:`w-10 h-10 rounded-lg text-lg flex items-center justify-center border transition-colors ${r.icon===u?"border-primary bg-primary/10":"hover:bg-muted"}`,children:h},u))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Meeting Link Override (optional)"}),e.jsx(xe,{value:r.meeting_link_override||"",onChange:u=>a({...r,meeting_link_override:u.target.value||null}),placeholder:"Use a different link for this type"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Virtual meeting (auto Google Meet)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Creates a Google Meet link on the event and emails it to the guest. Requires your Google Calendar connection."})]}),e.jsx(wn,{checked:r.create_google_meet||!1,onCheckedChange:u=>a({...r,create_google_meet:u})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Pre-Qualification Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ask qualifying questions before booking"})]}),e.jsx(wn,{checked:r.qualification_enabled||!1,onCheckedChange:u=>a({...r,qualification_enabled:u})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Coaching sessions only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Hidden from your public booking page — only your coaching agents can book it"})]}),e.jsx(wn,{checked:r.is_coaching_only||!1,onCheckedChange:u=>a({...r,is_coaching_only:u})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{children:"Active"}),e.jsx(wn,{checked:r.is_active??!0,onCheckedChange:u=>a({...r,is_active:u})})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(U,{onClick:d,children:"Save"})]})]})})]})}const Tmr={confirmed:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400",cancelled:"bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400",completed:"bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400",no_show:"bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400"};function Mmr({bookings:s,onCancel:t}){const n=s.filter(i=>i.status==="confirmed"&&new Date(i.booking_date)>=new Date(new Date().toDateString())),r=s.filter(i=>i.status!=="confirmed"||new Date(i.booking_date){var o,c;return e.jsxs("div",{className:"flex items-start justify-between p-4 rounded-lg border hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(So,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:i.guest_name}),e.jsx(Be,{className:`text-xs ${Tmr[i.status]||""}`,children:i.status})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(nc,{className:"h-3.5 w-3.5"}),Gs(new Date(i.booking_date+"T00:00:00"),"MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yr,{className:"h-3.5 w-3.5"}),(o=i.start_time)==null?void 0:o.slice(0,5)," - ",(c=i.end_time)==null?void 0:c.slice(0,5)]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-sm text-muted-foreground",children:[i.guest_email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ln,{className:"h-3 w-3"}),i.guest_email]}),i.guest_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ba,{className:"h-3 w-3"}),i.guest_phone]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1",children:[i.booking_type&&e.jsx(Be,{variant:"outline",className:"text-xs",children:i.booking_type.name}),i.google_sync_status==="synced"&&e.jsxs(Be,{variant:"outline",className:"text-xs gap-1 text-emerald-700 border-emerald-300 dark:text-emerald-400",children:[e.jsx(cv,{className:"h-3 w-3"})," On Google Calendar"]}),i.google_sync_status==="failed"&&e.jsxs(Be,{variant:"outline",className:"text-xs gap-1 text-amber-700 border-amber-300 dark:text-amber-400",children:[e.jsx(GU,{className:"h-3 w-3"})," Not synced to Google"]})]}),i.guest_message&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1 italic",children:['"',i.guest_message,'"']})]}),l&&i.status==="confirmed"&&e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>t(i.id),className:"text-destructive hover:text-destructive",children:[e.jsx(ou,{className:"h-4 w-4 mr-1"})," Cancel"]})]},i.id)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"Upcoming Bookings"}),e.jsxs(Jn,{children:[n.length," upcoming appointment",n.length!==1?"s":""]})]}),e.jsx(Ie,{children:n.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No upcoming bookings"}):e.jsx("div",{className:"space-y-3",children:n.map(i=>a(i,!0))})})]}),r.length>0&&e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{children:"Past & Cancelled"})}),e.jsx(Ie,{children:e.jsx("div",{className:"space-y-3",children:r.slice(0,20).map(i=>a(i))})})]})]})}function Pmr(){const{settings:s,bookingTypes:t,availability:n,blockedDates:r,bookings:a,isLoading:i,initializeSettings:l,updateSettings:o,upsertBookingType:c,deleteBookingType:d,upsertAvailability:u,deleteAvailability:h,addBlockedDate:m,removeBlockedDate:p,cancelBooking:f}=WOt(),[x,y]=j.useState("");j.useState(15),x||s!=null&&s.meeting_link;const v=s!=null&&s.slug?`https://booking.relevelup.com/${s.slug}`:null;return i?e.jsx(qs,{children:e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):s?e.jsx(qs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(nc,{className:"h-6 w-6 text-primary"}),"LevelUp Scheduler"]}),e.jsx("p",{className:"text-muted-foreground",children:"Manage your booking types, availability, and appointments"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[v&&e.jsxs(e.Fragment,{children:[e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>{navigator.clipboard.writeText(v),re.success("Booking link copied!")},children:[e.jsx(Pa,{className:"h-4 w-4 mr-1"})," Copy Link"]}),e.jsx(U,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:v,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Sr,{className:"h-4 w-4 mr-1"})," Preview"]})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(te,{htmlFor:"scheduler-active",className:"text-sm",children:"Active"}),e.jsx(wn,{id:"scheduler-active",checked:s.is_active,onCheckedChange:b=>o.mutate({is_active:b})})]})]})]}),e.jsxs(oa,{defaultValue:"types",className:"space-y-4",children:[e.jsxs(la,{children:[e.jsx(Kt,{value:"types",children:"Booking Types"}),e.jsx(Kt,{value:"availability",children:"Availability"}),e.jsx(Kt,{value:"settings",children:"Settings"}),e.jsxs(Kt,{value:"bookings",children:["Bookings",a.filter(b=>b.status==="confirmed").length>0&&e.jsx(Be,{variant:"secondary",className:"ml-1.5 text-xs",children:a.filter(b=>b.status==="confirmed").length})]})]}),e.jsx(Zt,{value:"types",children:e.jsx(Emr,{types:t,onSave:b=>c.mutate(b),onDelete:b=>d.mutate(b)})}),e.jsx(Zt,{value:"availability",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(KOt,{slots:n,onSave:b=>u.mutate(b),onDelete:b=>h.mutate(b)}),e.jsx(YOt,{blockedDates:r,onAdd:b=>m.mutate(b),onRemove:b=>p.mutate(b)})]})}),e.jsxs(Zt,{value:"settings",className:"space-y-6",children:[e.jsx(XOt,{scope:"agent"}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsxs(It,{className:"flex items-center gap-2",children:[e.jsx(R4,{className:"h-5 w-5"}),"General Settings"]}),e.jsx(Jn,{children:"Configure your booking page defaults"})]}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Booking Page URL"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{value:s.slug,readOnly:!0,className:"bg-muted"}),e.jsx(U,{variant:"outline",size:"sm",onClick:()=>{v&&(navigator.clipboard.writeText(v),re.success("Copied!"))},children:e.jsx(Pa,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(te,{htmlFor:"meeting-link",children:[e.jsx(ad,{className:"h-4 w-4 inline mr-1"}),"Default Meeting Link"]}),e.jsx(xe,{id:"meeting-link",placeholder:"https://zoom.us/j/your-personal-link",defaultValue:s.meeting_link||"",onBlur:b=>o.mutate({meeting_link:b.target.value||null})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your Zoom personal link, Google Meet, or phone number"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Buffer Between Meetings"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"number",min:0,max:60,defaultValue:s.buffer_minutes,onBlur:b=>o.mutate({buffer_minutes:parseInt(b.target.value)||15})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"min"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Minimum Notice"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"number",min:0,max:72,defaultValue:s.min_notice_hours,onBlur:b=>o.mutate({min_notice_hours:parseInt(b.target.value)||2})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"hours"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(te,{children:"Max Advance Booking"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe,{type:"number",min:1,max:90,defaultValue:s.max_advance_days,onBlur:b=>o.mutate({max_advance_days:parseInt(b.target.value)||30})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"days"})]})]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsx(te,{className:"text-sm font-semibold",children:"Guest Reminders"}),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:"Email reminders"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sends 24 hours and 1 hour before the meeting, with reschedule and cancel links."})]}),e.jsx(wn,{checked:s.reminders_enabled!==!1,onCheckedChange:b=>o.mutate({reminders_enabled:b})})]}),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:"Text message reminders"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Texts guests who left a phone number. Standard opt-out language is included."})]}),e.jsx(wn,{checked:!!s.sms_reminders_enabled,onCheckedChange:b=>o.mutate({sms_reminders_enabled:b})})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[e.jsx(te,{className:"text-sm font-semibold",children:"Embed on your website"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste this snippet anywhere on your site to show your booking page inline."}),e.jsx("pre",{className:"text-[11px] bg-muted rounded-lg p-3 overflow-x-auto whitespace-pre-wrap",children:``}),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>{navigator.clipboard.writeText(``),re.success("Embed code copied")},children:[e.jsx(Pa,{className:"h-4 w-4 mr-1.5"})," Copy embed code"]})]})]})]})]}),e.jsx(Zt,{value:"bookings",children:e.jsx(Mmr,{bookings:a,onCancel:b=>f.mutate({id:b})})})]})]})}):e.jsx(qs,{children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 md:p-8 space-y-8",children:[e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-16 h-16 bg-primary/10 rounded-2xl flex items-center justify-center",children:e.jsx(nc,{className:"h-8 w-8 text-primary"})}),e.jsx("h1",{className:"text-3xl font-bold",children:"LevelUp Scheduler"}),e.jsx("p",{className:"text-muted-foreground text-lg max-w-md mx-auto",children:"Your own booking page — built for real estate. Prospects book with you, get auto-added to your CRM, and you never miss a lead."})]}),e.jsx(we,{children:e.jsxs(Ie,{className:"pt-6 space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[{icon:"🏠",title:"Listing Consultation",desc:"60 min"},{icon:"🔍",title:"Buyer Consultation",desc:"45 min"},{icon:"💰",title:"Home Valuation",desc:"30 min"},{icon:"☕",title:"General Meeting",desc:"30 min"}].map(b=>e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-muted/30",children:[e.jsx("span",{className:"text-2xl",children:b.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:b.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b.desc})]})]},b.title))}),e.jsx(hc,{}),e.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsx("p",{children:"✅ Auto-creates CRM contacts from every booking"}),e.jsx("p",{children:"✅ Optional pre-qualification questions per booking type"}),e.jsx("p",{children:"✅ Embeds on your Smart Card — replaces TidyCal"}),e.jsx("p",{children:"✅ Standalone shareable booking page"})]}),e.jsxs(U,{onClick:()=>l.mutate(),disabled:l.isPending,className:"w-full",size:"lg",children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),l.isPending?"Setting up...":"Activate Scheduler"]})]})})]})})}function Lmr(s,t,n=!0){return ct({queryKey:["my-calendar",s,t],enabled:n&&!!s&&!!t,staleTime:6e4,queryFn:async()=>{const{data:r,error:a}=await q.functions.invoke("my-calendar",{body:{start:s,end: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}})}async function pBe(s){const{data:t,error:n}=await q.functions.invoke("agent-appointments",{body:s});if(n){let r=n.message;try{const a=n.context;if(a!=null&&a.json){const i=await a.json();i!=null&&i.error&&(r=i.error)}}catch{}throw new Error(r)}if(t!=null&&t.error)throw new Error(t.error);return t}function Imr(){const s=Qt(),t=()=>{s.invalidateQueries({queryKey:["my-calendar"]}),s.invalidateQueries({queryKey:["agent-appointments"]})},n=yt({mutationFn:async i=>pBe({action:i.id?"update":"create",...i}),onSuccess:t}),r=yt({mutationFn:async i=>pBe({action:"cancel",id:i}),onSuccess:t});return{save:n,remove:r,checkConflicts:async(i,l,o)=>pBe({action:"check_conflicts",start_at:i,end_at:l,id:o})}}function A3t(s,t){const[n,r,a]=s.split("-").map(Number),[i,l]=t.split(":").map(Number),o=Date.UTC(n,(r||1)-1,a||1,i||0,l||0);let c=o;for(let d=0;d<2;d++){const u=new Intl.DateTimeFormat("en-US",{timeZone:XP(),year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(new Date(c)),h=p=>{var f;return Number((f=u.find(x=>x.type===p))==null?void 0:f.value)},m=Date.UTC(h("year"),h("month")-1,h("day"),h("hour")%24,h("minute"),h("second"));c+=o-m}return new Date(c).toISOString()}function fBe(s){const t=new Intl.DateTimeFormat("en-CA",{timeZone:XP(),year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(new Date(s)),n=r=>{var a;return((a=t.find(i=>i.type===r))==null?void 0:a.value)??"00"};return{date:`${n("year")}-${n("month")}-${n("day")}`,time:`${n("hour")==="24"?"00":n("hour")}:${n("minute")}`}}const Rmr=[{id:"google_meet",label:"Google Meet",icon:Wr},{id:"in_person",label:"In person",icon:ni},{id:"phone",label:"Phone",icon:ba}];function Dmr({open:s,onOpenChange:t,defaultDate:n,defaultTime:r,defaultContactId:a,defaultDealId:i,appointment:l,googleConnected:o,onSaved:c}){const{save:d,remove:u,checkConflicts:h}=Imr(),m=!!(l!=null&&l.id),[p,f]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState("09:00"),[N,S]=j.useState("09:30"),[A,T]=j.useState("in_person"),[L,M]=j.useState(""),[I,R]=j.useState(""),[z,$]=j.useState([]),[H,V]=j.useState(""),[K,Z]=j.useState(!1);j.useEffect(()=>{if(s){if(l){const je=fBe(l.start_at),be=fBe(l.end_at);f(l.title),y(je.date),b(je.time),S(be.time),T(l.meeting_mode),M(l.location||""),R(l.notes||""),$((l.agent_appointment_contacts||[]).map(he=>he.contact_id))}else{f(""),y(n||fBe(new Date().toISOString()).date);const je=r||"09:00",[be,he]=je.split(":").map(Number),ge=be*60+he+30;b(je),S(`${`${Math.floor(ge/60)%24}`.padStart(2,"0")}:${`${ge%60}`.padStart(2,"0")}`),T(o?"google_meet":"in_person"),M(""),R(""),$(a?[a]:[])}V(""),Z(!1)}},[s,l,n,r,a,o]),j.useEffect(()=>{if(N<=v){const[je,be]=v.split(":").map(Number),he=new Date(0,0,0,je,be+30);S(`${String(he.getHours()).padStart(2,"0")}:${String(he.getMinutes()).padStart(2,"0")}`)}},[v]);const Q=j.useMemo(()=>x?A3t(x,v):"",[x,v]),le=j.useMemo(()=>x?A3t(x,N):"",[x,N]);j.useEffect(()=>{if(!s||!o||!Q||!le)return;let je=!1;const be=setTimeout(async()=>{try{const he=await h(Q,le,l==null?void 0:l.id);je||Z(!!he.conflicts.length)}catch{}},500);return()=>{je=!0,clearTimeout(be)}},[s,o,Q,le]);const{data:ue=[]}=ct({queryKey:["appointment-contact-search",H],enabled:s,queryFn:async()=>{let je=q.from("innercircle_contacts").select("id, first_name, last_name, email").not("email","is",null).neq("email","").like("email","%@%").order("first_name").limit(20);if(H.trim()){const ge=`%${H.trim()}%`;je=je.or(`first_name.ilike.${ge},last_name.ilike.${ge},email.ilike.${ge}`)}const{data:be,error:he}=await je;if(he)throw he;return(be||[]).filter(ge=>!!ge.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ge.email.trim()))}}),{data:se=[]}=ct({queryKey:["appointment-selected-contacts",z],enabled:s&&z.length>0,queryFn:async()=>{const{data:je}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").in("id",z);return je||[]}}),ne=je=>[je.first_name,je.last_name].filter(Boolean).join(" ")||je.email||"Contact",ie=async()=>{if(!p.trim())return re.error("Give the appointment a title");if(!x)return re.error("Pick a date");try{await d.mutateAsync({id:l==null?void 0:l.id,title:p.trim(),start_at:Q,end_at:le,meeting_mode:A,location:A==="google_meet"?null:L||null,notes:I||null,deal_id:i??(l==null?void 0:l.deal_id)??null,contact_ids:z}),re.success(m?"Appointment updated":"Appointment created"),c==null||c(),t(!1)}catch(je){re.error(je instanceof Error?je.message:"Could not save the appointment")}},ce=async()=>{if(l!=null&&l.id)try{await u.mutateAsync(l.id),re.success("Appointment deleted"),c==null||c(),t(!1)}catch(je){re.error(je instanceof Error?je.message:"Could not delete the appointment")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Ds,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:m?"Edit appointment":"New appointment"}),e.jsx(Pr,{children:o?"Saves to LevelUp and your connected Google Calendar.":"Connect Google Calendar to also push this to your Google account."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Title"}),e.jsx(xe,{value:p,onChange:je=>f(je.target.value),placeholder:"Listing presentation — 12 Oak St"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Date"}),e.jsx(xe,{type:"date",value:x,onChange:je=>y(je.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Start"}),e.jsx(xe,{type:"time",value:v,onChange:je=>b(je.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"End"}),e.jsx(xe,{type:"time",value:N,onChange:je=>S(je.target.value)})]})]}),K&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-300 bg-amber-50 dark:bg-amber-950/20 p-2.5 text-xs text-amber-800 dark:text-amber-300",children:[e.jsx(tc,{className:"h-4 w-4 shrink-0 mt-0.5"}),"You already have something on your Google Calendar during this time. You can still save it."]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Meeting type"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Rmr.map(je=>{const be=je.icon,he=A===je.id;return e.jsxs("button",{type:"button",onClick:()=>T(je.id),className:Mt("inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-xs font-medium transition-colors",he?"bg-primary text-primary-foreground border-primary":"hover:bg-accent"),children:[e.jsx(be,{className:"h-3.5 w-3.5"}),je.label]},je.id)})}),A==="google_meet"&&!o&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connect Google Calendar to auto-create the Meet link."})]}),A!=="google_meet"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:A==="phone"?"Phone number":"Location"}),e.jsx(xe,{value:L,onChange:je=>M(je.target.value),placeholder:A==="phone"?"(555) 123-4567":"123 Main St, Suite 200"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(te,{className:"flex items-center gap-1.5",children:[e.jsx(Bn,{className:"h-3.5 w-3.5"})," Contacts"]}),se.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:se.map(je=>e.jsxs(Be,{variant:"secondary",className:"max-w-[220px] gap-1",title:ne(je),children:[e.jsx("span",{className:"truncate",children:ne(je)}),e.jsx("button",{type:"button",onClick:()=>$(be=>be.filter(he=>he!==je.id)),children:e.jsx(er,{className:"h-3 w-3"})})]},je.id))}),e.jsx(xe,{value:H,onChange:je=>V(je.target.value),placeholder:"Search contacts with an email…"}),H.trim()&&e.jsxs("div",{className:"max-h-40 overflow-y-auto rounded-lg border divide-y",children:[ue.filter(je=>!z.includes(je.id)).map(je=>e.jsxs("button",{type:"button",onClick:()=>{$(be=>[...be,je.id]),V("")},className:"flex w-full items-baseline gap-2 overflow-hidden px-3 py-2 text-left text-sm hover:bg-accent/50",title:[ne(je),je.email].filter(Boolean).join(" · "),children:[e.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:ne(je)}),je.email&&e.jsx("span",{className:"max-w-[45%] shrink-0 truncate text-xs text-muted-foreground",children:je.email})]},je.id)),ue.length===0&&e.jsx("p",{className:"px-3 py-2 text-sm text-muted-foreground",children:"No contacts found"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:z.length===0?"Tap a search result to add a guest — they get the Google invite.":`${z.length} guest${z.length>1?"s":""} will be invited to the calendar event.`})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Notes"}),e.jsx(Fs,{value:I,onChange:je=>R(je.target.value),rows:3,placeholder:"Anything you want on the invite…"})]})]}),e.jsxs(Mr,{className:"gap-2 sm:justify-between",children:[m?e.jsxs(U,{variant:"ghost",onClick:ce,disabled:u.isPending,className:"text-destructive hover:text-destructive",children:[e.jsx(In,{className:"h-4 w-4 mr-1.5"})," Delete"]}):e.jsx("span",{}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(U,{onClick:ie,disabled:d.isPending,children:d.isPending?"Saving…":m?"Save changes":"Create appointment"})]})]})]})})}function Omr(s){const t=s.meta||{};return{id:t.appointment_id,user_id:"",title:s.title,start_at:s.start||`${s.date}T09:00:00Z`,end_at:s.end||s.start||`${s.date}T09:30:00Z`,all_day:s.allDay,timezone:XP(),meeting_mode:t.meeting_mode||"in_person",location:t.location??null,meeting_link:s.externalLink??null,notes:t.notes??null,deal_id:t.deal_id??null,listing_id:null,status:"confirmed",google_event_id:null,google_sync_status:t.google_sync_status??null,google_sync_error:null,agent_appointment_contacts:(t.contact_ids||[]).map(n=>({contact_id:n,invite_email:null}))}}function dX(s){const[t,n,r]=s.split(/[-/T]/).map(Number);return new Date(t,(n||1)-1,r||1)}function fw(s){const t=`${s.getMonth()+1}`.padStart(2,"0"),n=`${s.getDate()}`.padStart(2,"0");return`${s.getFullYear()}-${t}-${n}`}function vC(s,t){const n=new Date(s);return n.setDate(n.getDate()+t),n}function gBe(s){return vC(s,-s.getDay())}function bT(){return new Intl.DateTimeFormat("en-CA",{timeZone:XP(),year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date)}function Nat(s){return s?new Intl.DateTimeFormat("en-US",{timeZone:XP(),hour:"numeric",minute:"2-digit"}).format(new Date(s)).toLowerCase().replace(" ",""):""}function Jte(s){return new Intl.DateTimeFormat("en-US",{weekday:"long",month:"long",day:"numeric"}).format(dX(s))}const cYe=[{id:"google",label:"Google Calendar",color:"#4285F4",soft:"#4285F41A",icon:nc},{id:"appointments",label:"My appointments",color:"#0F766E",soft:"#0F766E1A",icon:sv},{id:"bookings",label:"Guest bookings",color:"#406E71",soft:"#406E711A",icon:Yr},{id:"deals",label:"Deal dates",color:"#2a4c64",soft:"#2a4c641A",icon:a1},{id:"tasks",label:"Tasks",color:"#B45309",soft:"#B453091A",icon:cy},{id:"open_houses",label:"Open houses",color:"#7C3AED",soft:"#7C3AED1A",icon:ra},{id:"events",label:"LevelUp events",color:"#0EA5E9",soft:"#0EA5E91A",icon:cn},{id:"coaching",label:"Coaching",color:"#DB2777",soft:"#DB27771A",icon:Wr}],c8e=Object.fromEntries(cYe.map(s=>[s.id,s])),vas="levelup.myCalendar.layers",E3t="levelup.myCalendar.view";function Fmr(){try{return JSON.parse(localStorage.getItem(vas)||"{}")}catch{return{}}}function zmr(){var ke,Te;const s=Wn(),[t,n]=fc(),[r,a]=j.useState(()=>dX(bT())),[i,l]=j.useState(()=>localStorage.getItem(E3t)||"month"),[o,c]=j.useState(Fmr),[d,u]=j.useState(bT()),[h,m]=j.useState(!1),[p,f]=j.useState(bT()),[x,y]=j.useState(void 0),[v,b]=j.useState(null),[N,S]=j.useState(!1),{timezone:A}=wre(),T=(Me,Oe)=>{b(null);const Se=bT(),Qe=Me||Se;f(Qe{u(Me),a(dX(Me)),l("day")},M=Me=>{Me.layer==="appointments"&&(b(Omr(Me)),m(!0))};j.useEffect(()=>localStorage.setItem(E3t,i),[i]),j.useEffect(()=>localStorage.setItem(vas,JSON.stringify(o)),[o]);const I=ZOt(!0,"agent");j.useEffect(()=>{const Me=t.get("google_calendar");if(!Me)return;Me==="connected"?re.success("Google Calendar connected"):re.error(t.get("google_calendar_error")||"Google Calendar connection failed");const Oe=new URLSearchParams(t);Oe.delete("google_calendar"),Oe.delete("google_calendar_error"),n(Oe,{replace:!0})},[t,n]);const{rangeStart:R,rangeEnd:z,gridDays:$}=j.useMemo(()=>{if(i==="week"){const Qe=gBe(r);return{rangeStart:fw(Qe),rangeEnd:fw(vC(Qe,6)),gridDays:Array.from({length:7},(Ae,Fe)=>vC(Qe,Fe))}}if(i==="day")return{rangeStart:fw(r),rangeEnd:fw(r),gridDays:[r]};if(i==="agenda")return{rangeStart:fw(r),rangeEnd:fw(vC(r,44)),gridDays:[]};const Me=new Date(r.getFullYear(),r.getMonth(),1),Oe=gBe(Me),Se=Array.from({length:42},(Qe,Ae)=>vC(Oe,Ae));return{rangeStart:fw(Oe),rangeEnd:fw(Se[41]),gridDays:Se}},[r,i]),{data:H,isLoading:V,isFetching:K,refetch:Z,error:Q}=Lmr(R,z),le=!!((ke=I.status.data)!=null&&ke.connected)||!!(H!=null&&H.google.connected),ue=j.useMemo(()=>((H==null?void 0:H.items)||[]).filter(Me=>!o[Me.layer]),[H,o]),se=j.useMemo(()=>{const Me=new Map;return ue.forEach(Oe=>{const Se=Me.get(Oe.date)||[];Se.push(Oe),Me.set(Oe.date,Se)}),Me},[ue]),ne=j.useMemo(()=>se.get(d)||[],[se,d]),ie=bT(),ce=j.useMemo(()=>ue.filter(Me=>Me.date>=ie).slice(0,6),[ue,ie]),je=j.useMemo(()=>ue.filter(Me=>{var Oe,Se;return Me.date{if(i==="week"){const Me=gBe(r),Oe=vC(Me,6),Se=Me.getMonth()===Oe.getMonth(),Qe=(Ae,Fe)=>new Intl.DateTimeFormat("en-US",{month:Fe?"short":void 0,day:"numeric"}).format(Ae);return`${Qe(Me,!0)} – ${Qe(Oe,!Se)}, ${Oe.getFullYear()}`}return i==="day"?Jte(fw(r)):i==="agenda"?"Next 45 days":new Intl.DateTimeFormat("en-US",{month:"long",year:"numeric"}).format(r)},[r,i]),he=Me=>{if(i==="day"){a(Oe=>{const Se=vC(Oe,Me);return u(fw(Se)),Se});return}a(i==="week"?Oe=>vC(Oe,Me*7):i==="agenda"?Oe=>vC(Oe,Me*45):Oe=>new Date(Oe.getFullYear(),Oe.getMonth()+Me,1))},ge=Me=>{if(Me==="google"&&!le){I.connect.mutate();return}c(Oe=>({...Oe,[Me]:!Oe[Me]}))};return e.jsxs(qs,{children:[e.jsxs("div",{className:"p-4 md:p-6 space-y-5 max-w-[1600px] mx-auto",children:[e.jsxs("div",{className:"rounded-2xl border bg-card shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"px-5 py-5 md:px-7 md:py-6",style:{background:"linear-gradient(135deg, #2a4c6412, #406E7112)"},children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl md:text-3xl font-semibold tracking-tight text-foreground",children:"My Calendar"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Appointments, deal deadlines, tasks and open houses — all in one place."}),e.jsxs("button",{type:"button",onClick:()=>S(!0),className:"mt-2 inline-flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Ok,{className:"h-3.5 w-3.5"}),"Times shown in ",A.replace(/_/g," "),Ree(A)?` (${Ree(A)})`:""," · change"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>S(!0),className:"rounded-full","aria-label":"Calendar settings",children:[e.jsx(qc,{className:"h-4 w-4 mr-2"}),"Settings"]}),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>Z(),disabled:K,className:"rounded-full",children:[e.jsx(no,{className:Mt("h-4 w-4 mr-2",K&&"animate-spin")}),"Refresh"]}),e.jsxs(U,{size:"sm",className:"rounded-full",onClick:()=>T(),children:[e.jsx(an,{className:"h-4 w-4 mr-1.5"}),"New appointment"]}),e.jsxs(U,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>s("/mission-control/scheduler"),children:["Scheduler settings",e.jsx(Oa,{className:"h-4 w-4 ml-2"})]})]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-2",children:[le?e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full px-3 py-1.5 text-xs font-medium border",style:{background:"#4285F412",borderColor:"#4285F440",color:"#1f4fa8"},children:[e.jsx(zr,{className:"h-3.5 w-3.5"}),"Google Calendar connected",((Te=I.status.data)==null?void 0:Te.account_email)&&e.jsxs("span",{className:"opacity-70",children:["· ",I.status.data.account_email]})]}):e.jsxs("button",{onClick:()=>I.connect.mutate(),disabled:I.connect.isPending,className:"inline-flex items-center gap-2 rounded-full px-3 py-1.5 text-xs font-medium border border-dashed hover:bg-accent transition-colors",children:[e.jsx(nc,{className:"h-3.5 w-3.5"}),I.connect.isPending?"Opening Google…":"Connect Google Calendar"]}),(H==null?void 0:H.google.error)&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs text-destructive",children:[e.jsx(Vo,{className:"h-3.5 w-3.5"}),H.google.error]})]})]}),!le&&!I.status.isLoading&&e.jsxs("div",{className:"border-t px-5 py-4 md:px-7 flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl flex items-center justify-center shrink-0",style:{background:"#4285F41A"},children:e.jsx(nc,{className:"h-5 w-5",style:{color:"#4285F4"}})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-foreground",children:"See your Google events here too"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect once and your Google Calendar events appear alongside your LevelUp activity. We never post to your calendar without you."})]})]}),e.jsx(U,{onClick:()=>I.connect.mutate(),disabled:I.connect.isPending,className:"rounded-full",children:"Connect Google Calendar"})]})]}),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(U,{variant:"outline",size:"icon",className:"rounded-full h-9 w-9",onClick:()=>he(-1),children:e.jsx(rd,{className:"h-4 w-4"})}),e.jsx(U,{variant:"outline",size:"icon",className:"rounded-full h-9 w-9",onClick:()=>he(1),children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx(U,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>{a(dX(bT())),u(bT())},children:"Today"}),e.jsx("h2",{className:"text-lg font-semibold ml-1 text-foreground",children:be})]}),e.jsx("div",{className:"inline-flex rounded-full border p-1 bg-card",children:["month","week","day","agenda"].map(Me=>e.jsx("button",{onClick:()=>{Me==="day"&&a(dX(d||bT())),l(Me)},className:Mt("px-3.5 py-1.5 text-xs font-medium rounded-full capitalize transition-all",i===Me?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:Me},Me))})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:cYe.map(Me=>{const Oe=Me.id==="google"?!le:o[Me.id],Se=Me.icon;return e.jsxs("button",{onClick:()=>ge(Me.id),className:Mt("inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-xs font-medium transition-all hover:-translate-y-0.5",Oe&&"border-dashed opacity-70"),style:Oe?void 0:{background:Me.soft,borderColor:`${Me.color}55`,color:Me.color},children:[e.jsx(Se,{className:"h-3.5 w-3.5"}),Me.label,Me.id==="google"&&!le&&e.jsx("span",{className:"opacity-70",children:"· connect"})]},Me.id)})}),Q&&e.jsx(we,{className:"p-4 border-destructive/40",children:e.jsx("p",{className:"text-sm text-destructive",children:Q.message})}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_320px] gap-5",children:[e.jsx(we,{className:"rounded-2xl overflow-hidden shadow-sm",children:V?e.jsx("div",{className:"p-6 space-y-3",children:Array.from({length:6}).map((Me,Oe)=>e.jsx(xn,{className:"h-16 w-full"},Oe))}):i==="agenda"?e.jsx(Umr,{items:ue,today:ie,onOpenItem:M}):i==="day"?e.jsx(qmr,{dayKey:fw(r),items:se.get(fw(r))||[],today:ie,onCreate:T,onOpenItem:M}):e.jsx(Bmr,{days:$,byDay:se,anchorMonth:r.getMonth(),today:ie,week:i==="week",selectedDay:d,onSelectDay:u,onOpenDay:L,onCreate:T,onOpenItem:M})}),e.jsxs("div",{className:"space-y-4",children:[i!=="day"&&ne.length>0&&e.jsxs(we,{className:"rounded-2xl p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-3",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-2 text-foreground",children:[e.jsx(nc,{className:"h-4 w-4 text-primary"})," ",Jte(d)]}),e.jsxs(U,{size:"sm",variant:"ghost",className:"rounded-full h-7 px-2 text-xs",onClick:()=>L(d),children:["Day view ",e.jsx(Oa,{className:"h-3 w-3 ml-1"})]})]}),e.jsx("div",{className:"space-y-2",children:ne.map(Me=>e.jsx(xBe,{item:Me,onOpen:s},Me.id))})]}),e.jsxs(we,{className:"rounded-2xl p-4",children:[e.jsxs("h3",{className:"text-sm font-semibold mb-3 flex items-center gap-2 text-foreground",children:[e.jsx(Yr,{className:"h-4 w-4 text-primary"})," Up next"]}),ce.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing scheduled in this range."}):e.jsx("div",{className:"space-y-2",children:ce.map(Me=>e.jsx(xBe,{item:Me,onOpen:s},Me.id))})]}),je.length>0&&e.jsxs(we,{className:"rounded-2xl p-4 border-destructive/30",children:[e.jsxs("h3",{className:"text-sm font-semibold mb-3 flex items-center gap-2 text-foreground",children:[e.jsx(Vo,{className:"h-4 w-4 text-destructive"})," Needs attention"]}),e.jsx("div",{className:"space-y-2",children:je.map(Me=>e.jsx(xBe,{item:Me,onOpen:s,overdue:!0},Me.id))})]}),e.jsxs(we,{className:"rounded-2xl p-4",children:[e.jsx("h3",{className:"text-sm font-semibold mb-2 text-foreground",children:"This range"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:cYe.filter(Me=>!o[Me.id]).map(Me=>{const Oe=ue.filter(Se=>Se.layer===Me.id).length;return Oe?e.jsxs("div",{className:"rounded-xl px-3 py-2",style:{background:Me.soft},children:[e.jsx("p",{className:"text-lg font-semibold",style:{color:Me.color},children:Oe}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-tight",children:Me.label})]},Me.id):null})})]})]})]})]}),e.jsx(Dmr,{open:h,onOpenChange:m,defaultDate:p,defaultTime:x,appointment:v,googleConnected:le,onSaved:()=>Z()}),e.jsx(TBt,{open:N,onOpenChange:S})]})}function xBe({item:s,onOpen:t,overdue:n}){const r=c8e[s.layer];return e.jsxs("button",{onClick:()=>s.link?t(s.link):s.externalLink&&window.open(s.externalLink,"_blank"),className:"w-full text-left rounded-xl border p-2.5 hover:bg-accent/50 transition-colors flex gap-2.5 items-start",children:[e.jsx("span",{className:"mt-1 h-2 w-2 rounded-full shrink-0",style:{background:r.color}}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block text-sm font-medium truncate text-foreground",children:s.title}),e.jsxs("span",{className:"block text-xs text-muted-foreground truncate",children:[Jte(s.date),s.start&&!s.allDay?` · ${Nat(s.start)}`:"",s.subtitle?` · ${s.subtitle}`:""]})]}),n&&e.jsx(Be,{variant:"destructive",className:"text-[10px]",children:"Overdue"})]})}function dYe({item:s,onOpen:t}){var c,d;const n=c8e[s.layer],r=s.layer==="tasks"?!!((c=s.meta)!=null&&c.done):!!((d=s.meta)!=null&&d.completed),a=Mt("group flex w-full items-center gap-1.5 rounded-md px-1.5 py-1 text-[11px] leading-tight text-left transition-all hover:translate-x-0.5",r&&"opacity-50 line-through"),i={background:n.soft,color:n.color},l=e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full shrink-0",style:{background:n.color}}),!s.allDay&&s.start&&e.jsx("span",{className:"font-semibold shrink-0",children:Nat(s.start)}),e.jsx("span",{className:"truncate",children:s.title}),s.externalLink&&!s.link&&e.jsx(Sr,{className:"h-3 w-3 shrink-0 opacity-0 group-hover:opacity-100"})]}),o=`${s.title}${s.subtitle?` — ${s.subtitle}`:""}`;return s.layer==="appointments"&&t?e.jsx("span",{role:"button",tabIndex:0,onClick:u=>{u.stopPropagation(),t(s)},onKeyDown:u=>{u.key==="Enter"&&(u.stopPropagation(),t(s))},className:a,style:i,title:o,children:l}):e.jsx("a",{href:s.link||s.externalLink||void 0,target:s.link?void 0:"_blank",rel:"noreferrer",onClick:u=>u.stopPropagation(),className:a,style:i,title:o,children:l})}function Bmr({days:s,byDay:t,anchorMonth:n,today:r,week:a,selectedDay:i,onSelectDay:l,onOpenDay:o,onCreate:c,onOpenItem:d}){const u=a?12:4;return e.jsxs("div",{children:[e.jsx("div",{className:"grid grid-cols-7 border-b bg-muted/40",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(h=>e.jsx("div",{className:"px-2 py-2 text-center text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:h},h))}),e.jsx("div",{className:Mt("grid grid-cols-7",a?"min-h-[520px]":""),children:s.map(h=>{const m=fw(h),p=t.get(m)||[],f=m===r,x=!a&&h.getMonth()!==n;return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>l(m),onKeyDown:y=>{y.key==="Enter"&&l(m)},onDoubleClick:()=>o==null?void 0:o(m),className:Mt("group/day text-left border-b border-r p-1.5 align-top min-h-[104px] transition-colors hover:bg-accent/40",a&&"min-h-[520px]",x&&"bg-muted/20",i===m&&"bg-accent/50"),children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("button",{type:"button",title:"Open day view",onClick:y=>{y.stopPropagation(),o?o(m):l(m)},className:Mt("inline-flex h-6 min-w-6 px-1.5 items-center justify-center rounded-full text-xs font-semibold transition-colors hover:bg-primary/15",f?"bg-primary text-primary-foreground hover:bg-primary":x?"text-muted-foreground/60":"text-foreground"),children:h.getDate()}),e.jsxs("span",{className:"flex items-center gap-1",children:[p.length>u&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:p.length}),c&&e.jsx("button",{type:"button","aria-label":`Add appointment on ${m}`,onClick:y=>{y.stopPropagation(),c(m)},className:"opacity-0 group-hover/day:opacity-100 focus:opacity-100 rounded-full p-0.5 text-muted-foreground hover:text-foreground hover:bg-background transition-opacity",children:e.jsx(an,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"space-y-1",children:[p.slice(0,u).map(y=>e.jsx(dYe,{item:y,onOpen:d},y.id)),p.length>u&&e.jsxs("button",{type:"button",onClick:y=>{y.stopPropagation(),o?o(m):l(m)},className:"block text-[10px] text-muted-foreground pl-1.5 hover:text-foreground hover:underline",children:["+",p.length-u," more"]})]})]},m)})})]})}function Umr({items:s,today:t,onOpenItem:n}){const r=j.useMemo(()=>{const a=new Map;return s.filter(i=>i.date>=t).forEach(i=>{const l=a.get(i.date)||[];l.push(i),a.set(i.date,l)}),[...a.entries()].sort((i,l)=>i[0]e.jsxs("div",{className:"p-4 md:p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("span",{className:Mt("text-sm font-semibold",a===t?"text-primary":"text-foreground"),children:Jte(a)}),a===t&&e.jsx(Be,{className:"text-[10px]",children:"Today"})]}),e.jsx("div",{className:"space-y-2",children:i.map(l=>{const o=c8e[l.layer],c=l.layer==="appointments"&&!!n,d="flex w-full text-left items-center gap-3 rounded-xl border p-3 hover:bg-accent/50 transition-colors",u=e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"w-16 shrink-0 text-xs font-semibold text-muted-foreground",children:l.allDay?"All day":Nat(l.start)}),e.jsx("span",{className:"h-8 w-1 rounded-full shrink-0",style:{background:o.color}}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block text-sm font-medium truncate text-foreground",children:l.title}),e.jsx("span",{className:"block text-xs text-muted-foreground truncate",children:l.subtitle||o.label})]}),e.jsx(Be,{variant:"secondary",className:"text-[10px] shrink-0",children:o.label})]});return c?e.jsx("button",{type:"button",onClick:()=>n(l),className:d,children:u},l.id):e.jsx("a",{href:l.link||l.externalLink||void 0,target:l.link?void 0:"_blank",rel:"noreferrer",className:d,children:u},l.id)})})]},a))}):e.jsxs("div",{className:"p-10 text-center",children:[e.jsx(nc,{className:"h-8 w-8 mx-auto text-muted-foreground/50 mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing scheduled in the next 45 days."})]})}const T3t=6,M3t=22,cZ=60;function fde(s){var a,i;const t=new Intl.DateTimeFormat("en-US",{timeZone:XP(),hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(new Date(s)),n=Number(((a=t.find(l=>l.type==="hour"))==null?void 0:a.value)||0),r=Number(((i=t.find(l=>l.type==="minute"))==null?void 0:i.value)||0);return n%24*60+r}function qmr({dayKey:s,items:t,today:n,onCreate:r,onOpenItem:a}){const[i,l]=j.useState(()=>fde(new Date().toISOString()));j.useEffect(()=>{const S=setInterval(()=>l(fde(new Date().toISOString())),6e4);return()=>clearInterval(S)},[]);const o=t.filter(S=>S.allDay||!S.start),c=t.filter(S=>!S.allDay&&S.start).map(S=>{const A=fde(S.start),T=S.end?Math.max(fde(S.end),A+15):A+30;return{item:S,start:A,end:T}}).sort((S,A)=>S.start-A.start||S.end-A.end),d=[];let u=[];const h=()=>{if(!u.length)return;const S=[];u.map(T=>{let L=S.findIndex(M=>M<=T.start);return L===-1?(L=S.length,S.push(T.end)):S[L]=T.end,{...T,col:L}}).forEach(T=>d.push({...T,cols:S.length})),u=[]};let m=-1;for(const S of c)u.length&&S.start>=m&&h(),u.push(S),m=Math.max(m,S.end);h();const p=c.length?Math.min(...c.map(S=>S.start)):T3t*60,f=c.length?Math.max(...c.map(S=>S.end)):M3t*60,x=Math.min(T3t,Math.floor(p/60)),y=Math.max(M3t,Math.ceil(f/60)),v=Array.from({length:y-x+1},(S,A)=>x+A),b=S=>(S-x*60)/60*cZ,N=s===n;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b px-4 py-3 bg-muted/30",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:Jte(s)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.length===0?"Nothing scheduled":`${t.length} item${t.length>1?"s":""}`})]}),r&&e.jsxs(U,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>r(s),children:[e.jsx(an,{className:"h-4 w-4 mr-1.5"})," Add"]})]}),o.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1.5 border-b px-4 py-2.5 bg-background",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mr-1 self-center",children:"All day"}),o.map(S=>e.jsx("span",{className:"max-w-[240px]",children:e.jsx(dYe,{item:S,onOpen:a})},S.id))]}),e.jsx("div",{className:"relative overflow-y-auto max-h-[640px] pt-3 pb-4",children:e.jsxs("div",{className:"relative",style:{height:v.length*cZ},children:[v.map((S,A)=>e.jsxs("div",{className:"absolute left-0 right-0 border-t border-border/60",style:{top:A*cZ,height:cZ},children:[e.jsx("span",{className:"absolute -top-2 left-2 text-[10px] font-medium text-muted-foreground w-14",children:new Intl.DateTimeFormat("en-US",{hour:"numeric"}).format(new Date(2e3,0,1,S)).toLowerCase()}),e.jsx("button",{type:"button","aria-label":`Create at ${S}:00`,onClick:()=>r==null?void 0:r(s,`${`${S}`.padStart(2,"0")}:00`),className:"absolute left-16 right-2 top-0 h-full rounded-md hover:bg-accent/50 transition-colors"})]},S)),N&&i>=x*60&&i<=y*60&&e.jsxs("div",{className:"absolute left-14 right-2 z-20 pointer-events-none",style:{top:b(i)},children:[e.jsx("div",{className:"h-px bg-destructive"}),e.jsx("div",{className:"absolute -left-1.5 -top-1 h-2.5 w-2.5 rounded-full bg-destructive"})]}),d.map(({item:S,start:A,end:T,col:L,cols:M})=>{const I=c8e[S.layer],R=Math.max(22,(T-A)/60*cZ-4),z=100/M;return e.jsx("div",{className:"absolute z-10",style:{top:b(A)+2,height:R,left:`calc(4rem + ${L*z}% * 0.92)`,width:`calc(${z}% * 0.92 - 0.35rem)`},children:e.jsxs("div",{className:"h-full rounded-lg border p-1.5 overflow-hidden",style:{background:I.soft,borderColor:`${I.color}55`},children:[e.jsx(dYe,{item:S,onOpen:a}),R>44&&S.subtitle&&e.jsx("p",{className:"text-[10px] text-muted-foreground truncate pl-1.5 mt-0.5",children:S.subtitle})]})},S.id)})]})})]})}function gde(s){const[t,n]=String(s).split(":").map(Number),r=t>=12?"PM":"AM";return`${t%12||12}:${String(n).padStart(2,"0")} ${r}`}function $mr(s){const[t,n,r]=s.split(/[-/T]/).map(Number);return Gs(new Date(t,n-1,r),"EEEE, MMMM d, yyyy")}function Vmr(){var ue;const{token:s}=Di(),[t]=fc(),[n,r]=j.useState(null),[a,i]=j.useState(!0),[l,o]=j.useState(null),[c,d]=j.useState("details"),[u,h]=j.useState(!1),[m,p]=j.useState(""),[f,x]=j.useState(null),[y,v]=j.useState(new Date),[b,N]=j.useState({}),[S,A]=j.useState(!1),[T,L]=j.useState(null),[M,I]=j.useState(null),R=async se=>{var ce,je;const{data:ne,error:ie}=await q.functions.invoke("agent-booking",{body:se});if(ie){let be=ie.message;try{const he=await((je=(ce=ie.context)==null?void 0:ce.json)==null?void 0:je.call(ce));he!=null&&he.error&&(be=he.error)}catch{}throw new Error(be)}if(ne!=null&&ne.error)throw new Error(ne.error);return ne};j.useEffect(()=>{s&&(async()=>{try{const se=await R({action:"manage_get",manage_token:s});r(se),t.get("cancel")==="1"&&d("cancel")}catch(se){o(se.message)}finally{i(!1)}})()},[s]),j.useEffect(()=>{if(c!=="reschedule"||!(n!=null&&n.booking_type))return;let se=!1;return(async()=>{A(!0);try{const ne=new Date(y.getFullYear(),y.getMonth(),1),ie=vf(new Date),ce=F4(ie,ne)?ie:ne,je=new Date(y.getFullYear(),y.getMonth()+1,0),be=Math.max(1,Math.round((je.getTime()-ce.getTime())/864e5)+1),he=await R({action:"availability",slug:n.slug,booking_type_id:n.booking_type.id,start:Gs(ce,"yyyy-MM-dd"),days:Math.min(be,90),ignore_booking_id:n.booking.id});se||N((he==null?void 0:he.availability)||{})}catch(ne){se||re.error(ne.message)}finally{se||A(!1)}})(),()=>{se=!0}},[c,y,(ue=n==null?void 0:n.booking_type)==null?void 0:ue.id]);const z=j.useMemo(()=>{const se=y.getFullYear(),ne=y.getMonth(),ie=new Date(se,ne,1),ce=new Date(se,ne+1,0),je=[];for(let be=0;be{h(!0);try{await R({action:"manage_cancel",manage_token:s,reason:m}),x("cancelled"),d("done")}catch(se){re.error(se.message)}finally{h(!1)}},V=async()=>{if(!(!T||!M)){h(!0);try{await R({action:"manage_reschedule",manage_token:s,date:Gs(T,"yyyy-MM-dd"),time:M}),x("rescheduled"),d("done")}catch(se){re.error(se.message)}finally{h(!1)}}};if(a)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] flex items-center justify-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx(Et,{className:"h-8 w-8 animate-spin text-[#406E71]"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Loading your booking…"})]})});if(l||!n)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] flex items-center justify-center px-4",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-lg p-8 max-w-sm text-center space-y-3",children:[e.jsx(ou,{className:"h-10 w-10 text-slate-300 mx-auto"}),e.jsx("h1",{className:"text-lg font-bold text-slate-800",children:"Booking not found"}),e.jsx("p",{className:"text-sm text-slate-500",children:l||"This management link is no longer valid."})]})});const{booking:K,booking_type:Z,agent:Q}=n,le=K.status==="cancelled";return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] py-10 px-4",children:e.jsxs("div",{className:"max-w-lg mx-auto",children:[e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-br from-[#406E71] to-[#2a4c64] px-8 py-7 text-center",children:[e.jsx("h1",{className:"text-xl font-bold text-white",children:c==="done"?f==="cancelled"?"Booking cancelled":"Booking rescheduled":"Manage your booking"}),e.jsxs("p",{className:"text-white/80 text-sm mt-1",children:[(Z==null?void 0:Z.name)||"Meeting",Q!=null&&Q.name?` with ${Q.name}`:""]})]}),e.jsxs("div",{className:"p-7 space-y-6",children:[c!=="reschedule"&&e.jsxs("div",{className:"rounded-xl border border-slate-100 bg-slate-50 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-800 font-semibold",children:[e.jsx(nc,{className:"h-4 w-4 text-[#406E71]"}),$mr(K.booking_date)]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-600",children:[e.jsx(Yr,{className:"h-4 w-4 text-[#406E71]"}),gde(String(K.start_time).slice(0,5))," –"," ",gde(String(K.end_time).slice(0,5)),e.jsxs("span",{className:"text-xs text-slate-400",children:["(",n.timezone.replace(/_/g," "),")"]})]}),le&&e.jsx("p",{className:"text-xs font-semibold text-red-600 pt-1",children:"This booking is cancelled."})]}),c==="details"&&!le&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[n.allow_reschedule&&e.jsx(U,{className:"h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold",onClick:()=>d("reschedule"),children:"Reschedule"}),n.allow_cancel&&e.jsx(U,{variant:"outline",className:"h-12 rounded-xl border-red-200 text-red-600 hover:bg-red-50 font-semibold",onClick:()=>d("cancel"),children:"Cancel booking"})]}),c==="cancel"&&!le&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-slate-600",children:["Let ",(Q==null?void 0:Q.name)||"your host"," know why you can't make it (optional)."]}),e.jsx(Fs,{value:m,onChange:se=>p(se.target.value),placeholder:"Something came up…",className:"rounded-xl",rows:3}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(U,{variant:"ghost",className:"flex-1 h-11 rounded-xl",onClick:()=>d("details"),disabled:u,children:"Keep booking"}),e.jsx(U,{className:"flex-1 h-11 rounded-xl bg-red-600 hover:bg-red-700 text-white font-semibold",onClick:H,disabled:u,children:u?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):"Cancel booking"})]})]}),c==="reschedule"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("button",{onClick:()=>d("details"),className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800",children:[e.jsx(Aa,{className:"h-3.5 w-3.5"})," Back"]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("button",{className:"p-2 rounded-lg hover:bg-slate-100",onClick:()=>v(new Date(y.getFullYear(),y.getMonth()-1,1)),children:e.jsx(rd,{className:"h-4 w-4 text-slate-500"})}),e.jsx("span",{className:"text-sm font-semibold text-slate-800",children:Gs(y,"MMMM yyyy")}),e.jsx("button",{className:"p-2 rounded-lg hover:bg-slate-100",onClick:()=>v(new Date(y.getFullYear(),y.getMonth()+1,1)),children:e.jsx(gi,{className:"h-4 w-4 text-slate-500"})})]}),e.jsxs("div",{className:"grid grid-cols-7 gap-1 text-center",children:[["S","M","T","W","T","F","S"].map((se,ne)=>e.jsx("div",{className:"text-[11px] font-semibold text-slate-400 py-1",children:se},ne)),z.map((se,ne)=>{if(!se)return e.jsx("div",{},`p${ne}`);const ie=Gs(se,"yyyy-MM-dd"),ce=(b[ie]||[]).length>0&&!rS(se,vf(new Date)),je=T&&Hh(se,T);return e.jsx("button",{disabled:!ce,onClick:()=>{L(se),I(null)},className:`aspect-square rounded-lg text-sm font-medium transition-colors ${je?"bg-[#406E71] text-white":ce?"bg-[#406E71]/10 text-[#406E71] hover:bg-[#406E71]/20":"text-slate-300"}`,children:se.getDate()},ie)})]}),S&&e.jsxs("p",{className:"text-center text-xs text-slate-400 flex items-center justify-center gap-2",children:[e.jsx(Et,{className:"h-3.5 w-3.5 animate-spin"})," Checking availability…"]}),T&&e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2 max-h-48 overflow-y-auto",children:$.length===0?e.jsx("p",{className:"col-span-full text-center text-sm text-slate-400 py-4",children:"No open times on this day"}):$.map(se=>e.jsx("button",{onClick:()=>I(se),className:`px-3 py-2.5 rounded-xl text-sm font-medium ${M===se?"bg-[#406E71] text-white":"bg-slate-50 text-slate-700 hover:bg-[#406E71]/10"}`,children:gde(se)},se))}),e.jsx(U,{className:"w-full h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold",disabled:!T||!M||u,onClick:V,children:u?e.jsx(Et,{className:"h-4 w-4 animate-spin"}):"Confirm new time"}),e.jsxs("p",{className:"text-center text-[11px] text-slate-400",children:["Times shown in ",n.timezone.replace(/_/g," ")]})]}),c==="done"&&e.jsxs("div",{className:"text-center space-y-4 py-4",children:[f==="cancelled"?e.jsx(ou,{className:"h-12 w-12 text-red-500 mx-auto"}):e.jsx(zr,{className:"h-12 w-12 text-emerald-500 mx-auto"}),e.jsx("p",{className:"text-sm text-slate-600",children:f==="cancelled"?`Your meeting has been cancelled and ${(Q==null?void 0:Q.name)||"your host"} has been notified.`:`Your meeting is now on ${T?Gs(T,"EEEE, MMMM d"):""} at ${M?gde(M):""}. A confirmation is on its way.`})]})]})]}),e.jsx("p",{className:"text-center text-[11px] text-slate-400 mt-6",children:"Powered by LevelUp Scheduler"})]})})}const P3t=[{id:"event_registration",label:"Event Registration",description:"Capture RSVPs for open houses, expos, seminars"},{id:"buyer_consultation",label:"Buyer Consultation",description:"Pre-qualify buyers with targeted questions"},{id:"home_valuation",label:"Home Valuation Request",description:`"What's your home worth?" lead capture`},{id:"lead_capture",label:"General Lead Capture",description:"Flexible form for any lead gen purpose"},{id:"lead_magnet",label:"Lead Magnet / Giveaway",description:"Offer a free download (PDF, guide, checklist) in exchange for contact info"},{id:"just_listed",label:"Just Listed",description:"Showcase a new listing with photos & details + contact CTA"},{id:"just_sold",label:"Just Sold",description:'Celebrate a sale & capture "Want results like this?" leads'}];function Hmr(){const{user:s}=vs(),t=Sa(),{toast:n}=Ai(),r=Wn(),a=Qt(),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState(null),[h,m]=j.useState({title:"",description:"",page_type:"lead_capture"}),{data:p=[],isLoading:f}=ct({queryKey:["landing-pages",t],queryFn:async()=>{const{data:b,error:N}=await q.from("landing_pages").select("*").eq("user_id",t).is("deleted_at",null).order("created_at",{ascending:!1});if(N)throw N;return b},enabled:!!t}),x=yt({mutationFn:async()=>{const b=h.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")+"-"+Date.now().toString(36),{data:N}=await q.from("profiles").select("name, phone, avatar_url, email").eq("id",t).single(),S=h.page_type==="just_listed"||h.page_type==="just_sold",{data:A,error:T}=await q.from("landing_pages").insert({user_id:t,title:h.title,description:h.description||null,page_type:h.page_type,slug:b,hero_headline:S?h.page_type==="just_listed"?"🏡 Just Listed":"🎉 Just Sold":h.page_type==="lead_magnet"?"📥 Free Download":h.title,agent_name:(N==null?void 0:N.name)||null,agent_phone:(N==null?void 0:N.phone)||null,agent_email:(N==null?void 0:N.email)||s.email||null,agent_photo_url:(N==null?void 0:N.avatar_url)||null,property_status:S?h.page_type.replace("just_",""):null}).select().single();if(T)throw T;const L=Gmr(h.page_type);if(L.length>0){const{error:M}=await q.from("landing_page_fields").insert(L.map((I,R)=>({...I,page_id:A.id,sort_order:R})));if(M)throw M}return A},onSuccess:b=>{a.invalidateQueries({queryKey:["landing-pages"]}),l(!1),m({title:"",description:"",page_type:"lead_capture"}),n({title:"Landing page created!"}),r(`/mission-control/landing-pages/${b.id}`)},onError:b=>n({title:"Error",description:b.message,variant:"destructive"})}),y=yt({mutationFn:async b=>{const{error:N}=await q.from("landing_pages").update({deleted_at:new Date().toISOString(),is_published:!1}).eq("id",b);if(N)throw N},onSuccess:()=>{a.invalidateQueries({queryKey:["landing-pages"]}),c(null),n({title:"Landing page deleted"})}}),v=b=>`https://pages.relevelup.com/${b}`;return e.jsxs(qs,{title:"Landing Pages",children:[e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Landing Pages"}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"Create branded lead capture pages for events, consultations, and more"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(U,{variant:"outline",onClick:()=>r("/mission-control/landing-pages/defaults"),children:[e.jsx(qc,{className:"h-4 w-4 mr-2"})," Defaults"]}),e.jsxs(U,{onClick:()=>l(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-2"})," New Page"]})]})]}),f?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"})}):p.length===0?e.jsx(we,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(Ur,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"No landing pages yet"}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1 mb-4",children:"Create your first page to start capturing leads"}),e.jsxs(U,{onClick:()=>l(!0),children:[e.jsx(an,{className:"h-4 w-4 mr-2"})," Create Landing Page"]})]})}):e.jsx("div",{className:"grid gap-4",children:p.map(b=>{var N;return e.jsx(we,{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 min-w-0 cursor-pointer",onClick:()=>r(`/mission-control/landing-pages/${b.id}`),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold truncate",children:b.title}),e.jsx(Be,{variant:b.is_published?"default":"secondary",className:"text-[10px]",children:b.is_published?"Published":"Draft"}),e.jsx(Be,{variant:"outline",className:"text-[10px]",children:((N=P3t.find(S=>S.id===b.page_type))==null?void 0:N.label)||b.page_type})]}),b.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:b.description}),e.jsxs("div",{className:"flex items-center gap-4 mt-2 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(xa,{className:"h-3 w-3"})," ",b.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ur,{className:"h-3 w-3"})," ",b.submission_count," submissions"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-4",children:[b.is_published&&e.jsxs(e.Fragment,{children:[e.jsx(U,{size:"sm",variant:"outline",onClick:()=>u(v(b.slug)),children:e.jsx(Sf,{className:"h-3.5 w-3.5"})}),e.jsx(U,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(v(b.slug)),n({title:"Link copied!"})},children:e.jsx(Pa,{className:"h-3.5 w-3.5"})}),e.jsx(U,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:v(b.slug),target:"_blank",rel:"noopener noreferrer",children:e.jsx(Sr,{className:"h-3.5 w-3.5"})})})]}),e.jsxs(Ku,{children:[e.jsx(Yu,{asChild:!0,children:e.jsx(U,{size:"sm",variant:"ghost",children:e.jsx(ey,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",children:[e.jsxs(La,{onClick:()=>r(`/mission-control/landing-pages/${b.id}`),children:[e.jsx(ri,{className:"h-3.5 w-3.5 mr-2"})," Edit"]}),e.jsxs(La,{onClick:()=>c(b.id),className:"text-destructive",children:[e.jsx(In,{className:"h-3.5 w-3.5 mr-2"})," Delete"]})]})]})]})]})})},b.id)})})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Ds,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Create Landing Page"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Page Title"}),e.jsx(xe,{value:h.title,onChange:b=>m(N=>({...N,title:b.target.value})),placeholder:"e.g. Veterans Home & Land Expo"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Description (optional)"}),e.jsx(Fs,{value:h.description,onChange:b=>m(N=>({...N,description:b.target.value})),placeholder:"Brief internal description...",rows:2})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Page Template"}),e.jsxs(Ns,{value:h.page_type,onValueChange:b=>m(N=>({...N,page_type:b})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:P3t.map(b=>e.jsx(et,{value:b.id,children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:b.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:b.description})]})},b.id))})]})]})]}),e.jsxs(Mr,{children:[e.jsx(U,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(U,{onClick:()=>x.mutate(),disabled:!h.title.trim()||x.isPending,children:x.isPending?"Creating...":"Create Page"})]})]})}),e.jsx(Fl,{open:!!o,onOpenChange:()=>c(null),children:e.jsxs(El,{children:[e.jsxs(Tl,{children:[e.jsx(Pl,{children:"Delete Landing Page?"}),e.jsx(Ll,{children:"This will permanently delete this page and all its submissions."})]}),e.jsxs(Ml,{children:[e.jsx(Il,{children:"Cancel"}),e.jsx(_l,{onClick:()=>o&&y.mutate(o),children:"Delete"})]})]})}),e.jsx(zs,{open:!!d,onOpenChange:()=>u(null),children:e.jsxs(Ds,{className:"max-w-sm",children:[e.jsx(Vs,{children:e.jsx($s,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[d&&e.jsx(fS,{value:d,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:d}),e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>{d&&(navigator.clipboard.writeText(d),n({title:"URL copied!"}))},children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1"})," Copy URL"]})]})]})})]})}function Gmr(s){const t=[{field_type:"text",label:"Full Name",placeholder:"Your name",is_required:!0},{field_type:"email",label:"Email",placeholder:"your@email.com",is_required:!0},{field_type:"phone",label:"Phone",placeholder:"(555) 123-4567",is_required:!1}];switch(s){case"event_registration":return[...t,{field_type:"select",label:"How did you hear about this event?",options:JSON.stringify(["Social Media","Friend/Referral","Email","Flyer/Sign","Other"]),is_required:!1},{field_type:"textarea",label:"Any questions or special needs?",placeholder:"Let us know...",is_required:!1}];case"buyer_consultation":return[...t,{field_type:"select",label:"Interested in",options:JSON.stringify(["Buying","Selling","Both"]),is_required:!0},{field_type:"select",label:"Timeline",options:JSON.stringify(["0-3 months","3-6 months","6-12 months","Just exploring"]),is_required:!1},{field_type:"toggle",label:"Already working with a Realtor?",is_required:!1},{field_type:"toggle",label:"Do you have property to sell?",is_required:!1},{field_type:"textarea",label:"Anything else we should know?",placeholder:"Tell us about your situation...",is_required:!1}];case"home_valuation":return[...t,{field_type:"text",label:"Property Address",placeholder:"123 Main St, City, State",is_required:!0},{field_type:"select",label:"Reason for Valuation",options:JSON.stringify(["Thinking of selling","Refinancing","Curiosity","Estate planning","Other"]),is_required:!1},{field_type:"select",label:"Timeline to Sell",options:JSON.stringify(["ASAP","1-3 months","3-6 months","6+ months","Not sure"]),is_required:!1}];case"lead_magnet":return[...t,{field_type:"select",label:"Are you currently working with a Realtor?",options:JSON.stringify(["Yes","No","Not yet"]),is_required:!1}];case"just_listed":return[...t,{field_type:"select",label:"I am interested in",options:JSON.stringify(["Scheduling a showing","Getting more details","Similar properties","Selling my home"]),is_required:!0},{field_type:"textarea",label:"Message",placeholder:"Tell me more about this property...",is_required:!1}];case"just_sold":return[...t,{field_type:"select",label:"I am looking to",options:JSON.stringify(["Sell my home","Buy a home","Both","Just curious"]),is_required:!0},{field_type:"text",label:"My Property Address",placeholder:"123 Main St, City, State",is_required:!1}];default:return[...t,{field_type:"textarea",label:"Message",placeholder:"How can we help you?",is_required:!1}]}}function Wmr(s,t){return t?`${(s/t*100).toFixed(1)}%`:"0%"}function Kmr({pageId:s}){const{data:t=[],isLoading:n}=ct({queryKey:["landing-page-events",s],queryFn:async()=>{const l=new Date(Date.now()-2592e6).toISOString(),{data:o,error:c}=await q.from("landing_page_events").select("event_type, session_id, utm_source, utm_medium, utm_campaign, referrer, device, created_at").eq("page_id",s).gte("created_at",l).order("created_at",{ascending:!1}).limit(1e3);if(c)throw c;return o||[]}}),{data:r=[]}=ct({queryKey:["landing-page-submissions-analytics",s],queryFn:async()=>{const{data:l}=await q.from("landing_page_submissions").select("id, created_at").eq("page_id",s);return l||[]}}),a=j.useMemo(()=>{const l=t.filter(f=>f.event_type==="view"),o=t.filter(f=>f.event_type==="click"),c=new Set(l.map(f=>f.session_id).filter(Boolean)),d=new Map,u=new Map,h=new Map;for(const f of l){const x=f.utm_source||"Direct / unknown";if(d.set(x,(d.get(x)||0)+1),f.referrer)try{const v=new URL(f.referrer).hostname.replace(/^www\./,"");u.set(v,(u.get(v)||0)+1)}catch{}const y=f.device||"unknown";h.set(y,(h.get(y)||0)+1)}const m=[];for(let f=13;f>=0;f--){const x=new Date;x.setHours(0,0,0,0),x.setDate(x.getDate()-f);const y=new Date(x);y.setDate(x.getDate()+1);const v=x.toLocaleDateString("en-US",{month:"numeric",day:"numeric"}),b=l.filter(S=>{const A=new Date(S.created_at);return A>=x&&A{const A=new Date(S.created_at);return A>=x&&Af.views));return{views:l.length,sessions:c.size,clicks:o.length,submissions:r.length,conversion:Wmr(r.length,c.size||l.length),sourceCounts:[...d.entries()].sort((f,x)=>x[1]-f[1]).slice(0,6),referrerCounts:[...u.entries()].sort((f,x)=>x[1]-f[1]).slice(0,6),deviceCounts:[...h.entries()].sort((f,x)=>x[1]-f[1]),days:m,maxBar:p}},[t,r]);if(n)return e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Array.from({length:4}).map((l,o)=>e.jsx(xn,{className:"h-24"},o))});const i=[{label:"Views (30d)",value:a.views,icon:xa},{label:"Unique visitors",value:a.sessions,icon:Bn},{label:"Submissions",value:a.submissions,icon:$r},{label:"Conversion rate",value:a.conversion,icon:rc}];return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:i.map(l=>e.jsx(we,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(l.icon,{className:"h-3.5 w-3.5"})," ",l.label]}),e.jsx("div",{className:"text-2xl font-semibold mt-1",children:l.value})]})},l.label))}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Last 14 days"})}),e.jsxs(Ie,{children:[a.views===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No traffic yet. Share your page link or QR code to start collecting visits."}):e.jsx("div",{className:"flex items-end gap-1.5 h-32",children:a.days.map((l,o)=>e.jsxs("div",{className:"flex-1 flex flex-col items-center gap-1",children:[e.jsxs("div",{className:"w-full flex flex-col justify-end h-24",children:[e.jsx("div",{title:`${l.views} views · ${l.submits} submits`,className:"w-full rounded-t bg-primary/70",style:{height:`${l.views/a.maxBar*100}%`,minHeight:l.views?2:0}}),l.submits>0&&e.jsx("div",{className:"w-full bg-emerald-500",style:{height:`${Math.max(2,l.submits/a.maxBar*100)}%`}})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:l.label})]},o))}),e.jsxs("div",{className:"flex items-center gap-4 mt-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm bg-primary/70"})," Views"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm bg-emerald-500"})," Submissions"]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(Ch,{className:"h-4 w-4"})," Top sources"]})}),e.jsx(Ie,{children:a.sourceCounts.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No UTM data yet."}):e.jsx("ul",{className:"space-y-1.5 text-sm",children:a.sourceCounts.map(([l,o])=>e.jsxs("li",{className:"flex justify-between",children:[e.jsx("span",{className:"truncate",children:l}),e.jsx("span",{className:"text-muted-foreground",children:o})]},l))})})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Top referrers"})}),e.jsx(Ie,{children:a.referrerCounts.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No external referrers tracked."}):e.jsx("ul",{className:"space-y-1.5 text-sm",children:a.referrerCounts.map(([l,o])=>e.jsxs("li",{className:"flex justify-between",children:[e.jsx("span",{className:"truncate",children:l}),e.jsx("span",{className:"text-muted-foreground",children:o})]},l))})})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Devices"})}),e.jsx(Ie,{children:a.deviceCounts.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No device data."}):e.jsx("ul",{className:"space-y-1.5 text-sm",children:a.deviceCounts.map(([l,o])=>e.jsxs("li",{className:"flex justify-between",children:[e.jsx("span",{className:"capitalize",children:l}),e.jsx("span",{className:"text-muted-foreground",children:o})]},l))})})]})]})]})}const Ymr=[{value:"text",label:"Short Text"},{value:"email",label:"Email"},{value:"phone",label:"Phone"},{value:"textarea",label:"Long Text"},{value:"select",label:"Dropdown"},{value:"multiselect",label:"Multi-Select"},{value:"toggle",label:"Yes / No Toggle"}];let Zmr=0;const L3t=()=>`f_${Date.now()}_${++Zmr}`;function Xmr({field:s,index:t,updateField:n,removeField:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=QMe({id:s.clientId}),u={transform:pP.Transform.toString(o),transition:c,zIndex:d?50:void 0,opacity:d?.85:1};return e.jsx(we,{ref:l,style:u,children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("button",{type:"button",...a,...i,className:"mt-1 p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted cursor-grab active:cursor-grabbing touch-none","aria-label":"Drag to reorder",children:e.jsx(kf,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Field Type"}),e.jsxs(Ns,{value:s.field_type,onValueChange:h=>n(t,{field_type:h}),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsx(js,{children:Ymr.map(h=>e.jsx(et,{value:h.value,children:h.label},h.value))})]})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Label"}),e.jsx(xe,{value:s.label,onChange:h=>n(t,{label:h.target.value}),placeholder:"e.g. Full Name"})]}),e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Placeholder"}),e.jsx(xe,{value:s.placeholder||"",onChange:h=>n(t,{placeholder:h.target.value}),placeholder:"Optional hint text"})]})]}),(s.field_type==="select"||s.field_type==="multiselect")&&e.jsxs("div",{children:[e.jsx(te,{className:"text-xs",children:"Options (comma-separated)"}),e.jsx(xe,{value:s.options?(typeof s.options=="string"?JSON.parse(s.options):s.options).join(", "):"",onChange:h=>n(t,{options:JSON.stringify(h.target.value.split(",").map(m=>m.trim()).filter(Boolean))}),placeholder:"Option 1, Option 2, Option 3"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wn,{checked:s.is_required,onCheckedChange:h=>n(t,{is_required:h})}),e.jsx(te,{className:"text-xs",children:"Required"})]})]}),e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>r(t),children:e.jsx(In,{className:"h-3.5 w-3.5 text-destructive"})})]})})})}function Qmr(){const{pageId:s}=Di(),t=Wn(),{user:n}=vs(),r=Sa(),{toast:a}=Ai(),i=Qt(),[l,o]=j.useState(null),[c,d]=j.useState(!1),{data:u,isLoading:h}=ct({queryKey:["landing-page",s],queryFn:async()=>{const{data:se,error:ne}=await q.from("landing_pages").select("*").eq("id",s).single();if(ne)throw ne;return se},enabled:!!s}),{data:m=[],isLoading:p}=ct({queryKey:["landing-page-fields",s],queryFn:async()=>{const{data:se,error:ne}=await q.from("landing_page_fields").select("*").eq("page_id",s).order("sort_order");if(ne)throw ne;return se},enabled:!!s}),{data:f=[]}=ct({queryKey:["landing-page-submissions",s],queryFn:async()=>{const{data:se,error:ne}=await q.from("landing_page_submissions").select("*").eq("page_id",s).order("created_at",{ascending:!1});if(ne)throw ne;return se},enabled:!!s}),{data:x=[]}=ct({queryKey:["my-listings-for-pages",r],queryFn:async()=>{const{data:se,error:ne}=await q.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, description, status").eq("agent_id",r).order("created_at",{ascending:!1});if(ne)throw ne;return se},enabled:!!n&&((u==null?void 0:u.page_type)==="just_listed"||(u==null?void 0:u.page_type)==="just_sold")}),{data:y=[]}=ct({queryKey:["drips-for-landing",r],queryFn:async()=>{const{data:se}=await q.from("drip_campaigns").select("id, name").eq("owner_user_id",r).eq("is_active",!0).order("name");return se||[]},enabled:!!r}),{data:v}=ct({queryKey:["agent-landing-defaults",r],queryFn:async()=>{const{data:se}=await q.from("agent_landing_page_defaults").select("*").eq("user_id",r).maybeSingle();return se},enabled:!!r}),[b,N]=j.useState({title:"",hero_headline:"",hero_subtext:"",hero_image_url:null,logo_url:null,primary_color:"#406E71",accent_color:"#2a4c64",agent_name:"",agent_phone:"",agent_email:"",agent_photo_url:null,success_message:"Thank you! We'll be in touch soon.",is_published:!1,description:"",lead_magnet_file_url:null,lead_magnet_file_name:null,lead_magnet_external_url:null,listing_id:null,property_address:"",property_price:"",property_beds:"",property_baths:"",property_sqft:"",property_description:"",property_photos:[],property_status:"just_listed",theme_style:"premium",eyebrow:"",headline_accent:"",heading_font:"playfair",trust_pills:["No obligation","100% free","60 seconds or less"],settings_redirect_url:"",settings_auto_responder_subject:"",settings_auto_responder_body:"",settings_drip_campaign_id:null,settings_disable_auto_responder:!1,settings_disable_drip:!1,settings_event_starts_at:"",settings_event_location_name:"",settings_event_address:""}),[S,A]=j.useState([]);j.useEffect(()=>{var se,ne,ie,ce,je,be,he,ge,ke;u&&N({title:u.title,hero_headline:u.hero_headline,hero_subtext:u.hero_subtext||"",hero_image_url:u.hero_image_url,logo_url:u.logo_url,primary_color:u.primary_color,accent_color:u.accent_color,agent_name:u.agent_name||"",agent_phone:u.agent_phone||"",agent_email:u.agent_email||"",agent_photo_url:u.agent_photo_url,success_message:u.success_message||"Thank you! We'll be in touch soon.",is_published:u.is_published,description:u.description||"",lead_magnet_file_url:u.lead_magnet_file_url||null,lead_magnet_file_name:u.lead_magnet_file_name||null,lead_magnet_external_url:u.lead_magnet_external_url||null,listing_id:u.listing_id||null,property_address:u.property_address||"",property_price:u.property_price||"",property_beds:u.property_beds||"",property_baths:u.property_baths||"",property_sqft:u.property_sqft||"",property_description:u.property_description||"",property_photos:Array.isArray(u.property_photos)?u.property_photos:[],property_status:u.property_status||"just_listed",theme_style:u.theme_style||"premium",eyebrow:u.eyebrow||"",headline_accent:u.headline_accent||"",heading_font:u.heading_font||"playfair",trust_pills:Array.isArray(u.trust_pills)?u.trust_pills:["No obligation","100% free","60 seconds or less"],settings_redirect_url:((se=u.settings)==null?void 0:se.redirect_url)||"",settings_auto_responder_subject:((ne=u.settings)==null?void 0:ne.auto_responder_subject)||"",settings_auto_responder_body:((ie=u.settings)==null?void 0:ie.auto_responder_body)||"",settings_drip_campaign_id:((ce=u.settings)==null?void 0:ce.drip_campaign_id)||null,settings_disable_auto_responder:!!((je=u.settings)!=null&&je.disable_auto_responder),settings_disable_drip:!!((be=u.settings)!=null&&be.disable_drip),settings_event_starts_at:((he=u.settings)==null?void 0:he.event_starts_at)||"",settings_event_location_name:((ge=u.settings)==null?void 0:ge.event_location_name)||"",settings_event_address:((ke=u.settings)==null?void 0:ke.event_address)||""})},[u]),j.useEffect(()=>{m.length>0&&A(m.map(se=>({id:se.id,clientId:se.id||L3t(),field_type:se.field_type,label:se.label,placeholder:se.placeholder,is_required:se.is_required,options:typeof se.options=="string"?se.options:se.options?JSON.stringify(se.options):null,sort_order:se.sort_order})))},[m]);const T=yt({mutationFn:async()=>{const{error:se}=await q.from("landing_pages").update({title:b.title,hero_headline:b.hero_headline,hero_subtext:b.hero_subtext||null,hero_image_url:b.hero_image_url,logo_url:b.logo_url,primary_color:b.primary_color,accent_color:b.accent_color,agent_name:b.agent_name||null,agent_phone:b.agent_phone||null,agent_email:b.agent_email||null,agent_photo_url:b.agent_photo_url,success_message:b.success_message,is_published:b.is_published,description:b.description||null,lead_magnet_file_url:b.lead_magnet_file_url,lead_magnet_file_name:b.lead_magnet_file_name,lead_magnet_external_url:b.lead_magnet_external_url,listing_id:b.listing_id,property_address:b.property_address||null,property_price:b.property_price||null,property_beds:b.property_beds||null,property_baths:b.property_baths||null,property_sqft:b.property_sqft||null,property_description:b.property_description||null,property_photos:b.property_photos,property_status:b.property_status,theme_style:b.theme_style,eyebrow:b.eyebrow||null,headline_accent:b.headline_accent||null,heading_font:b.heading_font,trust_pills:b.trust_pills,redirect_url:b.settings_redirect_url||null,auto_responder_enabled:!b.settings_disable_auto_responder,auto_responder_subject:b.settings_auto_responder_subject||null,auto_responder_body:b.settings_auto_responder_body||null,drip_campaign_id:b.settings_disable_drip?null:b.settings_drip_campaign_id||null,settings:{...(u==null?void 0:u.settings)||{},redirect_url:b.settings_redirect_url||null,auto_responder_subject:b.settings_auto_responder_subject||null,auto_responder_body:b.settings_auto_responder_body||null,drip_campaign_id:b.settings_drip_campaign_id||null,disable_auto_responder:!!b.settings_disable_auto_responder,disable_drip:!!b.settings_disable_drip,event_starts_at:b.settings_event_starts_at||null,event_location_name:b.settings_event_location_name||null,event_address:b.settings_event_address||null},updated_at:new Date().toISOString()}).eq("id",s);if(se)throw se;if(await q.from("landing_page_fields").delete().eq("page_id",s),S.length>0){const{error:ne}=await q.from("landing_page_fields").insert(S.map((ie,ce)=>({page_id:s,field_type:ie.field_type,label:ie.label,placeholder:ie.placeholder||null,is_required:ie.is_required,options:ie.options?JSON.parse(ie.options):null,sort_order:ce})));if(ne)throw ne}},onSuccess:()=>{i.invalidateQueries({queryKey:["landing-page",s]}),i.invalidateQueries({queryKey:["landing-page-fields",s]}),a({title:"Page saved!"})},onError:se=>a({title:"Error",description:se.message,variant:"destructive"})}),L=async(se,ne)=>{const ie=se.name.split(".").pop(),ce=`landing-pages/${n.id}/${ne}-${Date.now()}.${ie}`,{error:je}=await q.storage.from("recruit-landing").upload(ce,se);if(je)throw je;const{data:{publicUrl:be}}=q.storage.from("recruit-landing").getPublicUrl(ce);return be},M=async(se,ne)=>{var ce;const ie=(ce=se.target.files)==null?void 0:ce[0];if(ie){o(ne);try{const je=await L(ie,ne);N(be=>({...be,[ne]:je})),a({title:"Image uploaded!"})}catch(je){a({title:"Upload failed",description:je.message,variant:"destructive"})}finally{o(null)}}},I=async se=>{var ie;const ne=(ie=se.target.files)==null?void 0:ie[0];if(ne){o("lead_magnet");try{const ce=await L(ne,"lead-magnet");N(je=>({...je,lead_magnet_file_url:ce,lead_magnet_file_name:ne.name})),a({title:"File uploaded!"})}catch(ce){a({title:"Upload failed",description:ce.message,variant:"destructive"})}finally{o(null)}}},R=async se=>{const ne=se.target.files;if(!(!ne||ne.length===0)){o("property_photos");try{const ie=[];for(const ce of Array.from(ne)){const je=await L(ce,"property-photo");ie.push(je)}N(ce=>({...ce,property_photos:[...ce.property_photos,...ie]})),a({title:`${ie.length} photo(s) uploaded!`})}catch(ie){a({title:"Upload failed",description:ie.message,variant:"destructive"})}finally{o(null)}}},z=async se=>{const ne=x.find(ce=>ce.id===se);if(!ne)return;const{data:ie}=await q.from("listing_photos").select("photo_url").eq("listing_id",se).order("sort_order");N(ce=>({...ce,listing_id:se,property_address:ne.property_address||`${ne.city}, ${ne.state}`,property_price:ne.price?`$${ne.price.toLocaleString()}`:"",property_beds:ne.bedrooms?String(ne.bedrooms):"",property_baths:ne.bathrooms?String(ne.bathrooms):"",property_sqft:ne.square_footage?ne.square_footage.toLocaleString():"",property_description:ne.description||"",property_photos:(ie==null?void 0:ie.map(je=>je.photo_url))||ce.property_photos})),a({title:"Listing data imported!"})},$=()=>{A(se=>[...se,{clientId:L3t(),field_type:"text",label:"",placeholder:"",is_required:!1,options:null,sort_order:se.length}])},H=(se,ne)=>{A(ie=>ie.map((ce,je)=>je===se?{...ce,...ne}:ce))},V=se=>{A(ne=>ne.filter((ie,ce)=>ce!==se))},K=$Me(HV(SG,{activationConstraint:{distance:6}}),HV(GMe,{coordinateGetter:FFt})),Z=se=>{const{active:ne,over:ie}=se;!ie||ne.id===ie.id||A(ce=>{const je=ce.findIndex(he=>he.clientId===ne.id),be=ce.findIndex(he=>he.clientId===ie.id);return je<0||be<0?ce:ZMe(ce,je,be).map((he,ge)=>({...he,sort_order:ge}))})},Q=u?`https://pages.relevelup.com/${u.slug}`:"",le=(u==null?void 0:u.page_type)==="lead_magnet",ue=(u==null?void 0:u.page_type)==="just_listed"||(u==null?void 0:u.page_type)==="just_sold";return h||p?e.jsx(qs,{title:"Loading...",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):u?e.jsxs(qs,{title:b.title||"Edit Page",children:[e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/landing-pages"),children:e.jsx(Aa,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold",children:b.title||"Untitled Page"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsx(Be,{variant:b.is_published?"default":"secondary",className:"text-[10px]",children:b.is_published?"Published":"Draft"}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(xa,{className:"h-3 w-3"})," ",u.view_count," views"]}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3 w-3"})," ",f.length," submissions"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[b.is_published&&e.jsxs(e.Fragment,{children:[e.jsx(U,{size:"sm",variant:"outline",onClick:()=>d(!0),children:e.jsx(Sf,{className:"h-3.5 w-3.5"})}),e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(Q),a({title:"Link copied!"})},children:[e.jsx(Pa,{className:"h-3.5 w-3.5 mr-1"})," Copy Link"]}),e.jsx(U,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:Q,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Sr,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(U,{onClick:()=>T.mutate(),disabled:T.isPending,children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"}),T.isPending?"Saving...":"Save"]})]})]}),e.jsxs(oa,{defaultValue:"design",children:[e.jsxs(la,{children:[e.jsx(Kt,{value:"design",children:"Design"}),le&&e.jsx(Kt,{value:"lead_magnet",children:"Lead Magnet"}),ue&&e.jsx(Kt,{value:"property",children:"Property Details"}),e.jsxs(Kt,{value:"fields",children:["Form Fields (",S.length,")"]}),e.jsxs(Kt,{value:"submissions",children:["Submissions (",f.length,")"]}),e.jsx(Kt,{value:"automation",children:"Automation"}),e.jsx(Kt,{value:"analytics",children:"Analytics"}),e.jsx(Kt,{value:"settings",children:"Settings"})]}),e.jsxs(Zt,{value:"design",className:"space-y-4 mt-4",children:[e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Page Details"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Page Title (internal)"}),e.jsx(xe,{value:b.title,onChange:se=>N(ne=>({...ne,title:se.target.value}))})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Description (internal)"}),e.jsx(xe,{value:b.description,onChange:se=>N(ne=>({...ne,description:se.target.value}))})]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:["Theme & Style",e.jsx(Be,{variant:"secondary",className:"text-[10px]",children:"New"})]})}),e.jsxs(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(te,{children:"Theme Style"}),e.jsxs(Ns,{value:b.theme_style,onValueChange:se=>N(ne=>({...ne,theme_style:se})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"premium",children:"Premium — cinematic + glass form"}),e.jsx(et,{value:"classic",children:"Classic — centered card"})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Headline Font"}),e.jsxs(Ns,{value:b.heading_font,onValueChange:se=>N(ne=>({...ne,heading_font:se})),children:[e.jsx(ws,{children:e.jsx(ks,{})}),e.jsxs(js,{children:[e.jsx(et,{value:"playfair",children:"Playfair Display (editorial serif)"}),e.jsx(et,{value:"baskerville",children:"Libre Baskerville (classic serif)"}),e.jsx(et,{value:"instrument",children:"Instrument Serif (modern serif)"}),e.jsx(et,{value:"sans",children:"Inter (clean sans-serif)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Trust Pills (comma separated, shown under CTA)"}),e.jsx(xe,{value:b.trust_pills.join(", "),onChange:se=>N(ne=>({...ne,trust_pills:se.target.value.split(",").map(ie=>ie.trim()).filter(Boolean)})),placeholder:"No obligation, 100% free, 60 seconds or less"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Premium theme uses a cinematic full-screen hero, italic accent word, glass-effect form, and trust pills — magazine-style."})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Hero Section"})}),e.jsxs(Ie,{className:"space-y-4",children:[b.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(te,{children:"Eyebrow (small label above headline)"}),e.jsx(xe,{value:b.eyebrow,onChange:se=>N(ne=>({...ne,eyebrow:se.target.value})),placeholder:"HOME VALUE"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Headline"}),e.jsx(xe,{value:b.hero_headline,onChange:se=>N(ne=>({...ne,hero_headline:se.target.value})),placeholder:"What Is Your Home"})]}),b.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(te,{children:"Accent Word(s) — italic & colored (optional)"}),e.jsx(xe,{value:b.headline_accent,onChange:se=>N(ne=>({...ne,headline_accent:se.target.value})),placeholder:"Actually Worth?"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Subtext"}),e.jsx(Fs,{value:b.hero_subtext,onChange:se=>N(ne=>({...ne,hero_subtext:se.target.value})),rows:3,placeholder:"A brief description..."})]}),e.jsxs("div",{children:[e.jsxs(te,{children:["Background Image ",b.theme_style==="premium"&&e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"(dusk/cinematic recommended)"})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[b.hero_image_url&&e.jsx("img",{src:b.hero_image_url,alt:"Hero",className:"h-16 w-28 object-cover rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(U,{variant:"outline",size:"sm",asChild:!0,disabled:l==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(qa,{className:"h-3.5 w-3.5 mr-1"}),l==="hero_image_url"?"Uploading...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:se=>M(se,"hero_image_url")})]}),b.hero_image_url&&e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>N(se=>({...se,hero_image_url:null})),children:e.jsx(In,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Branding"})}),e.jsxs(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(te,{children:"Logo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[b.logo_url&&e.jsx("img",{src:b.logo_url,alt:"Logo",className:"h-10 w-auto rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(U,{variant:"outline",size:"sm",asChild:!0,disabled:l==="logo_url",children:e.jsxs("span",{children:[e.jsx(qa,{className:"h-3.5 w-3.5 mr-1"}),l==="logo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:se=>M(se,"logo_url")})]})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[b.agent_photo_url&&e.jsx("img",{src:b.agent_photo_url,alt:"Agent",className:"h-10 w-10 rounded-full object-cover"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(U,{variant:"outline",size:"sm",asChild:!0,disabled:l==="agent_photo_url",children:e.jsxs("span",{children:[e.jsx(qa,{className:"h-3.5 w-3.5 mr-1"}),l==="agent_photo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:se=>M(se,"agent_photo_url")})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Primary Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:b.primary_color,onChange:se=>N(ne=>({...ne,primary_color:se.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(xe,{value:b.primary_color,onChange:se=>N(ne=>({...ne,primary_color:se.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Accent Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:b.accent_color,onChange:se=>N(ne=>({...ne,accent_color:se.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(xe,{value:b.accent_color,onChange:se=>N(ne=>({...ne,accent_color:se.target.value})),className:"font-mono text-xs"})]})]})]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Agent Info (shown on page)"})}),e.jsx(Ie,{className:"space-y-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Name"}),e.jsx(xe,{value:b.agent_name,onChange:se=>N(ne=>({...ne,agent_name:se.target.value}))})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Phone"}),e.jsx(xe,{value:b.agent_phone,onChange:se=>N(ne=>({...ne,agent_phone:se.target.value}))})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Email"}),e.jsx(xe,{value:b.agent_email,onChange:se=>N(ne=>({...ne,agent_email:se.target.value}))})]})]})})]})]}),le&&e.jsx(Zt,{value:"lead_magnet",className:"space-y-4 mt-4",children:e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(pi,{className:"h-4 w-4"})," Giveaway File"]})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload a file or provide an external URL. Visitors will receive the download link after submitting the form."}),e.jsxs("div",{children:[e.jsx(te,{children:"Upload File (PDF, guide, checklist, etc.)"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[b.lead_magnet_file_name&&e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(pi,{className:"h-3 w-3"})," ",b.lead_magnet_file_name]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(U,{variant:"outline",size:"sm",asChild:!0,disabled:l==="lead_magnet",children:e.jsxs("span",{children:[e.jsx(qa,{className:"h-3.5 w-3.5 mr-1"}),l==="lead_magnet"?"Uploading...":"Upload File"]})}),e.jsx("input",{type:"file",className:"hidden",onChange:I})]}),b.lead_magnet_file_url&&e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>N(se=>({...se,lead_magnet_file_url:null,lead_magnet_file_name:null})),children:e.jsx(In,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("div",{className:"flex-1 border-t"}),e.jsx("span",{children:"OR"}),e.jsx("div",{className:"flex-1 border-t"})]}),e.jsxs("div",{children:[e.jsxs(te,{className:"flex items-center gap-1",children:[e.jsx(ad,{className:"h-3.5 w-3.5"})," External URL"]}),e.jsx(xe,{value:b.lead_magnet_external_url||"",onChange:se=>N(ne=>({...ne,lead_magnet_external_url:se.target.value||null})),placeholder:"https://drive.google.com/... or https://dropbox.com/...",className:"mt-1"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Link to a file on Google Drive, Dropbox, or any URL"})]})]})]})}),ue&&e.jsxs(Zt,{value:"property",className:"space-y-4 mt-4",children:[e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsxs(It,{className:"text-base flex items-center gap-2",children:[e.jsx(ra,{className:"h-4 w-4"})," Import from Listing Exchange"]})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pull property details and photos directly from one of your listings, or enter them manually below."}),e.jsxs(Ns,{value:b.listing_id||"",onValueChange:se=>z(se),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Select a listing to import..."})}),e.jsx(js,{children:x.map(se=>{var ne;return e.jsxs(et,{value:se.id,children:[se.property_address||`${se.city}, ${se.state}`," — $",(ne=se.price)==null?void 0:ne.toLocaleString()]},se.id)})})]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Property Information"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Property Address"}),e.jsx(xe,{value:b.property_address,onChange:se=>N(ne=>({...ne,property_address:se.target.value})),placeholder:"123 Main St, City, State"})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Price"}),e.jsx(xe,{value:b.property_price,onChange:se=>N(ne=>({...ne,property_price:se.target.value})),placeholder:"$450,000"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Beds"}),e.jsx(xe,{value:b.property_beds,onChange:se=>N(ne=>({...ne,property_beds:se.target.value})),placeholder:"4"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Baths"}),e.jsx(xe,{value:b.property_baths,onChange:se=>N(ne=>({...ne,property_baths:se.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Sq Ft"}),e.jsx(xe,{value:b.property_sqft,onChange:se=>N(ne=>({...ne,property_sqft:se.target.value})),placeholder:"2,400"})]})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Description"}),e.jsx(Fs,{value:b.property_description,onChange:se=>N(ne=>({...ne,property_description:se.target.value})),rows:3,placeholder:"Beautiful home in a great neighborhood..."})]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Property Photos"})}),e.jsxs(Ie,{className:"space-y-4",children:[b.property_photos.length>0&&e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-4 gap-2",children:b.property_photos.map((se,ne)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:se,alt:`Property ${ne+1}`,className:"h-24 w-full object-cover rounded"}),e.jsx(U,{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:()=>N(ie=>({...ie,property_photos:ie.property_photos.filter((ce,je)=>je!==ne)})),children:e.jsx(In,{className:"h-3 w-3"})})]},ne))}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(U,{variant:"outline",size:"sm",asChild:!0,disabled:l==="property_photos",children:e.jsxs("span",{children:[e.jsx(qa,{className:"h-3.5 w-3.5 mr-1"}),l==="property_photos"?"Uploading...":"Add Photos"]})}),e.jsx("input",{type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:R})]})]})]})]}),e.jsxs(Zt,{value:"fields",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure the form fields visitors will fill out"}),e.jsxs(U,{size:"sm",onClick:$,children:[e.jsx(an,{className:"h-3.5 w-3.5 mr-1"})," Add Field"]})]}),S.length===0?e.jsx(we,{children:e.jsx(Ie,{className:"py-8 text-center text-muted-foreground",children:"No fields yet. Add fields to build your form."})}):e.jsx(YMe,{sensors:K,collisionDetection:VMe,onDragEnd:Z,children:e.jsx(XMe,{items:S.map(se=>se.clientId),strategy:s7s,children:e.jsx("div",{className:"space-y-3",children:S.map((se,ne)=>e.jsx(Xmr,{field:se,index:ne,updateField:H,removeField:V},se.clientId))})})})]}),e.jsx(Zt,{value:"submissions",className:"mt-4",children:f.length===0?e.jsx(we,{children:e.jsx(Ie,{className:"py-12 text-center text-muted-foreground",children:"No submissions yet. Share your page to start collecting leads!"})}):e.jsx("div",{className:"space-y-3",children:f.map(se=>e.jsx(we,{children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:se.contact_name||"Anonymous"}),se.synced_to_crm&&e.jsx(Be,{variant:"outline",className:"text-[10px]",children:"Synced"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[se.contact_email&&e.jsx("span",{className:"mr-3",children:se.contact_email}),se.contact_phone&&e.jsx("span",{children:se.contact_phone})]}),se.answers&&typeof se.answers=="object"&&e.jsx("div",{className:"mt-2 text-sm space-y-1",children:Object.entries(se.answers).map(([ne,ie])=>e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium text-muted-foreground",children:[ne,":"]})," ",e.jsx("span",{children:String(ie)})]},ne))})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(se.created_at).toLocaleDateString()})]})})},se.id))})}),e.jsxs(Zt,{value:"automation",className:"space-y-4 mt-4",children:[(u==null?void 0:u.page_type)==="event_registration"&&e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-base",children:"Event details"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown to visitors as a live countdown with add-to-calendar buttons."})]}),e.jsxs(Ie,{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5 md:col-span-2",children:[e.jsx(te,{children:"Starts at"}),e.jsx(xe,{type:"datetime-local",value:b.settings_event_starts_at,onChange:se=>N(ne=>({...ne,settings_event_starts_at:se.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Venue / location name"}),e.jsx(xe,{placeholder:"e.g. The Grand Hotel",value:b.settings_event_location_name,onChange:se=>N(ne=>({...ne,settings_event_location_name:se.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(te,{children:"Address (for map link)"}),e.jsx(xe,{placeholder:"123 Main St, City, ST",value:b.settings_event_address,onChange:se=>N(ne=>({...ne,settings_event_address:se.target.value}))})]})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-base",children:"Instant auto-reply to lead"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sent the moment someone submits this page. Leave blank to use your",v!=null&&v.default_auto_responder_body?" account default":" built-in template",". Merge fields: ",e.jsx("code",{children:"{{client_first_name}}"}),", ",e.jsx("code",{children:"{{agent_name}}"}),", ",e.jsx("code",{children:"{{page_title}}"}),", ",e.jsx("code",{children:"{{calendar_link}}"}),"."]})]}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{children:"Send auto-reply for this page"}),e.jsx(wn,{checked:!b.settings_disable_auto_responder,onCheckedChange:se=>N(ne=>({...ne,settings_disable_auto_responder:!se}))})]}),!b.settings_disable_auto_responder&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(te,{children:"Subject (override)"}),e.jsx(xe,{value:b.settings_auto_responder_subject,onChange:se=>N(ne=>({...ne,settings_auto_responder_subject:se.target.value})),placeholder:(v==null?void 0:v.default_auto_responder_subject)||"Thanks for reaching out, {{client_first_name}}!"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Body (override)"}),e.jsx(Fs,{rows:8,value:b.settings_auto_responder_body,onChange:se=>N(ne=>({...ne,settings_auto_responder_body:se.target.value})),placeholder:(v==null?void 0:v.default_auto_responder_body)||`Hi {{client_first_name}}, Thanks for reaching out…`})]})]})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{className:"text-base",children:"Smart Drip enrollment"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Automatically enroll every new lead into a drip campaign.",(v==null?void 0:v.default_drip_campaign_id)&&" Account default applies if no override is selected."]})]}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(te,{children:"Enroll new leads in a drip"}),e.jsx(wn,{checked:!b.settings_disable_drip,onCheckedChange:se=>N(ne=>({...ne,settings_disable_drip:!se}))})]}),!b.settings_disable_drip&&e.jsxs("div",{children:[e.jsx(te,{children:"Drip override for this page"}),e.jsxs("select",{className:"mt-1 w-full rounded-md border bg-background px-3 py-2 text-sm",value:b.settings_drip_campaign_id||"",onChange:se=>N(ne=>({...ne,settings_drip_campaign_id:se.target.value||null})),children:[e.jsx("option",{value:"",children:"— Use account default —"}),y.map(se=>e.jsx("option",{value:se.id,children:se.name},se.id))]})]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Redirect after submit"})}),e.jsxs(Ie,{children:[e.jsx(xe,{value:b.settings_redirect_url,onChange:se=>N(ne=>({...ne,settings_redirect_url:se.target.value})),placeholder:(v==null?void 0:v.default_redirect_url)||"https://your-site.com/thank-you (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Leave blank to keep the inline Thank-You message."})]})]})]}),e.jsx(Zt,{value:"analytics",className:"space-y-4 mt-4",children:e.jsx(Kmr,{pageId:s})}),e.jsxs(Zt,{value:"settings",className:"space-y-4 mt-4",children:[e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Publishing"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Published"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Make this page publicly accessible"})]}),e.jsx(wn,{checked:b.is_published,onCheckedChange:se=>N(ne=>({...ne,is_published:se}))})]}),b.is_published&&e.jsxs("div",{className:"p-3 bg-muted/50 rounded-lg border",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Public URL:"}),e.jsx("code",{className:"text-xs ml-2 break-all",children:Q})]})]})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{className:"text-base",children:"Thank You Message"})}),e.jsx(Ie,{children:e.jsx(Fs,{value:b.success_message,onChange:se=>N(ne=>({...ne,success_message:se.target.value})),rows:2,placeholder:"Message shown after form submission"})})]})]})]})]}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Ds,{className:"max-w-sm",children:[e.jsx(Vs,{children:e.jsx($s,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx(fS,{value:Q,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:Q})]})]})})]}):e.jsx(qs,{title:"Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Page not found"}),e.jsx(U,{variant:"link",onClick:()=>t("/mission-control/landing-pages"),children:"Go back"})]})})}const Jmr={default_auto_responder_subject:"",default_auto_responder_body:"",default_drip_campaign_id:null,default_redirect_url:"",default_calendar_link:"",text_agent_on_lead:!1,agent_sms_phone:"",use_brand_kit:!0},epr=`Hi {{client_first_name}}, Thanks for reaching out — I've got your information and will personally follow up within one business day. If it's easier, you can also call or text me directly at {{agent_phone}}. Talk soon, {{agent_name}}`;function tpr(){const s=Sa(),{toast:t}=Ai(),n=Wn(),r=Qt(),[a,i]=j.useState(Jmr),{data:l}=ct({queryKey:["landing-page-defaults",s],queryFn:async()=>{const{data:d}=await q.from("agent_landing_page_defaults").select("*").eq("user_id",s).maybeSingle();return d||null},enabled:!!s}),{data:o=[]}=ct({queryKey:["drip-campaigns-mine",s],queryFn:async()=>{const{data:d}=await q.from("drip_campaigns").select("id, name").eq("owner_user_id",s).eq("is_active",!0).order("name");return d||[]},enabled:!!s});j.useEffect(()=>{l&&i({default_auto_responder_subject:l.default_auto_responder_subject??"",default_auto_responder_body:l.default_auto_responder_body??"",default_drip_campaign_id:l.default_drip_campaign_id??null,default_redirect_url:l.default_redirect_url??"",default_calendar_link:l.default_calendar_link??"",text_agent_on_lead:!!l.text_agent_on_lead,agent_sms_phone:l.agent_sms_phone??"",use_brand_kit:l.use_brand_kit??!0})},[l]);const c=yt({mutationFn:async()=>{const{error:d}=await q.from("agent_landing_page_defaults").upsert({user_id:s,...a},{onConflict:"user_id"});if(d)throw d},onSuccess:()=>{r.invalidateQueries({queryKey:["landing-page-defaults"]}),t({title:"Defaults saved"})},onError:d=>t({title:"Save failed",description:d.message,variant:"destructive"})});return e.jsx(qs,{title:"Landing Page Defaults",children:e.jsxs("div",{className:"space-y-6 max-w-3xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>n("/mission-control/landing-pages"),children:[e.jsx(Aa,{className:"h-4 w-4 mr-1"})," Back to pages"]}),e.jsxs(U,{onClick:()=>c.mutate(),disabled:c.isPending,children:[e.jsx(Ho,{className:"h-4 w-4 mr-2"})," ",c.isPending?"Saving…":"Save Defaults"]})]}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Landing Page Defaults"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"These run on every landing page automatically. Any page can override them in its own settings."})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"Instant auto-reply to the lead"}),e.jsxs(Jn,{children:["Sent the moment someone submits one of your pages. Uses your Gmail if connected, otherwise your verified sender. Merge fields: ",e.jsx("code",{children:"{{client_first_name}}"}),", ",e.jsx("code",{children:"{{agent_name}}"}),", ",e.jsx("code",{children:"{{agent_phone}}"}),", ",e.jsx("code",{children:"{{page_title}}"}),", ",e.jsx("code",{children:"{{calendar_link}}"}),"."]})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Subject"}),e.jsx(xe,{value:a.default_auto_responder_subject||"",onChange:d=>i(u=>({...u,default_auto_responder_subject:d.target.value})),placeholder:"Thanks for reaching out, {{client_first_name}}!"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Message body"}),e.jsx(Fs,{rows:10,value:a.default_auto_responder_body||"",onChange:d=>i(u=>({...u,default_auto_responder_body:d.target.value})),placeholder:epr}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Leave blank to use the polished built-in template that adapts to each page type."})]})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"Default Smart Drip"}),e.jsx(Jn,{children:"Every new lead drops into this drip unless a page overrides it."})]}),e.jsx(Ie,{children:e.jsxs(Ns,{value:a.default_drip_campaign_id||"none",onValueChange:d=>i(u=>({...u,default_drip_campaign_id:d==="none"?null:d})),children:[e.jsx(ws,{children:e.jsx(ks,{placeholder:"Pick a drip…"})}),e.jsxs(js,{children:[e.jsx(et,{value:"none",children:"— No default drip —"}),o.map(d=>e.jsx(et,{value:d.id,children:d.name},d.id))]})]})})]}),e.jsxs(we,{children:[e.jsx(Tt,{children:e.jsx(It,{children:"Defaults for every page"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(te,{children:"Default booking / calendar link"}),e.jsx(xe,{value:a.default_calendar_link||"",onChange:d=>i(u=>({...u,default_calendar_link:d.target.value})),placeholder:"https://calendly.com/your-name/intro"})]}),e.jsxs("div",{children:[e.jsx(te,{children:"Default redirect after submit (optional)"}),e.jsx(xe,{value:a.default_redirect_url||"",onChange:d=>i(u=>({...u,default_redirect_url:d.target.value})),placeholder:"https://your-site.com/thanks"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(te,{className:"text-base",children:"Use my brand kit colors"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"New pages pick up your brand colors/logo automatically."})]}),e.jsx(wn,{checked:a.use_brand_kit,onCheckedChange:d=>i(u=>({...u,use_brand_kit:d}))})]})]})]}),e.jsxs(we,{children:[e.jsxs(Tt,{children:[e.jsx(It,{children:"Text me when a lead submits"}),e.jsx(Jn,{children:"Get an SMS the second a lead hits your inbox. Coming soon — requires SMS sender setup."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx(te,{className:"text-base",children:"SMS me new leads"}),e.jsx(wn,{checked:a.text_agent_on_lead,onCheckedChange:d=>i(u=>({...u,text_agent_on_lead:d}))})]}),a.text_agent_on_lead&&e.jsxs("div",{children:[e.jsx(te,{children:"Phone number for alerts"}),e.jsx(xe,{type:"tel",value:a.agent_sms_phone||"",onChange:d=>i(u=>({...u,agent_sms_phone:d.target.value})),placeholder:"(555) 123-4567"})]})]})]})]})})}function bas({hasLeadSite:s}){const t=Wn(),n=Qt(),[r,a]=j.useState(!1),{offer:i}=fMe(!s);if(s||!i)return null;const l=async()=>{a(!0);try{const{data:o,error:c}=await q.functions.invoke("claim-free-lead-site",{body:{}});if(c)throw c;if(o!=null&&o.error)throw new Error(o.error);await n.invalidateQueries({queryKey:["agent-lead-site"]}),re.success("Your website is live! Let’s make it yours."),t(`/admin/lead-sites/${o.siteId}/edit`)}catch(o){re.error((o==null?void 0:o.message)||"Could not create your website")}finally{a(!1)}};return e.jsx(we,{className:"p-6 border-2 border-amber-300 bg-gradient-to-br from-amber-50 via-background to-background",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"w-11 h-11 rounded-xl bg-gradient-to-br from-amber-400 to-amber-600 text-white flex items-center justify-center flex-shrink-0",children:e.jsx(h0,{className:"w-5 h-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-base",children:i.offer_headline||"Claim your free luxury website"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:i.offer_description||"A designer luxury website included with your brokerage — your bio, your branding, your Listing Exchange listings and lead capture. Upgrade any time to add full MLS home search."}),e.jsx("ul",{className:"mt-3 space-y-1.5",children:["Luxury design, fully editable in the Site Builder","Your own listings featured automatically","Blog, city pages, contact and lead capture included"].map(o=>e.jsxs("li",{className:"flex items-start gap-2 text-xs text-muted-foreground",children:[e.jsx(cn,{className:"w-3.5 h-3.5 mt-0.5 text-amber-500 shrink-0"}),o]},o))}),e.jsxs("div",{className:"flex items-center gap-3 mt-4",children:[e.jsx(U,{onClick:l,disabled:r,children:r?"Creating your site…":"Claim my free website"}),e.jsxs("a",{href:"https://danicapatton.thelocalmove.com",target:"_blank",rel:"noreferrer",className:"text-xs text-muted-foreground hover:text-foreground inline-flex items-center gap-1",children:["See an example ",e.jsx(Sr,{className:"w-3 h-3"})]})]})]})]})})}function spr(){return ct({queryKey:["website-apps"],queryFn:async()=>{const{data:s,error:t}=await q.from("website_apps").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s||[]}})}function d8e(){const{user:s}=vs();return ct({queryKey:["agent-website-app-installs",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await q.from("agent_website_app_installs").select("*").eq("user_id",s.id);if(n)throw n;return t||[]},enabled:!!(s!=null&&s.id)})}function u8e(){const{user:s}=vs(),t=Qt();return yt({mutationFn:async({app_slug:n,enabled:r})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:a}=await q.from("agent_website_app_installs").upsert({user_id:s.id,app_slug:n,enabled:r},{onConflict:"user_id,app_slug"});if(a)throw a},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["agent-website-app-installs"]}),re.success(r.enabled?"App installed":"App turned off")},onError:n=>re.error(n.message||"Failed to update app")})}const npr={video_greeter:{gradient:"from-rose-500 via-fuchsia-500 to-indigo-500",iconBg:"bg-gradient-to-br from-rose-500 to-fuchsia-600",iconText:"text-white",ring:"hover:ring-fuchsia-400/50",chip:"bg-fuchsia-100 text-fuchsia-700"},exit_popup:{gradient:"from-amber-400 via-orange-500 to-red-500",iconBg:"bg-gradient-to-br from-amber-400 to-orange-600",iconText:"text-white",ring:"hover:ring-orange-400/50",chip:"bg-orange-100 text-orange-700"},chatbot:{gradient:"from-emerald-400 via-teal-500 to-cyan-600",iconBg:"bg-gradient-to-br from-emerald-500 to-teal-600",iconText:"text-white",ring:"hover:ring-teal-400/50",chip:"bg-teal-100 text-teal-700"},lead_magnet:{gradient:"from-sky-400 via-blue-500 to-indigo-600",iconBg:"bg-gradient-to-br from-sky-500 to-indigo-600",iconText:"text-white",ring:"hover:ring-blue-400/50",chip:"bg-blue-100 text-blue-700"}},rpr={gradient:"from-violet-500 via-purple-500 to-pink-500",iconBg:"bg-gradient-to-br from-violet-500 to-purple-600",iconText:"text-white",ring:"hover:ring-violet-400/50",chip:"bg-violet-100 text-violet-700"};function apr(){const s=Wn(),{data:t=[],isLoading:n}=spr(),{data:r=[]}=d8e(),{hasLeadSite:a,siteUrl:i,isLoading:l}=$p(),o=u8e(),[c,d]=j.useState(!1),u=m=>{var p;return((p=r.find(f=>f.app_slug===m))==null?void 0:p.enabled)??!1},h=m=>r.some(p=>p.app_slug===m);return e.jsxs(qs,{title:"Website Apps",description:"Conversion-boosting widgets for your website",children:[e.jsxs("div",{className:"max-w-6xl mx-auto p-6 lg:p-8 space-y-8",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-3xl bg-gradient-to-br from-indigo-600 via-fuchsia-600 to-rose-500 p-8 lg:p-10 shadow-xl",children:[e.jsx("div",{className:"absolute -top-20 -right-20 w-72 h-72 rounded-full bg-white/10 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-24 -left-16 w-80 h-80 rounded-full bg-fuchsia-300/20 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/15 backdrop-blur-sm text-white text-xs font-semibold uppercase tracking-wider mb-4",children:[e.jsx(Af,{className:"w-3.5 h-3.5"})," Boost conversions on autopilot"]}),e.jsxs("h1",{className:"text-3xl lg:text-4xl font-extrabold tracking-tight text-white flex items-center gap-3",children:[e.jsx(cn,{className:"w-8 h-8 text-yellow-300 drop-shadow"}),"Website Apps"]}),e.jsx("p",{className:"text-white/90 mt-2 max-w-2xl text-base lg:text-lg",children:"Drop-in widgets that turn website visitors into leads. Add them to your Lead Site or embed on your own website with one line of code."}),e.jsxs(U,{onClick:()=>d(!0),className:"mt-5 bg-white text-indigo-700 hover:bg-white/90 shadow-lg font-semibold gap-2",children:[e.jsx($h,{className:"w-5 h-5"}),"Watch: How to use Website Apps"]})]})]}),e.jsx(bas,{hasLeadSite:a}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(we,{className:`p-5 border-2 ${a?"border-emerald-200 bg-emerald-50/50":"border-dashed border-muted"}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`w-11 h-11 rounded-xl flex items-center justify-center flex-shrink-0 ${a?"bg-emerald-500 text-white":"bg-muted text-muted-foreground"}`,children:e.jsx(fl,{className:"w-5 h-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Option 1 — The Local Move Websites"}),a&&e.jsxs(Be,{className:"bg-emerald-100 text-emerald-700 hover:bg-emerald-100 text-[10px] gap-1",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"})," Auto-installed"]})]}),a&&i?e.jsxs("a",{href:i,target:"_blank",rel:"noreferrer",className:"text-xs text-emerald-700 hover:underline inline-flex items-center gap-1 mt-1",children:[i.replace(/^https?:\/\//,"")," ",e.jsx(Sr,{className:"w-3 h-3"})]}):e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Don't have a Local Move website yet? Visit"," ",e.jsxs("a",{href:"https://www.thelocalmove.com",target:"_blank",rel:"noreferrer",className:"text-primary font-medium hover:underline inline-flex items-center gap-0.5",children:["www.thelocalmove.com ",e.jsx(Sr,{className:"w-3 h-3"})]})," ","to learn more — apps install automatically once you have one."]})]})]})}),e.jsx(we,{className:"p-5 border-2 border-indigo-200 bg-indigo-50/40",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"w-11 h-11 rounded-xl bg-gradient-to-br from-indigo-500 to-fuchsia-600 text-white flex items-center justify-center flex-shrink-0",children:e.jsx(PC,{className:"w-5 h-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Option 2 — Your existing website"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Already have a site (Wix, Squarespace, WordPress, custom)? Paste a one-line snippet and the widget appears anywhere."}),e.jsx("p",{className:"text-[11px] text-indigo-700 mt-2 font-medium",children:'Open any app below → "Install on my website" tab to copy your code.'})]})]})})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading apps..."}):e.jsx("div",{className:"grid gap-5 sm:grid-cols-2 lg:grid-cols-3",children:t.map(m=>{const p=b6e[m.icon||"Sparkles"]||cn,f=u(m.slug),x=h(m.slug),y=m.status==="coming_soon",v=npr[m.slug]||rpr;return e.jsxs(we,{className:`group relative overflow-hidden border-0 ring-1 ring-border ${v.ring} hover:ring-2 transition-all hover:shadow-xl ${y?"opacity-70":""}`,children:[e.jsx("div",{className:`h-1.5 w-full bg-gradient-to-r ${v.gradient}`}),e.jsxs("div",{className:"p-5 flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:`w-14 h-14 rounded-2xl ${v.iconBg} ${v.iconText} flex items-center justify-center shadow-md group-hover:scale-105 transition-transform`,children:e.jsx(p,{className:"w-7 h-7"})}),y?e.jsx(Be,{variant:"secondary",children:"Coming soon"}):f?e.jsxs(Be,{className:"bg-emerald-100 text-emerald-700 hover:bg-emerald-100 gap-1",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"}),"Live"]}):x?e.jsx(Be,{variant:"outline",children:"Paused"}):e.jsx(Be,{className:v.chip+" hover:"+v.chip,children:"New"})]}),e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsx("h3",{className:"font-bold text-lg",children:m.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:m.description})]}),!y&&e.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wn,{checked:f,onCheckedChange:b=>o.mutate({app_slug:m.slug,enabled:b})}),e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:f?"On":"Off"})]}),e.jsxs(U,{size:"sm",className:`bg-gradient-to-r ${v.gradient} text-white hover:opacity-90 shadow-md border-0`,onClick:()=>s(`/website-apps/${m.slug}`),children:[e.jsx(qc,{className:"w-3.5 h-3.5 mr-1.5"}),"Configure",e.jsx(Oa,{className:"w-3.5 h-3.5 ml-1"})]})]})]})]},m.id)})})]}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Ds,{className:"max-w-4xl p-0 overflow-hidden bg-black border-0",children:[e.jsx(Vs,{className:"px-5 pt-4 pb-2 bg-background",children:e.jsx($s,{children:"How to use Website Apps"})}),c&&e.jsx("video",{src:"/website-apps-tutorial.mp4",controls:!0,autoPlay:!0,playsInline:!0,className:"w-full h-auto bg-black"})]})})]})}function ipr(){const{leadSite:s,hasLeadSite:t,isLoading:n}=$p(),{hasOffer:r,isLoading:a}=fMe(!t);return t&&s?e.jsx(td,{to:`/my-website/${s.id}/edit`,replace:!0}):e.jsx(qs,{title:"Get My Website",description:"Claim your complimentary luxury website",children:e.jsx("div",{className:"max-w-3xl mx-auto p-6 lg:p-8 space-y-6",children:n||a?e.jsx("div",{className:"h-40 flex 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(bas,{hasLeadSite:!1}):e.jsxs("div",{className:"rounded-xl border border-border p-8 text-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"No website yet"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:["Your brokerage doesn’t currently offer a complimentary website. Visit"," ",e.jsx("a",{href:"https://www.thelocalmove.com",target:"_blank",rel:"noreferrer",className:"text-primary hover:underline",children:"thelocalmove.com"})," ","to get started with a full IDX website."]})]})})})}const yBe={video_id:null,video_url:null,video_embed_url:null,thumbnail_url:null,greeting_title:"Glad you're here!",greeting_subtitle:"",position:"bottom-left",size:"md",shape:"rounded",ctas:[],show_socials:!0,lead_form_enabled:!0,lead_form_fields:["name","email","phone"],targeting:{mode:"all",include:[],exclude:[]},trigger:{type:"immediate",value:0},schedule:{mode:"always"}};function opr(){const{user:s}=vs();return ct({queryKey:["video-greeter-config",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return yBe;const{data:t,error:n}=await q.from("video_greeter_configs").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t?{...yBe,...t}:yBe},enabled:!!(s!=null&&s.id)})}function lpr(){const{user:s}=vs(),t=Qt();return yt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:r}=await q.from("video_greeter_configs").upsert({user_id:s.id,...n},{onConflict:"user_id"});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["video-greeter-config"]}),re.success("Saved")},onError:n=>re.error(n.message||"Failed to save")})}function cpr({label:s,value:t,onChange:n,thumbnailUrl:r,placeholder:a="https://...",hint:i}){const l=j.useRef(null),[o,c]=j.useState(!1),d=async u=>{var m;const h=(m=u.target.files)==null?void 0:m[0];if(h){if(!h.type.startsWith("video/")){re.error("Please select a video file");return}if(h.size>50*1024*1024){re.error("Video must be under 50MB");return}c(!0);try{const p=h.name.split(".").pop()||"mp4",f=`lead-site/videos/${Date.now()}-${Math.random().toString(36).slice(2,6)}.${p}`,{error:x}=await q.storage.from("agent-uploads").upload(f,h,{upsert:!0});if(x)throw x;const{data:{publicUrl:y}}=q.storage.from("agent-uploads").getPublicUrl(f);n(y),re.success("Video uploaded!")}catch(p){re.error(p.message||"Upload failed")}finally{c(!1),l.current&&(l.current.value="")}}};return e.jsxs("div",{children:[e.jsx(te,{children:s}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xe,{value:t,onChange:u=>n(u.target.value),placeholder:a,className:"flex-1"}),e.jsxs(U,{type:"button",variant:"outline",size:"sm",className:"shrink-0 gap-1.5 h-9",onClick:()=>{var u;return(u=l.current)==null?void 0:u.click()},disabled:o,children:[o?e.jsx(Et,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(qa,{className:"h-3.5 w-3.5"}),o?"Uploading...":"Upload"]}),e.jsx("input",{ref:l,type:"file",accept:"video/*",className:"hidden",onChange:d})]}),i&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:i}),t&&(()=>{const u=t.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/),h=u==null?void 0:u[1];return e.jsxs("div",{className:"relative group mt-2",children:[e.jsx("div",{className:`rounded-lg border border-border overflow-hidden bg-black w-full mx-auto ${h?"max-w-xl aspect-video":"max-w-sm aspect-[9/16]"}`,children:h?e.jsx("iframe",{src:`https://www.youtube.com/embed/${h}`,className:"w-full h-full",title:"Video preview",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0}):OU(t)?e.jsx(ZKe,{sourceUrl:t,thumbnailUrl:r,autoPlay:!0,muted:!0,loop:!0,className:"w-full h-full object-contain"}):e.jsx("video",{src:t,className:"w-full h-full object-contain",controls:!0,muted:!0,preload:"metadata"})}),e.jsx(U,{type:"button",variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>n(""),children:e.jsx(er,{className:"h-3 w-3"})})]})})()]})}const dpr=[{id:"warm-welcome",title:"Warm Welcome",duration:"15-20 sec",description:"Friendly intro that invites visitors to click for more.",text:"Hey there — welcome! I'm so glad you stopped by. I'm here to help you make smart, confident moves in this market — whether you're buying, selling, or just exploring. Click play and let me share a quick something that might help you today."},{id:"just-listed",title:"Just Listed Highlight",duration:"20-25 sec",description:"Drive attention to a new listing on your site.",text:"Hi! Quick heads up — I just listed a beautiful new home you'll want to see before anyone else. Click the video and I'll walk you through what makes it special and how to get a private showing this week."},{id:"home-value",title:"Free Home Value",duration:"15-20 sec",description:"Encourage seller leads to request an evaluation.",text:"Curious what your home is actually worth in today's market? It's probably more — or less — than you think. Click play and I'll show you exactly how to get a real, no-pressure home value report in under a minute."},{id:"buyer-tips",title:"Buyer Quick Tips",duration:"25-30 sec",description:"Position yourself as the trusted local expert for buyers.",text:"Thinking about buying? Before you do anything else, there are three things every smart buyer should know about our market right now. Click the video — I'll break them down in plain English so you can move forward with total confidence."},{id:"market-update",title:"Monthly Market Update",duration:"30 sec",description:"Quick authority builder — refresh monthly.",text:"Hey — quick market update. The numbers just dropped and there's something really interesting happening in our area that affects buyers AND sellers. Click play and I'll give you the 30-second breakdown so you know exactly where things stand."},{id:"book-call",title:"Book a Call",duration:"15 sec",description:"Direct invitation to schedule a chat.",text:"Hi! If you'd rather just talk it through with a real person — that's what I do best. Click play, then grab a 15-minute call with me. No pressure, no pitch — just answers to your questions."}];function upr({onVideoReady:s}){const[t,n]=j.useState(!1),[r,a]=j.useState("script"),[i,l]=j.useState(""),[o,c]=j.useState(!0),[d,u]=j.useState(!1),[h,m]=j.useState(0),[p,f]=j.useState(0),x=f3(),y=()=>{a("script"),l(""),m(0),f(0),c(!0)},v=N=>{!N&&(r==="uploading"||r==="processing")||(n(N),N||y())},b=j.useCallback(async(N,S)=>{a("uploading");try{const A="Video Greeter",{videoId:T,libraryId:L}=await cL(A),{uploadUrl:M,apiKey:I}=await dL(T),R=new XMLHttpRequest;R.upload.onprogress=ue=>{ue.lengthComputable&&m(ue.loaded/ue.total*100)},await new Promise((ue,se)=>{R.onload=()=>R.status>=200&&R.status<300?ue():se(new Error("Upload failed")),R.onerror=()=>se(new Error("Upload failed")),R.open("PUT",M),R.setRequestHeader("AccessKey",I),R.send(N)}),a("processing");let z=0;const $=Date.now(),H=9e4,V=`https://iframe.mediadelivery.net/embed/${L}/${T}`,K=`https://iframe.mediadelivery.net/play/${L}/${T}`;for(;z<4;){if(await new Promise(se=>setTimeout(se,3e3)),Date.now()-$>H){const se=N.size/1048576,ne=await x.mutateAsync({bunny_video_id:T,playback_url:K,file_size_mb:se,title:A,status:"processing",touch_type:"video"});s({videoId:(ne==null?void 0:ne.id)||T,playbackUrl:V,thumbnailUrl:null}),re.success("Video saved — still encoding. Will be ready shortly."),a("done"),setTimeout(()=>{n(!1),y()},1500);return}const ue=await fN(T);if(z=ue.status,f(ue.encodeProgress||0),z===5||z===6)throw new Error("Video processing failed")}const Z=await fN(T),Q=(Z.storageSize||N.size)/(1024*1024),le=await x.mutateAsync({bunny_video_id:T,playback_url:Z.directPlayUrl||V,thumbnail_url:Z.thumbnailUrl,preview_url:Z.previewUrl||null,duration_seconds:Z.length||S,file_size_mb:Q,title:A,status:"ready",touch_type:"video"});s({videoId:(le==null?void 0:le.id)||T,playbackUrl:Z.directPlayUrl||V,thumbnailUrl:Z.thumbnailUrl||null}),re.success("Video recorded & added to your library!"),a("done"),setTimeout(()=>{n(!1),y()},1500)}catch(A){console.error(A),re.error("Failed to process video. Please try again."),a("record")}},[x,s]);return e.jsxs(zs,{open:t,onOpenChange:v,children:[e.jsx(al,{asChild:!0,children:e.jsxs(U,{variant:"default",size:"sm",className:"gap-1.5",children:[e.jsx(Wr,{className:"h-4 w-4"}),"Record now"]})}),e.jsxs(Ds,{className:"sm:max-w-3xl max-h-[92vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(cn,{className:"h-5 w-5 text-primary"}),"Record your Video Greeter"]})}),r==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"1. Pick a script (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Edit it to sound like you, or skip and freestyle."}),e.jsx(Gi,{className:"h-[280px] pr-3",children:e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:dpr.map(N=>e.jsxs(we,{className:"p-3 cursor-pointer hover:border-primary transition-colors",onClick:()=>l(N.text),children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-1",children:[e.jsx("h4",{className:"font-medium text-sm",children:N.title}),e.jsx(Be,{variant:"outline",className:"text-[10px] shrink-0",children:N.duration})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:N.description})]},N.id))})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"2. Edit your script"}),e.jsx(Fs,{rows:5,value:i,onChange:N=>l(N.target.value),placeholder:"Pick a script above or type your own. Leave blank to freestyle."})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t",children:[e.jsx(U,{variant:"ghost",onClick:()=>{l(""),a("record")},children:"Skip — freestyle"}),e.jsxs(U,{onClick:()=>a("record"),children:[e.jsx(Ur,{className:"h-4 w-4 mr-1.5"})," Continue to recorder"]})]})]}),r==="record"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(kE,{maxDurationSeconds:60,onRecordingComplete:b,onRecordingStateChange:u,onError:N=>re.error(N),teleprompterContent:o&&i?e.jsx(Pnt,{text:i,isVisible:o,onToggleVisibility:()=>c(!1),isRecording:d,startCountdown:!1}):void 0}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>a("script"),children:"← Back to script"}),i&&!o&&e.jsxs(U,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(Ur,{className:"h-4 w-4 mr-1.5"})," Show teleprompter"]})]})]}),r==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Et,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(ro,{value:h,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(h),"%"]})]}),r==="processing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Et,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(ro,{value:p,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(p),"%"]})]}),r==="done"&&e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(Yo,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your greeter!"})]})]})]})}function hpr(){var S;const s=Wn(),{user:t}=vs(),{leadSite:n}=$p(),{data:r}=opr(),a=lpr(),{data:i=[]}=d8e(),l=u8e(),[o,c]=j.useState(null),[d,u]=j.useState({impressions:0,expands:0,ctaClicks:0,leads:0});if(j.useEffect(()=>{r&&!o&&c(r)},[r,o]),j.useEffect(()=>{t!=null&&t.id&&q.from("widget_events").select("event_type",{count:"exact"}).eq("user_id",t.id).eq("app_slug","video_greeter").then(({data:A})=>{const T=A||[];u({impressions:T.filter(L=>L.event_type==="impression").length,expands:T.filter(L=>L.event_type==="expand").length,ctaClicks:T.filter(L=>L.event_type==="cta_click").length,leads:T.filter(L=>L.event_type==="lead_capture").length})})},[t==null?void 0:t.id]),!o)return e.jsx(qs,{title:"Video Greeter",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading..."})});const h=((S=i.find(A=>A.app_slug==="video_greeter"))==null?void 0:S.enabled)??!1,m=A=>c({...o,...A}),p=A=>m({ctas:A}),f=()=>p([...o.ctas||[],{id:crypto.randomUUID(),label:"New Button",url:"https://",style:"primary"}]),x=A=>p((o.ctas||[]).filter(T=>T.id!==A)),y=(A,T)=>p((o.ctas||[]).map(L=>L.id===A?{...L,...T}:L)),v=()=>a.mutate(o),b=(n==null?void 0:n.subdomain_slug)||(t==null?void 0:t.id)||"",N=`